Friday, December 23, 2011

Nunit 2.5.2 dose not work with Visual Studio 2010 (i.e. with framework 4.0


Hi All

As we all know Nunit 2.5.2 dose not work with Visual Studio 2010 (i.e. with framework 4.0). By updating appropriate ‘config’ files of Nunit we can make it run for Visual Studio 2010.

Please follow the below steps:

1.    Go to flowing folder : C:\Program Files\NUnit 2.5.2\bin\net-2.0\
2.    Open the file ‘nunit.exe.config’ and/Or  ‘nunit-agent.exe.config’ and update it with the below attributes

Under <configuration> add:
<startup>
  <supportedRuntime version="v4.0.30319" />
</startup>

And under <runtime> add:
<loadFromRemoteSources enabled="true" />

Enjoy J

Thursday, December 22, 2011

ASP.Net DataBound Controls and their Differences

1. GridView
Layouts Has default layout and support custom layout
Events Supported 1. Insert
2. Update
3. Delete
4. Filter
5. Sort
(Renders Multiple records at time)
Additional Information Supports default as well as custom paging. Allows adding custom column and apply custom formatting to columns. Supports Data bound filed, DataControl filed, Command filed and Hyperlink filed.
2. DetailsView
Layouts Has default layout and support custom layout
Events Supported 1. Insert
2. Update
3. Delete
(Renders Single records at a time)
Additional Information Supports default as well as custom paging if underlying data source supports paging. Supports Databound filed, DataControl filed, Command filed and Hyperlink filed.
3. FormView
Layouts Has no default layout and Need to set the custom layout
Events Supported 1. Insert
2. Update
3. Delete
(Renders Single records at a time)
Additional Information Supports default as well as custom paging if underlying data source supports paging. We can also customize the display format of FormView control by using style properties like EditRowStyle, EmptyDataRowStyle, FooterStyle, HeaderStyle, InsertRoStyle and PageStyle
4. Repeater
Layouts The Repeater control dose not have built in rendering of its own, which means we have to provide the layout for the repeater control by creating the Templates
Events Supported Read-only Data Presentation 
Additional Information Repeater control contains Header Template, ItemTemplete and Footer Template. Repeater control dose not support Paging, Insertion,  Selection, Editing, Deleting as this is Read-only data display control
5. DataListView
Layouts Has default layout and support custom layout
Events Supported 1. Insert
2. Update
3. Delete
(Renders Multiple records at a time)
Additional Information DataListView control contains Header Template, Alternate Item Template, ItemTemplete and Footer Template. DataListView dose not support Sorting and Paging but dose support Selection and Editing.
6. ListView
Layouts Has no default layout and Need to set the custom layout
Events Supported 1. Insert
2. Update
3. Delete
4. Filter
5. Sort
(Renders Multiple records at a time)
Additional Information To show the data in the ListView Control we need to use the LayoutTmplete, ItemTempltete.
  

Hope this helps to understand the basic difference between the ASP.Net DataBound Controls

Check If URL Exists in ASP.Net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;

namespace MyHttpHandler
{
public class URLChecker
{
protected bool DoseUrlExits(String UrlToCheck)
{
WebRequest req = WebRequest.Create(UrlToCheck);
WebResponse res;

bool IfUrlExitsFlag = false;
try
{
res = req.GetResponse();
IfUrlExitsFlag = true;
}
catch (Exception)
{
IfUrlExitsFlag = false;
}

return IfUrlExitsFlag;
}
}
}

Tuesday, December 20, 2011

Forms Authentication Configuration

Forms Authentication Configuration

The default attribute values for forms authentication are shown in the following configuration-file fragment.

The default attribute values are described below:

1. loginUrl points to your application's custom logon page. You should place the logon page in a folder that requires Secure Sockets Layer (SSL). This helps ensure the integrity of the credentials when they are passed from the browser to the Web server.
2. protection is set to All to specify privacy and integrity for the forms authentication ticket. This causes the authentication ticket to be encrypted using the algorithm specified on the machineKey element, and to be signed using the hashing algorithm that is also specified on the machineKey element.
3. timeout is used to specify a limited lifetime for the forms authentication session. The default value is 30 minutes. If a persistent forms authentication cookie is issued, the timeout attribute is also used to set the lifetime of the persistent cookie.
4. name and path are set to the values defined in the application's configuration file.
5. requireSSL is set to false. This configuration means that authentication cookies can be transmitted over channels that are not SSL-encrypted. If you are concerned about session hijacking, you should consider setting requireSSL to true.
6. slidingExpiration is set to true to enforce a sliding session lifetime. This means that the session timeout is periodically reset as long as a user stays active on the site.
7. defaultUrl is set to the Default.aspx page for the application.
8. cookieless is set to UseDeviceProfile to specify that the application use cookies for all browsers that support cookies. If a browser that does not support cookies accesses the site, then forms authentication packages the authentication ticket on the URL.
8. enableCrossAppRedirects is set to false to indicate that forms authentication does not support automatic processing of tickets that are passed between applications on the query string or as part of a form POST.

Original Source : http://msdn.microsoft.com/en-us/library/ff647070.aspx

Forms Authentication - Creating the Forms Authentication Cookie

We can explicitly create the Authentication Cookie in Forms Authentication mode. using below code.

E.g.

protected void LoginUser_Authenticate(object sender, AuthenticateEventArgs e)
{
if (Membership.ValidateUser(LoginUser.UserName, LoginUser.Password))
{
if (Request.QueryString["ReturnUrl"] != null)
{
FormsAuthentication.RedirectFromLoginPage(LoginUser.UserName,false);
}
else
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
LoginUser.UserName,
DateTime.Now,
DateTime.Now.AddMinutes(30), // value of time out property
false, // Value of IsPersistent property
String.Empty,
FormsAuthentication.FormsCookiePath);

string encryptedTicket = FormsAuthentication.Encrypt(ticket);

HttpCookie authCookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
encryptedTicket);

Response.Cookies.Add(authCookie);

Response.Redirect("~/Default.aspx", false);
}

}
else
{
e.Authenticated = false;
}
}

