Showing posts with label .NET Framework. Show all posts
Showing posts with label .NET Framework. Show all posts

Friday, May 26, 2017

Running the first .NET Core program in Docker environment


 

What is .NET Core?

.NET Core is a general purpose development platform maintained by Microsoft and the .NET community. It is cross-platform which suppors Windows, macOS and Linux, and can be used in device, cloud, and embedded/IoT scenarios.

What is Docker?
Docker is an open platform for developers and sysadmins to build, ship, and run distributed applications. It leverage the speed in developing, packaging and running portable distributed applications. Docker for Windows is a Docker Community Edition (CE) app.

Note: It requires Microsoft Hyper-V to run and the current version of Docker for Windows runs on 64bit Windows 10 Pro, Enterprise and Education (1511 November update, Build 10586 or later).
Hardware Virtualization must be enabled. It is prerequisites for Hyper-V and also for Docker also.. You can check it in the Task Manager’s performance tab for CPU.

image



Now we start installing Docker on Windows 10 Pro.
First enable Hyper-V and here are the steps:
  1. Press Windows + R and run appwiz.cpl to open “Programs and Features” section of Control Panel.

    clip_image001
  2. Now click on “Turn Windows features on or off”.

    clip_image003
  3. Check Hyper-V in Windows Features section to enable it.

    clip_image004
I found an interesting and easy to understand moving image(gif) to know that how to enable Hyper-V form control panel.
clip_image005
Installing Docker application
  1. First download Docker InstallDocker.msi installer from here and then double-click InstallDocker.msi to run the installer.
  2. Follow the install wizard to accept the license, authorize the installer, and proceed with the install.

    clip_image006
  3. Follow the install wizard to accept the license,and click Next.

    clip_image007
  4. Click Finish on the setup complete dialog to launch Docker.

    clip_image008
  5. When Docker start without error then you will see Docker icon in the taskbar.

    clip_image010
and Linux virtual machine in the Hyper-V so we need to switch to Windows containers. It may restart your computer as did with me.
and switch to windows container.
Now time to come for creating the first “Hello World” program on Docker and run it. To work with Docker, we have start “Power Shell” to run the CLI command to create the program.
  1. First run the following command to get a container with the dotnet core tools.

    docker run -it microsoft/dotnet:latest
  2. Now create “Hello World” console application:

    dotnet new console -o hwapp 
  3. It will create a directory with name ‘hwapp’. Go into that directory using ‘cd hwapp’ and run the restore command.
    dotnet restore
image

 

Description from MSDN article:
You can, of course, develop your applications by using any language supported by Docker, like Node.js, Java, Go, Python, etc., Right now Microsoft working hard to make better support for .NET Core and .NET Framework in Docker environments. You can actually try the official  .NET and ASP.NET Core images available at Docker Hub as I have used one of them in above exercise to run the program on the Docker container.

It is quite interesting that these containers are help full to create different type application and host them to make auto build as read so far about them.
















Friday, October 7, 2016

How to configure log4net in .NET projects?

log4net is an open source library that help the programmer output log statements to a variety of output targets in .NET .
Here we are going setup logging using the Log4Net. Below are the necessary step to get Log4Net in the project and configure it:
  1. Right click on the solution in the “Solution Explorer” and select “Manage Nuget Packages for Solutions..

    image_thumb[9][4]_thumb[2][1]

    Now search for the log4net using the search box and you will find the log4net by Apache Software foundation. The another thing need to remember is that you have to select the projects on the right side where log4net reference is required. It should be in start up project and another projects are optional to add the reference of the log4net.

    image_thumb[10][4]_thumb[3][1]
    After this you will find log4net in referenced libraries of the selected projects.

    image_thumb13[4]_thumb[1][1]


    This can be done by running the “Install-Package” command on the “Package Manager Console” as seen in below image:

    image_thumb[13][4]_thumb[1][1]

    Alternative, you can download the binaries from Apache.Org website and reference them manually in the project where logging is required’'.
  2. Now you need to configure log4net to log the information or errors to different targets e.g Console, file, database etc. Right now we are going to configure it for the easiest way to log the information.

    Using log4net is a three stage process. First thing we need to do is configure log4net. For an example, below are simple steps to configure the BasicConfigurator.
    log4net.Config.BasicConfigurator.Configure();
    In second step, is to get Logger object using the static method GetLogger of the LogManager to log using the log4net:
    var log = log4net.LogManager.GetLogger(typeof(Program));
    After that use the logger object to log the message:

    log.Info("Exception Message");

