Search My Warehouse

2010-05-24

how to use stored procedures C#

1 using System;

2 using System.Collections.Generic;

3 using System.Linq;

4 using System.Text;

5 using System.Data;

6 using System.Data.SqlClient;

7

8

9

10 class ProcessDL

11 {

12 MyClass Obj = new MyClass();

13

14 string[] UserDetail;

15 SqlConnection con;

16 SqlCommand com;

17 SqlDataReader dr;

18 SqlDataAdapter da;

19 DataSet ds;

20

21 public int InsertProcess(string Processname,string InputPath,string OutputPath, string InputParameter, string FTPparameter, string CSVTriggerName,

22 string ImgTriggerName, string ExceptionFTPpath, string UN, string PWD, string FileFormat, string CreatedBy, string CreatedDate,string status,string ContainsKey)

23 {

24 try

25 {

26 con = new SqlConnection(Obj.ConnectionStr);

27 com = new SqlCommand("InsertNewProcess", Obj.DBConnect());

28 com.CommandType = CommandType.StoredProcedure;

29 com.Parameters.AddWithValue("@ProcessName", Processname);

30 com.Parameters.AddWithValue("@InputPath", InputPath);

31 com.Parameters.AddWithValue("@OutputPath", OutputPath);

32 com.Parameters.AddWithValue("@InputParameter", InputParameter);

33 com.Parameters.AddWithValue("@FTPParameter", FTPparameter);

34 com.Parameters.AddWithValue("@CSVTriggerName", CSVTriggerName);

35 com.Parameters.AddWithValue("@ImgTriggerName", ImgTriggerName);

36 com.Parameters.AddWithValue("@ExceptionFTPpath", ExceptionFTPpath);

37 com.Parameters.AddWithValue("@UserName", UN);

38 com.Parameters.AddWithValue("@Pwd", PWD);

39 com.Parameters.AddWithValue("@FileFormat", FileFormat);

40 com.Parameters.AddWithValue("@CreatedBY", CreatedBy);

41 com.Parameters.AddWithValue("@CreatedDate", CreatedDate);

42 com.Parameters.AddWithValue("@status", status);

43 com.Parameters.AddWithValue("@containsKey", ContainsKey);

44 return com.ExecuteNonQuery();

45 }

46 catch (Exception)

47 {

48

49 throw;

50 }

51

52 }

53

54 public int UpdateProcess(string Processname, string InputPath, string OutputPath, string InputParameter, string FTPparameter, string CSVTriggerName,

55 string ImgTriggerName, string ExceptionFTPpath, string UN, string PWD, string FileFormat,string ContainsKey)

56 {

57 try

58 {

59 con = new SqlConnection(Obj.ConnectionStr);

60 com = new SqlCommand("UpdateProcess", Obj.DBConnect());

61 com.CommandType = CommandType.StoredProcedure;

62 com.Parameters.AddWithValue("@ProcessName", Processname);

63 com.Parameters.AddWithValue("@InputPath", InputPath);

64 com.Parameters.AddWithValue("@OutputPath", OutputPath);

65 com.Parameters.AddWithValue("@InputParameter", InputParameter);

66 com.Parameters.AddWithValue("@FTPParameter", FTPparameter);

67 com.Parameters.AddWithValue("@CSVTriggerName", CSVTriggerName);

68 com.Parameters.AddWithValue("@ImgTriggerName", ImgTriggerName);

69 com.Parameters.AddWithValue("@ExceptionFTPpath", ExceptionFTPpath);

70 com.Parameters.AddWithValue("@UserName", UN);

71 com.Parameters.AddWithValue("@Pwd", PWD);

72 com.Parameters.AddWithValue("@FileFormat", FileFormat);

73 com.Parameters.AddWithValue("@containsKey", ContainsKey);

74 return com.ExecuteNonQuery();

75 }

76 catch (Exception)

77 {

78

79 throw;

80 }

81 }

82

83 public DataSet FetchAllValues(string Status)

84 {

85 try

86 {

87 ds = new DataSet();

88 ds.Clear();

89 con = new SqlConnection(Obj.ConnectionStr);

90 com = new SqlCommand("FetchAllProcess", Obj.DBConnect());

91 com.CommandType = CommandType.StoredProcedure;

92 com.Parameters.AddWithValue("@Status", Status);

93 da = new SqlDataAdapter(com);

94 da.Fill(ds);

95 return ds;

96 }

97 catch (Exception)

98 {

99

100 throw;

101 }

102 }

103 }

104


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



Stored Procedures



set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go




create procedure [dbo].[FetchAllProcess] @Status varchar(50)
as begin

SELECT [ProcessName]
,[InputPath]
,[OutputPath]
,[InputParameter]
,[FTPParameter]
,[CSVTriggerName]
,[ImgTriggerName]
,[ExceptionFTPpath]
,[UserName]
,[Pwd]
,[FileFormat]
,[CreatedBY]
,convert(varchar, CreatedDate,103) as 'Created On',
containsKey
FROM [ProcessMaster] order by [ProcessName] asc
end



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


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