Forms Authentication - Passing logged in user details to current context

We can set the Logged in user details to current context using Application_AuthenticateRequest function in Global.asax file.

E.g.

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
// look if any security information exists for this request
if (HttpContext.Current.User != null)
{
// see if this user is authenticated, any authenticated cookie (ticket) exists for this user
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
// see if the authentication is done using FormsAuthentication
if (HttpContext.Current.User.Identity is FormsIdentity)
{
// Get the roles stored for this request from the ticket
// get the identity of the user
FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;
// get the forms authetication ticket of the user
FormsAuthenticationTicket ticket = identity.Ticket;
// get the roles stored as UserData into the ticket
string[] roles = ticket.UserData.Split(',');
// create generic principal and assign it to the current request
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);
}
}
}
}

Check Session for expiry in Gloab.asax

One way to check, if session is expired or not is checking for cookies created in current context when session was created. We can check this in Session_Start function in Global.asax file.

E.g.

void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
HttpContext context = HttpContext.Current;
HttpCookieCollection cookies = context.Request.Cookies;

if (cookies["starttime"] == null)
{
HttpCookie kookie = new HttpCookie("starttime", DateTime.Now.ToString());
kookie.Path = "/";
context.Response.Cookies.Add(kookie);
}
else
{
FormsAuthentication.SignOut();
context.Response.Redirect("Expired.aspx", false);
}
}

Read Connection String from Web.Config

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Demo
{
public class ApplicationGenral
{
internal string ConnectionStr()
{
System.Configuration.Configuration rootWebConfig =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/DemoApp");
System.Configuration.ConnectionStringSettings connString;
if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
connString = rootWebConfig.ConnectionStrings.ConnectionStrings["AuthDemo"];
if (connString != null)
return connString.ConnectionString;
else
return "";
}
else
{
return "";
}
}
}
}