Complete code snippet:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Log4NetConsoleCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            log4net.Config.BasicConfigurator.Configure();

            var log = log4net.LogManager.GetLogger(typeof(Program));

            log.Info("Exception Message");

            Console.ReadKey();
        }
    }
}
If we run the program then it will show log message in console.
image_thumb15[4]_thumb[1][1]




Thursday, July 14, 2016

Run CSharp “Hello World!” program on Developer Command prompt

To start writing your first program without using the Visual Studio or other tools, you just need to open “Command Prompt”. Just type command on the search in Start menu either you are using Windows 7 or any higher.
image_thumb[10]_thumb[3][4]
Visual Studio installs few command line tools to do some operation using command tools and these can be invoked using the “Developer Command Prompt for VS2015”(For Visual Studio 2015). If someone has not installed Visual Studio then just install .NET Framework on the computer.
After this we are ready to create and compile our “Hello World!” program using the .NET Framework compilers.
Now create a file “hello.cs” using the “notepad”. We are going to write our code to print “Hello World!” on the screen for this example. “.cs” is the common extension for the C# file and “.vb” for Visual Basic. So now we going to create a C# program now so this file will contain C# code.
image_thumb[16]_thumb[1][4]
After running this command a prompt will appear with message “Do you want to create a new file?”. Click on “Yes” to create a new file.
In this we are going to create a class with a static method “Main”. In a Console application that would run on command prompt, CLR look for class named “Program” with a “Main” method to run the program.
image_thumb[8][3]
Now save this file and come back to the command prompt.
Now one of the tool “csc.exe” exists in the “Windows” directory in the .NET framework installation paths. It can be located at the path “C:\Windows\Microsoft.NET\Framework\{.NET Framework}”. Under the Framework folder you will find installation of .NET Framework multiple version. Below is the path of the latest one on my system. It is the “Visual C# Command Line Compiler” which compiles the C# code.
image_thumb[24][4]
Now we are going to compile the C# code then execute the program. After compiling the program C# compiler produce a executable file(.exe).
To compile the created C# code file, use the below command line on command prompt. Just pass the created “hello.cs” as parameter.
  1. csc hello.cs 
image_thumb[29][4]
On windows we can run exe. Now run the hello.exe to view the result of our example program.
image_thumb[32][4]
That’s all done. We have created an example program run on the command prompt using the C# command line compiler.
Actually it transforms C# code into Microsoft Intermediate Language. This can either an exe or dynamic link library. We specify the assembly format to the csc.exe using the /targe:library option. See below image for various target options:
image_thumb[37][4]
  Happy Coding!



















Wednesday, June 29, 2016

New feature “Add a reference to a NuGet package” in Visual Studio 2015 Update 3

Microsoft announced the release of Visual Studio 2015 Update 3 two days ago. They have addressed issues from previous update and improved few things. In the list of improvements, I found an interesting thing that you can now quickly include NuGet packages by just using the resolve reference method. You can say it An option to add a reference to a NuGet package as a quick fix.

nugetbulb

You can enable this option from Tools > Options > Text Editor > C# > Advanced, under "Using Directives":

nuget

Visual Studio is improving in most of the expects for the development of the Universal Application development. There kind of improvements can make you more productive..

Monday, May 2, 2016

Analyzing the Quality of your code with NDepend

Throughout my carrier I have worked on various projects in different environment. Few of them are completed solo and few are with small or big teams. As per my opinion and learning till now “Writing a good and clean code is an art”. This is improved with experience and learning about the “Design Patterns”.

