Updating row in Gridview not saving to my database - c#

I am trying to update the row in my GridView to my SQL table. But when I change some information and click on update it then does nothing, doesn't save it to the database?
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["PROJECTS"].ConnectionString);
DataTable dt = new DataTable();
con1.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand($"SELECT id, " +
$"Date, " +
$"Number, " +
$"CustomerName, " +
$"AccpacPcNo, " +
$"CRMCaseNo, " +
$"ProjectDetails, " +
$"TechnicalResourceAssigned," +
$"ProjectPhase, " +
$"WorkHours, " +
$"PlannedCompletionDate, " +
$"Comments FROM tbl_projects WHERE ID={Request["id"]}", con1);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
txtProjectDate.Text = (myReader["Date"].ToString());
txtProjectNumber.Text = (myReader["Number"].ToString());
txtProjectCustomerName.Text = (myReader["CustomerName"].ToString());
txtProjectAccpacNumber.Text = (myReader["AccpacPcNo"].ToString());
txtProjectCRMCaseNumber.Text = (myReader["CRMCaseNo"].ToString());
txtProjectDetails.Text = (myReader["ProjectDetails"].ToString());
txtProjectTechnicalResourceAssigned.Text = (myReader["TechnicalResourceAssigned"].ToString());
txtProjectPhase.SelectedItem.Text = (myReader["ProjectPhase"].ToString());
txtProjectWorkHours.Text = (myReader["WorkHours"].ToString());
txtProjectPlannedCompletionDate.Text = (myReader["PlannedCompletionDate"].ToString());
txtProjectComments.Text = (myReader["Comments"].ToString());
}
con1.Close();
}
protected void BtnUpdate_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["PROJECTS"].ConnectionString);
SqlCommand cmd = new SqlCommand($"UPDATE tbl_projects SET [Date] = #Date, " +
$"[Number] = #Number, " +
$"[CustomerName] = #CustomerName, " +
$"[AccpacPcNo] = #AccpacPcNo, " +
$"[CRMCaseNo] = #CRMCaseNo, " +
$"[ProjectDetails] = #ProjectDetails, " +
$"[TechnicalResourceAssigned] = #TechnicalResourceAssigned, " +
$"[ProjectPhase] = #ProjectPhase, " +
$"[WorkHours] = #WorkHours, " +
$"[PlannedCompletionDate] = #PlannedCompletionDate, " +
$"[Comments] = #Comments FROM tbl_Projects WHERE ID = {Request["id"]}", con);
con.Open();
cmd.Parameters.AddWithValue("#Date", txtProjectDate.Text);
cmd.Parameters.AddWithValue("#Number", txtProjectNumber.Text);
cmd.Parameters.AddWithValue("#CustomerName", txtProjectCustomerName.Text);
cmd.Parameters.AddWithValue("#AccpacPcNo", txtProjectAccpacNumber.Text);
cmd.Parameters.AddWithValue("#CRMCaseNo", txtProjectCRMCaseNumber.Text);
cmd.Parameters.AddWithValue("#ProjectDetails", txtProjectDetails.Text);
cmd.Parameters.AddWithValue("#TechnicalResourceAssigned", txtProjectTechnicalResourceAssigned.Text);
cmd.Parameters.AddWithValue("#ProjectPhase", txtProjectPhase.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#WorkHours", txtProjectWorkHours.Text);
cmd.Parameters.AddWithValue("#PlannedCompletionDate", txtProjectPlannedCompletionDate.Text);
cmd.Parameters.AddWithValue("#Comments", txtProjectComments.Text);
cmd.ExecuteNonQuery();
con.Close();
}
I am not sure what I am doing wrong? It displays the correct information when I click on the row to update but just doesn't want to update. I get no error messages or anything?

