Request multiple tracking numbers with Fedex API - c#

I'm making a web app, for tracking Fedex shipments, I currently have about 10,000-15,000 packages daily.
I integrated Fedex Api in my System but it takes more tan 20 minutes to get the status of only 1300 packages. Is there a Way to make this faster? I read that you can send 30 packages in one request but can't find a Way to make it work.
Here is a link to another question, that I found but didn't get it to work
Requesting many tracking numbers with Fedex SOAP API with PHP
CODE
{
TrackRequest request = new TrackRequest();
request.WebAuthenticationDetail = new WebAuthenticationDetail();
request.WebAuthenticationDetail.UserCredential = new WebAuthenticationCredential();
request.WebAuthenticationDetail.UserCredential.Key = ""; // Replace "XXX" with the Key
request.WebAuthenticationDetail.UserCredential.Password = ""; // Replace "XXX" with the Password
request.WebAuthenticationDetail.ParentCredential = new WebAuthenticationCredential();
request.WebAuthenticationDetail.ParentCredential.Key = ""; // Replace "XXX" with the Key
request.WebAuthenticationDetail.ParentCredential.Password = ""; // Replace "XXX"
request.ClientDetail = new ClientDetail();
request.ClientDetail.AccountNumber = ""; // Replace "XXX" with the client's account number
request.ClientDetail.MeterNumber = ""; // Replace "XXX" with the client's meter number
request.TransactionDetail = new TransactionDetail();
request.TransactionDetail.CustomerTransactionId = "***Track Request using VC#***"; //This is a reference field for the customer. Any value can be used and will be provided in the response.
request.Version = new VersionId();
// Tracking information
request.SelectionDetails = new TrackSelectionDetail[1] { new TrackSelectionDetail() };
request.SelectionDetails[0].PackageIdentifier = new TrackPackageIdentifier();
request.SelectionDetails[0].PackageIdentifier.Value = TrackNumberGlobal; //"787883551221" Replace "XXX" with tracking number or door tag
request.SelectionDetails[0].PackageIdentifier.Type = TrackIdentifierType.TRACKING_NUMBER_OR_DOORTAG;
request.ProcessingOptions = new TrackRequestProcessingOptionType[1];
request.ProcessingOptions[0] = TrackRequestProcessingOptionType.INCLUDE_DETAILED_SCANS;
return request;
}
private void TrackReplyy(TrackReply reply)
{
foreach (CompletedTrackDetail completedTrackDetail in reply.CompletedTrackDetails)
{
foreach (TrackDetail trackDetail in completedTrackDetail.TrackDetails)
{
SqlCommand cos = new SqlCommand();
cos.CommandText = "Update estatus_fedex SET estadofedex = #estado WHERE fedextracking = #track";
cos.Parameters.AddWithValue("#estado", trackDetail.StatusDetail.Description);
cos.Parameters.AddWithValue("#track", TrackNumberGlobal);
cos.CommandType = CommandType.Text;
cos.Connection = sqlConn;
cos.ExecuteNonQuery();
if (trackDetail.Events != null)
{
foreach (TrackEvent trackevent in trackDetail.Events)
{
if(trackevent.StatusExceptionCode != null)
{
SqlCommand cmd2 = new SqlCommand();
cmd2.CommandText = "UPDATE estatus_fedex SET ExcpetionCode = #codigo WHERE fedextracking = #param2";
cmd2.Parameters.AddWithValue("#codigo", trackevent.StatusExceptionCode);
cmd2.Parameters.AddWithValue("#param2", TrackNumberGlobal);
cmd2.CommandType = CommandType.Text;
cmd2.Connection = sqlConn;
cmd2.ExecuteNonQuery();
if (trackevent.TimestampSpecified)
{
SqlCommand insert = new SqlCommand();
insert.CommandText = "INSERT INTO EstatusFedexHistorial(FedexTracking,EstadoFedex_Hist,ExceptionCode_Hist,Tiempo_Hist,EventDescription) VALUES (#Track,#Estado,#Excepcion,#Tiempo,#Evento)";
insert.Parameters.AddWithValue("#Track", TrackNumberGlobal);
insert.Parameters.AddWithValue("#Estado", trackDetail.StatusDetail.Description);
insert.Parameters.AddWithValue("#Excepcion", trackevent.StatusExceptionCode);
insert.Parameters.AddWithValue("#Tiempo", trackevent.Timestamp);
insert.Parameters.AddWithValue("#Evento", trackevent.EventDescription);
insert.CommandType = CommandType.Text;
insert.Connection = sqlConn;
insert.ExecuteNonQuery();
}
}
else
{
if (trackevent.TimestampSpecified)
{
SqlCommand sqlc = new SqlCommand();
sqlc.CommandText = "INSERT INTO EstatusFedexHistorial(FedexTracking,EstadoFedex_Hist,Tiempo_Hist,EventDescription) VALUES (#Track,#Estado,#Tiempo,#Evento)";
sqlc.Parameters.AddWithValue("#Track", TrackNumberGlobal);
sqlc.Parameters.AddWithValue("#Estado", trackDetail.StatusDetail.Description);
sqlc.Parameters.AddWithValue("#Tiempo", trackevent.Timestamp);
sqlc.Parameters.AddWithValue("#Evento", trackevent.EventDescription);
sqlc.CommandType = CommandType.Text;
sqlc.Connection = sqlConn;
sqlc.ExecuteNonQuery();
}
}
}
}
}
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE EstatusFedexHistorial SET Manifiesto = #manifiesto WHERE FedexTracking = #track";
cmd.Parameters.AddWithValue("#manifiesto", manifiesto);
cmd.Parameters.AddWithValue("#track", TrackNumberGlobal);
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConn;
cmd.ExecuteNonQuery();
}
}

