Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, 23 March 2012

MVC 4 Web API access Session

It's not recommended to use Session  in Web API for various of good reasons. However, in case you're still so interested to access Session for any business needs, here is a quick solution to allow accessing Session in Web API.

 
// In global.asax
public class MvcApp : System.Web.HttpApplication
{
 public static void RegisterRoutes(RouteCollection routes)
 {
  var route = routes.MapHttpRoute(
   name: "DefaultApi",
   routeTemplate: "api/{controller}/{id}",
   defaults: new { id = RouteParameter.Optional }
  );
  route.RouteHandler = new MyHttpControllerRouteHandler();
 }
}

// Create two new classes
public class MyHttpControllerHandler : HttpControllerHandler, IRequiresSessionState
{
 public MyHttpControllerHandler(RouteData routeData): base(routeData)
 {
 }
}
public class MyHttpControllerRouteHandler : HttpControllerRouteHandler
{
 protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
 {
  return new MyHttpControllerHandler(requestContext.RouteData);
 }
}

// Now Session is visible in your Web API
public class ValuesController : ApiController
{
 public string GET(string input)
 {
  var session = HttpContext.Current.Session;
  if (session != null)
  {
   if (session["Time"] == null)
    session["Time"] = DateTime.Now;
   return "Session Time: " + session["Time"] + input;
  }
  return "Session is not availabe" + input;
 }
}
 



Source is here.

Sunday, 13 November 2011

Manage IIS Application Pool from .Net C# code

  .Net framework provides a very easy-to-use API wrapper class, ServerManager, to help manage IIS system from any .Net application using either C# or VB.net. Below C# code snippet demonstrates how to restart/recycle a given AppPool in IIS.
     
    public void RestartAppPool(string appPool)
        {
            try
            {
                logger.Info("Restarting app pool: " + appPool);

                // Recycle app pool
                using (var manager = new ServerManager())
                {
                    var pool = manager.ApplicationPools[appPool];

                    if (pool != null) 
                    {
                        Process process = null;

                        if (pool.WorkerProcesses.Count > 0)
                        {
                            process = Process.GetProcessById(pool.WorkerProcesses[0].ProcessId);
                        }

                        if (pool.State == ObjectState.Stopped)
                            pool.Start();
                        else
                            pool.Recycle();

                        // clean up any worker thread created by app pool
                        if (process != null)
                        {
                            while (!process.HasExited)
                            {
                                Thread.Sleep(10);
                            }

                            process.Dispose();
                        }
                    }
                }

                //logger.Info("Successfully restarted app pool: " + appPool);
            }
            catch (Exception ex)
            {
               // logger.Error("Restart app pool error: " + ex);
            }
        }
 

Friday, 23 September 2011

JQuery Ajax Call to Web service via POST

Have been used a lots of jquery in the recent real-time information web development project, I found this quite easy to initiate a POST HTTP call to web service through JQuery. Here are 2 sample code snippets.

Case 1: Pass no parameter

 
<script type="text/javascript">
    // in this case, we post nothing back to api but
    // just call it (no parameter required) and expected json object as result
    function callWebApiViaPost() {
        $.ajax({
            type: "POST",
            url: "yourwebapi",
            data: "{}",
            contentType: "application/json;",
            dataType: "json",
            success: function (t) {
                $("#your_result_display_div").text(t.d);
            }
        });
    }

</script>
 

Case 2: Pass parameter(s)

For example, you have a API like below:
 
[WebMethod]
public static string ToUpperCase(string yourparam)
{
    return yourparam.ToUpper();
}
 
The corresponding jquery ajax post call will be like this:
 
<script type="text/javascript">
    // in this case, we post nothing back to api but
    // just call it (no parameter required) and expected json object as result
    function callWebApiViaPost() {
        $.ajax({
            type: "POST",
            url: "yourweb/ToUpperCase",
            data: "{yourparam: 'hello-world'}",
            contentType: "application/json;",
            dataType: "json",
            success: function (t) {
                $("#your_result_display_div").text(t.d);
            }
        });
    }

</script>
 

Thursday, 8 September 2011

Dynamically add CSS file to ASP.Net page

Programmatically include CSS file to ASP.Net page is considerable simple. Add follow code to your page initialization event. Next time when page was loaded, reference to your css file will be added at runtime.

 
    protected void Page_Init(object sender, EventArgs e)
    {
        HtmlLink css = new HtmlLink();
        css.Href = "css/fancyforms.css";
        css.Attributes["rel"] = "stylesheet";
        css.Attributes["type"] = "text/css";
        css.Attributes["media"] = "all";
        Page.Header.Controls.Add(css);
    }
 

