Archive for the ‘Uncategorized’ Category

Getting started with C# 6.0

Posted: November 17, 2014 in Uncategorized

Getting started with C# 6.0 :

I have just installed Visual Studio 2015 and was playing with C# 6.0. Has loads of new features supported out of the box which are mainly for making the code clean and lean.

Some of the features supported by C# 6.0 are already listed in the below link :

http://www.c-sharpcorner.com/UploadFile/mahesh/what-is-new-in-C-Sharp-6-0384/

I tried to run a sample application which uses some of the new features and found it very interesting.

Null checks using ?. operator (also called as Elvis operator) and String.Format using \{} (also called as String interpolation) and loads of such things are supported by the Framework out of the box.

Here is a sample code which can get you started :

using System.Console;

namespace VS2015Sample

{

class Program

{

   static void Main(string[] args)

  {

      string version = “Dotnet 4.6”;

      object vsEditor = null;

      WriteLine(“Sample executing with VS 2015 on \{version} \{vsEditor?.ToString()}”);

      vsEditor = “VS 2015”;

      WriteLine(“Sample executing with VS 2015 on \{version} \{vsEditor?.ToString()}”);

      ReadLine();

    }

  }

}

If you see the above code, I am not using Console.WriteLine or Console.ReadLine anywhere. I am also not having null checks for displaying the vsEditor details. Also, String.Format is not used anywhere for formatting display strings.

Output of the above code will be as depicted below:

Output

C# 6.0 looks promising and will help developer fraternity with a lot of simple tricks.

Happy coding!

Advertisements

ASP.Net Web API

Posted: October 14, 2013 in Uncategorized

What is ASP.Net WebAPI

In this article, I will take you through the basics of ASP.Net Web API. Restful Service is a buzz word now a days. Since, we want Services to be platform agnostic and support all types of devices , Http based services were introduced. WebAPI is just a step forward in this direction. WebAPI is a framework for building Http based services and clients built on top of ASP.Net. REST based services can easily be built on top of WebAPI.

Some of the salient features of WebAPI are :

  • Modern HTTP programming model: It uses the power of Http as Http is simple, ubiquitous and flexible.
  • Routing support : Supports routing capabilities similar to MVC framework.
  • Content negotiation : This is one of the major features. The client and server can work together to determine the right format for data being returned from an API. The support is mainly extended in the form of Media formatters which typically support JSON, XML , Url Encoded formats.
  • Model binding and validation: Model binders provide an easy way to extract data from various parts of an HTTP request (header, querystring and body) and convert those message parts into .NET objects.
  • Support for filters and OData using IQueryable<T>
  • Support for Self Hosting – Can be hosted using IIS, Exe (Console Application) or as a Windows Service.

Lets get started with a sample for creating a WebAPI Service.

 1. Create a new MVC4 Application as seen below :

Image

 2. Select the Project Type as WebAPI.

 

Image

 

  3. This will create a MCV4 Application with WebAPI infrastructure and a sample Service already available.

  4. Open Global.asax.cs

 

  protected void Application_Start()

        {

            AreaRegistration.RegisterAllAreas();

             WebApiConfig.Register(GlobalConfiguration.Configuration);

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            RouteConfig.RegisterRoutes(RouteTable.Routes);

            BundleConfig.RegisterBundles(BundleTable.Bundles);

        }

 

The highlighted line shows the routing configuration for WebAPI

If you go to WebAPIConfig class, you will find

 

 

public static class WebApiConfig

    {

        public static void Register(HttpConfiguration config)

        {

            config.Routes.MapHttpRoute(

                name: “DefaultApi”,

                routeTemplate: “api/{controller}/{id}”,

                defaults: new { id = RouteParameter.Optional }

            );

        }

    }

MVC urls are generally “controller/action/parameters” format where WebAPI Urls are “api/controller/parameters”.

5. WebAPI supports all 4 Http Verbs namely Get, Post, Put and Delete. As per WebAPI convention, the method names will be mapped to Http verbs if the method name starts with Verb. If method is different, we can also use Attributes to indicate Verbs. Copy and paste below StudentController class. Please note that the class  should be placed under Controller folder as seen below:

 Image

 

  using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Web.Http;

 

namespace SampleWebAPI.Controllers

{

    public class StudentController : ApiController

    {

        static List<Student> StudentList = InitStudents();

         private static List<Student> InitStudents()

        {

            List<Student> tempList = new List<Student>();

            tempList.Add(new Student() { ID = 1, Name = “A” });

            tempList.Add(new Student() { ID = 2, Name = “B” });

            return tempList;

      

        }

 

        // GET api/student

        [HttpGet]

        public IEnumerable<Student> FetchStudents()

        {

            return StudentList;

        }

 

 

        // POST api/student

        public Student Post(Student student)

        {

            StudentList.Add(student);

            return student;

        }

 

