Friday 13 July 2012

Using the AJAX Control Toolkit in SharePoint

The ASP.NET AJAX Control Toolkit provides a set of sample controls and extenders that makes it a snap to spice up your web site with rich functionality. Think about the Control Toolkit as a bunch of sexy controls which use the ASP.NET AJAX extensions, plus a framework to create a new even sexier control on your own. In this post I'll describe how you can make use of the Control Toolkit in your SharePoint 2007 sites, for example by using the SmartPart.

Actually SharePoint doesn't differ from any other ASP.NET web site to use the Control Toolit, there are only three things that you need to do:

  1. Make sure SharePoint has access to AjaxControlToolkit.dll
    You can do this in two ways: either you deploy the assembly to the Global Assembly Cache (GAC) or you put in the \BIN folder of the SharePoint site's folder.

  2. Add an assembly reference in the web.config (note: for the future versions of the Control Tookit, the version number can change!):
    <assemblies>
    ...
    <add assembly="AjaxControlToolkit, Version=1.0.10201.0, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
    ....
    </assemblies>

  3. Add the tagprefix for the Control Toolkit in the web.config:
    <controls>
    ...
    <add namespace="AjaxControlToolkit" assembly="AjaxControlToolkit" tagPrefix="ajaxToolkit"/>
    ....
    </controls>


That's it! Now you can make use of the Control Toolkit coolness in your SharePoint 2007 sites! If you want to test if the Control Toolkit is working on your installation: I've upload a very small example to CodePlex.

InfoPath 2010 – Error “The amount of data that was returned by a data connection has exceeded the maximum limit that was configured by the server administrator.”

the error message on the screen, (below is an example)

DataConnErr


So lets talk thru the issue.


Problem


So they are using SharePoint 2010 Enterprise, and InfoPath Form Services.  The form in question is a monster custom InfoPath form.  It uses every custom option you can think of, with popup tool tips, custom controls, workflows tied it, and has Java and .NET running some logic.  Generally a “WHY, WHY WOULD YOU DO IT” form.


The size of the form can also be huge when saved with about 5 different Rich Text fields that customers and Support folks put links, images, etc. in.  I have seen forms go in 12 mb in size. 


When they attempt to load these files, or open a view with all these files in it (7500 list items) the are getting that lovely warning.




“The amount of data that was returned by a data connection has exceeded the maximum limit that was configured by the server administrator. Form elements, such as drop-down lists may be blank.”



Solution


So this is an easy fix.


Go to Central Administration > General Application Settings > Configure InfoPath Form Services


Down on the page you are going to see a Data Connection Response Size.  It is defaulted to 1500 kilobytes.


033111_1610_DataConnect2

Change that setting to support your needs, in this case 4500 kilobytes solved the problem.

Once adjusted…..TADA it was reacting just fine, all was well and the Support team was back in action.

Conclusion

So you might ask was this the best solution.  NO, but this was a quick fix.  What additional information should you take from this use case…….FORM REWORK.

The form is out of control,  a new requirements gathering and analysis should be performed to determine a solution that will limit the risk of data size, large list sizes, and responses.  I do expect this content to be moved to a SQL Table, and the use of External Content Types, and Dataviews to support interaction in SharePoint.

Remember that there is a lot of size limitations and thresholds available in SharePoint Central Administration.  Any service you are using can run into this. It is important to have your service limitations documented, and have a running log of these error your SharePoint Admin can reference.  Also this change needs to be documented in the Governance Control documentation, and should be brought up in the next SharePoint Steering Committee.  Use it as an opportunity, not a scar.

URL Rewriting with URLRewriter.Net Simplest Way

URL Rewriting with URLRewriter.Net

URL Rewriting has lots of benefits, listing its main benefits

  • SEO Friendly URL

  • Secured URL

  • No need to change bookmark with change in site structure.


Before URL Rewriting my URL looks like
http://localhost:2661/URLRewrite2/DynamicPage.aspx?MyTitleId=1

After URL Rewriting URL is changed to
http://localhost:2661/URLRewrite2/Article/Asp-Net-website-paths-1.aspx


Lets Understand URL Rewriting with Simple Example

A Website displaying articles list in a gridview on clicking the article link, it will display dynamically generated article content.

Before URL Rewriting when you mouse-over 1st Article Link, "Asp.net Website Path" it uses query string to display the article content.


Dynamic page display Querysting, before URL Rewriting.



After URL Rewriting we will achieve how SEO Friendly URL is used to display article content.


Now, lets understand how we can achieve it.

For URL Rewriting we are using URLRewriter.Net which is available free. Download URLRewriter.Net

Step-by-Step Explanation

Step 1: Download Binary Files for URLRewriter.Net

Step 2: Add Reference to Binary Files, Right click project "Add Reference" and add binary files.


Step 3: Update Web.Config File to make URLRewriter.Net works.
<configuration>

<configSections>
<section name="rewriter"
requirePermission="false"
type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
</configSections>

<system.web>

<httpModules>
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
</httpModules>

</system.web>

<system.webServer>

<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule" />
</modules>

<validation validateIntegratedModeConfiguration="false" />

</system.webServer>

<rewriter>
<rewrite url="~/Article/(.+)-(.+).aspx" to="~/DynamicPage.aspx?MyTitleId=$2"/>
</rewriter>

</configuration>

Step 4: Adding Function to Generate SEO Friendly URL from given Title

public static string GenerateURL(object Title, object strId)
{
string strTitle = Title.ToString();

#region Generate SEO Friendly URL based on Title
//Trim Start and End Spaces.
strTitle = strTitle.Trim();

//Trim "-" Hyphen
strTitle = strTitle.Trim('-');

strTitle = strTitle.ToLower();
char[] chars = @"$%#@!*?;:~`+=()[]{}|\'<>,/^&"".".ToCharArray();
strTitle = strTitle.Replace("c#", "C-Sharp");
strTitle = strTitle.Replace("vb.net", "VB-Net");
strTitle = strTitle.Replace("asp.net", "Asp-Net");

//Replace . with - hyphen
strTitle = strTitle.Replace(".", "-");

//Replace Special-Characters
for (int i = 0; i < chars.Length; i++)
{
string strChar = chars.GetValue(i).ToString();
if (strTitle.Contains(strChar))
{
strTitle = strTitle.Replace(strChar, string.Empty);
}
}

//Replace all spaces with one "-" hyphen
strTitle = strTitle.Replace(" ", "-");

//Replace multiple "-" hyphen with single "-" hyphen.
strTitle = strTitle.Replace("--", "-");
strTitle = strTitle.Replace("---", "-");
strTitle = strTitle.Replace("----", "-");
strTitle = strTitle.Replace("-----", "-");
strTitle = strTitle.Replace("----", "-");
strTitle = strTitle.Replace("---", "-");
strTitle = strTitle.Replace("--", "-");

//Run the code again...
//Trim Start and End Spaces.
strTitle = strTitle.Trim();

//Trim "-" Hyphen
strTitle = strTitle.Trim('-');
#endregion

//Append ID at the end of SEO Friendly URL
strTitle = "~/Article/" + strTitle + "-" + strId + ".aspx";

return strTitle;
}

Step 5: Changing DataBinder.Eval Function in .Aspx Page to reflect changes in URL of Grid.
Note: Learn more about DataBinder.Eval Function

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" Width="788px">
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<Columns>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:HyperLink ID="hlTitle" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Title")%>' NavigateUrl='<%#GenerateURL(DataBinder.Eval(Container.DataItem,"Title"),DataBinder.Eval(Container.DataItem,"Id"))%>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblDesc" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Description")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
</asp:GridView>

Now, Lets Check the stuff so far developed.

Assigning SEO Friendly URL in to grid.


On clicking URL inside grid it will point to Dynamically Generated Page with SEO Friendly URL, rather than QueryString.


Things to consider while URL Rewriting.

Problem 1: Page Postback, will turns User Friendly URL into Original URL.
Problem 2: CSS, Image Files pointing to URL Rewriting Page won't work, as they might be pointing with absolute path.

Problem 1: Page Postback for Page displaying URL Rewritten URL
Page Postback of Page displaying User friendly URL will turns into original state when same page postback occurs. In our example, I am adding one button and trying to make Page Postback. You will notice that Page Postback will turns the User Friendly URL into original URL containing QueryString.


For Resolving Page PostBack problem for Page displaying URL Rewritten URL

This article is inspired from Scott's URL Rewritten article. Adding two files as mentioned by scott. If you are developing code in VB download files from Scott's article, else for C# download files with Sourcecode at the end of this article.



Now, lets test the Page Postback by clicking on Button, you will notice this time, URL remains the same.




Problem 2: Image Display Problem
Now, lets display image on for this page and lets observe what problem we may run into. I have added following line to display image, but it won't works.

<img src="Images/article.gif" />



Resolve Problem, by refrencing file from root.
<img src="../Images/article.gif" />

Adding the left navigation menu to web part pages in SharePoint 2010

I taught a SharePoint 2010 super-user class last week, and the students experienced like so many before them that the web part page layouts which come with SharePoint 2010 removes the left hand navigation menu (the quick launch).
image
This is nothing new and it has been blogged about since 2007. But on my 15 minute Google spree this morning I could not find a recipe which worked 100% with SharePoint 2010,  so I will give it a try myself, and hopefully this can help some others in the future. I’m sure someone else has a complete post on this which I missed, but at least I have leveled up myself in the use of SharePoint Designer and modifying existing layouts instead of creating custom ones :)