When you are doing project as one man army then you are good to write better code and refactor it maximum as per your understanding and knowledge, but when it done with in a large project and team then a project manager or Architect will definitely worry about the quality and success of the project.

In starting days of my carrier, One day my manager asked me to learn about the Cohesion and Coupling. I was not able to understand it much at that time and tried so many time to implement it in my coding practices. After continuously taking care of such factors and knowing about the “Design Patterns” e.g. SOLID, FAÇADE etc. what I have realized that all of these things redirect the programmers to make “Quality Code”.

After this when it comes to manage a big project then you require some tools which help to find issues in a large project. It makes an architect to keep free from these below question for some instance:

  • Is the code looking good?
  • What about its complexity and test coverage?
  • Can you consider the code as maintainable with a good scalability?
  • Are there instances of copy and paste code smells?
  • How loosely and tightly coupled is the architecture? (In terms of cohesion and coupling etc.)

Doing this task manually is a time consuming process because checking and running every module will definitely consume some time. Without running the project it is possible in manually compiling and inspecting but with the tools it is much time saving process.

To check the quality of the code and analyze, I put my hands on Visual Studio inbuilt tools e.g. Unit Test Runner, Code Metrics, and Static Code Analyzes. These tools are good to work but there are few third party tools available to do some task with high precision analyzes e.g. FxCop, JustCode, ReSharper, and NDepend.

In this article, I am going to explorer the features and benefits of NDepend.


What is NDepend and its use??

NDepend is a static code analyzes for .NET. NDepend can be used in both standalone and Visual Studio integrated mode (Through Visual Studio extension). This nice tool is create by Patrick Smacchia for the developer community.

NDepend Visual Studio extension performs a range of analyzes across a solution, either during design time or retrospectively across an existing project. Current version of NDepend 6 provides 82 Code Metrics which are analyzed and reported on by the tool either in GUI or html format.

Right now I have used it in Visual Studio Integration mode. I prefer to use in integrated environment rather than doing application switch for doing same thing in different window and NDepend provide most of its functionality in Visual Studio while working with the project through a separate menu.

clip_image001

Setting NDepend Integration with Visual Studio:

To enable work NDepend in Visual Studio, NDepend guys provides an extension installer “NDepend.VisualStudioExtension.Installer.exe”. Check highlighted file in the below image.

clip_image002

Once you run this extension installer it will pop up an installation dialog which let us to integrate NDepend in our desired version of Visual Studio. Right now I am using Visual Studio 2015, so I installed for my IDE.

clip_image003[6]

After completing installation, you can access to various metrics, rules, graph, reports, analyzer results and tools at one place to analyze the project for different aspect of the quality measures.

NDepend is mainly a static analyzes tool and more. It provide out of the box rule and customizability of rule through CQLinq, Visual Dependency representation, Build Integration and Change tracking. NDepend allow us to write own custom rules and you can visualize your code base and its dependencies with series of matrices and graphs as well.

It does more than providing snapshot of the code base at moment some times. It integrates in to Build process and allows us to monitor the evolution of the code and decide whether you making progress towards quality or not.

Start analyzing my first project with NDepend

After installing NDepend in Visual Studio, I found it very user friendly and quite intuitive. You can just select project from the NDepend menu to start analyzing it. Let see how its start screen looks like in first glance.

clip_image004

Here you can select specific menu to start working with NDepend. Now my solution is open so I am just going attach a new NDepend project to current solution. Just click on the circle in status bar of the Visual Studio and you have access to NDepend here also. See below image.

clip_image005

Now select “Attach new NDepend project to current VS Solution”. Now it prompt to select the assembly to analyze and you can also add another assemblies on below screen.

clip_image006[6]

Just click on “Analyze a single .NET Assembly”. Now it start analyzing the assembly and after completion of process it will pop up a dialog and along this generates html report about the analyze results.

clip_image007

I am going to click on the View NDepend Dashboard and it redirected me to dashboard.

clip_image008[6]

  And html generated report is shown as below:

clip_image009