Sunday, May 29, 2011

Self Join and when do you use it

Self Join and when do you use it

Use the script below to create Employee Table and populate it with some sample data. We will be using Employee Table to understand Self Join.

CREATE TABLE EMPLOYEE (
[EMP_ID] INT PRIMARY KEY,
[NAME] NVARCHAR(50),
[RO_ID] INT
)
GO
INSERT INTO EMPLOYEE VALUES(101,'Amol',102)
INSERT INTO EMPLOYEE VALUES(102,'Amit',104)
INSERT INTO EMPLOYEE VALUES(103,'Swati',102)
INSERT INTO EMPLOYEE VALUES(104,'Chetan',103)
INSERT INTO EMPLOYEE VALUES(105,'Rakesh',NULL)
INSERT INTO EMPLOYEE VALUES(106,'Sree',103)
GO

We use Self Join, when we have a table that references itself. For example, In the Employee Table under RO_ID column points to EMP_ID column. This is the right scenario where we can use Self Join. Now suppose you want to write a query that will give you the list of all Employee Names and their respective Reporting Officer’s Names. In order to achieve this you can use Self Join.

Employee Table




The query below is an example of Self Join. Both E1 and E2 refer to the same Employee Table. In this query we are joining the Employee Table with itself.

SELECT E1.[NAME],E2.[NAME] AS [RO NAME]
FROM EMPLOYEE E1
INNER JOIN EMPLOYEE E2
ON E2.EMP_ID =E1.RO_ID

If we run the above query we only get 5 rows out of the 6 rows as shown in Results1 below.



Output 1

This is because Rakesh does not have a Manager. RO_ID column for Rakesh is NULL. If we want to get all the rows then we can use LEFT OUTER JOIN as shown below. For a list of all different types of JOINS in SQL Server, please


SELECT E1.[NAME],E2.[NAME] AS [RO NAME]
FROM EMPLOYEE E1
LEFT OUTER JOIN EMPLOYEE E2
ON E2.EMP_ID =E1.RO_ID
If we execute the above query we get all the rows, including the row that has a null value in the RO_ID column. The results are shown below. The RO NAME for 2nd record is NULL as Rakesh does not have a Manager.

Monday, April 25, 2011

Import Bulk Data to SQL Server Using SqlBulkCopy

Import Bulk Data to SQL Server Using SqlBulkCopy

using System;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Data.Sql;
using System.Data.SqlClient;