Step 1 – Create a new web part page


Create a new web part page either via SharePoint or SharePoint Designer

Step 2 – Edit the page in SharePoint Designer


Edit your web part page in “Advanced Mode” in SharePoint Designer

image

Step 3 – Remove custom css


Around line 34 you will find a code block like the one below











1

2

3

4

5

6

7

8

9

10

11

12


<SharePoint:UIVersionedContent ID="WebPartPageHideQLStyles" UIVersion="4" runat="server">

<ContentTemplate>

<style type="text/css">

body #s4-leftpanel {

display:none;

}

.s4-ca {

margin-left:0px;

}

</style>

</ContentTemplate>

</SharePoint:UIVersionedContent>




Delete this code block.


Step 4 – Remove the overrides for the left column

Further down you will find three lines which prevents the left column for rendering.











1

2

3


<asp:Content ContentPlaceHolderId="PlaceHolderPageImage" runat="server"></asp:Content>

<asp:Content ContentPlaceHolderId="PlaceHolderNavSpacer" runat="server"></asp:Content>

<asp:Content ContentPlaceHolderId="PlaceHolderLeftNavBar" runat="server"></asp:Content>




Remove all three lines.


Step 5 –Save the page

Save and publish your page.


Step 6 – Preview your changes


image

Ajax Control Toolkit with SharePoint 2010

I had to use Ajax control toolkit with sharepoint and I had download the latest version from codeplex. We usually download latest versions of software because we believe that with latest version we can get more features and more bug-free. I had used Ajax Control Toolkit with SharePoint 2007 and it was much easier to configure and use Ajax Control Toolkit. With that belief in mind I had started using Ajax Control Toolkit in SharePoint 2010 downloading latest version for .net framework 3.5. But I failed  and after investigating I had found the following errors.


  • AjaxControlToolkit requires ASP.NET Ajax 4.0 scripts. Ensure the correct version of the scripts are referenced. If you are using an ASP.NET ScriptManager, switch to the ToolkitScriptManager in AjaxControlToolkit.dll.



  • Sys.registerComponent is not a function



The problem here is that latest versions of Ajax Control Toolkit is more optimized or targeted with .net framework 4.0. Even the Ajax control toolkit for .net framework 3.5 doesn’t work with SharePoint 2010. If you try to use Ajax Control Toolkit for 3.5 with SharePoint 2010, you may get the exceptions shown above.

How to make Ajax Control Toolkit working with SharePoint 2010?


Here are the steps to make Ajax Control Toolkit working with SharePoint 2010.

  1. Download Correct (compatible) version of Ajax Control Toolkit.Since current release of Ajax Control Toolkit doesn’t work with SharePoint 2010, you need to download previous release. Maybe Ajax Control Toolkit team will address this issue and we’ll be able to use current Toolkit version with SharePoint in future. Until the current release is made compatible, please download the SharePoint 2010 compatible Ajax Control Toolkit from here.

  2. Add AjaxControlToolkit.dll reference to your projectTo use the Ajax Control Toolkit in your SharePoint project, add reference to the AjaxControlToolkit.dll in your project. To use the Ajax Control Toolkit in any web part control add the following lines to register the Ajax Control Toolkit namespace at web.config
    <%@ Register Assembly="AjaxControlToolkit, Version=3.0.30930.28736,
    Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"
    Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>


  3. Remember, here version 3.x version of Ajax Control Toolkit is used instead 3.5.

  4. Add Ajax Control Toolkit ScriptManager in master page.Open the Master page in SharePoint Designer. By default the v4.Master file is the default master page can be found “_catalogs/masterpage” folder. Before modifying the master page, keep a backup copy.

    • First register the Ajax Control Toolkit namespace in the masterpage file by putting the following line at the top of the file:
      <%@ Register Assembly="AjaxControlToolkit, Version=3.0.30930.28736,
      Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"
      Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>


    • Then remove the ScriptManager registration from the master page by removing the following line:
      <asp:ScriptManager id="ScriptManager" runat="server" EnablePageMethods="false"  
      EnablePartialRendering="true" EnableScriptGlobalization="false" EnableScriptLocalization="true"/>


    • Finally Add the following line in place of the above line to register Ajax Control Toolkit
      <ajaxToolkit:ToolkitScriptManager id="ScriptManager" runat="server" EnablePageMethods="false" 
      EnablePartialRendering="true" EnableScriptGlobalization="false" EnableScriptLocalization="true"/>




  5. Register Ajax Control Toolkit namespaces in SharePoint package DesignerFinally, you need to register the Ajax Control Toolkit namespace with SharePoint Package designer. Registering Ajax Control Toolkit namespaces will add Ajax Control Toolkit namespaces in web.config’s safecontrol list. First open the Package designer in Visual Studio (Package usually exists under Package folder in Visual Studio). And then click the “Advanced” button in package designer window as shown in the image below. In that advanced tab you can add/edit assemblies to be registered safe as part of the deployment of the solution package. Click Add ==> “Add Existing Assembly”. The following image shows wizard to follow.

    image

    Figure 1: Package Designer’s Advance tab

     

    In the “Add existing Assembly” window, add the following namespaces for Ajax Control Toolkit.






































    NamespaceType NameAssembly Name
    AjaxControlToolkit*AjaxControlToolkit
    AjaxControlToolkit.Design*AjaxControlToolkit
    AjaxControlToolkit.HTMLEditor*AjaxControlToolkit
    AjaxControlToolkit.HTMLEditor.Popups*AjaxControlToolkit
    AjaxControlToolkit.HTMLEditor.ToolbarButton*AjaxControlToolkit
    AjaxControlToolkit.MaskedEditValidatorCompatibility*AjaxControlToolkit

    The following image shows the “Add Existing Assembly” window for AjaxControlToolkit dll.

    image

    Figure 2: Add/Edit Existing Assembly window

     

    Now you can build and deploy the package and as a result of deployment, Ajax Control Toolkit namespaces will be registered as safe controls in web.config.


Conclusion


Its really hard to believe that Ajax Control Toolkit’s  latest version doesn’t work with SharePoint. We expect to have the latest version of Ajax Control Toolkit to be compatible with SharePoint 2010. Until then we might have to use an old version of Ajax Control Toolkit.

Tuesday 10 July 2012

Database in recovery



If this is 2005, this might be what you need:

 
select der.session_id, der.command, der.status, der.percent_complete, *
from sys.dm_exec_requests as der


It works for other types of commands that have known progress indicators.  If not, then I really don't think it tells you.  You might also check the error log to see how long it took the previous time...

Monday 9 July 2012

String.Split does not support splitting by a string

error: The best overloaded method match for 'string.Trim(params char[])' has some invalid arguments

 

Lets say I have a multiline TextBox that I want to split into an array of String objects, each containing a line from the TextBox.

A logical way to do this would be:
String[] s = textBox1.Text.Split("\r\n");

This does not work.

A workaround is to use this:

String[] s = textBox1.Text.Split("\r\n".ToCharArray());

URL Rewriting in ASP.NET using global.asax and web.config

URL rewriting is very important for search engines like google, yahoo, etc. as we know website getting most of the traffic from search engines.


Here I am explaining 2 way to rewrite URL in asp.net.
URL rewrining using web.config and URL rewriting using global.asax


URL rewrining using web.config:
URL rewriting in web.config is only use for small number of pages. Here you have to rewrite every page manually in web.config. I am writing sample code for 4 urls.
xml version="1.0"?>
<configuration>
<urlMappings enabled="true">
<add url="~/About-company.aspx"
mappedUrl="~/index.aspx?id=1" />
<add url="~/About-products.aspx"
mappedUrl="~/index.aspx?id=2" />
<add url="~/Contact-us.aspx"
mappedUrl="~/index.aspx?id=3" />
<add url="~/our-team.aspx"
mappedUrl="~/index.aspx?id=4" />
urlMappings>
. . .
configuration>


URL rewriting using global.aspx:


This very simple way and very use full. In this way we can rewrite N number of pages and there is no need extra server configuration. Only you have to use Application_BeginRequest event. Inside this event use Context.RewritePath method to set which URL will execute internally in code behind. Here is the code:


void Application_BeginRequest(object sender, EventArgs e)
{
// Get the current path
string CurrentURL_Path = Request.Path.ToLower();

if (CurrentURL_Path.StartsWith("/news/"))
{

CurrentURL_Path = CurrentURL_Path.Trim("/");
string NewsID = CurrentPath.Substring(CurrentPath.IndexOf("/"));
HttpContext MyContext = HttpContext.Current;
MyContext.RewritePath("/news-show.aspx?News=" +  NewsID);
}
}

A potentially dangerous Request.Form value was detected from the client



Server Error in 'ASP.Net' Application.





A potentially dangerous Request.Form value was detected from the client (TextBox1"=<p>Hello</p>").

Description: Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. You can disable request validation by setting validateRequest=false in the Page directive or in the configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case.

Exception Details: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (TextBox1="<p>Hello</p>").


 

Cause

ASP.Net By default validates all input controls for potentially unsafe contents that can lead to Cross Site Scripting and SQL Injections. Thus it disallows such content by throwing the above Exception. By default it is recommended to allow this check to happen on each postback.

 

Solution

