Create text file in c#

string[] lines = {"First line", "Second line", "Third line"};
            System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);

            // Example #2: Write one string to a text file. 
            string text = "A class is the most powerful data type in C#. Like structures, " +
                           "a class defines the data and behavior of the data type. ";
            System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text);

            // Example #3: Write only some strings in an array to a file. 
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt"))
            {
                foreach (string line in lines)
                {
                    if (line.Contains("Second") == false)
                    {
                        file.WriteLine(line);
                    }
                }
            }

            // Example #4: Append new text to an existing file 
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
            {
                file.WriteLine("Fourth line");
            }

form authentication in asp.net 4.0 example

1)in web.config place this code

<configuration>

<system.web>

<authentication mode=”Forms”>

<forms name=”TestAuthCookie” loginUrl=”Default.aspx” timeout=”30″>

<credentials passwordFormat=”Clear”>

<user name=”user1″ password=”pass1″/>

<user name=”user2″ password=”pass2″/>

</credentials>

</forms>

</authentication>

<authorization>

<deny users=”?”/>

</authorization>

<compilation targetFramework=”4.0″ debug=”true”/>

<pages controlRenderingCompatibilityVersion=”3.5″/>

</system.web>

</configuration>

2)create one page with name Default.aspx and place this code

<form id=”form1″ runat=”server”>

Username: <asp:TextBox ID=”txtUsername” runat=”server” /><br>

Password:<asp:TextBox ID=”txtPassword” runat=”server” /><br>

<asp:Button ID=”Button1″ runat=”server” onclick=”Button1_Click” Text=”Login” /><br>

<asp:Label ID=”lblStatus” runat=”server” Text=”Please login” />

</form>

 

3)or in  Default.aspx.cs file plase this code

 

 

protected void Button1_Click(object sender, EventArgs e)

{

if (FormsAuthentication.Authenticate(txtUsername.Text, txtPassword.Text))

{

lblStatus.Text = (“Welcome ” + txtUsername.Text);

FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);

}

else

{

lblStatus.Text = “Invalid login!”;

}

}

 

set external javascript variable from content page ,javascript reference in mastepage

1)create one external javascript file with name “userdetail.js” place in “Scripts” folder

var setRepete;

alert(“UserDetails :” + setRepete);

2)add javascript referrence in mastepage (.aspx)

<script type=”text/javascript” language=”javascript”>

var setRepete = ‘<%=UserDetail_setRepete%>’;

</script>

<script src=”/Scripts/userdetail.js” type=”text/javascript”></script>

3)in masterpage codebehind (.aspx.cs) page

public string UserDetail_setRepete { get; set; } //defind properity before page_load

protected void Page_Load(object sender, EventArgs e)

{

}

4)in content page (.aspx) file

<%@ Page Title=””  …. your page directory…   %>

<%@ MasterType VirtualPath=”~/MasterPage.master” %> // write this

5)in content page codebehind (.aspx.cs)

Master.UserDetail_setRepete = “hiiii”;

                                    Or second way is  

string script = “”;

script += “var setRepete = \”” + Convert.ToString(datalist2.Count())+ “\”;”;

Page.ClientScript.RegisterStartupScript(this.GetType(), “MyScript”, script, true);

Note: here var “setRepete” is your javascript variable. your javascript reference is added in master page

json string with multiple objects and array . accesss json sting values from codebehind in asp.net

1) add namespaces
using System.Web.Script.Serialization;
using System.Runtime.Serialization.Json;

2)my json string is like this in that i have two objects
1)_ReachOut
2) userDetails
and one array name is reachoutfactorsList