create procedure [dbo].[UpdateProcess]

@ProcessName varchar(500),
@InputPath varchar(500),
@OutputPath varchar(500),
@InputParameter varchar(500),
@FTPParameter varchar(500),
@CSVTriggerName varchar(500),
@ImgTriggerName varchar(500),
@ExceptionFTPpath varchar(500),
@UserName varchar(100),
@Pwd varchar(100),
@FileFormat varchar(100),
@containsKey varchar(100)

as begin

UPDATE ProcessMaster
SET InputPath = @InputPath,OutputPath = @OutputPath,InputParameter = @InputParameter,FTPParameter = @FTPParameter,
CSVTriggerName = @CSVTriggerName,ImgTriggerName = @ImgTriggerName,ExceptionFTPpath = @ExceptionFTPpath,
UserName = @UserName,Pwd = @Pwd,FileFormat = @FileFormat,containsKey=@containsKey
WHERE ProcessName = @ProcessName

end

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


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


create procedure [dbo].[InsertNewProcess]

@ProcessName varchar(500),
@InputPath varchar(500),
@OutputPath varchar(500),
@InputParameter varchar(500),
@FTPParameter varchar(500),
@CSVTriggerName varchar(500),
@ImgTriggerName varchar(500),
@ExceptionFTPpath varchar(500),
@UserName varchar(100),
@Pwd varchar(100),
@FileFormat varchar(100),
@CreatedBY varchar(100),
@CreatedDate datetime,
@status varchar(50),
@containsKey varchar(100)

as begin

INSERT INTO ProcessMaster
(ProcessName,InputPath,OutputPath,InputParameter,FTPParameter,CSVTriggerName,ImgTriggerName,ExceptionFTPpath,UserName,Pwd,FileFormat,
CreatedBY,CreatedDate,status,containsKey)

VALUES
(@ProcessName ,@InputPath,@OutputPath,@InputParameter,@FTPParameter,@CSVTriggerName,@ImgTriggerName,@ExceptionFTPpath,@UserName,@Pwd,@FileFormat,
@CreatedBY,@CreatedDate,@status,@containsKey)

end

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

2010-05-20

Error log in ASP.net c#

Just put log.cs in appcode, create a folder in application root named ‘Logs’

log.cs

using System;
using System.Configuration;
using System.Data;
using System.IO;
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;

///


/// Summary description for Log
///

public class Log
{
#region Methods

public void WritetoLog(string strModule, string strRemarks)
{
// sLogDateFormat: take current date and time

string sLogDateFormat = DateTime.Now.ToString(“dd/MM/yyyy”) + ” ” + DateTime.Now.ToString(“HH:mm:ss”);

// sLogFileName: log file name for the module – user login with month and year

string sLogFileName = @”Error_Log_” + DateTime.Now.ToString(“MMMMyy”) + “.txt”;

// sLogFilePath: virtual path for storing the log file

string sLogFilePath = @”Logs/” + DateTime.Now.Year.ToString() + “/” + DateTime.Now.ToString(“MMMMyy”);

// check for existance of virtual path, if not create the pathin YYYY/MonthNameYYYY format, ex:- Logs/2008/July2008/

if (!Directory.Exists(sLogFilePath))
{

Directory.CreateDirectory(HttpContext.Current.Server.MapPath(sLogFilePath));

}

// open streamwriter to check existance of log filename, if notcreate the log file

StreamWriter sw;

if (!File.Exists(HttpContext.Current.Server.MapPath(sLogFilePath + “/” + sLogFileName)))
{

sw = File.CreateText(HttpContext.Current.Server.MapPath(sLogFilePath + “/” + sLogFileName));

sw.Flush(); // Flush the streamwriter object

sw.Close(); // Close the streamwriter object

sw = null;

}

//open streamwriter object to open the log file and appendremarls

StreamWriter writer = new StreamWriter(HttpContext.Current.Server.MapPath(sLogFilePath) + “/” + sLogFileName, true);

writer.WriteLine(sLogDateFormat + ” :| : ” + strModule + ” :| : ” + strRemarks); // write current date & remarks

writer.Close(); //close the streamwriter

writer = null;
}

#endregion Methods

}

.aspx.cs

try
{

//Your Function

}

catch (Exception ex)

{

StackFrame stackFrame = new StackFrame(0, true);
objLog.WritetoLog(stackFrame.GetFileName() + “_” + stackFrame.GetMethod().Name, ex.Message.ToString());

}

2010-03-18

CLASS FILE FOR DATABASE OPERATION



using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Web.Configuration;


///


/// Summary description for MyFunction
///