On many occasions you need to submit HTML Content to your page through Rich TextBoxes or Rich Text Editors. In that case you can avoid this exception by setting the ValidateRequest tag in the @Page Directive to false.


<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest = "false"


 

This will disable the validation of requests for the page you have set the ValidateRequest flag to false. If you want to disable this check throughout your Web Application you’ll need to set it  false in your web.config <system.web> section


<pages validateRequest ="false " />


 

That’s it. Hope this helps you in getting rid of the above issue.

HttpSimpleClientProtocol.Invoke Method

namespace MyMath {
using System.Diagnostics;
using System.Xml.Serialization;
using System;
using System.Web.Services.Protocols;
using System.Web.Services;

[System.Web.Services.WebServiceBindingAttribute(Name="MathSoap", Namespace="http://tempuri.org/")]
public class Math : System.Web.Services.Protocols.SoapHttpClientProtocol {

[System.Diagnostics.DebuggerStepThroughAttribute()]
public Math() {
this.Url = "http://www.contoso.com/math.asmx";
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Add", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public int Add(int num1, int num2) {
object[] results = this.Invoke("Add", new object[] {num1,
num2});
return ((int)(results[0]));
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
public System.IAsyncResult BeginAdd(int num1, int num2, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("Add", new object[] {num1,
num2}, callback, asyncState);
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
public int EndAdd(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((int)(results[0]));
}
}
}

Create and Use a Sample SQL Cursor and T-SQL Cursor Example Code

Here is a SQL cursor example code created for looping through a list of records as a result of a select query, which enables the sql developer to execute a stored procedure for each row in the cursor which use the values fetched by the cursor as the input arguments. The sample cursor is developed on a MS SQL Server and is a sample for sql server cursor. The sql codes may use t-sql codes so the sql cursor example may have differences than a typical pl/sql cursor or an Oracle cursor.

The sample sql cursor codes below illustrates a process of merging duplicate customer records kept in an application database. Assume that the duplicate customers list and relation among the duplicate customer records are inserted into and kept in a table named DuplicateCustomers which is simply formed of columns MasterCustomerId, DuplicateCustomerId and some other columns like MergeDate, IsMerged, MergedByUserId, InsertedDate, InsertedByUserId, etc which are used during processing some details and useful in the reporting of the duplicate record merge process results.


The list of the original customer records and the duplicate customer records can be selected by the sql select query below:
SELECT MasterCustomerId, DuplicateCustomerId
FROM DuplicateCustomers WHERE IsMerged = 0

You can either create a temporary table to keep the result set in order to use your initial set of records in the next steps of your process. Or you can just use the above transact sql query to supply your records set to feed the t-sql cursor example we will create.

Here with the variable declarations we will set column values we fetch with the tsql cursor to the variables.
DECLARE @MergeDate Datetime
DECLARE @MasterId Int
DECLARE @DuplicateId Int

Then the sql cursor definition or the t-sql cursor declaration code takes place.
DECLARE merge_cursor CURSOR FAST_FORWARD FOR
SELECT MasterCustomerId, DuplicateCustomerId
FROM DuplicateCustomers WHERE IsMerged = 0

During the example sql cursor declaration you can set the sql cursor properties or the attributes of the cursor. Note that the sample cursor declaration uses the FAST_FORWARD key attribute in order to create a sql cursor with a high performance. Since FAST_FORWARD states that the cursor is FORWARD_ONLY and READ_ONLY the performance of the cursor is optimized.

The t-sql syntax of cursor declaration command DECLARE CURSOR is stated as below in MSDN :
DECLARE cursor_name CURSOR
[ LOCAL | GLOBAL ]
[ FORWARD_ONLY | SCROLL ]
[ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ]
[ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ]
[ TYPE_WARNING ]
FOR select_statement
[ FOR UPDATE [ OF column_name [ ,...n ] ] ]

You can find more on how to declare a t-sql cursor and cursor attributes in Books Online

With the call of the OPEN command the t-sql server cursor is opened and the cursor is populated with the data by the execution of the select query of the DECLARE CURSOR command.
OPEN merge_cursor

So the OPEN command runs or executes the "SELECT MasterCustomerId, DuplicateCustomerId FROM DuplicateCustomers WHERE IsMerged = 0" select query defined in the DECLARE CURSOR definition command which is set after FOR key. With the execution of this select query the cursor is populated with the rows or the data returned as a result set of the query.

The next step in using a cursor is fetching the rows from the populated cursor one by one.
FETCH NEXT FROM merge_cursor INTO @MasterId, @DuplicateId

The syntax of the FETCH command is as follows
FETCH
[ [ NEXT | PRIOR | FIRST | LAST
| ABSOLUTE { n | @nvar }
| RELATIVE { n | @nvar }
]
FROM
]
{ { [ GLOBAL ] cursor_name } | @cursor_variable_name }
[ INTO @variable_name [ ,...n ] ]

With the use of the NEXT, the FETCH NEXT command returns the next row following the current row. If FETCH NEXT is called for the first time for a cursor, or we can say if it is called after the OPEN CURSOR command, then the first row in the returned result set is fetched or returned. The column values in the returned row can be set into variables with the INTO key and by giving the names of the variables as a comma seperated list after the INTO key.

So for our example the first row in the return result set of the cursor is set into two variables named @MasterId and @DuplicateId. Here one important point is the first column of the result set (column named MasterCustomerId) is set to first variable defined in the list which is the @MasterId variable. And the secod column named DuplicateCustomerId is set to the second variable @DuplicateId.

So the variable types must be carefully declared according to the column types of the selected rows.

After the FETCH command, you should always control the value of the @@FETCH_STATUS. This variable returns the status of the last cursor FETCH command in the current connection.

The possible return values of @@FETCH_STATUS are;















0FETCH statement was successful
-1FETCH statement failed or the row was beyond the result set
-2Row fetched is missing

By always checking the @@FETCH_STATUS and controlling that it is value is equal to "0" we will have a new row fetched. When the fetched status is different than the "0" we can say that we have no more records are fetched. In short, the value of @@FETCH_STATUS variable is the controlling parameter of the loop we will use during processing all records or rows in the cursor.

In the body part of the WHILE statement the codes to process each row returned by the cursor takes place. This code block changes according to your reason to create and use a cursor. I placed an EXEC call for a sql stored procedure and an UPDATE sql statement here in order to show as a sample.

The most important thing to care for the inside codes of the WHILE code block is the last code statement FETCH NEXT command is recalled to get the next row from the return cursor data set.

After all the records are processed the @@FETCH_STATUS parameter returns -1, so the cursor can be now closed with the CLOSE CURSOR command. CLOSE CURSOR releases the current result set. And the DEALLOCATE CURSOR command releases the last cursor reference.

Here you can find the full sql cursor example code used in this article for explaining the t-sql cursors in SQL Server.
DECLARE @MergeDate Datetime
DECLARE @MasterId Int
DECLARE @DuplicateId Int

SELECT @MergeDate = GetDate()


DECLARE merge_cursor CURSOR FAST_FORWARD FOR SELECT MasterCustomerId, DuplicateCustomerId FROM DuplicateCustomers WHERE IsMerged = 0

OPEN merge_cursor

FETCH NEXT FROM merge_cursor INTO @MasterId, @DuplicateId

WHILE @@FETCH_STATUS = 0
BEGIN
EXEC MergeDuplicateCustomers @MasterId, @DuplicateId

UPDATE DuplicateCustomers
SET
IsMerged = 1,
MergeDate = @MergeDate
WHERE
MasterCustomerId = @MasterId AND
DuplicateCustomerId = @DuplicateId

FETCH NEXT FROM merge_cursor INTO @MasterId, @DuplicateId
END

CLOSE merge_cursor
DEALLOCATE merge_cursor

Wednesday 13 June 2012

How to format datetime & date in Sql Server 2005

Execute the following Microsoft SQL Server T-SQL datetime and date formatting scripts in Management Studio Query Editor to demonstrate the multitude of temporal data formats available in SQL Server.

First we start with the conversion options available for sql datetime formats with century (YYYY or CCYY format). Subtracting 100 from the Style (format) number will transform dates without century (YY). For example Style 103 is with century, Style 3 is without century. The default Style values – Style 0 or 100, 9 or 109, 13 or 113, 20 or 120, and 21 or 121 – always return the century (yyyy) format.

 

– Microsoft SQL Server T-SQL date and datetime formats

– Date time formats – mssql datetime

– MSSQL getdate returns current system date and time in standard internal format

SELECT convert(varchar, getdate(), 100) – mon dd yyyy hh:mmAM (or PM)

– Oct  2 2008 11:01AM

SELECT convert(varchar, getdate(), 101) – mm/dd/yyyy - 10/02/2008

SELECT convert(varchar, getdate(), 102) – yyyy.mm.dd – 2008.10.02

SELECT convert(varchar, getdate(), 103) – dd/mm/yyyy

SELECT convert(varchar, getdate(), 104) – dd.mm.yyyy

SELECT convert(varchar, getdate(), 105) – dd-mm-yyyy

SELECT convert(varchar, getdate(), 106) – dd mon yyyy

SELECT convert(varchar, getdate(), 107) – mon dd, yyyy

SELECT convert(varchar, getdate(), 108) – hh:mm:ss

SELECT convert(varchar, getdate(), 109) – mon dd yyyy hh:mm:ss:mmmAM (or PM)

– Oct  2 2008 11:02:44:013AM

SELECT convert(varchar, getdate(), 110) – mm-dd-yyyy

SELECT convert(varchar, getdate(), 111) – yyyy/mm/dd

SELECT convert(varchar, getdate(), 112) – yyyymmdd

SELECT convert(varchar, getdate(), 113) – dd mon yyyy hh:mm:ss:mmm

– 02 Oct 2008 11:02:07:577

SELECT convert(varchar, getdate(), 114) – hh:mm:ss:mmm(24h)

SELECT convert(varchar, getdate(), 120) – yyyy-mm-dd hh:mm:ss(24h)

SELECT convert(varchar, getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm

SELECT convert(varchar, getdate(), 126) – yyyy-mm-ddThh:mm:ss.mmm

– 2008-10-02T10:52:47.513

– SQL create different date styles with t-sql string functions

SELECT replace(convert(varchar, getdate(), 111), ‘/’, ‘ ‘) – yyyy mm dd

SELECT convert(varchar(7), getdate(), 126)                 – yyyy-mm

SELECT right(convert(varchar, getdate(), 106), 8)          – mon yyyy

————

– SQL Server date formatting function – convert datetime to string

————

– SQL datetime functions

– SQL Server date formats

– T-SQL convert dates

– Formatting dates sql server

CREATE FUNCTION dbo.fnFormatDate (@Datetime DATETIME, @FormatMask VARCHAR(32))

RETURNS VARCHAR(32)

AS

BEGIN

DECLARE @StringDate VARCHAR(32)

SET @StringDate = @FormatMask

IF (CHARINDEX (‘YYYY’,@StringDate) > 0)

SET @StringDate = REPLACE(@StringDate, ‘YYYY’,

DATENAME(YY, @Datetime))

IF (CHARINDEX (‘YY’,@StringDate) > 0)

SET @StringDate = REPLACE(@StringDate, ‘YY’,

RIGHT(DATENAME(YY, @Datetime),2))

IF (CHARINDEX (‘Month’,@StringDate) > 0)

SET @StringDate = REPLACE(@StringDate, ‘Month’,

DATENAME(MM, @Datetime))

IF (CHARINDEX (‘MON’,@StringDate COLLATE SQL_Latin1_General_CP1_CS_AS)>0)

SET @StringDate = REPLACE(@StringDate, ‘MON’,

LEFT(UPPER(DATENAME(MM, @Datetime)),3))

IF (CHARINDEX (‘Mon’,@StringDate) > 0)

SET @StringDate = REPLACE(@StringDate, ‘Mon’,

LEFT(DATENAME(MM, @Datetime),3))

IF (CHARINDEX (‘MM’,@StringDate) > 0)

SET @StringDate = REPLACE(@StringDate, ‘MM’,

RIGHT(’0′+CONVERT(VARCHAR,DATEPART(MM, @Datetime)),2))

IF (CHARINDEX (‘M’,@StringDate) > 0)

SET @StringDate = REPLACE(@StringDate, ‘M’,

CONVERT(VARCHAR,DATEPART(MM, @Datetime)))

IF (CHARINDEX (‘DD’,@StringDate) > 0)

SET @StringDate = REPLACE(@StringDate, ‘DD’,

RIGHT(’0′+DATENAME(DD, @Datetime),2))

IF (CHARINDEX (‘D’,@StringDate) > 0)

SET @StringDate = REPLACE(@StringDate, ‘D’,

DATENAME(DD, @Datetime))

RETURN @StringDate

END

GO

 

– Microsoft SQL Server date format function test

– MSSQL formatting dates

SELECT dbo.fnFormatDate (getdate(), ‘MM/DD/YYYY’)           – 01/03/2012

SELECT dbo.fnFormatDate (getdate(), ‘DD/MM/YYYY’)           – 03/01/2012

SELECT dbo.fnFormatDate (getdate(), ‘M/DD/YYYY’)            – 1/03/2012

SELECT dbo.fnFormatDate (getdate(), ‘M/D/YYYY’)             – 1/3/2012

SELECT dbo.fnFormatDate (getdate(), ‘M/D/YY’)               – 1/3/12

SELECT dbo.fnFormatDate (getdate(), ‘MM/DD/YY’)             – 01/03/12

SELECT dbo.fnFormatDate (getdate(), ‘MON DD, YYYY’)         – JAN 03, 2012

SELECT dbo.fnFormatDate (getdate(), ‘Mon DD, YYYY’)         – Jan 03, 2012

SELECT dbo.fnFormatDate (getdate(), ‘Month DD, YYYY’)       – January 03, 2012

SELECT dbo.fnFormatDate (getdate(), ‘YYYY/MM/DD’)           – 2012/01/03

SELECT dbo.fnFormatDate (getdate(), ‘YYYYMMDD’)             – 20120103

SELECT dbo.fnFormatDate (getdate(), ‘YYYY-MM-DD’)           – 2012-01-03

– CURRENT_TIMESTAMP returns current system date and time in standard internal format

SELECT dbo.fnFormatDate (CURRENT_TIMESTAMP,‘YY.MM.DD’)      – 12.01.03

GO

————

 

/***** SELECTED SQL DATE/DATETIME FORMATS WITH NAMES *****/

 

– SQL format datetime

– Default format: Oct 23 2006 10:40AM

SELECT [Default]=CONVERT(varchar,GETDATE(),100)

 

– US-Style format: 10/23/2006

SELECT [US-Style]=CONVERT(char,GETDATE(),101)

 

– ANSI format: 2006.10.23

SELECT [ANSI]=CONVERT(char,CURRENT_TIMESTAMP,102)

 

– UK-Style format: 23/10/2006

SELECT [UK-Style]=CONVERT(char,GETDATE(),103)

 

– German format: 23.10.2006

SELECT [German]=CONVERT(varchar,GETDATE(),104)

 

– ISO format: 20061023

SELECT ISO=CONVERT(varchar,GETDATE(),112)

 

– ISO8601 format: 2008-10-23T19:20:16.003

SELECT [ISO8601]=CONVERT(varchar,GETDATE(),126)

————

 

– SQL Server datetime formats

– Century date format MM/DD/YYYY usage in a query

– Format dates SQL Server 2005

SELECT TOP (1)

SalesOrderID,

OrderDate = CONVERT(char(10), OrderDate, 101),

OrderDateTime = OrderDate

FROM AdventureWorks.Sales.SalesOrderHeader

/* Result

 

SalesOrderID      OrderDate               OrderDateTime

43697             07/01/2001          2001-07-01 00:00:00.000

*/

 

– SQL update datetime column

– SQL datetime DATEADD

UPDATE Production.Product

SET ModifiedDate=DATEADD(dd,1, ModifiedDate)

WHERE ProductID = 1001

 

– MM/DD/YY date format

– Datetime format sql

SELECT TOP (1)

SalesOrderID,

OrderDate = CONVERT(varchar(8), OrderDate, 1),

OrderDateTime = OrderDate

FROM AdventureWorks.Sales.SalesOrderHeader

ORDER BY SalesOrderID desc

/* Result

 

SalesOrderID      OrderDate         OrderDateTime

75123             07/31/04          2004-07-31 00:00:00.000

*/

 

– Combining different style formats for date & time

– Datetime formats

– Datetime formats sql

DECLARE @Date DATETIME

SET @Date = ’2015-12-22 03:51 PM’

SELECT CONVERT(CHAR(10),@Date,110) + SUBSTRING(CONVERT(varchar,@Date,0),12,8)

– Result: 12-22-2015  3:51PM

 

– Microsoft SQL Server cast datetime to string

SELECT stringDateTime=CAST (getdate() as varchar)

– Result: Dec 29 2012  3:47AM

————

– SQL Server date and time functions overview

————

– SQL Server CURRENT_TIMESTAMP function

– SQL Server datetime functions

– local NYC – EST – Eastern Standard Time zone

– SQL DATEADD function – SQL DATEDIFF function

SELECT CURRENT_TIMESTAMP                        – 2012-01-05 07:02:10.577

– SQL Server DATEADD function

SELECT DATEADD(month,2,’2012-12-09′)            – 2013-02-09 00:00:00.000

– SQL Server DATEDIFF function

SELECT DATEDIFF(day,’2012-12-09′,’2013-02-09′)  – 62

– SQL Server DATENAME function

SELECT DATENAME(month,   ’2012-12-09′)          – December

SELECT DATENAME(weekday, ’2012-12-09′)          – Sunday

– SQL Server DATEPART function

SELECT DATEPART(month, ’2012-12-09′)            – 12

– SQL Server DAY function

SELECT DAY(’2012-12-09′)                        – 9

– SQL Server GETDATE function

– local NYC – EST – Eastern Standard Time zone

SELECT GETDATE()                                – 2012-01-05 07:02:10.577

– SQL Server GETUTCDATE function

– London – Greenwich Mean Time

SELECT GETUTCDATE()                             – 2012-01-05 12:02:10.577

– SQL Server MONTH function

SELECT MONTH(’2012-12-09′)                      – 12

– SQL Server YEAR function

SELECT YEAR(’2012-12-09′)                       – 2012

 

 

————

– T-SQL Date and time function application

– CURRENT_TIMESTAMP and getdate() are the same in T-SQL

————

– SQL first day of the month

– SQL first date of the month

– SQL first day of current month – 2012-01-01 00:00:00.000

SELECT DATEADD(dd,0,DATEADD(mm, DATEDIFF(mm,0,CURRENT_TIMESTAMP),0))

– SQL last day of the month

– SQL last date of the month

– SQL last day of current month – 2012-01-31 00:00:00.000

SELECT DATEADD(dd,-1,DATEADD(mm, DATEDIFF(mm,0,CURRENT_TIMESTAMP)+1,0))

– SQL first day of last month

– SQL first day of previous month – 2011-12-01 00:00:00.000

SELECT DATEADD(mm,-1,DATEADD(mm, DATEDIFF(mm,0,CURRENT_TIMESTAMP),0))

– SQL last day of last month

– SQL last day of previous month – 2011-12-31 00:00:00.000

SELECT DATEADD(dd,-1,DATEADD(mm, DATEDIFF(mm,0,DATEADD(MM,-1,GETDATE()))+1,0))

– SQL first day of next month – 2012-02-01 00:00:00.000

SELECT DATEADD(mm,1,DATEADD(mm, DATEDIFF(mm,0,CURRENT_TIMESTAMP),0))

– SQL last day of next month – 2012-02-28 00:00:00.000

SELECT DATEADD(dd,-1,DATEADD(mm, DATEDIFF(mm,0,DATEADD(MM,1,GETDATE()))+1,0))

GO

– SQL first day of a month – 2012-10-01 00:00:00.000

DECLARE @Date datetime; SET @Date = ’2012-10-23′

SELECT DATEADD(dd,0,DATEADD(mm, DATEDIFF(mm,0,@Date),0))

GO

– SQL last day of a month – 2012-03-31 00:00:00.000

DECLARE @Date datetime; SET @Date = ’2012-03-15′

SELECT DATEADD(dd,-1,DATEADD(mm, DATEDIFF(mm,0,@Date)+1,0))

GO

– SQL first day of year

– SQL first day of the year  -  2012-01-01 00:00:00.000

SELECT DATEADD(yy, DATEDIFF(yy,0,CURRENT_TIMESTAMP), 0)

– SQL last day of year

– SQL last day of the year   – 2012-12-31 00:00:00.000

SELECT DATEADD(yy,1, DATEADD(dd, -1, DATEADD(yy,

DATEDIFF(yy,0,CURRENT_TIMESTAMP), 0)))

– SQL last day of last year

– SQL last day of previous year   – 2011-12-31 00:00:00.000

SELECT DATEADD(dd,-1,DATEADD(yy,DATEDIFF(yy,0,CURRENT_TIMESTAMP), 0))

GO

– SQL calculate age in years, months, days

– SQL table-valued function

– SQL user-defined function – UDF

– SQL Server age calculation – date difference

– Format dates SQL Server 2008

USE AdventureWorks2008;

GO

CREATE FUNCTION fnAge  (@BirthDate DATETIME)

RETURNS @Age TABLE(Years  INT,

Months INT,

Days   INT)

AS

BEGIN

DECLARE  @EndDate     DATETIME, @Anniversary DATETIME

SET @EndDate = Getdate()

SET @Anniversary = Dateadd(yy,Datediff(yy,@BirthDate,@EndDate),@BirthDate)

INSERT @Age

SELECT Datediff(yy,@BirthDate,@EndDate) - (CASE

WHEN @Anniversary > @EndDate THEN 1

ELSE 0

END), 0, 0

UPDATE @Age     SET    Months = Month(@EndDate - @Anniversary) - 1

UPDATE @Age     SET    Days = Day(@EndDate - @Anniversary) - 1

RETURN

END

GO

 

– Test table-valued UDF

SELECT * FROM   fnAge(’1956-10-23′)

SELECT * FROM   dbo.fnAge(’1956-10-23′)

/* Results

Years       Months      Days

52          4           1

*/

 

———-

– SQL date range between

———-

– SQL between dates

USE AdventureWorks;

– SQL between

SELECT POs=COUNT(*) FROM Purchasing.PurchaseOrderHeader

WHERE OrderDate BETWEEN ’20040301′ AND ’20040315′

– Result: 108

 

– BETWEEN operator is equivalent to >=…AND….<=

SELECT POs=COUNT(*) FROM Purchasing.PurchaseOrderHeader

WHERE OrderDate

BETWEEN ’2004-03-01 00:00:00.000′ AND ’2004-03-15  00:00:00.000′

/*

Orders with OrderDates

’2004-03-15  00:00:01.000′  – 1 second after midnight (12:00AM)

’2004-03-15  00:01:00.000′  – 1 minute after midnight

’2004-03-15  01:00:00.000′  – 1 hour after midnight

 

are not included in the two queries above.

*/

– To include the entire day of 2004-03-15 use the following two solutions

SELECT POs=COUNT(*) FROM Purchasing.PurchaseOrderHeader

WHERE OrderDate >= ’20040301′ AND OrderDate < ’20040316′

 

– SQL between with DATE type (SQL Server 2008)

SELECT POs=COUNT(*) FROM Purchasing.PurchaseOrderHeader

WHERE CONVERT(DATE, OrderDate) BETWEEN ’20040301′ AND ’20040315′

———-

– Non-standard format conversion: 2011 December 14

– SQL datetime to string

SELECT [YYYY Month DD] =

CAST(YEAR(GETDATE()) AS VARCHAR(4))+ ‘ ‘+

DATENAME(MM, GETDATE()) + ‘ ‘ +

CAST(DAY(GETDATE()) AS VARCHAR(2))

 

– Converting datetime to YYYYMMDDHHMMSS format: 20121214172638

SELECT replace(convert(varchar, getdate(),111),‘/’,”) +

replace(convert(varchar, getdate(),108),‘:’,”)

 

– Datetime custom format conversion to YYYY_MM_DD

select CurrentDate=rtrim(year(getdate())) + ‘_’ +

right(’0′ + rtrim(month(getdate())),2) + ‘_’ +

right(’0′ + rtrim(day(getdate())),2)

 

– Converting seconds to HH:MM:SS format

declare @Seconds int

set @Seconds = 10000

select TimeSpan=right(’0′ +rtrim(@Seconds / 3600),2) + ‘:’ +

right(’0′ + rtrim((@Seconds % 3600) / 60),2) + ‘:’ +

right(’0′ + rtrim(@Seconds % 60),2)

– Result: 02:46:40

 

– Test result

select 2*3600 + 46*60 + 40

– Result: 10000

– Set the time portion of a datetime value to 00:00:00.000

– SQL strip time from date

– SQL strip time from datetime

SELECT CURRENT_TIMESTAMP ,DATEADD(dd, DATEDIFF(dd, 0, CURRENT_TIMESTAMP), 0)

– Results: 2014-01-23 05:35:52.793 2014-01-23 00:00:00.000

/*******

 

VALID DATE RANGES FOR DATE/DATETIME DATA TYPES

 

SMALLDATETIME date range:

January 1, 1900 through June 6, 2079

 

DATETIME date range:

January 1, 1753 through December 31, 9999

 

DATETIME2 date range (SQL Server 2008):

January 1,1 AD through December 31, 9999 AD

 

DATE date range (SQL Server 2008):

January 1, 1 AD through December 31, 9999 AD

 

*******/

– Selecting with CONVERT into different styles

– Note: Only Japan & ISO styles can be used in ORDER BY

SELECT TOP(1)

Italy  = CONVERT(varchar, OrderDate, 105)

, USA    = CONVERT(varchar, OrderDate, 110)

, Japan  = CONVERT(varchar, OrderDate, 111)

, ISO    = CONVERT(varchar, OrderDate, 112)

FROM AdventureWorks.Purchasing.PurchaseOrderHeader

ORDER BY PurchaseOrderID DESC

/* Results

Italy       USA         Japan       ISO

25-07-2004  07-25-2004  2004/07/25  20040725

*/

– SQL Server convert date to integer

DECLARE @Datetime datetime

SET @Datetime = ’2012-10-23 10:21:05.345′

SELECT DateAsInteger = CAST (CONVERT(varchar,@Datetime,112) as INT)

– Result: 20121023

 

– SQL Server convert integer to datetime

DECLARE @intDate int

SET @intDate = 20120315

SELECT IntegerToDatetime = CAST(CAST(@intDate as varchar) as datetime)

– Result: 2012-03-15 00:00:00.000

————

– SQL Server CONVERT script applying table INSERT/UPDATE

————

– SQL Server convert date

– Datetime column is converted into date only string column

USE tempdb;

GO

CREATE TABLE sqlConvertDateTime   (

DatetimeCol datetime,

DateCol char(8));

INSERT sqlConvertDateTime (DatetimeCol) SELECT GETDATE()

 

UPDATE sqlConvertDateTime

SET DateCol = CONVERT(char(10), DatetimeCol, 112)

SELECT * FROM sqlConvertDateTime

 

– SQL Server convert datetime

– The string date column is converted into datetime column

UPDATE sqlConvertDateTime

SET DatetimeCol = CONVERT(Datetime, DateCol, 112)

SELECT * FROM sqlConvertDateTime

 

– Adding a day to the converted datetime column with DATEADD

UPDATE sqlConvertDateTime

SET DatetimeCol = DATEADD(day, 1, CONVERT(Datetime, DateCol, 112))

SELECT * FROM sqlConvertDateTime

 

– Equivalent formulation

– SQL Server cast datetime

UPDATE sqlConvertDateTime

SET DatetimeCol = DATEADD(dd, 1, CAST(DateCol AS datetime))

SELECT * FROM sqlConvertDateTime

GO

DROP TABLE sqlConvertDateTime

GO

/* First results

DatetimeCol                   DateCol

2014-12-25 16:04:15.373       20141225 */

 

/* Second results:

DatetimeCol                   DateCol

2014-12-25 00:00:00.000       20141225  */

 

/* Third results:

DatetimeCol                   DateCol

2014-12-26 00:00:00.000       20141225  */

————

– SQL month sequence – SQL date sequence generation with table variable

– SQL Server cast string to datetime – SQL Server cast datetime to string

– SQL Server insert default values method

DECLARE @Sequence table (Sequence int identity(1,1))

DECLARE @i int; SET @i = 0

DECLARE @StartDate datetime;

SET @StartDate = CAST(CONVERT(varchar, year(getdate()))+

RIGHT(’0′+convert(varchar,month(getdate())),2) + ’01′ AS DATETIME)

WHILE ( @i < 120)

BEGIN

INSERT @Sequence DEFAULT VALUES

SET @i = @i + 1

END

SELECT MonthSequence = CAST(DATEADD(month, Sequence,@StartDate) AS varchar)

FROM @Sequence

GO

/* Partial results:

MonthSequence

Jan  1 2012 12:00AM

Feb  1 2012 12:00AM

Mar  1 2012 12:00AM

Apr  1 2012 12:00AM

*/

————

 

————

– SQL Server Server datetime internal storage

– SQL Server datetime formats

————

– SQL Server datetime to hex

SELECT Now=CURRENT_TIMESTAMP, HexNow=CAST(CURRENT_TIMESTAMP AS BINARY(8))

/* Results

 

Now                     HexNow

2009-01-02 17:35:59.297 0x00009B850122092D

*/

– SQL Server date part – left 4 bytes – Days since 1900-01-01

SELECT Now=DATEADD(DAY, CONVERT(INT, 0x00009B85), ’19000101′)

GO

– Result: 2009-01-02 00:00:00.000

 

– SQL time part – right 4 bytes – milliseconds since midnight

– 1000/300 is an adjustment factor

– SQL dateadd to Midnight

SELECT Now=DATEADD(MS, (1000.0/300)* CONVERT(BIGINT, 0x0122092D), ’2009-01-02′)

GO

– Result: 2009-01-02 17:35:59.290

————

————

– String date and datetime date&time columns usage

– SQL Server datetime formats in tables

————

USE tempdb;

SET NOCOUNT ON;

– SQL Server select into table create

SELECT TOP (5)

FullName=convert(nvarchar(50),FirstName+‘ ‘+LastName),

BirthDate = CONVERT(char(8), BirthDate,112),

ModifiedDate = getdate()

INTO Employee

FROM AdventureWorks.HumanResources.Employee e

INNER JOIN AdventureWorks.Person.Contact c

ON c.ContactID = e.ContactID

ORDER BY EmployeeID

GO

– SQL Server alter table

ALTER TABLE Employee ALTER COLUMN FullName nvarchar(50) NOT NULL

GO

ALTER TABLE Employee

ADD CONSTRAINT [PK_Employee] PRIMARY KEY (FullName )

GO

/* Results

 

Table definition for the Employee table

Note: BirthDate is string date (only)

 

CREATE TABLE dbo.Employee(

FullName nvarchar(50) NOT NULL PRIMARY KEY,

BirthDate char(8) NULL,

ModifiedDate datetime NOT NULL

)

*/

SELECT * FROM Employee ORDER BY FullName

GO

/* Results

FullName                BirthDate   ModifiedDate

Guy Gilbert             19720515    2009-01-03 10:10:19.217

Kevin Brown             19770603    2009-01-03 10:10:19.217

Rob Walters             19650123    2009-01-03 10:10:19.217

Roberto Tamburello      19641213    2009-01-03 10:10:19.217

Thierry D’Hers          19490829    2009-01-03 10:10:19.217

*/

 

– SQL Server age

SELECT FullName, Age = DATEDIFF(YEAR, BirthDate, GETDATE()),

RowMaintenanceDate = CAST (ModifiedDate AS varchar)

FROM Employee ORDER BY FullName

GO

/* Results

FullName                Age   RowMaintenanceDate

Guy Gilbert             37    Jan  3 2009 10:10AM

Kevin Brown             32    Jan  3 2009 10:10AM

Rob Walters             44    Jan  3 2009 10:10AM

Roberto Tamburello      45    Jan  3 2009 10:10AM

Thierry D’Hers          60    Jan  3 2009 10:10AM

*/

 

– SQL Server age of Rob Walters on specific dates

– SQL Server string to datetime implicit conversion with DATEADD

SELECT AGE50DATE = DATEADD(YY, 50, ’19650123′)

GO

– Result: 2015-01-23 00:00:00.000

 

– SQL Server datetime to string, Italian format for ModifiedDate

– SQL Server string to datetime implicit conversion with DATEDIFF

SELECT FullName,

AgeDEC31 = DATEDIFF(YEAR, BirthDate, ’20141231′),

AgeJAN01 = DATEDIFF(YEAR, BirthDate, ’20150101′),

AgeJAN23 = DATEDIFF(YEAR, BirthDate, ’20150123′),

AgeJAN24 = DATEDIFF(YEAR, BirthDate, ’20150124′),

ModDate = CONVERT(varchar, ModifiedDate, 105)

FROM Employee

WHERE FullName = ‘Rob Walters’

ORDER BY FullName

GO

/* Results

Important Note: age increments on Jan 1 (not as commonly calculated)

 

FullName    AgeDEC31    AgeJAN01    AgeJAN23    AgeJAN24    ModDate

Rob Walters 49          50          50          50          03-01-2009

*/

 

————

– SQL combine integer date & time into datetime

————

– Datetime format sql

– SQL stuff

DECLARE @DateTimeAsINT TABLE ( ID int identity(1,1) primary key,

DateAsINT int,

TimeAsINT int

)

– NOTE: leading zeroes in time is for readability only!

INSERT @DateTimeAsINT (DateAsINT, TimeAsINT) VALUES (20121023, 235959)

INSERT @DateTimeAsINT (DateAsINT, TimeAsINT) VALUES (20121023, 010204)

INSERT @DateTimeAsINT (DateAsINT, TimeAsINT) VALUES (20121023, 002350)

INSERT @DateTimeAsINT (DateAsINT, TimeAsINT) VALUES (20121023, 000244)

INSERT @DateTimeAsINT (DateAsINT, TimeAsINT) VALUES (20121023, 000050)

INSERT @DateTimeAsINT (DateAsINT, TimeAsINT) VALUES (20121023, 000006)

 

SELECT DateAsINT, TimeAsINT,

CONVERT(datetime, CONVERT(varchar(8), DateAsINT) + ‘ ‘+

STUFF(STUFF ( RIGHT(REPLICATE(’0′, 6) + CONVERT(varchar(6), TimeAsINT), 6),

3, 0, ‘:’), 6, 0, ‘:’))  AS DateTimeValue

FROM   @DateTimeAsINT

ORDER BY ID

GO

/* Results

DateAsINT   TimeAsINT   DateTimeValue

20121023    235959      2012-10-23 23:59:59.000

20121023    10204       2012-10-23 01:02:04.000

20121023    2350        2012-10-23 00:23:50.000

20121023    244         2012-10-23 00:02:44.000

20121023    50          2012-10-23 00:00:50.000

20121023    6           2012-10-23 00:00:06.000

*/

————

 

– SQL Server string to datetime, implicit conversion with assignment

UPDATE Employee SET ModifiedDate = ’20150123′

WHERE FullName = ‘Rob Walters’

GO

SELECT ModifiedDate FROM Employee WHERE FullName = ‘Rob Walters’

GO

– Result: 2015-01-23 00:00:00.000

 

/* SQL string date, assemble string date from datetime parts  */

– SQL Server cast string to datetime – sql convert string date

– SQL Server number to varchar conversion

– SQL Server leading zeroes for month and day

– SQL Server right string function

UPDATE Employee SET BirthDate =

CONVERT(char(4),YEAR(CAST(’1965-01-23′ as DATETIME)))+

RIGHT(’0′+CONVERT(varchar,MONTH(CAST(’1965-01-23′ as DATETIME))),2)+

RIGHT(’0′+CONVERT(varchar,DAY(CAST(’1965-01-23′ as DATETIME))),2)

WHERE FullName = ‘Rob Walters’

GO

SELECT BirthDate FROM Employee WHERE FullName = ‘Rob Walters’

GO

– Result: 19650123

 

– Perform cleanup action

DROP TABLE Employee

– SQL nocount

SET NOCOUNT OFF;

GO

————

————

– sql isdate function

————

USE tempdb;

– sql newid – random sort

SELECT top(3) SalesOrderID,

stringOrderDate = CAST (OrderDate AS varchar)

INTO DateValidation

FROM AdventureWorks.Sales.SalesOrderHeader

ORDER BY NEWID()

GO

SELECT * FROM DateValidation

/* Results

SalesOrderID      stringOrderDate

56720             Oct 26 2003 12:00AM

73737             Jun 25 2004 12:00AM

70573             May 14 2004 12:00AM

*/

– SQL update with top

UPDATE TOP(1) DateValidation

SET stringOrderDate = ‘Apb 29 2004 12:00AM’

GO

– SQL string to datetime fails without validation

SELECT SalesOrderID, OrderDate = CAST (stringOrderDate as datetime)

FROM DateValidation

GO

/* Msg 242, Level 16, State 3, Line 1

The conversion of a varchar data type to a datetime data type resulted in an

out-of-range value.

*/

– sql isdate – filter for valid dates

SELECT SalesOrderID, OrderDate = CAST (stringOrderDate as datetime)

FROM DateValidation

WHERE ISDATE(stringOrderDate) = 1

GO

/* Results

SalesOrderID      OrderDate

73737             2004-06-25 00:00:00.000

70573             2004-05-14 00:00:00.000

*/

– SQL drop table

DROP TABLE DateValidation

Go

 

————

– SELECT between two specified dates – assumption TIME part is 00:00:00.000

————

– SQL datetime between

– SQL select between two dates

SELECT EmployeeID, RateChangeDate

FROM AdventureWorks.HumanResources.EmployeePayHistory

WHERE RateChangeDate >= ’1997-11-01′ AND

RateChangeDate < DATEADD(dd,1,’1998-01-05′)

GO

/* Results

EmployeeID  RateChangeDate

3           1997-12-12 00:00:00.000

4           1998-01-05 00:00:00.000

*/

 

/* Equivalent to

 

– SQL datetime range

SELECT EmployeeID, RateChangeDate

FROM AdventureWorks.HumanResources.EmployeePayHistory

WHERE RateChangeDate >= ’1997-11-01 00:00:00′ AND

RateChangeDate <  ’1998-01-06 00:00:00′

GO

*/

————

– SQL datetime language setting

– SQL Nondeterministic function usage – result varies with language settings

SET LANGUAGE  ‘us_english’;  –– Jan 12 2015 12:00AM

SELECT US = convert(VARCHAR,convert(DATETIME,’01/12/2015′));

SET LANGUAGE  ‘British’;     –– Dec  1 2015 12:00AM

SELECT UK = convert(VARCHAR,convert(DATETIME,’01/12/2015′));

SET LANGUAGE  ‘German’;      –– Dez  1 2015 12:00AM

SET LANGUAGE  ‘Deutsch’;     –– Dez  1 2015 12:00AM

SELECT Germany = convert(VARCHAR,convert(DATETIME,’01/12/2015′));

SET LANGUAGE  ‘French’;      –– déc  1 2015 12:00AM

SELECT France = convert(VARCHAR,convert(DATETIME,’01/12/2015′));

SET LANGUAGE  ‘Spanish’;     –– Dic  1 2015 12:00AM

SELECT Spain = convert(VARCHAR,convert(DATETIME,’01/12/2015′));

SET LANGUAGE  ‘Hungarian’;   –– jan 12 2015 12:00AM

SELECT Hungary = convert(VARCHAR,convert(DATETIME,’01/12/2015′));

SET LANGUAGE  ‘us_english’;

GO

————

————

– Function for Monday dates calculation

————

USE AdventureWorks2008;

GO

– SQL user-defined function

– SQL scalar function – UDF

CREATE FUNCTION fnMondayDate

(@Year          INT,

@Month         INT,

@MondayOrdinal INT)

RETURNS DATETIME

AS

BEGIN

DECLARE  @FirstDayOfMonth CHAR(10),

@SeedDate        CHAR(10)

SET @FirstDayOfMonth = convert(VARCHAR,@Year) + ‘-’ + convert(VARCHAR,@Month) + ‘-01′

SET @SeedDate = ’1900-01-01′

RETURN DATEADD(DD,DATEDIFF(DD,@SeedDate,DATEADD(DD,(@MondayOrdinal * 7) - 1,

@FirstDayOfMonth)) / 7 * 7,  @SeedDate)

END

GO

 

– Test Datetime UDF

– Third Monday in Feb, 2015

SELECT dbo.fnMondayDate(2016,2,3)

– 2015-02-16 00:00:00.000

 

– First Monday of current month

SELECT dbo.fnMondayDate(Year(getdate()),Month(getdate()),1)

– 2009-02-02 00:00:00.000

————

Remove duplicate rows from a DataTable

--------- Demo Removing Duplicate rows in a DataTable ----------------

using System;

using System.Data;

using System.Collections;

 

namespace Demo_DataTableRemoveDupRows

{

class Class1

{

[STAThread]

static void Main(string[] args)

{

 

// create an example datatable with duplicate rows

DataTable tbl = new DataTable();

 

tbl.Columns.Add("ColumnA");

tbl.Columns.Add("ColumnB");

tbl.Columns.Add("ColumnC");

for(int i = 0; i<10; i++)

{

DataRow nr = tbl.NewRow();

nr["ColumnA"] = "A" + i.ToString();

nr["ColumnB"] = "B" + i.ToString();

nr["ColumnC"] = "C" + i.ToString();

tbl.Rows.Add(nr);

// duplicate

nr = tbl.NewRow();

nr["ColumnA"] = "A" + i.ToString();

nr["ColumnB"] = "B" + i.ToString();

nr["ColumnC"] = "C" + i.ToString();

tbl.Rows.Add(nr);

}

 

PrintRows(tbl); // show table with duplicates

 

//Create an array of DataColumns to compare

//If these columns all match we consider the

                  //rows duplicate.

DataColumn[] keyColumns =

                              new DataColumn[]{tbl.Columns["ColumnA"],

                                               tbl.Columns["ColumnA"]};

 

//remove the duplicates

RemoveDuplicates(tbl, keyColumns);

 

 

PrintRows(tbl); // show table again

Console.ReadLine(); // pause to view output

 

}

/// <summary>

/// Removes duplicate rows from given DataTable

/// </summary>

/// <param name="tbl">Table to scan for duplicate rows</param>

/// <param name="KeyColumns">An array of DataColumns

///   containing the columns to match for duplicates</param>

private static void RemoveDuplicates(DataTable tbl,

DataColumn[] keyColumns)

{

int rowNdx = 0;

while(rowNdx < tbl.Rows.Count-1)

{

DataRow[] dups = FindDups(tbl, rowNdx, keyColumns);

if(dups.Length>0)

{

foreach(DataRow dup in dups)

{

tbl.Rows.Remove(dup);

}

}

else

{

rowNdx++;

}

}

}

 

private static DataRow[] FindDups(DataTable tbl,

int sourceNdx,

DataColumn[] keyColumns)

{

ArrayList retVal = new ArrayList();

 

DataRow sourceRow = tbl.Rows[sourceNdx];

for(int i=sourceNdx + 1; i<tbl.Rows.Count; i++)

{

DataRow targetRow = tbl.Rows[i];

if(IsDup(sourceRow, targetRow, keyColumns))

{

retVal.Add(targetRow);

}

}

return (DataRow[]) retVal.ToArray(typeof(DataRow));

}

 

private static bool IsDup(DataRow sourceRow,

DataRow targetRow,

DataColumn[] keyColumns)

{

bool retVal = true;

foreach(DataColumn column in keyColumns)

{

retVal = retVal && sourceRow[column].Equals(targetRow[column]);

if(!retVal) break;

}

return retVal;

}

 

private static void PrintRows(DataTable tbl)

{

for(int i=0; i<tbl.Rows.Count; i++)

{

Console.WriteLine("row: {0}, ColumnA: {1}, ColumnB: {2}", i, tbl.Rows[i]["ColumnA"], tbl.Rows[i]["ColumnB"]);

}

 

}

}

}

--------- End Demo Code ----------------

copy Outlook Calendar items from one folder to another

For Outlook 2010


Clearing the filter from an existing view


To clear the filter from an existing tabular view, follow these steps:

  1. Click to select the Outlook Calendar folder.

  2. On the View tab, click Change view, and then click to select one of the tabular views such as By List or ByCategory.

  3. On the View menu, click Reset View.

  4. Click Yes to reset the view to the original settings.


Defining a new tabular view


To define a new permanent tabular view, follow these steps:

  1. Click to select the Calendar folder.

  2. On the View tab, click Change view, click Manage Views, and then click New.

  3. Type a name for the new view, click to select Table, and then click OK.

  4. In Advanced View Settings, click Sort.

  5. In the Sort items by list, click to select Start and Ascending.

  6. In the Then By list, click to select (none), and then click OK.

  7. Click OK, and then click Apply View.


Either of the previous procedures will display a list of all Calendar items.

After all items are displayed, follow these steps:

  1. To select all items, use the keyboard shortcut, CONTROL+A.

  2. To copy the items, use the keyboard shortcut, CONTROL+C.

  3. Click to select the destination folder.
    Note To paste the items correctly, the destination folder must be a calendar folder.

  4. To paste the items, use the keyboard shortcut, CONTROL+V.


This process inserts a copy of all the Calendar items into the destination folder.

Additional option for Outlook 2010



  1. On the Folder tab, click Copy Calendar.

  2. Select the folder location where you want the calendar to be saved, and then click OK.


NoteTo copy the items correctly, the destination folder must be a calendar folder.

For Outlook 2007, 2003, 2002, 2000


Clearing the filter from an existing view


To clear the filter from an existing tabular view, follow these steps:

  1. Click to select the Outlook Calendar folder.

  2. On the View menu, point to Current View, and then click to select one of the tabular views such as Events or By Category.

  3. On the View menu, point to Current View, and then click Customize Current View.

  4. In the View Summary dialog box, click Filter, click Clear All, and then click OK twice.


Defining a new tabular view


To define a new permanent, tabular view, follow these steps:

  1. Click to select the Calendar folder.

  2. On the View menu, point to Current View, click Define Views, and then click New.

  3. Type a name for the new view, click to select Table, and then click OK.

  4. In View Summary, click Sort.

  5. In the Sort items by list, click to select Start and Ascending.

  6. In the Then By list, click to select (none), and then click OK.

  7. Click OK, and then click Apply View.


Either one of the previous procedures will display a list of all Calendar items.

After all items are displayed, follow these steps:

  1. On the Edit menu, click Select All.

  2. On the Edit menu, click Copy.

  3. Click to select the destination folder.

  4. On the Edit menu, click Paste.


This process inserts a copy of all the Calendar items into the destination folder.

check if node exists









using System;
using System.IO;
using System.Xml;

public class Sample
{
public static void Main()
{
XmlDocument doc = new XmlDocument();
doc.Load("booksort.xml");

//Select the book node with the matching attribute value.
XmlNode nodeToFind;
XmlElement root = doc.DocumentElement;

// Selects all the title elements that have an attribute named lang
nodeToFind = root.SelectSingleNode("//title[@lang]");

if( nodeToFind != null )
{
// It was found, manipulate it.
}
else
{
// It was not found.
}
}
}

Monday 11 June 2012

Import Excel Sheet to SharePoint List



In this article, we will learn how to export the excel data to the SharePoint list.
Steps:

1. Click on Site Actions -> More Options


2. Now click on the Lists -> Select Import Spread Sheet from the type -> then Click Create


3. Give the Name and Description of the List to be created and then browse the Excel Sheet to be uploaded


4. Clicking on Import option, you will find see a popup window opens. Select Range of Cells in the Range Type


5. This option allows you to select the table columns and rows in excel as shown below. After selecting, you will see the selected field’s column and row data being populated in the Select Range field in the popup window


6. Now click on Import in the popup window. Your SharePoint list will be created from the Excel Sheet and the values are also populated as shown below:


You may face some issues while importing the Excel Sheet to SharePoint and the solution is follows:

Error: “Method ‘Post’ of object ‘IOWSPostData’ failed” in SharePoint


Solution:

 Ã˜  Open the Excel Sheet Add-In EXPTOOWS.XLA which will is available at the following location C:\Program Files\Microsoft Office\Office12\1033 by default.

 Ã˜  Press Alt+F11 to display the Visual Basic code editor. Locate the form named "PublishForm" under the folder "Forms" and open the code view of this form.

 Ã˜  Search (Ctrl+F) for the line "lVer = Application.SharePointVersion(URL)" and place a new line "lVer=2" after that line.

 Ã˜  Now try to import the Excel Sheet to the SharePoint, you will not get any errors.


Error: "The specified file is not a valid spreadsheet or contains no data to import"




Solution:

This error occurs when the site you are opening do not have permission to file system. To give permission follow the below steps:

In Internet Explorer click Tools --> Internet Options -> Click Security tab --> Select Trusted Sites --> In the Sites add your URL here.

Now you will be able to import the file properly.

Hope this post helps you! Please free to comment and share this post.

Friday 8 June 2012

How to Find the Duplicate Values in ArrayList

contacts.Sort();

for (int i=1; i <= contacts.Count-1; i++)
{
Console.WriteLine(contacts[ i ]);
Console.WriteLine(contacts[ i-1] );
if(contacts[ i ].ToString() == contacts[ i-1 ].ToString())
{
Console.WriteLine("Duplicate: "+contacts[ i ]);
}
}

Finding Duplicates with SQL

Here's a handy query for finding duplicates in a table. Suppose you want to find all email addresses in a table that exist more than once:
SELECT email, 
COUNT(email) AS NumOccurrences
FROM users
GROUP BY email
HAVING ( COUNT(email) > 1 )

You could also use this technique to find rows that occur exactly once:
SELECT email
FROM users
GROUP BY email
HAVING ( COUNT(email) = 1 )

The difference between Public, Private, Protected, and Nothing?


Access modifiers


public
The type or member can be accessed by any other code in the same assembly or another assembly that references it.

private
The type or member can only be accessed by code in the same class or struct.

protected
The type or member can only be accessed by code in the same class or struct, or in a derived class.

internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal
The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.


Static
The static modifier on a class means that the class cannot be instantiated, and that all of its members are static. A static member has one version regardless of how many instances of its enclosing type are created.

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself.

Static classes are often used as services, you can use them like so:
MyStaticClass.ServiceMethod(...);

Sunday 27 May 2012

Wednesday 16 May 2012

Sharepoint adding an item into a Picture Library



private byte [] StreamFile(string filename)
{
FileStream fs = new FileStream(filename, FileMode.Open,FileAccess.Read);
// Create a byte array of file stream length
byte[] ImageData = new byte[fs.Length];
//Read  block of bytes from stream into the byte array
fs.Read(ImageData,0,System.Convert.ToInt32(fs.Length));
//Close the File Stream
fs.Close();
return ImageData;
}


// then use the following to add the file to the list
list.RootFolder.Files.Add(fileName, StreamFile(fileName));

Retrieve the current username for an FBA user in IP2010

have to use fully trusted forms...might as well use administrator approved forms as well so you dont have to mess with certificates...and use some code like this:

int index = 0;
userName = (this.Application.User.LoginName);
if (userName.Contains("sqlmembershipprovider"))

{
index = userName.IndexOf("sqlmembershipprovider|") + 22;
userName = userName.Substring(index, userName.Length - index);
}

Monday 14 May 2012

Exceptions-log4net

log4 net
-----------------------------------------------------
config settings---

<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="MonitorVendors.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
</configSections>


<log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
<param name="File" value="C:\log.txt" />
<param name="AppendToFile" value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="2MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n" />
</layout>
</appender>
</log4net>

private static readonly ILog LogExamp = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
--------------------------------------------------------------------------

Sunday 13 May 2012

Excel

Excel.Application excelApp = default(Excel.Application);
Excel.Workbook excelWorkbook = default(Excel.Workbook);
Excel.Worksheet excelWorksheet = default(Excel.Worksheet);
excelApp = new Excel.Application();
excelWorkbook = excelApp.Workbooks.Open(bbi, 0,
true,
5,
"",
"",
true,
Excel.XlPlatform.xlWindows,
"t",
false,
false,
0,
true,
1,
0);
excelWorksheet = (Excel.Worksheet)excelWorkbook.ActiveSheet;
Excel.Sheets shts = (Excel.Sheets)excelWorkbook.Sheets;
int startingrowId = 23;
foreach (Excel.Worksheet sheet1 in shts)
{
excelWorksheet = (Excel.Worksheet)sheet1;

switch (excelWorksheet.Name)
{
case "***": Samplemethod();
break;
case Samplemethod2: continue;
}
}
}

---------------------------------------------------------------------

object columnA = 2;
object columnB = 3;
object columnC = new object();
object columnD = new object();
object columnE = 11;
while (((Excel.Range)excelWorksheet.Cells[startingRowId, columnA]).Value2 != null)
{
try
{
string description = ((Excel.Range)excelWorksheet.Cells[startingRowId, columnA]).Value2.ToString();
string ppString = ((Excel.Range)excelWorksheet.Cells[startingRowId, columnB]).Value2.ToString();
if (((Excel.Range)excelWorksheet.Cells[startingRowId, columnD]).Value2 != null)
{
}
startingRowId++;
}
--------------------------------------------------------------------------------------

public static void readExcelfile()
{
Excel.Application excelApp = default(Excel.Application);
Excel.Workbook excelWorkbook = default(Excel.Workbook);
Excel.Worksheet excelWorksheet = default(Excel.Worksheet);
excelApp = new Excel.ApplicationClass();

//excelWorkbook = excelApp.Workbooks.Open(@"C:Tempsample.xls", 0,
excelWorkbook = excelApp.Workbooks.Open(@"C:Tempsample.xls", 0,
true,
5,
"",
"",
true,
Excel.XlPlatform.xlWindows,
"t",
false,
false,
0,
true,
1,
0);
excelWorksheet = (Excel.Worksheet)excelWorkbook.ActiveSheet;
int index = 0;
int i = 1;
// This row,column index should be changed as per your need.
// i.e. which cell in the excel you are interesting to read.
object rowIndex = 1;
object colIndex1 = 1;
object colIndex2 = 2;
try
{
while (((Excel.Range)excelWorksheet.Cells[rowIndex, colIndex1]).Value2 != null)
{
//rowIndex = 1+index;
string firstName = ((Excel.Range)excelWorksheet.Cells[rowIndex, colIndex1]).Value2.ToString();
string lastName = ((Excel.Range)excelWorksheet.Cells[rowIndex, colIndex2]).Value2.ToString();
Console.WriteLine("Name : {0},{1} ", firstName, lastName);
rowIndex = 1 + i;
i++;
index++;
}
}
catch (Exception ex)
{
excelApp.Quit();
Console.WriteLine(ex.Message);
}
}

--------------------------------------------------------

http://support.microsoft.com/kb/302084
http://vb.net-informations.com/excel-2007/vb.net_excel_2007_open_file.htm
http://exceldatareader.codeplex.com/
http://www.codeproject.com/KB/cs/Excel_Application_in_C_.aspx
http://stackoverflow.com/questions/193092/c-how-to-add-excel-worksheet-programatically-office-xp-2003