        // PUT api/student/5

        public Student Put(int id, string name)

        {

            var tempstudent = StudentList.Where(p => p.ID == id).SingleOrDefault();

             if (tempstudent != null)

            {

                tempstudent.Name = name;

            }

             return tempstudent;

        }

         // DELETE api/values/5

        public void Delete(int id)

        {

            var student = StudentList.Where(p => p.ID == id).SingleOrDefault();

             if (student != null)

            {

                StudentList.Remove(student);

           }

     

        }

    }

 

    public class Student

    {

        public int ID { get; set; }

        public string Name { get; set; }

    } 

}

 6. Build the solution. I have used VS.Net 2012 environment.

 7. Just run the application, you should see the ASP.NET Web API help page.

 Image

 

 8. To Test the WebAPI we will use Fiddler as our client tool. Just open the Fiddler tool (a web debugging tool).

 9. Grab the url from the help page and paste it on the Composer tab of Fiddler. Lets us test all the Http Verbs one by one.

 10. On the fiddler , paste url as  <help-page url>/api/Student/Get

 Image

 

Select Verb as Get(in the first dropdown) and click on Execute button.

 

 

 

You can as well break at any point inside the code by using breakpoints.

 Image

On the fiddler, output will be as seen below :

 Image

 

You can see the list of students displayed in JSON format.

11. Screens for Post operation. Notice the use of Content-Type header and also we are passing values through the Request body. This will insert a new student.

 Image

 12. Follow this up, with another Get operation and you will see the new record added.

 

 Image

 In the similar fashion, you can update existing Students using Put operation and remove existing Student using Delete operation.

 

 

You can run through the sample and test all operations.

 

WebAPI is currently embraced as it is more lightweight and suited for all devices and it also relies purely on Http programming model. Content negotiation, Rest support and routing are also important features for WebAPI. I will try to come up with series of articles and take this discussion forward.

 

Feel free to leave your comments. Till we meet again, happy coding!

 

 

Windows Azure Tutorial For Beginners

Windows Azure is one of the most widely used Cloud operation platforms. Its more of Platform As A Service (PAAS). I found one interesting link which contains tutorial for Windows Azure. Please visit the link windowsazure4beginner.com .

Rank of Databases

Posted: April 15, 2013 in Uncategorized

Rank of Databases

The below link shows ranking of all SQL / NO SQL Databases. This will help us to know which one of the databases is widely used in market.

Command Design Pattern

Posted: April 14, 2013 in Uncategorized

Command Pattern falls under the category of Behavioural Design Patterns. If you have quite amount of experience in C# particularly WPF, you must have used DelegateCommand or Routed Command or RelayCommands. This internally uses Command Pattern only. Command pattern can be used in any of the projects and we will quicky understand what is it and how to use it in our project.

The command pattern encapsulates a request as an object and gives it a known public interface. Request or action is mapped and stored as an object. Invoker will be ultimately responsible for processing the request. This clearly decouples request from the invoker. This is more suited for scenarios where we implement Redo, Copy, Paste and Undo operations where action is stored as an object. We generally use Menu or Shortcut key gestures for any of the above actions to be executed.

Let us run through sample code for the Command Pattern.

  1. Define a Command for processing action or request. For demo purpose, I am defining two Commands StartCommand and StopCommand.

 

   public interface ICommand

    {

        string Name { get; }

        void Execute();

    }

 

public  class StartCommand : ICommand

{

public void Execute()

{

Console.WriteLine(“I am executing StartCommand”);

}

 

public string Name

{

get { return “Start”; }

}

}

 

public class StopCommand : ICommand

{

public void Execute()

{

Console.WriteLine(“I am executing StopCommand”);

}

 

public string Name

{

get { return “Stop”; }

}

}

2. Now that we have defined Commands, we need to define Invoker which will be responsible for executing the Commands. This is more of a Factory pattern which will execute requested Command.

public  class Invoker