Public class bulkcopyTest
{

Public void bulkcopyTestEG(DataTable dtEmport)
{

try
{
OleDbConnection Con = CreateConnection("Connection_String");

//Open bulkcopy connection.
using (SqlBulkCopy bulkcopy = new SqlBulkCopy(Con))
{
//Set destination table name
//to table previously created.
bulkcopy.DestinationTableName = "Bulk_Copy_Test";

try
{
bulkcopy.WriteToServer(dtEmport);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

}
}
}
}

Import Data from Excel in SQL server.

Import Data from Excel in SQL server.

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.ComponentModel;
namespace ExcelImport
{
public class ExcelBase : Component, IDisposable
{
///
/// Creates a NEW connection. If this method is called directly, this
/// class will not check if it is closed.
/// To get a handled connection, use the property.
///

///
public OleDbConnection CreateConnection()
{
return new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myOldExcelFile.xls;Extended Properties="Excel 12.0;HDR=YES");
}
public DataTable GetDataFromExcel()
{
try
{
OleDbConnection Conn = CreateConnection();

DataTable dt = new DataTable();

OleDbDataAdapter DA = new OleDbDataAdapter("Select * From [Sheet1$]",Conn);

DA.Fill(dt);

return dt;
}
finally
{
CloseConnection(true);
}
}
}

Friday, March 11, 2011

Copy Pecific Columns(With Data) of One DataTable To Unother DataTable

Copy Pecific Columns(With Data) of One DataTable To Unother DataTable

There are two datatable DT1 And DT2

DT1 Consists of below 5 Coloumns:

1. EmpID
2. EmpName
3. Department
4. Designation
5. Reporting_Office

Now I Want to Copy Only below 3 columns data to DT2

1. EmpID
2. EmpName
3. Department

Code :

// Create Array with required coloumns Name
string[] cols = {"EmpID","EmpName","Designation"};

// Create new Datatable
DataTable DT2 = new DataTable();

// Fill datatable with new colunms data
DT2 = DT1.DefaultView.ToTable("DT2", false, cols);

Fill Array With DataTable in C#.Net

// Create Array to hold the data of DataTable
object[,] DataArray = new object[dt.Rows.Count, dt.Columns.Count];

//Fill DataTable in Array
for (int row = 0; row < dt.Rows.Count; row++)
{
DataRow dr = dt.Rows[row];
for (int col = 0; col < dt.Columns.Count; col++)
{
arr[row, col] = dr[col];
}
}

Export DataTable to Excel in C#.Net

This is one of the fastest way to export data to Excel file from DataTable

You Need to Import below 2 Libraries for this class to work.
1. Microsoft Office 12.0 Object Library
2. Microsoft Excel 12.0 Object Library


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Threading;
using System.IO;

namespace ExportData2Excel
{
class Export2Excel
{

public void export(DataTable dt)
{
//Create Excel Objects
Microsoft.Office.Interop.Excel.Application oExcel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbooks oBooks;
Microsoft.Office.Interop.Excel.Sheets oSheets;
Microsoft.Office.Interop.Excel.Workbook oBook;
Microsoft.Office.Interop.Excel.Worksheet oSheet;

//Create New Excel WorkBook
oExcel.Visible = true;
oExcel.DisplayAlerts = false;
oExcel.Application.SheetsInNewWorkbook = 1;
oBooks = oExcel.Workbooks;

oBook = (Microsoft.Office.Interop.Excel.Workbook)(oExcel.Workbooks.Add(Type.Missing));
oSheets = oBook.Worksheets;
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oSheets.get_Item(1);
oSheet.Name = "FinalData";

// Create Array to hold the data of DataTable
object[,] arr = new object[dt.Rows.Count, dt.Columns.Count];

//Fill DataTable in Array
for (int r = 0; r < dt.Rows.Count; r++)
{
DataRow dr = dt.Rows[r];
for (int c = 0; c < dt.Columns.Count; c++)
{
arr[r, c] = dr[c];
}
}

//Set Excel Range to Paste the Data
Microsoft.Office.Interop.Excel.Range c1 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1, 1];
Microsoft.Office.Interop.Excel.Range c2 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1 + dt.Rows.Count - 1, dt.Columns.Count];
Microsoft.Office.Interop.Excel.Range range = oSheet.get_Range(c1, c2);

//Fill Array in Excel
range.Value2 = arr;

}

}

}

Monday, February 7, 2011

Populate Datagrid Using Datareader in C#.Net

try
{
string SQLstr = "Select * from Employee";

SqlConnection con = new SqlConnection("Connection_String");

//Open Connection
con.Open();

SqlCommand com = new SqlCommand(SQLstr, con);
SqlDataReader read = com.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(read);

// finally bind the data to the grid
dataGridView1.DataSource = dt;

// Close Connection
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error");
}

Populate Datagrid using data adapter in C# .Net

SqlConnection OCon;

try
{
// Create Insert Query

string SQLstr = "Select * from Employee";

OCon = new SqlConnection("Connection_String");

SqlDataAdapter dataAdapter = new SqlDataAdapter(SQLstr, OCon);

// Populate a new data table and bind it to the BindingSource.
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;

dataAdapter.Fill(table);
BindingSource dbBindSource = new BindingSource();
dbBindSource.DataSource = table;

// Resize the DataGridView columns to fit the newly loaded content.
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);

