Saturday, September 15, 2012

MVC 3 Reload Partial View with Validations

 $('#partialcontroldiv').load('@Url.Content("~/ControlerName/ActionName")?id=' + id, '', function () {               
              //below lines to reapply dataannotation validation on partial view
                $('form').removeData("validator");
                $("form").removeData("unobtrusiveValidation");
                $.validator.unobtrusive.parse(document);


            });
Read More

MVC 3: Generate Textbox or labels in Foreach Loop

@foreach (var item in Model )
{







@Html.LabelFor(a=> item.ItemName)



@Html.LabelFor(a => item.Description)




@Html.LabelFor(a => item.Qty)



@Html.TextBoxFor(a => item.Price)





}
Read More

MVC 3: Cross Site Request Forgery protection

write @Html.AntiForgeryToken() in view to generate any forgery token (hidden textbox)
and use [ValidateAntiForgeryToken] on action to validate that request has valid anti forgery token
Read More

Change value of RequiresQuestionAndAnswer in ASP.NET Membership provider

MembershipUser user = Membership.GetUser();
string newPassword = "newPass";
string tempPassword = string.Empty;
if (Membership.Provider.RequiresQuestionAndAnswer)
{
var _requiresQA = Membership.Provider.GetType().GetField("_RequiresQuestionAndAnswer",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
//change the value in the private field
_requiresQA.SetValue(Membership.Provider, false);
//do the reset
tempPassword = user.ResetPassword();
//set it's original value
_requiresQA.SetValue(Membership.Provider, true);
}
else
{
tempPassword = user.ResetPassword();
}

http://djsolid.net/blog/asp.net-membership---change-password-without-asking-the-old-with-question-and-answer
Read More

Singleton Session

public class SingletonSession
{
// private constructor
private SingletonSession()
{

}

// Gets the current session.
public static SingletonSession Current
{
get
{
SingletonSession session =
(SingletonSession)HttpContext.Current.Session["__SingletonSession__"];
if (session == null)
{
session = new SingletonSession();
HttpContext.Current.Session["__SingletonSession__"] = session;
}
return session;
}
}

// **** add your session properties here, e.g like this:

public Guid UserId { get; set; }
public string UserName { get; set; }
public string AccountNo { get; set; }
public MembershipUser User { get; set; }
}

}
Read More

Authorization and Permission using Attribute in MVC3

Public enum PermissionType
{
permission1,
permission2,
permissiontype3
}
public class AuthorizePermissionAttribute : AuthorizeAttribute
{
private readonly IRolesService _rolesService;
private readonly IUserService _userService;
private string[] _rolesSplit;
private string[] _usersSplit;
public PermissionType[] PermissionName;
public AuthorizePermissionAttribute()
: this(new AspNetMembershipProviderWrapper(), new AspNetRoleProviderWrapper())
{
}
public AuthorizePermissionAttribute(IUserService userService, IRolesService rolesService)
{
_userService = userService;
_rolesService = rolesService;
}
public AuthorizePermissionAttribute(PermissionType[] PermissionName)
: this(new AspNetMembershipProviderWrapper(), new AspNetRoleProviderWrapper())
{
this.PermissionName = PermissionName;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
try
{

var user = httpContext.User;
if (!user.Identity.IsAuthenticated)
return false;

if (_usersSplit == null)
_usersSplit = SplitString(Users);
if (_rolesSplit == null)
_rolesSplit = SplitString(Roles);

if (_usersSplit.Any() && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase))
return false;

//if (!_rolesService.Enabled || !_rolesSplit.Any())
// return true;

//return _rolesSplit.Any(user.IsInRole);

IEnumerable userroles = _rolesService.FindByUser(MySession.Current.User);


var roleids = _context.aspnet_Roles.Where(a => userroles.Contains(a.RoleName)).Select(a => a.RoleId);
var rpt = _context.Role_Permission_Trans.Where(a => roleids.Contains(a.RoleID)).Select(a => a.PID);
var pm = _context.PermissionMasters.Where(p => rpt.Contains(p.PID));
var permissions = PermissionName.ToString(",").ToLower().Split(",".ToCharArray());
var res = pm.Where(p => permissions.Contains(p.PermissionName.ToLower()));
if (res.IsNotNull() && res.Count() > 0)
{
return true;
}
else
{
return false;
}

}
catch (Exception)
{


}
return false;
//return base.AuthorizeCore(httpContext);

}
private static string[] SplitString(string original)
{
if (String.IsNullOrEmpty(original))
return new string[0];

var split = from piece in original.Split(',')
let trimmed = piece.Trim()
where !String.IsNullOrEmpty(trimmed)
select trimmed;
return split.ToArray();
}
}

