Pages

Jul 29, 2008

SQL DateTime Functions

SQL - Timestamp
A timestamp servers as the catch all for dates and times. Retrieving a timestamp is very simple and the result can be converted or manipulated in nearly every way imaginable.

SQL Code:
SELECT CURRENT_TIMESTAMP;
Return a Timestamp:2004-06-22 10:33:11.840
Keep in mind that each platform of SQL (DB2, Oracle, SQL Server, etc...) may return dates and times which are formatted differently.
SQL - Date FunctionsAs we just mentioned, it is possible to breakdown timestamps into their individual pieces using any of the following date functions.

SQL Code:
SELECT MONTH(CURRENT_TIMESTAMP);
Return a Month:6 SQL Code:
SELECT DAY(CURRENT_TIMESTAMP);
Return a Day:22

There are many more functions available, including functions to extract milliseconds, names of the months, names of each week day, etc.
Each SQL platform varies in the actual naming of date functions. Here's a few c\The following is a list of other date functions available to most platforms of SQL with the exception of MS's SQL Server.

SQL Function Code:
SELECT DATE(CURRENT_TIMESTAMP); - returns a date (2004-06-22)
SELECT TIME(CURRENT_TIMESTAMP); - returns the time (10:33:11.840)
SELECT DAYOFWEEK(CURRENT_TIMESTAMP); - returns a numeric value (1-7)
SELECT DAYOFMONTH(CURRENT_TIMESTAMP); - returns a day of month (1-31)
SELECT DAYOFYEAR(CURRENT_TIMESTAMP); - returns the day of the year (1-365)
SELECT MONTHNAME(CURRENT_TIMESTAMP); - returns the month name (January - December
SELECT DAYNAME(CURRENT_TIMESTAMP); - returns the name of the day (Sunday - Saturday)
SELECT WEEK(CURRENT_TIMESTAMP); - returns number of the week (1-53)


Timestamps are often the easiest to work with, but we certainly are not limited to using only the current_timestamp as our parameter. We can send any date, time, or timestamp to the function which then returns our result.

SQL Code:
SELECT MONTHNAME('2004-11-27');
Return a Month Name: MONTHNAME('2004-11-27') November
Date functions can also be performed on table columns similarly to numeric and mathematical functions such as SUM() or AVG().

SQL Code:
SELECT DAYOFYEAR(column_name) FROM table_name WHERE name = 'Joe';
SQL will return a numeric result from 1 - 365 representing the day of the year that Joe's record was created/inserted.We can expand this concept one step further with the use of a subquery. Say we have a table with a column named timestamp. In this table column are timestamps of when each record was entered and we would like to know what was the numeric day of the year that a record was entered.

SQL Code:
SELECT DAYOFYEAR((SELECT DATE(timestamp) FROM employees WHERE name = 'James Bond'));
Above you can see how it is possible to combine several date functions as well as a subquery to return very specific information about Mr. James Bond.
SQL - Inserting Date DataDate data exists as numbers, strings, and timestamps. Built into most platforms are several date column types such as DATE or TIMESTAMP. By setting the default value to the current date or timestamp, the table column will automatically be filled with a current date/timestamp as each record is inserted.
Here's the code to add a timestamp column to an existing table.
SQL Code:
ALTER TABLE `orders` ADD `order_date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL;
Now each time an order is placed in our make believe business, a timestamp of that order is also recorded.A date or timestamp table column will only allow date data types to be inserted as values so be sure to convert any strings or numbers to dates and timestamps before trying to insert them.

SQL - Datepart()

Microsoft's SQL Server takes a little different approach to working with dates. It is still possible to extract individual parts of a timestamp and several other functions also work as outlined in SQL - Date. The difference is that SQL Server uses one main function as oppose to several different functions ie the DATEPART() function.
Datepart() requires two parameters, a part argument and a date argument. By part we mean year, day of the year, day of the week, etc. Let's look at an example.

SQL Code:
SELECT DATEPART(week, '2005-12-31');Return the Week Number:53

Here we have successfully pulled the "week number" from existing date.
SQL's CURRENT_DATE function could be also be substituted or a string value representing the year ('Dec 31, 2005').

Jul 25, 2008

Handy Keyboard Shortcuts for c# 2005


Handy Keyboard Shortcuts for c# 2005

The following keyboard shortcuts I find invaluable. It's amazing how many people still use the mouse to do everything.
Document navigation :

Ctrl+Tab Switch documents

Ctrl+Shift+Tab Reverse switch documents

Ctrl+kk Drop a bookmark

Ctrl+kn Itterate through bookmarks

F7 Switch from HTML to Codebehind view

Ctrl+- Navigate backward through last cursor locations


Code Navigation :

F12 Goto Definition

Ctrl+] Jump to matching brace


Editing :

Ctrl+c Copy a whole line

Ctrl+v When a whole line in the clipboard (as above) this will instet a whole copied line.. handy for quick duplication

Ctrl+u Change to lower case

Ctrl+Shift+U Change to UPPER case


Macros :

Ctrl+Shift+R Record a quick Macro

Ctrl+Shift+P Run the quick Macro you just recorded
Comments

Ctrl+kc Comment out selected lines

Ctrl+ku Uncomment selected lines


Formatting

Ctrl+kd Autoformat selected lines

Hope this is more useful to attract others!Happy Programming

Jul 22, 2008

Add,Edit, Delete and View in GridView in Asp.net 2.0

Description
DataGrid plays very important component in ASP.Net Application. It covers most of the basic reports for which you do not need any reporting component like Crystal Report, Report Viewer etc.
Major concern with any data entry form is Add, Edit, Delete and View.


Assumptions-
We are using SQL Server Express editions as Database.
Table Name- Employees
Fields- EmpId, EmpName, Designation
Take GridView control on page and set the ID property to dgEmployees.
Go to property builder by right click on

GridView -> Show Smart Tag -> Edit Columns.

Uncheck Auto-Generate Field from the Property window.
Add three TemplateField Column for Employee Name, Designation, & Delete Button. Add Edit button from CommandField Group from Property Window.
TemplateField Colums have ItemTemplate,

Alternating Item Template,

Edit Template, Header Template, Footer Template.


Each template columns Item Template field contains Label Control & Edit Template contains TextBox control for Editing item. Set the Binding Field name to the Text Property of both controls for each template field to the respective Database Column Name

i.e Eval("EmpName").


Set the DataKeyNames property of GridView to Primary Key Column of DataBase i.e. EmpId.

This property binds the database column field value to each row of gridview as a Unique Identifier.
Set the data bindings for Delete Button for CommandArgument Eval("EmpId"); for saving the ID column value from database for fetching the ID field value while Deleting the Record.

Set the CommandName property to Delete Button to CMDDelete. The CommandName property can contain any string name which can be used to recognize the type of command invoked from gridview. Because when any of the event generated in GridVeiw it fires RowCommand Event. In this event we have to handle the Delete Button Code. Instead if you are using default Delete Button of GridView then register for RowDeleting event of GridView and for accessing Unique ID columnvalue from database you need to fetch the id from DataKeys collection of GridView.

For e.g.
int EmpId = Convert.ToInt32(dgEmployees.DataKeys[e.RowIndex].Value);


Place the Textbox control in the grids Footer template for Adding new record. Set the CommandName to CMDAdd for Add button.
Register events for Edit, Update, Cancel button of gridview RowEditing, RowUpdating, RowCancelEditing.


View in GridView
To view data in gridview is very simple. Just create a DataSet using SqlDataAdapter̢۪s Fill method and set the GridViews DataSource Property to DataSet.
Create a Method to Bind the GridView to DataSource named BindGrid. This method fetches data from the GetEmployees method which returns DataSet from Employees table.
Call the BindGrid on Page_Load in !IsPostBack block to fill the grid by default.
private void BindGrid()
{
dgEmployees.DataSource = GetEmployees();
dgEmployees.DataBind();
}
private DataSet GetEmployees()
{
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection();
conn.ConnectionString =ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
SqlDataAdapter da = new SqlDataAdapter("Select * From Employees", conn);
try
{
da.Fill(ds);
return ds;
}
catch { }
finally
{
conn.Close();
conn.Dispose();
}
return null;
}


Edit in GridView
For Editing Register RowEditing event of GridView. To switch the normal mode to Edit mode of gridview EditIndex property plays important role. EditIndex specifies which row is in edit mode by setting RowIndex to it. By default EditIndex of gridview is -1 (Normal mode).

If you want to edit 3rd Row then set the EditIndex to 2 (Row index starts from 0,1,2..).
After setting editindex refresh the grid by calling BinGrid. GridViewEditEventArgs object knows the current row index so getting row index of the selected row in gridveiw is not big deal; just

e.NewEditIndex (e object of GridViewEditEventArgs).


protected void dgEmployees_RowEditing(object sender, GridViewEditEventArgs e)
{
dgEmployees.EditIndex = e.NewEditIndex;
BindGrid();
}


Cancel in GridView
For Cancel just reset the GridView editindex to default i.e. -1 and refresh the grid.
protected void dgEmployees_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
dgEmployees.EditIndex = -1;
BindGrid();
}


Update in GridView
For Update register RowUpdating event of the gridview. Find the Unique id for updating the row from DataKeys collection of gridview.
int EmpId = Convert.ToInt32(dgEmployees.DataKeys[e.RowIndex].Value);
Find the controls in the selected row by using FindControl method of gridviews rows collection and collect data from the text boxes.


TextBox txtname = dgEmployees.Rows[e.RowIndex].FindControl("txtEmpName") as TextBox;


TextBox txtdesign = dgEmployees.Rows[e.RowIndex].FindControl("txtDesignation") as TextBox;


Finally update the row and refresh the grid.


if(txtname!=null && txtdesign!=null)
UpdateEmployee(empId, txtname.Text.Trim(), txtdesign.Text.Trim());
dgEmployees.EditIndex = -1;
BindGrid();


Complete code-
protected void dgEmployees_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int empId = Convert.ToInt32(dgEmployees.DataKeys[e.RowIndex].Value);
//Find Text boxex
TextBox txtname = dgEmployees.Rows[e.RowIndex].FindControl("txtEmpName") as TextBox;
TextBoxtxtdesign=dgEmployees.Rows[e.RowIndex].FindControl("txtDesignation") as TextBox;
if(txtname!=null && txtdesign!=null)
UpdateEmployee(empId, txtname.Text.Trim(), txtdesign.Text.Trim());
dgEmployees.EditIndex = -1;
BindGrid();
}


Custom Delete in GridView
For Delete register RowCommand event of the gridview. Find the Unique id for deleting the row from DataKeys collection of gridview. Check for CommanName and invoke delete method for the selected row.
protected void dgEmployees_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("CMDDelete"))
{
int EmpId = Convert.ToInt32(e.CommandArgument);
DeleteEmployee(EmpId);
//Refresh Grid
BindGrid();
}
}
Add in GridView
Adding from GridView is just some trick with Footer Template. I added textboxes and a add button in the footer row of the gridview. When u are in Normal mode it is visible else it is invisible to synchronize between edit and add.
Like Updating find the Textbox and pass the values to Addemployee method like
else if (e.CommandName.Equals("CMDAdd"))
{
TextBox txtname = dgEmployees.FooterRow.FindControl("txtEmpName") asTextBox;
TextBox txtdesign = dgEmployees.FooterRow.FindControl("txtDesignation") as TextBox;
if (txtname != null && txtdesign != null)
{
AddEmployee(txtname.Text.Trim(), txtdesign.Text.Trim());
BindGrid();
}
}
The Complete code for EditEmployee, AddEmployee, UpdateEmployee, DeleteEmployee is in Source File.

The code should be in RowCommand event only. Due to this we use CommandName for different button control to differentiate between the type of code to be handled by gridview.

Jul 17, 2008

How to provide ASP.NetWebadminfiles (WSAT) like user management for your hosted or online site

How to provide ASP.NetWebadminfiles (WSAT) like user management for your hosted or online site:
Bulk User ModificationActive Directory Display Name, Logon Name Modification, AD Reports
www.admanagerplus.com
I recently was working on a ASP.net 2.0 website. I used the ActiveDirectoryMembershipProvider and used the membership API along with Login controls to provide a nice experience to the user with features like Sign up as new user, change password, password reset, login and all related functionality which any website offers you.When my code was in development, I had the built in WSAT (ASP.Net website administration tool), which I could launch from Visual Studio.Net and I could easily administer my website.
You can launch this tool using the Website–>ASP.Net configuration menu. This tool is really cool and without writing a single line of code you can easily manage all the security and settings for your website.But the problem arises when you move your code to production. The WSAT tool only works locally (i.e via localhost). By default, it prohibits remote access.In this post, I will explore two ways of managing your website security remotely.

Option 1 :Make changes to the WSAT tool to make it work remotelyThe WSAT tool with source code is located in your C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ASP.NETWebAdminFiles folder. To make it accessible on the network, all you have to do is go to IIS–>Create new virtual directory–>Point to the above folder and remove anonymous access from directory settings page.

Then you need to access it the same way your local ASP.Net configuration tool is accessed i.e via a URL which resembles something like :
http://SERVER/AdminTool/default.aspx?applicationPhysicalPath=C:\Inetpub\wwwrooot\testsite\&applicationUrl=/testsite
But you will notice, as soon as you try to access it, it will spit out an ugly error “This tool cannot be remotely accessed.“. This is because by default the tool is locked down for local access only. To fix this, all you need to do is open
C:\WINDOWS\Microsoft.NET\Framework64\v2.0.50727\ASP.NETWebAdminFiles\App_Code\WebAdminPage.cs file
in a text editor and change line#488 FROM >>
if (!application.Context.Request.IsLocal)
{ <<>
if(false){
Once you save your file, the tool will allow remote access.

Option 2:

Some people may not allow you to mess with the production webserver like above, becasue it involves changing a .net framework file and it can be a security risk. 4guysfromrolla.com has done a nice thing, they have written a generic user management piece which works just like WSAT and you can easily include it as part of your website. Just package it with your website, since it comes with source code (although the source code is in C#). You just have to follow a few steps to make it work for you. You can find the article which talks about the custom tool here : http://aspnet.4guysfromrolla.com/articles/052307-1.aspx
and download the source code here http://aspnet.4guysfromrolla.com/code/ezdeploy.zip

Here are few things I had to do to make it work for my website:
Copy the source code to a subfolder in my site Delete the web.config from the root level which comes with the source code Move the 4guys.master file to the root of my website (this is mentioned in the article) Move images from the i folder to the images folder of my website and change links which point to these images (this is mentioned in the article) Change the stylesheet link in 4guys.master file to point to the correct location. Move _controls folder to the root of my website Delete all subfolders except admin from the source code. We dont need these. Changed the 4guys.master to remove menu links to pages which are irrelevant for the security piece.

NOTE: If you are using ActiveDirectoryMembershipProvider, you will get bunch of errors like The property 'LastLoginDate' is not supported by the Active Directory membership provider.]
System.Web.Security.ActiveDirectoryMembershipUser.get_LastLoginDate()To solve this all you have to do is remove following lines in all the .aspx pages.
(asp:BoundField DataField=”lastlogindate” HeaderText=”Last Login Date” /)
(asp:BoundField DataField=”lastactivitydate” HeaderText=”Last Activity Date” /)(asp:BoundField DataField=”isonline” HeaderText=”Is Online” /)

Jul 8, 2008

ASP.NET Basics

ASP.NET Basics: Foundation of ASP.NET
This has been pooled together from a number of resources:

What is ASP.NET?
Microsoft ASP.NET is a server side technology that enables programmers to build dynamic Web sites, web applications, and XML Web services. It is a part of the .NET based environment and is built on the Common Language Runtime (CLR) . So programmers can write ASP.NET code using any .NET compatible language.
What are the differences between ASP.NET 1.1 and ASP.NET 2.0?
A comparison chart containing the differences between ASP.NET 1.1 and ASP.NET 2.0 can be found over
here.

Which is the latest version of ASP.NET? What were the previous versions released?
The latest version of ASP.NET is 2.0. There have been 3 versions of ASP.NET released as of date. They are as follows :
ASP.NET 1.0 – Released on January 16, 2002.
ASP.NET 1.1 – Released on April 24, 2003.
ASP.NET 2.0 – Released on November 7, 2005.
Additionally, ASP.NET 3.5 is tentatively to be released by the end of the 2007.


Explain the Event Life cycle of ASP.NET 2.0?
The events occur in the following sequence. Its best to turn on tracing(% @Page Trace=”true”%) and track the flow of events :
PreInit – This event represents the entry point of the page life cycle. If you need to change the Master page or theme programmatically, then this would be the event to do so. Dynamic controls are created in this event.
Init – Each control in the control collection is initialized.
Init Complete* - Page is initialized and the process is completed.
PreLoad* - This event is called before the loading of the page is completed.
Load – This event is raised for the Page and then all child controls. The controls properties and view state can be accessed at this stage. This event indicates that the controls have been fully loaded.
LoadComplete* - This event signals indicates that the page has been loaded in the memory. It also marks the beginning of the rendering stage.
PreRender – If you need to make any final updates to the contents of the controls or the page, then use this event. It first fires for the page and then for all the controls.
PreRenderComplete* - Is called to explicitly state that the PreRender phase is completed.
SaveStateComplete* - In this event, the current state of the control is completely saved to the ViewState.
Unload – This event is typically used for closing files and database connections. At times, it is also used for logging some wrap-up tasks.
The events marked with * have been introduced in ASP.NET 2.0.
You have created an ASP.NET Application. How will you run it?
With ASP.NET 2.0, Visual Studio comes with an inbuilt ASP.NET Development Server to test your pages. It functions as a local Web server. The only limitation is that remote machines cannot access pages running on this local server. The second option is to deploy a Web application to a computer running IIS version 5 or 6 or 7.


Explain the AutoPostBack feature in ASP.NET?
AutoPostBack allows a control to automatically postback when an event is fired. For eg: If we have a Button control and want the event to be posted to the server for processing, we can set AutoPostBack = True on the button.

How do you disable AutoPostBack?
Hence the AutoPostBack can be disabled on an ASP.NET page by disabling AutoPostBack on all the controls of a page. AutoPostBack is caused by a control on the page.

What are the different code models available in ASP.NET 2.0?
There are 2 code models available in ASP.NET 2.0. One is the single-file page and the other one is the code behind page.
Which base class does the web form inherit from?
Page class in the System.Web.UI namespace.


Which are the new special folders that are introduced in ASP.NET 2.0?
There are seven new folders introduced in ASP.NET 2.0 :
\App_Browsers folder – Holds browser definitions(.brower) files which identify the browser and their capabilities.
\App_Code folder – Contains source code (.cs, .vb) files which are automatically compiled when placed in this folder. Additionally placing web service files generates a proxy class(out of .wsdl) and a typed dataset (out of .xsd).
\App_Data folder – Contains data store files like .mdf (Sql Express files), .mdb, XML files etc. This folder also stores the local db to maintain membership and role information.
\App_GlobalResources folder – Contains assembly resource files (.resx) which when placed in this folder are compiled automatically. In earlier versions, we were required to manually use the resgen.exe tool to compile resource files. These files can be accessed globally in the application.
\App_LocalResources folder – Contains assembly resource files (.resx) which can be used by a specific page or control.
\App_Themes folder – This folder contains .css and .skin files that define the appearance of web pages and controls.
\App_WebReferences folder – Replaces the previously used Web References folder. This folder contains the .disco, .wsdl, .xsd files that get generated when accessing remote web services.


Explain the ViewState in ASP.NET?
Http is a stateless protocol. Hence the state of controls is not saved between postbacks. Viewstate is the means of storing the state of server side controls between postbacks. The information is stored in HTML hidden fields. In other words, it is a snapshot of the contents of a page.
You can disable viewstate by a control by setting the EnableViewState property to false.

What does the EnableViewState property signify?
EnableViewState saves the state of an object in a page between postbacks. Objects are saved in a Base64 encoded string. If you do not need to store the page, turn it off as it adds to the page size.
There is an excellent
article by Peter Bromberg to understand Viewstate in depth.

Explain the ASP.NET Page Directives?
Page directives configure the runtime environment that will execute the page. The complete list of directives is as follows:
@ Assembly - Links an assembly to the current page or user control declaratively.
@ Control - Defines control-specific attributes used by the ASP.NET page parser and compiler and can be included only in .ascx files (user controls).
@ Implements - Indicates that a page or user control implements a specified .NET Framework interface declaratively.
@ Import - Imports a namespace into a page or user control explicitly.
@ Master - Identifies a page as a master page and defines attributes used by the ASP.NET page parser and compiler and can be included only in .master files.
@ MasterType - Defines the class or virtual path used to type the Master property of a page.
@ OutputCache - Controls the output caching policies of a page or user control declaratively.
@ Page - Defines page-specific attributes used by the ASP.NET page parser and compiler and can be included only in .aspx files.
@ PreviousPageType - Creates a strongly typed reference to the source page from the target of a cross-page posting.
@ Reference - Links a page, user control, or COM control to the current page or user control declaratively.
@ Register - Associates aliases with namespaces and classes, which allow user controls and custom server controls to be rendered when included in a requested page or user control.
This list has been taken from
here.

Explain the Validation Controls used in ASP.NET 2.0?
Validation controls allows you to validate a control against a set of rules. There are 6 different validation controls used in ASP.NET 2.0.
RequiredFieldValidator – Checks if the control is not empty when the form is submitted.
CompareValidator – Compares the value of one control to another using a comparison operator (equal, less than, greater than etc).
RangeValidator – Checks whether a value falls within a given range of number, date or string.
RegularExpressionValidator – Confirms that the value of a control matches a pattern defined by a regular expression. Eg: Email validation.
CustomValidator – Calls your own custom validation logic to perform validations that cannot be handled by the built in validators.
ValidationSummary – Show a summary of errors raised by each control on the page on a specific spot or in a message box.
How do you indentify that the page is post back?
By checking the IsPostBack property. If IsPostBack is True, the page has been posted back.


What are Master Pages?
Master pages is a template that is used to create web pages with a consistent layout throughout your application. Master Pages contains content placeholders to hold page specific content. When a page is requested, the contents of a Master page are merged with the content page, thereby giving a consistent layout.


How is a Master Page different from an ASP.NET page?
The MasterPage has a @Master top directive and contains ContentPlaceHolder server controls. It is quiet similar to an ASP.NET page.

How do you attach an exisiting page to a Master page?
By using the MasterPageFile attribute in the @Page directive and removing some markup.

How do you set the title of an ASP.NET page that is attached to a Master Page?
By using the Title property of the @Page directive in the content page. Eg:
OpenTag @Page MasterPageFile="Sample.master" Title="I hold content" % CloseTag

What is a nested master page? How do you create them?
A Nested master page is a master page associated with another master page. To create a nested master page, set the MasterPageFile attribute of the @Master directive to the name of the .master file of the base master page.

What are Themes?
Themes are a collection of CSS files, .skin files, and images. They are text based style definitions and are very similar to CSS, in that they provide a common look and feel throughout the website.

What are skins?
A theme contains one or more skin files. A skin is simply a text file with a .skin extension and contains definition of styles applied to server controls in an ASP.NET page. For eg:

(asp:button runat="server" BackColor="blue" BorderColor="Gray" Font-Bold ="true" ForeColor="white"/ )

Defines a skin that will be applied to all buttons throughout to give it a consistent look and feel.


What is the difference between Skins and Css files?
Css is applied to HTML controls whereas
skins are applied to server controls.

What is a User Control?
User controls are reusable controls, similar to web pages. They cannot be accessed directly.


Explain briefly the steps in creating a user control?
· Create a file with .ascx extension and place the @Control directive at top of the page.
· Included the user control in a Web Forms page using a @Register directive

What is a Custom Control?
Custom controls are compiled components that run on the server and that encapsulate user-interface and other related functionality into reusable packages. They can include all the design-time features of standard ASP.NET server controls, including full support for Visual Studio design features such as the Properties window, the visual designer, and the Toolbox.

What are the differences between user and custom controls?
User controls are easier to create in comparison to custom controls, however user controls can be less convenient to use in advanced scenarios.
User controls have limited support for consumers who use a visual design tool whereas custom controls have full visual design tool support for consumers.
A separate copy of the user control is required in each application that uses it whereas only a single copy of the custom control is required, in the global assembly cache, which makes maintenance easier.
A user control cannot be added to the Toolbox in Visual Studio whereas custom controls can be added to the Toolbox in Visual Studio.
User controls are good for static layout whereas custom controls are good for dynamic layout.

Where do you store your connection string information?
The connection string can be stored in configuration files (web.config).

What is the difference between ‘Web.config’ and ‘Machine.config’?
Web.config files are used to apply configuration settings to a particular web application whereas machine.config file is used to apply configuration settings for all the websites on a web server.
Web.config files are located in the application's root directory or inside a folder situated in a lower hierarchy. The machine.config is located in the Windows directory Microsoft.Net\Framework\Version\CONFIG.
There can be multiple web.config files in an application nested at different hierarchies. However there can be only one machine.config file on a web server.

What is the difference between Server.Transfer and Response.Redirect?
Response.Redirect involves a roundtrip to the server whereas Server.Transfer conserves server resources by avoiding the roundtrip. It just changes the focus of the webserver to a different page and transfers the page processing to a different page.
Response.Redirect can be used for both .aspx and html pages whereas Server.Transfer can be used only for .aspx pages.
Response.Redirect can be used to redirect a user to an external websites.
Server.Transfer can be used only on sites running on the same server. You cannot use Server.Transfer to redirect the user to a page running on a different server.
Response.Redirect changes the url in the browser. So they can be bookmarked. Whereas Server.Transfer retains the original url in the browser. It just replaces the contents of the previous page with the new one.

What method do you use to explicitly kill a users session?
Session.Abandon().


What is a webservice?
Web Services are applications delivered as a service on the Web. Web services allow for programmatic access of business logic over the Web. Web services typically rely on XML-based protocols, messages, and interface descriptions for communication and access. Web services are designed to be used by other programs or applications rather than directly by end user. Programs invoking a Web service are called clients. SOAP over HTTP is the most commonly used protocol for invoking Web services.



Jul 2, 2008

How to check whether the SP exist and DROP the SP

-- Checks the sys objects for the existence of SP and drops it.
IF EXISTS (SELECT 1 FROM sys.objects
WHERE object_id = OBJECT_ID (N'[dbo].[SP_Name]')
AND
type in (N'P', N'PC'))
BEGIN
DROP PROCEDURE [dbo].[SP_Name]

END

Jun 19, 2008

State Management in asp.net 2.0

State Management Techniques in ASP.NET
This article discusses various options for state management for web applications developed using ASP.NET. Generally, web applications are based on stateless HTTP protocol which does not retain any information about user requests. In typical client and server communication using HTTP protocol, page is created each time the page is requested.Developer is forced to implement various state management techniques when developing applications which provide customized content and which "remembers" the user.
Here we are here with various options for ASP.NET developer to implement state management techniques in their applications.
Broadly, we can classify state management techniques as client side state management or server side state management. Each technique has its own pros and cons. Let's start with exploring client side state management options.

Client side State management Options:
ASP.NET provides various client side state management options like Cookies, QueryStrings (URL), Hidden fields, View State and Control state (ASP.NET 2.0). Let's discuss each of client side state management options.
Bandwidth should be considered while implementing client side state management options because they involve in each roundtrip to server. Example: Cookies are exchanged between client and server for each page request.

Cookie:
A cookie is a small piece of text stored on user's computer. Usually, information is stored as name-value pairs. Cookies are used by websites to keep track of visitors. Every time a user visits a website, cookies are retrieved from user machine and help identify the user. Let's see an example which makes use of cookies to customize web page.
if (Request.Cookies["UserId"] != null)
lbMessage.text = "Dear" + Request.Cookies["UserId"].Value + ", Welcome to our website!";
else
lbMessage.text = "Guest,welcome to our website!";

If you want to store client's information use the below code
Response.Cookies["UserId"].Value=username;
Advantages:
Simplicity
Disadvantages:
Cookies can be disabled on user browsers
Cookies are transmitted for each HTTP request/response causing overhead on bandwidth
Inappropriate for sensitive data

Hidden fields:
Hidden fields are used to store data at the page level. As its name says, these fields are not rendered by the browser. It's just like a standard control for which you can set its properties. Whenever a page is submitted to server, hidden fields values are also posted to server along with other controls on the page. Now that all the asp.net web controls have built in state management in the form of view state and new feature in asp.net 2.0 control state, hidden fields functionality seems to be redundant. We can still use it to store insignificant data. We can use hidden fields in ASP.NET pages using following syntax
protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;

//to assign a value to Hidden field
Hidden1.Value="Create hidden fields";
//to retrieve a value
string str=Hidden1.Value;
Advantages:
Simple to implement for a page specific data
Can store small amount of data so they take less size.
Disadvantages:
Inappropriate for sensitive data
Hidden field values can be intercepted(clearly visible) when passed over a network

View State:
View State can be used to store state information for a single user. View State is a built in feature in web controls to persist data between page post backs. You can set View State on/off for each control using EnableViewState property. By default, EnableViewState property will be set to true. View state mechanism poses performance overhead. View state information of all the controls on the page will be submitted to server on each post back. To reduce performance penalty, disable View State for all the controls for which you don't need state. (Data grid usually doesn't need to maintain state). You can also disable View State for the entire page by adding EnableViewState=false to @page directive.
View state data is encoded as binary Base64 - encoded which add approximately 30% overhead. Care must be taken to ensure view state for a page is smaller in size. View State can be used using following syntax in an ASP.NET web page.
// Add item to ViewState
ViewState["myviewstate"] = myValue;

//Reading items from ViewStateResponse.Write(ViewState["myviewstate"]);
Advantages:
Simple for page level data
Encrypted
Can be set at the control level
Disadvantages:
Overhead in encoding View State values
Makes a page heavy

Query strings:


Query strings are usually used to send information from one page to another page. They are passed along with URL in clear text. Now that cross page posting feature is back in asp.net 2.0, Query strings seem to be redundant. Most browsers impose a limit of 255 characters on URL length. We can only pass smaller amounts of data using query strings. Since Query strings are sent in clear text, we can also encrypt query values. Also, keep in mind that characters that are not valid in a URL must be encoded using Server.UrlEncode.
Let's assume that we have a Data Grid with a list of products, and a hyperlink in the grid that goes to a product detail page, it would be an ideal use of the Query String to include the product ID in the Query String of the link to the product details page (for example, productdetails.aspx?productid=4).
When product details page is being requested, the product information can be obtained by using the following codes:
string productid;productid=Request.Params["productid"];
Advantages:
Simple to Implement
Disadvantages:
Human Readable
Client browser limit on URL length
Cross paging functionality makes it redundant
Easily modified by end user

Control State:


Control State is new mechanism in ASP.NET 2.0 which addresses some of the shortcomings of View State. Control state can be used to store critical, private information across post backs. Control state is another type of state container reserved for controls to maintain their core behavioral functionality whereas View State only contains state to maintain control's contents (UI). Control State shares same memory data structures with View State. Control State can be propagated even though the View State for the control is disabled.
For example, new control Grid View in ASP.NET 2.0 makes effective use of control state to maintain the state needed for its core behavior across post backs. Grid View is in no way affected when we disable View State for the Grid View or entire page

Server Side State management:


As name implies, state information will be maintained on the server. Application, Session, Cache and Database are different mechanisms for storing state on the server.
Care must be taken to conserve server resources. For a high traffic web site with large number of concurrent users, usageof sessions object for state management can create load on server causing performance degradation

Application object:
Application object is used to store data which is visible across entire application and shared across multiple user sessions. Data which needs to be persisted for entire life of application should be stored in application object.
In classic ASP, application object is used to store connection strings. It's a great place to store data which changes infrequently. We should write to application variable only in application_Onstart event (global.asax) or application.lock event to avoid data conflicts. Below code sample gives idea
Application.Lock();
Application["mydata"]="mydata";
Application.UnLock();

Session object:



Session object is used to store state specific information per client basis. It is specific to particular user. Session data persists for the duration of user session you can store session's data on web server in different ways. Session state can be configured using the section in the application's web.config file.
Configuration information: cookieless = <"true" "false"> timeout = sqlconnectionstring= server = port =


Mode:This setting supports three options. They are InProc, SQLServer, and State ServerCookie less:
This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less one.


Timeout:
This indicates the Session timeout vale in minutes. This is the duration for which a user's session is active. Note that the session timeout is a sliding value; Default session timeout value is 20 minutesSqlConnectionString:
This identifies the database connection string that names the database used for mode SQLServer. Server:
In the out-of-process mode State Server, it names the server that is running the required Windows NT service: aspnet_state.
Port:This identifies the port number that corresponds to the server setting for mode State Server. Note that a port is an unsigned integer that uniquely identifies a process running over a network.
You can disable session for a page using EnableSessionState attribute. You can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application.
Session state in ASP.NET can be configured in different ways based on various parameters including scalability, maintainability and availability
In process mode (in-memory)- State information is stored in memory of web server
Out-of-process mode- session state is held in a process called aspnet_state.exe that runs as a windows service.
Database mode session state is maintained on a SQL Server database.
In process mode:This mode is useful for small applications which can be hosted on a single server. This model is most common and default method to store session specific information. Session data is stored in memory of local web server
Configuration information:
Advantages:
Fastest mode
Simple configuration
Disadvantages:
Session data will be lost if the worker process or application domain recycles
Not ideal for web gardens and web farms


Out-of-process Session mode (state server mode):
This mode is ideal for scalable and highly available applications. Session state is held in a process called aspnet_state.exe that runs as a windows service which listens on TCP port 42424 by default. You can invoke state service using services MMC snap-in or by running following net command from command line.

Net start aspnet_state
Configuration information:
Advantages:
Supports web farm and web garden configuration
Session data is persisted across application domain recycles. This is achieved by using separate worker process for maintaining state
Disadvantages:
Out-of-process mode provides slower access compared to In process
Requires serializing data


SQL-Backed Session state:

ASP.NET sessions can also be stored in a SQL Server database. Storing sessions in SQL Server offers resilience that can serve sessions to a large web farm that persists across IIS restarts.SQL based Session state is configured with aspnet_regsql.exe. This utility is located in .NET Framework's installed directory C:\\microsoft.net\framework\. Running this utility will create a database which will manage the session state.
Configuration Information:

Advantages:
Supports web farm and web garden configuration
Session state is persisted across application domain recycles and even IIS restarts when session is maintained on different server.
Disadvantages:
Requires serialization of objects
Choosing between client side and Server side management techniques is driven by various factors including available server resources, scalability and performance. We have to leverage both client side and server side state management options to build scalable applications.
When leveraging client side state options, ensure that little amount of insignificant information is exchanged between page requests.
Various parameters should be evaluated when leveraging server side state options including size of application, reliability and robustness. Smaller the application, In process is the better choice. We should account in the overheads involved in serializing and deserializing objects when using State Server and Database based session state. Application state should be used religiously.

Jun 18, 2008

Joins With examples

joins:
1)These are used to retrieve the data from more than one table.
2)To retrieve the data from more than one table the datatypes of fields which related to different tables need not be same while using the joins
Types of joins:
1):Inner Join
2):Cross Join
3)OuterJoin
a)Left Outer Join
b)Right Outer Join
c)Full Outer Join
4)Natural Join
5)Equi Join
Examples and Description:
1:Emp
EmployeeID EmployeeName 1 Ramesh2 Sukumar3 Ravi 4 Kalyani
2.Products:
ProductID EmployeeID Productname1 1 2 Pen12 3 Pencil1 2 3 Eraser1 3 6 Book
1):Inner Join:This join returns all the rows from the both the tables where there is a match.The result set consists of only matched rows.
Syntax:
select E. Employeeid,E.EmployeeName,P.ProductName from Employees E inner join Products on E.EmployeeID=P.EmployeeID
Result:
1) EmployeeID EmployeeName Productname 2 Sukumar Pen3 Ravi Pencil 3 Ravi Eraser
2)Cross Join:Cross join is nothing but retrieving the data from more than one table with out using the condition.
Here two cases are there:
a)select E.EmployeeID,E.EmployeeName,P.Productname from Employees E,Products P
Note:(here we are using the cross join defaultly.Means we have not mentioned the any condition here.)
b)select E.EmployeeID,E.EmployeeName,P.Productname from Employees E cross join Products P
Note:this is the syantax of cross join..both queries(a &b)returns the same result) only the difference is Synatx but the o/p is same.
3)Outer Join:In outer join the resulting table may have empty columns.
a)Left Outer Join:Here left means first table.it reurns all the rows from the first table even though it does not have the matchs in Second table.But it returns only the matched rows from the second table.
Syntax:
select E. Employeeid,E.EmployeeName,P.ProductName from Employees E left join Products on E.EmployeeID=P.EmployeeID
Result:
1) EmployeeID EmployeeName Productname 2 Sukumar Pen3 Ravi Pencil 3 Ravi Eraser
1 Ramesh null
4 Kalyani null
a)Right Outer Join:Here Right means Second table.it returns all the rows from the second table even though it does not have the matchs in First table.But it returns only the matched rows from the First table.
Syntax:
select E. Employeeid,E.EmployeeName,P.ProductName from Employees E right join Products on E.EmployeeID=P.EmployeeID
Result:
1) EmployeeID EmployeeName Productname 2 Sukumar Pen3 Ravi Pencil 3 Ravi Eraser
6 null Book
5)Natural JOIN:it eliminates the duplicate values from the output.
6)Equi JOIN:An inner join is called equi-join when all the columns are selected with a *, or natural join otherwise

VS 2005 Keyboard Shortcuts

VS 2005 Keyboard Shortcuts
Shortcut (memorize)
Function (memorize)

F5---------------->Debug.Start
Shift + F5--------> Debug.StopDebugging
CTRL + F5---------> Debug.StartWithoutDebugging
F9----------------> Debug.ToggleBreakpoint
CTRL + ALT + V, T--> Debug.This
CTRL + ALT + H ----> Debug.Threads
F10 ---------------> Debug.StepOver
CTRL + F10 --------> Debug.RunToCursor
F11 ---------------> Debug.StepInto
Shift + F4 --------> View.PropertyPages
Shift + F11--------> Debug.StepOut
CTRL + ALT + C-----> View.ClassView
CTRL + ALT + L ----> View.SolutionExplorer
CTRL + ALT + K ----> View.TaskList
CTRL + ALT + O ----> View.Output
CTRL + ALT + B ----> Debug.Breakpoints
CTRL + ALT + C ----> Debug.CallStack
CTRL + ALT + I ----> Debug.Immediate C
TRL + ALT + E ----> Debug.Exceptions
CTRL + ALT + X ----> View.Toolbox
CTRL + ALT + V, L--> Debug.Locals
CTRL + Shift + B---> Build.BuildSolution
CTRL + F7 ---------> Build.Compile
CTRL + F12---------> Edit.GoToDeclaration
F12 ---------------> Edit.GoToDefinition
CTRL + - --------> View.NavigateBackward
CTRL + Shift + - -> View.NavigateForward
ALT + Shift + Enter -> View.FullScreen
CTRL + K, CTRL + U --> Edit.UncommentSelection
CTRL + K, CTRL + C --> Edit.CommentSelection
Shift + Tab ---------> Edit.TabLeft
CTRL + L -----------> Edit.LineCut
CTRL + Shift + L ----> Edit.lineDelete
CTRL + ] ------------> Edit.GoToBrace
CTRL + Shift + ] ----> Edit.GoToBraceExtend
CTRL + M, CTRL + M --> Edit.ToggleOutliningExpansion
CTRL + K, CTRL + K --> Edit.ToggleBookmark
CTRL + F ------------> Edit.Find
CTRL + Shift + F -----> Edit.FindInFiles
F7 ------------------> View.ViewCode
Shift + F7 ----------> View.ViewDesigner

How to Implement themes to GridView in asp.net2.0

Introduction:
The theme of this article is Themes. I will show you that what Themes are used for and how you can make you own Themes quickly and easily. This is a multi series article so stay tuned for the rest of the series. What's up with Themes? Hey! we got CSS (Cascading Style Sheets) so why do we need Themes? The thing about CSS is that it only exposes some fixed style properties which we can use. If we want to change some property like AlternatingItemStyle of the GridView control we will not be able to do this by using simple CSS. Themes allow you to change the control properties. This mean you can change most of the properties exposed by any server control in ASP.NET 2.0.

Gettting Started With Themes: Let's get started with Themes. The first thing that you need to do is to add a skin file. Once you try to add a new skin file ASP.NET will make a folder called App_Themes in which all Themes will be placed. After the App_Themes folder has been created you can simply add .skin files inside the App_Themes folder. You can name the Theme files according to their action. Like if you are adding a Theme which makes the appearance of your page orange you can name is [YourSideName]_Orange_Theme. You can name it anything you want from orange Theme to "Yellow Banana" Theme.

What is in that Skin?
Skin files contains the definition of the server controls on which the Themes will be applied. Here is my Skin file called "Red" whose purpose is to make the GridView red.

As, you might have already noticed that the GridView definition does not contain the ID attribute. That is because this Theme is applied to all the GridViews on the page. There are couple of ways that you can apply different Themes for the same server control.

Applying Themes: There are various ways to apply the Theme to the page. The simplest one of them is to use the Page directive to apply the Theme to the current page.
The above will apply the Theme to the current page. If you wish to apply the same Theme to all the pages of your website then it is a better idea to define the Themes in the configuration file.
Eg:




You can also apply Themes dynamically using the Page.Theme property. The thing to remember about applying the Themes programmatically is that you can only apply it inside the Page_PreInit event.
Check out the code below which applies the Theme at runtime. protected void Page_PreInit(object sender, EventArgs e)
{
Page.Theme = "Green";
}

One thing that you need to remember is that when you set the Theme at different stages the Theme that is set dynamically takes precedence over the Page directive and Web.config. This means that if you have define your Theme to be "Blue" in Web.config and "Green" is Page directive and "Red" dynamically then the Theme set for the page will be set "Red". There is much more to cover in Themes which will be covered in later articles.
Reference: GridViewGuy



Jun 17, 2008

Difference between out and ref parameters in C#.net


C# Imp. Basics - Ref and Out parameters

Well, I am still learning .net, so please excuse me for some confusing words.
Sometimes there is a confusion whether to pass the parameters to a method byreference (ref keyword) or using out keyword. As, both keywords are sometimes confused to be used to get the multiple return values from the target method.
1. When to use ref:
the parameters that are needed to be changed by the target method and the change in value is required to be visible after the method call returns should be passed byref.first, the key thing to remember is that each parameter passed by ref must be initialized before passing to the target method (which will finally change their values) and the change will be visible after the target method call returns.secondly, it is not mandatory to change the values of any of the parameter recieved as by ref in the target method.---------------------------------------------------------------------------

2. When to use out:
out parameters are used when there is a certain need to return multiple values from a method call.first, its not mandatory to initialize each parameter marked as out in the target method, before calling that method.secondly, each parameter which is marked as out in the target method, must be assigned a value corresponding to its type in all code return paths of the target method implementation (otherwise compile error).---------------------------------------------------------------------------
Hope the readers understand what i have tried to explain. Suggestions and questions are always welcome.
Note: out parameters are not supported in the Visual Basic.Net language
Reference: Essential C# 2.0 by Mark Michaelis

Use of Out and Ref parameter in C#

OUT:

The out keyword causes arguments to be passed by reference. This is like the ref keyword, except that ref requires that the variable be initialized before it is passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword. For example:


Class Sample
{
static void Method(out int i)
{
i = 2;
}
static void Main()
{
int value;
Method(out value);
// value is now 2// We can use this value for further process
}
}

The ref and out keywords are treated differently at run-time, but they are treated the same at compile time. Therefore methods cannot be overloaded if one method takes a ref argument and the other takes an out argument

Example of ref

Class Sample

{

static void Method(ref int i)

{

i = i + 2;

}

static void Main()

{

int value = 2;\\ should be initialized for ref method

Method(ref value);// value is now 4
// We can use this value for further process

}

}

This methods are mainly used when hirarchical function where method A(ref int a) --> calls method B(ref int b) -->calls method C(ref int c)

Here in this case the value got in method c is returned to method B which is returned and got in method A.In this next section we ll discuss about out parameters in SQL2005

Jun 11, 2008

how to select middle rows using ROW_NUMBER() in SQL2005

Here the example describes the ROW_NUMBER() approach to select a set or rows using virtual rownumber
SELECT ID, Row FROM
( SELECT ID, (ROW_NUMBER() OVER (ORDER BY ID))
AS Row FROM TableName) Rows
WHERE Row BETWEEN 10 and 20

The other option is using of CTE

How to select middle rows using CTE in SQL2005

CTE Common Table Expression are used for custom paging in asp.net
Gets the row number from the number of IDs present in the table
WITH ItemCTE AS

(
SELECT *, (ROW_NUMBER() OVER( ORDER BY ID)) as RowID FROM tablename
)

-- each CTE should be followed by an select statement
SELECT * FROM ItemCTE WHERE RowID BETWEEN 11 AND 20

Feb 26, 2008

Microsoft Outlook shotcuts

Here are a list of shortcuts to help you move faster in Microsoft Outlook:
Alt + . (period) Open the Address Book with the To field selected
Alt + A Open the Action drop-down menu
Alt + B Open the Address Book with the BCC field selected
Alt + C Select message recipients for CC field
Alt + D Switch to Daily calendar view
Alt + E Open the Edit drop-down menu
Alt + F Open the File drop-down menu
Alt + G Open the Go drop-down menu
Alt + H Open the Help drop-down menu
Alt + I Open the Find tool bar / Open the Insert drop-down menu
Alt + J Move to the Subject field
Alt + K Check names in the To, CC, or BCC field against the Address Book (cursor must be in the corresponding message header field)
Alt + L Reply All
Alt + M Switch to Monthly calendar view
Alt + N Open the Accounts drop-down menu
Alt + O Open the Format drop-down menu / Switch to Today calendar view
Alt + P Open the Message Options dialog box
Alt + R Reply / Switch to Work Week Calendar view
Alt + S Send
Alt + T Open the Tools drop-down menu
Alt + V Open the View drop-down menu
Alt + W Forward an item / Switch to Weekly calendar view
Alt + Y Switch to Daily calendar view
Ctrl + 1 Go to Mail
Ctrl + 2 Go to Calendar
Ctrl + 3 Go to Contacts
Ctrl + 4 Go to Tasks
Ctrl + 5 Go to Notes
Ctrl + 6 Go to Folder List
Ctrl + 7 Go to Shortcuts
Ctrl + 8 Go to Journal
Ctrl + A Select all
Ctrl + B Bold when editing a rich text message
Ctrl + C Copy
Ctrl + D Delete an item (message, task, contact, etc.)
Ctrl + E Activate the Find drop-down menu / Center Align when editing a rich text message
Ctrl + F Forward
Ctrl + J Open a new Journal Entry from the selected item (message, task, contact, etc.)
Ctrl + K Check names in the To, CC, or BCC field against the Address Book (cursor must be in the corresponding message header field)
Ctrl + M Send/Receive all
Ctrl + O Open
Ctrl + P Print
Ctrl + Q Mark the selected message Read
Ctrl + R Reply
Ctrl + S Save a draft message
Ctrl + T Tab
Ctrl + U Mark the selected message Unread
Ctrl + V Paste
Ctrl + X Cut
Ctrl + Y Go to Folder
Ctrl + Z Undo
Ctrl + Backspace Delete the previous word
Ctrl + End Move to the end
Ctrl + Home Move to the beginning
Ctrl + Shift + A Open a new Appointment
Ctrl + Shift + B Open the Address Book
Ctrl + Shift + C Create a new Contact
Ctrl + Shift + E Open a new folder
Ctrl + Shift + F Open the Advanced Find window
Ctrl + Shift + G Flag message for follow up
Ctrl + Shift + J Open a new Journal Entry
Ctrl + Shift + K Open a new Task
Ctrl + Shift + L Open a new Distribution List
Ctrl + Shift + M Open a new Message
Ctrl + Shift + N Open a new Note
Ctrl + Shift + O Switch to the Outbox
Ctrl + Shift + P Open the New Search Folder window
Ctrl + Shift + Q Open a new Meeting Request
Ctrl + Shift + R Reply All
Ctrl + Shift + S Open a new Discussion
Ctrl + Shift + U Open a new Task Request
Ctrl + Shift + Y Copy a Folder
Shift + Tab Select the previous message header button or field
F1 Open Outlook Help
F3 Activate the Find toolbar
F4 Open the Find window
F7 Spellcheck
F9 Send and receive all
F10 Select File from the Outlook toolbar button
F11 Activate the "Find a contact" dialog box
F12 Save As
Alt + F4 Close the active window

Feb 12, 2008

Importing a Text File into SQL server 2005 programatically using Bulk Insert method

First create a table to which the values from the txt file has to be imported
say we create a table with 2 fields as shown below


create table BULK_INSERTTest
(
LINE_NUM int null,
LINE_DATA VARCHAR(50) null
)


Then using the Bulk Insert command as shown below we can easily import a txt file values
to a table in Sqlserver 2005



BULK INSERT
BULK_INSERTTest
from
'\\ppdys1402\Share\Manual.txt'
WITH
(
FIELDTERMINATOR = '\t',
ROWTERMINATOR = '\n',
FIRSTROW = 2
)

Now view the table using

select *from BULK_INSERTTest

Note:
Here the file that u give should have the access permission to ur account
various constraints like field delimiters , format file , First row etc are there to perform various operations
refer msdn for details

Feb 1, 2008

load an array of strings to a text file (one string value per line) and vice versa

Hi friends this is a simple idea of loading a string values from an array to a text file and re -loading the lines in the text file to a string array and printing it..

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace StringArrayToFileAndwiseversa
{
public class Program
{
static void Main(string[] args)
{
string path = @"E:\Projects\rao.txt";
string[] str = {"rao","ram","raj","sundu"};
//StreamWriter sw = new StreamWriter();
ArrayToTextFile(str,path);
TextFileToArray(path);
}
// To load a array of strings to a text file
public static void ArrayToTextFile(string[] str1, string pathFilename)
{
StreamWriter sw = File.CreateText(pathFilename);
foreach (string str in str1)
{
sw.WriteLine(str);
}
sw.Close();
}
// Extract each line in a text file as an string array element
public static void TextFileToArray(string path)
{
string[] text = new string[10];
int i = 0;
StreamReader sr = File.OpenText(path);
text[i] = sr.ReadLine();
while (text[i] != null)
{
Console.WriteLine(text[i]);
i++;
text[i] = sr.ReadLine();
}
}
}
}

Jan 28, 2008

How to compare 2 arraylist and find the one is the sublist of the other in c#


using System;
using System.Collections.Generic;

list declaration:
List RecipIDList = new List(new int[] { 1,2,3,4, 5, 7 });
List subList = new List(new int[] { 4, 5, 7 });


Function that does actual process:
// to find that the 2nd list is the sublist of the first one

public static string IndexOf(List RecipIDList, List subList)
{
int recipCount = 0;
int j = 0;
while (j < recipcount ="="">

Comparing 2 arrays and finding missing Items

//Gets a list of the items in an array missing from a second array.

using System.Collections;

public ArrayList GetMissingItems(string[] allItems, ArrayList someItems)
{
ArrayList missingItems = new ArrayList();
for (int i=0; i
{
if ( allItems[i].Trim().Length > 0 ) //filter out empty strings
{
if ( !someItems.Contains(allItems[i].Trim()) )
{
missingItems.Add(allItems[i]);
}
}
} return missingItems;
}