Sunday, May 18, 2014

Tips #-.Net Reflection to fetch value of Object Property.

Runtime Activity- I want to pass a class and property in the string and resolve the value of the property.

 With Generics

Generics

Friday, May 2, 2014

Get website details such as physical path using Powershell



Import-Module "WebAdministration" -ErrorAction Stop

foreach($site in (dir iis:\sites\*WebSiteNameXyz*))



{

write-host $site.Name

write-host $site.Bindings

write-host $site.State

write-host $site.physicalpath



}

Power of Powershell remoting WSMan

If you want to execute powershell script from your local box onto remote server this is the best solution to do.

Before you take deep dive in below powershell script . Ensure few things in local source and destination remote server settings.
* Ensure WinRs windows remote services . Type services.msc and this service should be enabled and auto mode.
* Ensure WSMan is enabled
Use gpedit.msc and look at the following policy:
 
Computer Configuration ->
Administrative Templates ->
System ->
Credentials Delegation -> Allow Delegating Fresh Credentials. 
 
Verify that it is enabled and configured with an SPN appropriate for the target computer.C lick on add server list mention WSMAN/myserver.domain.com
 

set-item wsman:localhost\client\trustedhosts -value *

#Enable credssp authentication
Enable-WSManCredSSP -Role Client –DelegateComputer *

# This will establish server connection
Connect-WSMan myserver

invoke-command -computername myserver-authentication credssp -credential domain\username -filepath c:\dbtest.ps1

  

This will prompt for password and you are good to go.
Now this dbtest.ps1 can be your powershell script which will deploy code base to different environment.

 
Useful References


Write to event log
http://blogs.technet.com/b/heyscriptingguy/archive/2013/06/20/how-to-use-powershell-to-write-to-event-logs.aspx

Monitor Scheduled Job
http://blogs.technet.com/b/heyscriptingguy/archive/2014/04/29/powertip-use-powershell-to-show-state-of-scheduled-tasks.aspx

 
Database administration

Wednesday, April 16, 2014

Four Timeout Property for Bindings in WCF

Four Timeout Property for Bindings in WCF
sendTimeout: time taken by WCF service to respond to client
openTimeout: Amount of time client willing to wait for WCF service to open connection
closeTimeOut: Amount of time client close the proxy connection to WCF service
receiveTimeout: Time spent by client to process response received from WCF service

 
                 sendTimeout="00:25:00">
   

 


http://stackoverflow.com/questions/1520283/wcf-service-how-to-increase-the-timeout

Powershell Issue: SOAP header Action was not understood. when use wsHttpBinding

Powershell Script Calling WCF Service.

Issue: SOAP header Action was not understood. when use wsHttpBinding

This can be solved if we use basicHttpBinding.

You might want to use the basicHttpBinding to get it working with a .NET 2.0 client. That binding already provides the compatibility required by older clients or other platforms. If you still decide to go with wsHttpBinding, you will have to use Microsoft WSE to create messages in the .NET 2.0 client that are compatible with the wsHttpBinding.
With Above statement from Stackoverflow that means we can run powershell in .net 4 runtime to even overcome above problem.
http://stackoverflow.com/questions/8518282/how-to-communicate-with-a-wcf-service-wshttpbinding-a-net-2-0-client


http://stackoverflow.com/questions/2094694/how-can-i-run-powershell-with-the-net-4-runtime

Simply modify (or create) $pshome\powershell.exe.config so that it contains the following:
xml version="1.0"?> 
 
     useLegacyV2RuntimeActivationPolicy="true"> 
         version="v4.0.30319"/> 
         version="v2.0.50727"/> 
     

Path where this config file must be created :C:\Windows\System32\WindowsPowerShell\v1.0\

Sample Script to call WCF Service with Powershell as client
$uri="http://localhost:59889/Service1.svc"

$proxy = New-WebServiceProxy -Uri $URI -Class newClass1 -Namespace WebService1




$proxy.GetName()
#this is where we have int as input to service and string as output. GetData below ... 
 
$proxy.GetData(5,$true)
 

Wednesday, March 26, 2014

Force Explicit Calling of Static Class-Static constructor

The static constructor loads or called only once when any method of static class is invoked or initialize. There is no need of explicit calling of static constructor. But when there is no static property or method to do so then we can have explicit option to call static constructor as given below
typeof(StaticClassName).TypeInitializer.Invoke(null, null);

Monday, March 24, 2014

C# Cool Code Tips

1.Specialized Collection- NameValueCollection
Real time example
Parse a string such as "p1=6&p2=7&p3=8" into a NameValueCollection

NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);

Results-
qscoll["p1"] , qscoll["p2"] and qscoll["p3"]                

