Wednesday, April 27, 2011

Add/Substract Min/sec with DateTime in c#

To Add Minutes/Seconds

<datetime variable>.AddMinute(double value);
<datetime variable>.Addseconds(double value);


To Substract Minutes/Seconds

<datetime variable>.AddMinute(-(double value));
<datetime variable>.Addseconds(-(double value));

Friday, April 22, 2011

how can we know the OS the client is using

Using C# Code Behind

You can use the following code to find out if the incoming request is from any Mobile device or not (the following code is not updated for Android but you can easily build on it).

string strUserAgent = Request.UserAgent.ToString().ToLower();
if (strUserAgent != null)
{
        if (Request.Browser.IsMobileDevice == true || strUserAgent.Contains("iphone") ||
             strUserAgent.Contains("blackberry") || strUserAgent.Contains("mobile") ||
             strUserAgent.Contains("windows ce") || strUserAgent.Contains("opera mini") ||
             strUserAgent.Contains("palm"))
        {
                //Request from Mobile Device
        }
        else{
                //Request from Computer
        }
}
Once, request is identified to be orignated from any computer, you can put the following code to detect its operating system.

if (Request.UserAgent.IndexOf("Windows NT 5.1") > 0)
{    //Windows XP 
}
else if (Request.UserAgent.IndexOf("Windows NT 5.0") > 0)
{    //Windows 2000
}
else
{    //Other Operation System 
}
 

Using .aspx Page     



Paste this in an .aspx page no code behind needed.
    <!-- p class="title">Browser Capabilities :</p -->
        
        <table width="90%" border="0" align="center" 
                cellpadding="2" cellspacing="2">
                <tr class="header">
                        <td width="30%">Property</td>
                        <td>Value</td>
                </tr>
                <tr>
                        <td>ActiveXControls </td>
                        <td> <%= Request.Browser.ActiveXControls %></td>
                </tr>
                <tr>
                        <td>AOL </td>
                        <td> <%= Request.Browser.AOL %></td>
                </tr>
                <tr>
                        <td>BackgroundSounds </td>
                        <td> <%= Request.Browser.BackgroundSounds %></td>
                </tr>
                <tr>
                        <td>Beta </td>
                        <td> <%= Request.Browser.Beta %></td>
                </tr>
                <tr>
                        <td>Browser </td>
                        <td> <%= Request.Browser.Browser %></td>
                </tr>
                <tr>
                        <td>CDF </td>
                        <td> <%= Request.Browser.CDF %></td>
                </tr>
                <tr>
                        <td>ClrVersion </td>
                        <td> <%= Request.Browser.ClrVersion %></td>
                </tr>
                <tr>
                        <td>Cookies </td>
                        <td> <%= Request.Browser.Cookies %></td>
                </tr>
                <tr>
                        <td>Crawler </td>
                        <td> <%= Request.Browser.Crawler %></td>
                </tr>
                <tr>
                        <td>EcmaScriptVersion </td>
                        <td> <%= Request.Browser.EcmaScriptVersion %></td>
                </tr>
                <tr>
                        <td>Frames </td>
                        <td> <%= Request.Browser.Frames %></td>
                </tr>
                <tr>
                        <td>JavaApplets </td>
                        <td> <%= Request.Browser.JavaApplets %></td>
                </tr>
                <tr>
                        <td>JavaScript </td>
                        <td> <%= Request.Browser.JavaScript %></td>
                </tr>
                <tr>
                        <td>MajorVersion </td>
                        <td> <%= Request.Browser.MajorVersion %></td>
                </tr>
                <tr>
                        <td>MinorVersion </td>
                        <td> <%= Request.Browser.MinorVersion %></td>
                </tr>
                <tr>
                        <td>MSDomVersion </td>
                        <td> <%= Request.Browser.MSDomVersion %></td>
                </tr>
                <tr>
                        <td>Platform </td>
                        <td> <%= Request.Browser.Platform %></td>
                </tr>
                <tr>
                        <td>Tables </td>
                        <td> <%= Request.Browser.Tables %></td>
                </tr>
                <tr>
                        <td>Type </td>
                        <td> <%= Request.Browser.Type %></td>
                </tr>
                <tr>
                        <td>VBScript </td>
                        <td> <%= Request.Browser.VBScript %></td>
                </tr>
                <tr>
                        <td>Version </td>
                        <td> <%= Request.Browser.Version %></td>
                </tr>
                <tr>
                        <td>W3CDomVersion </td>
                        <td> <%= Request.Browser.W3CDomVersion %></td>
                </tr>
                <tr>
                        <td>Win16 </td>
                        <td> <%= Request.Browser.Win16 %></td>
                </tr>
                <tr>
                        <td>Win32 </td>
                        <td> <%= Request.Browser.Win32 %></td>
                </tr>
        </table>

