Tuesday, January 10, 2023

Deploy custom policies and got "the policy being uploaded not xml"

 

Please add ContentType "application/xml; charset=utf-8" to your Invoke-Resetmethod

$response = Invoke-RestMethod -Uri $graphapiuri -Method Put -Body $policycontent -Headers $headers -ContentType "application/xml; charset=utf-8"

Friday, March 23, 2018

Handle with JSON Dates in ASP.NET or ASP.NET MVC

Problem:
When we got date in the below format from the server when we are doing async call to get the data and it would be hard to read and format it again.
 "/Date(1521707071869)/"

Solution:
function toDate(dt) {
        var milisegundos = parseInt(dt.replace(/\/Date\((.*?)\)\//gi, "$1"));
        var newDate = new Date(milisegundos);

//return newDate.toLocaleString("en-US"), {weekday: "long", year: "numeric", month: "short",
//    day: "numeric", hour: "2-digit", minute: "2-digit"};
//Or
        return newDate.toLocaleDateString("en-US") + " " + newDate.toLocaleTimeString("en-US", { "second": "2-digit", "minute": "2-digit", "hour": "2-digit" });
    }

Thursday, November 2, 2017

Read Promoted properties in Orchestration from XmlDocument Message


When the PropertySchemaBase property is set to MessageDataPropertyBase, it means that the value of the promoted property corresponds to data in the message, such as the value of some field. When the PropertySchemaBase attribute is set to MessageContextPropertyBase, it means that the value of the promoted property may be from somewhere else, such as an envelope, or that it may be set by a pipeline component.


So, change the PropertySchemaBase property to MessageDataPropertyBase for all Promoted fields in Property schema.

We can bale to read the promoted property value by assigning the untyped document (XmlDocument) to XLANGMessage.

Declare the varXlangMessage is an orchestration variable of type Microsoft.XLANGs.BaseTypes.XLANGMessage. Use below code to read the property value.

varXlangMessage= msgXmlDocument;
varValue = System.Convert.ToString(varXlangMessage.GetPropertyValue(typeof({YourPropertySchema}.{PromtedProperty})));

Subscribe for Routing failure on Delivery Notifications (NACK messages)

I could not found exact solution for this, i followed below work-around, but it won’t solve all of the problems and side effects. The idea is to create an orchestration which subscribes to all NACK acknowledgments. That is to say:
·         The message type of the incoming message will be XmlDocument
·         The BTS.AckType property == NACK
·         The logical receive port will use direct binding
By doing so, all acknowledgments will be consumed by an instance of this orchestration, thus avoiding the routing failure. 



Friday, July 7, 2017

New Features in C# 7

Deconstructors
    Usually Constructor would do is, it will create a new object of given type with given parameters. So what the Deconstructor would do is, it will deconstruct the object back into it’s original parts. To be specific, we have the control of specifying how would you like the object to be deconstructed.

The method must be named Deconstruct and have a return type of void. The parameters to be assigned all must be out parameters, and because they are out parameters with a return type of void, C# allows the Deconstruct method to be overloaded just based on these parameters.


public class Employee
{
    public string FirstName { get; }
    public string LastName { get; }

    public Employee(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = LastName;
    }
}

We'll see how we can add a Deconstructor to Employee.

public class Employee
{
    public string FirstName { get; }
    public string LastName { get; }

    public Employee(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = LastName;
    }

    public void Deconstruct(out string firstName, out string lastName)
    {
        firstName = FirstName;
        lastName = LastName;
    }
}

We'll see how to call the Deconstruct.

Employee employee = new Employee("AAA", "BBB");

1.  // Example 1: Deconstructing declaration and assignment.
    (string firstName , string lastName) = employee;

2.  // Example 2: Deconstructing assignment.
     string firstName , lastName = null;
    (firstName , lastName) = employee;

3.  // Example 3: Deconstructing declaration and assignment with var.
  var (firstName, lastName) = employee;

The following example shows a Employeeclass with a deconstructor that returns the FirstName and LastName properties:
public class Employee
{
    public string FirstName { get; }
    public string LastName { get; }
    public int Age { get; set; }
    public string Email { get; set; }

    public Employee(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = LastName;
    }
    public void Deconstruct(out string firstName, out string lastName)
    {
        firstName = FirstName;
        lastName = LastName;
    }
}

var emp= new Employee
{
    FirstName = "FN",
    LastName = "LN",
    Email = "test@example.com",
    Age = 99
};

(var firstName, var lastName) = user;

We are creating a Employee object, and then deconstructing it into the firstName and lastName variables, which are declared as part of the deconstruction.

    Here we can notice C# is allowing simultaneous assignment to multiple variables of different values. This is not the same as the null assigning declaration in which all variables are initialized to the same value (null):
     string firstName , lastName = null;


The C# 7.0 tuple-like syntax requires that at least two variables appear within the parentheses. For example, (FileInfo path) = pathInfo; is not allowed even if a deconstructor exists for:

public void Deconstruct(out FileInfo file)

With the new tuple-like syntax, each variable is assigned a different value corresponding not to its name, but to the order in which it appears in the declaration and the deconstruct statement.

In other words, we can’t use the C# 7.0 deconstructor syntax for Deconstruct methods with only one out parameter.

Deconstruct() has the ability to split a tuple’s values up and put them into variables. In the above expamples, we can see how you take a tuple with a string and int and deconstruct them into variables.

Deconstruct also does not need to be directly attached to the class. C# allows the method to be implemented as an extension method as well.

public class AbstractClassA
{
  public string UserID{ get; }
   public string IPAddress{ get; }
}
static class AbstractExtensions
{
  public static void Deconstruct
    (this AbstractClassA obj, out string userID, out string ipAddress)
  {
    userID= obj.UserID
    ipAddress= obj.IPAddress;
  }
 
}

class Request : AbstractClassA
{
 public FirstAndLastNameNoDeconstructor(string userID, string ipAddress)
 {
   UserID = userID
   IPAddress = ipAddress;
 }
}

Request obj = new Request ("A001", "127.0.0.1")
var(userID, ipAddress) = obj;


Pattern Matching with the Switch Statement
C# 7.0 allows user to use pattern in IS statement and with SWITCH statement, so we can match pattern with any datatype, patterns can be constant patterns, Type patterns, Var patterns. following sample snippet will clear your concepts, let's start with IS pattern


public void PrintStars(object o)
{
    if (o is null) return;     // constant pattern "null"
    if (!(o is int i)) return; // type pattern "int i"
OR
  if (o is int i || (o is string s && int.TryParse(s, out i))

    WriteLine(new string('*', i));
}

Switch statements with patterns
    1. Patterns can be used in case clauses
    2. Case clauses can have additional conditions on them

switch(shape)
{
    case Circle c:
        WriteLine($"circle with radius {c.Radius}");
        break;
    case Rectangle s when (s.Length == s.Height):
        WriteLine($"{s.Length} x {s.Height} square");
        break;
    case Rectangle r:
        WriteLine($"{r.Length} x {r.Height} rectangle");
        break;
    default:
        WriteLine("<unknown shape>");
        break;
    case null:
        throw new ArgumentNullException(nameof(shape));
}

Local Functions
    Local methods and functions is already there in current version of C# (Yes, we can achieve them using Deleage, Func and Action types), but still there are some limitations to local method, we can not have following features in it
    1. Generic
    2. out parameters
    3. Ref
    4. params
Example:
bool IsPalindrome(string text)
{
  if (string.IsNullOrWhiteSpace(text)) return false;
  bool LocalIsPalindrome(string target)
  {
    target = target.Trim();  // Start by removing any surrounding whitespace.
    if (target.Length <= 1) return true;
    else
    {
      return char.ToLower(target[0]) ==
        char.ToLower(target[target.Length - 1]) &&
        LocalIsPalindrome(
          target.Substring(1, target.Length - 2));
    }
  }
  return LocalIsPalindrome(text);
}

Return by Reference
Since C# 1.0 it has been possible to pass arguments into a function by reference (ref). The result is that any change to the parameter itself will get passed back to the caller.

In C# 7, we can also use ‘ref’ for returning a variable from a method i.e. a method can return variable with reference. We can also store a local variable with reference.

public ref int GetFirstOddNumber(int[] numbers) {
    for (int i = 0; i < numbers.Length; i++) {
        if (numbers[i] % 2 == 1) {
            return ref numbers[i];
        }
    }
    throw new Exception("odd number not found");
}

int[] x = { 2, 4, 62, 54, 33, 55, 66, 71, 92 };
ref int oddNum = ref GetFirstOddNumber(x);
Console.WriteLine($"\t\t\t\t\t{oddNum}");

oddNum = 35;

for(int i=0; i < x.length; i++)
{
    Console.WriteLine($"{x[i]}\t");
}

Th output:
                               33
2     4     62     54    35     55     66     71     92


The GetFirstOddNumber(), retruns 33 value and it's holding by oddNum and after we have value, we modified the value and it is reflecting to the main collection.

 When declaring a reference local variable, initialization is required. This involves assigning it a ref return from a function or a reference to a variable:

     ref string text;  // Error

We can’t declare a by reference type for an auto-implemented property:
     class Thing { ref string Text { get;set; }  /* Error */ }

Properties that return a reference are allowed:
     class Thing { string _Text = "Inigo Montoya";
          ref string Text { get { return ref _Text; } } }

A reference local variable can’t be initialized with a value (such as null or a constant). It must be assigned from a by reference returning member or a local variable/field:
     ref int number = null; ref int number = 42;  // ERROR


Out Variables
If you had to pass a variable as out parameter, then the variable must had been declared before passing it to the method. But in C# 7, you can declare variable directly when you are passing it inside a method.



Throw Expressions

In C# 7, we can throw an exception directly through expression. Thus, an exception can be thrown from an expression.
static void Main(string[] args)
{
var a = Divide(10,0);
}
public static double Divide(int x, int y)
{
return y!=0? x %y : throw new DivideByZeroException();
}

Record Type
C# support record type, which is nothing but a container of a properties and variables, most of the time classes are full with properties and variables, we need lot of code to just declare them but with the help of Record Type you can reduce your effort, see below snippet

class studentInfo
{
    string _strFName;
    string _strMName;
    string _strLName;
    studentInfo(string strFN, string strMN, string strLN){
        this._strFName = strFN;
        this._strMName = strMN;
        this._strLName = strLN;
    }
    public string StudentFName {get{ return this._strFName;}}
    public string StudentMName {get{ return this._strMName;}}
    public string StudentLName {get{ return this._strLName;}}
}
In above code we have a class with property, constructor and variable, so access and declare variable i need to write more code.

To avoid it i can use  Record Type in C#, see below snippet


class studentInfo(string StudentFName, string StudentMName, string StudentLName);

That's it and we have Done !


Non-'NULL' able reference type
Null reference is really a headache for all programmers, it is a million dollar exception. If you don't check them you got runtime exception or if you check them for each object then your code goes long and long, To deal with this problem C# 7.0 come with non-nullable reference types

**I think syntax for it yet not fixed still they have release following syntax

'?' is for nullable value-type and '!' is for non-nullable reference type

Hide   Copy Code
int objNullVal;     //non-nullable value type
int? objNotNullVal;    //nullable value type
string! objNotNullRef; //non-nullable reference type
string objNullRef;  //nullable reference type
Now look at the following complier effect after we run this snippet

Hide   Copy Code
MyClass objNullRef;  // Nullable reference type
MyClass! objNotNullRef; // Non-nullable reference type

objNullRef = null;   // this is nullable, so no problem in assigning
objNotNullRef = null;   // Error, as objNotNullRef is non-nullable
objNotNullRef = objNullRef;      // Error, as nullable object can not be refered

WriteLine(objNotNullRef.ToString()); // Not null so can convert to tostring
WriteLine(objNullRef.ToString()); // could be null

if (objNullRef != null) { WriteLine(objNullRef.ToString); } // No error as we have already checked it
WriteLine(objNullRef!.Length); // No error

More Expression-Bodied Members

C# 6.0 introduced expression-bodied members for functions and properties, enabling a streamlined syntax for implementing trivial methods and properties. In C# 7.0, expression-bodied implementations are added to constructors, accessors (get and set property implementations) and even finalizers (see Figure 11).

Figure 11 Using Expression-Bodied Members in Accessors and Constructors
class TemporaryFile  // Full IDisposible implementation
                     // left off for elucidation.
{
  public TemporaryFile(string fileName) =>
    File = new FileInfo(fileName);
  ~TemporaryFile() => Dispose();
  Fileinfo _File;
  public FileInfo File
  {
    get => _File;
    private set => _File = value;
  }
  void Dispose() => File?.Delete();
}

Friday, July 8, 2016

"Keyset does not exist" error message when you try to change the identity of an application pool by using Internet Information Services


When I try to change the identity of any application pool, received the following error message:

---------------------------
Application Pools
---------------------------
There was an error while performing this operation.

Details:

Keyset does not exist (Exception from HRESULT: 0x80090016)


Reason : 
         There is not enough permissions to open file

  • %ALLUSERSPROFILE%\Microsoft\Crypto\RSA\MachineKeys\ 6de9cb26d2b98c01ec4e9e8b34824aa2_*
  • %ALLUSERSPROFILE%\Microsoft\Crypto\RSA\MachineKeys\ 76944fb33636aeddb9590521c2e8815a_*


Resolution

  1.     Go to '%ALLUSERSPROFILE%\Microsoft\Crypto\RSA\MachineKeys'
  2.     Find files with name starts as 6de9cb26d2b98c01ec4e9e8b34824aa2_ and                            76944fb33636aeddb9590521c2e8815a_.
  3.    Check permission for this file. Default permissions are:
    •        System, Administrators,TrustedInstaller - Full permissions
    •       IIS_IUSR,WMSVC - Read permissions
    •       LOCAL SERVICE - Read permission

If the issue still persists:

Take backup of MachineKeys (%ALLUSERSPROFILE%\Microsoft\Crypto\RSA\MachineKeys)
Give full permissions to your account to access the MachineKeys folder.

  Please check that files have name 6de9cb26d2b98c01ec4e9e8b34824aa2_GUID and 76944fb33636aeddb9590521c2e8815a_GUID .

If not, just copy existing files started with name 6de9cb26d2b98c01ec4e9e8b34824aa2_ and 76944fb33636aeddb9590521c2e8815a_ and then set GUID part in the file name equals to GUID obtained from MachineGuid registry key from HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryprography\





Wednesday, June 1, 2016

C# 6.0 New Features

Using Static Statement
We all know that you can import a namespace with using.  This gives us the ability to use a type with just the type’s name in our code. 
using System;

public class Driver
{
    public static void Main()
    {
         // without importing a namespace, we'd have to fully qualify the type
        // Console as System.Console
       //System.Console.WriteLine("Hello, World!");

        Console.WriteLine("Hello, World!");
    }
}

In C#6.0, import the static members of a class into our namespace , making them available without qualification in subsequent code:
using static System.Console;
 
public class Driver
{
    public static void Main()
    {
        // Now, the System.Console static class is imported, so we
        // can use WriteLine directly
        WriteLine("Hello, World!");
    }
}
 
void Main()
{
    MyStaticClass.Print("this string");      //Print is a static member in MyStaticClass
    // or...
    Print("this string");
}
 
Importing static types and accessing extension methods of them like the code above will give you an error. The following code will generate the "The name 'IsPolygon' does not exist in the current context".
Non-extension static methods are invoked as though they are methods on the current type, whereas extension methods are invoked only as though they are methods on a variable.
Read only Property and initialization
Public string Name {get;} = “XXXXX”;       or            public string Name => “XXXX”;
Expression-Bodied Get-Only Properties
Now, if you have a property that is get-only, you can write the body of the property using the expression syntax.  That is, you can use the lambda-expression syntax to write the body of the property. 
That is, instead of writing the { get { return your expression; } } syntax, we can simply write => your expression;
For example, if we convert our get-only properties above, we can get:
   1: public class Rectangle
   2: {
   3:     public int Length { get; set; }
   4:     public int Width { get; set; }
   5:  
   6:     // much more concise! Read Only properties
   7:     public int Area => Length * Width;
   8:     public int Perimeter => 2 * (Length + Width);
   9:  
  10:     public override string ToString()
  11:     {
  12:         return $"Rectange: Length={Length}, Width={Width}";
  13:     }
  14: }
It does not create a delegate, it is simply borrowing the lambda expression syntax to simplify writing simple bodies that result in an expression.
After lambda express we always have single statement.
Expression-bodied function members can work for both methods and properties. If you have a method with one statement, and that statement can be represented as an expression:
public string GetFullName() {
  return FirstName + " " + LastName;
}
Or a getter-only properties/indexers with a body that can be represented as an expression:
public string FormalName {
  get { return FirstName[0] + ". " + LastName; }
}
Public object TestObj {get {return obj;}}                //Read only property
You can collapse those down into something that looks like a cross between a member declaration and a lambda expression:
public string GetFullName() => FirstName + " " + LastName;
public string FormalName => FirstName[0] + ". " + LastName;
public object TestObj => obj;      //Read only property in C#6.0
Null Propagation Operator
In earlier versions of the C# language, we always had to write an if condition for a null check before using an object or its property. Now C# 6.0 has introduced the Null-Propagation Operator (?.) that enables developers to check for the null value within an object reference chain. The null-propagation operator (?.) will return null if anything in the object reference chain is null.

Example 1
In earlier versions of the C# language, you always had to check for nulls explicitly before using an object or its property, as shown below:
Hide   Copy Code
if (Employee.Name == null
    Console.WriteLine("No Employee name provided"); 
}
The same can be converted into a one-liner using the Conditional Access Operator in C# 6.
Hide   Copy Code
Console.WriteLine(Employee?.Name ?? "No Employee name provided");
Example 2
Suppose we have a class called Student that has another property studentdetails of type Details class. Now we can have the following code snippet to print theAddress .
Hide   Copy Code
if (student != null && student.studentdetails != null
    Console.WriteLine(student.studentdetails.Address); 
else 
    Console.WriteLine("No Address"); 
}
As we can see, to avoid the null-reference exception, we have checked the null for student andstudent.studentdetails since they can have a null reference as object. So, the preceding code snippet can be re-written using the null propagation operator (?.) as follows:
Hide   Copy Code
Console.WriteLine(student?.studentdetails?.Address ?? "No Address");
Both code snippets will provide us the address of the student.

What I think is, it's a really nice feature because instead of checking each and individual objects, using the nullpropagation operator (?.) we can check the entire chain of references together and whenever there is a nullvalue in the entire chain of reference, it will return null.

nameof Operator
nameof operator allows you to retrieve the name of a variable, type or member.
Use the nameof operator to avoid the use of hard-coded strings in our code.
This operator will help us get rid of “magic strings” in our code. We all know following use case:
public void Method(int arg)
{
    if (arg < 0)
    {
        throw new ArgumentOutOfRangeException("arg");
    }
}
With nameof operator we can rewrite code in a nicer way:
public void Method(int arg)
{
    if (arg < 0)
    {
        throw new ArgumentOutOfRangeException(nameof(arg));
    }
}
That is! nameof just returns a string representation of variable\method\type\propery\field.

String Interpolation
This feature inserts values into a string with simple syntax. It is similar to string.Format, but variables may be accessed directly
            string name = "Valentino";
            int age = 7;

            var data1 = string.Format("name:{0}, age:{1}", name, age);
            Console.WriteLine("classic string format - {0}", data1);

            var data2 = $"name:{name}, age:{age}";
            Console.WriteLine("string interpolation  - {0}", data2);
            Console.ReadLine();

Exception Filters
It allows us to specify conditions along with a catch block. The catch block is only executed if the condition satisfies. 
public void Main()
{
  try
  {  
      throw new Exception("E2");
  }
  catch(Exception ex) when(ex.Message == "E1")
  {
    Console.WriteLine("caught E1");
  }
  catch(Exception ex) when(ex.Message == "E2")
  {
    Console.WriteLine("caught E2");
  }
}

Setting default values to Auto Properties
Now we can assign default value to the properties without writing a second line.  Just place an “=” equal sign at the end and write the default value to it.
Earlier we used to have to do this by setting the default value in the constructor
public string FirstName { get; set; } = "Default Value";