You need to do something like the following code where trackingNumbers is an array of tracking numbers.
request.SelectionDetails = new TrackSelectionDetail[trackingNumbers.Length];
for (int i = 0; i < trackingNumbers.Length; i++)
{
request.SelectionDetails[i] = new TrackSelectionDetail()
{
PackageIdentifier = new TrackPackageIdentifier
{
Value = trackingNumbers[i],
Type = TrackIdentifierType.TRACKING_NUMBER_OR_DOORTAG
}
};
}

Related

how to create an id to be shown in the text box based on selected dropdownlist

i would like to create an id generator based on their department selected from the dropdownlist. lets say my ddl has 3 departments (A,B,C) and when generating an id it will be A20181001 and then A20181002 upon submission but when i pick B from the ddl after sending A20181001 to the database, it will be B20181001.
so far i have created the code for the increment for the id without the departments. here is the code i did so far. (I used the date for today so the 20181001 is just an example):
void getMRF_No()
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
int mrf = 0;
int i;
string a;
//string x = Request.QueryString["BUnit"];
string mrfNo = "";
database db = new database();
string conn = dbe.BU();
SqlConnection connUser = new SqlConnection(conn);
SqlCommand cmd = connUser.CreateCommand();
SqlDataReader sdr = null;
string query = "SELECT TOP 1 MRF_NO FROM incMRF ORDER BY MRF_NO DESC";
connUser.Open();
cmd.CommandText = query;
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr.GetInt32(0).ToString();
}
if (mrfNo == "")
{
mrfNo = Convert.ToString(year) + "" + 00;
}
mrf += 0;
i = Convert.ToInt32(mrfNo) + 1;
a = i.ToString();
txtMRFNo.Text = a;
connUser.Close();
}
any help to improve this code will be helpful. thank you :)
EDIT:
here is the dropdown list code:
void SelectBU()
{
string database = dbe.BU ();
using (SqlConnection con = new SqlConnection(database))
{
con.Open();
string query = "select BUnit from BusinessUnit";
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
DataSet ds = new DataSet();
sda.Fill(ds, "BUnit");
ddlBu.DataSource = ds;
ddlBu.DataTextField = "BUnit";
ddlBu.DataValueField = "BUnit";
ddlBu.DataBind();
selectOption(ddlBu, "Select Dept");
}
con.Close();
}
}
EDIT2: I will state what im searching for here incase some doesnt know or understand. What i want is upon selecting a department from a dropdownlist, for example i picked A. the textbox show show A2018102201. if i select B it should show B2018102201 and if its C then c2018102201. and it will change its number once i submit it to a database and a new form loads. So if A2018102201 is already in the database, then the text shown in the text box will be A2018102202. BUT if i select B then the textbox will show B2018102201 since it does not exist in the database yet.
First you should get max ID, then increase the numeric part of your Id, and If this is a multi-user application, you have to lock your table, because it might create many ID duplication, Therefore I'm not recommend to create ID like this on c#, it is better to create a Sequence on SQL server. but I wrote this sample for you, just call it with proper value.
static string getMRF_No(string prefixCharFromDropDownList)
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
string mrfNo = "";
SqlConnection connUser = new SqlConnection("Server=130.185.76.162;Database=StackOverflow;UID=sa;PWD=$1#mssqlICW;connect timeout=10000");
SqlCommand cmd = new SqlCommand(
$"SELECT MAX(MRF_NO) as MaxID FROM incMRF where MRF_NO like '{prefixCharFromDropDownList}%'"
,connUser
);
connUser.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr["MaxID"].ToString();
}
if (mrfNo == "")
{
mrfNo = prefixCharFromDropDownList + year + "000";
}
else
{
mrfNo = prefixCharFromDropDownList + (long.Parse(mrfNo.Substring(1)) + 1).ToString().PadLeft(2);
}
sdr.Close();
cmd = new SqlCommand($"INSERT INTO incMRF (MRF_NO) values ('{mrfNo}')",connUser);
cmd.ExecuteNonQuery();
connUser.Close();
//txtMRFNo.Text = prefixCharFromDropDownList + i.ToString();
return mrfNo;
}
I call this method on a console application as test.
static void Main(string[] args)
{
// send dropdown (selected char) as prefix to method
var newAId = getMRF_No("A");
var newAnotherAId = getMRF_No("A");
var newBId = getMRF_No("B");
var newAnotherAId2 = getMRF_No("A");
Console.ReadKey();
}