{

ICommand cmd = null;

public ICommand GetCommand(string action)

{

switch(action)

{

case “Start” :

cmd = new StartCommand();

break;

case “Stop”:

cmd = new StopCommand();

break;

default :

break;

}

return cmd;

}

3. Then from my application, I will just add logic to just invoke specific commands.

 

class Program

{

static void Main(string[] args)

{

Invoker invoker = new Invoker();

// Execute Start Command

            ICommand command = invoker.GetCommand(“Start”);

            command.Execute();

// Execute Stop Commad

command = invoker.GetCommand(“Stop”);

command.Execute();

Console.WriteLine(“Command Pattern demo”);

Console.Read();

}

}

 

Command Pattern is one of useful and most widely used patterns. This is just one of the approaches for demonstrating usage of Command Pattern. Again, we can customize code as per our needs.

 

I am also attaching sample of this  Code which is used for demo. Please feel free to comment feedback / clarifications if you have any.

 

Happy Coding!

 

DevCon 2012 Experience

Posted: August 7, 2012 in Uncategorized

According to Benjamin Franklin ,“An investment in knowledge pays the best interest.” That is why I always try to learn new things and of course participate in some technical forums and events. BDotnet is one community which is helping me a lot to enhance my learning. BDotnet is Bangalore Dotnet community and the group is well known among Microsoft developers. The group is actively involved in conducting  regular Dotnet events like the UG meet (every alternate weeks) and Tech events. The group’s mantra is “Learn And Share”.  Being a member of this group has helped me to keep up to date with the current happenings in Microsoft Space. For more details, browse bdotnet.in. Recently it conducted a conference and I am writing this blog to share my experiences about the eventful day.

 

 

 

 

 

 

 

DevCon 2012 :

Announcement of DevCon 2012 content immediately forced my mind to blindly register for it. I was just waiting for the Saturday (4th August). Entire day of sessions on various new topics always keeps me updated about the latest happening and of course clear some of the misconceptions too besides getting to meet and interact with lot of known and unknown faces.

Saturday morning, EGL campus, lot of crowds..believe it or not, it had happened. I was keenly waiting for the commencement of the sessions. I prepared mentally to attend some of the sessions with some confusions though whether to attend session of Lohith (my good friend) or Pinal.

The content for the DevCon 2012 as seen below were divided into 2 tracks.

Keynote by Ranjan Bhattacharjee

Windows 8 – A peek insideSpeaker: Vic Parmar ASP.NET MVC4 + Web APISpeaker: Chaitra Nagaraj
Windows 8 for DevelopersSpeaker: Rajashekaran Vengalil Battle of Cloud ServicesSpeaker: Niraj Bhatt
Walkthrough of a Metro ApplicationSpeaker: Praveen Srivatsa Bulding Apps for Intel Ultrabook and Windows 8Speaker: Rajagopal A
Kendo UI community launchSpeaker: Abhishek Kant Ignite the leader within youSpeaker: Vinod Kumar
SQL Server Tips and Tricks for Web DevelopersSpeaker: Pinal Dave Visual Studio 2012 – Tips & TricksSpeaker: Lohith G N
Introduction to No-SQL & Mongo DBSpeaker: Manoj G HTML5 – what you NEED to knowSpeaker: Amar Nithyananda

The sessions which I attended and my observations are detailed out below :