Tuesday, 6 September 2011

Detect Browser or User Agent from Server-side

My previous post on Detect Browser or User Agent using JavaScript has described a solution on how to do it from client-side. Today, I want to show how to detect user agent or browser type at server-side. It's quite straightforward under ASP.Net framework. Put the following code in your Global.asax so it checks for every new request. The sample code is written in C# and can be in any .Net language.


 
public class Global : System.Web.HttpApplication
{
    void Session_Start(object sender, EventArgs e)
    {
        DetectBrowser();
    }
    // detect browser type by checking user agent
    // and then do specific things for each platform
    private void DetectBrowser()
    {
        string agent = Request.UserAgent.ToLower();
        if (agent.Contains("iphone") ||
            agent.Contains("symbianos") || 
            agent.Contains("ipad") || 
            agent.Contains("ipod") || 
            agent.Contains("android") || 
            agent.Contains("blackberry") || 
            agent.Contains("samsung") || 
            agent.Contains("nokia") || 
            agent.Contains("windows ce") || 
            agent.Contains("sonyericsson") || 
            agent.Contains("webos") || 
            agent.Contains("wap") || 
            agent.Contains("motor") || 
            agent.Contains("symbian"))
        {
            // do your logic here for device specific requests
        }
        else
        {
            // do your logic here for PC/Mac requests
        }
    }
}
 

Thursday, 1 September 2011

Generate Random bytes using C#

There is a quick way to generate random bytes for any given size using .Net framework. Why people would want to do so? I personally find it very handy in case I need to test network flow, encryption and/or do load/stress testing. Here is the code that you can past to your project. It generate a random bytes array for the given size.
 
public static byte[] GenerateRandomBytes(int length)
{
      // Create a buffer
      byte[] randBytes;
 
      if (length >= 1)
       {
            randBytes = new byte[length];
        }
        else
        {
            randBytes = new byte[1];
        }

        // Create a new RNGCryptoServiceProvider.
        System.Security.Cryptography.RNGCryptoServiceProvider rand = 
             new System.Security.Cryptography.RNGCryptoServiceProvider();

        // Fill the buffer with random bytes.
        rand.GetBytes(randBytes);

        // return the bytes.
        return randBytes;
}
 
 

Wednesday, 31 August 2011

Convert XML to JSON using C#