public class EBizFunction
{
public string ConnectionStr = ConfigurationManager.ConnectionStrings["EBizConnectionString"].ToString();
SqlConnection con;
SqlCommand com;
SqlDataReader dr;
SqlDataReader Drr;
SqlDataAdapter da;
DataSet ds;
ArrayList ArrList = new ArrayList();
int Result;
static Random random = new Random();
string FromMail = ConfigurationManager.AppSettings["SenderUsername"].ToString();
string password = ConfigurationManager.AppSettings["SenderPassword"].ToString();
string host = ConfigurationManager.AppSettings["HostIP"].ToString();
//string portNo = ConfigurationManager.AppSettings[""].ToString();
string portNo = "587";
string[] StrArr = null;


public EBizFunction()
{
//
// TODO: Add constructor logic here
//
}

public SqlConnection DBConnect()
{
try
{
con = new SqlConnection(ConnectionStr);
if (con.State != ConnectionState.Open)
{
con.Open();
}
return con;
}
catch (Exception)
{

throw;
}

}

public string ExecScalar(string Qry)
{
try
{
com = new SqlCommand(Qry, DBConnect());
return Convert.ToString(com.ExecuteScalar());
}
catch (Exception)
{
throw;
}
finally
{

con.Close();
}
}

public int ExecQry(string Qry)
{
try
{
com = new SqlCommand(Qry, DBConnect());
return com.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{

con.Close();
}
}

public string[] ExecDataReader(string Qry)
{
try
{

com = new SqlCommand(Qry, DBConnect());
dr = com.ExecuteReader();
return StrArr;
}
catch
{
return StrArr = null;
}
finally
{

con.Close();
}
}

public DataSet FillDataset(string Qry)
{
ds = new DataSet();
ds.Clear();
da = new SqlDataAdapter(Qry, DBConnect());
da.Fill(ds);
return ds;
}

public ArrayList FillArrayList(string Qry)
{
try
{
ArrList.Clear();
FillDataset(Qry);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { if(ds.Tables[0].Rows[i][0].ToString()!="") ArrList.Add(ds.Tables[0].Rows[i][0].ToString()); } return ArrList; } catch (Exception) { throw; } finally { ds.Clear(); con.Close(); } }

public ArrayList FillArrayListTwoValues(string Qry)
{ try
{ ArrList.Clear(); FillDataset(Qry); for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { if (ds.Tables[0].Rows[i][0].ToString() != "") { ArrList.Add(ds.Tables[0].Rows[i][0].ToString() + " (" + ds.Tables[0].Rows[i][1].ToString()+ ")"); } } return ArrList; } catch (Exception) { throw; } finally { ds.Clear(); con.Close(); } }

public void GenerateRandomValue()
{ Result= RandomNumber(0, 1000); }

public int RandomNumber(int min, int max)
{ Random random = new Random(); return random.Next(min, max); }

public string RandomString(int size, bool lowerCase)

{ StringBuilder builder = new StringBuilder(); Random random = new Random(); char ch; for (int i = 0; i < size; i++) { ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); builder.Append(ch); } if (lowerCase) return builder.ToString().ToLower(); return builder.ToString(); }

public void SendMail(string ToMail, string MailBody ,string SubjecT)

{ System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath); System.Net.Configuration.MailSettingsSectionGroup settings = (System.Net.Configuration.MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings"); System.Net.NetworkCredential credential = new System.Net.NetworkCredential(settings.Smtp.Network.UserName, settings.Smtp.Network.Password); int i = 0; //Create the SMTP Client SmtpClient client = new SmtpClient(); client.Host = settings.Smtp.Network.Host; client.Credentials = credential; HttpResponse response = HttpContext.Current.Response; MailMessage email = new MailMessage(); email.IsBodyHtml = true; email.From = new MailAddress(FromMail); email.To.Add(
ToMail);


//email.To.Add(strToEmail)
email.Subject = SubjecT;
email.IsBodyHtml = true;
email.Body = MailBody;
email.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

try
{
client.Send(email);
}
catch (Exception exc)
{
response.Write("Send failure: " + exc.ToString());
}
}

public void SendMail(string FrmMail, string ToMail, string MailBody, string SubjecT)
{
System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
System.Net.Configuration.MailSettingsSectionGroup settings = (System.Net.Configuration.MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
System.Net.NetworkCredential credential = new System.Net.NetworkCredential(settings.Smtp.Network.UserName, settings.Smtp.Network.Password);

int i = 0;
//Create the SMTP Client
SmtpClient client = new SmtpClient();
client.Host = settings.Smtp.Network.Host;
client.Credentials = credential;
HttpResponse response = HttpContext.Current.Response;
MailMessage email = new MailMessage();



email.IsBodyHtml = true;
email.From = new MailAddress(FrmMail);

email.To.Add(ToMail);

//email.To.Add(strToEmail)
email.Subject = SubjecT;
email.IsBodyHtml = true;
email.Body = MailBody;
email.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

try
{
client.Send(email);

}
catch (Exception exc)
{
response.Write("Send failure: " + exc.ToString());

}
}

public string SplitUp(string StrToSpilt, char cut,int Indx,char EndCut)
{
string[] Splt = null;
Splt = StrToSpilt.Split(cut);
return Splt[Indx].TrimEnd(EndCut);
}

public string[] SplitUp(string StrToSpilt, char cut)
{
string[] Splt = null;
Splt = StrToSpilt.Split(cut);
return Splt;
}

public int NoOfDays(DateTime FromDate, DateTime ToDate)
{
TimeSpan ts = ToDate.Subtract(FromDate);
int day = ts.Days;
return day+1;
}

public string IndianDateConverter(string Dat)
{
string[] StrArr;
string str;
StrArr = Dat.Split('/');
str = Convert.ToString(StrArr[0]);
StrArr[0] = Convert.ToString(StrArr[1]);
StrArr[1] = str;
Dat = "";
Dat = StrArr[0] + "/";
Dat += StrArr[1] + "/";
Dat += StrArr[2];
return Dat;
}

}

