Script message not showing - clientscript

Page script keeps on running, doesn't shows message "Your request has been submitted successfully" as mentioned in my below. Can anyone please help what I am missing here?
protected void Button1_Click1(object sender, EventArgs e)
{
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["GerpConnStr"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
string name = System.Web.HttpContext.Current.User.Identity.Name;
string domain = name.Substring(+13);
try
{
con.Open();
SqlCommand cmd = con.CreateCommand();
SqlCommand cmd1 = new SqlCommand("SELECT max(ID) as maxReq FROM request", con);
cmd1.CommandType = CommandType.Text;
int result = ((int)cmd1.ExecuteScalar());
int req = result + 1;
if (FileUpload1.HasFile)
{
string extension1 = Path.GetExtension(FileUpload1.PostedFile.FileName);
string attachment = (FileUpload1.FileName + '_' + req + extension1);
cmd.CommandType = CommandType.Text;
string dt2 = DateTime.Now.ToString("yyyyMMddHHmmss");
DateTime time = DateTime.Now;
cmd.CommandText = "insert into request (request_type,request_area,subject,description,requestor,req_status,attachment,request_time) values('" + DropDownList1.SelectedValue + "','" + DropDownList2.SelectedValue + "','" + TextBox1.Text + "','" + TextArea1.InnerText + "','" + Label3.Text + "','" + "Open" + "','" + attachment + "','" + time + "')";
string saveDir = #"\upload\" + Server.HtmlEncode(FileUpload1.FileName);
string dt = DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss") + "_";
string appPath = Request.PhysicalApplicationPath;
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string savePath = appPath + saveDir +
Server.HtmlEncode(FileUpload1.FileName);
string saveSess = saveDir + dt +
Server.HtmlEncode(FileUpload1.FileName);
FileUpload1.SaveAs(saveDir + '_' + req + extension);
// Label4.Text = "Your request has been submitted successfully";
string message = "Your request has been submitted successfully";
string script = "window.onload = function(){ alert('";
script += message;
script += "');";
script += "window.location = '";
script += Request.Url.AbsoluteUri;
script += "'; }";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
Session["sessimage1"] = saveSess;
// CreateMailItem();
} //if
else
{
// string extension1 = Path.GetExtension(FileUpload1.PostedFile.FileName);
// string attachment = (FileUpload1.FileName + '_' + req + extension1);
// SqlCommand cmd1 = con.CreateCommand();
cmd.CommandType = CommandType.Text;
DateTime time = DateTime.Now;
// string dt1 = DateTime.Now.ToString("yyyyMMddHHmmss");
cmd.CommandText = "insert into request (request_type,request_area,subject,description,requestor,req_status,request_time) values('" + DropDownList1.SelectedValue + "','" + DropDownList2.SelectedValue + "','" + TextBox1.Text + "','" + TextArea1.InnerText + "','" + Label3.Text + "','" + "Open" + "','" + time + "')";
// Label4.Text = "Your request has been submitted successfully";
string message = "Your request has been submitted successfully";
string script = "window.onload = function(){ alert('";
script += message;
script += "');";
script += "window.location = '";
script += Request.Url.AbsoluteUri;
script += "'; }";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
// Response.Redirect(Request.Url.AbsoluteUri);
// EmptyTextBoxes(TextBox1.Text);
// this.Controls.Clear();
// this.InitializeComponent();
} //else
// SaveFile(FileUpload1.PostedFile);
cmd.ExecuteNonQuery();
cmd1.ExecuteNonQuery();
con.Close();
} //try
catch
{
Console.WriteLine("Insert failed");
Console.Read();
}
finally
{
con.Close();
}
CreateMailItem();
} //button1

Its solved now. Its was getting error at Console.Read() in CreateMailItem(). Thats why it was never going back to Button1_Click1(object sender, EventArgs e) to post the message of successful submission. I have omitted Console.Read() and now the execution of CreateMailItem() gets completed and control gets back to Button1_Click1(object sender, EventArgs e) to post the message of successful submission.
Updated part:
catch
{
Console.WriteLine("Insert failed");
//Console.Read();
}

Related

Error while getting records from stored procedure

I have code to take data from stored procedure.
I just want record from stored procedure. But now I am getting error with this code in class with DataAccess code:
SelectCommand.Connection property has not been initialized. fill data adapter
I just want to track all rows with pagination:
namespace SpidiWeb.App_Code.Helper
{
public class DataAccess
{
public string mstr_ConnectionString;
public SqlConnection mobj_SqlConnection;
public SqlCommand mobj_SqlCommand;
public int mint_CommandTimeout = 30;
public void GetConnection(string cnn_type, string dbname)
{
try
{
if (cnn_type == "W")
{
string Cnn_Str = "";
//string ServerName = "SHREE-PC";
//string DBUserName = string.Empty;
//string DBPassword = string.Empty;
string ServerName = ConfigurationManager.AppSettings["SERVER"];
string DBUserName = ConfigurationManager.AppSettings["UID"] ?? string.Empty;
string DBPassword = ConfigurationManager.AppSettings["PASSWORD"] ?? string.Empty;
string Database = dbname;
DBPassword += "c#" + Convert.ToChar(49);
//Cnn_Str = "Server=" + ServerName + ";User Id=" + DBUserName + ";Password=" + DBPassword + ";Initial Catalog=" + Database;
Cnn_Str = "Server=" + ServerName + ";Initial Catalog=" + Database +";Integrated Security=True";
mstr_ConnectionString = Cnn_Str;
}
else if (cnn_type == "S")
{
string Cnn_Str = "";
//string ServerName = "SHREE-PC";
//string DBUserName = string.Empty;
//string DBPassword = string.Empty;
string ServerName = ConfigurationManager.AppSettings["SERVER"];
string DBUserName = ConfigurationManager.AppSettings["UID"] ?? string.Empty;
string DBPassword = ConfigurationManager.AppSettings["PASSWORD"] ?? string.Empty;
string Database = "NEWSMSLOG_" + dbname;
DBPassword += "c#" + Convert.ToChar(49);
//Cnn_Str = "Server=" + ServerName + ";User Id=" + DBUserName + ";Password=" + DBPassword + ";Initial Catalog=" + Database;
Cnn_Str = "Server=" + ServerName + ";Initial Catalog=" + Database + ";Integrated Security=True";
mstr_ConnectionString = Cnn_Str;
}
mobj_SqlConnection = new SqlConnection(mstr_ConnectionString);
mobj_SqlCommand = new SqlCommand();
mobj_SqlCommand.CommandTimeout = mint_CommandTimeout;
mobj_SqlCommand.CommandType = CommandType.StoredProcedure;
mobj_SqlCommand.Connection = mobj_SqlConnection;
mobj_SqlConnection.Open();
}
catch (Exception ex)
{
throw new Exception("Error initializing data class." + Environment.NewLine + ex.Message);
}
and this code is from my page :
DataAccess obj_con = new DataAccess();
protected void Get_Data()
{
try
{
DataTable dt = new DataTable();
int intUserId = ddl_users.SelectedItem.Text.ToString() == "All" ? 0 : Convert.ToInt32(ddl_users.SelectedValue.ToString());
string strCampaignName = string.IsNullOrEmpty(txt_CompaignName.Text.Trim()) ? string.Empty : txt_CompaignName.Text.Trim();
string mobileNo = string.IsNullOrEmpty(txt_mobileno.Text.Trim()) ? string.Empty : txt_mobileno.Text.Trim();
int intSenderId = ddl_sender.SelectedItem.Text.ToString() == "All" ? 0 : Convert.ToInt32(ddl_sender.SelectedValue.ToString());
string strDeliveryId = ddl_delevery.SelectedItem.Text.ToString() == "All" ? "-1" : ddl_delevery.SelectedItem.Text.ToString();
using (var con = obj_con.mobj_SqlConnection)
{
//if (con.State == ConnectionState.Closed)
// con.Open();
var cmd = new SqlCommand();
cmd.Parameters.AddWithValue("intUserID", intUserId);
cmd.Parameters.AddWithValue("strCampaignName", strCampaignName);
cmd.Parameters.AddWithValue("strMobileNo", mobileNo);
cmd.Parameters.AddWithValue("intSenderId", intSenderId);
cmd.Parameters.AddWithValue("strDeliveryId", strDeliveryId);
if (ddl_account.SelectedItem.Text.ToString() == "All")
{
cmd.Parameters.AddWithValue("intAccType", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("intAccType", Convert.ToInt32(ddl_account.SelectedValue.ToString()));
}
if (chk_date.Checked == true)
{
DateTime dateValue = Convert.ToDateTime(CommonLogic.Get_Date_From_String(txt_date_from.Text.Trim(), 1));
cmd.Parameters.AddWithValue("strdbNM ", dateValue.ToString("yyyy_MM"));
}
else
{
cmd.Parameters.AddWithValue("strdbNM ", DateTime.Now.Date.ToString("yyyy_MM"));
}
if (!string.IsNullOrEmpty(txt_date_from.Text.Trim()))
{
DateTime date = Convert.ToDateTime(txt_date_from.Text.Trim());
cmd.Parameters.AddWithValue("strTBNM", date.ToString("ddMMyy"));
}
else
{
cmd.Parameters.AddWithValue("strTBNM", DateTime.Now.Date.ToString("ddMMyy"));
}
cmd.Parameters.AddWithValue("PageIndex", 1);
cmd.Parameters.AddWithValue("PageSize", 1000);
cmd.Parameters.Add("RecordCount", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.Connection = con;
cmd.CommandText = "dbo.Report_ViewCombineReport";
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.SelectCommand = cmd;
ad.Fill(dt); // Error Occurs here Fill: SelectCommand.Connection property has not been initialized.
egrd.DataSource = dt;
egrd.DataBind();
}
}
catch (Exception ex)
{
CommonLogic.SendMailOnError(ex);
}
}
You didn't pass Connection to SqlCommand object, pass it in parameter like below
var cmd = new SqlCommand("Your query", con);
Or you can also set it by
cmd.Connection = con;

How to send a request to upload image file to LINE server with multipart/form-data for posting image to LINE Notify?

I'm trying to post an image from local using LINE Notify, but get bad request, how to send the right request using HttpWebRequest with multipart/form-data content-type in vb.net?
I've tried on cURL, and it's woking:
curl -i -X POST https://notify-api.line.me/api/notify -H "Authorization: Bearer <TOKEN>" -F "message=test" -F "imageFile=#C:\PATH\to\file.jpg"
Here is what I've done in vb.net:
Imports System.IO
Imports System.Net
Imports System.Security.Cryptography
Imports System.Text
Public Class Form1
Private Sub btnPic_Click(sender As Object, e As EventArgs) Handles btnPic.Click
OpenFileDialog1.Filter = "Image File (*.jpg)|*.jpg;*.JPG |Image File (*.png)|*.png;*.PNG"
OpenFileDialog1.FileName = ""
If OpenFileDialog1.ShowDialog() <> DialogResult.Cancel Then
txtPic.Text = OpenFileDialog1.FileName
End If
End Sub
Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
' [references]
'https://notify-bot.line.me/doc/en/
'http://white5168.blogspot.com/2017/01/line-notify-6-line-notify.html
'https://aprico-media.com/posts/1824
'https://stackoverflow.com/questions/3890754/using-httpwebrequest-to-post-data-upload-image-using-multipart-form-data
Dim md5Hash As MD5 = MD5.Create()
'Boundary string
Dim strBound As String = "---------------------" & GetMd5Hash(md5Hash, CInt(Int((654321 * Rnd()) + 1))).Substring(0, 10)
Try
Dim request = DirectCast(WebRequest.Create("https://notify-api.line.me/api/notify"), HttpWebRequest)
Dim postData As String = "--" & strBound & vbCrLf
postData += "Content-Disposition: form-data; name=""message""" & vbCrLf & vbCrLf
postData += txtText.Text & vbCrLf
' [Not working] sticker part
'postData += "--" & strBound & vbCrLf
'postData += "Content-Disposition: form-data; name=""stickerPackageId""" & vbCrLf & vbCrLf
'postData += 1 & vbCrLf
'postData += "--" & strBound & vbCrLf
'postData += "Content-Disposition: form-data; name=""stickerId""" & vbCrLf & vbCrLf
'postData += 2 & vbCrLf
If txtPic.Text <> "" Then
Dim ext As String = Path.GetExtension(txtPic.Text)
If ext = ".jpg" Then
ext = "jpeg"
ElseIf ext = ".png" Then
ext = "png"
Else
MessageBox.Show("Sorry! LINE Notify supports only jpeg/png image file.")
btnPic.PerformClick()
Return
End If
' [Not working] image part
postData += "--" & strBound & vbCrLf
postData += "Content-Disposition: form-data; name=""imageFile""; filename=""" & Path.GetFileName(txtPic.Text) & """" & vbCrLf
postData += "Content-Type: image/" & ext & vbCrLf & vbCrLf
postData += Convert.ToBase64String(File.ReadAllBytes(txtPic.Text)) & vbCrLf
End If
postData += vbCrLf & "--" & strBound & "--"
Dim data = Encoding.UTF8.GetBytes(postData)
request.Method = "POST"
request.ContentType = "multipart/form-data; boundary=" & strBound
request.ContentLength = data.Length
request.Headers.Add("Authorization", "Bearer <TOKEN>")
Using stream = request.GetRequestStream()
stream.Write(data, 0, data.Length)
End Using
Dim response = DirectCast(request.GetResponse(), HttpWebResponse)
Dim responseString = New StreamReader(response.GetResponseStream()).ReadToEnd()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
End Try
End Sub
Shared Function GetMd5Hash(ByVal md5Hash As MD5, ByVal Input As String) As String
' Convert the input string to a byte array and compute the hash.
Dim data As Byte() = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(Input))
' Create a new Stringbuilder to collect the bytes
' and create a string.
Dim sBuilder As New StringBuilder()
' Loop through each byte of the hashed data
' and format each one as a hexadecimal string.
Dim i As Integer
For i = 0 To data.Length - 1
sBuilder.Append(data(i).ToString("x2"))
Next i
' Return the hexadecimal string.
Return sBuilder.ToString()
End Function 'GetMd5Hash
End Class
There is no problem for sending only "message", whenever the other parts i.e."imageFile", "stickerPackageId", "stickerId",... are combined with, the result is getting error (400). However, if a field name is changed to small letter as i.e."stickerpackageid", "stickerid" vb will not catch any exception, but just send the "message" to Notify. So, I think a wrong part should be in http request string, or does it needed to convert each field into binary array? If that is the case how to obtain the right result?
POST multipart/form-data for line notify , need generate output byte array list by yourself
LINE Notify API Reference https://notify-bot.line.me/doc/en/
Upload File Class
public class FormFile
{
public string Name { get; set; }
public string ContentType { get; set; }
public string FilePath { get; set; }
public byte[] bytes { get; set; }
}
Test Data
private void multipartTest(string access_token)
{
Dictionary<string, object> d = new Dictionary<string, object>()
{
// message , imageFile ... name is provided by LINE API
{ "message", #"message..." },
{ "imageFile", new FormFile(){ Name = "notify.jpg", ContentType = "image/jpeg", FilePath="notify.jpg" }
}
};
string boundary = "Boundary";
List<byte[]> output = genMultPart(d, boundary);
lineNotifyMultipart(access_token, boundary, output);
}
C# Code
private void lineNotifyMultipart(string access_token, string boundary, List<byte[]> output)
{
try
{
#region POST multipart/form-data
StringBuilder sb = new StringBuilder();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(lineNotifyURL);
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=Boundary";
request.Timeout = 30000;
// header
sb.Clear();
sb.Append("Bearer ");
sb.Append(access_token);
request.Headers.Add("Authorization", sb.ToString());
// note: multipart/form-data boundary must exist in headers ContentType
sb.Clear();
sb.Append("multipart/form-data; boundary=");
sb.Append(boundary);
request.ContentType = sb.ToString();
// write Post Body Message
BinaryWriter bw = new BinaryWriter(request.GetRequestStream());
foreach(byte[] bytes in output)
bw.Write(bytes);
#endregion
getResponse(request);
}
catch (Exception ex)
{
#region Exception
StringBuilder sbEx = new StringBuilder();
sbEx.Append(ex.GetType());
sbEx.AppendLine();
sbEx.AppendLine(ex.Message);
sbEx.AppendLine(ex.StackTrace);
if (ex.InnerException != null)
sbEx.AppendLine(ex.InnerException.Message);
myException ex2 = new myException(sbEx.ToString());
//message(ex2.Message);
#endregion
}
}
private void getResponse(HttpWebRequest request)
{
StringBuilder sb = new StringBuilder();
string result = string.Empty;
StreamReader sr = null;
try
{
#region Get Response
if (request == null)
return;
// HttpWebRequest GetResponse() if error happened will trigger WebException
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
sb.AppendLine();
foreach (var x in response.Headers)
{
sb.Append(x);
sb.Append(" : ");
sb.Append(response.Headers[x.ToString()]);
if (x.ToString() == "X-RateLimit-Reset")
{
sb.Append(" ( ");
sb.Append(CheckFormat.ToEpcohDateTimeUTC(long.Parse(response.Headers[x.ToString()])));
sb.Append(" )");
}
sb.AppendLine();
}
using (sr = new StreamReader(response.GetResponseStream()))
{
result = sr.ReadToEnd();
sb.Append(result);
}
}
//message(sb.ToString());
#endregion
}
catch (WebException ex)
{
#region WebException handle
// WebException Response
using (HttpWebResponse response = (HttpWebResponse)ex.Response)
{
sb.AppendLine("Error");
foreach (var x in response.Headers)
{
sb.Append(x);
sb.Append(" : ");
sb.Append(response.Headers[x.ToString()]);
sb.AppendLine();
}
using (sr = new StreamReader(response.GetResponseStream()))
{
result = sr.ReadToEnd();
sb.Append(result);
}
//message(sb.ToString());
}
#endregion
}
}
public List<byte[]> genMultPart(Dictionary<string, object> parameters, string boundary)
{
StringBuilder sb = new StringBuilder();
sb.Clear();
sb.Append("\r\n--");
sb.Append(boundary);
sb.Append("\r\n");
string beginBoundary = sb.ToString();
sb.Clear();
sb.Append("\r\n--");
sb.Append(boundary);
sb.Append("--\r\n");
string endBoundary = sb.ToString();
sb.Clear();
sb.Append("Content-Type: multipart/form-data; boundary=");
sb.Append(boundary);
sb.Append("\r\n");
List<byte[]> byteList = new List<byte[]>();
byteList.Add(System.Text.Encoding.UTF8.GetBytes(sb.ToString()));
foreach (KeyValuePair<string, object> pair in parameters)
{
if (pair.Value is FormFile)
{
byteList.Add(System.Text.Encoding.ASCII.GetBytes(beginBoundary));
FormFile form = pair.Value as FormFile;
sb.Clear();
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(pair.Key);
sb.Append("\"; filename=\"");
sb.Append(form.Name);
sb.Append("\"\r\nContent-Type: ");
sb.Append(form.ContentType);
sb.Append("\r\n\r\n");
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
byteList.Add(bytes);
if (form.bytes == null && !string.IsNullOrEmpty(form.FilePath))
{
FileStream fs = new FileStream(form.FilePath, FileMode.Open, FileAccess.Read);
MemoryStream ms = new MemoryStream();
fs.CopyTo(ms);
byteList.Add(ms.ToArray());
}
else
byteList.Add(form.bytes);
}
else
{
byteList.Add(System.Text.Encoding.ASCII.GetBytes(beginBoundary));
sb.Clear();
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(pair.Key);
sb.Append("\"");
sb.Append("\r\n\r\n");
sb.Append(pair.Value);
string data = sb.ToString();
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
byteList.Add(bytes);
}
}
byteList.Add(System.Text.Encoding.ASCII.GetBytes(endBoundary));
return byteList;
}

Editing telephone number in active directory

I am able to retrieve user information from Active Directory as per below code. But how can I authorized current to edit and update their telephone numbers? This application is running in SharePoint server.
Dim netBIOSname As String = Me.Page.User.Identity.Name
Dim sAMAccountName As String = netBIOSname.Substring(netBIOSname.LastIndexOf("\"c) + 1)
txtuser.Text = sAMAccountName
Try
Dim userName As String = txtuser.Text
Dim searcher As New DirectoryServices.DirectorySearcher( _
"(mailNickname=" + userName + ")")
Dim result As DirectoryServices.SearchResult = searcher.FindOne()
If result Is Nothing Then
Label2.Text = "Unable to find user: " + userName
Else
Dim employee As DirectoryServices.DirectoryEntry = result.GetDirectoryEntry()
txtfirstname.Text = employee.Properties("givenName").Value.ToString()
txtlastname.Text = employee.Properties("sn").Value.ToString()
txtfullname.Text = employee.Properties("cn").Value.ToString()
txtempid.Text = employee.Properties("physicalDeliveryOfficeName").Value.ToString()
txttitle.Text = employee.Properties("title").Value.ToString()
txttele.Text = employee.Properties("telephoneNumber").Value.ToString()
txtdept.Text = employee.Properties("department").Value.ToString()
txtmobile.Text = employee.Properties("mobile").Value.ToString()
Dim ManagerName As String = employee.Properties("manager").Value.ToString()
ManagerName = ManagerName.Substring(3, ManagerName.IndexOf(",") - 3)
Dim searchMgr As New DirectoryServices.DirectorySearcher("(cn=" + ManagerName + ")")
Dim resultMgr As DirectoryServices.SearchResult = searchMgr.FindOne()
If resultMgr Is Nothing Then
Label2.Text = "Unable to find Manager: " + ManagerName
Else
Dim empManager As DirectoryServices.DirectoryEntry = resultMgr.GetDirectoryEntry()
searchMgr.Dispose()
resultMgr = Nothing
empManager.Close()
End If
searcher.Dispose()
result = Nothing
employee.Close()
End If
Catch ex As Exception
Label2.Text = "The following error occurred: " + ex.Message.ToString()
End Try

OR statement in SQL command does not function

Does anyone know to fix the error? I would like to create the OR statement but it does not function in my code. The code is shown below. I have removed the OR to see the code function or not, it can function if I remove the or statement. So I desperately want to know what the real problem with my code is.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class updateform : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=test;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("Select * FROM [EMP] WHERE Serial_Num='" + TextBox2.Text + "' or Equipment_ID ='" + TextBox1.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
TextBox3.Text = dt.Rows[0][2].ToString();
TextBox4.Text = dt.Rows[0][6].ToString();
DropDownList1.Text = dt.Rows[0][7].ToString();
TextBox5.Text = dt.Rows[0][18].ToString();
TextBox6.Text = dt.Rows[0][11].ToString();
TextBox11.Text = dt.Rows[0][8].ToString();
TextBox7.Text = dt.Rows[0][20].ToString();
TextBox12.Text = dt.Rows[0][17].ToString();
DropDownList2.Text = dt.Rows[0][23].ToString();
TextBox9.Text = dt.Rows[0][14].ToString();
TextBox10.Text = dt.Rows[0][13].ToString();
TextBox13.Text = dt.Rows[0][12].ToString();
TextBox2.Text = dt.Rows[0][5].ToString();
TextBox1.Text = dt.Rows[0][4].ToString();
}
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source =.\\sqlexpress; Initial Catalog = test; Integrated Security = True");
con.Open();
SqlCommand cmd = new SqlCommand(#"UPDATE EMP SET Model='" + TextBox3.Text + "' ,Description= '" + TextBox4.Text + "' ,Location='" + DropDownList1.Text + "',Manufacturer_or_Vendor= '" + TextBox5.Text + "',NCR_or_OOT_History='" + TextBox6.Text + "',Due_date= '" + TextBox11.Text + "' ,Year_of_Manufacturing='" + TextBox12.Text + "',Asset_No= '" + TextBox7.Text + "' ,Status='" + DropDownList2.Text + "',Responsible_Person= '" + TextBox9.Text + "',Available_in_Sapphire= '" + TextBox10.Text + "',Last_OOT_issuance_Date= '" + TextBox13.Text + "' WHERE (Serial_Num = '" + TextBox2.Text + "' or Equipment_ID = '" + TextBox1.Text + "' )", con);
cmd.ExecuteNonQuery();
con.Close();
}
protected void Page_load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Calendar1.Visible = false;
Calendar2.Visible = false;
Calendar3.Visible = false;
}
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
if (Calendar1.Visible)
{
Calendar1.Visible = false;
}
else
{
Calendar1.Visible = true;
}
}
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
if (Calendar2.Visible)
{
Calendar2.Visible = false;
}
else
{
Calendar2.Visible = true;
}
}
protected void ImageButton3_Click(object sender, ImageClickEventArgs e)
{
if (Calendar3.Visible)
{
Calendar3.Visible = false;
}
else
{
Calendar3.Visible = true;
}
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
TextBox11.Text = Calendar1.SelectedDate.ToString("dd/MM/yyyy");
Calendar1.Visible = false;
}
protected void Calendar2_SelectionChanged(object sender, EventArgs e)
{
TextBox12.Text = Calendar2.SelectedDate.ToString("dd/MM/yyyy");
Calendar2.Visible = false;
}
protected void Calendar3_SelectionChanged(object sender, EventArgs e)
{
TextBox13.Text = Calendar1.SelectedDate.ToString("dd/MM/yyyy");
Calendar3.Visible = false;
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.IsOtherMonth)
{
e.Day.IsSelectable = false;
}
}
protected void Calendar2_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.IsOtherMonth)
{
e.Day.IsSelectable = false;
}
}
protected void Calendar3_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.IsOtherMonth)
{
e.Day.IsSelectable = false;
}
}
protected void Button3_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
}
It is not clear from your description whether it fails at compile time or execution time, or what the error is. But a wild guess of what could be the problem, try the followings:
Instead of Select * try specifying the actual columns (like select col1, col2, ..
Instead of:
sda.Fill(dt);
Declare a dataset and fill the dataset and see if it works.
DataSet ds = new DataSet ();
sda.Fill (ds);
If this works, check and see how many tables are created in your dataset and what records are in each table.

vb.net send email with image

there is a lot of topic about sending email with attachment but i couldn't find what i was looking for
my form contain 8 textbox and 1 PictureBox i can send all textbox via email but ican't send PictureBox i try many code
this is my form.
and here is my code
Dim MyMessage As New MailMessage
Try
MyMessage.From = New MailAddress("x#gmail.com")
MyMessage.To.Add("x#gmail.com")
MyMessage.Subject = "Data"
MyMessage.Body = Label1.Text + " = " + IDTextBox.Text + Environment.NewLine + Label2.Text + " = " + ناوی_سیانی_کارمەندTextBox.Text + Environment.NewLine + Label3.Text + " = " + ساڵی_لە__دایک_بوونTextBox.Text + Environment.NewLine + Label4.Text + " = " + شوێنی_دانیشتنTextBox.Text + Environment.NewLine + Label5.Text + " = " + گروپی_خوێنTextBox.Text + Environment.NewLine + Label6.Text + " = " + ناو_نیشانی_کار_لە_کۆمپانیاTextBox.Text + Environment.NewLine + Label7.Text + " = " + ژمارەی_مۆبایلTextBox.Text + Environment.NewLine + Label8.Text + " = " + شوێنی_کارTextBox.Text
Dim SMTP As New SmtpClient("smtp.gmail.com")
SMTP.Port = 587
SMTP.EnableSsl = True
SMTP.Credentials = New System.Net.NetworkCredential("x#gmail.com", "x")
SMTP.Send(MyMessage)
MsgBox("your message Has been sent successfully")
Catch ex As Exception
End Try
i will be greatfull if you could help me :)
Have you tried this.You can use the LinkedResource and AlternatiView for the same.
string path = Filelocation; // as you are using picture box,give the location from where the image is loading into picture box.
LinkedResource imageLink = new LinkedResource(path);
imageLink.ContentId = "myImage";
AlternateView altView = AlternateView.CreateAlternateViewFromString(
"<html><body><img src=cid:myImage/>" +
"<br></body></html>" + strMailContent,
null, MediaTypeNames.Text.Html);
altView.LinkedResources.Add(imageLink);
//now append it to the body of the mail
msg.AlternateViews.Add(altView);
msg.IsBodyHtml = true;
or
You can send it with HtmlBody here is the
reference : http://vba-useful.blogspot.fr/2014/01/send-html-email-with-embedded-images.html
You need to add the directory of the picture file or any file you have and add it as attachment to your mail like this...
Dim attachment As System.Net.Mail.Attachment
attachment = New System.Net.Mail.Attachment(FilePath)
MyMessage.Attachments.Add(attachment)