check this create gloabal variable that store Request ID then use ID in other Events or function.
private static string _REQID = "";
protected void Page_Load(object sender, EventArgs e)
{
_REQID = Request["id"];
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["PROJECTS"].ConnectionString);
DataTable dt = new DataTable();
con1.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand($"SELECT id, " +
$"Date, " +
$"Number, " +
$"CustomerName, " +
$"AccpacPcNo, " +
$"CRMCaseNo, " +
$"ProjectDetails, " +
$"TechnicalResourceAssigned," +
$"ProjectPhase, " +
$"WorkHours, " +
$"PlannedCompletionDate, " +
$"Comments FROM tbl_projects WHERE ID=#ReqID", con1);
myCommand.Parameters.AddWithValue("#ReqID", _REQID );
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
txtProjectDate.Text = (myReader["Date"].ToString());
txtProjectNumber.Text = (myReader["Number"].ToString());
txtProjectCustomerName.Text = (myReader["CustomerName"].ToString());
txtProjectAccpacNumber.Text = (myReader["AccpacPcNo"].ToString());
txtProjectCRMCaseNumber.Text = (myReader["CRMCaseNo"].ToString());
txtProjectDetails.Text = (myReader["ProjectDetails"].ToString());
txtProjectTechnicalResourceAssigned.Text = (myReader["TechnicalResourceAssigned"].ToString());
txtProjectPhase.SelectedItem.Text = (myReader["ProjectPhase"].ToString());
txtProjectWorkHours.Text = (myReader["WorkHours"].ToString());
txtProjectPlannedCompletionDate.Text = (myReader["PlannedCompletionDate"].ToString());
txtProjectComments.Text = (myReader["Comments"].ToString());
}
con1.Close();
}
protected void BtnUpdate_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["PROJECTS"].ConnectionString);
SqlCommand cmd = new SqlCommand($"UPDATE tbl_projects SET [Date] = #Date, " +
$"[Number] = #Number, " +
$"[CustomerName] = #CustomerName, " +
$"[AccpacPcNo] = #AccpacPcNo, " +
$"[CRMCaseNo] = #CRMCaseNo, " +
$"[ProjectDetails] = #ProjectDetails, " +
$"[TechnicalResourceAssigned] = #TechnicalResourceAssigned, " +
$"[ProjectPhase] = #ProjectPhase, " +
$"[WorkHours] = #WorkHours, " +
$"[PlannedCompletionDate] = #PlannedCompletionDate, " +
$"[Comments] = #Comments FROM tbl_Projects WHERE ID = #ReqID", con);
con.Open();
cmd.Parameters.AddWithValue("#Date", txtProjectDate.Text);
cmd.Parameters.AddWithValue("#Number", txtProjectNumber.Text);
cmd.Parameters.AddWithValue("#CustomerName", txtProjectCustomerName.Text);
cmd.Parameters.AddWithValue("#AccpacPcNo", txtProjectAccpacNumber.Text);
cmd.Parameters.AddWithValue("#CRMCaseNo", txtProjectCRMCaseNumber.Text);
cmd.Parameters.AddWithValue("#ProjectDetails", txtProjectDetails.Text);
cmd.Parameters.AddWithValue("#TechnicalResourceAssigned", txtProjectTechnicalResourceAssigned.Text);
cmd.Parameters.AddWithValue("#ProjectPhase", txtProjectPhase.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#WorkHours", txtProjectWorkHours.Text);
cmd.Parameters.AddWithValue("#PlannedCompletionDate", txtProjectPlannedCompletionDate.Text);
cmd.Parameters.AddWithValue("#Comments", txtProjectComments.Text);
cmd.Parameters.AddWithValue("#ReqID", _REQID);
cmd.ExecuteNonQuery();
con.Close();
}

Related

Reading access database