var datalist={“_ReachOut”:{“reachoutid”:65,”user_ID”:100,”question”:”reaching out about”,”anonymous”:false,”shared”:true,”create_date”:”\/Date(1345772377607)\/”,”update_date”:”\/Date(1346040165280)\/”,”status”:1,”start_date”:”\/Date(-62135596800000)\/”,”end_Date”:”\/Date(-62135596800000)\/”,”reachoutfactorsList”:[{“reachoutid”:0,”factor_ID”:373,”orders”:0,”description”:”p”,”preachOutID”:0,”pfactor_ID”:373,”porders”:0,”pdescription”:”p”},{“reachoutid”:0,”factor_ID”:374,”orders”:0,”description”:”q”,”preachOutID”:0,”pfactor_ID”:374,”porders”:0,”pdescription”:”q”},{“reachoutid”:0,”factor_ID”:375,”orders”:0,”description”:”r”,”preachOutID”:0,”pfactor_ID”:375,”porders”:0,”pdescription”:”r”},{“reachoutid”:0,”factor_ID”:376,”orders”:0,”description”:”s”,”preachOutID”:0,”pfactor_ID”:376,”porders”:0,”pdescription”:”s”}],”reachoutchoicesList”:[{“choice_ID”:1,”orders”:1,”description”:”s”,”detail”:null,”rouserid”:0,”reachOutID”:0,”getChoiceData”:null,”mediaURL”:null,”_arrayReachOutChoice”:null,”mediaURL_AttachmentID”:null,”pchoice_ID”:1,”porders”:1,”pdescription”:”s”},{“choice_ID”:2,”orders”:2,”description”:”d”,”detail”:null,”rouserid”:0,”reachOutID”:0,”getChoiceData”:null,”mediaURL”:null,”_arrayReachOutChoice”:null,”mediaURL_AttachmentID”:null,”pchoice_ID”:2,”porders”:2,”pdescription”:”d”},{“choice_ID”:3,”orders”:3,”description”:”f”,”detail”:null,”rouserid”:0,”reachOutID”:0,”getChoiceData”:null,”mediaURL”:null,”_arrayReachOutChoice”:null,”mediaURL_AttachmentID”:null,”pchoice_ID”:3,”porders”:3,”pdescription”:”f”},{“choice_ID”:4,”orders”:4,”description”:”sd”,”detail”:null,”rouserid”:0,”reachOutID”:0,”getChoiceData”:null,”mediaURL”:null,”_arrayReachOutChoice”:null,”mediaURL_AttachmentID”:null,”pchoice_ID”:4,”porders”:4,”pdescription”:”sd”},{“choice_ID”:5,”orders”:5,”description”:”dfd”,”detail”:null,”rouserid”:0,”reachOutID”:0,”getChoiceData”:null,”mediaURL”:null,”_arrayReachOutChoice”:null,”mediaURL_AttachmentID”:null,”pchoice_ID”:5,”porders”:5,”pdescription”:”dfd”},{“choice_ID”:6,”orders”:6,”description”:”werte”,”detail”:null,”rouserid”:0,”reachOutID”:0,”getChoiceData”:null,”mediaURL”:null,”_arrayReachOutChoice”:null,”mediaURL_AttachmentID”:null,”pchoice_ID”:6,”porders”:6,”pdescription”:”werte”}],”detail”:”&lt;p&gt;Give us some details Give us some details&lt;/p&gt;”,”set_Listof_Tags”:null,”tag”:{“similarTag”:null,”_TagID”:0,”_TagText”:null,”_TagType”:null},”get_Listof_Tags”:null,”goal”:”Be happy”,”Title”:”reaching-out-about-65″,”reachouttag”:null,”arrayOfreachouttag”:null,”haveliked”:false,”showcountoflike”:”0″,”Reachout_Like_Punch_Retry_date”:””,”finalchoiceid”:0,”finalchoicedesc”:null,”finalchoicename”:null},”userDetails”:{“emailid”:”a@a.com”,”password”:”M40FsP+6CcI=”,”firstname”:”Amar”,”lastname”:”Kumar”,”initials”:null,”age”:”25″,”dob”:”\/Date(528661800000)\/”,”gender”:”M”,”create_date”:”\/Date(1332916788510)\/”,”update_date”:”\/Date(1345464704810)\/”,”status”:1,”facebookuser”:true,”roleid”:1,”FacebookID”:null,”ThumImage”:””,”Image”:””,”addressid”:0,”userid”:100,”address1″:null,”address2″:null,”city”:null,”po_box”:0,”zip”:0,”statecode”:null,”countrycode”:null,”IsActive_Facebook”:0,”Attachments_ID”:0,”TimeZone”:null,”Location”:”pune”,”aboutyourself”:”What makes Amar tick?”,”ProfileComplete”:1,”quote”:”Hi I am Shailesh Sahu “,”profileimageurl”:”https://lh5.googleusercontent.com/-DZgr7J9D6xM/UCiD50ANpRI/AAAAAAAAEPs/VxQLI4sMVdU/s75/Shailesh-Aug2012.jpg&#8221;,”titleUserName”:”amarkumar-100″,”addresscreate_date”:”\/Date(-62135596800000)\/”,”addressupdate_date”:”\/Date(-62135596800000)\/”,”alreadyhavetuned”:false,”Twitter_User”:false,”TwitterID”:null,”IsActive_Twitter”:0,”ActivationNumber”:null,”ActivationCode”:null,”ActivationID”:0,”PicasaAlbumID”:0,”FacebookOfflineToken”:null,”TwitterOfflineToken”:null,”TwitterScreenName”:null,”TwitteruserAccessToken”:null,”TwitteruserAccessSecret”:null,”UserFacebookID”:null,”FriendFacebookID”:null,”FriendName”:null,”FriendPictureURL”:null,”Love”:0,”following”:4,”follower”:2,”Punched”:0,”Retry”:0,”Thanked”:0,”BulkDataTableName”:null,”BulkTableName”:null,”EmailNotification”:1},”actType”:”RO”,”userActivitiesList”:null}

3) accessing values from datalist

 foreach (var data in datalist)
            {
                string[] matchstr = data.ToString().Split(‘:’);
                matchstr = matchstr[0].ToString().Split(‘\”‘);
                var json = data.ToString();
                var jss = new JavaScriptSerializer();
                var table = jss.Deserialize<dynamic>(json);

if (matchstr[1].ToString() == “_ReachOut”) //RO
                {
                    var RoChoiceLst = table[“_ReachOut”][“reachoutchoicesList”];  // assining array values to variable
                    foreach (var nRoChoiceLst in RoChoiceLst) //accessing array variable values one by one
                    {
                        rochlist += Convert.ToString(nRoChoiceLst[“porders”]);
                       
                    }
                
     reachoutStrip +=table[“userDetails”][“lastname”] //accessing “lastname” values form userDetails object
     reachoutStrip+=table[“_ReachOut”][“question”]; // accessing “question” values form  ReachOut object

                }
}

asp.net Properities

1)disable controls not work in javascipt to add this properity in chield page

