Thursday, June 28, 2012

C# deserialize JSON post


[Serializable]
public class Person
{
  public int personId;
  public int appId;
  public string name;
}
 
string input = new StreamReader(Request.InputStream).ReadToEnd();
JavaScriptSerializer deserializer = new JavaScriptSerializer();

Person _person = deserializer.Deserialize(input);
Console.Writeline(string.Format("Person delivered is: {0}", _person.name));

You can test this with the code below --------------------------------------------------:

string url = "the_test_url";
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
StringBuilder jsonData = new StringBuilder();

jsonData.AppendLine("{");
jsonData.AppendLine("\"personId\" : 1234,");
jsonData.AppendLine("\"appId\" : 2334,");
jsonData.AppendLine("\"name\" : \"John\"");
jsonData.Append("}");

byte[] dataArray = Encoding.UTF8.GetBytes(jsonData.ToString());
httpReq.Method = @"POST";
httpReq.ContentType = @"application/json";
httpReq.ContentLength = dataArray.Length;
httpReq.Timeout = 60000; // 1 minute (in milliseconds)
httpReq.KeepAlive = false;

using (Stream requestStream = httpReq.GetRequestStream())
{
  requestStream.Write(dataArray, 0, dataArray.Length);
  requestStream.Flush();
  requestStream.Close();
}
HttpWebResponse _resp = (HttpWebResponse)httpReq.GetResponse();
_resp.Close();

Wednesday, June 27, 2012

Using SQL recursion


This example will generate an employee/manager heirarchy.

DECLARE @employeeId INT
SET @employeeId = 123
WITH emp_hier AS
(
SELECT e.employeeId , e.managerEmployeeId, l.JobLevel as employeeLevel
FROM EmployeeData e
INNER JOIN EmployeeJobLevel l ON l.JobLevel=e.JobLevel
WHERE e.employeeId = @employeeid
UNION ALL
SELECT e2.employeeId , e2.managerEmployeeId, c2.JobLevel as employeeLevel
FROM EmployeeData e2
INNER JOIN EmployeeJobLevel  l2 ON l2.JobLevel=l2.JobLevel
INNER JOIN emp_hier ecte ON ecte.managerEmployeeId= g2.employeeId
WHERE ecte.employeeId <> ISNULL(g2.managerEmployeeId, -1) --This clause prevents maximum recursion error when two employees share each other as their supervisors
)

SELECT *
FROM emp_hier