Web Service REST Calls With C#

The .NET Framework provides classes for performing HTTP requests. This HOWTO describes how to perform both GET and POST requests.

Overview

The System.Net namespace contains the HttpWebRequest and HttpWebResponse classes which fetch data from web servers and HTTP based web services. Often you will also want to add a reference to System.Webwhich will give you access to the HttpUtility class that provides methods to HTML and URL encode and decode text strings.

Yahoo! Web Services return XML data. While some web services can also return the data in other formats, such as JSON and Serialized PHP, it is easiest to utilize XML since the .NET Framework has extensive support for reading and manipulating data in this format.

Simple GET Requests

The following example retrieves a web page and prints out the source.

C# GET SAMPLE 1

  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Text;
  5. // Create the web request
  6. HttpWebRequest request = WebRequest.Create(https://developer.yahoo.com/”as HttpWebRequest;
  7. // Get response
  8. using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
  9. {
  10.     // Get the response stream
  11.     StreamReader reader = new StreamReader(response.GetResponseStream());
  12.     // Console application output
  13.     Console.WriteLine(reader.ReadToEnd());
  14. }

Simple POST Requests

Some APIs require you to make POST requests. To accomplish this we change the request method and content type and then write the data into a stream that is sent with the request.

C# POST SAMPLE 1

  1. // We use the HttpUtility class from the System.Web namespace
  2. using System.Web;
  3. Uri address = new Uri(http://api.search.yahoo.com/ContentAnalysisService/V1/termExtraction”);
  4. // Create the web request
  5. HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
  6. // Set type to POST
  7. request.Method = “POST”;
  8. request.ContentType = “application/x-www-form-urlencoded”;
  9. // Create the data we want to send
  10. string appId = “YahooDemo”;
  11. string context = “Italian sculptors and painters of the renaissance”
  12.                     + “favored the Virgin Mary for inspiration”;
  13. string query = “madonna”;
  14. StringBuilder data = new StringBuilder();
  15. data.Append(“appid=” + HttpUtility.UrlEncode(appId));
  16. data.Append(“&context=” + HttpUtility.UrlEncode(context));
  17. data.Append(“&query=” + HttpUtility.UrlEncode(query));
  18. // Create a byte array of the data we want to send
  19. byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
  20. // Set the content length in the request headers
  21. request.ContentLength = byteData.Length;
  22. // Write data
  23. using (Stream postStream = request.GetRequestStream())
  24. {
  25.     postStream.Write(byteData, 0, byteData.Length);
  26. }
  27. // Get response
  28. using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
  29. {
  30.     // Get the response stream
  31.     StreamReader reader = new StreamReader(response.GetResponseStream());
  32.     // Console application output
  33.     Console.WriteLine(reader.ReadToEnd());
  34. }

HTTP Authenticated requests

The del.icio.us API requires you to make authenticated requests, passing your del.icio.us username and password using HTTP authentication. This is easily accomplished by adding an instance ofNetworkCredentials to the request.

C# HTTP AUTHENTICATION

  1. // Create the web request
  2. HttpWebRequest request
  3.     = WebRequest.Create(https://api.del.icio.us/v1/posts/recent”as HttpWebRequest;
  4. // Add authentication to request
  5. request.Credentials = new NetworkCredential(“username”“password”);
  6. // Get response
  7. using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
  8. {
  9.     // Get the response stream
  10.     StreamReader reader = new StreamReader(response.GetResponseStream());
  11.     // Console application output
  12.     Console.WriteLine(reader.ReadToEnd());
  13. }

Error Handling

Email Send in C#

private static int SendEmail()
{
// email setting
string sSMTPHost = ConfigurationManager.AppSettings[“SMTPHost”];
string sSMTPEmail = ConfigurationManager.AppSettings[“SMTPEmail”];
string sSMTPPassword = ConfigurationManager.AppSettings[“SMTPPassword”];
string sSMTPPort = ConfigurationManager.AppSettings[“SMTPPort”];
string sToMail = ConfigurationManager.AppSettings[“ToMail”];
int iSMTPPort = Convert.ToInt16(sSMTPPort);

// email send status
int iSendEmail = 1;
// end of email setting

// ReadFileLoc
string sBody = “”;
string ReadFileLoc = Convert.ToString(ConfigurationManager.AppSettings[“ReadFileLoc”]);
string emailSubject = Convert.ToString(ConfigurationManager.AppSettings[“emailSubject”]);
sBody = Convert.ToString(ConfigurationManager.AppSettings[“emailBody”]);

var fromAddress = new MailAddress(sSMTPEmail);
var fromPassword = sSMTPPassword;
var toAddress = new MailAddress(sToMail);

string subject = “”;

MailMessage mail = new MailMessage();

mail.From = new MailAddress(fromAddress.ToString(), “Organization Name”, System.Text.Encoding.UTF8);
mail.To.Add(toAddress);
mail.Subject = emailSubject;

//// //Creating AlternateView for Plain Text Mail
AlternateView normalView = AlternateView.CreateAlternateViewFromString(sBody, null, “text/plain”);

//// //Creating AlternateView for HTML Mail
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(sBody, null, “text/html”);

System.Net.Mail.Attachment data;
data = new System.Net.Mail.Attachment(ReadFileLoc + getFileName(“1”));

// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(data.ToString());
disposition.ModificationDate = System.IO.File.GetLastWriteTime(data.ToString());
disposition.ReadDate = System.IO.File.GetLastAccessTime(data.ToString());

mail.Attachments.Add(data);

System.Net.Mail.Attachment data1;
data1 = new System.Net.Mail.Attachment(ReadFileLoc + getFileName(“2”));

// Add time stamp information for the file.
disposition = data1.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(data1.ToString());
disposition.ModificationDate = System.IO.File.GetLastWriteTime(data1.ToString());
disposition.ReadDate = System.IO.File.GetLastAccessTime(data1.ToString());

mail.Attachments.Add(data1);

mail.AlternateViews.Add(normalView);
mail.AlternateViews.Add(htmlView);

System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient
{
Host = sSMTPHost,
Port = iSMTPPort,
EnableSsl = false,
DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)

};

try
{

smtp.Send(mail);

Console.WriteLine(“Email Send Successfully.”);

}
catch (Exception ex)
{
iSendEmail = 0;
Console.WriteLine(“SendEmail: ” + ex.ToString());

}

return iSendEmail;
}

Add returning Clause in Insert statement in oracle and get last inserted value using c#

static void Main(string[] args)
{
OracleConnection conn = new OracleConnection(“Data Source=localhost; User Id=test;Password=test; Integrated Security=no;”);
OracleCommand cmd = new OracleCommand(“insert into orders (name) values(:nameToInsert) returning id into :outId”, conn);

OracleParameter p1 = new OracleParameter(“nameToInsert”, OracleType.VarChar);
OracleParameter p2 = new OracleParameter(“outId”, OracleType.Int32);

p1.Value = “John Doe”;
p2.Direction = ParameterDirection.Output;

cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);

conn.Open();
cmd.ExecuteNonQuery();
conn.Close();

int insertedId = (int)p2.Value;
}

Large File Uploading in ASP.NET

In your web.config, add a line under your system.web
 <httpRuntime executionTimeout="54000" maxRequestLength="512000" />
 where execution timeout is in seconds, and maxRequestLength is in KB.
 executionTimeout, is basically the amount of time a thread will continue 
to run, and accept data by IIS/.NET. maxRequestLength, is the total amount
 of data that can be sent through HTTP Post to the server. 
The default is 4MB (4096)...and is generally set low so that
 your server will not be overwhelmed by possible DoS attacks.

Group wise Serial No in Crystal Report

if you want to view report like the following ways

Group 1
1 Abc xyz
2 abc xyx
3 abc xyz
Group 2
1 abc xyz
2 abc xyz
Group 3
1 abc xyz
2 abc xyz
3 abc xyz
4 abc xyz

you can do this things by the following settings

Right click -> New on the on the Running total fields.

1. Enter the running total name , i.e; rtotal1
2. From summary Section set the the following
2.1 Select a filed name to summarize
2.2 Set type of Summary to Count
3. From evaluate section set for each record
4. from Reset section select on changing to group

and now put this rtotal1 field in your report.

UTL_MATCH : String Matching by Testing Levels of Similarity/Difference

The examples in this article require the following table definition.

DROP TABLE match_tab;

CREATE TABLE match_tab (
id NUMBER,
col1 VARCHAR2(15),
col2 VARCHAR2(15),
CONSTRAINT match_tab_pk PRIMARY KEY (id)
);

INSERT INTO match_tab VALUES (1, 'Peter Parker', 'Pete Parker');
INSERT INTO match_tab VALUES (2, 'Peter Parker', 'peter parker');
INSERT INTO match_tab VALUES (3, 'Clark Kent', 'Claire Kent');
INSERT INTO match_tab VALUES (4, 'Wonder Woman', 'Ponder Woman');
INSERT INTO match_tab VALUES (5, 'Superman', 'Superman');
INSERT INTO match_tab VALUES (6, 'The Hulk', 'Iron Man');
COMMIT;


EDIT_DISTANCE

The “Edit Distance”, or “Levenshtein Distance”, test measures the similarity between two strings by counting the number of character changes (inserts, updates, deletes) required to transform the first string into the second. The number of changes required is know as the distance.

SELECT col1,
       col2,
       UTL_MATCH.edit_distance(col1, col2) AS ed
FROM   match_tab
ORDER BY id;

COL1            COL2                    ED
--------------- --------------- ----------
Peter Parker    Pete Parker              1
Peter Parker    peter parker             2
Clark Kent      Claire Kent              2
Wonder Woman    Ponder Woman             1
Superman        Superman                 0
The Hulk        Iron Man                 8

6 rows selected.

SQL>

EDIT_DISTANCE_SIMILARITY

The EDIT_DISTANCE_SIMILARITY function uses the same method as the EDIT_DISTANCE function to determine the similarity of the strings, but it returns a normalized result ranging from 0 (no match) to 100 (complete match).

SELECT col1,
       col2,
       UTL_MATCH.edit_distance_similarity(col1, col2) AS eds
FROM   match_tab
ORDER BY id;

COL1            COL2                   EDS
--------------- --------------- ----------
Peter Parker    Pete Parker             92
Peter Parker    peter parker            84
Clark Kent      Claire Kent             82
Wonder Woman    Ponder Woman            92
Superman        Superman               100
The Hulk        Iron Man                 0

6 rows selected.

SQL>


SELECT id,
       col1,
       col2,
       UTL_MATCH.edit_distance_similarity(col1, col2) AS eds
FROM   match_tab
WHERE  UTL_MATCH.edit_distance_similarity(col1, col2) > 90
ORDER BY id;

        ID COL1            COL2                   EDS
---------- --------------- --------------- ----------
         1 Peter Parker    Pete Parker             92
         4 Wonder Woman    Ponder Woman            92
         5 Superman        Superman               100

SQL>

JARO_WINKLER

The “Jaro-Winkler Algorithm” provides a different method for finding the distance between two strings.

SELECT col1,
       col2,
       UTL_MATCH.jaro_winkler(col1, col2) AS jw
FROM   match_tab
ORDER BY id;

COL1            COL2                    JW
--------------- --------------- ----------
Peter Parker    Pete Parker     9.288E-001
Peter Parker    peter parker    8.889E-001
Clark Kent      Claire Kent     9.083E-001
Wonder Woman    Ponder Woman    9.444E-001
Superman        Superman          1.0E+000
The Hulk        Iron Man        4.167E-001

6 rows selected.

SQL>

JARO_WINKLER_SIMILARITY

The JARO_WINKLER_SIMILARITY function uses the same method as the JARO_WINKLER function to determine the similarity of the strings, but it returns a normalized result ranging from 0 (no match) to 100 (complete match).

SELECT col1,
       col2,
       UTL_MATCH.jaro_winkler_similarity(col1, col2) AS jws
FROM   match_tab
ORDER BY id;

COL1            COL2                   JWS
--------------- --------------- ----------
Peter Parker    Pete Parker             92
Peter Parker    peter parker            88
Clark Kent      Claire Kent             90
Wonder Woman    Ponder Woman            94
Superman        Superman               100
The Hulk        Iron Man                41

6 rows selected.

SQL>


SELECT col1,
       col2,
       UTL_MATCH.jaro_winkler_similarity(col1, col2) AS jws
FROM   match_tab
WHERE  UTL_MATCH.jaro_winkler_similarity(col1, col2) > 90
ORDER BY id;

COL1            COL2                   JWS
--------------- --------------- ----------
Peter Parker    Pete Parker             92
Wonder Woman    Ponder Woman            94
Superman        Superman               100

SQL>

For more information see: