Tuesday, December 17, 2013

How to Convert JSON XML string representation to Object in C#

my workmate had asked me this question for while.. I gave him the solution is that he did not need to convert the JSon object to C#object. he can create a new store procedure to load the data into the C# object.

currently i worked on a project that i need to consume the JSon object via the WCF  (Windows communication foundation). Since I did not have the control on the data source, it means that i can call the store procedure to load those data into the C# object.

JSON.Net is the solution to deserialzie the json object back to .net object.


http://james.newtonking.com/json

http://json.codeplex.com/

First we will define C# object with Properties matching to the json object.

here is the json sample object from
http://adobe.github.io/Spry/samples/data_region/JSONDataSetSample.html

{
 "id": "0001",
 "type": "donut",
 "name": "Cake",
 "ppu": 0.55,
 "batters":
  {
   "batter":
    [
     { "id": "1001", "type": "Regular" },
     { "id": "1002", "type": "Chocolate" },
     { "id": "1003", "type": "Blueberry" },
     { "id": "1004", "type": "Devil's Food" }
    ]
  },
 "topping":
  [
   { "id": "5001", "type": "None" },
   { "id": "5002", "type": "Glazed" },
   { "id": "5005", "type": "Sugar" },
   { "id": "5007", "type": "Powdered Sugar" },
   { "id": "5006", "type": "Chocolate with Sprinkles" },
   { "id": "5003", "type": "Chocolate" },
   { "id": "5004", "type": "Maple" }
  ]
}
 
 
we define the c# object MyJson based on the JSon xml Schema

public class MyJson    {
        [JsonProperty("id")]
        public string id
        {
            get;
            set;
        }
        [JsonProperty("type")]
        public string type
        {
            get;
            set;
        }
        [JsonProperty("name")]
        public string name
        {
            get;
            set;
        }
        [JsonProperty("Pricing")]
        public Pricing Pricing
        {
            get;
            set;
        }

        [JsonProperty("ppu")]
        public string ppu
        {
            get;
            set;
        }

        [JsonProperty("batters")]
        public batters batters

        {
            get;
            set;
        }

      [JsonProperty("topping")]
        public topping[] topping

        {
            get;
            set;
        }


      

    }

    public class batters
    {
        [JsonProperty("batter")]
        public  batter[] batter
        {
            get;
            set;
        }
}

  public class batter
    {
        [JsonProperty("id")]
        public string id
        {
            get;
            set;
        }

        [JsonProperty("type")]
        public string type
        {
            get;
            set;
        }
}


  public class topping
    {
        [JsonProperty("id")]
        public string id
        {
            get;
            set;
        }

        [JsonProperty("type")]
        public string type
        {
            get;
            set;
        }
}

in my sample i will convert the json object in my page load event

 protected void Page_Load(object sender, EventArgs e)
        {
            using (var webClient = new System.Net.WebClient())
            {
                 try
                {
                    var jsonString = webClient.DownloadString("Your WCF Url with paramter input options");
                    // if you need to remove any string that did not need in the json xml string.
                    jsonString = jsonString.Replace("{\"MyJSonOjects\":", "").TrimEnd('}');
                   //use JsonConvert object in Json.Net to deserialize the json to .net Object.
                    List<MyJson> MyJsonList= JsonConvert.DeserializeObject<List<MyJson >(jsonString) as List<MyJson>;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }



       

Monday, November 18, 2013

How to use regular expression to trim leading and trailing characters of a specific character in C#

After i enabled filter on the Telerik Grid, the grid filter was not function property, when i copied and paste those search criteria into the filter textbox.

the root cause of this issue is that when i highlight and copy the context in the grid. the context was copied with space in the front and end.  I must trim those leading and trailing space

the following is the filter syntax that i grab via the visual studio debugger

MyColumnName.Contains("  MySearchCriteria  ")

so I need to clear the space before and after double quotation mark.

the regular expression is the good fit for this issue.

first i will define the regular expression pattern to represent the issue.

s*: space appears 0 or more in the string.
\s*\""\*: space before and after the double quotation mark.

var slashRegex = new Regex(@"(?:\s*\""\s*)+");
 
var filterExpression=MyColumnName.Contains("  MySearchCriteria  "); 
  
filterExpression = slashRegex.Replace(filterExpression, "\"");
 

after i apply the regular expression. 


MyColumnName.Contains("MySearchCriteria")

Thursday, September 26, 2013

How to qucikly launch Task Managment Window

it should be hard to launch the CMD command window after i accidently close it in windows Server 2008 Core.

since the administrator had setup my profit to have CMD prompt since i log into the server with Remote access. i do not have access CMD Prompte after i close it. we should be able to access the
task window by using Ctrl-Alt-Del command to launch the login screen. However this command always trigger the login screen of host window.

here is the quickly solution to access the Task Manager Window in the remote server.


Ctrl+Shift+Esc will work to start Task Manager.

Tuesday, August 27, 2013

How to import unicode characters from Excel to SQL Server

I got a complaint this monring

when the user run the import application to extract excel data to SQL Server.  the data did not import properly since the data contains french characters.

in the excle spreadsheet

LAVALLÉE-BRIEN          

in SQL Server

LAVALLÉE-BRIEN          
 
you can find the specific identifier for each encode in .net from the page below.

Code Page Identifiers


My excel is Unicode delimited format file. so i will have to use CharacterSet=65001 to represent that file format . Warmming if you use CharacterSet=Unicode, you will see the data table will scremup in the debug window.

here is the solution

  string ConnectionString = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0} ; 
Extended Properties=""Text; HDR=NO;FMT=Delimited; CharacterSet=65001;IMEX=1;"";"
Excle File with absolute path);
 
                         