// you can make it grid readonly.
dataGridView1.ReadOnly = true;

// finally bind the data to the grid
dataGridView1.DataSource = dbBindSource;

//ONTCon.CloseConn();

}
catch (Exception ex)
{
// Trough Error
}

Send Mail through outlook using C#

To Send Email Using Outlook you need to add refrence of Outlook to your project



using Outlook = Microsoft.Office.Interop.Outlook;

public class ODA_Genral
{
public void sendemail()
{
try
{
// Create the Outlook application.
Outlook.Application objApp = new Outlook.Application();

// Get the NameSpace and Logon information.
Outlook.NameSpace objNS = oApp.GetNamespace("mapi");

// Log on by using a dialog box to choose the profile.
objNS.Logon(System.Reflection.Missing.Value, System.Reflection.Missing.Value, true, true);

// Create a new mail item.
Outlook.MailItem objMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

// Set the subject.
objMsg.Subject = "Mail Send Using Outlook through C#.net";

// Set HTML Body for you mail.
String HtmlBoday;
HtmlBoday = "Send Mail Through Outlook using C#.Net";

objMsg.HTMLBody = HtmlBoday;

// Add a recipient.
Outlook.Recipients objRecips = (Outlook.Recipients)oMsg.Recipients;

// TODO: Change the recipient in the next line if necessary.
Outlook.Recipient objRecip = (Outlook.Recipient)oRecips.Add("Email ID");
objRecip.Resolve();

// Call Send Method to send the mail.
objMsg.Send();

// Log off from Outlook.
objNS.Logoff();

// Set All Objects to Null.
objRecip = null;
objRecips = null;
objMsg = null;
objNS = null;
objApp = null;
}

// Simple error handling.
catch (Exception ex)
{
Console.WriteLine("{0} Exception Occured. Mail Sending Failed", ex);
}
}
}

Thursday, January 27, 2011

Filter DataTable

Most of them we come across the situation where we need to filter the data from Datatable. Below are the two ways we can achieve this functionality.

1. Filter the Datatable and save the result in Datarow

SqlConnection myConn = new SqlConnection(strConString);
string strSql = "select * from Employee";DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(strSql, myConn);

// Filters the data by "EmployeeID = 143" and returns an array of DataRow
da.Fill(ds);
DataTable dt = ds.Tables[0];
DataRow[] dRow = dt.Select("EmployeeID=’143’");
for (int i = 0; i < dRow.Length; i++)
{
Response.Write("Row " + dRow[i]["Employee_Name"].ToString());
}

2. Create DataView populate it with Datatable and then use Filter Property of Dataview

DataView dtView = ds.Tables["Employee"].DefaultView;
dtView.RowFilter = "EmpployeeID = '143'";

Wednesday, January 12, 2011

Copy DataRows from one DataTables to another

using System;
using System.Data;
using System.Data.SqlClient;