JavaScript Validations in ASP.Net

Validations



validate ONLY NUMBERS on TEXTBOX
-------------------------------------------
--------

function OnlyNumber(e)

{
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (event)
keycode = event.keyCode;

else if (e)
keycode = e.which;
else
return true;
if((keycode >= 48 && keycode <= 57) || keycode == 13)
{
return true;
}
else
{
alert('Enter Only Number');
return false;
}
return true;
}


validate ONLY NUMBERS on TEXTBOX
-------------------------------------------
--------

function OnlyCharacters(e)

{
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (event)
keycode = event.keyCode;

else if (e)
keycode = e.which;
else
return true;
if( (keycode >= 65 && keycode <= 90) || (keycode >= 97 && keycode <= 122) || keycode == 13 )
{
return true;
}
else
{
alert('Enter Only Characters');
return false;
}
return true;
}


validate SPECIAL Character on TEXTBOX
-------------------------------------------
--------


.CS
---------


Txt_Pwd.Attributes.Add("onkeypress", "return alphanumeric_SomeSpl(this);");


HEAD
---------


function alphanumeric_SomeSpl(e)

{
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (event)
keycode = event.keyCode;

else if (e)
keycode = e.which;
else
return true;
//Number, Character,Enter key(13),Underscore,Hyphen,@,fullstop,comma,dollar,
if( (keycode >= 48 && keycode <= 57) || (keycode >= 65 && keycode <= 90) || (keycode >= 97 && keycode <= 122) || keycode == 13 || keycode == 45 || keycode == 64 || keycode == 46 || keycode == 44 || keycode == 36 || keycode == 95 )
{
return true;
}
else
{
alert('Character Not Allowed Only');
return false;
}
return true;
}


validate Character on date Field
-------------------------------------------


.CS
---------


txt_FromDateFilter.Attributes.Add("onkeypress", "return TypeDate1();");



HEAD
---------


function TypeDate1()
{
var txt1=document.getElementById('<%=txt_FromDateFilter.ClientID %>');
var fromDate = txt1.value;
var iChars = "!@#$%^&*()+=[]\\\';,.{}|\":<>?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (var i = 0; i < fromDate.length; i++)
{
if (iChars.indexOf(fromDate.charAt(i)) != -1)
{
alert ("Invalid From Date Format.\n Characters not allowed \n Ex: 12/31/2000 or 12-31-2000");
txt1.value='';
return false;
}

}
return true;
}

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

Validate for FUTURE date
------------------------------------


HEAD
---------


//Check For Past Date, if it is past date it l clear the value....
function DateChek(txtDate)
{
var Lstid=txtDate.id;
var txtBox=document.getElementById(Lstid);
var spanDays = $get("spanDays");

var toDate=txtBox.value;
var mySplitResult;
var dt;



var myDay1;
var MyMon1;
var myYear1;

mySplitResult= toDate.split("/");
myDay1=mySplitResult[0];
MyMon1=mySplitResult[1];
myYear1=mySplitResult[2];
dt=MyMon1 + '/' + myDay1 + '/' + myYear1;



var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
spanDays.innerHTML='';
if(Date.parse(month + "/" + day + "/" + year)>Date.parse(dt))
{

alert('Enter Future Date');
//spanDays.innerHTML='Enter Future Date';
txtBox.value="";
return false;
}

}

BODY


<asp:TextBox ID="txt_FromDateFilter" runat="server" CssClass="TxtBxCalender" onchange="DateChek(this)"></asp:TextBox>

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


To Date must be greater than or equal to From Date.

HEAD
---------

function ValidateDate()