I have written code to return values based on a search box however at times, the value entered into the search box can apply to several records within an MSAccess DB.
Is there a way where I can scroll through the records that apply to the value in the search box by using a button?
public void LoopThroughRecs(OleDbDataReader Data)
{
Data.Read();
{
FirstName.Text = Data["Initial"].ToString();
LastName.Text = Data["Surname"].ToString();
Address1.Text = Data["Address 1"].ToString();
Address2.Text = Data["Address 2"].ToString();
Address3.Text = Data["Address 3"].ToString();
TownCity.Text = Data["Post Town"].ToString();
PostCode.Text = Data["Post Code"].ToString();
Telephone.Text = Data["Telephone"].ToString();
LstSvcDat.Text = Data["LastService"].ToString();
BoilerMan.Text = Data["Manufacturer"].ToString();
BoilerMod.Text = Data["Model"].ToString();
}
Data.Close();
}
public void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=BoilerSvc_be.mdb";
try
{
conn.Open();
OleDbCommand command = new OleDbCommand("SELECT CustCode,Initial,Surname,[Address 1],[Address 2],[Address 3],[Post Town],[Post Code],Telephone,Equipment.CustID AS CustID,Equipment.Manufacturer AS Manufacturer,Equipment.Model AS Model,Equipment.LastService AS LastService FROM Contacts LEFT OUTER JOIN Equipment ON Equipment.CustID = Contacts.CustID WHERE Archived = 0 AND (CustCode = '" + textBox12.Text + "' OR Initial = '" + textBox12.Text + "' OR Surname = '" + textBox12.Text + "' OR Initial = '" + textBox12.Text + "' OR [Post Town] = '" + textBox12.Text + "' OR [Post Code] = '" + textBox12 + "')", conn);
OleDbDataReader Data = command.ExecuteReader();
LoopThroughRecs(Data);
}
finally
{
conn.Close();
}
}

Local database not refreshing after updating data from C#