c# Must declare the scalar variable "#Kundenname"

I am trying to get a little tool to work, for our little company.
This should fill data from a DataGridView into a SQL Server Standard database.
Reading out the SQL table is working fine, but I can't get the tool to write the values.
I get the error mentioned in the title.
Here the code:
var kdNummer = new SqlParameter("Kundennummer", SqlDbType.Int);
var kdName = new SqlParameter("Kundenname", SqlDbType.VarChar);
var kdMail = new SqlParameter("Kundenmail", SqlDbType.VarChar);
var kdTele = new SqlParameter("Telefon", SqlDbType.VarChar);
string kdquery = "INSERT INTO Kunden VALUES (#Kundennummer, #Kundenname, #Kundenmail, #Telefon)";
using (SqlConnection updatedb = new SqlConnection("Data Source=;Initial Catalog=updatedb;User ID=;Password="))
{
updatedb.Open();
for (int i = 0;i<dataGridView1.Rows.Count;i++)
{
using(SqlCommand NrDaten = new SqlCommand(kdquery, updatedb))
{
kdNummer.Value = dataGridView1.Rows[i].Cells["Kundennummer"].Value;
NrDaten.Parameters.Add(kdNummer);
NrDaten.ExecuteNonQuery();
}
using (SqlCommand NameDaten = new SqlCommand(kdquery, updatedb))
{
kdName.Value = dataGridView1.Rows[i].Cells["Kundenname"].Value;
NameDaten.Parameters.Add(kdName);
NameDaten.ExecuteNonQuery();
}
using (SqlCommand MailDaten = new SqlCommand(kdquery, updatedb))
{
kdMail.Value = dataGridView1.Rows[i].Cells["Kundenmail"].Value;
MailDaten.Parameters.Add(kdMail);
MailDaten.ExecuteNonQuery();
}
using (SqlCommand TeleDaten = new SqlCommand(kdquery, updatedb))
{
kdTele.Value = dataGridView1.Rows[i].Cells["Telefon"].Value;
TeleDaten.Parameters.Add(kdTele);
TeleDaten.ExecuteNonQuery();
}
}
updatedb.Close();
}
Your query requires 4 parameters, but you're always only setting one (also please note that in the SqlParameter you need to have the # sign as well). Thus you get an error about missing parameters. Your code should probably look like this:
var kdNummer = new SqlParameter("#Kundennummer", SqlDbType.Int);
var kdName = new SqlParameter("#Kundenname", SqlDbType.VarChar);
var kdMail = new SqlParameter("#Kundenmail", SqlDbType.VarChar);
var kdTele = new SqlParameter("#Telefon", SqlDbType.VarChar);
string kdquery = "INSERT INTO Kunden VALUES (#Kundennummer, #Kundenname, #Kundenmail, #Telefon)";
using (SqlConnection updatedb = new SqlConnection("..."))
{
updatedb.Open();
using (SqlCommand insert = new SqlCommand(kdquery, updatedb))
{
insert.Parameters.Add(kdName);
insert.Parameters.Add(kdNummer);
insert.Parameters.Add(kdMail);
insert.Parameters.Add(kdTele);
for (int i = 0;i<dataGridView1.Rows.Count;i++)
{
kdName.Value = dataGridView1.Rows[i].Cells["Kundenname"].Value;
kdNummer.Value = dataGridView1.Rows[i].Cells["Kundennummer"].Value;
kdMail.Value = dataGridView1.Rows[i].Cells["Kundenmail"].Value;
kdTele.Value = dataGridView1.Rows[i].Cells["Telefon"].Value;
insert.ExecuteNonQuery();
}
}
}
Or even shorter:
string kdquery = "INSERT INTO Kunden VALUES (#Kundennummer, #Kundenname, #Kundenmail, #Telefon)";
using (SqlConnection updatedb = new SqlConnection("..."))
{
updatedb.Open();
for (int i = 0;i<dataGridView1.Rows.Count;i++)
{
using (SqlCommand insert = new SqlCommand(kdquery, updatedb))
{
insert.Parameters.AddWithValue("#Kundenname", dataGridView1.Rows[i].Cells["Kundenname"].Value);
insert.Parameters.AddWithValue("#Kundennummer", dataGridView1.Rows[i].Cells["Kundennummer"].Value);
insert.Parameters.AddWithValue("#Kundenmail", dataGridView1.Rows[i].Cells["Kundenmail"].Value);
insert.Parameters.AddWithValue("#Telefon", dataGridView1.Rows[i].Cells["Telefon"].Value);
insert.ExecuteNonQuery();
}
}
}
EDIT: I modified the long version of the code for maximum re-use of instances. Otherwise you get the errors mentioned in your comment.