Wednesday, July 17, 2013

How to fix Master Table always NULL in get_masterTableView() method in Telerik Grid

I encounter a very weird issue today when i implemented a new feature with Telerik grid in my app

since i only manipulate the telerik grid from the client side.  the following is the snippet of my javascript code.

  var gridMasterTable = $find("<%=leadGrid.ClientID%>").get_masterTableView();
            gridMasterTable.set_dataSource(new Array());
            gridMasterTable.dataBind();

I try to bind the grid with empty array to show the grid. unfortunately the application always stop and show the warming message to indicate the master table is null.. it means that the table does not exist in the grid.

after I google the web for the solution, this post really help me identify the cause of the issue

http://www.telerik.com/community/forums/aspnet-ajax/grid/find-quot-lt-gridresults-clientid-gt-quot-get-mastertableview-is-coming-back-null.aspx

the trick to solve this issue is that when you bind your grid in the client side. you must have the onCommand property set in the ClientSettings section



 <ClientSettings>
         <ClientEvents OnGridCreated="leadGrid_Created" OnCommand="Customer_Command"/>
 </ClientSettings>

 

Thursday, July 11, 2013

How to enable Web API Session feature in Windows authentication Web Application

Recently i use javascript to call Web API method to set and load the object store in the session in IIS server.

when i try to run the application, I never was able to retrieve the object from the session, when i debug the method in the web api controller, it indicated that the session was always null.


 since the Web API had disabled the session by default, we can use the following code to force the Web API to support the session.

 protected void Application_PostAuthorizeRequest()
 {
    if (IsWebApiRequest())
    {
       HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
    }
 } 
 
private static bool IsWebApiRequest()
{
   return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith("~/api");
 }

after i put the above code in the Global.asax file, the session objects are enable.

 Now i can save the object in the session and update or retrieve from the session.


 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  

Friday, May 17, 2013

How to convert only alphabet character to uppercase or lowercase in the string

Today I got a question from my teammate how can we quickly convert those alphabet characters only in a give string.

if we want to efficiently convert find those alphabet characters and  change it to Upper or Lowercase,

use the regular expression is best approach.

first we need to define the regular expression term for the match.

[a-z] reprsents that match all lower case alphabet characters

[A-Z] will be the pattern that match all upper case alphabet.

next step
we will create a delegate that will convert the alphabet to uppercase or lowercase when the match is found

delegate(Match match)
  {
       return  match.ToString().ToUpper();
  });

the following snippet of code will demo how it works

 static void Main(string[] args)
 {
   string testString="12po78er67oiiu";
  string test = System.Text.RegularExpressions.Regex.Replace(testString, @"[a-z]"delegate(Match match)
  {
       return  match.ToString().ToUpper();
  });
}

Tuesday, April 23, 2013

How to host a Nest ASP.Net applicaiton within the same source code.

I encounter an issue when i try to use the same source code to create a sub web application under

the current web application. the following picture will show the scenario that i want to acomplish






then i will receive the follow 500 Error




after i google  the web and do some research the following will solve the issue

this link will provide me great help in solving my problem

http://stackoverflow.com/questions/782252/avoid-web-config-inheritance-in-child-web-application-using-inheritinchildapplic

I must stop the nested child application inherit System.Web and System.WebServer configuration from the parent which is the source.

<location path="." inheritInChildApplications="false">
  <system.web>
   <compilation debug="true" targetFramework="4.5"/>
   <httpRuntime targetFramework="4.5"/>
   <pages controlRenderingCompatibilityVersion="4.0" clientIDMode="AutoID">
    <controls>
     <add tagPrefix="telerik" namespace="Telerik.Web.UI" assembly="Telerik.Web.UI"/>
    </controls>
   </pages>
   <httpHandlers>
    <add path="Telerik.Web.UI.WebResource.axd" verb="*" type="Telerik.Web.UI.WebResource, Telerik.Web.UI" validate="false"/>
   </httpHandlers>
   <httpModules>
    <add name="RadCompression" type="Telerik.Web.UI.RadCompression"/>
   </httpModules>
   <!--<httpRuntime maxRequestLength="92160000" executionTimeout="112"/>-->
   <identity impersonate="false"/>
  </system.web>
 
  <system.webServer>
   <validation validateIntegratedModeConfiguration="false"/>
   <modules runAllManagedModulesForAllRequests="true">
    <add name="RadCompression" type="Telerik.Web.UI.RadCompression"/>
   </modules>
   <handlers>
    <remove name="Telerik.Web.UI.WebResource.axd" />
    <add name="Telerik.Web.UI.WebResource.axd" path="Telerik.Web.UI.WebResource.axd" verb="*" type="Telerik.Web.UI.WebResource, Telerik.Web.UI" preCondition="integratedMode"/>
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit"/>
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit"/>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0"/>
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0"/>
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
   </handlers>
   <security>
    <requestFiltering>
     <requestLimits maxAllowedContentLength="943718"/>
    </requestFiltering>
   </security>
   </system.webServer>
 </location>