this.Form.SubmitDisabledControls = true;

2)Mantain scroll in page after post back

this.MaintainScrollPositionOnPostBack = true;

Javascript Basics

1)get dropdown selected text in javascript

var ddlCal = document.getElementById(“%=ddl_CustomsCalsAS.ClientID%>”);
var Text = ddlCal.options[ddlCal.selectedIndex].text;

2)disable form auto complete in control

<form id=”form1″ runat=”server” autocomplete=”off”>

your design here

</form>
3)KeysShortcut in asp.net using javascript

<script language=”javascript” type=”text/javascript”>
document.attachEvent(‘onkeyup’, KeysShortcut);
function KeysShortcut()
{
if (event.keyCode == 83)// Ctrl+S (Save)
{
document.getElementById(‘<%= imbMainSave.ClientID %>’).click();
}

if (event.keyCode == 88)// Ctrl+X) (Back)
{
document.getElementById(‘<%= imgCancel.ClientID %>’).click();
}
if (event.keyCode == 85)//Ctrl+U (Logout)
{
document.getElementById(‘ctl00$Logh1$imbLogout’).click();
}
}

</script>

4)div with background-image in asp.net

<div style=”background-image: url(‘../Images/Winsoft.jpg’); height: 500px;”>
<table>
<tr>
<td>
<asp:Label ID=”Label1″ runat=”server” Text=”Name”></asp:Label>
</td>
<td>
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
</td>
</tr>
</table>
</div>
5)div with vertical scroll only

<div style=”height: 100px; overflow: scroll; width: 900px; overflow-x:hidden;”>

your table

</div>

<div style=”overflow: auto; width: 140px; height: 20px; overflow-x:hidden;”>

</div>

6)disable cut,copy,paste on textbox using javascript
<asp:TextBox ID=”TextBox2″ oncopy=”return false” onpaste=”return false” oncut=”return false”
runat=”server”></asp:TextBox>

7)open new page in pageload

<script>
win2=window.open(“http://www.msn.com&#8221;)
win2.blur()
window.focus()
</script>

8)disable right mouse button click

<script language=”javascript”>
var message=”Function Disabled!”;
function clickIE4(){
if (event.button==2)
{
alert(message);
return false;
}
}

function clickNS4(e)
{
if (document.layers||document.getElementById&&!document.all)
{
if (e.which==2||e.which==3)
{
alert(message);
return false;
}
}
}

if (document.layers)
{
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById)
{
document.onmousedown=clickIE4;
}

document.oncontextmenu=new Function(“alert(message);return false”)
</script>

9)inside grid hide overflow text
<asp:TemplateField HeaderText=”Reference” SortExpression=”Job_Reference”>
<ItemStyle Width=”50px” Height=”18px” />
<ItemTemplate>
<div style=”height: 15px; width: 50px; overflow: hidden;”>
<asp:Label ID=”lblJob_Reference” runat=”server” Text='<%# Bind(“Job_Reference”) %>’>
</asp:Label>
</div>
</ItemTemplate>
<HeaderStyle Width=”50px” />
</asp:TemplateField>

