Monday, December 24, 2012

Read Private Type using Visual Studio Unit Testing in C#

small things can make a different

I want to read my class  private values to verify the unit testing using MS unit test.

Here is the sample code

Created the sample class named NumberChecker, it contains two private property and public method.
The method going to check, the passed number is greater than zero or not. based on that it's going to pass a different message back the client.


namespace PrivateTypeDemo
{
    public class NumberChecker
    {
        private const string Validmessage = "The Number is Greater than Zero";
        private const string DefaultMessage = "The Number is Zero or Less than Zero";
        public string ValidateNumber(int number)
        {
            return number > 0 ? Validmessage : DefaultMessage;
        }
    }
}
Here is the console application which consumes the library

namespace PrivateTypeDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var numcheck = new NumberChecker();
            Console.WriteLine("Please Enter your Number");
            var  number = Convert.ToInt32(Console.ReadLine());
            var result = numcheck.ValidateNumber(number);
            Console.WriteLine(result);
 
 
        }
    }
}

Unit Test for the NumberCheck class
 [TestClass]
    public class NumberCheckerTest
    {
        [TestMethod]
        public void ValidateNumberTest()
        {
            var target = new NumberChecker();
            const int number = 15;
            var privateType = new PrivateType(target.GetType());
            var expected = privateType.GetStaticFieldOrProperty("Validmessage");
            string actual = target.ValidateNumber(number);
            Assert.AreEqual(expected, actual);
        }
        [TestMethod]
        public void ValidateNumber2Test()
        {
            var target = new NumberChecker();
            const int number = -5;
            var privateType = new PrivateType(target.GetType());
            var expected = privateType.GetStaticFieldOrProperty("DefaultMessage");
            string actual = target.ValidateNumber(number);
            Assert.AreEqual(expected, actual);
        }
        [TestMethod]
        public void NumberCheckerConstructorTest()
        {
            var target = new NumberChecker();
            Assert.IsNotNull(target);
        }
    }
The below lines does the magic of accessing the private type of the classes.This class is shipped part of the 
Microsoft.VisualStudio.TestTools.UnitTesting Assembly  which support this functionality in unit Testing

var privateType = new PrivateType(target.GetType());
var expected = privateType.GetStaticFieldOrProperty("DefaultMessage");

Here i am reading the value of DefaultMessage through the GetStaticFieldOrProperty Method in the PrivateType class
To Learn More about this,
PrivateType

Monday, October 29, 2012

Performance Measurement Tools

List of Performance Measurement Tools in Microsoft .NET


  • Visual Studio Sampling Profiler
              http://msdn.microsoft.com/en-us/library/ms242753.aspx
              http://msdn.microsoft.com/en-us/library/ms182372.aspx
  • Visual Studio Instrumentation Profiler
              http://dotnet.dzone.com/articles/profiling-application-visual-0
  • Visual Studio Allocation Profiler
              http://dotnet.dzone.com/articles/profiling-application-visual-1
  • Visual Studio Concurrency Profiler
              http://www.youtube.com/watch?v=Bofk3ecJOtk
              http://msdn.microsoft.com/en-us/magazine/ee336027.aspx
  • CLR Profiler
              http://msdn.microsoft.com/en-us/library/ff650691.aspx
  • Performance Monitoring
               http://msdn.microsoft.com/en-us/library/aa645516(v=vs.71).aspx
  • PerfView
              http://channel9.msdn.com/Series/PerfView-Tutorial
  • Windows Performance Toolkit
              http://msdn.microsoft.com/en-us/performance/cc825801.aspx
  • Process Monitor
             http://en.wikipedia.org/wiki/Process_Monitor
  • Entity Framework Profiler
            http://www.hibernatingrhinos.com/products/efprof
  • ANTS Memory Profiler
              http://www.red-gate.com/products/dotnet-development/ants-performance-profiler/
  • .NET Memory Profiler
              http://memprofiler.com/


Sunday, October 21, 2012

Enable Wifi without the Wireless Router for Home Usage

Recently I bought a Samsung mobile phone Y Series. To activate the Samsung app store and Google play store, it's asking me to connect via  WiFi . But i don't have a WiFi router with me. but i have 10 Mbps Airtel Broadband Connection











Now i have two options


  • I have to activate Air tel 3 G in my mobile to access all the Samsung apps
  • I need to buy the WiFi Router , so i could use my existing broad band connection
I don't want to spend extra money to activate 3G also WiFi router is extra overhead for me

I found this useful software for Windows 7, it will act as Virtual WiFi Router

Download the WiFi Router from here Download

 You can create a WiFi hotspot for WiFi Reverse Tethering for wifi supported mobiles and other wifi enabled computer to create a network and to share internet. Convert your PC into a WiFi hot spot for free.

Follow this instructions to configure it for the first time


Now enjoy the same speed in your mobile and save money

Tuesday, October 16, 2012

SOA Design Patterns

List of SOA(Service Orientated Architecture Link) Patterns for distributed system development

Foundation Structure Pattern

  • Service Host Pattern
  • Active Service Pattern
  • Transactional Service Pattern
  • Workflodize Pattern
  • Edge Component Pattern
Patterns for Performance, Scalability
  • Decoupled Invocation Pattern
  • Parallel Pipelines Pattern
  • Gridable Service Pattern
  • Service Instance Pattern
  • Virtual Endpoint Pattern
  • Service Watchdog Pattern
Security and Manageability
  • Secured Message Pattern
  • Secured Infrastructure Pattern
  • Service Firewall Pattern
  • Identity Provider Pattern
  • Service Monitor Pattern
Message Exchange Pattern
  • Request / Reply Pattern
  • Request / Reaction Pattern
  • Inversion of communication Pattern
  • Saga Pattern
Service Consumer Pattern
  • Reservation Pattern
  • Composite Front End Pattern
  • Client /Server / Service Pattern

Service Integration Pattern
  • Service Bus Pattern
  • Orchestration Pattern
  • Aggregated Reporting Pattern

Service Anti Pattern
  • Knot anti-pattern
  • Nano service anti-pattern
  • Transactional Integration anti-pattern

Reference




Read Event Log Information using LINQ PAD


Anyone tried the LINQ PAD. I found this is very useful to execute for query any short of information from different sources like database, xml, event logs, iis logs with the minimal code

In this blog, i am going to show a example, how we could pull the summary of the events using the LINQ PAD

Link to download LINQ PAD http://www.linqpad.net/


LINQPad is a free software utility for Microsoft .NET to interactively query SQL databases and other data sources such as OData or WCF Data Services using LINQ. LINQPad supports the following LINQ dialects:
  • LINQ to Objects
  • LINQ to SQL
  • Entity Framework
  • LINQ to XML
It also supports writing queries in SQL as well.

Download and install the LINQ PAD. Open the LINQ PAD and select a new query and select the language as C# Program

Code



void Main()
{
var serverList = new List
  {
  //List of Servers Name
  };
var eventCollection = new Dictionary();

int count = 0;
foreach (var list in serverList)
{
var eventLog = new EventLog(EVENTLOGNAME, list, SOURCENAME);
        foreach (EventLogEntry logEntry in eventLog.Entries)
        {
if (logEntry.TimeGenerated  >=  DateTime.Today)
{
if (eventCollection.ContainsKey(logEntry.InstanceId))
{
eventCollection[logEntry.InstanceId]++;
}
else
{
eventCollection.Add(logEntry.InstanceId, 1);
}
}

        }
Console.WriteLine("Summary of Server " + list);
foreach (var logs in eventCollection)
{
Console.WriteLine(logs.Key + "  " + logs.Value);
}
eventCollection.Clear();
}

}

// Define other methods and classes here


Sample Output

Summary of the Server "ServerName1"
Event ID   Number Of Times
100            7
106            15

Summary of the Server "ServerName2"
Event ID   Number Of Times
100            70
106            8

Wednesday, July 4, 2012

One Way Contract in WCF

In this post, i am going to explain the benefit of the One way contract. I have a page which collect the feedback from the customer. it internally calls web service and send the feed back information to the DB via Wcf service

Created the simple Asp.NET web application which accept the feedback from the users


when the user enter the feedback and click the submit button it's going to call the FeedBackService and the service is not going to return back anything

For demo purpose, in WCF service side, i put thread to sleep for 5 seconds

[ServiceContract]
    public interface IService1
    {
 
        [OperationContract]
        void SendFeedBack(string Name, string Message);
 
       
 
    }


 public class FeedBackService : IService1
    {
        public void SendFeedBack(string Name, String Message)
        {
            Thread.Sleep(5000);
        }
 
        
    }



Let's look at the response time
Http Watch report for the response time

Before


Response time is 5.2 seconds

Adding the OneWay is true in  the service side and updating the proxy class from the client side
Server Side
 [ServiceContract]
    public interface IService1
    {
 
        [OperationContract(IsOneWay=true)]
        void SendFeedBack(string Name, string Message);
 
       
 
    }



Client Side

The following piece of code added part of the proxy

 [System.ServiceModel.OperationContractAttribute(IsOneWay=true, Action="http://tempuri.org/IService1/SendFeedBack")]
        void SendFeedBack(string Name, string Message);



After



The response time is comes down to 0.2 seconds


MSDN Description on Oneway call
There are cases when an operation has no returned values and the client does not care about the success or failure of the invocation. To support this sort of fire-and-forget invocation, Windows Communication Foundation offers one-way operations. After the client issues the call, Windows Communication Foundation generates a request message, but no correlated reply message will ever return to the client. As a result, one-way operations can't return values, and any exception thrown on the service side will not make its way to the client. One-way calls do not equate to asynchronous calls. When one-way calls reach the service, they may not be dispatched all at once and may be queued up on the service side to be dispatched one at a time, all according to the service configured concurrency mode behavior and session mode. How many messages (whether one-way or request-reply) the service is willing to queue up is a product of the configured channel and the reliability mode. If the number of queued messages has exceeded the queue's capacity, then the client will block, even when issuing a one-way call. However, once the call is queued, the client is unblocked and can continue executing while the service processes the operation in the background. This usually gives the appearance of asynchronous calls. 


Tuesday, June 26, 2012

Shanmugam Currently Reading this Book


I am listing out the technical books i was currently reading it

CLR Via C#


CLR via C#


ASP.NET MVC 4 in Action




MVC 4 in Action


The Science of Influence



The Science of Influence

Domain Driven Design

DDD

Thursday, June 21, 2012

Pluralsight Hardcore developer Training





I was using the  .NET video tutorial site pluralsight.com  for past one month. I got the 1 month free subscription during  Microsoft Tech Ed 2012 happend in Bangalore. The videos were really good and very informative and the time saver for the developer. please check it out Pluralsight

Some of the Quotes about the pluralSight
"Classroom training is in the past. Our library of developer training videos is as mobile as you are. With our new mobile app, you have access to all our latest content, so that you can learn when and wherever you need it. Say goodbye to the old way of learning, and meet the new face of hardcore developer training."

"Technology isn’t slowing down. No wonder our library keeps growing. And because your work demands the newest technology, we often have new videos out before many realize they need it. In fact, we average 2-3 new training videos per week. At that speed to market, you can only imagine the wealth of valuable content we are constantly creating. You can see why it’s worth visiting us often."


"Developers are at the core of every business. And the world’s most recognizable businesses are using Pluralsight training. With our small business and enterprise plans, you get it all—simple license management, progress reports, assessments, and measurable ROI—all in a customized plan for you. We’ve changed the landscape of developer training. Let us change the landscape of your business."


I really like the following topics


  • Design Patterns
  • HTML 5
  • Networking for developers
  • jQuery
  • Windows 8 Metro Style Apps
  • Advanced Debugging


Monday, June 18, 2012

Enhanced Project Template in MVC4

Project Template is gives us the predefined, customized and reusable components. So It accelerates the development process  instead of starting the project from scratch.

Install the ASP.NET MVC 4 from the following Location MVC4 Setup

MVC 4 Enables list of following built in Template.


  • Internet Application
  • Intranet Application
  • Mobile Application
  • Web API
  • Basic Template 
  • Empty Template



MVC 4 Built In Templates

Go to Visual studio 2010 click File -> New Project and Select ASP.NET MVC 4 and click OK. this will popup another window,

This will list out Project Template and the option for the View Engine and whether to include the unit project or not



Internet Application

This templates help us to create a web application using asp.net MVC 4

For the first demo i am going to select the Internet Application,  if you notice the bottom of the visual studio while loading the first application in MVC 4, it will load all the dependent packages through Nuget. This is one of the new functionality which is added part of the MVC 4




How do i check the list of package installed part of my application?


In Solution Explorer, select your project and open the Package.Config File, This file contains the list of the Nuget Package used in this project.

This is my package.config file






 
 


I selected the internet application and the View Engine as Razor and i didn't check in the Unit Test Project
and click OK, it creates My Project with the list of predefined files. To run the application i hit Ctrl +F5

It loads my first application

In addition to cosmetic improvements, there’s improved functionality in the new template. The template employs a technique called adaptive rendering to look good in both desktop browsers and mobile browsers without any customization.

Intranet Application


This template look similar to the internet application, It uses the windows authentication instead of the forms authentication which is used by the Internet Application


Mobile Template


This template used to develop the project specific to the mobile and tablets browsers


This template contains the same application structure as the Internet Application template (and the controller code is virtually identical), but it's styled using jQuery Mobile to look good and behave well on touch-based mobile devices. To learn more about how to structure and style mobile UI, see the jQuery Mobile project website.

What's New in MVC 4

Today I start reading the book ASP.NET MVC 4. I am going to list out the New Features in MVC 4 and planning to share the code example on each topic


  • ASP.NET Web API
  • Enhancements to default project Templates
  • Mobile Project Template
  • Display Modes
  • JQuery Mobile
  • View Switcher
  • Browser Overriding
  • Task Support For Asynchronous controller
  • Empty Project template

The Complete Release Note Details hereRelease Note

The book which includes the complete details MVC 4 in Action