Various Build Actions in Visual Studio

Hello everyone, In this post we are going to learn about various Build Actions of Visual Studio. The Build Action property indicates what Visual Studio does with a file when a build is executed. 

Actually you can change build action of each and every file in any visual studio project. Each build action has its own functionality as described below:

  • None: The file is not included in the project output group and is not compiled in the build process. An example is a text file that contains documentation, such as a Readme file.
  • Compile: The file is compiled into the build output. This setting is used for code files.
  • Content: Allows you to retrieve a file (in same dir as assembly) as a stream via Application.GetContentStream( uri ). For this method to work, it needs a AssemblyAssociatedContentFile custom attribute which VS graciously adds when you mark a file as “Content”
  • Embedded resource: embeds the file in an exclusive assembly manifest resource.
  • Resource (wpf only): embeds the file in a shared (by all files in the assembly with similar setting) assembly manifest resource named AppName.g.resources.
  • Page (wpf only): Used to compile a xaml file into baml. The baml is then embedded with the same technique as Resource (i.e. available as `AppName.g.resources)
  • ApplicationDefinition (wpf only): Mark the XAML/class file that defines your application. You specify the code-behind with the x:Class=”Namespace.ClassName” and set the startup form/page with StartupUri=”Window1.xaml”
  • SplashScreen (wpf only): An image that is marked as SplashScreen is shown automatically when an WPF application loads, and then fades
  • DesignData: Compiles xaml viewmodels so that usercontrols can be previewed with sample data in visual studio (uses mock types)
  • DesignDataWithDesignTimeCreatableTypes: Compiles xaml viewmodels so that usercontrols can be previewed with sample data in visual studio (uses actual types)
  • EntityDeploy: (Entity Framework): used to deploy the Entity Framework artifacts
  • CodeAnalysisDictionary: A xml file containing custom word dictionary for spelling rules

 

Common Questions / Issues associated with understanding Build Action:

  1. My class under App_Code / App_Data is not accessible in Visual Studio .NET
  2. Cannot reference App_Code in .NET

Resolution:

The above questions mostly asked with the ASP.NET development, The answer is simple change the Build Action of the files under App_Data from Content to Compile.

If you have trouble to find build action, kindly follow the steps below.
  1. Select the file under App_Code / App_Data
  2. Go to Properties window
  3. Change Build Action to Compile

Consuming a WebService using LINQ

[dropcap]T[/dropcap]his article demonstrates how to query a Web Service’s public API using LINQ. For this article, I am using the Web Service located at GeoNames. Our code will query the CountryInfo webservice which accepts a Country Code and returns information like the country’s capital, population, currency and so on.
Check out the XML document returned from this service over here http://ws.geonames.org/countryInfo?
Let us get started:

 

Step 1: Create a Console Application. To this application, add a class named ‘Country’ and ‘CountryInfo’. The CountryInfo class has the following definition:
class CountryInfo
{
    public string CountryName { get; set; }
    public long Population { get; set; }
    public string Capital { get; set; }
    public string CurrencyCode { get; set; }
    public float AreaSqKm { get; set; }
}
Step 2: The Country class contains a SearchCountry method that returns an IEnumerable<CountryInfo> as shown below:

 

class Country
{
    public IEnumerable<CountryInfo> SearchCountry(string countryCode)
    {
        string uri = Uri.EscapeUriString(countryCode);
        string url = FormatUrl(uri);
        XDocument xdoc = XDocument.Load(url);
        IEnumerable<CountryInfo> results =
        from cntry in xdoc.Descendants(“country”)
        select new CountryInfo
        {
            CountryName = cntry.Element(“countryName”).Value,
            Capital = cntry.Element(“capital”).Value,
            AreaSqKm = Convert.ToSingle(cntry.Element(“areaInSqKm”).Value),
            Population = Convert.ToInt64(cntry.Element(“population”).Value),
            CurrencyCode = cntry.Element(“currencyCode”).Value
        };
        return results;
    }
    string FormatUrl(string cCode)
    {
        return “http://ws.geonames.org/countryInfo?” +
            “country=” + cCode +
            “&username=christlin”;
    }
}
The code is pretty straightforward. We first create the url with the search string using our FormatUrlmethod. We then use the XDocument.Load to create an XML document from the url. The last step is to loop through the XML document, populate the CountryInfo object and return the results.

 

Step 3: The final step is to code the Main() method to retrieve and display the results from the WebService. Here’s how the Main() method looks
static void Main(string[] args)
{
    Country country = new Country();
    string cntryCode = “IN”;
    IEnumerable<CountryInfo> cntryInfo = country.SearchCountry(cntryCode);
    foreach (var c in cntryInfo)
    {
        Console.WriteLine(“You searched for {0}. “ +
                        “The population of {0} is {1} and its capital is {2}. “ +
                        “The CurrencyCode for {0} is {3} and it’s area in Sq. Km is {4}”,
            c.CountryName, c.Population, c.Capital,
            c.CurrencyCode, c.AreaSqKm);
    }
    Console.ReadLine();
}

 

In the example above, we are passing in the country code ‘IN’ for India. We then loop through an object of IEnumberable<CountryInfo> and print the result on the console. The output looks similar to the following:

 

00130032015 Console Output

 

Well that was a simple example of how to query a webservice using LINQ. I hope you liked this article and I thank you for viewing it. The entire source code of this article can be downloaded here

[wpfilebase tag=file id=1 tpl=download-button /]

Local Variable Type Inference

Local Variable Type Inference

Local variables can be given an inferred “type” of var instead of an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. The inferred type may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET Framework class library

With this feature, the type of the local variable being declared is inferred from the expression used to initialize the variable. This is achieved using the var keyword (familiar to those who work with scripting languages, but actually it is quite different). It allows us to write the following code:

 

var num = 50; 
var str = "simple string";
var obj = new myType();
var numbers = new int[] {1,2,3};
var dic = new Dictionary<int,myType>();

The compiler would generate the same IL as if we compiled:

int num = 50; 
string str = "simple string";
myType obj = new myType();
int[] numbers = new int[] {1,2,3};
Dictionary<int,myType> dic = new Dictionary<int,myType>();

Note that there is no un-typed variable reference nor late-binding happening, instead the compiler is inferring and declaring the type of the variable from the right-hand side of the assignment. As a result, the var keyword is generating a strongly typed variable reference.

Automatic Properties C#

[dropcap]A[/dropcap]utomatic properties used as a shorter way of defining a simple property which just sets and gets the value of a private member variable. Consider the following Code;

public class Point
 {
    private int _x, _y;
    public int X
    {
        get
        {
          return _x;
        }
        set
        {
          _x = value;
        }
    }
    public int Y
    {
        get
        {
          return _y;
        }
        set
        {
          _y = value;
        }
    }
}

The above code simply defining a class with basic properties. Now with the new C# compiler in Visual Studio .NET, we can write a shorter cleaner version using Automatic Properties which automatically generates the private fields with get/set operations :

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }
}

The code above is even more readable and less verbose.
Note that this feature has nothing to do with LINQ. I just thought it would be appropriate to list it with the other new language features.

 

For more information see MSDN C# Programming Guide

Delegates C Sharp – The Complete Tutorial

Introduction

        Delegate is like a buzz word in C#.NET programming. In this article, I explain delegates, multicast delegates and their usage with the help of simple C# programs.

What is a Delegate?

        Delegate is a type which holds the method(s) reference in an object. It is also referred to as a type safe function pointer. The below figure illustrates the overview of Delegate.

Delegate is a type which holds the method(s) reference in an object. It is also referred to as a type safe function pointer.

Advantages

  • Encapsulating the method’s call from caller
  • Effective use of delegate improves the performance of application
  • Used to call a method asynchronously

Declaration

public delegate type_of_delegatedelegate_name()

Example:

publicdelegate int mydelegate(int delvar1,int delvar2)

Note

  • You can use delegates without parameters or with parameter list
  • You should follow the same syntax as in the method
    (If you are referring to the method with two int parameters and int return type, the delegate which you are declaring should be in the same format. This is why it is referred to as type safe function pointer.)

Sample Program using Delegate

public delegate double Delegate_Prod(int a,int b);
class Class1
{    
  static double fn_Prodvalues(int val1,int val2)    
  {        
    return val1*val2;    
  }    
  static void Main(string[] args)    
  {        //Creating the Delegate Instance        
    Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);        
    Console.Write("Please Enter Values");        
    int v1 = Int32.Parse(Console.ReadLine());        
    int v2 = Int32.Parse(Console.ReadLine());        //use a delegate for processing        
    double res = delObj(v1,v2);        
    Console.WriteLine ("Result :"+res);        
    Console.ReadLine();    
  }
}

Explanation

Here I have used a small program which demonstrates the use of delegate.

The delegate “Delegate_Prod” is declared with double return type and accepts only two integer parameters.

Inside the class, the method named fn_Prodvalues is defined with double return type and two integer parameters. (The delegate and method have the same signature and parameter type.)

Inside the Main method, the delegate instance is created and the function name is passed to the delegate instance as follows:

Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);

After this, we are accepting the two values from the user and passing those values to the delegate as we do using method:

delObj(v1,v2);

Here delegate object encapsulates the method functionalities and returns the result as we specified in the method.

Multicast Delegate

What is Multicast Delegate?

 

It is a delegate which holds the reference of more than one method.

Multicast delegates must contain only methods that return void, else there is a run-time exception.

Simple Program using Multicast Delegate

delegate void Delegate_Multicast(int x, int y);
Class Class2
{    
 static void Method1(int x, int y)    
 {        
   Console.WriteLine("You r in Method 1");    
 }     
 static void Method2(int x, int y)    
 {        
   Console.WriteLine("You r in Method 2");    
 }    
 public static void Main()  
 {      
   Delegate_Multicast func = new Delegate_Multicast(Method1);     
   func += new Delegate_Multicast(Method2);   
   func(1,2);             // Method1 and Method2 are called     
   func -= new Delegate_Multicast(Method1);     
   func(2,3);             // Only Method2 is called    
 }
}

Explanation

In the above example, you can see that two methods are defined named method1 and method2 which take two integer parameters and return type as void.

In the main method, the Delegate object is created using the following statement:

Delegate_Multicast func = new Delegate_Multicast(Method1);

Then the Delegate is added using the += operator and removed using the -= operator.

For more information see this MSDN C# Programming Guide.

Method Overriding in C#

Method overriding in C# is a feature like the virtual function in C++. Method overriding is a feature that allows you to invoke functions (that have the same signatures) that belong to different classes in the same hierarchy of inheritance using the base class reference. C# makes use of two keywords: virtual and overrides to accomplish Method overriding.

The figure below illustrates the overview of method overriding

 

Method Overriding of Shape ( Circle, Square and Triangle are basically Shapes but having different method to draw each shape)

The concept of method overriding is simple; Circle, Square and Triangle are basic shapes, But the method to draw each of them is different. So circle is a shape but we have set of rules to draw a circle, so we are creating unique method for drawing circle.

Method Overriding in C# – Examples

Let’s understand this through small examples.

P1.cs
class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new BC();
     b.Display();
   }
}
Output
BC::Display

The above program compiles and runs successfully to give the desired output. It consists of a base class BC and a derived class DC. Class BC consists of function Display(). Class DC hides the function Display() it inherited from the base class BC by providing its on implementation of Display(). Class Demo consists of entry-point function Main(). Inside Main() we first create a reference b of type BC. Then we create an object of type BC and assign its reference to reference variable b. Using the reference variable b we invoke the function Display(). As expected, Display() of class BC is executed because the reference variable b refers to the object of class BC.

Now we add a twist of lime to the above program.

P2.cs
class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new BC();
     b.Display();
     b = new DC();
     b.Display();   
   }
}
Output
BC::DisplayBC::Display

Here we are creating an object of Derived class DC and storing its reference in the reference variable b of type BC. This is valid in C#. Next, using the reference variable b we invoke the function Display(). Since b contains a reference to object of type DC one would expect the function Display() of class DC to get executed. But that does not happen. Instead what is executed is the Display() of BC class. That’s because the function is invoked based on type of the reference and not to what the reference variable b refers to. Since b is a reference of type BC, the function Display()of class BC will be invoked, no matter whom b refers to. Take one more example.

P3.cs
class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class TC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new BC();
     b.Display();
     b = new DC();
     b.Display();    
     b = new TC();
     b.Display();
   }
}
Output
BC::DisplayBC::DisplayBC::Display

The output of the above program is a receipt of the fact that no matter to whom base class reference b refers, it invokes the functions of the class that matches its type. But doesn’t this sound absurd? If b contains the reference to a particular derived class object, then its supposed to invoke the function of that class. Well, C# helps us do this by the usage of keywords virtual and override as shown in the following program.

P4.cs
class BC
{
  public virtual void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  public override void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new BC();
     b.Display();     
     b = new DC();
     b.Display();    
  }
}
Output
BC::DisplayDC::Display

The above program compiles and runs successfully to give the expected desired output. The function Display() of Base class BC is declared as virtual, while the Derived class’s implementation of Display() is decorated with the modifier override. Doing so enables C# to invoke functions like Display() based on objects the reference variable refers to and not the type of reference that is invoking the function. Hence in the above program when b refers to the object of class BC it invokes Display() of BC and then when b refers to the object of class DC it invokes Display() of class DC. Let’s see if this holds true for the third generation of derived classes. Take the following program.

P4.cs
class BC
{
  public virtual void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  public override void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class TC : DC
{
  public override void Display()
  {
     System.Console.WriteLine("TC::Display");
  }
} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new BC();
     b.Display();     
     b = new DC();
     b.Display();     
     b = new TC();
     b.Display();   
  }
}
Output
BC::DisplayDC::DisplayTC::Display

The above program compiles and runs successfully to give the expected desired output. The function Display() of Base class BC is declared as virtual, while the implementation of Display() in successive Derived classes is decorated with the modifier override. Next, we successively create objects of each class and store their reference in base class reference variable b and invoke Display(). The rite versions of Display get invoked based on the object the reference variable refers to. Time for a tiny teaser! Guess what the output would be in the following program?

P5.cs
class BC
{
  public virtual void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  public override void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class TC : DC
{ 

} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new TC();
     b.Display();   
  }
}
Output
DC::Display

Since TC has no implementation of Display(), it inherits Display() from DC as TC is derived from DC. Hence Display() from Derived class DC gets executed. It’s as if the derived class TC looked like this:

class TC 
{
  public override void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

to the compiler. Take one more example. Guess what its output will be.

P6.cs
class BC
{
  public virtual void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
} 
class DC : BC
{
  public override void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
} 
class TC : DC
{
  public new void Display()
  {
     System.Console.WriteLine("TC::Display");
  }
} 
class Demo
{
  public static void Main()
  {
     BC b;
     b = new TC();
     b.Display();
  }
}
Output
DC::Display

Agreed that TC defines its own new version of Display(). But its version of display is not invoked as Display() of TC does not override the Display() of the base class. With this understood we are done with Method overriding in C#.

For more information see MSDN Reference Document Method Overriding in C#