Repeated values in list in while(reader.Read()) {}

[WebMethod]
public List<reports> getMyReports( int user_id )
{
string cs = ConfigurationManager.ConnectionStrings["ReportDB"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("getAllReportsByUserID", con);
cmd.CommandType = CommandType.StoredProcedure;
List<reports> repers = new List<reports>();
//users[][] liser = new users[][];
SqlParameter user_id_parameter = new SqlParameter("#user_id", user_id);
cmd.Parameters.Add(user_id_parameter);
reports report = new reports();
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
report.id = Convert.ToInt32(reader["id"]);
report.title = reader["title"].ToString();
report.description = reader["description"].ToString();
report.anonymous = (bool)reader["anonymous"];
report.location = reader["location"].ToString();
report.status = reader["status"].ToString();
report.category = reader["category"].ToString();
report.date = (DateTime)reader["date"];
report.picture_url = reader["picture_url"].ToString();
report.admin_id = Convert.ToInt32(reader["admin_id"]);
repers.Add(report);
}
return repers;
}
}
I have the top function that calls the following stored procedure:
CREATE Proc [dbo].[getAllReportsByUserID]
#user_id int
as
Begin
Select
id,
title,
description,
anonymous,
location,
status,
category,
date,
picture_url,
admin_id
from reports
where user_id = #user_id
End
I have tested the procedure individually and it works fine. Yet, when I test the WebService created above I get a list with the last value duplicated along the whole list.
Can someone please help me figure out why do I get the same (last)value repeated over and over again?
By creating the report object before the loop and reusing it repeatedly, you insert a reference to that same object multiple times in your list.
You should create the report object inside your loop:
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
reports report = new reports();
report.id = Convert.ToInt32(reader["id"]);
report.title = reader["title"].ToString();
report.description = reader["description"].ToString();
report.anonymous = (bool)reader["anonymous"];
report.location = reader["location"].ToString();
report.status = reader["status"].ToString();
report.category = reader["category"].ToString();
report.date = (DateTime)reader["date"];
report.picture_url = reader["picture_url"].ToString();
report.admin_id = Convert.ToInt32(reader["admin_id"]);
repers.Add(report);
}
return repers;