public class LogonAuthorize : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!(filterContext.Controller is AccountController) && !(filterContext.Controller is HomeController))
base.OnAuthorization(filterContext);
}
}
Read More

Features of SQL Server 2012

Features

}Column Store Index
}Sequence objects
}Contained Database
}Always On (HADRON)
}Ad Hoc Query Paging
}FileTable
}Audit Enhancements
}Enhanced PowerShell Support
}Big Data Support


Column Store Index

}Columnstore indexes provide an easy way to significantly improve data warehouse and decision support query performance against very large data sets
}Performance improvements for “typical” data warehouse queries from 10x to 100x
}Ideal candidates include queries against star schemas that use filtering, aggregations and grouping against very large fact tables


How Are These Performance Gains Achieved?

Two complimentary technologies:
Storage
Data is stored in a compressed columnar data format (stored by column) instead of row store format (stored by row). 
Columnar storage allows for less data to be accessed when only a sub-set of columns are referenced
Data density/selectivity determines how compression friendly a column is – example “State” / “City” / “Gender”
Translates to improved buffer pool memory usage
New “batch mode” execution
Data can then be processed in batches (1,000 row blocks) versus row-by-row
Depending on filtering and other factors, a query may also benefit by “segment elimination” - bypassing million row chunks (segments) of data, further reducing I/O

Creating a columnstore index

Defining the Columnstore Index

}Index type
Columnstore indexes are always non-clustered and non-unique
They cannot be created on views, indexed views, sparse columns
They cannot act as primary or foreign key constraints
}Column selection
Unlike other index types, there are no “key columns”
Instead you choose the columns that you anticipate will be used in your queries
Up to 1,024 columns – and the ordering in your CREATE INDEX doesn’t matter
No concept of “INCLUDE”
No 900 byte index key size limit
}Column ordering
Use of ASC or DESC sorting not allowed – as ordering is defined via columnstore compression algorithms

Supported Data Types

Supported data types
Char / nchar / varchar / nvarchar
(max) types, legacy LOB types and FILESTREAM are not supported
Decimal/numeric
Precision greater than 18 digits NOT supported
Tinyint, smallint, int, bigint
Float/real
Bit
Money, smallmoney
Date and time data types
Datetimeoffset with scale > 2 NOT supported

Maintaining Data in a Columnstore Index

}Once built, the table becomes “read-only” and INSERT/UPDATE/DELETE/MERGE is no longer allowed
}ALTER INDEX REBUILD / REORGANIZE not allowed
}Other options are still supported:
Partition switches (IN and OUT)
Drop columnstore index / make modifications / add columnstore index
UNION ALL (but be sure to validate performance)

Sequence objects

The new CREATE SEQUENCE statement can be used to create a database wide SEQUENCE object to use.

-- Create a SEQUENCE object on schema "dbo".
CREATE SEQUENCE MySeq AS tinyint
START WITH 0
INCREMENT BY 5
MINVALUE 0
MAXVALUE 255
CYCLE; GO
                        OR
CREATE SEQUENCE MySeq;
-- Verify if the MySeq is created.
SELECT * FROM sys.sequences WHERE name = N'MySeq';
-- Use Sequence object like:
SELECT NEXT VALUE FOR MySeq;


Contained Database


}A Contained Database is a database which contains all the necessary settings and metadata, making database easily portable to another server. This database will contain all the necessary details and will not have to depend on any server where it is installed for anything. You can take this database and move it to another server without having any worries.
}The real question is, “What about users who are connecting to this database?” Once the contained database is moved, the users are moved as well, and users who belong to the contained database will have no access outside the contained database.

In short

Database is now self-contained. Database which is ’contained’ will not depend on anything on the server where it is installed.

}Create Contained Database
CREATE DATABASE [ContainedDatabase]
CONTAINMENT = PARTIAL
ON PRIMARY
( NAME = 
N'ContainedDatabase', FILENAME = N'C:\ContainedDatabase.mdf')
LOG ON
( NAME = 
N'ContainedDatabase_log', FILENAME =N'C:\ContainedDatabase_log.ldf')
GO
}Create User in Contained Database
USE [ContainedDatabase]
GO
CREATE USER 
ContainedUser
WITH PASSWORD = '
pass@word';
GO
Enable Contained Database