In Visual Studio, there are lots of windows available through NDepend to analyze quality of the code base and even you can customize these. I am going through main features of the NDepend one by one. See below screen shot with Queries and Rules Explorer, Dependency Graph and Queries editor. 

clip_image010[6]

Code Rule and Code Query over LINQ (CQLinq)

NDepend project provides build-in metrics when you create a new project to analyze an assembly. As I saw in Queries and Rules Explorer, there are more than 200 default project rules and their queries.

These rules are made up using the CQLinq. CQLinq is default scripting for NDepend to create rule queries. So in this way you can create our own queries and customize them too. CQLinq editor provides code completion and intellisense with live error description.

clip_image011

Dependency Matrix

Dependency Matrix shows dependency and coupling between the projects and their module. NDepend must responsive and easy navigate through the dependencies between the projects. When you click on any cell then it shows graph and information in tooltip manner. I liked this behavior because I do not need to switch between dependency graph and dependency matrix. They are shown in a synchronized way and easy to visualize and analyze the results.

clip_image012[6]

Dependency Graph

It is an interactive way to represent coupling between the code base elements. Actually NDepend provide this graph for various code exploration scenarios. You can find full description about these in documentation - Exploring Existing Code Architecture in Visual Studio through Dependency Graph.

  • Dependency Graph
  • Call Graph
  • Class Inheritance Graph
  • Coupling Graph
  • Path Graph
  • All Paths Graph
  • Cycle Graph

These various type of graphs are accessible from NDepend->Graph menu items.

clip_image013

clip_image014[6]

Code Metrics View

Code metrics view represents tree-structured data in rectangular blocks format.

clip_image015

Continuous Integration Reporting

These feature matter much analyzing a huge code base. Along with CQLinq, I like NDepend for this feature. NDepend integrate with TFS, Team city etc. in build process to check for the violation of CQLinq rules continuously and these are reported to the development teams to improve the code.

NDepend can analyze source code and .NET assemblies through NDepend.Console.exe. Each time it analyzes a code base, NDepend yields a report that can inform you about the status of our development. As I described in the starting of article about the html document which generated during the analyzing process is generated during build process.

This exe is located in the installation folder and the file name is “NDepend.Console.exe”. It is integrated in the building process by specifying command line arguments.

Conclusion

These are the few features which I have used so far but NDepend is loaded with lots features. In my opinion NDepend is light weight, powerful and intuitive application. Customization with the rules and metrics is an additional advantage using its best part CQLinq. It also integrate with Reflector and other tools which improves the productivity. I found it much better tool for maintaining quality of the application so far. Hope NDepend will continue improving this tool in future and let development process to improvise in easy way.

Wednesday, December 2, 2015

Install .NET Framework 3.5 in Windows 8 and 10

Windows 8 and 10 comes with .NET framework 4 or higher pre-installed, but there are lots of applications require the .NET framework v3.5 installed to install on these newer version of operating systems. These applications will not run unless you will install the required version of .NET framework. When you try to run any such sort of applications then Windows 8 and 10 will prompt you to download and install .NET framework 3.5 from the Internet. However, this will take a lot of time.

Source: MSDN article.
Below are the steps to enable .NET framework 3.5:

  1. Go to Settings. Choose Control Panel then choose Programs.

    clip_image002
  2. Click Turn Windows features on or off, and the user will see window as image below.

    clip_image004

    clip_image006

    You can enable this feature by click on .NET Framework 3.5 (include .NET 2.0 and 3.0) select it and click OK. After this step, it will download the entire package from internet and install the .NET Framework 3.5 feature.