ExecuteNonQuery requires the command to have a transaction error in my code

I get the following error on cmd.ExecuteNonQuery.
"ExecuteNonQuery requires the command to have a transaction when the
connection assigned to the command is in a pending local transaction.
The Transaction property of the command has not been initialized."
Here is my code:
//if (hdRefresh.Value.Length > done.Value.Length || done.Value == "1")
//{
// //Write Your Add Customer Code here > Response.Write("true")
// done.Value = hdRefresh.Value;
//}
//else
//{
// Response.Redirect("~/Cashier/BTBill.aspx");
// return;
//}
if (IsClosedToDay())
{
ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "Warning", "<script>alert('Day Closing has been Performed ')</script>", false);
return;
}
DateTime dateFeomDB = getdate();
// by atizaz
if (HDD.Value == "" || HDD.Value == null)
{
ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "Warning", "<script>alert('No Transaction Found')</script>", false);
return;
}
//
SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLCONN"].ToString());
Common.BillTransaction bill1 = new Common.BillTransaction();
ProcessUpdateBalandUnAuthBal insertBalance = new ProcessUpdateBalandUnAuthBal();
Common.Currency currencyy = new Common.Currency();
ProcessAuthorizeTokenByBillNo authorize = new ProcessAuthorizeTokenByBillNo();
BillTransaction bill = new BillTransaction();
scon.Open();
SqlTransaction sqlTrans = scon.BeginTransaction();
try
{
string strforxml = HDD.Value;
XmlDocument docXml = new XmlDocument();
#region Read In To Sender Controlls
#region Common Information
Contact con = new Contact();
con.Title = ddlTitle.SelectedItem.Text;
con.FirstName = TextBox1.Text.Trim();
con.LastName = TextBox9.Text.Trim();
con.ConTactNo = txtCell.Text == "" ? SqlString.Null : txtCell.Text;
con.Country = ddlCountry.SelectedItem.Text;
con.CustomerType = ddlCustomerType.SelectedItem.Text;
con.CustTypeID = int.Parse(ddlCustomerType.SelectedValue);
con.CountryID = Int32.Parse(ddlCountry.SelectedValue);
con.sqlTransaction = sqlTrans;
if (Scitytxt.Value != "")
{
try
{
con.City = Scitytxt.Value;
con.CityID = Int32.Parse(Scityval.Value);
}
catch (Exception)
{ }
}
else
{
con.City = SqlString.Null;// Scitytxt.Value;
con.CityID = SqlInt32.Null;// Int32.Parse(Scityval.Value);
con.Address = "";
}
//con.City = ddlCity.SelectedItem.Text;
//con.CityID = int.Parse(ddlCity.SelectedValue);
con.Address = TextBox10.Text;
#endregion
#region Check For NIC and Passport
if (txtNIC.Text != "" || txtPassport.Text != "")
{
SqlDataReader rdrsender;
if (txtNIC.Text != "")
{
con.NIC = txtNIC.Text;
}
else
{
con.NIC = SqlString.Null;
}
if (txtPassport.Text != "")
{
con.Passport = txtPassport.Text;
}
else
{
con.Passport = SqlString.Null;
}
ProcessSearchContactInContactInfo srchSender = new ProcessSearchContactInContactInfo();
srchSender.Contact = con;
srchSender.Invokewith5parameters();
rdrsender = srchSender.ResultSet;
#region If record Doesnot Exist In response of NIC Passport
if (!rdrsender.Read())
{
rdrsender.Close();
rdrsender.Dispose();
// con.sqlTransaction = sqlTrans;
ProcessAddContact InsertnewSenderInfo = new ProcessAddContact();
// InsertnewSenderInfo.sqlTransaction = sqlTrans;
InsertnewSenderInfo.Contact = con;
InsertnewSenderInfo.Invoke();
// sender1 = InsertnewSenderInfo.ResultSet;
// Sender_ID.Value = sender1[13].ToString();
}
#endregion
#region If Record Exists
else
{
con.CustomerID = Int32.Parse(rdrsender["Customer_ID"].ToString());
rdrsender.Close();
rdrsender.Dispose();
}
#endregion
}
#endregion
#region If Customer Donot Have NIC And/OR Passport
else// this executes when both Pasport and NIC are Null
{
con.NIC = SqlString.Null;
con.Passport = SqlString.Null;
ProcessAddContact InsertnewSenderInfo = new ProcessAddContact();
InsertnewSenderInfo.Contact = con;
InsertnewSenderInfo.Invoke();
DataSet ds = new DataSet();
int a = con.CustomerID;
StringReader inforeader = new StringReader("<CusTable><CusInfo><Relation_Type></Relation_Type><HusbandFather_Name></HusbandFather_Name><Address_Present></Address_Present><Address_Other></Address_Other><Phone_No_Office></Phone_No_Office><Cell_No></Cell_No><Fax_No></Fax_No><Date_Of_Birth></Date_Of_Birth><NTN_No></NTN_No><Nationality></Nationality><Occupation></Occupation><Relation_With_Financial_Institution></Relation_With_Financial_Institution><Other_Relation_With_Financial_Institution></Other_Relation_With_Financial_Institution><Business_Relation></Business_Relation></CusInfo></CusTable>");
ds.ReadXml(inforeader);
ds.GetXml();
SqlCommand cmd = new SqlCommand("update Contact_Info set CustInfo=" + ds.GetXml() + " WHERE Customer_ID=" + a + "", scon);
cmd.ExecuteNonQuery();
// sender1 = InsertnewSenderInfo.ResultSet;
// Sender_ID.Value = sender1[13].ToString();
}
tell me what is problem in my code and how to solve it.
You need to change this line
SqlCommand cmd = new SqlCommand("update Contact_Info set CustInfo=" + ds.GetXml() +
" WHERE Customer_ID=" + a + "", scon);
in this way
SqlCommand cmd = new SqlCommand("update Contact_Info set CustInfo=" + ds.GetXml() +
" WHERE Customer_ID=" + a + "", scon, sqlTrans);
The error message states exactly the problem.
Before code reaches that line you have opened a transaction and it is still open at the point of error
.....
scon.Open();
SqlTransaction sqlTrans = scon.BeginTransaction();
.....
Now, every SqlCommand executed when the connection has an opened transaction need to be informed of this. The transaction is not automatically set by the Framework.
You can use the SqlCommand constructor, as explained above, or you can set the cmd.Transaction property before executing the command.
Warning 1
The need to set the transaction for the current command is true even if you create the SqlCommand directly from the connection itself.
SqlCommand cmd = scon.CreateCommand();
cmd.Transaction = sqlTrans; // Required when inside a transaction
Warning 2
Avoid at all cost the use of string concatenation when using query text to update/insert/delete/select on a database. Use parameters. This will remove problems with strange or invalid characters and, most important, will prevent SqlInjection Attacks
string sqlText = "update Contact_Info set CustInfo=#info WHERE Customer_ID=#id";
SqlCommand cmd = new SqlCommand(sqlText, scon, sqlTrans);
cmd.Parameters.AddWithValue("#info", ds.GetXml());
cmd.Parameters.AddWithValue("#id",a);
cmd.ExecuteNonQuery();
Also, another recommendation is to NOT use AddWithValue, while handy, this method has many problems as explained in my answer here
You have started a transaction that is not commited before you called cmd.ExecuteNonQuery().
Just write down cmd.Transaction = sqlTrans; just before cmd.ExecuteNonQuery();
it will ensure that Now ExecuteNonQuery() will be executed in same transaction and also will be able to see all the modification done to database in the same transaction.
If you have this code:
SqlTransaction sqlTrans = scon.BeginTransaction();
then you should also have this:
cmd.Transaction = sqlTrans;
they work together.
For me dapper's ExecuteAsync takes 2 optional parameters and transaction wasn't being recognized so I had to name the parameters like this:
var result = await a_mConn.ExecuteAsync(sql: a_sSqlQuery,transaction: a_mTransaction);

How to implement Edit Feature in asp.net application?

Below 2 links give the preview of my sample application.
http://img812.imageshack.us/i/image1adl.jpg/ : shows mine sample application. All fields are self explanatory (if query, let me know)
http://img834.imageshack.us/i/image2vc.jpg/ : shows, when clicked the "Edit" button from the grid, the timings are shown correctly but the order gets disturbed. (See 7:00 coming on the top and then the timings list are seen).
My Questions
How to correct the timings problem? (Link # 2)
Code for "Edit" is below
protected void lnkEdit_Click(object sender, EventArgs e)
{
int imageid = Convert.ToInt16((sender as Button).CommandArgument);
DataSet ds = new DataSet();
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString;
string sql = #"SELECT * FROM Images WHERE IsDeleted=0 and Imageid='"+ imageid +"'";
SqlCommand sqlcommand = new SqlCommand(sql, sqlconn);
sqlcommand.CommandType = CommandType.Text;
sqlcommand.CommandText = sql;
SqlDataAdapter da = new SqlDataAdapter(sqlcommand);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
txtImageName.Text = ds.Tables[0].Rows[0].ItemArray[1].ToString();
chkIsActive.Checked = Convert.ToBoolean(ds.Tables[0].Rows[0]["IsActive"].ToString());
ddlStartTime.DataSource = ds;
ddlStartTime.DataTextField = ds.Tables[0].Columns["StartTime"].ColumnName.ToString();
ddlStartTime.DataValueField = ds.Tables[0].Columns["ImageId"].ColumnName.ToString();
ddlStartTime.DataBind();
ddlEndTime.DataSource = ds;
ddlEndTime.DataTextField = ds.Tables[0].Columns["EndTime"].ColumnName.ToString();
ddlEndTime.DataValueField = ds.Tables[0].Columns["ImageId"].ColumnName.ToString();
ddlEndTime.DataBind();
BindDropDownList();
IsEdit = true;
}
When i edit the existing record in the grid, i am getting the values, but the record is not being updated but added as a new record into db. I am aware that i am suppose to write update script. But where to write that?
Below the code is for the same;
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
try
{
string strImageName = txtImageName.Text.ToString();
int IsActive = 1;
if (chkIsActive.Checked)
IsActive = 1;
else
IsActive = 0;
string startDate = ddlStartTime.SelectedItem.Text;
string endDate = ddlEndTime.SelectedItem.Text;
if ( Convert.ToDateTime(endDate) - Convert.ToDateTime(startDate) > new TimeSpan(2, 0, 0) || Convert.ToDateTime(endDate)- Convert.ToDateTime(startDate) < new TimeSpan(2,0,0))
{
//Response.Write(#"<script language='javascript'> alert('Difference between Start Time and End Time is 2 hours'); </script> ");
lblHours.Visible = true;
lblHours.Text = "Difference between Start Time and End Time should be 2 hours";
return;
}
if (checkConflictTime())
{
lblMessage.Visible = true;
lblMessage.Text = "Time Conflict";
return;
}
//if (checkTimeBetween())
//{
//}
if (fuFileUpload.PostedFile != null && fuFileUpload.PostedFile.FileName != "")
{
lblHours.Visible = false;
byte[] imageSize = new Byte[fuFileUpload.PostedFile.ContentLength];
HttpPostedFile uploadedImage = fuFileUpload.PostedFile;
uploadedImage.InputStream.Read(imageSize, 0, (int)fuFileUpload.PostedFile.ContentLength);
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString;
SqlCommand cmd = new SqlCommand();
if (IsEdit == false)
{
cmd.CommandText = "Insert into Images(FileName,FileContent,IsDeleted,IsActive,StartTime,EndTime) values (#img_name, #img_content,#IsDeleted,#IsActive,#StartTime,#EndTime)";
}
else
{
cmd.CommandText = "Update Images set FileName=#img_name, FileContent=#img_content, IsDeleted= #IsDeleted,IsActive= #IsActive, StartTime=#StartTime,EndTime=#EndTime";
}
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlconn;
SqlParameter ImageName = new SqlParameter("#img_name", SqlDbType.NVarChar, 50);
ImageName.Value = strImageName.ToString();
cmd.Parameters.Add(ImageName);
SqlParameter ActualImage = new SqlParameter("#img_content", SqlDbType.VarBinary);
ActualImage.Value = imageSize;
cmd.Parameters.Add(ActualImage);
SqlParameter DeletedImage = new SqlParameter("#IsDeleted", SqlDbType.Bit);
DeletedImage.Value = 0;
cmd.Parameters.Add(DeletedImage);
SqlParameter IsActiveCheck = new SqlParameter("#IsActive", SqlDbType.Bit);
IsActiveCheck.Value = IsActive;
cmd.Parameters.Add(IsActiveCheck);
SqlParameter StartDate = new SqlParameter("#StartTime", SqlDbType.NVarChar, 100);
StartDate.Value = startDate;
cmd.Parameters.Add(StartDate);
SqlParameter EndDate = new SqlParameter("#EndTime", SqlDbType.NVarChar, 100);
EndDate.Value = endDate;
cmd.Parameters.Add(EndDate);
sqlconn.Open();
int result = cmd.ExecuteNonQuery();
sqlconn.Close();
if (result > 0)
{
lblMessage.Visible = true;
lblMessage.Text = "File Uploaded!";
gvImages.DataBind();
}
}
}
catch (Exception ex)
{
lblMessage.Text = ex.ToString();
}
}
}
Please help!
Where do you define Bool/Bolean IsEdit? I think its value is reset on page postback, that's why it is always false and the record is being inserted. I would suggest you to use a hidden field to track this and set its value there and check the value upon insert/updating. Finally it will be something like...
if (ds.Tables[0].Rows.Count > 0)
{
//your code
hiddenField.Value = "true"; // you can set default value to false
}
and then after
if (hiddenField.Value == "false")
{
cmd.CommandText = "Insert into Images(FileName,FileContent,IsDeleted,IsActive,StartTime,EndTime) values (#img_name, #img_content,#IsDeleted,#IsActive,#StartTime,#EndTime)";
}
else
{
cmd.CommandText = "Update Images set FileName=#img_name, FileContent=#img_content, IsDeleted= #IsDeleted,IsActive= #IsActive, StartTime=#StartTime,EndTime=#EndTime";
}

Categories

Resources