Set the Containment Type to Partial in the Database Properties

Always On (HADRON)

The new High Availability and Disaster Recovery (HADR) features of Denali will offer a vast improvement over the database mirroring capabilities of SQL Server 2008.  AlwaysOn allows you to create availability groups of databases that can be failed over simultaneously.  This is especially important when you wish to fail over interdependent applications that rely upon more than one database.  AlwaysOn also allows you to create active secondary servers, making use of the redundant databases for part of your read workload.

}AlwaysOn Availability Groups is a new feature that enhances and combines database mirroring and log shipping capabilities
}Ability to configure availability groups through T-SQL, SSMS, and PowerShell
}Synchronous or Asynchronous commit
}Automatic and Manual failover
}Multiple databases support in availability groups
}Read-only access to the secondary
}Support for Filestream data type
}Failing over client connections using the new connectivity story based on virtual network names and virtual IP addresses
}Including logins in user databases through a Contained Database
}SSMS, Catalog Views, and DMVs to view and monitor state
}Support for multiple availability groups on the same instance
}Support for availability groups on standalone instances and/or failover cluster instances

Ad Hoc Query Paging

The ad hoc query paging enhancements to TSQL add the OFFSET and FETCH keywords to the ORDER BY clause, allowing you to specify the number of rows you wish to retrieve from a long result set and page through those results in a manner specified in the query.

FileTable

The FileTable is a neat bridge between databases and the operating system allowing database users to directly access unstructured data stored in the Windows file system.  Each FileTable uses a predefined schema to access a hierarchy of directories and files stored in the file system.  Each row in the FileTable corresponds to a single directory or file in the file system.  Files can be modified either through SQL Server or through Windows and updates are reflected in both places.

GUI after creating the table

Here is how the folder looks

Query The FileTable

Audit Enhancements

Hippa Compliance with SQL Server 2008:
(These all Audit Features are more enhanced in SQL Server 2012)
Enhancements to SQL Server auditing capabilities bring added flexibility and usability for auditing across the SQL Server environment, helping to make it even easier for organizations to meet compliance policies:
}SQL Audit is now available for all editions of SQL Server (previously was only available via the Enterprise edition
}User-Defined Audit allows an application to write custom events into the audit log to allow more flexibility to store audit information
}Audit Filtering provides greater flexibility to filter unwanted events into an audit log
}Audit Resilience delivers the ability to recover auditing data from temporary file and network issues











On Audit Log Failure Options

In SQL Server 2012 they have added two more options for audit log failure. In earlier version the only option was to shut down the server when there was audit log failure. Now you can fail the operation as well continue on log failure. This new options now give finer control on the behavior of the audit failure scenario. When target is not available due to any reason and audit cannot log the event, it can be now continued, in another word the audit continues to attempt to log events and will resume if the failure condition is resolved. This is very important feature because earlier when Audio was failing the option which we had was to shutdown the server. There were the cases when shutting down the server is not the good option but continuing the business operation is the priority, this option should be exercised.

Maximum Rollover Files

Earlier in 2008, there were two options – have infinite number of log files or roll over the files after fixed number. Now in SQL Server 2012 there is option to keep the fixed number of the files along with no roll-over. This gives additional control to user when they want to save every single data and do not want to lose any critical information due to rollover.

Enhanced PowerShell Support

Powershell leverages many components to bring a powerful scripting interface that surpasses the old WMI and VBScripting, making use of the .NET framework and other rich programming interfaces and libraries to leap over the boundaries that each of the general MS applications and components encounter.

Big Data Support

Microsoft announced a partnership with Hadoop provider Cloudera. One part of this involves MS releasing a ODBC driver for SQL Server that will run on a Linux platform. Additionally, Microsoft is building connectors for Hadoop, which is an extremely popular NoSQL platform. With this announcement, Microsoft has made a clear move into this very rapidly growing space.



Compiled By: Rajesh Rolen



Read More

Tuesday, April 3, 2012

Using JQGrid in ASP.NET MVC 3

JQGrid is one of the most powerful opensource grid available for commercial use.

We can easily use JQGrid in MVC 3 also, but instead of directly using JQGrid, i would like to refer to use any component/wrapper built over JQGrid, which can make data and grid structure in strongly typed form.

After lots of search i found a very good helper Lib.Web.MVC, it is a library which contains some helper classes for ASP.NET MVC such as strongly typed jqGrid helper, XSL transformation HtmlHelper/ActionResult, custom attributes and more.