10)call two js funcion in one button click from code behind in asp.net

a)function one

function CalAmtQtySlab(grdQty,grdAmt,PopUpBillRate,grdPayableAmt,PopUpPayableBillRate,popupPayableAmt)
{
var State=true;
var qty=new Number(grdQty.value) ;
if(qty==”0″)
{
alert(“Please Fill Qty”);
grdQty.value=1;
State=false;
}
var BillRate=new Number(PopUpBillRate.value);
if(BillRate!=”0″)
{
var amt1=new String();
amt1=PopUpBillRate.value*grdQty.value.substr(0,12);
var ccal=new Number(amt1);
ccal=ccal.toFixed(2);
grdAmt.value=ccal;
//grdAmt.value=PopUpBillRate.value*grdQty.value;
}

var tr;
tr=SlabValidation();
if(tr==false)
{
State=false;
}
else
{
State=true;
PayableBillRate=new Number(PopUpPayableBillRate.value);
if(PayableBillRate!=”0″)
{
var amt2=new String();
amt2=PopUpPayableBillRate.value*grdQty.value.substr(0,12);
var ccal2=new Number(amt2);
ccal2=ccal2.toFixed(2);
grdPayableAmt.value=ccal2;
popupPayableAmt.value=ccal2;
//grdPayableAmt.value=PopUpPayableBillRate.value*grdQty.value;
}
}
return State;
}

b)function two

function SlabValidation()
{
var state=true;
var str=””;
if(document.getElementById(“<%=ddl_CustomsSlabType.ClientID %>”).value==0)
{
return state;
}
else
{
if(document.getElementById(“<%=txt_CustomsBillingRate.ClientID %>”).value.indexOf(” “) == 0 || document.getElementById(“<%=txt_CustomsBillingRate.ClientID %>”).value==””)
{
str=str+”Please Fill BillingRate \n”;
}
if(document.getElementById(“<%=ddl_CustomsCalsAS.ClientID %>”).value == 0)
{
str=str+”Please Select CalsAS \n”;
}
if(document.getElementById(“<%=txt_Amount.ClientID %>”).value == 0)
{
str=str+”Please Fill Amt \n”;
}
if(str.length>0)
{
var Msg=”NOTE: Field(s) Cannot be blank: \n” + str;
alert(Msg);
state=false;
}
return state;
}
return state;
}

c)in code behind

btn_SlabSave.Attributes.Add(“onclick”, “return CalAmtQtySlab(” + txt_CustomsQty.ClientID + “,” + txt_CustomsAmt.ClientID + “,” + txt_CustomsBillingRate.ClientID + “,” + txt_CustomsPayableAmt.ClientID + “,” + txt_CustomsPayableRate.ClientID + “,” + txt_CustomsAmtPayable.ClientID +”)”);

 

 

11)button in fixed position in scroable page in asp.net

<div style=”position: fixed; left: 0%;bottom: 0%;”>

<asp:ImageButton ID=”lnkEdit” runat=”server”
ImageUrl=”~/images/create-other.gif” ToolTip=”Edit Record”
Height=”15px” />

</div>

links

http://www.yaldex.com/

http://www.tutorialspoint.com/

http://www.onlywebpro.com

http://www.codeproject.com/Articles/25600/Triggers-Sql-Server

http://www.koderguru.com/tutorials/javascript/javascriptevents.php

 

http://www.devshed.com/c/a/JavaScript/Controlling-Browser-Properties-with-JavaScript/4/

multiple transaction in different database in one button click

1)datautility

 

public string ExecuteSqlNewList_outputPara_MultiTrans(List<SqlParam> arrPrams, string spName, SqlConnection Conn1, SqlTransaction SqlTran)
{
int iResult = 0;
string ErrMsg = string.Empty;
string spara = string.Empty;
try
{
for (int i = 0; i <= arrPrams.Count – 1; i++)
{
if (arrPrams[i] != null)
{
SqlCommand cmd = new SqlCommand(spName);

foreach (SqlParameter param in arrPrams[i].sqlParm)
{
cmd.Parameters.Add(param);
}
cmd.CommandText = spName;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters[“@outputTest”].Direction = ParameterDirection.Output;
cmd.Connection = Conn1;
cmd.Transaction = SqlTran;
iResult = cmd.ExecuteNonQuery();
ErrMsg = Convert.ToString(cmd.Parameters[“@outputTest”].Value);
IsSuccess = iResult > 0 ? true : false;
if (IsSuccess == false)
{
throw new Exception(“Transaction Failed ” + spName.ToString());
ErrMsg = Convert.ToString(cmd.Parameters[“@outputTest”].Value);
}
cmd.Parameters.Clear();
}
}
}
catch (Exception ex)
{
IsSuccess = false;
ErrMsg = “ERROR:” + ex.Message.ToString();
throw ex;
}
return ErrMsg;
}

 