Speciality- This NameValueCollection can hold duplicates Key with different Values.

   // Creates and initializes a new NameValueCollection.
      NameValueCollection myCol = new NameValueCollection();
      myCol.Add( "red", "rojo" );
      myCol.Add( "green", "verde" );
      myCol.Add( "blue", "azul" );
      myCol.Add( "red", "rouge" );


 public static void PrintKeysAndValues2( NameValueCollection myCol )  {
      Console.WriteLine( " [INDEX] KEY VALUE" );
      for ( int i = 0; i < myCol.Count; i++ )
         Console.WriteLine( " [{0}] {1,-10} {2}", i, myCol.GetKey(i), myCol.Get(i) );
      Console.WriteLine();
   }

Displays the elements using
GetKey and Get:   
[INDEX] KEY VALUE   
[0]     red rojo,rouge   
[1]     green verde   
[2]     blue azul

2. Array.ConvertAll
Real Time Example
You have string  with comma separated with integer value and you want to have int[] conversion from string [] array.

look at this now!

string commaSep= "1,2,3"
int[] transform= Array.ConvertAll(commaSep.split(','),s=>int.parse(s))

3. Fetch Calling Method Name using CallerMemberNameAttribute C#4.5

In .Net 4.5 there is now a much easier way to do this. You can take advantage of the CallerMemberNameAttribute
public class SomeClass
{
    public void SomeMethod([CallerMemberName]string memberName = "")
    {
        Console.WriteLine(memberName); //output will be name of calling method
    }
}


https://stackoverflow.com/questions/3095696/how-do-i-get-the-calling-method-name-and-type-using-reflection

Thursday, March 13, 2014

Linq to replace Dictionary values with XML formed tag values.

