I have a task to upload the excel file and also check update if the same record found, I have uploaded the excel file in the database which is working fine.
Now, I have to check if the same records inserted then update otherwise insert the new records, I have two table first I am inserting the records in the temp table then after that I am checking the temp table with the original table , if records matches then update else insert, I am using nested for loop to check the records
my loop works fine and insert the top two records, but when it comes to the 3rd record then insert it multiple times and on 4th again multiple times,Kindly guide me what i am doing wrong
here is my code so far
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
int id;
string contactPerson;
string designation;
string company;
string contact;
string emailaddress;
string city;
string region;
string industry;
string division;
string mobile;
string address;
string path = Path.GetFileName(FileUpload1.FileName);
path = path.Replace(" ", "");
FileUpload1.SaveAs(Server.MapPath("~/uploadExcel/") + FileUpload1.FileName);
String ExcelPath = Server.MapPath("~/uploadExcel/") + FileUpload1.FileName;
OleDbConnection mycon = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + ExcelPath + "; Extended Properties=Excel 8.0; Persist Security Info = False");
mycon.Open();
DeleteRecords();
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", mycon);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr[0].ToString() != "")
{
// Response.Write("<br/>"+dr[0].ToString());
id = Convert.ToInt32(dr[0].ToString());
contactPerson = dr[1].ToString();
designation = dr[2].ToString();
company = dr[3].ToString();
emailaddress = dr[4].ToString();
contact = dr[5].ToString();
mobile = dr[6].ToString();
address = dr[7].ToString();
city = dr[8].ToString();
region = dr[9].ToString();
industry = dr[10].ToString();
division = dr[11].ToString();
InsertTemp(id, contactPerson, designation, company, emailaddress, contact,
mobile, address, city, region, industry, division);
//InsertOrignal(id, contactPerson, designation, company, emailaddress, contact,
// mobile, address, city, region, industry, division);
}
else
{
break;
}
String myconn = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True";
SqlConnection conn = new SqlConnection(myconn);
conn.Open();
DataTable dt_temp = new DataTable();
DataTable dt_orignal = new DataTable();
SqlDataAdapter da_temp = new SqlDataAdapter("select * from Tbl_ExcelData order by id asc", conn);
SqlDataAdapter da_orignal = new SqlDataAdapter("select * from Tbl_ExcelUploadData order by id asc", conn);
da_temp.Fill(dt_temp);
da_orignal.Fill(dt_orignal);
if (dt_orignal.Rows.Count > 0)
{
for (int i = 0; i < dt_temp.Rows.Count; i++)
{
for (int j = 0; j < dt_orignal.Rows.Count; j++)
{
if (dt_temp.Rows[i]["email"].ToString() == dt_orignal.Rows[j]["email"].ToString())
{
//Update Record if required
}
else
{
//insert record into orignal table
InsertOrignal(id, contactPerson, designation, company, emailaddress, contact, mobile, address, city, region, industry, division);
}
}
}
}
else
{
InsertOrignal(id, contactPerson, designation, company, emailaddress, contact, mobile, address, city, region, industry, division);
}
}
lblmessage.Text = "Data Has Been Updated Successfully";
mycon.Close();
File.Delete(ExcelPath);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void InsertTemp(int id, String contactPerson, String designation, String company, String emailaddress,
String contact, String mobile, String address,String city,String region,String industry,
String division)
{
//String mycon = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True";
SqlConnection con = new SqlConnection(mycon);
con.Open();
string query = "insert into Tbl_ExcelData (id,contactperson,designation,company,email,contact,mobile,address,city,region,industry,division) values('" + id + "','" + contactPerson + "', '" + designation + "','" + company + "','" + emailaddress + "','" + contact + "','" + mobile + "','" + address + "','" + city + "','" + region + "','" + industry + "','" + division + "')";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
private void InsertOrignal(int id, String contactPerson, String designation, String company, String emailaddress,
String contact, String mobile, String address, String city, String region, String industry,
String division)
{
//String mycon = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True";
SqlConnection con = new SqlConnection(mycon);
con.Open();
string query = "insert into Tbl_ExcelUploadData (id,contactperson,designation,company,email,contact,mobile,address,city,region,industry,division) values('" + id + "','" + contactPerson + "', '" + designation + "','" + company + "','" + emailaddress + "','" + contact + "','" + mobile + "','" + address + "','" + city + "','" + region + "','" + industry + "','" + division + "')";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
private void DeleteRecords()
{
SqlConnection con = new SqlConnection(mycon);
con.Open();
string query = "Delete from Tbl_ExcelData";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
}
If you have the Temporary table just to check if the row exists in an Original table, then it is not a good practice.
Directly check if the row exists in your original table with the Primary key id or any Unique Key and then decide whether to Insert or Update.
One way to do this,
while (dr.Read())
{
if (dr[0].ToString() != "")
{
id = Convert.ToInt32(dr[0].ToString()); //add other columns which needs to be fetched from Excel
string query = "select count(1) from Tbl_ExcelData where id=?"; //To check if the row already exsits
SqlCommand cmd = new SqlCommand(con);
cmd.CommandText = query;
cmd.Paramaters.Add(new SqlParameter(1, id));
int count = (Int32) cmd.ExecuteScalar();
if (count > 0) //which means row already exists
{
//Your update code goes here
}
else
{
InsertOrignal(id, contactPerson, designation, company, emailaddress, contact, mobile, address, city, region, industry, division);
}
}
After comments, here is a basic idea. One way you can load your excel data into DataTable and loop through it and decide for Upsert. Remember to learn about MultipleActiveResultSets
try
{
string ExcelPath = Server.MapPath("~/uploadExcel/") + FileUpload1.FileName;
string _oleDBConnectionString = string.Format("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0}; Extended Properties=Excel 8.0; Persist Security Info = False", ExcelPath);
string _sqlConnectionString = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True; MultipleActiveResultSets=true;"; //enable MultipleActiveResultSets as you'll be opening a nested SqlConnection
string _excelQuery = "select * from [Sheet1$]";
DataTable tempDataTable = null;
using (var conn = new OleDbConnection(_oleDBConnectionString)) //This code loads your excel data into data table
{
conn.Open();
using (var cmd = new OleDbCommand(_excelQuery, conn))
{
using (var reader = cmd.ExecuteReader())
{
var dt = new DataTable();
dt.Load(reader); //this will load your excel data into DataTable
tempDataTable = dt;
}
}
}
using(var sqlConn = new SqlConnection(_sqlConnectionString)) //this code will connect to sql db and upsert based on the id from the excel
{
sqlConn.Open();
string countQuery = "select count(1) from Tbl_ExcelData where id=:id";
using(var cmd = new SqlCommand(countQuery, sqlConn))
{
var param = new SqlParameter("#id");
foreach (DataRow row in tempDataTable.Rows) //this will loop through the DataTable rows, the actual rows from Excel which are loaded into DataTable
{
var id = row["id"]; //get the id column from the excel
var contactPerson = row["contactPerson"]; //get the contactPerson column from the excel
cmd.Paramaters["#id"] = id;
int count = (int) cmd.ExecuteScalar();
if (count) //row already exist in original table
{
//update the row in original table
}
else
{
//insert the row in original table
InsertOriginal(sqlConn, id, contactPerson);
}
}
}
}
}
catch(Exception ex)
{
}
function InsertOriginal(SqlConnection conn, int id, string contactPerson)
{
string insertQuery = "insert into Tbl_ExcelUploadData (id,contactpersonn) values('#id','#contactPerson');
using(var cmd = new SqlCommand(insertQuery, conn))
{
cmd.Parameters.Add(new SqlParameter("#id",id));
cmd.Parameters.Add(new SqlParameter("#contactPerson", contactPerson));
cmd.ExecuteNonQuery();
}
}
Also, this is not a tested code. Feel free to comment back.
I set the code for sending the photo to telegram, first is working on my localhost, after Update the telegram.bot package to ver 9.0.0 and publish to sever dosen't work at localhost and server.
i use the try/catch for sending Text instead of photo and now they not working, it is mean the Try block is working but it can't effect.
if (offerListDetail != null)
{
StringBuilder botTextA2 = new StringBuilder();
StringBuilder botTextB2 = new StringBuilder();
string remoteImgPath = offerListDetail.OFL_OfferImageUrl;
Uri remoteImgPathUri = new Uri(remoteImgPath);
string remoteImgPathWithoutQuery = remoteImgPathUri.GetLeftPart(UriPartial.Path);
string fileName = Path.GetFileName(remoteImgPathWithoutQuery);
string localPath = Server.MapPath("~/Images/telegram/"); //AppDomain.CurrentDomain.BaseDirectory + "Images/telegram/" + fileName;
WebClient webClient = new WebClient();
webClient.DownloadFile(remoteImgPath, localPath + fileName);
var botphoto = new FileToSend()
{
Content = OpenFile(localPath + fileName),
Filename = fileName
};
//var botClient = new Telegram.Bot.Api("157612108:AAFr4y7WWT32xX41EMOVkmEW19pIgcHImv4"); // استانبولیار
var botClient = new Telegram.Bot.Api("186221188:AAHrihjOH7__4vlF0DCNWLEzYQ3p3ORO0_k"); // ربات ری را
try
{
botTextA2.AppendLine("🔍 http://order.reera.ir/offers.aspx?offer=" + offerListDetail.OFL_ID);
botTextA2.AppendLine("📢 " + offerListDetail.OFL_OfferName);
botTextA2.AppendLine("📌 " + offerListDetail.brn_Name);
botTextA2.AppendLine("🕔 مهلت " + offerListDetail.remainday + " روز");
botTextA2.AppendLine("📦 سفارش در http://order.reera.ir");
botTextA2.AppendLine("📝 یا تلگرام #reerabrand");
string botTextA = botTextA2.ToString().Replace(Environment.NewLine, "\n");
botClient.SendPhoto("#istanbulyar", botphoto, "ddd");//botTextA);
botClient.SendPhoto("#reera", botphoto, "ddd");//botTextA);
}
catch
{
botTextB2.AppendLine(offerListDetail.OFL_OfferImageUrl);
botTextB2.AppendLine("*********************************");
botTextB2.AppendLine("📢<b> حراجی " + offerListDetail.OFL_OfferName + "</b> ");
botTextB2.AppendLine("📌<i> توسط وبسایت " + offerListDetail.brn_Name + "</i> ");
botTextB2.AppendLine("🕔 <b>مهلت خرید تا " + offerListDetail.remainday + " روز دیگر</b> ");
botTextB2.AppendLine("🔍 <a href='http://order.reera.ir/offers.aspx?offer=" + offerListDetail.OFL_ID + "'> مشاهده بوتیک </a> ");
botTextB2.AppendLine("");
botTextB2.AppendLine("📦 سفارش در http://order.reera.ir");
botTextB2.AppendLine("📝 یا تلگرام #reerabrand");
string botTextB = botTextB2.ToString().Replace(Environment.NewLine, "\n");
botClient.SendTextMessage("#istanbulyar", botTextB, parseMode: ParseMode.Html);
botClient.SendTextMessage("#reera", botTextB, disableNotification: true, parseMode: ParseMode.Html);
}
}
read picture with stream
example
string pic = "نام عکس مورد نظر";
string yourpath = Environment.CurrentDirectory + #"\Pic\"+pic;
FileStream stream = new FileStream(yourpath, FileMode.Open, FileAccess.Read);
FileToSend fs = new FileToSend("photo3.jpg",stream);
bot.MakeRequestAsync(new SendPhoto(update.Message.Chat.Id, fs)).Wait();
I use yahoo oAuth1 and yahoo API to get contact list from yahoo server.
Here the code that I use to get contacts:
private void RetriveContacts()
{
OAuthBase oauth = new OAuthBase();
Uri uri = new Uri("https://social.yahooapis.com/v1/user/" + (string)Session["xoauth_yahoo_guid"] + "/contacts?format=XML");
string nonce = oauth.GenerateNonce();
string timeStamp = oauth.GenerateTimeStamp();
string normalizedUrl;
string normalizedRequestParameters;
string sig = oauth.GenerateSignature(uri, ConsumerKey, ConsumerSecret,
(string)Session["oauth_token"], (string)Session["oauth_token_secret"], "GET",
timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1,
out normalizedUrl, out normalizedRequestParameters);
StringBuilder sbGetContacts = new StringBuilder(uri.ToString());
try
{
string returnStr = string.Empty;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sbGetContacts.ToString());
req.Method = "GET";
string authHeader = "Authorization: OAuth " +
"realm=\"yahooapis.com\"" +
",oauth_consumer_key=\"" + ConsumerKey + "\"" +
",oauth_nonce=\"" + nonce + "\"" +
",oauth_signature_method=\"HMAC-SHA1\"" +
",oauth_timestamp=\"" + timeStamp + "\"" +
",oauth_token=\"" + (string)Session["oauth_token"] + "\"" +
",oauth_version=\"1.0\"" +
",oauth_signature=\"" + HttpUtility.UrlEncode(sig) + "\"";
req.Headers.Add(authHeader);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader streamReader = new StreamReader(res.GetResponseStream());
returnStr = streamReader.ReadToEnd();
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(returnStr);
XmlNodeList elemList = xmldoc.DocumentElement.GetElementsByTagName("fields");
List<string> emails = new List<string>();
for (int i = 0; i < elemList.Count; i++)
{
if (elemList[i].ChildNodes[1].InnerText == "email")
emails.Add(elemList[i].ChildNodes[2].InnerText);
//Response.Write(elemList[i].ChildNodes[2].InnerText + "<br/>");
}
}
catch (WebException ex)
{
//Response.Write(ex.Message);
Response.Write("<br/>" + ex.Message + "</br>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
Response.Write("<br/>length: " + ex.Source.Length.ToString());
Response.Write("<br/>stack trace: " + ex.StackTrace);
Response.Write("<br/>status: " + ex.Status.ToString());
HttpWebResponse res = (HttpWebResponse)ex.Response;
int code = Convert.ToInt32(res.StatusCode);
Response.Write("<br/>Status Code: (" + code.ToString() + ") " + res.StatusCode.ToString());
Response.Write("<br/>Status Description: " + res.StatusDescription);
if (ex.InnerException != null)
{
Response.Write("<br/>innerexception: " + ex.InnerException.Message);
}
if (ex.Source.Length > 0)
Response.Write("<br/>source: " + ex.Source.ToString());
if (res != null)
{
for (int i = 0; i < res.Headers.Count; i++)
{
Response.Write("<br/>headers: " + i.ToString() + ": " + res.Headers[i]);
}
}
}
}
But in this row:
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
I get this Error:
Any why I get this error and how to fix it?
Thank you in advance.
Try setting the Accept header in your HTTP request. Something like this:
Accept: text/html,*/*;q=0.9
HTTP 406 indicates that either this header is expected but missing, or that it was present but did not specify a Content-Type that is compatible with the resource (e.g. asking for Accept: text/html when requesting a JPEG image.)
See also the Accept-Charset, Accept-Encoding, and Accept-Language headers which can also trigger this status code.
My issue had to do with format=XML > changing it to format=json and changing both the accept and content type headers to appliocation/json, returns the emails which i was trying to GET
Get Yahoo Contact List in C# application
I am downloading data from yahoo stocks using the Web.DownloadString(); the site will have multiply users so I need to have the client send the download request rather than the server to avoid getting blocked from sending too many request from the servers Ip address. I can't find a way to run it on the client side and am looking for assistance making it run from client rather than server.
below is a poorly formatted function that I plan to clean up that I am using right now
I plan only do use the part required to get the data run client side and the rest run server I have just yet to clean up my code.
Public void DownloadData()
{
string csvData = null;
string month1 = Convert.ToString(DropDownList1.SelectedIndex);
string month2 = Convert.ToString(DropDownList2.SelectedIndex);
string Temp = "http://ichart.finance.yahoo.com/table.csv?s=" + SymbolName.Text + "&d=" + month2 + "&e=" + TextBox3.Text + "&f=" + TextBox4.Text + "&g=d&a=" + month1 + "&b=" + TextBox1.Text + "&c=" + TextBox2.Text + "&ignore=.csv";
string FileRead;
List<string> Remove1 = new List<string>();
string path = System.AppDomain.CurrentDomain.BaseDirectory;
using (WebClient web = new WebClient())
{
try
{
csvData = web.DownloadString(Temp);
}
catch
{
}
}
if (csvData != null && csvData != "")
{
File.WriteAllText(path + "\\MyTest.txt", csvData);
}
System.IO.StreamReader file = new System.IO.StreamReader(path + "\\MyTest.txt");
while ((FileRead = file.ReadLine()) != null) //reads from file
{
Remove1.Add(FileRead);
}
file.Close();
csvData = csvData.Replace("Date,Open,High,Low,Close,Volume,Adj Close", "");
List<stock> prices = YahooFinance.Parse(csvData);
double Lowest = 0;
foreach (stock price in prices) // finds lowest value to addjust priceing
{
if (Lowest == 0)
{
Lowest = Convert.ToDouble(price.low);
}
if (Lowest > Convert.ToDouble(price.low))
{
Lowest = Convert.ToDouble(price.low);
}
}
// new double[] { Convert.ToDouble(price.low), Convert.ToDouble(price.high), Convert.ToDouble(price.Open), Convert.ToDouble(price.close) }
Chart1.ChartAreas[0].AxisX.Interval = 2;
Chart2.ChartAreas[0].AxisX.Interval = 2;
Chart1.ChartAreas[0].AxisX.Maximum = prices.Count + 20;
Chart1.ChartAreas[0].AxisY.Minimum = Lowest - 3;
foreach (stock price in prices)
{
Chart1.Series[0].Points.AddXY(price.date, Convert.ToDouble(price.low), Convert.ToDouble(price.high), Convert.ToDouble(price.Open), Convert.ToDouble(price.close));
Chart2.Series[0].Points.AddXY(price.date, Convert.ToDouble(price.Volume));
}
}
`
string s1 = DropDownList1.SelectedItem.Text;
string s2 = DropDownList2.SelectedItem.Text;
string sql1 = ("Select Case_Type_Value FROM Case_Type where Case_Type_Text IS'" + s1 + "' ");
string sql2 = ("Select Case_Status_Value FROM Case_Status where Case_Status_Text IS'" + s2 + "' ");
int v1 = Int32.Parse(sql1);
int v2 = Int32.Parse(sql2);
Hi
I am getting error "Input string was not in a correct format" on line:
int v1 = Int32.Parse(sql1);
Of course you are getting an error!
See you are not fetching result from database. Instead you are assigning your query to sql1 and trying to convert it into integer. See below in your code you are actually assigning whole select query to the string sql1.You can try this one :
string sql1 = ("Select Case_Type_Value FROM Case_Type where Case_Type_Text IS'" + s1 + "' ");
string sql2 = ("Select Case_Status_Value FROM Case_Status where Case_Status_Text IS'" + s2 + "' ");
sqlconnection con = new SqlConnection("Blah Blah")
Sqlcommand cmd = new sqlcommand(sql1,con);
con.open();
int v1 = Convert.toint32(cmd.ExecuteScalar());
con.close();
con.Dispose();
Which type you receive when you
string sql1 = ("Select Case_Type_Value FROM Case_Type where Case_Type_Text IS'" + s1 + "' ");
string sql2 = ("Select Case_Status_Value FROM Case_Status where Case_Status_Text IS'" + s2 + "' ");
?
you can do one thing just take column called Group like you have taken in the Usertype.
Take a session variable and capture username in it.Then get the group to which the username belongs. Based on the role redirect the user to his corresponding page.
Session["unmae"]=txtuname.text;
string username=Session["unmae"].Text;
string group=obj.getgroup(username);
if(group=="Admin")
{
Response.Redirect("1.aspx");
}
else if(group=="User")
{
Response.Redirect("2.aspx");
}
else
{
Response.Redirect("error.aspx");
}
Hope this helps.
Happy coding