How to find the max identity value in an identity colum using sql server 2008

declare @val as int
select @val = IDENT_CURRENT('table_name')
print @val

Wednesday, April 20, 2011

SQL Server CONVERT() Function

Definition and Usage

The CONVERT() function is a general function for converting data into a new data type.
The CONVERT() function can be used to display date/time data in different formats.

Syntax

CONVERT(data_type(length),data_to_be_converted,style)
Where data_type(length) specifies the target data type (with an optional length), data_to_be_converted contains the value to be converted, and style specifies the output format for the date/time.
The styles that can be used are:
Style IDStyle Format
100 or 0mon dd yyyy hh:miAM (or PM)
101mm/dd/yy
102yy.mm.dd
103dd/mm/yy
104dd.mm.yy
105dd-mm-yy
106dd mon yy
107Mon dd, yy
108hh:mm:ss
109 or 9mon dd yyyy hh:mi:ss:mmmAM (or PM)
110mm-dd-yy
111yy/mm/dd
112yymmdd
113 or 13dd mon yyyy hh:mm:ss:mmm(24h)
114hh:mi:ss:mmm(24h)
120 or 20yyyy-mm-dd hh:mi:ss(24h)
121 or 21yyyy-mm-dd hh:mi:ss.mmm(24h)
126yyyy-mm-ddThh:mm:ss.mmm(no spaces)
130dd mon yyyy hh:mi:ss:mmmAM
131dd/mm/yy hh:mi:ss:mmmAM


Example

The following script uses the CONVERT() function to display different formats. We will use the GETDATE() function to get the current date/time:
CONVERT(VARCHAR(19),GETDATE())
CONVERT(VARCHAR(10),GETDATE(),110)
CONVERT(VARCHAR(11),GETDATE(),106)
CONVERT(VARCHAR(24),GETDATE(),113)
The result would look something like this:
Nov 04 2008 11:45 PM
11-04-2008
04 Nov 08
04 Nov 2008 11:45:34:243

Tuesday, April 19, 2011

Code Snippets – List of C# snippets in VS2008

List of Code Snippets in VS2008 for C#

#if Code snippet for #if
#region Code snippet for #region
attribute Code snippet for attribute using recommended pattern
checked Code snippet for checked block
class Code snippet for class
ctor Code snippet for constructor
~ Code snippet for destructor
cw Code snippet for Console.WriteLine
do Code snippet for do…while loop
else Code snippet for else statement
enum Code snippet for enum
equals Code snippet for implementing Equals() according to guidelines
exception Code snippet for exception
for Code snippet for ‘for’ loop
foreach Code snippet for foreach statement
forr Code snippet for reverse ‘for’ loop
if Code snippet for if statement
indexer Code snippet for indexer
interface Code snippet for interface
invoke Code snippet for safely invoking an event
iterator Code snippet for a simple iterator
iterindex Code snippet for ‘named’ iterator/indexer pair using a nested class
lock Code snippet for lock statement
mbox Code snippet for MessageBox.Show
namespace Code snippet for namespace
prop Code snippet for an automatically implemented property
propg Code snippet for an automatically implemented property with a ‘get’ access or and a private ‘set’ accessor
sim Code snippet for int Main()
struct Code snippet for struct
svm Code snippet for ‘void Main’ method
switch Code snippet for switch statement
try Code snippet for try catch
tryf Code snippet for try finally
unchecked Code snippet for unchecked block
unsafe Code snippet for unsafe statement
using Code snippet for using statement
while Code snippet for while loop

You can see snippet’s keyword typically matches the operator.  So next time you type for or while or try remember to hit TAB-TAB to expand the snippet.  Next time we’ll look at making your own code snippets.


Using Literal Character Strings

A literal string is a sequence of bytes or characters, enclosed within either two single quotes (' ') or two double quotes (" ").
Read Prerequisites for this tutorial and practices if you haven't done so.
Consider the following facts when using literal strings in a SELECT statement:
  1. Literal strings are enclosed in single or double quotation marks.
  2. You can use literal strings just like you normally use a column name in the SELECT statement. The literal string will be displayed in very row of the query result.
  3. Literal strings can be concatenated with another literal string or another column by using function CONCAT.
  4. Special characters (e.g. single or double quotes) in the literal string need to be escaped.
