Monthly Archives: June 2011

ASP.NET file upload size limit – simple solution

Using Global.asax file

public class Global : System.Web.HttpApplication{    protected void Application_Start(object sender, EventArgs e)    {    }    protected void Session_Start(object sender, EventArgs e)    {    }    protected void Application_BeginRequest(object sender, EventArgs e)    {    }    protected void Application_AuthenticateRequest(object sender, EventArgs e)    {    }    protected void Application_Error(object sender, EventArgs e)    {        Exception currentException = Server.GetLastError();        string RequestedUrl = string.Empty;        try        {            //RequestedUrl = HttpUtility.UrlDecode(HttpUtility.UrlEncode(Request.Url.PathAndQuery));            RequestedUrl = HttpUtility.UrlDecode(HttpUtility.UrlEncode(Request.RawUrl));        }        catch        {            RequestedUrl = string.Empty;        }        if (((currentException) is System.Web.HttpException))        {            if (currentException.GetBaseException().Message.StartsWith("Maximum request length exceeded"))            {                Response.Redirect(string.Format("~/{0}&E=FTL", RequestedUrl));            }        }    }    protected void Session_End(object sender, EventArgs e)    {    }    protected void Application_End(object sender, EventArgs e)    {    }}

SQL Merge Multiple Rows Into Single String (3)

Sample data

DECLARE @SampleTable AS TABLE (SampleData VARCHAR(255))INSERT INTO @SampleTable ( SampleData )SELECT 'Value 1' UNION ALLSELECT 'Value 2' UNION ALLSELECT 'Value 3'SELECT SampleData FROM @SampleTable

In the above example, FOR XML clause is used to concatenate row values. Since a comma is used, the query concatenates values separated by comma.

Resource SQL Server curry

SQL Leading zeros

The problem

DECLARE @StartDateTime SMALLDATETIMESET @StartDateTime = '2011-06-20 1:00:00'SELECT CONVERT(CHAR(2), DATEPART(minute, @StartDateTime)) AS Minutes

Quick Tip: Comparing a .NET string to multiple values

The Problem

Do you ever wish you could use the SQL IN operator in your C# code to make your conditional blocks more concise and your code easier to read?

Perhaps it’s just my persnickety nature, but I believe that line-wrapped conditional expressions like this are a code smell.

if (animal.Equals("Cow") ||   animal.Equals("Horse") ||   animal.Equals("Hen")){   Console.WriteLine("We must be on the farm.");}

This would be so much cleaner…

if (animal.CompareMultiple("Cow","Horse","Hen"){   Console.WriteLine("We must be on the farm.");}

The Code

With a simple extension class you can upgrade your string classes to do this very thing.

Step 1: Create an extension class as demonstrated here.


namespace extenders.strings{  public static class StringExtender {    public static bool CompareMultiple(this string data, StringComparison compareType, params string[] compareValues) {      foreach (string s in compareValues) {        if (data.Equals(s, compareType)) {          return true;        }      }      return false;   }  }}


Imports System.Runtime.CompilerServicesNamespace Extenders.Strings  Public Module StringExtender    <Extension()> _    Public Function CompareMultiple(ByVal this As String, compareType As StringComparison, ParamArray compareValues As String()) As Boolean       Dim s As String       For Each s In compareValues         If (this.Equals(s, compareType)) Then            Return True         End If       Next s       Return False    End Function  End ModuleEnd Namespace

Step 2: Add a reference to the extension namespace and use it.


using extenders.strings;namespace MyProgram{  static class program {    static void Main() {      string foodItem = "Bacon";      if (foodItem.CompareMultiple(StringComparison.CurrentCultureIgnoreCase, "bacon", "eggs", "biscuit")) {         System.Console.WriteLine("Breakfast!");      }      else {         System.Console.Write("Dinner");      }    }  }}


Imports StringExtenderExampleVB.Extenders.StringsModule Program  Sub Main()    Dim foodItem As String = "Bacon"    If (foodItem.CompareMultiple(System.StringComparison.CurrentCultureIgnoreCase, "bacon", "eggs", "biscuit")) Then      System.Console.WriteLine("Breakfast!")    Else      System.Console.Write("Dinner")    End If    System.Console.ReadLine()  End SubEnd Module

SQL Merge Multiple Rows Into Single String (2)

Method 1:

DECLARE @str varchar(4000)SET @str = (SELECT CONTACT_EMAIL + ';' FROM table FOR XML PATH(''))SET @str = SUBSTRING(@str,1,LEN(@str)-1)SELECT @str

Method 2:

DECLARE @str varchar(4000)SELECT @str = COALESCE(@str + ';', '') + CONTACT_EMAIL FROM tableSELECT @str

Method 3:

DECLARE @str varchar(4000)SELECT DISTINCT STUFF( (SELECT CONTACT_EMAIL + ';'   from table FOR XML PATH('')),1,1,'')SELECT @str

Resource: Nagendra Prasad

ASP.NET How to dynamically add attributes to BODY tag of MasterPage

Line ‘Master.Master.Master.FindControl’ will depend on how many nested MasterPages you have and from where you try accessing specific control

Private Sub SetMasterBodyClass()    Dim bodyClass As HtmlGenericControl = DirectCast(Master.Master.Master.FindControl("bodyClass"), HtmlGenericControl)    If Not bodyClass Is Nothing Then        If CurrentLanguageCode = "french" Then            bodyClass.Attributes.Add("class", "french")        End If    End IfEnd Sub


ASP.NET Url rewriting – change form action value

Before change you can see real file name:

<form name="aspnetForm" method="post" action="/templates/myPage.aspx" id="aspnetForm">

In the top Master Page change form action:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)    Me.form1.Action = Page.Request.RawUrlEnd Sub

After change:

<form name="aspnetForm" method="post" action="/english/AboutUs.aspx" id="aspnetForm">

Inject JavaScript from code behind (C#/VB.NET)


var sb = new System.Text.StringBuilder();sb.AppendLine("<script language='javascript'>");sb.AppendLine("var pageId = ' + PageId + ';");sb.AppendLine("</script>n");Type t = this.GetType();if (!Page.ClientScript.IsClientScriptBlockRegistered(t, ("ScriptName"))){    Page.ClientScript.RegisterClientScriptBlock(t, "ScriptName", sb.ToString());}


Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder()sb.AppendLine("<script language='javascript'>")sb.AppendLine("var channelid = '" & PageID & "';")sb.AppendLine("</script>")Dim t As Type = Me.GetType()If Not Page.ClientScript.IsClientScriptBlockRegistered(t, ("ScriptName")) Then    Page.ClientScript.RegisterClientScriptBlock(t, "ScriptName", sb.ToString())End If