2)in dl

public string Update_JobEntry(List<CboAEJobEntryHeader_FromFF> oCboAEJobEntryHeader_FromFF, SqlConnection conn, SqlTransaction trans)
{
bool IsUpdate = true;
string op = string.Empty;
oMyConnection = new MyConnection();
try
{
DataUtility oDataUtility = new DataUtility();
#region JobEntryHeader
if (oCboAEJobEntryHeader_FromFF.Count > 0)
{
List<string> spName = new List<string>();
List<SqlParam> oSqlParam = new List<SqlParam>();
for (int j = 0; j < oCboAEJobEntryHeader_FromFF.Count; j++)
{

SqlParameter[] oSqlParameterJobEntry = {
new SqlParameter(“@Job_Kid”,oCboAEJobEntryHeader_FromFF[j].Job_Kid),
new SqlParameter(“@Job_IsTPT”,oCboAEJobEntryHeader_FromFF[j].Job_IsTPT),
new SqlParameter(“@Job_TPTProviderId”,oCboAEJobEntryHeader_FromFF[j].Job_TPTProviderId),
new SqlParameter(“@Job_TPTProviderName”,oCboAEJobEntryHeader_FromFF[j].Job_TPTProviderName),
new SqlParameter(“@Job_TPTVendorId”,oCboAEJobEntryHeader_FromFF[j].Job_TPTVendorId),
new SqlParameter(“@Job_TPTVendorName”,oCboAEJobEntryHeader_FromFF[j].Job_TPTVendorName),
new SqlParameter(“@Job_TPTVendorLocId”,oCboAEJobEntryHeader_FromFF[j].Job_TPTVendorLocId),
new SqlParameter(“@Job_TPTVendorLocName”,oCboAEJobEntryHeader_FromFF[j].Job_TPTVendorLocName),
new SqlParameter(“@Job_IsDestDel”,oCboAEJobEntryHeader_FromFF[j].Job_IsDestDel),
new SqlParameter(“@Job_DestDelOverseasAgentId”,oCboAEJobEntryHeader_FromFF[j].Job_DestDelOverseasAgentId),
new SqlParameter(“@Job_DestDelOverseasAgentName”,oCboAEJobEntryHeader_FromFF[j].Job_DestDelOverseasAgentName),
new SqlParameter(“@Job_DestDelOverseasAgentLocId”,oCboAEJobEntryHeader_FromFF[j].Job_DestDelOverseasAgentLocId),
new SqlParameter(“@Job_DestDelOverseasAgentLocName”,oCboAEJobEntryHeader_FromFF[j].Job_DestDelOverseasAgentLocName),
new SqlParameter(“@outputTest”,SqlDbType.VarChar,100)
};
oSqlParam.Add(new SqlParam(oSqlParameterJobEntry));
}
op = oDataUtility.ExecuteSqlNewList_outputPara_MultiTrans(oSqlParam, “[AirExport].[SP_tbl_JobEntry_Header_UpdateFromCharges]”, conn, trans);
}

#endregion JobEntryHeader
}
catch (Exception ex)
{
op = ex.Message.ToString();
throw ex;
}
return op;
}

3)in code behind