Practice #1: Using a literal string in SELECT statement.
In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. To execute a query, move your cursor anywhere inside the query and then press F9. Note that the SQL needs to end with semi-colon.
-- Use single quotes around literal string
SELECT CategoryID, CategoryName, 'Northwind Category' AS Note
FROM categories;
 -- Use double quotes around literal string
SELECT CategoryID, CategoryName, "Northwind Category" AS Note
FROM categories;
The two queries above produce the same result set. You can use two single quotes or two double quotes but you can't use one single quote and one double quote for a literal string.
Query result set - 8 rows returned:
Literal string in SELECT statement
Practice #2: Concatenate literal strings with columns in SELECT statement.
In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. To execute a query, move your cursor anywhere inside the query and then press F9. Note that the SQL needs to end with semi-colon.
-- Concatenate strings and columns
SELECT CONCAT('Quantity Per Unit for ', ProductName, ' is ', QuantityPerUnit)
        AS "Product Details"
FROM products;
The query above uses function CONCAT to concatenate literal string with column data. MySQL functions are covered in Using Single-Row Functions section.
Query result set - 77 rows returned:
Literal strings are concatenated in SELECT statement
Practice #3: Escape single quote character by backward slash.
In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. To execute a query, move your cursor anywhere inside the query and then press F9. Note that the SQL needs to end with semi-colon.
-- Escape single quote character
SELECT CategoryName, 'Northwind\'s category name' AS Note
FROM categories
Within a string, certain characters have special meaning. Each of these characters needs to be preceded by a backslash \, known as the escape character.
The query above uses a single quote character inside the literal string. Because the literal string is enclosed in two single quotes, we need to escape the one inside the string by using escape character backslash \.
Query result set - 8 rows returned:
Escape single quote in literal string
Practice #4: Use two single quote characters instead of escaping.
In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. To execute a query, move your cursor anywhere inside the query and then press F9. Note that the SQL needs to end with semi-colon.
Alternatively, you can use two single quote characters to mimic the effect of escaping one single quote character.
-- Use two single quote characters to mimic the effect of 
-- escaping one single quote character.
SELECT CategoryName, 'Northwind''s category name' AS Note
FROM categories;
The query above uses two single quotes and produced the same result as the one using escape character in Practice #3.
Query result set - 8 rows returned:
Escape single quote in literal string
Practice #5: Escape double quote character by backward slash.
In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. To execute a query, move your cursor anywhere inside the query and then press F9. Note that the SQL needs to end with semi-colon.
-- Escape double quote character
SELECT CategoryName, "Northwind \"category\" name" AS Note
FROM categories;
The double quote character inside the literal string needs to be escaped because the literal string is enclosed in two double quotes.
Query result set - 8 rows returned:
Escape double quote in literal string
Practice #6: Use two double quote characters instead of escaping.
In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. To execute a query, move your cursor anywhere inside the query and then press F9. Note that the SQL needs to end with semi-colon.
-- Use two double quote characters to mimic the effect of 
-- escaping one double quote.
SELECT CategoryName, "Northwind ""category"" name" AS Note
FROM categories;
The query above uses two double quote characters and produced the same result as the one using escape character in Practice #5.
Query result set - 8 rows returned:
Escape double quote in literal string
Practice #7: One or more single quote characters inside a literal string quoted with two double quotes needs no special treatment and need not to be doubled or escaped.
In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. To execute a query, move your cursor anywhere inside the query and then press F9. Note that the SQL needs to end with semi-colon.
-- A single quote inside a literal string quoted with two double 
-- quotes needs no special treatment and need not to be doubled or escaped.
SELECT CategoryName, "Northwind category's name" AS Note
FROM categories;
The query above uses a single quote inside the literal string that is quoted with two double quotes. The single quote does not need to be escaped.
Query result set - 8 rows returned:
Enclose single quote in double quoted literal string
Practice #8: One or more double quote characters inside a literal string quoted with two single quote characters needs no special treatment and need not to be doubled or escaped.
In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. To execute a query, move your cursor anywhere inside the query and then press F9. Note that the SQL needs to end with semi-colon.
-- double quote characters inside a literal string quoted 
-- with two single quote characters needs no special treatment 
-- and need not to be doubled or escaped.
SELECT CategoryName, 'Northwind "category" name' AS Note
FROM categories;
The query above uses double quotes inside the literal string that is quoted with two single quotes. The double quotes do not need to be escaped.
Query result set - 8 rows returned:
Enclose double quotes in single quoted literal string
Practice #9: Escape backslash itself.
In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. To execute a query, move your cursor anywhere inside the query and then press F9. Note that the SQL needs to end with semi-colon.
-- Add a backslash in the literal string
SELECT CategoryName, 'Northwind \\ category name' AS Note
FROM categories;
The query above displays a backslash in the result. The backslash needs to be escaped by preceding it with another backslash.
Query result set - 8 rows returned:
Escape backslash in literal string
Practice #10: Escape other special characters such as newline character.
In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. To execute a query, move your cursor anywhere inside the query and then press F9. Note that the SQL needs to end with semi-colon.
-- Add line break in the result set. Line break is achieved by using
-- newline character escape sequence \n
SELECT CategoryName, 'Northwind \ncategory \nname' AS Note
FROM categories;
The query above adds a newline in the result set. Newline character is added in by \n in the literal string.
Below is the query result in text view. We switched the result view from grid to text in order to see the multiple lines in the result. Grid view only shows the first line. To switch to text view in SQLyog, highlight anywhere in the result, and then press Ctrl+L on your keyboard.
Query result in text view:
Escape newline character in query result
To see a list of escaped characters in MySQL, click here to go to MySQL online documentation about String data type.