I'm working with a local database, and it works well, the whole app. The problem is that I'm facing with some annoying things. If I update, or add new data to my local database, I have to close the whole app and start it again so I can see the new data I have entered. Why is it not refreshing and how can I solve it?
Here is how I add data:
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
label5.Text = "1";
}
else
{
label5.Text = "0";
}
if (radioButton2.Checked)
{
label5.Text = "2";
}
if (textBox1.Text.Length == 0)
{
textBox1.Text = "Fara";
}
if (textBox2.Text.Length == 0)
{
textBox2.Text = "0";
}
if (textBox3.Text.Length == 0)
{
textBox3.Text = "0";
}
if (numeTextBox.TextLength != 0 && prenumeTextBox.TextLength != 0)
{
var connString = (#"Data Source=" + Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + #"\Angajati.sdf");
//var connString = #"Data Source=C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag\Angajati.sdf";
using (var conn = new SqlCeConnection(connString))
{
try
{
//deschide conectiunea in db
conn.Open();
//creaza comanda in SQL Server CE
SqlCeCommand cmd = new SqlCeCommand();
//conecteaza cmd la conn
cmd.Connection = conn;
//adauga parametru pt campul poza cu value image
SqlCeParameter picture = new SqlCeParameter("#Poza", SqlDbType.Image);
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Poza", a);
cmd.CommandText = "INSERT INTO info(Nume, Prenume, Data, Proiect, Schimburi, Poza, Acord, Baza) VALUES('" + numeTextBox.Text.Trim() + "', '" + prenumeTextBox.Text.Trim() + "', '" + dateTimePicker1.Value.ToShortDateString() + "', '" + textBox1.Text.Trim() + "', " + label5.Text + " , #Poza, " + textBox2.Text + ", " + textBox3.Text + ");";
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Salvat cu succes!");
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
numeTextBox.Clear();
prenumeTextBox.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
else
{
MessageBox.Show("Trebuie sa completezi campurile inainte de a salva!");
}
}
Here is how I update it:
private void button1_Click_1(object sender, EventArgs e)
{
//var connString = (#"Data Source= |DataDirectory|\Angajati.sdf");
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Angajati.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
SqlCeCommand cmd = new SqlCeCommand();
//conecteaza cmd la conn
cmd.Connection = conn;
//adauga parametru pt campul poza cu value image
SqlCeParameter picture = new SqlCeParameter("#Poza", SqlDbType.Image);
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Poza", a);
var query = "UPDATE info SET Nume='" + textBox5.Text + "' , Prenume='" + textBox4.Text + "' , Data='" + dateTimePicker1.Value.ToShortDateString() + "', Proiect='" + textBox1.Text + "', Schimburi='" + label10.Text + "', Poza=#Poza, Acord='" + textBox2.Text + "', Baza='" + textBox3.Text + "' WHERE Nume='" + textBox5.Text + "' AND Prenume='" + textBox4.Text + "'";
cmd.CommandText = query;
cmd.ExecuteNonQuery();
MessageBox.Show("Salvat cu succes!");
this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
Here is how I search data:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length != 0)
{
var numePrenume = textBox1.Text.Trim().Split(' ');
if (numePrenume.Count() > 1)
{
var nume = numePrenume[0];
var prenume = numePrenume[1];
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Angajati.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
var query = "SELECT COUNT(*) FROM info WHERE Nume='" + nume + "' AND Prenume='" + prenume + "'";
var command = new SqlCeCommand(query, conn);
var dataAdapter = new SqlCeDataAdapter(command);
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
//checks if there's the searched record is in the db.
int infoCount = (int)command.ExecuteScalar();
if (infoCount > 0)
{
Info form = new Info(nume, prenume);
form.Show();
}
else
{
MessageBox.Show("Nu exista un angajat cu acest nume");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
else
{
MessageBox.Show("Nu ai introdus prenumele");
}
}
else
{
MessageBox.Show("Nu ai introdus nici un nume!");
}
}
I have solved this problem by changing the path to the db, it was something wrong at it, and by creating a refresh function for my gridView called after the insert. Bellow is the code for the solution:
Getting the path like this now:
string startPath = Application.StartupPath;
var filepath = startPath + "\\" + "Grupe.sdf";
var connString = (#"Data Source=" + filepath +"");
The refresh function:
public void refresh()
{
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Grupe.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
var query = "SELECT * FROM copii";
var command = new SqlCeCommand(query, conn);
var dataAdapter = new SqlCeDataAdapter(command);
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
dataGridView1.DataSource = dataTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}

Ozeki is not returning other records

I'm doing an Ozeki Messenger Project using C#. I want to retrieve more than one record from the table. Its returning me the first record only...
Here's my code. Any Idea what am doing wrong guys?
protected void Page_Load(object sender, EventArgs e)
{
try
{
String x;
String y;
String z;
String SenderNumber, receiverNumber, message;
SenderNumber = Request.QueryString.Get("sender");
receiverNumber = Request.QueryString.Get("receiver");
message = Request.QueryString.Get("msg");
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
SqlDataReader reader;
connection.ConnectionString = Constring;
command.Connection = connection;
command.CommandText = "SELECT P_Name, P_Parking FROM tblPharmacy Where Code = '" + message + "'" ;
connection.Open();
reader = command.ExecuteReader();
String data = "";
while (reader.Read())
{
x = reader["P_Name"].ToString();
y = reader["P_Parking"].ToString();
data += x + " " + y + " - ";
Response.Redirect("http://localhost:9333/ozeki?login=admin&password=xxxxxx&action=sendMessage&messagetype=SMS:TEXT&recepient=" + SenderNumber + " &messageData= " + data);
}
reader.Close();
connection.Close();
}
catch (Exception)
{
}
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
String x;
String y;
String z;
String SenderNumber, receiverNumber, message;
SenderNumber = Request.QueryString.Get("sender");
receiverNumber = Request.QueryString.Get("receiver");
message = Request.QueryString.Get("msg");
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
SqlDataReader reader;
connection.ConnectionString = Constring;
command.Connection = connection;
command.CommandText = "SELECT P_Name, P_Parking FROM tblPharmacy Where Code = '" + message + "'" ;
connection.Open();
reader = command.ExecuteReader();
String data = "";
while (reader.Read())
{
x = reader["P_Name"].ToString();
y = reader["P_Parking"].ToString();
data += x + " " + y + " - ";
}
Response.Redirect("http://localhost:9333/ozeki?login=admin&password=xxxxxx&action=sendMessage&messagetype=SMS:TEXT&recepient=" + SenderNumber + " &messageData= " + data);
reader.Close();
connection.Close();
}
catch (Exception)
{
}
}
I got The Answer Myself.. LOL. The Response.Redirect should be outside the While Loop. It Works Just fine :D

Textbox value does not get updated in asp.net

I have some Textboxes in my page. I am getting values from Database in and updating Textboxes in my page load. I have a code to update values in database behind update button. the problem is that when I change the textbox value and click update button, the value in textbox is again the original one. It retains its value. My code is
protected void Page_Load(object sender, EventArgs e)
{
int id = Convert.ToInt32(Session["DocumentID"]);
Connection conn = new Connection();
string query = "SELECT * from Document where DocumentID='" + id + "'";
SqlCommand sqlcom = new SqlCommand(query, conn.conopen());
SqlDataAdapter daexp = new SqlDataAdapter(sqlcom);
System.Data.DataTable dtexp = new System.Data.DataTable();
daexp.Fill(dtexp);
TextBox1.Text = dtexp.Rows[0][1].ToString();
TextBox3.Text = dtexp.Rows[0][2].ToString();
TextBox6.Text = dtexp.Rows[0][3].ToString();
TextBox4.Text = dtexp.Rows[0][4].ToString();
TextBox5.Text = dtexp.Rows[0][5].ToString();
TextBox7.Text = dtexp.Rows[0][6].ToString();
TextBox7.ReadOnly = true;
}
protected void Button1_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(Session["DocumentID"].ToString());
if (FileUpload1.HasFile)
{
HttpPostedFile Image = FileUpload1.PostedFile;
string contentType = Image.ContentType;
if (contentType.Equals("application/octet-stream"))
{
contentType = "application/pdf";
}
else if (contentType.Equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
{
contentType = "application/msword";
}
int nFileLen = Image.ContentLength;
byte[] myData = new byte[nFileLen];
Image.InputStream.Read(myData, 0, nFileLen);
Connection con = new Connection();
con.conopen();
string query = "UPDATE Document SET Setup='" + TextBox1.Text + "', ReferenceNO='" + TextBox3.Text + "', DocumentDate='" + TextBox6.Text + "', Subject='" + TextBox4.Text + "', NameOfInitiator='" + TextBox5.Text + "', Document=#Doc, FolderID='" + DropDownList1.Text + "', DocTypeID='" + DropDownList4.Text + "', DirectorateID='" + DropDownList3.Text + "', OrganizationID='" + DropDownList2.Text + "' WHERE DocumentID='" + id + "'";
SqlCommand sqlcom = new SqlCommand(query, con.conopen());
sqlcom.Parameters.AddWithValue("#Doc", myData);
sqlcom.ExecuteNonQuery();
Label12.Text = "Document Updated Successfully";
Label12.ForeColor = System.Drawing.Color.Green;
Label12.Visible = true;
Label12.Text = "Document Updated Successfully";
Label12.ForeColor = System.Drawing.Color.Green;
Label12.Visible = true;
}
else
{
Connection conn = new Connection();
string query = "UPDATE Document SET Setup='" + TextBox1.Text + "', ReferenceNO='" + TextBox3.Text + "', DocumentDate='" + TextBox6.Text + "', Subject='" + TextBox4.Text + "', NameOfInitiator='" + TextBox5.Text + "', FolderID='" + DropDownList1.Text + "', DocTypeID='" + DropDownList4.Text + "', DirectorateID='" + DropDownList3.Text + "', OrganizationID='" + DropDownList2.Text + "' WHERE DocumentID='" + id + "'";
SqlCommand sqlcom = new SqlCommand(query, conn.conopen());
sqlcom.ExecuteNonQuery();
}
}
You are updating the values of Textboxes from database in your Page_Load. Every time page is posted back it gets values from database and sets in TextBoxes. You need to add a check and only update values and set to TextBoxes if page is loaded first time and not posted back. Like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
//your code here...
}
}
I know: Order Event of asp.net PreInit -Init -InitComplete -PreLoad -LoadPage -Control events -LoadComplete -PreRender -SaveStateComplete -Render -Unload
Therefore , When u onckick button, Webpage will ispostback. after, call pageload -> EventButton. value of textbox change, because your pageload set value for textbox.
Edit code:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack){
int id = Convert.ToInt32(Session["DocumentID"]);
Connection conn = new Connection();
string query = "SELECT * from Document where DocumentID='" + id + "'";
SqlCommand sqlcom = new SqlCommand(query, conn.conopen());
SqlDataAdapter daexp = new SqlDataAdapter(sqlcom);
System.Data.DataTable dtexp = new System.Data.DataTable();
daexp.Fill(dtexp);
TextBox1.Text = dtexp.Rows[0][1].ToString();
TextBox3.Text = dtexp.Rows[0][2].ToString();
TextBox6.Text = dtexp.Rows[0][3].ToString();
TextBox4.Text = dtexp.Rows[0][4].ToString();
TextBox5.Text = dtexp.Rows[0][5].ToString();
TextBox7.Text = dtexp.Rows[0][6].ToString();
TextBox7.ReadOnly = true;
}
}
Try to refer to the value Attribute:
TextBox1.Attributes("value")

