Thursday, December 10, 2009

LINQ - Simple examples



LINQ where - operation

int[]array ={1,2,3,4,5,6,7,8};

var between5 = from N in array where N < 5 select N;

foreach(var elements in between5)
{
Response.write(elements);
}

// Transforming the array into ToList

ToList - LINQ

string[] name ={"Senthil","Murugesan","Karthick"};
var Name = from SP in name order by K select K

var namelist=Name.ToList()
foreach(var item in namelist)
{
Response.write(item);
}



// Loading XML document in LINQ

var record = from e in XElement.Load(Server.Mappath("students.xml").Element("Name") select e.Element("Name");
foreach(students in record)
{
Response.write(students);
}

webservice consuming through jQuery - parameter

I have a web service which will check the user name and password against database.I used to send 2 parameters one is user id and password.If both are matched then status will be comes

$.ajax({
type: "POST",
url: "LoginService.asmx/AuthenticateMethod",
data: "{'UserName': '" + $("#TextBox1").val() +"', 'Password': '" + $("#TextBox2").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg)
{
$("#status").html(msg.d);
}
});

Wednesday, December 09, 2009

GridView with ModalPopupextender in C#












onrowdatabound="GridView1_RowDataBound">
















Code behind to send selected index as parameter to webservice to retrieve record
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lk = (LinkButton)e.Row.FindControl("lnk");

lk.Attributes.Add("onclick", "ShowMyModalPopup('"+s+"')");
}
}

Monday, December 07, 2009

Self Code testing - FxCop 1.36

I wanted to test my codes are written correctly what Microsoft's defined.So I prepared a class library for Banking Transaction.Before testing this my BankTransaction.dll

Simply I test my codes against Design Rules,Naming Rules,Interoperability Rules,Performance and Portability Rules.

My codes were

using System;
using System.Collections.Generic;
using System.Text;

namespace SP.MyBankTransaction
{

public class BankTransactionClass
{
private string account_holder_name;
private string account_number;
private double deposit_amount;
private double withdraw_amount;
private double balance_amount;
public string AccountHolderName
{
get { return account_holder_name; }
set { account_holder_name = valu; }
}
public string AccountNumber
{
get { return account_number; }
set { account_number=value; }
}
public double WithdrawAmount
{
get { return withdraw_amount; }
set { withdraw_amount = value; }
}
public double DepositAmount
{
get { return deposit_amount; }
set { deposit_amount =value; }
}

public double BalanceAmount
{
get { return balance_amount; }
set { balance_amount=value; }
}
public double DepositTrasaction(string FromAccount, double AmountToBeDeposited)
{
FromAccount = AccountNumber;
AmountToBeDeposited = DepositAmount;
return BalanceAmount + AmountToBeDeposited;

}
}

}






Resolution were

Correct the spelling of 'Trasaction' in member name 'BankTransactionClass.DepositTrasaction(string, double)' or remove it entirely if it represents any sort of Hungarian notation.

in line 43,Method name has been misspelled,I changed.Notice the "Transaction".
in line 42,Parameters were Pascal-cased word,I changed to camel cased.
in line 16,Compound Word "AccountHolderName" changed as "Accountholder.

My corrected Code is

using System;
using System.Collections.Generic;
using System.Text;

namespace SP.MyBankTransaction
{

public class BankTransactionClass
{
private string account_holder_name="";
private string account_number="";
private double deposit_amount=0.0;
private double withdraw_amount=0.0;
private double balance_amount=0.0;

public string Accountholder
{
get { return account_holder_name; }
set { value = account_holder_name; }
}
public string AccountNumber
{
get { return account_number; }
set { value = account_number; }
}
public double WithdrawAmount
{
get { return withdraw_amount; }
set { value = withdraw_amount; }
}
public double DepositAmount
{
get { return deposit_amount; }
set { value = deposit_amount; }
}

public double BalanceAmount
{
get { return balance_amount; }
set { value = balance_amount; }
}
public double DepositTransaction(string fromAccount, double amountToBeDeposited)
{
fromAccount = AccountNumber;
amountToBeDeposited = DepositAmount;
return BalanceAmount + amountToBeDeposited;

}
}

}

Wednesday, December 02, 2009

Gridview row deleting in C#

Steps to delete a row in Grid view programmatic which bind with real time database table.
1,In Grid view server control must be set to false of AutoGenerateColumns
2,Make Columns tag to list the user defined column header on the asp.net page.
just like the following
  
DataKeyNames="ProductID" SelectedIndex="1"
onselectedindexchanged="GridView1_SelectedIndexChanged"
onrowcommand="GridView1_RowCommand" AutoGenerateColumns="false">








3,Set to DataKeyNames value to Table's primary key like
  
DataKeyNames="ProductID" SelectedIndex="1"
onselectedindexchanged="GridView1_SelectedIndexChanged"
onrowcommand="GridView1_RowCommand" AutoGenerateColumns="false">


An event named "onrowcommand" triggered on the Grid view deletion of the selected row must be deleted from the table.

Here I used the filter CommandName and commandArgument to check whether the deletion link button which attached the GridView clicked.


protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Remove")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];

Database db = DatabaseFactory.CreateDatabase("DatabaseConnectionString");
DbCommand cmd = db.GetSqlStringCommand("DELETE from Products where ProductID='" + row.Cells[1].Text.ToString() + "'");
db.ExecuteNonQuery(cmd);
GridView1.DataSource = ShowProductDetail();
GridView1.DataBind();

}

}


I used Microsoft Enterprise Library 4.1 in my example to deal with database and its related operation.Its based on SQLExpress database.
  



Thursday, November 26, 2009

script test

  



Sunday, November 15, 2009

Convert DataSet into ArrayList in C#

Converting the DataSet into ArrayList is not an big deal anymore.
If you are sure about the number of columns in the DataTable,create the same class members in the Class.

Let assume I have an DataSet contains of the table named "Product" which has three columns called ProductID and Stock.

First step to convert the DataSet into ArrayList is,creating the Class name ProductClass



Database db = DatabaseFactory.CreateDatabase("DatabaseConnectionString");
DbCommand cmd = db.GetSqlStringCommand("Select * from Products");
DataSet ds = db.ExecuteDataSet(cmd);
List proList = new List();

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Products p = new Products();
p.ProductName = ds.Tables[0].Rows[i]["ProductName"].ToString();
p.ProductID = ds.Tables[0].Rows[i]["ProductID"].ToString();
proList.Add(p);

}


Product.cs

public class Products
{
private string _productName;

private string _productid;

public string ProductName
{
get { return _productName; }
set { _productName = value; }


}

public string ProductID
{
get { return _productid; }
set { _productid = value; }

}



}

GridView1.DataSource = proList.ToArray();
GridView1.DataBind();

Wednesday, November 11, 2009

LINQ to SQL Classes tutorial

Step 1:

Add Linq to Sql classes to your application,and make sure you selected the .NET 3.5 as target framework.



Step : 2

Add Server database to solution explorer.After adding Database diagram toggle to find the tables on selected database.



Step :3

Linq to SQL template name will becomes the parent class and retrieve the data from the table as below.



Snippet:

DataClasses2DataContext db2 = new DataClasses2DataContext();
var c = from sp in db.Peoples
select sp;
List li = c.ToList();
GridView1.DataSource = li.ToArray();
GridView1.DataBind();

Monday, November 02, 2009

Basic LINQ in C#

var c = new List left arrow bracket Customers right arrow bracket {
new Customers{Code=20,Name="Murugesan"},
new Customers{Code=21,Name="Pandian"},
new Customers{Code=22,Name="Senthilan"},
new Customers{Code=20,Name="Muthu"},
new Customers{Code=20,Name="Sachin"},
};
var result = from sp in c
select sp;
foreach (var Result in result)
{
Response.Write(Result.Name.ToString());
}


Class implementation

public class Customers
{
private int _code;
private string _name;
public int Code
{
get { return _code; }
set { _code = value; }
}

public string Name
{
get { return _name; }
set { _name = value; }
}
}

Sunday, November 01, 2009

Encrypting-Decrypting the password in C#

Encrypting the password in .NET become ease,DESCryptoServiceProvider enables the developer to encrypt the plain text in to encrypted form.

Code snippet as below :


public static byte[] Encrypt(string txtPassword, SymmetricAlgorithm key)
{
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, key.CreateEncryptor(), CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cStream);
sw.WriteLine(txtPassword);
sw.Close();
cStream.Close();
byte[] buffer = mStream.ToArray();
mStream.Close();
return buffer;
}


Decrypting the encrypted bytes:

public static string Decrypt(byte[] CryptedBytes, SymmetricAlgorithm key)
{
MemoryStream mStream = new MemoryStream(CryptedBytes);
CryptoStream cStream = new CryptoStream(mStream, key.CreateDecryptor(), CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cStream);
string PlainTxt = sr.ReadLine();
sr.Close();
cStream.Close();
mStream.Close();
return PlainTxt;
}