static void Main(string[] args)
{
 
IDictionary<string, string> placeHolder = new Dictionary<string, string>();

placeHolder.Add("#FirstName#","Phil");

placeHolder.Add("#MiddleName#", "J");

placeHolder.Add("#LastName#", "Haack");
        string parsedXmlString=GetParsedTemplate(@"



#FirstName#

#MiddleName#

#LastName#





", placeHolder);}
 
 
 

public static string GetParsedTemplate(string wellFormedXML, IDictionary<string, string> placeHolder)
{

placeHolder.AsEnumerable().ToList().ForEach(t => wellFormedXML = wellFormedXML.Replace(t.Key, t.Value));

return wellFormedXML;


}

Tuesday, January 7, 2014

Known Issue GetOwinContext() return System.NullReferenceException

HttpContext.Current.GetOwinContext().Authenticate returns System.NullReferenceException when used in web api ie. Apicontroller.

The reason is the original context is not restored after leaving the await block. This is when used with task parallelism await async block.

So switching to .NET 4.5 solved the problem. But why? It seems that in ASP.NET 4.5, a task friendly synchronization context got introduced. This synchronization context ensures that the originel context is restored after leaving the await block.
So make sure that you either:
  • Set httpRuntime.targetFramework to 4.5, or
  • In your appSettings, set aspnet:UseTaskFriendlySynchronizationContext to true.
http://bartwullems.blogspot.se/2013/09/aspnet-web-api-httpcontextcurrent-is.html

http://vegetarianprogrammer.blogspot.se/2012/12/understanding-synchronizationcontext-in.html

Monday, January 6, 2014

Variable Scoping in Javascript

It is always important to make use of VAR to declare variable identifiers. If you miss doing this , there are two implications.

1. It is then by default act as GLOBAL variable.

2. Chances are these variables will be overwritten everytime developers uses same variable name across the modules. This is worst defect and sometimes difficult to figure it out.

/* Declared globally. */

function FindTruth(id) {


}


// Later in your page, another programmer adds…

var FindTruth= $(‘Overwritten-False-Fact’); // The FindTruth function just got

// overwritten.

Namespacing- Best Practice



/* Using a namespace. */

var MyNamespace = {

FindTruth: function(id) {


},

// Other methods can go here as well.

}

// Later in your page, another programmer adds…
var Findtruth= $(‘Overwritten-False-Fact’);// Nothing was overwritten.

In JavaScript Object Oriented programming this is Singleton pattern.

Now one can access method using MyNamespace.Findtruth(Id);

We can even structure it separately and then later add group of methods to decorate as library.

/* Super namespace. */

var SuperLib = {};

SuperLib.Common = {

// A singleton with common methods used by all objects and modules.

};

SuperLib.DataAccess= {

//Hold and transfer data

};

SuperLib.Helper= {

//Html Helper

};

!! Negation in Javascript

Double negation casts a string or a number to a boolean:
var bool = !!num;
The following values are equivalent to false in conditional statements:
  • false
  • null
  • undefined
  • The empty string "" (\ '')
  • The number 0
  • The number NaN
All other values are equivalent to true.
var x = "somevalue" var isNotEmpty = !!x.length;
Let’s break it to pieces:
x.length   // 9
!x.length  // false
!!x.length // true
 

Some Useful Basic Different ways of Javascript Coding

Style 1 Procedural Way

/* Start and stop animations using functions. */

function startAnimation() {


}

function stopAnimation() {


}

Style 2: using Prototype to define Class function

/* Anim class. */

var Anim = function() {


};

Anim.prototype.start = function() {


};

Anim.prototype.stop = function() {


};

/* Usage. */

var myAnim = new Anim();

myAnim.start();

myAnim.stop();

Style 3: Encapsulated Prototyping

/* Anim class, with a slightly different syntax for declaring methods. */

var Anim = function() {


};

Anim.prototype = {

                start: function() {

               …

              },

               stop: function() {

              …

 }

};

Style 4: Function.prototype.method

/* Add a method to the Function object that can be used to declare methods. */

Function.prototype.method = function(name, fn) {

                this.prototype[name] = fn;

};

/* Anim class, with methods created using a convenience method. */

var Anim = function() {


};

Anim.method(‘start’, function() {


});

Anim.method(‘stop’, function() {


});



Style 5: Chain Function Approach

/* This version allows the calls to be chained. */

Function.prototype.method = function(name, fn) {

                     this.prototype[name] = fn;

                    return this;

};

/* Anim class, with methods created using a convenience method and chaining. */

var Anim = function() {


};

Anim.method(‘start’, function() {


})

.method(‘stop’, function() {


});

Tuesday, December 31, 2013

Owin Pipeline with respect to IIS Integrated Pipeline mode Issues

When working Owin authentication you must face following problems.

  • Check if your IIS application pool is in Integrated mode. Note: Running of an OWIN middleware is supported only on IIS Integrated pipeline. Classic pool is not supported. 
  • Check if you have Microsoft.Owin.Host.SystemWeb Nuget package installed. This package is required for the OWIN startup class detection.
  • If your Startup class is still not detected in IIS, try it again by clearing the ASP.net temporary files. 
  •  Sometimes Owin works well with VS IISexpress .
  • <

    appSettings>

    <


    add key="owin:AppStartup" value="[AssemblyNamespace].Startup,[AssemblyName]" />
    </

    appSettings>
     

    Tuesday, December 24, 2013

    Modified ASP.NET 4.5 CPU Throttling percentCpuLimit


    http://blogs.msdn.com/b/webdev/archive/2013/11/26/modified-asp-net-4-5-cpu-throttling.aspx

    <configuration>
        <system.web>
            <applicationPool percentCpuLimit=”90percentCpuLimitMinActiveRequestPerCpu=”100>
        </system.web>
    </configuration>

    The default throttling limit was also lowered from 99% to 90% in order to detect high pressure and avoid negative scaling earlier.

    Just Asp.net Identity Core


    Before You dive further please go through these blogpost for more clarity and brevity.






    1. No Entity Framework.
    2. No Asp.net database tables
    3. Use existing Database user table for authentication.
    Have extended and used following Interface and class
    1. IUser
    2. IUserStore
    3. UserManager

    In order to refer our own table we have extended the method FindSync of UserManager.


    public class CustomUserManager:UserManager<ApplicationUser>

    {


    public CustomUserManager() : base(new CustomUserSore<ApplicationUser>())

    {


    //We can retrieve Old System Hash Password and can encypt or decrypt old password using custom approach.


    this.PasswordHasher = new OldSystemPasswordHasher();

    }




    public override System.Threading.Tasks.Task<ApplicationUser> FindAsync(string userName, string password)

    {


    Task<ApplicationUser> taskInvoke = Task<ApplicationUser>.Factory.StartNew(() =>

    {


    //First Verify Password...


    PasswordVerificationResult result = this.PasswordHasher.VerifyHashedPassword(userName, password);


    if (result == PasswordVerificationResult.SuccessRehashNeeded)

    {


    //Return User Profile Object...


    //So this data object will come from DB via Nhiberanate


    ApplicationUser applicationUser = new ApplicationUser();

    applicationUser.UserName =
    "san";


    return applicationUser;

    }


    return null;

    });


    return taskInvoke;

    }

    }

    For Source code
    http://code.msdn.microsoft.com/Simple-Aspnet-Identiy-Core-7475a961


     

    Tuesday, December 3, 2013

    Javascript Identity Operator vs Equality Operator

     

    Equality and inequality tests

    ==, !=
    It checks and compare values of the variable.
     

    Example

    var firstVal = 5;//Number

    var secondVal = "5";//String

    if (firstVal == secondVal) {

    console.log("They are the equal");

    } else {

    console.log("They are NOT the equal");

    }

    Output:They are the equal
     ONlY Values are compared.

     

    Identity and nonidentity tests

    ===, !== It checks and compare values and types of the variable.

    Example

    var firstVal = 5; //Number

    var secondVal = "5"; //String

    if (firstVal === secondVal) {

    console.log("They are the same");

    } else {

    console.log("They are NOT the same");

    }

    Output : They are  NOT the same.

    Values and Types are compared.