Literal Improvement in C# 7.0

C# 7.0 now allows using underscore _ to be used a digit separator.

This adds more readability.

Similarly, we now have Binary Literals, so instead of specifying hexadecimal pattern we can specify bit patterns.

Hope it helps..

Using Out Variables (C# 7.0) instead of Out Parameters

Out Parameters must need to declared before they are used in the method which doesn’t seem intuitive.

Now with C# 7.0 we can now make use of Out variable.

Here in our second call to the method we have used out variable named outVariableString which we didn’t have to declare like output parameter.

Hope it helps..

Tuple Types and Tuple Literals in C# 7.0

Tuple are used when we need to get more than one value returned from the method.

C# 7.0 introduces Tuple Types and Tuple Literals to Tuples

We need to add System.ValueType Nuget Package to add the required assemblies to Visual Studio.

Below sample code shows usage of Tuple type and literal. In our second method, we have named the part of the tuple i.e. name and number.

Now to access the first method we use Item1 and Item2 field, however for our second method as we have named the part we can use those names to access them i.e. name and number.

Output in both the case

Hope it helps..

New Feature – Local Functions in C# 7.0

C# 7.0 adds a new feature called local functions.

Local functions allow us to define function within a function. It can be used to write helper methods that we need to use inside that function’s scope.

Here in the below sample code we have defined one main function (MainFunction) that has one local function(MultiplyBy10LocalFunction) defined inside it. And that local function has one more local function(Add10LocalFunction) defined inside it.

Hope it helps..

Sample Code to consume UNData API using JavaScript

Sharing a sample code that can be used to consume UNData API

http://data.un.org/Host.aspx?Content=API

The below code fetches the population data for country India.

Sample Code


var xmlHttp;
// creatng the xmlHttp object
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
// Calling the web service using post and true means asynchronous call
xmlHttp.open("POST", "http://data.un.org/WS/NSIEstatV20Service.asmx", false);

// Setting the request header to let the web service find the soap request we would be sending
xmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");

xmlHttp.setRequestHeader("SOAPAction", "http://ec.europa.eu/eurostat/sri/service/2.0/extended/GetCompactData");

var soapRequest = "<!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1"-->xml version='1.0' encoding='utf-8'?>"+
"<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"+
"<soap:Body>"+
"<GetCompactData xmlns='http://ec.europa.eu/eurostat/sri/service/2.0/extended'>"+
"<Query>"+
"<message:QueryMessage xsi:schemaLocation='http://ec.europa.eu/eurostat/sri/service/2.0/SDMXMessage.xsd http://ec.europa.eu/eurostat/sri/service/2.0/%20SDMXMessage.xsd' xmlns:generic='http://www.SDMX.org/resources/SDMXML/schemas/v2_0/generic' xmlns:message='http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message' xmlns:query='http://www.SDMX.org/resources/SDMXML/schemas/v2_0/query' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>"+
"<message:Header>"+
"<message:ID>onh14833545733929527</message:ID>"+
"<message:Test>false</message:Test>"+
"<message:Prepared>2017-01-01</message:Prepared>"+
"<message:Sender id='online-help' />"+
"</message:Header>"+
"<message:Query>"+
"<query:DataWhere>"+
"<query:And>"+
"<query:Dimension id='INDICATOR'>SP_POP_TOTL</query:Dimension>"+
"<query:Dimension id='AGE'>_T</query:Dimension>"+
"<query:Dimension id='SEX'>_T</query:Dimension>"+
"<query:Dimension id='LOCATION'>_T</query:Dimension>" +
"<query:Dimension id='REF_AREA'>DEU</query:Dimension>" +
"<query:Dimension id='SCENARIO'>H</query:Dimension>"+
"<query:Time>"+
"<query:StartTime>2014-01-02</query:StartTime>"+
"<query:EndTime>2017-01-02</query:EndTime>"+
"</query:Time>"+
"<query:Dataflow>DF_UNDATA_WPP</query:Dataflow>"+
"</query:And>"+
"</query:DataWhere>"+
"</message:Query>"+
"</message:QueryMessage>"+
"</Query>"+
"</GetCompactData>"+
"</soap:Body>" +
"</soap:Envelope>";

xmlHttp.send(soapRequest);
var xmlDoc = jQuery.parseXML(xmlHttp.responseText);
var popValue = xmlDoc.getElementsByTagName('ns1:Obs')['0'].attributes['OBS_VALUE'].nodeValue;
alert("Total Population " + popValue);

Output


<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body><GetCompactDataResponse
xmlns="http://ec.europa.eu/eurostat/sri/service/2.0/extended">
<GetCompactDataResult>
<CompactData
xmlns:ns1="urn:sdmx:org.sdmx.infomodel.datastructure.DataStructure
=UNSD:DSD_WPP_UNDATA(1.0):ObsLevelDim:TIME_PERIOD"
xmlns="http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message"
xmlns:common="http://www.SDMX.org/resources/SDMXML/schemas/v2_0/common"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xml="http://www.w3.org/XML/1998/namespace"><Header>
<ID>DF_UNDATA_WPP</ID><Test>false</Test><Prepared>2017-01-06T08:25:46
</Prepared>
<Sender id="1B0">
<Name xml:lang="en">United Nations Statistics Division</Name>
<Contact><Email>statistics@un.org</Email></Contact></Sender>
<KeyFamilyRef>DSD_WPP_UNDATA</KeyFamilyRef><KeyFamilyAgency>UNSD
</KeyFamilyAgency><DataSetAgency>UNSD</DataSetAgency>
<DataSetID>DF_UNDATA_WPP_1B0_2017-01-06T082546</DataSetID>
<DataSetAction>Information</DataSetAction>
<Extracted>2017-01-06T08:25:46</Extracted>
<Source xml:lang="en">
United Nations Population Division World Population Prospects</Source>
</Header>
<ns1:DataSet DATASET_NAME="World Population Prospects"
DATASET_SOURCE="United Nations Population Division"
DATASET_DESC="The United Nations World Population Prospects contains estimates and projections for every country in the world, including estimates and projections of demographic indicators such as birth rates, deaths rates, infant mortality rates and life expectancy." UNDATA_LASTUPDATE="20 Aug 2013" UNDATA_NEXTUPDATE="2015 release" METADATA="http://esa.un.org/unpd/wpp/index.htm"><ns1:Series AGE="_T" FREQ="A" INDICATOR="SP_POP_TOTL" LOCATION="_T" SEX="_T" REF_AREA="DEU" SCENARIO="H"><ns1:Obs TIME_PERIOD="2015" OBS_VALUE="83178.615" UNIT="NUMBER" UNIT_MULT="3" TIME_SPAN="2015" /></ns1:Series></ns1:DataSet></CompactData></GetCompactDataResult></GetCompactDataResponse></soap:Body></soap:Envelope>

Hope it helps.

Sample code to consume UNData API in C#

Hi,

Recently we were working on an application that had to fetch country specific details. For this we used the UNData API.

http://data.un.org/Host.aspx?Content=API

We can make use of SDMX Browser in helping us to write a query

http://data.un.org/SdmxBrowser/start

Create a console app\windows application and add web reference to the following web service

http://data.un.org/WS/NSIEstatV20Service.asmx

Below is the sample C# Code


string queryMsg = @"<message:QueryMessage
xsi:schemaLocation='http://ec.europa.eu/eurostat/sri/service/2.0/SDMXMessage.xsd
http://ec.europa.eu/eurostat/sri/service/2.0/%20SDMXMessage.xsd'
xmlns:generic='http://www.SDMX.org/resources/SDMXML/schemas/v2_0/generic'
xmlns:message='http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message'
xmlns:query='http://www.SDMX.org/resources/SDMXML/schemas/v2_0/query'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
<message:Header>
<message:ID>onh14833545733929527</message:ID>
<message:Test>false</message:Test>
<message:Prepared>2017-01-01</message:Prepared>
<message:Sender id='online-help'/>
</message:Header>
<message:Query>
<query:DataWhere>
<query:And>
<query:Dimension id='INDICATOR'>SP_POP_TOTL</query:Dimension>
<query:Dimension id='AGE'>_T</query:Dimension>
<query:Dimension id='SEX'>_T</query:Dimension>
<query:Dimension id='LOCATION'>_T</query:Dimension>
<query:Dimension id='REF_AREA'>IND</query:Dimension>
<query:Time>
<query:StartTime>2014-01-02</query:StartTime>
<query:EndTime>2017-01-02</query:EndTime>
</query:Time>
<query:Dataflow>DF_UNDATA_WPP</query:Dataflow>
</query:And>
</query:DataWhere>
</message:Query>
</message:QueryMessage>";
NSIEstatV20Service service = new NSIEstatV20Service();
System.Xml.XmlDocument queryMessageDocument = new XmlDocument();
queryMessageDocument.LoadXml(queryMsg);
System.Xml.XmlNode queryMessage = queryMessageDocument.DocumentElement;
var result = service.GetCompactData(queryMessage);
MessageBox.Show(result.InnerXml);

The output

The query here basically returns the Total population of India

Hope it helps..

.NET Framework missing from Visual Studio 2010 new project dialog box

To resolve this issue, download and install .NET Framework 3.5 sp1.

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=ab99342f-5d1a-413d-8319-81da479ab0d7&displaylang=en

Or if it is Windows Server 2008 R2,  just enable the .NET Framework 3.5.1 Features using Server Manager or else you will get the following error

“You must use role management tool to install or configure Microsoft .NET Framework 3.5”

Bye.

Understanding Constructors (C#)

What is constructor?

Constructor is a special type of function member of a class. It is used to initialize the instance variables of the object.

Person myPerson=new Person();

Here the new operator is used to allocate the memory needed to store the data of the object.

Now suppose this is how we have defined our Person class.

  public class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }  
   

( here we have used Automatic Properties feature of C# 3.0 to declare our properties FirstName and LastName)

Here in our class we haven’t defined a constructor but we are still able to create instance variables of the Person Object using following line of code

Person p = new Person();
 

The reason it is possible is because we don’t have to explicitly declare constructor for a class, C# automatically provides a default parameterless constructor for that class. The default constructor will initialize any fields of the class to their zero-equivalent values.

We can also write our own constructors, the things to remember are

  • They don’t have a return type.
  • Their name should be same as the name of the class.
  • Should contain a parameter list, which could be left empty.

Now the question is why would we be writing our own constructors?

Well the reason is because constructors can be used to pass initial values for an object’s fields at the time when an object is being instantiated.

For our above Person class

instead of the following code 

    Person p = new Person();
    p.FirstName = "Nishant";
    p.LastName = "Rana";

 

we can do the same in single line of code

Person p = new Person("Nishant", "Rana");
 

The constructor would be defined in the following manner

 public Person(string fname, string lname)
          {
              FirstName = fname;
              LastName = lname;
          }

One thing we have to remember is that if we are defining our own Parameterized constructor the default constructor would be eliminated.

We won’t be able to create person class object using default constructor.

i.e. Person p=new Person(); // it won’t compile.

In this case then we need to explicitly write a default constructor.

public Person()
        { 

        }

bye..

Events in C#

We’ll take a simple and useful scenario to make our understanding of Events as clear as possible.
First of all copy and paste the code below. We’ll try understanding the code than.

using System;
public class ResultDeclarationEventArgs : EventArgs
{
private string message;
public ResultDeclarationEventArgs(string message)
{
this.message = message;
}
public string Messsage
{
get
{
return message;
}
}
}
public delegate void ResultHandler(object sender, ResultDeclarationEventArgs e);
public class Kid
{
private int percentage;
public event ResultHandler onResultDeclaration;
public int Percentage
{
set
{
percentage = value;
if(percentage > 80)
{
ResultDeclarationEventArgs myREA = new ResultDeclarationEventArgs( ” I got Distinction”);
onResultDeclaration(this, myREA);
}
if(percentage > 60 && percentage < 80)
{
ResultDeclarationEventArgs myREA = new ResultDeclarationEventArgs(” I got FirstClass”);
onResultDeclaration(this, myREA);
}
if(percentage > 40 && percentage < 60)
{
ResultDeclarationEventArgs myREA = new ResultDeclarationEventArgs(” I got SecondClass”);
onResultDeclaration(this, myREA);
}
if(percentage < 40)
{
ResultDeclarationEventArgs myREA = new ResultDeclarationEventArgs(” Sorry I failed “);
onResultDeclaration(this, myREA);
}
}
}
}
public class Mom
{
public Mom(Kid myKid)
{
myKid.onResultDeclaration += new ResultHandler(GiveMsgToMom);
}
void GiveMsgToMom(object sender, ResultDeclarationEventArgs e)
{
Console.WriteLine(e.Messsage);
}
}

public class Dad
{
public Dad(Kid myKid)
{
myKid.onResultDeclaration += new ResultHandler(GiveMsgToDad);
}
void GiveMsgToDad(object sender, ResultDeclarationEventArgs e)
{
Console.WriteLine(e.Messsage);
}
}

class myDemo
{
public static void Main()
{
Kid kid = new Kid();
Mom mom = new Mom(kid);
Dad dad = new Dad(kid);
Console.WriteLine(“Please enter the percentage of the Kid”);
string percentage = Console.ReadLine();
kid.Percentage = Convert.ToInt32(percentage);
}
}

The scenario is something like this First there is a class named Kid. It has a field called Percentage and declares an event OnResultDeclaration. It is of type ResultHandler. ResultHandler is a delegate. public delegate void ResultHandler(object sender, ResultDeclarationEventArgs e);
It can point or refer to any method which has return type void and takes as parameter an object and ResultDeclarationEventArgs.
Object will give the name of the sender who has called this eventhandler and ResultDeclarationEventArgs is to pass any information regarding the event.

ResultDeclarationEventArgs is a class that derives from EventArgs class. It has a message field which will contain the message the Kid class, which has the event OnResultDeclaration, would like to convey to the class (e.g. Mom, Dad) which are interested in that event.
For this reason, we have our event handlers(method) inside Mom and Dad class which have the same signature as defined by the event.
void GiveMsgToMom(object sender, ResultDeclarationEventArgs e)
void GiveMsgToDad(object sender, ResultDeclarationEventArgs e)
Than we register these eventHandler to the events.
myKid.onResultDeclaration += new ResultHandler(GiveMsgToDad);
myKid.onResultDeclaration += new ResultHandler(GiveMsgToDad);

Kid class will check for the percentage passed in and accordingly set’s the message.
Whatever message is set is than displayed in the Event handler inside Mom and Dad class using e.Message

Understading Delegates

What are delegates?
Delegates are object that refer to an method. Normally we refer to objects, however referring to an object isn’t any different from referring a method they too have physical location in memory.

Why use delegate?
One delegate can be used to call different methods during runtime of a program by simply changing the method to which the delegate refers.
and Delegates Support Events.

delegate ret-type name(paramerter-list);
e.g. delegate string MyDelegate();

The MyDelegate can call any method whose return type is string and accepts no parameter. It can be instance method or a static method.

delegate string MyDelegate(String s);
class Program
{
static string GetNameLower(String s)
{
return s.ToLower() ;
}
static string GetNameUpper(string s)
{
return s.ToUpper();
}
static void Main(string[] args)
{
MyDelegate myD = new MyDelegate(GetNameLower); //or myD=GetNameLower
string s1 = myD(“Hi Nishant”);
Console.WriteLine(s1);
myD = new MyDelegate(GetNameUpper); //or myD=GetNameUpper
string s2 = myD(“Hi Nishant”);
Console.WriteLine(s2);
}
}

Understanding Multicasting

We can have chain of methods that will be called automatically when a delegate is invoked.
For this we will use += operator to add methods to chain and -= to remvove a method.
If delegate returns value than value returned by the last method becomes the return value of entire deleagation invocation. Thus a delegate making use of multicasting will have void as return type.

delegate void MyDelegate();
class Program
{
static void GetNameLower()
{
Console.WriteLine(“GetNameLower Called”);
}
static void GetNameUpper()
{
Console.WriteLine(“GetNameUpper Called”);
}
static void Main(string[] args)
{
MyDelegate myD = GetNameLower;
myD +=GetNameUpper;
myD(); //invoking the delegate
}