  1. Key Note : Perfect kickstart to the session  by Ranjan. Message was clear, MS is shifting all its focus on Windows 8 and Metro UI .  Just after the DevCon 2012, there was news that MS won’t use the term ‘Metro’ in Windows 8 (http://www.ibtimes.com/articles/370214/20120803/windows-8-release-rtm-leak-metro-ui.htm). I am waiting for the new name for Metro.
  2. ASP.Net MVC 4 + WebAPI : This session provided a nice overview on WebAPI. Chaitra delved into how to use WebAPI plus provided details about new features of MVC4. This session was well organized and content was presented well.  NuGet, bundling and minification and Package manager will surely remain in my mind, thanks to Chaitra! WebAPI has been running in my mind for sometime and this session has ignited a fire in my mind to try it out.
  3. Windows 8 for Developers : Though, I am using Windows 8 OS, I still don’t know many things in Win 8. This session exactly showed me this!  This session started with what is Windows 8, its architecture and capabilities. Creating a Metro App and demonstration of Win RT APIs and Win 8 capabilities were definitely a take away from this good session. Capturing a live photo in C#, C++ and JS was neatly demoed by Rajshekharan. Application life cycle  was also covered well here.
  4. WalkThrough of a Metro Application : Praveen started from where Rajshekharan had left and was able to instill real good concepts in all of us. Lot of confusions which people had were beautifully explained. Async behavior, Application Model , Metro App modes and even Microsoft App Store concepts were explained well. I was deeply impressed with this session.  I was able to understand why  javascript alert fails in Metro UI!  Details about older dotnet applications support on Win 8. Apart from this concepts, Live Tiles details and Language projections was also neatly covered.
  5. Kendo UI community launch (New Age HTML5 Apps with Kendo UI) : Abhishek Kant started this session after lunch break and was aware that people will definitely sleep! The session started discussing why Kendo UI is needed for Web and Mobile App developers. Kendo UI is a neat framework and every HTML5 developer recognizes that fact. This session also covered some rendering samples for Grid and Contact List samples and the same example was demoed on different devices.
  6. SQL Server Tips and Tricks for Web Developers : Finally Lohith’s session was not clashing with Pinal! Pinal’s appealing voice and his standout style of delivering content will surely make up a sleeping person awake, no doubt about it. This session started with a lot of humour and the humour lasted till the end!

Stand Out Comedy points :

  1. WebDevelopers are SpiderMan.
  2. With Great Power comes Great responsibility. North Indians do not have power and so no responsibility.

As always, Pinal cleared some basic SQL fundas. Started with performance comparison for a scenario using different keywords EXISTS, IN and JOIN. He clearly demonstrated and explained how to judge the query performance using execution plan. NULL does not participated in JOINs and Scalar functions are not caught by execution plan were the SQL tips for the day.

  1. 7.     Visual Studio 2012 – tips and tracks : Finally, last session and take too from Lohith! Lohith had already released some teasers in FB about his session . I was waiting to find answers. He showed a lot of tips and shortcuts on Visual Studio 2012. Some really good features like usage of Windows tab in VS.Net was presented well. Also, lot of tips was given on how to save time by using the newly available shortcuts. Now, I can have two solution explorers! Tips and tricks were too much to remember but definitely will help a lot if we know them.

After all gyaan, came the goodies! I was able to get key chains and PluralSight free one month subscription. PluralSight subscriptions are handy and always contribute to my learning. Also, some announcements came about blog contest and I was instantly thinking whether I should try to write one.Though, I missed a few important sessions like Cloud and HTML5, the learning provided in other sessions were good enough and I was pretty satisfied . It was quite a lively Saturday with a lot of learning.

The knowledge of useful things is a purse seldom lost. So, if you are not a member of BDotnet or if you are inactive member, then definitely you are losing something.

 

Assembly in Dotnet – Part1

Posted: February 3, 2011 in Uncategorized

Assembly in Dotnet – Part1

An assembly in dotnet world is nothing but a DLL or an exe. It is basic building block of any Dotnet application. Assembly contains
metadata and manifest information. The reason for the emergence of assembly concept was to overcome the common “DLL Hell” problem in COM. The assembly contains all the code, resources, metadata and even version information
. Metadata contains the details of every “type” inside the assembly. In addition to metadata,assemblies also have a special file called Manifest. It contains information about the current version of the assembly, culture information, public key token if available and other related information.

There is tool called ildasm which can used to view  the assembly information. There is also a Dotnet reflector which can be used to dig into assembly details.

Functions of a assembly :

  1. It contains code that the common language runtime executes. It is a managed environment
  2. It forms a security boundary. An assembly is the unit at which permissions are requested and granted
  3. It is the unit at which side-by-side execution is supported.
  4. It forms a deployment unit. When an application starts, only the assemblies that the applicationinitially calls must be present. Other assemblies, such as localization resources or assemblies containing utility classes,can be retrieved on demand
  5. It forms a version boundary. The assembly is the smallest versionable unit in the common language runtime; all types and resources in the same assembly are versioned as a unit.

There are in all 3 different types of assemblies :

  • 1. Private Assembly
  • 2. Shared or Strong named assembly
  • 3. Satellite assembly

This article focuses only on private assembly and few other assembly concepts. Private assembly is a managed standalone executable or a class library file.

§ Creating a simple assembly and referencing other assembly to it

§ Assembly probing

Creating a simple assembly and referencing other assembly to it

I have a created an assembly called “AssemblyHost” and added reference to “Test” assembly. I am calling method “Add” defined
within Test assembly’s class.

Test
Assembly

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Test

{

public class MyClass

{

public static int Add(int i,int j)

{

return (i + j);

}

}

}

AssemblyHost assembly

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Test;

namespace AssemblyHost
{
    class Program
    {
        static void Main(string[] args)
        {
            int j = MyClass.Add(5, 7);
            Console.WriteLine(j.ToString());
            Console.ReadLine();
        }
    }
}

Output

2. Assembly Probing – Dotnet runtime searches for the assembly in the following path

§

  • Look for the dll or exe under the Application directory (generally bin folder) or AppBase – Example shown above works in this fashion
  • §
  • Look for the assembly folder under the Application directory (generally bin/<assemblyname>) and try to find dll or exe .

Suppose I create one more project “Test1” as seen below :

When I try to load the new assembly without referencing, I get an error. However, if copy and paste a folder “Test1” under my application directory (bin/Debug) and copy the dll..it works

Application Directory – AssemblyHost/bin/Debug

Folder Path – AssemblyHost/bin/Debug/Test

Dll Path – Folder Path/Test.dll

§
Look for probing path defined under configuration file

I have to define my application config file as seen below to search for dll or exes to be loaded into my running assembly. The below configuration searches within MyLib folder inside my Application Directory and searches for all dlls.

<?xml version=1.0 encoding=utf-8 ?>

<configuration>

<runtime>

<assemblyBinding xmlns=urn:schemas-microsoft-com:asm.v1>

<probing privatePath=MyLib/>

</assemblyBinding>

</runtime>

</configuration>

GAC(Global Assembly Cache)

If the private probing fails, then the assembly is searched from within GAC. I will cover GAC in the next part of this article.

Till then happy reading.