In Database,I used to save these bytes in Password column.While retrieving/Checking the Password,I used the Decrypt the function.So Password column will have encrypted text that easily human can't read or memorize.

For using this code you need to import System.Security.Cryptography class into your application.

Thursday, September 24, 2009

Listing server files

This code snippet for listing all the files under specific folder.
string[] list = Directory.GetFiles(Server.MapPath("~/Images"));
for (int i = 0; i < files.Length; i++){
list [i] = Path.GetFileName(list [i]);
GridView1.DataSource = list;
GridView1.DataBind(); }

Saturday, August 22, 2009

Returning multiple refcursor in Oracle through enterprise library 4.1

I found this simple code snippet for how to retrieve multiple RefCursor values in Oracle through Enterprise Library 4.1

object[] parameters = new object[3];
DataSet ds = new DataSet();
Database db = DatabaseFactory.CreateDatabase();
DBCommandWrapper cw = db.GetStoredProcCommandWrapper("mypackage.mypackagename", parameters);
db.LoadDataSet(cw, ds, new string[] {"RefCur1", "RefCur2", "RefCur3"});

Thursday, August 20, 2009

Exception handling in Enterpirse Library 4.1

After goggling lot very patiently,I find something all irrelevant to my task.
Finally i corrected by watching carefully on my system thrown exceptions.

Add this below line between ConfigSection of tag.

section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling" /

Paste this line somewhere but between configuration tag
exceptionHandling
exceptionPolicies
add name="Global Policy"
exceptionTypes
add name="Exception"
type="System.Exception,
mscorlib, Version=2.0.0.0,
Culture=neutral,
PublicKeyToken=b77a5c561934e089"
postHandlingAction="None"

/add
/exceptionTypes
/add
/exceptionPolicies
/exceptionHandling

My source code for catching the exception is

try
{
int a = 0;
int b = 1;
int result = b / a;
Response.Write(result.ToString());

}
catch (System.Exception ex)
{
bool rethrow = ExceptionPolicy.HandleException(ex, "Global Policy");
Response.Write(rethrow.ToString());

}

Output is "False".So I am strongly believe exceptions were caught by enterprise library : )-

Monday, August 17, 2009

Record retreiving C# using OracleProcedure

Oracle Proc:

create or replace procedure returnAllRecords(cur_allrec out t_cursor)
is
begin
open cur_allrec for SELECT * from Students;
end returnAllRecords


on Button click event write this below code:



OracleConnection Conn = new OracleConnection("Data Source=ORCL; User ID=scott; Password=tiger")
OracleCommand Cmd = new OracleCommand();
Cmd.Connection = Conn;
Cmd.CommandText = "returnAllRecords";
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add("cur_allrec", OracleType.Cursor).Direction = ParameterDirection.Output;
try

{

Conn.Open();

OracleDataReader Reader = Cmd.ExecuteReader();


}

catch (Exception ex)

{

Response.Write(ex.ToString();

}


Conn.Close();

Wednesday, August 12, 2009

Operation Contract's properties

OperationContract Properties
Action
The Action property specifies the action that uniquely identifies this operation. WCF dispatches request messages to methods based on their action.
AsyncPattern
The AsyncPattern property indicates that the operation is implemented or can be called asynchronously using a Begin/End method pair.
HasProtectionLevel
The HasProtectionLevel property indicates whether the ProtectionLevel property has been explicitly set.
IsOneWay
The IsOneWay property indicates that the operation only consists of a single input message. The operation has no associated output message.
IsInitiating
The IsInitiating property specifies whether this operation can be the initial operation in a session.
IsTerminating
The IsTerminating property specifies whether WCF attempts to terminate the current session after the operation completes.
ProtectionLevel
The ProtectionLevel property specifies the message-level security that an operation requires at run time.
ReplyAction
The ReplyAction property specifies the action of the reply message for the operation.

Tuesday, August 04, 2009

Opening popup window in ASP.NET

Opening popup window in ASP.NET is quite simple,but you need to very concern about concatenation on javascript and as well as ASP.NET concatenation.

I spent more time on this silly issue,atlast i rectified.
Here i attach my querystring and its value from the selected dropdown list control.

string result = DropDownList1.SelectedValue.ToString();
string script = "";
Page.RegisterStartupScript("myScript", script);

Working with access database in C#

using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.OleDb;

public partial class _Default : System.Web.UI.Page
{
OleDbConnection Con = null;
OleDbCommand cmd = null;
OleDbDataReader reader;
protected void Page_Load(object sender, EventArgs e)
{


}
protected void btnUpdate_Click(object sender, EventArgs e)
{
Con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + Server.MapPath("iTrack.mdb"));
Con.Open();
string t_date = txtDate.Text;
string t_location = txtLocation.Text;
string t_descrip = txtNotes.Text;
string t_time = txtTime.Text;
cmd = new OleDbCommand("INSERT INTO bills (Transaction_date,Location,Transaction_Description,TTime)values('" + t_date + "','" + t_location + "','" + t_descrip + "','" + t_time + "')", Con);

cmd.ExecuteNonQuery();

Response.Write("Added");
cmd.Dispose();
Con.Close();
cmd = null;
Con = null;

}


protected void btnRetrieve_Click1(object sender, EventArgs e)
{
try
{
Con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + Server.MapPath("iTrack.mdb"));
Con.Open();
cmd = new OleDbCommand("SELECT * from Bills where Awb='"+DropDownList1.SelectedValue.ToString()+"'", Con);
reader = cmd.ExecuteReader();
while (reader.Read())
{
txtDate.Text = reader["Transaction_date"].ToString();
txtLocation.Text = reader["Location"].ToString();
txtNotes.Text = reader["Transaction_Description"].ToString();
txtTime.Text = reader["TTime"].ToString();
plDetails.Visible = true;
}
}
catch (Exception exception)
{
Response.Write("Exception Message " + exception.Message.ToString());
}

finally
{
cmd.Dispose();
cmd = null;
Con.Close();
Con = null;
}

}
}