c#-The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I'm new to .net development
I'm trying to fetch the data from Facebook app,when update the query I'm getting the above error on update customer details
in 'cust_date' filed and i taken in cust_date datatype is DATETIME.
so how to convert this DATETIME format to 'MM/DD/YYYY HH:MM'
public void Customer(string Customerid)
{
var accessToken = "CAACEdEose0cBAMTINaTZCrm67pT6cO16KHsR3UNgOTZAGH03GHmhKozUOxEXYpL3ZB9pfbFWm4Oj2VMVy8xMf5vXMpFtY6LZm2Hej0WmrHPlwk7pWyibf9gXbCaDBoIih26nRqffAfwZD";
var client = new FacebookClient(accessToken);
string clientfeed = client.Get(Customerid).ToString();
JObject obj = JObject.Parse(clientfeed);
string custid = obj["id"].ToString();
string name = obj["name"].ToString();
string fst_name = obj["first_name"].ToString();
string lst_name = obj["last_name"].ToString();
string link = obj["link"].ToString();
string[] splitlink = link.Split('/');
if (splitlink[3].StartsWith("profile"))
{
splitlink[3] =name.ToString();
link = splitlink[0] + '/' + splitlink[1] + '/' + splitlink[2] + '/' + splitlink[3];
}
string gender = obj["gender"].ToString();
string cust_updated_time = obj["updated_time"].ToString();
string abctime = cust_updated_time.Substring(0, cust_updated_time.ToString().Length - 3);
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
myConnection.Open();
string qy3 = "select count(*) from fb_customer where customer_fb_id='" + custid + "'";
string count;
SqlCommand myCommand = new SqlCommand(qy3, myConnection);
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
count = myReader[0].ToString();
int cnt = Convert.ToInt32(count);
if (cnt == 0)
{
SqlConnection myOleConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
string qy = "select * from fb_customer";
myOleConnection.Open();
SqlCommand myOleCommand = new SqlCommand(qy, myOleConnection);
myOleCommand.CommandText = "SET DATEFORMAT MDY insert into fb_customer(customer_fb_id,name,firstname,lastname,link,gender,cust_date,New) values('" + custid + "','" + name + "','" + fst_name + "','" + lst_name + "','" + link + "','" + gender + "','" + abctime + "','1')";
SqlDataReader myOleDataReader = myOleCommand.ExecuteReader();
myOleDataReader.Close();
myOleConnection.Close();
}
else
{
SqlConnection myOleDb = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
string qy1 = "select * from fb_customer";
myOleDb.Open();
SqlCommand mycmd = new SqlCommand(qy1, myOleDb);
mycmd.CommandText = " UPDATE fb_customer set name='" + name + "',firstname='" + fst_name + "',lastname='" + lst_name + "',link='" + link + "',gender='" + gender + "',cust_date= '" + abctime + "' where customer_fb_id = '" + custid + "'";
SqlDataReader mydatareader = mycmd.ExecuteReader();
mydatareader.Close();
myOleDb.Close();
}
}
myReader.Close();
myConnection.Close();
}
public void IIPLCustomer(string iiplcustid, string abctime)
{
var accessToken = "CAACEdEose0cBADKYiSkFVcqeZAYxmYlytKM5pQT6zuEvnNoU9soPlWc2pZAJvKDL557BKTGIRNhbcuZBR6Li8TlrcM8yG1yXYGzikVlUPyFgDPzEDMiIZAnuHe5y3gTZCxkyTeA12ISPPRhJev6B63rTr05slMfwZD";
var client = new FacebookClient(accessToken);
string clientfeed = client.Get(iiplcustid).ToString();
JObject obj = JObject.Parse(clientfeed);
string custid = obj["id"].ToString();
string name = obj["name"].ToString();
string[] splitname = name.Split(' ');
string link = obj["link"].ToString();
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
myConnection.Open();
string qy = "select count(*) from fb_customer where customer_fb_id='" + custid + "'";
string count;
SqlCommand myCommand = new SqlCommand(qy, myConnection);
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
count = myReader[0].ToString();
int cnt = Convert.ToInt32(count);
if (cnt == 0)
{
SqlConnection myConnection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
string qy1 = "select * from fb_customer";
myConnection1.Open();
SqlCommand myCommand1 = new SqlCommand(qy1, myConnection1);
myCommand1.CommandText = "SET DATEFORMAT MDY insert into fb_customer(customer_fb_id,name,link,firstname,lastname,cust_date,New) values('" + custid + "','" + name + "','" + link + "','" + splitname[0] + "','" + splitname[1] + "','" + abctime + "','1')";
SqlDataReader myReader1 = myCommand1.ExecuteReader();
myReader1.Close();
myConnection1.Close();
}
else
{
SqlConnection myOleDb = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
string qy1 = "select * from fb_customer";
myOleDb.Open();
SqlCommand mycmd = new SqlCommand(qy1, myOleDb);
mycmd.CommandText = "SET DATEFORMAT MDY UPDATE fb_customer set name='" + name + "',firstname='" + splitname[0] + "',lastname='" + splitname[1] + "',link='" + link + "',cust_date='" + abctime + "' where customer_fb_id = '" + custid + "'";
//Here I'm getting an error
SqlDataReader mydatareader = mycmd.ExecuteReader();
mydatareader.Close();
myOleDb.Close();
}
}
myReader.Close();
myConnection.Close();
}
You can use Datetime.ParseExact method to convert date into appropriate format. Use like this
DateTime.ParseExact('07-12-2013', 'dd/MM/yyyy',
System.Globalization.CultureInfo.InvariantCulture).ToString('yyyy/MM/dd')
You need to change the format whatever you like.
This is gonna be very simple. Try the following format.
string date = DateTime.Now.ToString("MM/dd/yyyy HH:MM");
I just gave DateTime.Now and converted it. You can give the DateTime which you get and convert it to the format specified in the above syntax.

Categories