Monday, April 18, 2011

No need to type runat=”server” now

If you are using Visual Studio 2005 or 2008, for every asp.net or Html control, you need to explicity write runat=”server” attribute. Sometimes I really wonder, why I have to write this attribute for every control as most of time I want to access controls on server side. Is n’t is tedious task? It should be added automatically. But it’s not possible with Visual Studio 2005 or 2008.

Well, we have a good news now. Now there is no need to type runat=”server“. It does not mean that It has been removed. Nope.. it’s get added automatically in VS 2010. Wow.. amazing..

In VS 2010, Microsoft has added hundereds of new code snippest for HTML, JavaScript and for ASPX.  If you want to place a textbox on the page, type tb and press Tab. Wow… You will see something like this..

<asp:TextBox ID="TextBox1" runat="server"/>

Type req and press Tab. Boom…

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="errormessage"></asp:RequiredFieldValidator>

There are lots of other code snippest almost for every control. Even for HTML tag also like table. Is n’t is cool?


Using C# and VB.NET classes together in the App_Code folder


In ASP.NET 2.0 one can mix web forms coded in C# and VB.NET together in a single web site. This works great for web forms. However if you want to code classes from App_Code folder in different languages? Such mixing of classes coded in different languages is not allowed with default settings. You can, however,configure your web site to get this done. This article is going to explain you that how one can do that.

Creating sub folders and classes

First of all, Create a new webSite in VS.NET 2005. Add App_Code folder to it. You can do so easily by right clicking on the web site in the Solution Explorer and choosing Add ASP.NET Folder” option (see below).

Different Language

Once you add the App_Code folder add two class files – Class1.cs and Class2.vb. Note that one class file must be in C# where as the other must be in VB.NET. Add the following code in Class1.cs.
C# Code

Similarly, add the following code in Class2.vb.

VB.NET Code

Both of these classes contain a method called HelloWorld() that simply return a string to the caller.

Now try compiling the web site. What happens? You will get an error as shown below:

Error 1 The files ‘/VBandCSharptogether/App_Code/Class2.vb’  and ‘/VBandCSharptogether/App_Code/Class1.cs’ use a
different language, which is not allowed since they need to be compiled together.

The error message bluntly tells us that you can not use different coding languages for the classes in App_Code folder. Fortunately, there is a way to get out of this trap. Firstly you need to put C# and VB.NET classes in separate sub-folders under App_Code. Secondly you need to add some markup in the web.config file to tell ASP.NET compiler about your intention.

<codeSubDirectories> Section


Create two folders under App_Code filder named CSCode and VBCode. Move Class1.cs inside CSCode folder and Class2.vb inside VBCode folder.

Add a web.config file to your web site and add the following markup to it:

Web Config Code

Here, we added <compilation> section. The <codeSubDirectories> section defines a set of sub-directories relative to App_Code folder that are compiled at run time. The directoryName attribute points to the sub-folder of App_code. Each sub folder is compiled separately and hence each can have classes coded in different languages. We added our CSCode and VBCode folder in this section. This way the compiler will compile classes from CSCode and VBCode folders separately.

After configuring the web site try to compile it. This time it compiles successfully.

Enjoy….

Wednesday, April 13, 2011

Programmatically creating an IIS7 site

Create a new solution and add a reference to C:\Windows\System32\InetServ\Microsoft.Web.Administration.dll. Paste the following code and you've got yourself a website on port 82 using the default application pool. In IIS it's named MyCoolWebsite.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Web.Administration;