public void SaveOrUpdate()
{

oCblAECharges = new CblAECharges();
oMyConnection = new MyConnection();
SqlConnection conFF = new SqlConnection(oMyConnection.FFConn);
SqlConnection conCHA = new SqlConnection(oMyConnection.CHAConn);
conFF.Open();
conCHA.Open();
SqlTransaction TransFF = conFF.BeginTransaction();
SqlTransaction TransCHA = conCHA.BeginTransaction();

try
{
#region Custome
List<CboAECharges> oCboAECharges = new List<CboAECharges>();
DataTable dtDet = new DataTable();
dtDet = ViewState[“dtCustome”] as DataTable;
if (dtDet.Rows.Count > 0)
{
for (int i = 1; i <= dtDet.Rows.Count – 1; i++)
{
if (dtDet.Rows[i][“ModeNew”].ToString() == “Edit”)
{

}
else
{
oCboAECharges.Add(new CboAECharges
{
JobCHA_Kid = new Guid(dtDet.Rows[i][“AE_Job_CHA_Kid”].ToString()),
JobCHA_AirExportId = new Guid(ViewState[“Jobid”].ToString()),

JobCHA_AirExportNo = ViewState[“JobNo”].ToString(),
JobCHA_AirExportDate = ViewState[“JobDate”].ToString(),

JobCHA_ChargeCodeId = new Guid(dtDet.Rows[i][“AE_Job_CHA_ChargeCodeId”].ToString()),
JobCHA_ChargeCodeName = dtDet.Rows[i][“AE_Job_CHA_ChargeCodeName”].ToString(),
JobCHA_ItemBehId = new Guid(dtDet.Rows[i][“AE_Job_CHA_ItemId”].ToString()),
JobCHA_ItemName = dtDet.Rows[i][“AE_Job_CHA_ItemName”].ToString(),
JobCHA_ChargesStatusId = Convert.ToInt32(dtDet.Rows[i][“AE_Job_CHA_ChargesStatusId”].ToString()),
JobCHA_ChargesStatusName = dtDet.Rows[i][“AE_Job_CHA_ChargesStatusName”].ToString(),
JobCHA_QtyAmt = Convert.ToDecimal(dtDet.Rows[i][“AE_Job_CHA_QtyAmt”]),
JobCHA_CurrencyId = new Guid(dtDet.Rows[i][“AE_Job_CHA_CurrencyId”].ToString()),
JobCHA_CurrencyName = dtDet.Rows[i][“AE_Job_CHA_CurrencyName”].ToString(),
JobCHA_BillingAmt = Convert.ToDecimal(dtDet.Rows[i][“AE_Job_CHA_BillingAmt”]),
JobCHA_ExchRate = Convert.ToDecimal(dtDet.Rows[i][“AE_Job_CHA_ExchRate”]),
JobCHA_SlabTypeId = new Guid(dtDet.Rows[i][“AE_Job_CHA_SlabTypeId”].ToString()),
JobCHA_SlabTypeName = dtDet.Rows[i][“AE_Job_CHA_SlabTypeName”].ToString(),
JobCHA_CalculateAsId = Convert.ToInt32(dtDet.Rows[i][“AE_Job_CHA_CalculateAsId”]),
JobCHA_CalculateAsName = dtDet.Rows[i][“AE_Job_CHA_CalculateAsName”].ToString(),

JobCHA_BiilingRate = dtDet.Rows[i][“AE_Job_CHA_BiilingRate”].ToString() == “0” ? 0 : (Convert.ToDecimal(dtDet.Rows[i][“AE_Job_CHA_BillingAmt”]) / Convert.ToDecimal(dtDet.Rows[i][“AE_Job_CHA_QtyAmt”])),

//JobCHA_BiilingRate =Convert.ToDecimal(dtDet.Rows[i][“AE_Job_CHA_BillingAmt”]) / Convert.ToDecimal(dtDet.Rows[i][“AE_Job_CHA_QtyAmt”]),

JobCHA_PayableAmt = Convert.ToDecimal(dtDet.Rows[i][“AE_Job_CHA_PayableAmt”]),

JobCHA_PayableRate = dtDet.Rows[i][“AE_Job_CHA_PayableRate”].ToString() == “0” ? 0 : (Convert.ToDecimal(dtDet.Rows[i][“AE_Job_CHA_PayableAmt”]) / Convert.ToDecimal(dtDet.Rows[i][“AE_Job_CHA_QtyAmt”])),

JobCHA_Remarks = dtDet.Rows[i][“AE_Job_CHA_Remarks”].ToString(),
JobCHA_PayToId = Convert.ToInt32(dtDet.Rows[i][“AE_Job_CHA_PayToId”]),
JobCHA_PayToName = dtDet.Rows[i][“AE_Job_CHA_PayToName”].ToString(),
JobCHA_PayToPartyId = new Guid(dtDet.Rows[i][“AE_Job_CHA_PayToPartyId”].ToString()),
JobCHA_PayToPartyName = dtDet.Rows[i][“AE_Job_CHA_PayToPartyName”].ToString(),
JobCHA_PayToPartyLocationId = new Guid(dtDet.Rows[i][“AE_Job_CHA_PayToPartyLocationId”].ToString()),
JobCHA_PayToPartyLocationName = dtDet.Rows[i][“AE_Job_CHA_PayToPartyLocationName”].ToString(),
Mode = 2,
CompanyId = new Guid(ViewState[“CompanyID”].ToString()),
BranchId = new Guid(ViewState[“BranchID”].ToString()),
FinYearId = new Guid(ViewState[“FinacialYearID”].ToString()),
UserId = new Guid(Convert.ToString(ViewState[“UserID”])),
JobCHA_IsSlab = dtDet.Rows[i][“AE_Job_CHA_SlabTypeId”].ToString() == “00000000-0000-0000-0000-000000000000” ? false : true,
JobCHA_PayModeId = dtDet.Rows[i][“AE_Job_CHA_PayToId”].ToString() == “0” ? 0 : 291,
JobCHA_PayModeName = dtDet.Rows[i][“AE_Job_CHA_PayToId”].ToString() == “0” ? “” : “Purchase”,
ModeNew = dtDet.Rows[i][“ModeNew”].ToString()
//ModeDetails = Convert.ToInt32(ViewState[“Mode_Det”])
}
);
}
}
}

#endregion Custome

string op = oCblAECharges.SaveFinal(oCboAECharges, oCboAETransportation, oCBOAEDestinationDelivery, conFF, TransFF);
if (op == “Success”)
{
List<CboAEJobEntryHeader_FromFF> oCboAEJobEntryHeader_FromFF = new List<CboAEJobEntryHeader_FromFF>();
string op1 = string.Empty;
if ((Chk_DestinationMain.Checked == true) || (Chk_TransportationMain.Checked == true))
{

oCboAEJobEntryHeader_FromFF.Add(new CboAEJobEntryHeader_FromFF
{
Job_Kid = new Guid(ViewState[“Jobid”].ToString()),
Job_IsTPT = Chk_TransportationMain.Checked == true ? true : false,
Job_TPTProviderId = Chk_TransportationMain.Checked == true ? Convert.ToInt32(ddlTransportation.SelectedValue) : 0,
Job_TPTProviderName = Chk_TransportationMain.Checked == true ? ddlTransportation.SelectedItem.Text.ToString() : string.Empty,
Job_TPTVendorId = Chk_TransportationMain.Checked == true ? new Guid(PsTransVendor.SelectedItem[“Vendor_Kid”].ToString()) : Guid.Empty,
Job_TPTVendorName = Chk_TransportationMain.Checked == true ? PsTransVendor.SelectedItem[“Vendor_Name”].ToString() : string.Empty,
Job_TPTVendorLocId = new Guid(PsTransVendor.SelectedItem[“VendorLoc_Kid”].ToString()),
Job_TPTVendorLocName = PsTransVendor.SelectedItem[“VendorLoc_Name”].ToString(),

Job_IsDestDel = Chk_DestinationMain.Checked == true ? true : false,
Job_DestDelOverseasAgentId = Chk_DestinationMain.Checked == true ? new Guid(PsOverSeasAgent.SelectedItem[“Vendor_Kid”].ToString()) : Guid.Empty,
Job_DestDelOverseasAgentName = Chk_DestinationMain.Checked == true ? PsOverSeasAgent.SelectedItem[“Vendor_Name”].ToString() : string.Empty,
Job_DestDelOverseasAgentLocId = Chk_DestinationMain.Checked == true ? new Guid(PsOverSeasAgent.SelectedItem[“VendorLoc_Kid”].ToString()) : Guid.Empty,
Job_DestDelOverseasAgentLocName = Chk_DestinationMain.Checked == true ? PsOverSeasAgent.SelectedItem[“VendorLoc_Name”].ToString() : string.Empty,
});
}
if((Chk_DestinationMain.Checked == true) || (Chk_TransportationMain.Checked == true))
{
op = oCblAECharges.Update_JobEntry(oCboAEJobEntryHeader_FromFF, conCHA, TransCHA);
}
if (op == “Success”)
{
TransCHA.Commit();
TransFF.Commit();
ScriptManager.RegisterClientScriptBlock(this, Page.GetType(), Guid.NewGuid().ToString(), “alert(‘Record Save Sucessfully !’)”, true);
ViewState[“dtTransportation”] = null;
ViewState[“dtCustome”] = null;
ViewState[“dtDestinationDelivery”] = null;
Fill_ExitData();
}
else
{
TransCHA.Rollback();
TransFF.Rollback();
}
}
else
{
TransCHA.Rollback();
TransFF.Rollback();
}
}
catch (Exception ex)
{
TransCHA.Rollback();
TransFF.Rollback();
}
}

 