Now lets use this "Lib.Web.MVC" and create an application.

Now lets say i wants to create an application which is showing employee details in grid using JQGrid (Lib.Web.MVC).


First of all add Lib.Web.MVC to you project either using NuGet or directly download the dll/application from Lib.Web.MVC.

Now next step is to create an ViewModel class for Grid, in which we creates properties for all the column (of employee) which we wants to show in grid and add various attributes on it.

like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using DataAnnotationsExtensions;
using Lib.Web.Mvc.JQuery.JqGrid.DataAnnotations;
using System.Web.Mvc;
//your project namespace will be here.
 public class EmployeeDetailViewModel
    {

        [JqGridColumnLayout(Width = 40)]//fix the width of column in grid
        [JqGridColumnLabel(Label = "")] // to show select all column with check box
        public string All { get; set; }

        [ScaffoldColumn(false)]//if you don't wants to show this column in grid
        public Guid ProfileID { get; set; }

        [StringLength(20)]
        [Display(Name = "Employee Id")]// heading of columns
        public string EmployeeId { get; set; }

        [StringLength(100)]
        [Display(Name = "Employee Name")]
        public string EmployeeName { get; set; }

        [Display(Name = "Email Address")]
        [Required, Email] // this will be used when same model will be used to take value for create employee
        public string Email { get; set; }

        [StringLength(50)]
        [Display(Name = "Address")]
        public string Address { get; set; }

        [JqGridColumnLayout(Width = 150)]
        public string Action { get; set; }

        public EmployeeDetailViewModel()
        {

        }

        public EmployeeDetailViewModel(MyNamespace.Models.EmployeeProfile profile)
        {
            All = "";
            ProfileID = profile.PID;
            EmployeeId = profile.EmployeeId;
            EmployeeName = profile.EmployeeName;
            Email = profile.Email;
            Address = profile.Address;

//the action column will contains "Edit" and "View" links in grid.
            Action = "" +
"";

        }

    }


 public class Mylib 
    {
        public static System.Web.Mvc.UrlHelper GetURLHelper()//to get the action url
        {
            return new UrlHelper(HttpContext.Current.Request.RequestContext);
        }
}


