Monday, September 16, 2013

How to use SqlClient.SqlFunctions.DateDiff in LINQ?

Here i am showing how to use SqlClient.SqlFunctions.DateDiff in Entity Framework to delete some records which are older than 8 hours.
/// <summary>
        /// Function Name: DeleteAllOutDatedSession
        /// Bishnu Tewary
        /// 16-09-2013
        /// This function will delete all those records which are older than 8 hours
        /// </summary>
        /// <param name="objEntities">DEMOEntities needs to be submitted to enable SQL-Transactions including Rollbacks</param>
        /// <returns> Result Type</returns>
        public DB DeleteAllOutDatedSession(DEMOEntities objEntities)
        {
            Result = DB.Unknown;
            try
            {
                using (objEntities)
                {
                   (from p in objEntities.tblDEMO.Where(x => System.Data.Objects.SqlClient.SqlFunctions.DateDiff("hour", x.Timestamp, DateTime.Now) >= 8) select p).ToList().ForEach(objEntities.DeleteObject);
                    objEntities.SaveChanges();
                }
                Report(DB.OK);
            }
            catch (Exception ex)
            {
                this.Report(DB.Error, ex);
            }
            return Result;
        }

Friday, September 13, 2013

How to replace multiple characters from a string in C#

 static Dictionary<char, char> ToReplace = new Dictionary<char, char>() { { '*', ' ' }, { '%', ' ' } };

Here ToReplace dictionary contains all characters and its replacement as key value , here the char you want to replace is KEY and the KEY will be Replace with VALUE from the bellow function

 /// <summary>
        /// Funtion Name: ReplaceWildchars
        /// Bishnu Tewary
        /// 13-09-2013
        /// This function will replace wildchar from the string
        /// </summary>
        /// <param name="inputString">input string</param>
        /// <returns>retun string after replacing </returns>
        public string ReplaceWildchars(string inputString)
        {
            var tmpStr = inputString.Select(c =>
            {
                char r;
                if (ToReplace.TryGetValue(c, out r))
                    return r;
                return c;
            });
            return new string(tmpStr.ToArray()).Trim();
        }

Tuesday, September 10, 2013

Culture based jQuery datepicker in MVC4

Hi , I am going to show you today a very interesting thing :) which i implemented yesterday in my project, where requirement is to show datetime format of whole site to client's culture (means browser dependent culture,which we can have from the browser default language). I create a html helper class for this which took the   CurrentCulture from the Thread.CurrentThread and from there we can easily have the datetime format for our beautiful :) datepicker ok? from this "Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern" .

Now we have to call this html helper's methode which return dateformat for the datepicker like this.

Here one more thing i implemeted is to create a custom select button for the  datepicker,with this
.next(".ui-datepicker-trigger").addClass("Datepicker-Orange"); where "Datepicker-Orange" is the css class which replace the datepicker button style.

$(function () {
        $("#ReleaseDate").datepicker({
            showOn: "button",
            buttonImageOnly: false,
            buttonText: "select",
            changeMonth: true,
            changeYear: false,
            dateFormat: '@Html.ConvertDateFormat()',
            onSelect: function (dateText) {

            }
        }).next(".ui-datepicker-trigger").addClass("Datepicker-Orange");

        $(".ui-datepicker-trigger").mouseover(function () {
            $(this).css('cursor', 'pointer');
        });
    });


Here is the Helper class
using System;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq.Expressions;
using System.Threading;

namespace <Somenamespace>
{
    ///<summary>
    /// JQuery UI DatePicker helper.
    ///</summary>
    public static class JQueryUIDatePickerHelper
    {
        /// <summary>
        /// Function Name:ConvertDateFormat
        /// Bishnu Tewary
        /// 09-09-2013
        /// Converts the .net supported date format current culture
        /// format into JQuery Datepicker format.
        /// </summary>
        /// <param name="html">HtmlHelper object.</param>
        /// <returns>Format string that supported in JQuery Datepicker.</returns>
        public static string ConvertDateFormat(this HtmlHelper html)
        {
            return ConvertDateFormat(html,
        Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern);
        }

        /// <summary>
        /// Function Name:ConvertDateFormat
        /// Bishnu Tewary
        /// 09-09-2013
        /// Converts the .net supported date format current culture
        /// format into JQuery Datepicker format.
        /// </summary>
        /// <param name="html">HtmlHelper object.</param>
        /// <param name="format">Date format supported by .NET.</param>
        /// <returns>Format string that supported in JQuery Datepicker.</returns>
        public static string ConvertDateFormat(this HtmlHelper html, string format)
        {
            /*
             *  Date used in this comment : 9th - Sep - 2013 (Monday)
             *
             *  .NET    JQueryUI        Output      Comment
             *  --------------------------------------------------------------
             *  d       d               9           day of month(No leading zero)
             *  dd      dd              09          day of month(two digit)
             *  ddd     D               Mon         day short name
             *  dddd    DD              Monday    day long name
             *  M       m               9          month of year(No leading zero)
             *  MM      mm              09          month of year(two digit)
             *  MMM     M               Sep         month name short
             *  MMMM    MM              September    month name long.
             *  yy      y               13          Year(two digit)
             *  yyyy    yy              2013        Year(four digit)             *
             */

            string currentFormat = format;

            // Convert the date
            currentFormat = currentFormat.Replace("dddd", "DD");
            currentFormat = currentFormat.Replace("ddd", "D");

            // Convert month
            if (currentFormat.Contains("MMMM"))
            {
                currentFormat = currentFormat.Replace("MMMM", "MM");
            }
            else if (currentFormat.Contains("MMM"))
            {
                currentFormat = currentFormat.Replace("MMM", "M");
            }
            else if (currentFormat.Contains("MM"))
            {
                currentFormat = currentFormat.Replace("MM", "mm");
            }
            else
            {
                currentFormat = currentFormat.Replace("M", "m");
            }

            // Convert year
            currentFormat = currentFormat.Contains("yyyy") ?
        currentFormat.Replace("yyyy", "yy") : currentFormat.Replace("yy", "y");

            return currentFormat;
        }
    }
}

NOTE : you need to add
<globalization culture="auto" uiCulture="auto" /> in web.config
Cheers :)

How to convert a List to a comma separated string in C#

Here i am showing how to convert a List<int> to a comma separated string,
where
 malist is a list of PublisherID (int),
manList.Distinct() is distict list of PublisherID i.e removed all duplicate items from the malist and
objModel.TempCommaPublisher is s string 

Here is the sample code

List<int> manList = (from item in model.SearchList orderby item.PublisherID ascending select item.PublisherID).ToList();
           
            if (string.IsNullOrEmpty(objModel.TempCommaPublisher))
                objModel.TempCommaPublisher = string.Join<int>(",", manList.Distinct());


Here string.Join<int>(",", manList.Distinct()); join all int items from manList.Distinct() separated by a "," to a string .

How to get number of UPPER case letters in a string in C#?

 Here i am using LINQ to get number of uppercase letters within a string,this countUpperLetters method takes the string as parameter and returns number of uppercase letters on it.
    /// <summary>
        /// Function Name:countUpperLetters
        /// Bishnu Tewary
        /// 10-09-2013
        /// this countUpperLetters method takes the string as parameter
        /// and returns number of   uppercase   letters on it.
        /// </summary>
        /// <param name="strString">string parameter for which
        ///  uppercase letters will be counted
        /// </param>
        /// <returns>int , number of uppercase letteres</returns>
        public static int countUpperLetters(string strString)
        {
            return strString.Count(c => char.IsUpper(c));
        }