Rearrange seriol Number

DataRow dRow1;
DataTable dtNewSrNo = new DataTable();
dtNewSrNo = DataTableSchema();
for (int i = 0; i < gvProductList.Rows.Count; i++)
{
dRow1 = CBO_Product.AddRow();

HiddenField hdn_Kid = (HiddenField)gvProductList.Rows[i].FindControl(“hdn_Kid”);
TextBox txt_NewProd_SrNo = (TextBox)gvProductList.Rows[i].FindControl(“txt_NewProd_SrNo”);
// LinkButton ProductLink = (LinkButton)gvProductList.Rows[i].FindControl(“ProductLink”);
Label lbl_ProductName = (Label)gvProductList.Rows[i].FindControl(“lbl_ProductName”);

HiddenField hdn_ProductKId = (HiddenField)gvProductList.Rows[i].FindControl(“hdn_ProductKId”);

 

if (txt_NewProd_SrNo.Text.Trim().ToString() == “”)
{
string msg = “All SrNo Must Change”;
//ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), “alert(‘” + msg.ToString() + “‘)”, true);
//return;
ErrMsg.Text = msg.ToString();
ErrMsg.Visible = true;
return;
}
else
{
if (txt_NewProd_SrNo.Text != “”)
{
if (Convert.ToInt32(txt_NewProd_SrNo.Text) == 0)
{
//ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), “alert(‘New SrNo can not ” + txt_NewProd_SrNo.Text + “‘)”, true);
ErrMsg.Text = “New SrNo can not ” + txt_NewProd_SrNo.Text;
ErrMsg.Visible = true;
return;
}
else
{
int count = Convert.ToInt32(gvProductList.Rows.Count);
if (Convert.ToInt32(txt_NewProd_SrNo.Text) > count)
{
//ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), “alert(‘New SrNo can not grater then ” + count + “‘)”, true);
ErrMsg.Text = “New SrNo can not grater then ” + count;
ErrMsg.Visible = true;

return;
}
else
{
//////
//ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), “alert(‘” + count + “‘)”, true);
//return;

DataRow[] result = dtNewSrNo.Select(“New_SrNo=” + txt_NewProd_SrNo.Text.ToString());
if (result.Length > 0)
{
//ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), “alert(‘New SrNo can not be Duplicate’)”, true);
ErrMsg.Text = “New SrNo can not be Duplicate”;
ErrMsg.Visible = true;

return;
}
else
{
DataRow dr;
if (txt_NewProd_SrNo.Text != “”)
{
dr = dtNewSrNo.NewRow();
dr[“Kid”] = hdn_Kid.Value.ToString();
dr[“SrNo”] = gvProductList.Rows[i].Cells[0].Text;
dr[“New_SrNo”] = txt_NewProd_SrNo.Text.ToString();

dr[“ProductName”] = Convert.ToString(lbl_ProductName.Text);
dr[“Product_Kid”] = Convert.ToString(hdn_ProductKId.Value);
dtNewSrNo.Rows.Add(dr);
}
dRow1[“JobInvProd_Kid”] = dtNewSrNo.Rows[i][“Kid”].ToString();
dRow1[“JobInvProd_SrNo”] = dtNewSrNo.Rows[i][“New_SrNo”].ToString();
dRow1[“Mode”] = 6;
dRow1[“JobInvProd_ProductKId”] = dtNewSrNo.Rows[i][“Product_Kid”].ToString();
dRow1[“JobInvProd_ProductName”] = dtNewSrNo.Rows[i][“ProductName”].ToString();

dRow1[“JobInvProd_JobId”] = Convert.ToString(ViewState[“Jobid”]);
dRow1[“JobInvProd_JobInvDetId”] = Convert.ToString(ViewState[“InvId”]);

 

CBO_Product.dttbl_JobEntry_InvProd.Rows.Add(dRow1);
}
////////
}

}
}
}
}

trape error in stored procedure in sql server

1)Create Table with Name “ErrorInfo” Columns Name are (ErrOn, ErrLineNo, ErrMsg, ErrNo, ErrSProc, ErrState, ErrSeverity)
2)create Procedure like this
Create PROCEDURE [Common].[GetErrorInfo]
AS
SET NOCOUNT ONINSERT INTO ErrorInfo(ErrOn, ErrLineNo, ErrMsg, ErrNo, ErrSProc, ErrState, ErrSeverity)

VALUES (GETDATE(), ERROR_LINE(), ERROR_MESSAGE(), ERROR_NUMBER(), ERROR_PROCEDURE(), ERROR_STATE(), ERROR_SEVERITY())