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.
Related
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;
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;
}
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();
}
I currently have a search that works and highlights the found text by replacing the found text with the found text but wrapped in a span tag for highlighting. Works just fine except for two issues. It is currently case sensitive, and I cannot figure out how to scroll to the first found instance. If the user searches for "nozzle" they need to be able to find "Nozzle". Here is the code I have.
Try
tmrSearch.Stop()
Try
If txtSearch.Text.Length <= 3 Then
If txtSearch.Text <> "" Then
MessageBox.Show("Please enter longer search terms!")
txtSearch.Text = String.Empty
End If
Else
Dim searchString As String = txtSearch.Text
Dim textToSearch As String = wbContent.Document.Body.InnerHtml
textToSearch = textToSearch.Replace(searchString, "<span style=""background-color:yellow"">" & searchString & "</span>")
If textToSearch.IndexOf(searchString) <> -1 Then
wbContent.Document.Body.InnerHtml = textToSearch
Else
MessageBox.Show(searchString & " is not located in this text!")
End If
txtSearch.Text = String.Empty
End If
Catch ex As Exception
MessageBox.Show("Please enter search terms!")
logger.WriteLog("Error Message : " & ex.Message)
End Try
Catch ex As Exception
logger.WriteLog("frmContent : tmrSearch_Tick() : FAILED")
logger.WriteLog("Error Message : " & ex.Message)
End Try
I know the .Replace() is case sensitive so I thought I would force the textToSearch to lower but then when I put it back, all the text in the Web browser control will be lowercase. That doesn't suit my needs here. Any suggestions here would be greatly appreciated.
Basically, you could try splitting a lower case innertext to find where your search string exists. Then use the lengths of strings from the split to rebuild your innerText from the original case copy. You will need to import system.text to use stringbuilder.
Else
Dim searchString As String = txtSearch.Text
Dim textOriginal As String = wbContent.Document.Body.InnerHtml
Dim textToLower As String = wbContent.Document.Body.InnerHtml.ToLower()
Dim textPieces() as String = textToLower.Split(New String() {searchString}, StringSplitOptions.RemoveEmptyEntries)
Dim i as integer = 0
Dim strNewInnerHtml as New StringBuilder
For each strPiece as String In textPieces
strNewInnerHtml.append(textOriginal.Substring(i,strPiece.Length)
strNewInnerHtml.append("<span style=""background-color:yellow"">" & searchString & "</span>")
i += strPiece.Length + searchString.Length
Next
If textToLower.IndexOf(searchString) <> -1 Then
wbContent.Document.Body.InnerHtml = strNewInnerHtml.ToString()
Else
MessageBox.Show(searchString & " is not located in this text!")
End If
txtSearch.Text = String.Empty
End If
You can use string.Replace(...) extension method, the following is a sample C# code (VB code version is in P.S. of this posting):
using System;
using System.Text;
namespace StringClassExtensions
{
public static class StringReplaceExtension
{
public static string Replace(this string str,
string oldValue, string newValue,
StringComparison comparisonType)
{
const int maxCapacity = 16777215;
if (string.IsNullOrEmpty(str)) return str;
if (string.IsNullOrEmpty(newValue)) return str;
if (oldValue == null) throw new ArgumentNullException("oldValue");
if (oldValue.Length == 0) return str;
if (str.Length > maxCapacity) throw new ArgumentException("'str' is too long");
if (oldValue.Length > maxCapacity) throw new ArgumentException("'oldValue' is too long");
if (newValue.Length > maxCapacity) throw new ArgumentException("'newValue' is too long");
int currentSearchPosition, lastSearchStartPosition = 0;
var returnValue = new StringBuilder(str.Length, maxCapacity);
while ((currentSearchPosition = str.IndexOf(oldValue, lastSearchStartPosition, comparisonType)) >= 0)
{
if (currentSearchPosition >= lastSearchStartPosition)
returnValue.Append(str.Substring(lastSearchStartPosition, currentSearchPosition - lastSearchStartPosition) + newValue);
lastSearchStartPosition = currentSearchPosition + oldValue.Length;
}
if (lastSearchStartPosition == 0) return str;
if (lastSearchStartPosition < str.Length)
returnValue.Append(str.Substring(lastSearchStartPosition));
return returnValue.ToString();
}
}
}
and edit just one line of your original code:
textToSearch = textToSearch.Replace(searchString, "<span style=""background-color:yellow"">" & searchString & "</span>")
to
textToSearch = textToSearch.Replace(searchString,
"<span style=""background-color:yellow"">" & searchString + "</span>",
StringComparison.InvariantCultureIgnoreCase)
Note: Original string.Replace(...) method's code is published on referencesource.microsoft.com and AFAIS it uses effective internal implementation - use posted here extension method only when original method isn't suitable.
P.S. Here is VB version of my sample String.Replace(...) method. I have got VB version by automatic conversion on developerFusion and then I edited conversion result VB code manually and briefly tested. It seems to work well.
Imports System.Text
Namespace StringClassExtensions
Public Module StringReplaceExtension
<System.Runtime.CompilerServices.Extension> _
Public Function Replace(str As String, oldValue As String, newValue As String, comparisonType As StringComparison) As String
Const maxCapacity As Integer = 16777215
If String.IsNullOrEmpty(str) Then
Return str
End If
If String.IsNullOrEmpty(newValue) Then
Return str
End If
If oldValue Is Nothing Then
Throw New ArgumentNullException("oldValue")
End If
If oldValue.Length = 0 Then
Return str
End If
If str.Length > maxCapacity Then
Throw New ArgumentException("'str' is too long")
End If
If oldValue.Length > maxCapacity Then
Throw New ArgumentException("'oldValue' is too long")
End If
If newValue.Length > maxCapacity Then
Throw New ArgumentException("'newValue' is too long")
End If
Dim currentSearchPosition As Integer, lastSearchStartPosition As Integer = 0
Dim returnValue = New StringBuilder(str.Length, maxCapacity)
While (InlineAssignHelper(currentSearchPosition, str.IndexOf(oldValue, lastSearchStartPosition, comparisonType))) >= 0
If currentSearchPosition >= lastSearchStartPosition Then
returnValue.Append(str.Substring(lastSearchStartPosition, currentSearchPosition - lastSearchStartPosition) & newValue)
End If
lastSearchStartPosition = currentSearchPosition + oldValue.Length
End While
If lastSearchStartPosition = 0 Then
Return str
End If
If lastSearchStartPosition < str.Length Then
returnValue.Append(str.Substring(lastSearchStartPosition))
End If
Return returnValue.ToString()
End Function
Private Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
target = value
Return value
End Function
End Module
End Namespace
P.P.S. Test suite for string.Replace(...) method extension
using System;
using System.Text;
using NUnit.Framework;
using StringClassExtensions;
namespace Unit_Tests_CS_ConsoleApplication1
{
[TestFixture]
public class Test_0001_StringReplaceMethodExtensionTests
{
[SetUp]
public void TestSetup()
{ }
[TearDown]
public void TestTearDown()
{ }
[Test]
public void TestNullSourceString()
{
string testStr = null;
string resultStr = testStr.Replace("oldValue", "newValue", StringComparison.InvariantCultureIgnoreCase);
Assert.IsNull(resultStr);
}
[Test]
public void TestEmptySourceString()
{
string testStr = string.Empty;
string resultStr = testStr.Replace("oldValue", "newValue", StringComparison.InvariantCultureIgnoreCase);
Assert.IsEmpty(resultStr);
}
[Test]
public void TestNullNewValue()
{
string testStr = "Hello, World!";
string resultStr = testStr.Replace("oldValue", null, StringComparison.InvariantCultureIgnoreCase);
Assert.IsTrue(resultStr == testStr);
}
[Test]
public void TestEmptyNewValue()
{
string testStr = "Hello, World!";
string resultStr = testStr.Replace("oldValue", string.Empty, StringComparison.InvariantCultureIgnoreCase);
Assert.IsTrue(resultStr == testStr);
}
[Test]
public void TestNullOldValue()
{
Assert.Throws(typeof(ArgumentNullException),
() =>
{
string testStr = "Hello, World!";
string resultStr = testStr.Replace(null, "newValue", StringComparison.InvariantCultureIgnoreCase);
}
);
}
[Test]
public void TestEmptyOldValue()
{
string testStr = "Hello, World!";
string resultStr = testStr.Replace(string.Empty, "newValue", StringComparison.InvariantCultureIgnoreCase);
Assert.IsTrue(resultStr == testStr);
}
[Test]
public void TestOldValueIsMissingInTheSearchStr()
{
string testStr = "Hello, World!";
string resultStr = testStr.Replace("oldValue", "newValue", StringComparison.InvariantCultureIgnoreCase);
Assert.IsTrue(resultStr == testStr);
}
[Test]
public void TestSearchStrEqualsToOldValue()
{
string testStr = "oldValue";
string resultStr = testStr.Replace("oldValue", "newValue", StringComparison.InvariantCultureIgnoreCase);
Assert.IsTrue(resultStr == "newValue");
}
[Test]
public void TestSearchStrStartsWithOldValue()
{
string testStr = "oldValue + some words";
string resultStr = testStr.Replace("oldValue", "newValue", StringComparison.InvariantCultureIgnoreCase);
Assert.IsTrue(resultStr == "newValue + some words");
}
[Test]
public void TestSearchStrEndsWithOldValue()
{
string testStr = "some words + oldValue";
string resultStr = testStr.Replace("oldValue", "newValue", StringComparison.InvariantCultureIgnoreCase);
Assert.IsTrue(resultStr == "some words + newValue");
}
[Test]
public void TestSearchStrHasSeveralOccurrencesOfOldValueSeparatedByOtherChars()
{
string testStr = "some words + oldValue + some more words + oldValue + even more words";
string resultStr = testStr.Replace("oldValue", "newValue", StringComparison.InvariantCultureIgnoreCase);
Assert.IsTrue(resultStr == "some words + newValue + some more words + newValue + even more words");
}
[Test]
public void TestSearchStrHasSeveralOccurrencesOfOldValueFollowingOneAfterAnother()
{
string testStr = "some words + oldValueoldValueoldValue + even more words";
string resultStr = testStr.Replace("oldValue", "newValue", StringComparison.InvariantCultureIgnoreCase);
Assert.IsTrue(resultStr == "some words + newValuenewValuenewValue + even more words");
}
[Test]
public void TestCaseInsensitiveStringComparison()
{
string testStr = "some words + oldValue + OldValue + oldValue + even more words";
string resultStr = testStr.Replace("oldValue", "newValue", StringComparison.InvariantCultureIgnoreCase);
Assert.IsTrue(resultStr == "some words + newValue + newValue + newValue + even more words");
}
[Test]
public void TestCaseSensitiveStringComparison()
{
string testStr = "some words + oldValue + OldValue + oldValue + even more words";
string resultStr = testStr.Replace("oldValue", "newValue", StringComparison.InvariantCulture);
Assert.IsTrue(resultStr == "some words + newValue + OldValue + newValue + even more words");
}
[Test]
public void TestSourceStringIsOutOfMaxCapacity()
{
Assert.Throws(typeof(ArgumentException),
() =>
{
int testCapacity = new StringBuilder().MaxCapacity / 128 + 1;
string testStr = new string('A', testCapacity);
string resultStr = testStr.Replace("oldValue", "newValue", StringComparison.InvariantCultureIgnoreCase);
}
);
}
[Test]
public void TestOldValueIsOutOfMaxCapacity()
{
Assert.Throws(typeof(ArgumentException),
() =>
{
int testCapacity = new StringBuilder().MaxCapacity / 128 + 1;
string testStr = "Hello, World!";
string oldValue = new string('A', testCapacity);
string resultStr = testStr.Replace(oldValue, "newValue", StringComparison.InvariantCultureIgnoreCase);
}
);
}
[Test]
public void TestNewValueIsOutOfMaxCapacity()
{
Assert.Throws(typeof(ArgumentException),
() =>
{
int testCapacity = new StringBuilder().MaxCapacity / 128 + 1;
string testStr = "Hello, World!";
string newValue = new string('A', testCapacity);
string resultStr = testStr.Replace("oldValue", newValue, StringComparison.InvariantCultureIgnoreCase);
}
);
}
[Test]
public void TestResultStringIsOutOfMaxCapacity()
{
Assert.Throws(typeof(ArgumentOutOfRangeException),
() =>
{
string oldValue = "Hello, World!";
int testCapacity = new StringBuilder().MaxCapacity / 128 - oldValue.Length;
string testStr = oldValue + new string('A', testCapacity);
string newValue = "Hello, the New World!";
string resultStr = testStr.Replace(oldValue, newValue, StringComparison.InvariantCultureIgnoreCase);
}
);
}
}
}
Replacing text will not work instead you just place the span tags before and after the searched text. This may need changes as follows.
Private Sub WebBrowser_DocumentCompleted(sender As Object, e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser.DocumentCompleted
Dim doc2 As mshtml.IHTMLDocument2 = WebBrowser.Document.DomDocument
Dim ReplacementTag As String = "<span style='background-color: rgb(255, 255, 0);'>"
Dim strBuilder As StringBuilder = New StringBuilder(doc2.body.outerHTML)
Dim HTMLString As String = strBuilder.ToString()
If Me.m_NoteType = ExtractionNoteType.SearchResult Then
Dim SearchWords As New List(Of String)
SearchWords.AddRange(Me.txtSearch.Text.Trim.Split(" "))
For Each item As String In SearchWords
Dim index As Integer = HTMLString.IndexOf(item, 0, StringComparison.InvariantCultureIgnoreCase)
''If index > 0 Then
While (index > 0 AndAlso index < HTMLString.Length)
HTMLString = HTMLString.Insert(index, ReplacementTag)
HTMLString = HTMLString.Insert(index + item.Length + ReplacementTag.Length, "</span>")
index = HTMLString.IndexOf(item, index + item.Length + ReplacementTag.Length + 7, StringComparison.InvariantCultureIgnoreCase)
End While
''End If
''strBuilder.Replace(item, "<span style='background-color: rgb(255, 255, 0);'>" + item + "</span>")
Next
Else
''strBuilder.Replace("<span style='background-color: rgb(255, 255, 0);'>", "<span style='background-color: rgb(255, 255, 255);'>")
End If
doc2.body.innerHTML = HTMLString
End Sub
I have this simple code to test that a DB is ready:
Function testlocalcon() As Boolean
Dim constr As String = _clconstr
Try
Using t As New SqlConnection()
constr = constr & " ; Connect Timeout=1"
If Not t.State = Data.ConnectionState.Open Then
t.ConnectionString = constr
t.Open()
If t.State = Data.ConnectionState.Open Then
Return True
Else
Return False
End If
Else
Return True
End If
End Using
Catch ex As Exception
Return False
End Try
End Function
I do not want to execute a query, just to check the connection, but no matter what the time out parameter is ignored. I search here (Stackoverflow) and internet and found nothing in how to fix this.
Any one else have this problem? Or, are there any other ideas on how to let the application know that the DB is ready?
I appologize for the code differenc but this is C# and I have used it in the past. Its pretty simple and should be readable.
private SQLServerConnection
private SqlConnection _SQLServerConnection;
public SqlConnection SQLServerConnection
{
get
{
return _SQLServerConnection;
}
set
{
_SQLServerConnection = value;
}
}
private void SetSQLServerConnectionString (string sqlServerName, string databaseName, string saPassword, int connectTimeout)
{
SQLServerConnection = new SqlConnection("Password=" + saPassword + ";Persist Security Info=True;User ID=sa;Initial Catalog=" + databaseName + ";Data Source=" + sqlServerName + ";connection timeout=" + connectTimeout.ToString(CultureInfo.InvariantCulture));
}
internal bool TestSQLServerConnection(string sqlServerName, string databaseName, string saPassword, int connectTimeout)
{
try
{
SetSQLServerConnectionString(sqlServerName, databaseName, saPassword, connectTimeout);
SQLServerConnection.Open();
return true;
}
catch (SqlException e)
{
return false;
}
finally
{
SQLServerConnection.Close();
}
}