{


// var fromDate = document.forms['recentUpdates'].elements['fromDate'].value;

// var toDate = document.forms['recentUpdates'].elements['toDate'].value;
var txt1=document.getElementById('<%=txt_FromDate.ClientID %>');
var txt2=document.getElementById('<%=txt_ToDate.ClientID %>');
var spanDays = $get("spanDays");



var fromDate = txt1.value;

var toDate = txt2.value;

var mySplitResult = fromDate.split("/");
var dt;

var myDay;
var MyMon;
var myYear;

var myDay1;
var MyMon1;
var myYear1;

myDay=mySplitResult[0];
MyMon=mySplitResult[1];
myYear=mySplitResult[2];
dt=MyMon + '/' + myDay + '/' + myYear;
fromDate=dt;

mySplitResult= toDate.split("/");
myDay1=mySplitResult[0];
MyMon1=mySplitResult[1];
myYear1=mySplitResult[2];
dt=MyMon1 + '/' + myDay1 + '/' + myYear1;
toDate=dt;

var alertReason1 = 'To Date must be greater than or equal to From Date.'

var endDate = new Date(toDate);

var startDate= new Date(fromDate);


// var startDateValuecmp = startDate.getTime();
// var endDateValuecmp = endDate.getTime();
spanDays.innerHTML='';
if(fromDate == '' && toDate == '')

{

alert("Please enter From Date and To Date.");

return false;

}

else if(fromDate == '')

{
txt2.value='';
alert("Please enter From Date. ");

return false;

}
else if(txt1.value == '')

{
txt2.value='';
alert("Please enter From Date. ");

return false;

}

else if(toDate == '')

{

alert("Please enter To Date. ");

return false;

}
else if(toDate != '' && fromDate == '')

{
txt2.value='';
alert("Please enter From Date. ");

return false;

}


else if (fromDate !='' && toDate != '' && startDate > endDate)

{
txt2.value='';
alert(alertReason1);

return false;

}
else if (fromDate !='' && toDate != '' && startDate <= endDate)
{

var startingdate=new Date(myYear,MyMon,myDay);
var endingdate=new Date(myYear1,MyMon1,myDay1);
var one_day=1000*60*60*24;
//alert("Difference is " + Math.ceil((endingdate.getTime()-startingdate.getTime())/(one_day)) + " days ");
spanDays.innerHTML="You are applying leave for " + ( Math.ceil((endingdate.getTime()-startingdate.getTime())/(one_day)) + 1 )+ " day(s) "
return true;
}


}

BODY
---------


<asp:TextBox ID="txt_TODATE" runat="server" CssClass="TxtBxCalender" onchange="ValidateDate()"></asp:TextBox>


====================================================================


GET MULTIPLE SELECTED VALUES IN LISTBOX USING JAVASCRIPT


Add 3 hidden fields and a list box, enable multiple select in listbox property

HEAD
---------



function MultipleSelect(listfield,HidID,HidID1,HidID2)
{
var selected="";
var Lstid=listfield.id;
var LstBox=document.getElementById(Lstid);
var HiddenFld=document.getElementById(HidID);
var HiddenFld1=document.getElementById(HidID1);
var HiddenFld2=document.getElementById(HidID2);
HiddenFld.value='';
HiddenFld1.value='';
HiddenFld2.value='0';
for (i=0; i < LstBox.length; i++)
{
if (LstBox.options[i].selected)
{

selected=LstBox.options[i].text; // Name and Designation
selected1=LstBox.options[i].value; //Mail ID and Emp Code

if(i==0)
{
HiddenFld.value = selected;
HiddenFld1.value = selected1;
}
else
{
HiddenFld.value = HiddenFld.value + "," + selected ;
HiddenFld1.value = HiddenFld1.value + "," + selected1 ;

}

}
}
HiddenFld2.value=i;

}

.CS
---------


ListBox_AbsenceWork.Attributes.Add("onchange", "MultipleSelect(this,'" + HiddenField1.ClientID + "','" + HiddenField2.ClientID + "','" + HiddenField3.ClientID + "')");

===================================================================

2010-03-15

Gridview Row Editing Event , Row Deleting Event, Selected Index Changed Event


Get Values in Row Editing Event

string Val= GridView1.Rows[e.NewEditIndex].Cells[1].Text;

Get Values in Row Deleting Event

string Val=GridView1.Rows[e.RowIndex].Cells[1].Text;

Get Values in SelectedIndexChanged Event

string Val=GridView1.SelectedDataKey["Fs_EmpCode"].Tostring();


Hide Columns in a GridView

GridView1RowCreated Event

if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].CssClass = "hiddencol";
e.Row.Cells[2].CssClass = "hiddencol";
}
else if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].CssClass = "hiddencol";
e.Row.Cells[2].CssClass = "hiddencol";
}


StyleSheet:

.hiddencol
{
display:none;
}


Client Click in Gridview command field

Gridview_RowDataBound Event

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// loop all data rows
foreach (DataControlFieldCell cell in e.Row.Cells)
{
// check all cells in one row
foreach (Control control in cell.Controls)
{
// Must use LinkButton here instead of ImageButton
// if you are having Links (not images) as the command button.
ImageButton button = control as ImageButton;
if (button != null && button.CommandName == "Delete")
// Add delete confirmation
button.OnClientClick = "if (!confirm('Are you sure " +
"you want to delete this record?')) return;";
}
}
}
}

Important Note:

The important bit here is to use exactly the OnClientClick
content provided (except the wording in the message, of course). If you,
for example, instead, had "return confirm('Are you sure you want to delete the
record')"
like many others have suggested, this would
mean the Delete command would never be posted back to the server. The
actual onclick function call generated/rendered by ASP.NET






2010-03-09

Username availability



<div>



<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">

</asp:ScriptManager>



<asp:TextBox ID="UserName" runat="server" CssClass="txt" onkeyup="usernameChecker(this.value);" />
<span id="spanAvailability"></span>


<script type="text/javascript">
var usernameCheckerTimer;
var spanAvailability = $get("spanAvailability");

function usernameChecker(username)
{
clearTimeout(usernameCheckerTimer);
if (username.length == 0)
spanAvailability.innerHTML = "";
else
{
spanAvailability.innerHTML = "<span style='color: #ccc;'>checking...</span>";
usernameCheckerTimer = setTimeout("checkUsernameUsage('" + username + "');", 750);
}
}

function checkUsernameUsage(username)
{
// initiate the ajax pagemethod call
// upon completion, the OnSucceded callback will be executed
PageMethods.IsUserAvailable(username, OnSucceeded);
}

// Callback function invoked on successful completion of the page method.
function OnSucceeded(result, userContext, methodName)
{

if (methodName == "IsUserAvailable")
{
if (result == true)
spanAvailability.innerHTML = "<span style='color: DarkGreen;'>Available</span>";
else
spanAvailability.innerHTML = "<span style='color: Red;'>Unavailable</span>";
}
}
</script>

</div>

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



Sql
-----

CREATE PROCEDURE CheckUserName( @User_Name VARCHAR(50) )
AS
BEGIN

IF EXISTS (SELECT * FROM TLOGIN WHERE USERNAME = @User_Name )

SELECT '1'; --user name already exist in database

ELSE

SELECT '0'; --user name does not exist in database

END





.aspx.cs
----------

using System.Web.Services;
using System.Data.SqlClient;



public partial class Default4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}


[WebMethod]
public static bool IsUserAvailable(string username)
{

string returnValue = string.Empty;

string conString = "Password=iclip;Persist Security Info=True;User ID=iclip;Initial Catalog=ebiz;Data Source=purush";

SqlConnection sqlConn = new SqlConnection(conString);

try
{

SqlCommand sqlCmd = new SqlCommand("CheckUserName", sqlConn);

sqlCmd.CommandType = CommandType.StoredProcedure;

sqlCmd.Parameters.AddWithValue("@User_Name", username.Trim());

sqlConn.Open();

int success = int.Parse((sqlCmd.ExecuteScalar().ToString()));

if (success == 1) // User Name Not Available
{
//returnValue = "<img src='Images/no.jpeg'><font color='#cc0000'><b>'" + username + "'</b> is already in use.</font></img>";
return false;
}
else//User_Name is available
{
return true;
//returnValue = "Available";
}

}
catch
{
return false;
}
finally
{
sqlConn.Close();
}


}
}


2010-02-24

AutoCompleteExtender with Animation

AutoCompleteExtender with Animation

<cc1:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server" BehaviorID="AutoCompleteEx"
DelimiterCharacters="" Enabled="True" ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList" MinimumPrefixLength="1" CompletionInterval="10"
EnableCaching="true" CompletionSetCount="12" TargetControlID="txtName" >
<Animations>
<OnShow>
<Sequence>
<OpacityAction Opacity="0" />
<HideAction Visible="true" />
<ScriptAction Script="
// Cache the size and setup the initial size
var behavior = $find('AutoCompleteEx');
if (!behavior._height) {
var target = behavior.get_completionList();
behavior._height = target.offsetHeight - 2;
target.style.height = '0px';
}" />
<Parallel Duration=".4">
<FadeIn />
<Length PropertyKey="height" StartValue="0" EndValueScript="$find('AutoCompleteEx')._height" />
</Parallel>
</Sequence>
</OnShow>
<OnHide>
<Parallel Duration=".4">
<FadeOut />
<Length PropertyKey="height" StartValueScript="$find('AutoCompleteEx')._height" EndValue="0" />
</Parallel>
</OnHide>
</Animations>

</cc1:AutoCompleteExtender>

2010-01-29

File word count, whitespace count,Word Matches in C#



load event()
{
string FPath = @"D:\x.docx";
string text = File.ReadAllText(FPath);
MatchWord(FPath,"TestWordTOCount");
}

public void MatchWord(string Fname, string WordToMatch)
{
int count;
StreamReader reader = File.OpenText(Fname);
string contents = reader.ReadToEnd();
MatchCollection matches = Regex.Matches(contents, WordToMatch);
count = matches.Count;
}

static int CountNonSpaceChars(string value)
{
///
/// Counts the number of non-whitespace characters.
/// It closely matches Microsoft Word 2007.
///

/// String you want to count non-whitespaces in.
/// Number of non-whitespace chars.

int result = 0;
foreach (char c in value)
{
if (!char.IsWhiteSpace(c))
{
result++;
}
}
return result;
}