in view create jqgrid like:
@{ 
   int noofrows = Convert.ToInt32( System.Configuration.ConfigurationManager.AppSettings["RowsInGrid"].ToString());//to get rows per page

   var grid = new Lib.Web.Mvc.JQuery.JqGrid.JqGridHelper("EmpGrid",
      dataType: Lib.Web.Mvc.JQuery.JqGrid.JqGridDataTypes.Json,
      methodType: Lib.Web.Mvc.JQuery.JqGrid.JqGridMethodTypes.Post,
      pager: true,
      rowsNumber: noofrows,
      url: Url.Action("GetEmployee"),//this action will be called to get data 
      viewRecords: true,
      autoWidth: true// to fit the grid in parent div/table
  );
  }

 [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GetEmployee(JqGridRequest request, EmployeeViewModel viewModel)
        {

   int totalPagesCount =0;
                        var employees = _empRepo.FindRange(pageIndex: request.PageIndex, pageLength: request.RecordsCount, out totalPagesCount);

                       
                        JqGridResponse response = new JqGridResponse()
                        {
                            TotalPagesCount = (int)Math.Ceiling((float)totalPagesCount / (float)request.RecordsCount),
                            PageIndex = request.PageIndex,
                            TotalRecordsCount = totalRecordsCount
                        };

                        response.Records.AddRange(from i in employees select new JqGridRecord(Convert.ToString(new EmployeeViewModel(i).employeeid), new EmployeeViewModel(i)));

                        return new JqGridJsonResult() { Data = response };
         }



Compiled By: Rajesh Rolen

Read More

Monday, January 30, 2012

Best Extension Methods

Read More

Best Extension Methods: Cookie Extension Methods

Best Cookies Extension Methods
public static class CookieExtensions
{

    /// 
    /// Sets a persistent cookie which expires after the given number of days
    /// 
    /// The HtmDocument to extend
    /// the cookie key
    /// the cookie value
    /// The number of days before the cookie expires
    public static void SetCookie(this HtmlDocument doc, string key, string value, int days)
    {
        DateTime expiration = DateTime.UtcNow + TimeSpan.FromDays(days);
        SetCookie(doc, key, value, expiration);
    }

    /// 
    /// Sets a persistent cookie with an expiration date
    /// 
    /// The HtmDocument to extend
    /// the cookie key
    /// the cookie value
    public static void SetCookie(this HtmlDocument doc, string key, string value, DateTime expiration)
    {
        string oldCookie = doc.GetProperty("cookie") as String;
        string cookie = String.Format("{0}={1};expires={2}", key, value, expiration.ToString("R"));
        doc.SetProperty("cookie", cookie);
    }

    /// 
    /// Retrieves an existing cookie
    /// 
    /// The HtmDocument to extend
    /// cookie key
    /// null if the cookie does not exist, otherwise the cookie value
    public static string GetCookie(this HtmlDocument doc, string key)
    {
        string[] cookies = doc.Cookies.Split(';');
        key += '=';
        foreach (string cookie in cookies)
        {
            string cookieStr = cookie.Trim();
            if (cookieStr.StartsWith(key, StringComparison.OrdinalIgnoreCase))
            {
                string[] vals = cookieStr.Split('=');

                if (vals.Length >= 2)
                {
                    return vals[1];
                }

                return string.Empty;
            }
        }

        return null;
    }

    /// 
    /// Deletes a specified cookie by setting its value to empty and expiration to -1 days
    /// 
    /// The HtmDocument to extend
    /// the cookie key to delete
    public static void DeleteCookie(this HtmlDocument doc, string key)
    {
        string oldCookie = doc.GetProperty("cookie") as String;
        DateTime expiration = DateTime.UtcNow - TimeSpan.FromDays(1);
        string cookie = String.Format("{0}=;expires={1}", key, expiration.ToString("R"));
        doc.SetProperty("cookie", cookie);
    }
}

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: HTTP Extension Methods

Best Http Extension Methods
public static class HttpExtension
{
    public static string HtmlEncode(this string data)
    {
        return HttpUtility.HtmlEncode(data);
    }

    public static string HtmlDecode(this string data)
    {
        return HttpUtility.HtmlDecode(data);
    }

    public static NameValueCollection ParseQueryString(this string query)
    {
        return HttpUtility.ParseQueryString(query);
    }

    public static string UrlEncode(this string url)
    {
        return HttpUtility.UrlEncode(url);
    }

    public static string UrlDecode(this string url)
    {
        return HttpUtility.UrlDecode(url);
    }

    public static string UrlPathEncode(this string url)
    {
        return HttpUtility.UrlPathEncode(url);
    }
}


Compiled By: Rajesh Rolen

Read More

Best Extension Methods: String Extension Methods

Best String Extension Methods

public static class StringExtensions
{
    /// 
    /// if the string is NULL, converts it to string.empty. Helpful when trying to avoid null conditions.
    /// 
    /// 
    /// 
    public static string IsNullThenEmpty(this string inString)
    {
        if (inString == null)
            return string.Empty;
        else
            return inString;
    }			

    public static string[] GetStringInBetween(this string strSource, string strBegin, string strEnd, bool includeBegin, bool includeEnd)
    {

        string[] result = { "", "" };

        int iIndexOfBegin = strSource.IndexOf(strBegin);

        if (iIndexOfBegin != -1)
        {

            // include the Begin string if desired

            if (includeBegin)

                iIndexOfBegin -= strBegin.Length;

            strSource = strSource.Substring(iIndexOfBegin

                + strBegin.Length);

            int iEnd = strSource.IndexOf(strEnd);

            if (iEnd != -1)
            {

                // include the End string if desired

                if (includeEnd)

                    iEnd += strEnd.Length;

                result[0] = strSource.Substring(0, iEnd);

                // advance beyond this segment

                if (iEnd + strEnd.Length < strSource.Length)

                    result[1] = strSource.Substring(iEnd

                        + strEnd.Length);

            }

        }

        else

            // stay where we are

            result[1] = strSource;

        return result;

    }

    public static T ToEnum(this string value)
       where T : struct
    {
       
        //Debug.Assert(!string.IsNullOrEmpty(value));
        return (T)Enum.Parse(typeof(T), value, true);
    }
    public static string Nl2Br(this string s)
    {
        return s.Replace("\r\n", "
").Replace("\n", "
"); } public static string Format(this string format, object arg, params object[] additionalArgs) { if (additionalArgs == null || additionalArgs.Length == 0) { return string.Format(format, arg); } else { return string.Format(format, new object[] { arg }.Concat(additionalArgs).ToArray()); } } public static bool ContainsAny(this string theString, char[] characters) { foreach (char character in characters) { if (theString.Contains(character.ToString())) { return true; } } return false; } /// /// Strip a string of the specified substring. /// /// the string to process /// substring to remove /// /// string s = "abcde"; /// /// s = s.Strip("bcd"); //s becomes 'ae; /// /// public static string Strip(this string s, string subString) { s = s.Replace(subString, ""); return s; } /// /// Strip a string of the specified character. /// /// the string to process /// character to remove from the string /// /// string s = "abcde"; /// /// s = s.Strip('b'); //s becomes 'acde; /// /// public static string Strip(this string s, char character) { s = s.Replace(character.ToString(), ""); return s; } /// /// Strip a string of the specified characters. /// /// the string to process /// list of characters to remove from the string /// /// string s = "abcde"; /// /// s = s.Strip('a', 'd'); //s becomes 'bce; /// /// public static string Strip(this string s, params char[] chars) { foreach (char c in chars) { s = s.Replace(c.ToString(), ""); } return s; } /// /// Splits a string into a NameValueCollection, where each "namevalue" is separated by /// the "OuterSeparator". The parameter "NameValueSeparator" sets the split between Name and Value. /// Example: /// String str = "param1=value1;param2=value2"; /// NameValueCollection nvOut = str.ToNameValueCollection(';', '='); /// /// The result is a NameValueCollection where: /// key[0] is "param1" and value[0] is "value1" /// key[1] is "param2" and value[1] is "value2" /// /// String to process /// Separator for each "NameValue" /// Separator for Name/Value splitting /// public static NameValueCollection ToNameValueCollection(this String str, Char OuterSeparator, Char NameValueSeparator) { NameValueCollection nvText = null; str = str.TrimEnd(OuterSeparator); if (!String.IsNullOrEmpty(str)) { String[] arrStrings = str.TrimEnd(OuterSeparator).Split(OuterSeparator); foreach (String s in arrStrings) { Int32 posSep = s.IndexOf(NameValueSeparator); String name = s.Substring(0, posSep); String value = s.Substring(posSep + 1); if (nvText == null) nvText = new NameValueCollection(); nvText.Add(name, value); } } return nvText; } /// /// Truncates the string to a specified length and replace the truncated to a ... /// /// string that will be truncated /// total length of characters to maintain before the truncate happens /// truncated string public static string Truncate(this string text, int maxLength) { // replaces the truncated string to a ... const string suffix = "..."; string truncatedString = text; if (maxLength <= 0) return truncatedString; int strLength = maxLength - suffix.Length; if (strLength <= 0) return truncatedString; if (text == null || text.Length <= maxLength) return truncatedString; truncatedString = text.Substring(0, strLength); truncatedString = truncatedString.TrimEnd(); truncatedString += suffix; return truncatedString; } /// /// Returns the last few characters of the string with a length /// specified by the given parameter. If the string's length is less than the /// given length the complete string is returned. If length is zero or /// less an empty string is returned /// /// the string to process /// Number of characters to return /// public static string Right(this string s, int length) { length = Math.Max(length, 0); if (s.Length > length) { return s.Substring(s.Length - length, length); } else { return s; } } public static String left(this String s, int len) { return s.Substring(0, Math.Min(len, s.Length)); } public static DateTime ToDateFromDDMMYYYY(this string date) { return DateTime.ParseExact(date, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture); } //Format string to Title case public static string ToTitleCase(this string mText) { if (mText == null) return mText; System.Globalization.CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture; System.Globalization.TextInfo textInfo = cultureInfo.TextInfo; // TextInfo.ToTitleCase only operates on the string if is all lower case, otherwise it returns the string unchanged. return textInfo.ToTitleCase(mText.ToLower()); } /// /// Parses a string into an Enum /// /// The type of the Enum /// String value to parse /// The Enum corresponding to the stringExtensions public static T EnumParse(this string value) { return EnumParse(value, false); } public static T EnumParse(this string value, bool ignorecase) { if (value == null) { throw new ArgumentNullException("value"); } value = value.Trim(); if (value.Length == 0) { throw new ArgumentException("Must specify valid information for parsing in the string.", "value"); } Type t = typeof(T); if (!t.IsEnum) { throw new ArgumentException("Type provided must be an Enum.", "T"); } return (T)Enum.Parse(t, value, ignorecase); } // Enable quick and more natural string.Format calls public static string F(this string s, params object[] args) { return string.Format(s, args); } public static DateTime? ToDateTime(this string source) { if (!string.IsNullOrEmpty(source)) { return Convert.ToDateTime(source); } return null; } public static int? ToNullableInt(this string source) { var i = 0; return int.TryParse(source, out i) ? (int?)i : null; } public static string ToPlural(this string singular) { // Multiple words in the form A of B : Apply the plural to the first word only (A) int index = singular.LastIndexOf(" of "); if (index > 0) return (singular.Substring(0, index)) + singular.Remove(0, index).ToPlural(); // single Word rules //sibilant ending rule if (singular.EndsWith("sh")) return singular + "es"; if (singular.EndsWith("ch")) return singular + "es"; if (singular.EndsWith("us")) return singular + "es"; if (singular.EndsWith("ss")) return singular + "es"; //-ies rule if (singular.EndsWith("y")) return singular.Remove(singular.Length - 1, 1) + "ies"; // -oes rule if (singular.EndsWith("o")) return singular.Remove(singular.Length - 1, 1) + "oes"; // -s suffix rule return singular + "s"; } public static bool IsValidEmailAddress(this string s) { Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"); return regex.IsMatch(s); } /// /// Converts a string into a "SecureString" /// /// Input String /// public static System.Security.SecureString ToSecureString(this String str) { System.Security.SecureString secureString = new System.Security.SecureString(); foreach (Char c in str) secureString.AppendChar(c); return secureString; } public static string ToProperCase(this string text) { System.Globalization.CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture; System.Globalization.TextInfo textInfo = cultureInfo.TextInfo; return textInfo.ToTitleCase(text); } public static bool IsNumeric(this string theValue) { long retNum; return long.TryParse(theValue, System.Globalization.NumberStyles.Integer, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum); } public static bool IsNotNullOrEmpty(this string input) { return !String.IsNullOrEmpty(input); } public static bool IsNullOrEmpty(this string input) { return String.IsNullOrEmpty(input); } public static bool IsNotNullOrEmptyOrSpace(this string input) { if (!String.IsNullOrEmpty(input)) { return !String.IsNullOrEmpty(input.Trim()); } else { return true; } } public static bool IsNullOrEmptyOrSpace(this string input) { if (!String.IsNullOrEmpty(input)) { return String.IsNullOrEmpty(input.Trim()); } else { return true; } } /// /// Count all words in a given string /// /// string to begin with /// int public static int WordCount(this string input) { var count = 0; try { // Exclude whitespaces, Tabs and line breaks var re = new Regex(@"[^\s]+"); var matches = re.Matches(input); count = matches.Count; } catch { } return count; } }

Compiled By: Rajesh Rolen

Read More

Best Extension Methods: Date and Time

Best Extension Methods for Date and time

public static class DateExtensions
{

    /// 
    /// DateDiff in SQL style. 
    /// Datepart implemented: 
    ///     "year" (abbr. "yy", "yyyy"), 
    ///     "quarter" (abbr. "qq", "q"), 
    ///     "month" (abbr. "mm", "m"), 
    ///     "day" (abbr. "dd", "d"), 
    ///     "week" (abbr. "wk", "ww"), 
    ///     "hour" (abbr. "hh"), 
    ///     "minute" (abbr. "mi", "n"), 
    ///     "second" (abbr. "ss", "s"), 
    ///     "millisecond" (abbr. "ms").
    /// 
    /// 
    /// 
    /// 
    public static Int64 DateDiff(this DateTime StartDate, String DatePart, DateTime EndDate)
    {
        Int64 DateDiffVal = 0;
        System.Globalization.Calendar cal = System.Threading.Thread.CurrentThread.CurrentCulture.Calendar;
        TimeSpan ts = new TimeSpan(EndDate.Ticks - StartDate.Ticks);
        switch (DatePart.ToLower().Trim())
        {
            #region year
            case "year":
            case "yy":
            case "yyyy":
                DateDiffVal = (Int64)(cal.GetYear(EndDate) - cal.GetYear(StartDate));
                break;
            #endregion

            #region quarter
            case "quarter":
            case "qq":
            case "q":
                DateDiffVal = (Int64)((((cal.GetYear(EndDate)
                                    - cal.GetYear(StartDate)) * 4)
                                    + ((cal.GetMonth(EndDate) - 1) / 3))
                                    - ((cal.GetMonth(StartDate) - 1) / 3));
                break;
            #endregion

            #region month
            case "month":
            case "mm":
            case "m":
                DateDiffVal = (Int64)(((cal.GetYear(EndDate)
                                    - cal.GetYear(StartDate)) * 12
                                    + cal.GetMonth(EndDate))
                                    - cal.GetMonth(StartDate));
                break;
            #endregion

            #region day
            case "day":
            case "d":
            case "dd":
                DateDiffVal = (Int64)ts.TotalDays;
                break;
            #endregion

            #region week
            case "week":
            case "wk":
            case "ww":
                DateDiffVal = (Int64)(ts.TotalDays / 7);
                break;
            #endregion

            #region hour
            case "hour":
            case "hh":
                DateDiffVal = (Int64)ts.TotalHours;
                break;
            #endregion

            #region minute
            case "minute":
            case "mi":
            case "n":
                DateDiffVal = (Int64)ts.TotalMinutes;
                break;
            #endregion

            #region second
            case "second":
            case "ss":
            case "s":
                DateDiffVal = (Int64)ts.TotalSeconds;
                break;
            #endregion

            #region millisecond
            case "millisecond":
            case "ms":
                DateDiffVal = (Int64)ts.TotalMilliseconds;
                break;
            #endregion

            default:
                throw new Exception(String.Format("DatePart \"{0}\" is unknown", DatePart));
        }
        return DateDiffVal;
    }
    public static string ToStringDDMMYYYYFromDate(this DateTime date)
    {
        if (date == null)
        {
            return "";
        }
        else
        {
            return date.ToString("dd/MM/yyyy");

        }
    }
    public static string ToStringDDMMYYYYFromDate(this DateTime? date)
    {
        if (date == null)
        {
            return "";
        }
        else
        {
            return ((DateTime)date).ToString("dd-MM-yyyy");

        }
    }
    static public int Age(this DateTime dateOfBirth)
    {
        if (DateTime.Today.Month < dateOfBirth.Month ||
        DateTime.Today.Month == dateOfBirth.Month &&
         DateTime.Today.Day < dateOfBirth.Day)
        {
            return DateTime.Today.Year - dateOfBirth.Year - 1;
        }
        else
            return DateTime.Today.Year - dateOfBirth.Year;
    }
    public static string ToFriendlyDateString(this DateTime Date)
    {
        string FormattedDate = "";
        if (Date.Date == DateTime.Today)
        {
            FormattedDate = "Today";
        }
        else if (Date.Date == DateTime.Today.AddDays(-1))
        {
            FormattedDate = "Yesterday";
        }
        else if (Date.Date > DateTime.Today.AddDays(-6))
        {
            // *** Show the Day of the week
            FormattedDate = Date.ToString("dddd").ToString();
        }
        else
        {
            FormattedDate = Date.ToString("MMMM dd, yyyy");
        }

        //append the time portion to the output
        FormattedDate += " @ " + Date.ToString("t").ToLower();
        return FormattedDate;
    }
    public static bool IsWeekend(this DayOfWeek d)
    {
        return !d.IsWeekday();
    }

    public static bool IsWeekday(this DayOfWeek d)
    {
        switch (d)
        {
            case DayOfWeek.Sunday:
            case DayOfWeek.Saturday: return false;

            default: return true;
        }
    }

    public static DateTime AddWorkdays(this DateTime d, int days)
    {
        // start from a weekday
        while (d.DayOfWeek.IsWeekday()) d = d.AddDays(1.0);
        for (int i = 0; i < days; ++i)
        {
            d = d.AddDays(1.0);
            while (d.DayOfWeek.IsWeekday()) d = d.AddDays(1.0);
        }
        return d;
    }
    public static string FirstDayOfMonth(this DateTime date)
    {
        return new DateTime(date.Year, date.Month, 1).ToString("MM/dd/yyyy");
    }

    public static string LastDayOfMonth(this DateTime date)
    {
        return new DateTime(DateTime.Now.Year, DateTime.Now.Month + 1, 1).AddDays(-1).ToString("MM/dd/yyyy");
    }
    /// 
    /// Converts a regular DateTime to a RFC822 date string.
    /// 
    /// The specified date formatted as a RFC822 date string.
    public static string ToRFC822DateString(this DateTime date)
    {
        int offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Hours;
        string timeZone = "+" + offset.ToString().PadLeft(2, '0');
        if (offset < 0)
        {
            int i = offset * -1;
            timeZone = "-" + i.ToString().PadLeft(2, '0');
        }
        return date.ToString("ddd, dd MMM yyyy HH:mm:ss " + timeZone.PadRight(5, '0'), System.Globalization.CultureInfo.GetCultureInfo("en-US"));
    }
}

Compiled By: Rajesh Rolen

Read More
Powered By Blogger · Designed By Seo Blogger Templates