You can save your time and install .NET Framework 3.5 from the Windows 8 and 10 installation media respectively. This method is much faster and does not even require an Internet connection.
Follow below steps to install .NET Framework 3.5 in Windows 8 and 10 using DISM:

  1. Bring your installation media to prepare installation either it is DVD or ISO image. If you are using ISO image then mount it using software e.g. Power ISO, DAEMON Tools so then you will be able to access the files for the installation.
    Packages are located in the drive letter: \sources\sxs directory.
  2. Open CMD.EXE with Administrative Privileges. Right click on the start button (or press “Win + X”) to popup the system menu. There you will find a menu item titled “Command Prompt (Admin)”. Click on this to launch the command prompt in admin mode.
    image
  3. Run the following command and hit Enter.
    Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:E:\sources\sxs /LimitAccess

    clip_image009
    Please make sure to change the source path:
    e.g.
    If you have Windows setup at “D:” drive, replace “E:” with “d:”
    If you have Windows setup at “F:\Win10Setup” folder path, replace “x:” with “f:\Win10Setup”
    When run from the command prompt, it will start installing the .NET framework. It will take a while to complete the whole process. Once done, restart your system for the changes to take effect.

Details on command line parameters of DISM:

  • /Online targets the operating system you're running (instead of an offline Windows image).
  • /Enable-Feature /FeatureName:NetFx3 specifies that you want to enable the .NET Framework 3.5.
  • /All enables all parent features of the .NET Framework 3.5.
  • /LimitAccess prevents DISM from contacting Windows Update.
  • /Source specifies the location of the files needed to restore the feature (in this example, the x:\sources\sxs directory).

After completion of this process .NET Framework 3.5 feature enabled. Restart and then you good to go for the installation of your application.

Monday, August 18, 2014

Debugging Threads with Concurrency Visualizer

Features of Concurrency Visualizer:

  • Shift+Alt+F5
  • Fast processing, faster loading
           o Supports big traces
  • Supports big traces
  • Support s EventSource and custom markers
            o Built-in support for TPL, PLINQ, Sync Data Structures, and Dataflow
            o Built-in support for your own EventSource types
                    § Also provides Visual Studio markers API
  • New Visualizations
             o e.g. defender view

Demo:

Here are few steps to know that how to utilize “Concurrency Visualizer” for multithreaded applications.

  1. Create a Console project.
  2. Create custom EventSource to trace in the visualizer as below:
    [EventSource(Guid = "7BBB4E52-7DA7-45EB-B6C2-C01D460A087C")]
    class MyEventSource : EventSource
    {
    internal static MyEventSource log = new MyEventSource();

    [Event(1)]
    public void SomeEventHandled(int data)
    {
    WriteEvent(1, data);
    }
    }

    To provide GUID to the event source use “guidgen” and copy newly generated GUID. Then put it in the attribute of the EventSource class.

    clip_image002
  3. Now complete the test code to proceed the demo.

    Full code snippet:

    using System.Threading;
    using System.Threading.Tasks;

    namespace ConcurrencyVisualizerDemo
    {
    class Program
    {
    static void Main(string[] args)
    {
    var list = new List<Task>();
    for (int i = 0; i < 10; i++)
    {
    list.Add(Task.Run(() =>
    {
    //Loging here
    MyEventSource.log.SomeEventHandled(21);
    Thread.SpinWait(1000000);
    }));
    }
    Task.WaitAll(list.ToArray());
    }

    [EventSource(Guid = "7BBB4E52-7DA7-45EB-B6C2-C01D460A087C")]
    class MyEventSource : EventSource
    {
    internal static MyEventSource log = new MyEventSource();

    [Event(1)]
    public void SomeEventHandled(int data)
    {
    WriteEvent(1, data);
    }
    }
    }
    }


  4. There is optional extension “Concurrency Visualizer” for visual studio, which visual all the data to debug the concurrency between the treads. After installing this, you can find the option under Analyze menu. See image below:

    clip_image004
  5. Now copy the GUID  of MyEventSource and go to the Concurrency Visualizer’s settings. Then add new provider and put this copied guid in the provider.
    Analyze->Concurrency Visualizer->Advance Settings->Markers

    image

    Provide name and paste copied guid in the Privider GUID field. Click ok to complete provider addition.
  6. Now start Concurrency Visualizer by pressing Shift+Alt+F5 and it will start Shift+Alt+F5. Now it will start generating reports. See the below images:

    image

    image

    image

    image