static int CountChars(string value)
{

///
/// Return the number of characters in a string using the same method
/// as Microsoft Word 2007. Sequential spaces are not counted.
///

/// String you want to count chars in.
/// Number of chars in string.


int result = 0;
bool lastWasSpace = false;

foreach (char c in value)
{
if (char.IsWhiteSpace(c))
{
// A.
// Only count sequential spaces one time.
if (lastWasSpace == false)
{
result++;
}
lastWasSpace = true;
}
else
{
// B.
// Count other characters every time.
result++;
lastWasSpace = false;
}
}
return result;
}

2010-01-10

Encoding and Decoding string c#

Encode

public string base64Encode(string data)
{
try
{
byte[] encData_byte = new byte[data.Length];
encData_byte = System.Text.Encoding.UTF8.GetBytes(data);
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
}
catch (Exception e)
{
throw new Exception("Error in base64Encode" + e.Message);
}
}

Decode

public string base64Decode(string data)
{
try
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decode = encoder.GetDecoder();

byte[] todecode_byte = Convert.FromBase64String(data);
int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
string result = new String(decoded_char);
return result;
}
catch (Exception e)
{
throw new Exception("Error in base64Decode" + e.Message);
}
}



2010-01-09

model

form.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Configuration;

namespace Text_Categorization
{
public partial class Form1 : Form
{
Funtions f = new Funtions();
string ConnStr = ConfigurationSettings.AppSettings["connect2DB"].ToString();
string PassQuery,Result;
int ResultInt,SplitID;
SqlConnection con = new SqlConnection();

public Form1()
{
InitializeComponent();
}

private void btnSave_Click(object sender, EventArgs e)
{
if (f.ErrProvider_AllFields(errorProvider1, this, "Mandatory") == true)
{
PassQuery = "INSERT INTO USERDETAIL VALUES('" + lblUserID.Text + "','" + txtUn.Text.Replace("'", "''") + "','" + txtPwd.Text.Replace("'", "''") + "','" + txtNickname.Text.Replace("'", "''") + "','" + dateDob.Text + "','" + comGender.SelectedItem.ToString() + "','" + txtAddr.Text.Replace("'", "''") + "','" + txtMob.Text.Replace("'", "''") + "','" + txtMail.Text.Replace("'", "''") + "','"+ comCountry.SelectedItem.ToString() +"',0)";
ResultInt = f.ExecQry(con, ConnStr, PassQuery);
if (ResultInt == 1)
MessageBox.Show("User Registered.");
else
MessageBox.Show("Not User Registered.");
}
}

private void Form1_Load(object sender, EventArgs e)
{
comGender.SelectedIndex = 0;
PassQuery = "SELECT MAX(UID) FROM USERDETAIL";
Result = Convert.ToString(f.GetSingle(con, ConnStr, PassQuery));
lblUserID.Text = "TC" + Convert.ToString(Result.Substring(2, 4));
}
}
}


cs:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Windows.Forms;

namespace Text_Categorization
{
class Funtions
{
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter da;
SqlDataReader dr;
DataSet ds;
DataTable dt;
int ResultStatus,Counter;
string ResultStr = "";
object ReturnObj = "";
string errorText;
bool bStatus;

public SqlConnection DBconnect(SqlConnection conn, string Constr)
{
if (conn.State != ConnectionState.Open)
{
conn = new SqlConnection(Constr);
conn.Open();
}
return conn;
}

public int ExecQry(SqlConnection conn,string ConnectStr, string Qry)
{
try
{
cmd = new SqlCommand(Qry, DBconnect(conn, ConnectStr));
return ResultStatus = cmd.ExecuteNonQuery();
}
catch
{
return ResultStatus = 0;
}
finally { conn.Close(); conn.Dispose(); }
}

public object GetSingle(SqlConnection conn, string ConnectStr, string Qry)
{
try
{

cmd = new SqlCommand(Qry, DBconnect(conn, ConnectStr));
return ReturnObj = cmd.ExecuteScalar();
}
catch
{
return ReturnObj;
}
finally { conn.Close(); conn.Dispose(); }
}

public DataTable GetDT(SqlConnection conn, string ConnectStr, string Qry)
{
try
{
da = new SqlDataAdapter(Qry, DBconnect(conn, ConnectStr));
da.Fill(dt);
return dt;
}
catch
{
dt.Clear();
return dt;
}
finally
{
conn.Close();
con.Dispose();
}
}

public bool ErrProvider_Combo(ComboBox ComBx, ErrorProvider errorProvider1, string msg)
{
bStatus = true;
if (ComBx.SelectedIndex == 0)
{
errorProvider1.SetError(ComBx, msg);
bStatus = false;
}
else
errorProvider1.SetError(ComBx, "");
return bStatus;
}

public bool ErrProvider_TextBox(TextBox TxtBX, ErrorProvider errorProvider1, string msg)
{
bool bStatus = true;
if (TxtBX.Text == "")
{
errorProvider1.SetError(TxtBX, msg);
bStatus = false;
}
else
errorProvider1.SetError(TxtBX, "");
return bStatus;
}

public bool ErrProvider_AllFields(ErrorProvider errorProvider1, Form ctr,string ErrMsg)
{
Counter=0;
bStatus=true;
foreach (Control ctrl in ctr.Controls)
{
if (ctrl.Text == "")
{
errorProvider1.SetError(ctrl, ErrMsg);
Counter++;
}
}
if (Counter != 0)
return bStatus = false;
else
return bStatus = true;
}

}
}