Saturday, July 04, 2009

How to install PHP on IIS 5.1

I found the extracting the PHP source files into PHP folder in windows XP over PHP installer [Executing .exe file for the ISAPI extension].

Steps to install PHP 5.2.1 in IIS 5.1

Create the folder in C:\PHP.

Extract the compressed format "php-5.2.10-Win32" on the newly created folder.

give the permission for the folder C:\PHP by right click on the folder like you see here..
and do not forget to share the websharing option for the folder.select Share this folder option.



Now the major property setting is how the IIS is going to process the PHP script.
We can achieve this by setting ISAPI Filter as follows.



Now home directory setting for the PHP processes by IIS,Just see next to ISAPI Filter tab.



After completing this process,reset the IIS server by typing "iisreset" in command prompt.

type the script as follows to check IIS process the php scripting.

phpinfo();
?>

save this under C:\Inetpub\wwwroot as First.php

type the http://localhost/First.php

My setting works fine and got output as like this..

Saturday, June 20, 2009

Converting DataSet to array list

public string[] ProductList()
{

ArrayList al = new ArrayList();
string s = "";

Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand("SELECT ProductName from Products");
DataSet ds = db.ExecuteDataSet(cmd);

foreach (DataRow dRow in ds.Tables[0].Rows)
{

al.Add(dRow);
}

foreach (Object row in al)
{
s = s + ((DataRow)row)["ProductName"].ToString() + ",";

}
string rawString = s.TrimEnd(',').ToString();
string[] result = rawString.Split(',');
return result;

}
then you can bind this array to Gridview
Gridview1.DataSource=ProductList();
Gridview1.Bind();

Tuesday, June 16, 2009

MSMQ - Architecture

This will be the simplest understanding diagram of what MSMQ architecture is
********************************************************
Sending Application[Physical]
|
|
|
V
MSMQ [Layer built in topof SQL Server]
|
|
|
V
Receiving Application [Physical]

**********************************************

Sending Application
|
|
|------>Writes Message [Transaction - 1]
|
|
|
|------> Put written message into Queue [Transaction-2]


Sending application prepares a message and puts into Queue.
A Message can be any type of information that receiving application understand.
Receiving Application
Receives the messages and process them.
Notes:
Receiving application and Sending application were not tightly coupled,they can work
without help of other application support

How it was possible ?
Because of built-in layers between connected computers[clients].
Two types of Messages are there,one is Private Message and secondly we have Public
message
Private message :These messages only on locally on particular machine and are not
published on publically.
Public message: These messages will reside on active directory.So applications
running on different servers throughout the network can find the public queues
through active directory.

Monday, June 15, 2009

Exception handling in WCF

This is an simple example for how to manage exception in WCF and their client.
WCF returns system exception and application exception during development time.
But hosting time,these kind of exception will not handled by SOAP protocol.
So SOAP friendly exception details must be implemented on service side using FaultContractAttribute.
Generate the custome exception message must be implemented on a class that start preceding with DataContractAttribute.