namespace TestApp
{
  class Program
  {
    static void Main(string[] args)
    {
      string siteName = "MyCoolWebsite";
      string applicationPoolName = "DefaultAppPool";
      string virtualDirectoryPath = "/";
      string virtualDirectoryPhysicalPath = "C:\\temp\\";
      string ipAddress = "*";
      string tcpPort = "81";
      string hostHeader = "";
      string applicationPath = "/";
      long highestId = 1;

      using (ServerManager mgr = new ServerManager())
      {
        Site site = mgr.Sites[siteName];
        if (site != null)
          return; // Site bestaat al

        ApplicationPool appPool = mgr.ApplicationPools[applicationPoolName];
        if (appPool == null)
          throw new Exception(String.Format("Application Pool: {0} does not exist.", applicationPoolName));

        foreach (Site mysite in mgr.Sites)
        {
          if (mysite.Id > highestId)
            highestId = mysite.Id;
        }
        highestId++;

        site = mgr.Sites.CreateElement();
        site.SetAttributeValue("name", siteName);
        site.Id = highestId;
        site.Bindings.Clear();

        string bind = ipAddress + ":" + tcpPort + ":" + hostHeader;

        Binding binding = site.Bindings.CreateElement();
        binding.Protocol = "http";
        binding.BindingInformation = bind;
        site.Bindings.Add(binding);
        //site.Bindings.Add(bind, "http");

        Application app = site.Applications.CreateElement();
        app.Path = applicationPath;
        app.ApplicationPoolName = applicationPoolName;
        VirtualDirectory vdir = app.VirtualDirectories.CreateElement();
        vdir.Path = virtualDirectoryPath;
        vdir.PhysicalPath = virtualDirectoryPhysicalPath;
        app.VirtualDirectories.Add(vdir);
        site.Applications.Add(app);

        mgr.Sites.Add(site);
        mgr.CommitChanges();
      }
    }
  }
}

Tuesday, April 12, 2011

Force ASP.NET Page to Use secure HTTP (https) with SSL/TLS

Sometimes we want to provide encryption and secure identification of the server creating a secure channel over an insecure network.
In that case we need HTTPS connection which ensures reasonable protection e.g. for payment transactions.
Ok let’s see how this thing works.
Say that your page is as follows: http://www.domain.com/yourpage.aspx
Ok, just add this code inside Load Event Handler and voila! That’s it!

If Not Request.IsSecureConnection Then
   Response.Redirect("https://www.domain.com/yourpage.aspx ")
End If

Conversion from Currency into English Words

Function Dollars(ByVal amount As Decimal, _
              Optional ByVal EmptyStringIfZero As Boolean = True) As String
Dim result As String = String.Empty
Select Case amount
Case 0
       result = If(EmptyStringIfZero, String.Empty, "Zero ")
Case 1 To 19
       result = Choose(amount, "One ", "Two ", "Three ", "Four ", _
"Five ", "Six ", "Seven ", "Eight ", "Nine ", "Ten ", "Eleven ", _
"Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", _
"Seventeen ", "Eighteen ", "Nineteen ")
Case 20 To 99
       result = Choose(amount \ 10 - 1, "Twenty ", "Thirty ", _
"Fourty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", _
"Ninety ") & Dollars(amount Mod 10)
Case 100 To 999
         result = Dollars(amount \ 100) & "Hundred" & IIf _
(amount >= 200, "s ", " ") & Dollars(amount Mod 100)
Case 1000 To 999999
         result = Dollars(amount \ 1000) & "Thousand" & IIf _
(amount >= 2000, "s ", " ") & Dollars(amount Mod 1000)
Case 1000000 To 999999999
         result = Dollars(amount \ 1000000) & "Million" & IIf _
(amount >= 2000000, "s ", " ") & Dollars(amount Mod 1000000)
Case Is >= 1000000000
         result = Dollars(amount \ 1000000000) & "Billion" & _
IIf(amount >= 2000000000, "s", " ") & Dollars(amount Mod 1000000000)
End Select
Return result
End Function
 
Public Function Cents(ByVal amount As Decimal) As String
Dim result As String = amount.ToString
If result.Contains("."c) Then
      result = result.Substring(result.IndexOf("."c) + 1)
Else
      result = "00"
End If
Return " and " &amp; result &amp; "/100"
End Function
The usage is also very simple:
Dim amount As Decimal = Decimal.Parse("123.45")
Response.Write(Dollars(amount) & Cents(amount))
P.S. if you are using culture that use comma for decimal separator please modify the cents function respectively.