2010-01-08

Load Image using Ajax C# and VB.net



Create a Empty Page as

ImagePrev.aspx

And Create a new page with the below code:


<div>
<asp:ScriptManager id="ScriptManager1" runat="server">
</asp:ScriptManager><br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Image id="Image1" runat="server"></asp:Image>
<br />
<div id="ImagePreviewer" runat="server" style="background-position: center center;
background-image: url(Images/no-image.gif); width: 150px; background-repeat: no-repeat;
height: 150px">
</div>
<asp:FileUpload id="FileUpload1" runat="server"></asp:FileUpload>
<br />
<asp:LinkButton id="lnk_viewImg" runat="server" OnClick="lnk_viewImg_Click">View Image</asp:LinkButton>
<br />
</ContentTemplate>

</asp:UpdatePanel>

</div>


ImagePrev.aspx.cs

protected void lnk_viewImg_Click(object sender, EventArgs e)
{
//Image1.ImageUrl = FileUpload1.

Stream stream = default(Stream);

//HttpPostedFile oFile = Request.Files(0);
HttpPostedFile oFile = Request.Files[0];

stream = oFile.InputStream;

byte[] uploadedFile = new byte[stream.Length + 1];
byte[] a = null;

stream.Read(uploadedFile, 0, Convert.ToInt32(stream.Length));

if (Session["UploadImage"] != null)
Session["UploadImage"] = uploadedFile;
else
Session.Add("UploadImage", uploadedFile);

//ImagePreviewer.Style.Item("BACKGROUND-IMAGE") = "url(ImagePrev.aspx)";
//ImagePreviewer.Style.Add("BACKGROUND-IMAGE") = "url(ImagePrev.aspx)";
ImagePreviewer.Style.Add("BACKGROUND-IMAGE", "url(ImagePrev.aspx)");

}

ImagePrev.aspx.vb

button click

' Create a stream object.
Dim stream As IO.Stream
' Get the file that was selected.
Dim oFile As HttpPostedFile = Request.Files(0)
' Place the file into the stream.
stream = oFile.InputStream
' Create a byte array for the image.
Dim uploadedFile(stream.Length) As Byte
Dim a() As Byte
' Store the image into the byte array.
stream.Read(uploadedFile, 0, stream.Length)
' Store the byte array into a session variable.
If Session.Item("UploadImage") IsNot Nothing Then
Session.Item("UploadImage") = uploadedFile
Else
Session.Add("UploadImage", uploadedFile)
End If

' Set the ImagePreviewer's url to the ImagePrev page.
'ImagePreviewer.Style.Value("BACKGROUND-IMAGE") = "url(ImagePrev.aspx)"
Me.ImagePreviewer.Style.Item("BACKGROUND-IMAGE") = "url(ImagePrev.aspx)"




view image





2010-01-01

save imges in folder. resizing images asp.net c#

resizing images using Class

public class ImageManipulator
{
public Bitmap ScaleByPercent(System.Drawing.Image imgPhoto, int Percent)
{
float nPercent = ((float)Percent / 100);

int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;

int destX = 0;
int destY = 0;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);

Bitmap bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);
//bmPhoto.SetResolution(imgPhoto.HorizontalResolution,imgPhoto.VerticalResolution);
bmPhoto.SetResolution(72, 72);

Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);

grPhoto.Dispose();
return bmPhoto;
}

public bool ThumbnailCallback()
{
return true;
}
}


Upload Images in folder

page load:

profileImageFolderPath = Server.MapPath("ProfileImages");

private void UploadPhoto()
{
Bitmap bitmap = new Bitmap(FileUpload1.FileContent);
float percent = 100;
if (bitmap.Width > bitmap.Height)
{
if (bitmap.Width > 500)
{
float width = (float)bitmap.Width / 500;
percent = percent / width;
}
}
else
{
if (bitmap.Height > 500)
{
float heigth = (float)bitmap.Height / 500;
percent = percent / heigth;
}
}
ImageManipulator imageManipulator = new ImageManipulator();
System.Drawing.Image image = imageManipulator.ScaleByPercent(bitmap, (int)percent);
string imagePath = profileImageFolderPath + "\\" + txtEmail.Text.Trim() + ".jpg";
image.Save(imagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}





Feed