Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Monday, 17 April 2017

Difference between var and dynamic in C#

var
dynamic
Statically typed – This means the type of variable declared is decided by the compiler at compile time.
Dynamically typed - This means the type of variable declared is decided by the compiler at runtime time.
Need to initialize at the time of declaration.
e.g., var str=I am a string;
Looking at the value assigned to the variable str, the compiler will treat the variable str as string.

No need to initialize at the time of declaration.
e.g., dynamic str; 
str=I am a string; //Works fine and compiles
str=2; //Works fine and compiles

Errors are caught at compile time.
Since the compiler knows about the type and the methods and properties of the type at the compile time itself

Errors are caught at runtime 
Since the compiler comes to about the type and the methods and properties of the type at the run time.

Visual Studio shows intellisense since the type of variable assigned is known to compiler.
Intellisense is not available since the type and its related methods and properties can be known at run time only
e.g., var obj1;
will  throw a compile error since the variable is not initialized. The compiler needs that this variable should be initialized so that it can infer a type from the value.

e.g., dynamic obj1; 
will compile;

e.g. var obj1=1;
will compile 
var obj1=” I am a string;
will throw error since the compiler has already decided that the type of obj1 is System.Int32 when the value 1 was assigned to it. Now assigning a string value to it violates the type safety.

e.g. dynamic obj1=1;
will compile and run 
dynamic obj1=” I am a string; 
will compile and run since the compiler creates the type for obj1 as System.Int32 and then recreates the type as string when the value I am a string” was assigned to it.
This code will work fine. 

Thursday, 30 June 2016

How to Consume RESTFul Service by passing complex type Object/parameters in wcf post method in C# Asp.Net

Firstly you need create a class if you want to send a complex object in WCF REST service request .Here is sample:
  public class Artist
    {
       
        public string SearchArtist { get; set; }
        public string State { get; set; }
        public string Suburb { get; set; }
        public string Postcode { get; set; }
        public DateTime DateForm { get; set; }
        public DateTime? DateTo { get; set; }
        public int TotalEventsToReturn { get; set; }

    }

Now import the following  namespace in your project
using System.Web.Script.Serialization;
and just copy and paste below code in your project
private void getArtist()
        {
           //Create object of Artist class
            Artist artist = new Artist();
            artist.DateForm = DateTime.UtcNow;
            artist.Postcode = "2000";
            artist.SearchArtist = "artistname";
            artist.State = "NSW";
            artist.Suburb = "Sydney";
            artist.TotalEventsToReturn = 80;
          
//If you want to add root name as well in your Json request then you need to                          write below code as well otherwise you can skip this code
            dynamic collectionWrapper = new
            {
                artist = artist
            };
          //Create JavaScriptSerializer  object to serialize artist object to Json string
            JavaScriptSerializer js = new JavaScriptSerializer();
          // Json string after serialization
            string json = js.Serialize(collectionWrapper);
   // Make a http web request with URL
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://local.liveguide.com.au/LiveGuideDataAPI.svc/GetArtistEvents");
// Set content type such as Json,Xml for response
            httpWebRequest.ContentType = "application/json; charset=utf-8";
            httpWebRequest.Method = "POST";

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Flush();
            }
 //Set header such as AccessToken or API Key, these are the confidential     information so need to send in Header. If you don’t need to send any such information than simply remove this code
            httpWebRequest.Headers.Add("AccessToken", "5347-c48b-4803-9056-6869");
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
              // Result as response for WCF Service
                var result = streamReader.ReadToEnd();
            }
        }
Noteè If you are getting compile time error ‘One or more types required to compile a dynamic expression cannot be found. Are you missing a reference?’ then you just need reference of  Microsoft.CSharp from assembly


How to Pass JavaScript object from jQuery AJAX post method in WCF REST Service

  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
   <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>

Now copy and paste below code in your page. You have to change URL and Artist object according  to your need.

    <script type="text/javascript">
        $("#btnEvent").live("click", function () {
            debugger;
            var myDate = '2016.06.26' //set from date here
            var jsondate = convertToJSONDate(myDate)
            var artist = {}; // object for request
            artist.SearchArtist = "t"; //Artist to be search
            artist.State = "NSW";
            artist.Suburb = "Sydney";
            artist.Postcode = 2000;
            artist.DateForm = convertToJSONDate(myDate) // convert from date to json
            artist.TotalEventsToReturn = 80;
            var jsonstng = "{\"artist\":" + JSON.stringify(artist) + "}"; // add root name if you need
            //Post request to Live Guide Service
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: 'http://local.abc.com.au/AbcDataAPI.svc/GetArtistEvents',//you can set local host
                headers: { 'AccessToken': '5347-c48b-4803-9056-6869' },//your API key
                data: jsonstng,
                dataType: "json",
                processData: false,
                success: function(result) {
                    for (var i = 0; i < result.GetArtistEventsResult.Events.length; i++) {
                        $("#Events").append("<tr><td>" + result.GetArtistEventsResult.Events[i].Name + "</td><td>" + result.GetArtistEventsResult.Events[i].Artists + "</td>");
                    }

                },
                error: function (result) {
                    alert(result);
                }
            });     
        });

        // Function to convert javascript date to json date
        function convertToJSONDate(myDate) {
            var dt = new Date(myDate);
            var newDate = new Date(Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate(), dt.getHours(), dt.getMinutes(), dt.getSeconds(), dt.getMilliseconds()));
            return '/Date(' + newDate.getTime() + ')/';
        }
    </script>

 // Code Sample for body section
<form id="form1" runat="server">
    <div>
      <div>
        <input type="button" id = "btnEvent" value="Get Events" />
          <table id="Events" border='1'>
    <tr>
        <th>Name</th>
         <th>Artists</th>
    </tr>
</table>
    </div>
    </div>
    </form>