namespace ImportRowFromDataTable
{
class Class1
{
static void Main(string[] args)
{
int tbl_1count;
int tbl_2count;
int i;

// Add code to start application here.
DataTable tbl_1 = new DataTable();
DataTable tbl_2 = new DataTable();

// Change the connection string to your server.
SqlConnection Con = new SqlConnection("Connectionstring");

// Create the DataAdapter.
SqlDataAdapter da = new SqlDataAdapter("Select * from tbl_1", Conn);

// Fill the DataSet with data.
DataSet ds = new DataSet();
da.Fill(ds, "tbl_1");
tbl_1 = ds.Tables["tbl_1"];
tbl_1count = tbl_1.Rows.Count;

// Write the number of rows in the Products table to the screen.
Console.WriteLine("Table tbl_1has " + tbl_1count.ToString() + " Rows.");

// Loop through the five rows, and disply the first column.
for (i = 0; i <= 4; ++i)
{
Console.WriteLine("Row(" + i.ToString() + ") = " + tbl_1.Rows[i][1]);
}

// Use Clone method to copy the table tbl_1 structure.
tbl_2 = tbl_1.Clone();

// Use the ImportRow method to copy from tbl_1's data to its clone.
for (i = 0; i <= 4; ++i)
{
tbl_2.ImportRow(tbl_1.Rows[i]);
}
tbl_2count = tbl_2.Rows.Count;


// Write the number of rows in tbl_2table to the screen.
Console.WriteLine("Table tbl_2 has " +tbl_2count.ToString() + " Rows");

// Loop through the rows of tbl_2, and display.
for (i = 0; i <= tbl_2count - 1; ++i)
{
Console.WriteLine("Row(" + i.ToString() + ") = " + tbl_2.Rows[i][1]);
}

Console.ReadLine();

}
}
}

Copy DataRows form DataTables to another

using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;

namespace ImportRowFromDataTable
{
class Class1
{
static void Main(string[] args)
{
int tbl_1count;
int tbl_2count;
int i;

// Add code to start application here.
DataTable tbl_1 = new DataTable();
DataTable tbl_2 = new DataTable();

// Change the connection string to your server.
SqlConnection Con = new SqlConnection("Connectionstring");

// Create the DataAdapter.
SqlDataAdapter da = new SqlDataAdapter("Select * from tbl_1", Conn);

// Fill the DataSet with data.
DataSet ds = new DataSet();
da.Fill(ds, "tbl_1");
tbl_1 = ds.Tables["tbl_1"];
tbl_1count = tbl_1.Rows.Count;

// Write the number of rows in the Products table to the screen.
Console.WriteLine("Table tbl_1has " + tbl_1count.ToString() + " Rows.");

// Loop through the five rows, and disply the first column.
for (i = 0; i <= 4; ++i)
{
Console.WriteLine("Row(" + i.ToString() + ") = " + tbl_1.Rows[i][1]);
}

// Use Clone method to copy the table tbl_1 structure.
tbl_2 = tbl_1.Clone();

// Use the ImportRow method to copy from tbl_1's data to its clone.
for (i = 0; i <= 4; ++i)
{
tbl_2.ImportRow(tbl_1.Rows[i]);
}
tbl_2count = tbl_2.Rows.Count;


// Write the number of rows in tbl_2table to the screen.
Console.WriteLine("Table tbl_2 has " +tbl_2count.ToString() + " Rows");

// Loop through the rows of tbl_2, and display.
for (i = 0; i <= tbl_2count - 1; ++i)
{
Console.WriteLine("Row(" + i.ToString() + ") = " + tbl_2.Rows[i][1]);
}

Console.ReadLine();

}
}
}

Wednesday, January 5, 2011

Stored Procedure to Create Dynamic PIVOT in SQL

We can create dynamic PIVOT in SQL. Check the below example

CREATE PROCEDURE [dbo].[Trainings]

-- Add the parameters for the stored procedure here

AS
BEGIN

SET NOCOUNT ON;
DECLARE @Columns varchar(8000)
DECLARE @SQL varchar(8000)

--Create PIVOT table fields list in ('', '') format

SET @Columns = substring((select ',['+Training_Name+']' from View_Training group by Training_Name for xml path('')),2,8000)

--PIVOT table query

SET @SQL = 'SELECT * FROM
(Select * from View_Training) CrossTraning
PIVOT
(max(Status) for Training_Name in ('+@Columns+')) pivottable'

EXEC(@sql)
END

CSS TO Display text vertically

To Rotate the text 90 degrees (i.e. Display it vertically) we can use below CSS Class

CSS Class.

.verticaltext
{
font-family:Verdana, Arial; font-size:12px;
writing-mode: tb-rl;
filter: flipH() flipV();
}