Here is the working solution I borrowed and modified from somewhere. But I forgot the original source. If you're the original author, please let me know if you'd like your name listed on this post.

 
public static class JSon
{
    public static string XmlToJSON(string xml)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);

        return XmlToJSON(doc);
    }
    public static string XmlToJSON(XmlDocument xmlDoc)
    {
        StringBuilder sbJSON = new StringBuilder();
        sbJSON.Append("{ ");
        XmlToJSONnode(sbJSON, xmlDoc.DocumentElement, true);
        sbJSON.Append("}");
        return sbJSON.ToString();
    }

    //  XmlToJSONnode:  Output an XmlElement, possibly as part of a higher array
    private static void XmlToJSONnode(StringBuilder sbJSON, XmlElement node, bool showNodeName)
    {
        if (showNodeName)
            sbJSON.Append("\"" + SafeJSON(node.Name) + "\": ");
        sbJSON.Append("{");
        // Build a sorted list of key-value pairs
        //  where   key is case-sensitive nodeName
        //          value is an ArrayList of string or XmlElement
        //  so that we know whether the nodeName is an array or not.
        SortedList<string, object> childNodeNames = new SortedList<string, object>();

        //  Add in all node attributes
        if (node.Attributes != null)
            foreach (XmlAttribute attr in node.Attributes)
                StoreChildNode(childNodeNames, attr.Name, attr.InnerText);

        //  Add in all nodes
        foreach (XmlNode cnode in node.ChildNodes)
        {
            if (cnode is XmlText)
                StoreChildNode(childNodeNames, "value", cnode.InnerText);
            else if (cnode is XmlElement)
                StoreChildNode(childNodeNames, cnode.Name, cnode);
        }

        // Now output all stored info
        foreach (string childname in childNodeNames.Keys)
        {
            List<object> alChild = (List<object>)childNodeNames[childname];
            if (alChild.Count == 1)
                OutputNode(childname, alChild[0], sbJSON, true);
            else
            {
                sbJSON.Append(" \"" + SafeJSON(childname) + "\": [ ");
                foreach (object Child in alChild)
                    OutputNode(childname, Child, sbJSON, false);
                sbJSON.Remove(sbJSON.Length - 2, 2);
                sbJSON.Append(" ], ");
            }
        }
        sbJSON.Remove(sbJSON.Length - 2, 2);
        sbJSON.Append(" }");
    }

    //  StoreChildNode: Store data associated with each nodeName
    //                  so that we know whether the nodeName is an array or not.
    private static void StoreChildNode(SortedList<string, object> childNodeNames, string nodeName, object nodeValue)
    {
        // Pre-process contraction of XmlElement-s
        if (nodeValue is XmlElement)
        {
            // Convert  <aa></aa> into "aa":null
            //          <aa>xx</aa> into "aa":"xx"
            XmlNode cnode = (XmlNode)nodeValue;
            if (cnode.Attributes.Count == 0)
            {
                XmlNodeList children = cnode.ChildNodes;
                if (children.Count == 0)
                    nodeValue = null;
                else if (children.Count == 1 && (children[0] is XmlText))
                    nodeValue = ((XmlText)(children[0])).InnerText;
            }
        }
        // Add nodeValue to ArrayList associated with each nodeName
        // If nodeName doesn't exist then add it
        List<object> ValuesAL;

        if (childNodeNames.ContainsKey(nodeName))
        {
            ValuesAL = (List<object>)childNodeNames[nodeName];
        }
        else
        {
            ValuesAL = new List<object>();
            childNodeNames[nodeName] = ValuesAL;
        }
        ValuesAL.Add(nodeValue);
    }

    private static void OutputNode(string childname, object alChild, StringBuilder sbJSON, bool showNodeName)
    {
        if (alChild == null)
        {
            if (showNodeName)
                sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
            sbJSON.Append("null");
        }
        else if (alChild is string)
        {
            if (showNodeName)
                sbJSON.Append("\"" + SafeJSON(childname) + "\": ");
            string sChild = (string)alChild;
            sChild = sChild.Trim();
            sbJSON.Append("\"" + SafeJSON(sChild) + "\"");
        }
        else
            XmlToJSONnode(sbJSON, (XmlElement)alChild, showNodeName);
        sbJSON.Append(", ");
    }

    // Make a string safe for JSON
    private static string SafeJSON(string sIn)
    {
        StringBuilder sbOut = new StringBuilder(sIn.Length);
        foreach (char ch in sIn)
        {
            if (Char.IsControl(ch) || ch == '\'')
            {
                int ich = (int)ch;
                sbOut.Append(@"\u" + ich.ToString("x4"));
                continue;
            }
            else if (ch == '\"' || ch == '\\' || ch == '/')
            {
                sbOut.Append('\\');
            }
            sbOut.Append(ch);
        }
        return sbOut.ToString();
    }
}
 
To convert a given XML string to JSON, simply call XmlToJSON() function as below.
 
 
string xml = "<menu id=\"file\" value=\"File\"> " +
                  "<popup>" +
                    "<menuitem value=\"New\" onclick=\"CreateNewDoc()\" />" +
                    "<menuitem value=\"Open\" onclick=\"OpenDoc()\" />" +
                    "<menuitem value=\"Close\" onclick=\"CloseDoc()\" />" +
                  "</popup>" +
                "</menu>";

    string json = JSON.XmlToJSON(xml);
    // json = { "menu": {"id": "file", "popup": { "menuitem": [ {"onclick": "CreateNewDoc()", "value": "New" }, {"onclick": "OpenDoc()", "value": "Open" }, {"onclick": "CloseDoc()", "value": "Close" } ] }, "value": "File" }}
 

Output JSON from WCF RESTful Web Service


Under Microsoft WCF 4 framework, output either XML or JSON is fairly straightforward by simply setting a proper attribute property in your public service API function.

 
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class MyWebService
{
   [OperationContract]
   [WebGet(UriTemplate = "MyWebFunction/{userReq}", 
           ResponseFormat = WebMessageFormat.Json )]
   public string MyWebFunction(string userReq)
   {
      // do your magic here
      return "your magic result";
   }
   
   // your other public web function(s)
}
 

Thursday, 25 August 2011

Dynamically add meta tags in ASP.Net

Add the following code to master page on the page_load event handler. All it does is to add a keyword meta tag to the header of the html page from server-side, which opens a door to all other possibilities.

protected void Page_Load(object sender, EventArgs e)
{
   HtmlMeta meta = new HtmlMeta();
   meta.Name = "keywords";
   meta.Content = "ASP.Net, Web, meta tag";
   Header.Controls.Add(meta);
}