While viewing some of the C# code written by a new programmer, I noticed that they lack of calling Dispose() method on SqlConnection and SqlCommand objects. And the dabase code was not placed in try/finally blocks. This coding style is typical newbie style of development that everyone, including myself, attempted in the very beginning.
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(commandString, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
The problem in the above code is that SqlConnection and SqlCommand implement IDisposable, which means they could have unmanaged resources to cleanup and it is our job, to make sure Dispose() gets called on these classes after we are finished with them. And, because an exception could be raised if the database is unavailable, we need to make sure Dispose() gets called even in the case of an exception.
Its better to use the “using” keyword in C#. Internally, this generates a try / finally around the object being allocated and calls Dispose() for you. It saves you the hassle of manually creating the try / finally block and calling Dispose().
The new code would looking something like this:
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(commandString, con))
{
con.Open();
cmd.ExecuteNonQuery();
}
}
This is essentially equivalent to the following:
SqlConnection con = null;
SqlCommand cmd = null;
try
{
con = new SqlConnection(connectionString);
cmd = new SqlCommand(commandString, cn);
con.Open();
cmd.ExecuteNonQuery();
}
finally
{
if (null != cm);
cmd.Dispose();
if (null != cn)
con.Dispose();
}
You may notice the lack of calling Close() on the SqlConnection class, con. Internally, Dispose() checks the status of the connection and closes it for you. Therefore, technically you don’t need to call Close() on the connection (con) as Dispose() will do it for you. In addition, Dispose() destroys the connection string of the SqlConnection class. Therefore, if you want to re-open the connection after calling Dispose() on con, you will have to re-establish the connection string. Not doing so will throw an exception.
VN:F [1.6.3_896]
Rating: 4.7/5 (3 votes cast)
Some times we do have a requirement to call external web pages through our application.
The System.Net.HttpWebRequest Class allow us to make a call to any web page programmatically.
In the below code you will see how we can make a call to any webpage and get there response on our page.
if (!(IsPostBack))
{
try
{
System.Net.HttpWebRequest webReader;
Uri targetUri = new Uri("http://www.soliddotnet.com/index.php/contributors/neeraj-mathur");
webReader = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(targetUri);
//In the above code http://www.soliddotnet.com/index.php/contributors/neeraj-mathur/ is used as an example
//it can be a different domain with a different filename and extension
if ((webReader.GetResponse().ContentLength > 0))
{
System.IO.StreamReader strResponse = new System.IO.StreamReader(webReader.GetResponse().GetResponseStream());
Response.Write(strResponse.ReadToEnd());
if (strResponse != null) strResponse.Close();
}
}
catch (System.Net.WebException ex)
{
Response.Write("Page does not exist.");
}
}
NOTE: If you will try to access any web page from your localhost then this example wont work at all, you need to be on web domain to test this code
Now comes How to use HttpWebRequest to send POST request to another web server?
Typical example of this kind of situation is when you need to access some web resource through your application and that requires login credentials, So for this you can send post request to another server.
private void OnPostInfoClick(object sender, System.EventArgs e)
{
string strUserId = txtUserId.Text;
string strPassword = txtPassword.Text;
ASCIIEncoding encoding=new ASCIIEncoding();
string postData="userid="+strUserId;
postData += ("&password="+strPassword);
byte[] data = encoding.GetBytes(postData);
// Prepare web request...
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http://yourwebresource/MyIdentity/Default.aspx");
myRequest.Method = "POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream=myRequest.GetRequestStream();
// Send the data.
newStream.Write(data,0,data.Length);
newStream.Close();
}
Resources :
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
http://www.codeproject.com/KB/IP/httpwebrequest_response.aspx
VN:F [1.6.3_896]
Rating: 5.0/5 (1 vote cast)
If your browser is capable of rendering the content type (or has a plugin that does
so), it will render the binary content when you click on a link to the handler.
However , if you’d prefer to have a Download dialog appear instead, you need to set the
Content-Disposition header like so:
Response.AddHeader("Content-Disposition",
"attachment; filename=\"MyFile.doc\"");
This code will display a File Save dialog in which the filename is defaulted to MyFile.doc.
VN:F [1.6.3_896]
Rating: 2.5/5 (2 votes cast)
While working as a developer we all face some syntax problem , So in order to reduce that same redundant syntax search effort everyday Technology people had compiled very good single page handy sheets which contains syntax and common features of each technology which is also known as Cheat Sheets, And i think every developer should have them.
These Cheat sheets are normally one-page reference guide
1. .NET Quick Reference
2. ASP.NET 2.0 Page Life Cycle & Common Event
3. Visual Studio Built-in Code Snippets (C#)
4. Quick Reference to JavaScript
5. ASP – Active Server Pages & ASP.Net
6. Quick Reference to C# common functions and methods
7. Quick Reference to Regular Expression
8. SQL – Structured Query Language
9. UML – Unified Modeling Language
10. XML – eXtensible Markup Language
11. Jquery cheat Sheet
12. AJAX
13. Others
VN:F [1.6.3_896]
Rating: 4.3/5 (4 votes cast)