WCF Source for Exception handling

[ServiceContract]
public interface IService
{
[OperationContract]
[FaultContractAttribute(typeof(FaultContractExceptionTest))]
string GetData(int value);

}
[DataContractAttribute]
public class FaultContractExceptionTest
{
private string Msg;
public FaultContractExceptionTest(string msg)
{
this.Msg = msg;
}
[DataMember]
public string ErrorMessage
{
get { return this.Msg; }
set { this.Msg = value; }
}
}
________________________________________________________________________

Service Implementation Source
_________________________________________________________________________
public class Service : IService
{
public string GetData(int value)
{

if (value == 152)
{
return "Your authentication code is " + value.ToString();
}
else
{
throw new FaultException(new FaultContractExceptionTest("Check your Pass Number"),"Some Problem");
}}}


Client Implementation - Source code - I written on Button click event
ServiceClient sc = new ServiceClient();
try
{

Response.Write(sc.GetData(Convert.ToInt32(TextBox1.Text)));

}

catch (FaultException msgObj)
{
Response.Write(msgObj.Detail.ErrorMessage);
}

Monday, April 20, 2009

Base64Binary-webservice consuming through PHP

This is an example for how to consume the asp.net webservice method which will return the bytes of array as datatype.

How it will be consumed in PHP client is slightly different one.The returned xsd schema data type will be not as byte as we had in ASP.NET service rather encoded base64 string.

So we need to decode the base64 string as plain text.After we can write back to stream or screen.

ASP.NET webservice code for Base64Binary type
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.IO;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
public Service ()
{


}

[WebMethod]
public byte[] ShowFileContent()
{

FileStream fs = File.OpenRead(Server.MapPath("Resume.doc"));
byte[] b = new byte[fs.Length];
fs.Read(b, 0, b.Length);
return b;
}

}

PHP Client:
using nusoap webservice class.really its very handy.so my code length shrink about to 4 or 5 lines.


require_once('lib/nusoap.php');
$client = new soapclient('http://localhost/website2/Service.asmx?WSDL','wsdl');
$result = $client->call(ShowFileContent);
$r=array($result['ShowFileContentResult']);
print_r(base64_decode($r[0]),$handle);

//here you can write into file also.

?>

Tuesday, April 14, 2009

asp.net webservice SoapHeader Authentication

After long time,this is my second attempt to authenticate the webservice using SoapHeader.My System Architect team asked me to work aroud on this issue.Its works atlast :)-


SoapAuthenticateService.cs
*******************************
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(Name = "TestService", ConformsTo = WsiProfiles.BasicProfile1_1)]

public class SoapAuthenticateService : System.Web.Services.WebService
{

public UserAuthorise name;
public SoapAuthenticateService()
{


}

[WebMethod]
[SoapDocumentMethod(Binding = "TestService")]
[SoapHeader("name")]
public string GetString()
{
if (checkUser())
{
return "Authenticated Successfully";
}
else
{
return " You are not authorised yet !";
}


}

public bool checkUser()
{
if (name.userName == "Murugesan" && name.password == "12345")
{
return true;
}
else
{
return false;
}

}

}
________________________________________________________________________________

UserAuthorise.cs
**************************

public class UserAuthorise : System.Web.Services.Protocols.SoapHeader
{

public string userName;
public string password;


}
__________________________________________________________________________________

Service.asmx
***********************

<%@ WebService Language="C#" CodeBehind="~/App_Code/SoapAuthenticateService.cs" Class="SoapAuthenticateService" %>


Consumer Application code :

SoapAuthenticateService ap = new SoapAuthenticateService();
UserAuthorise u = new UserAuthorise();
u.userName = "Murugesan";
u.password = "12345";
ap.UserAuthoriseValue = u;

Response.Write(ap.GetString());

instead of hard coded user name and password,you can use the DB or XML as datasource.

Consuming ASP.NET webservice through PHP

I am trying to get least familiar with PHP code.I tried this simple asp.net webservice which is going to be consumed through PHP.

My asp.net code snippet
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
public Service () {

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public string HelloWorld(string name) {
return "Hello " + name;

}

}
_________________________________________________________________________

PHP
_________________________________________________________________________

require_once('lib/nusoap.php');
$objClient = new soapclient("http://localhost/website1/Service.asmx?WSDL");
$result = $objClient->call("HelloWorld", array('name' => 'Murugesan'));
echo $result;
?>

After i tried neckling fight with PHP code,I did not get my code works as I expected.
I keep my fingers cross over where I am doing wrong.