Wednesday, November 6, 2024
Azure pipelines: error MSB4019 WebApplication.targets was not found
You can use a MSBUILD task and switch from Version
- task: VSBuild@1
inputs:
solution: $(Build.SourcesDirectory)$(appSourceUri)
platform: 'AnyCPU'
configuration: $(buildConfiguration)
vsVersion: '17.0'
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" });
}
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.
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();
}
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
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
- Go to '%ALLUSERSPROFILE%\Microsoft\Crypto\RSA\MachineKeys'
- Find files with name starts as 6de9cb26d2b98c01ec4e9e8b34824aa2_ and 76944fb33636aeddb9590521c2e8815a_.
- 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
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";
Wednesday, February 24, 2016
Get value when selected an item from datalist
The datalist element and the list attribute are the two new HTML features that bind up the autocomplete functionality.
I have used above features to implement autocomplete functionality in my sample.
My requirement is to select a cityName from the datalist and want to get cityId from cityList
<input list="fromCityList" required type="text" name="fromCity" placeholder="City" ng-model="Trip.from.city" ng-change="Trip.from.id = (cityList|filter:{name:Trip.from.city})[0].id">
<datalist id="fromCityList" >
<select>
<option ng-repeat="city in cityList | filter : {name : Trip.from.city}"
value="{{city.name}}" ></option>
</select>
</datalist>
I have ued the built-in filter to retrieve the correct cityId value for the cityName.
I have used above features to implement autocomplete functionality in my sample.
My requirement is to select a cityName from the datalist and want to get cityId from cityList
<input list="fromCityList" required type="text" name="fromCity" placeholder="City" ng-model="Trip.from.city" ng-change="Trip.from.id = (cityList|filter:{name:Trip.from.city})[0].id">
<datalist id="fromCityList" >
<select>
<option ng-repeat="city in cityList | filter : {name : Trip.from.city}"
value="{{city.name}}" ></option>
</select>
</datalist>
I have ued the built-in filter to retrieve the correct cityId value for the cityName.
Monday, January 11, 2016
Why BizTalk not supporting multiple send locations for one send port?
We can have multiple disassemblers in Receive Pipeline, we can receive multiple format files from the same receive pipeline. It execute all the components (0 to 255)placed in it.
But we cannot have multiple assemblers in Send Pipeline (it can have only 0 to 1). So, we can't use to send multiple format files through the same Send pipeline.
What if we want to send multiple format files through the same Send pipeline ?
We can create a Send port for each format and add them to a Send Port Group
Even I too have this below question in my mind, any idea!
Why BizTalk doesn't provide this feature, BizTalk server is not supporting more than one send location for one send port?
But we cannot have multiple assemblers in Send Pipeline (it can have only 0 to 1). So, we can't use to send multiple format files through the same Send pipeline.
What if we want to send multiple format files through the same Send pipeline ?
We can create a Send port for each format and add them to a Send Port Group
Even I too have this below question in my mind, any idea!
Why BizTalk doesn't provide this feature, BizTalk server is not supporting more than one send location for one send port?
Wednesday, January 6, 2016
Identity (===. !==) vs Equality (==, !=) operators in JavaScript
These operators behave identically to the equality operators except no type conversion is done, and the types must be the same to be considered equal.
Using the == operator (Equality)
true == 1; //true, because 'true' is converted to 1 and then compared
"2" == 2; //true, because "2" is converted to 2 and then compared
Using the === operator (Identity)
true === 1; //false
"2" === 2; //false
This is because the equality operator == does type coercion, meaning that the interpreter implicitly tries to convert the values before comparing.
On the other hand, the identity operator === does not do type coercion, and thus does not convert the values when comparing.
Saturday, November 14, 2015
An error occurred while parsing EntityName in asp.net
In my AppSettings in web.config, I have something like this:
<appSettings>
<add key="ExternalUrl" value="http://domain.com/samplepage.aspx?id={0}&action=xx" />
</appSettings>
However, it seems that when an ampersand (&) is included in an AppSettings value, ASP.NET throws the following error:
An error occurred while parsing EntityName.
Solution:
Replace & with &
<add
key="ExternalUrl"
value="http://domain.com/samplepage.aspx?id={0}&action=xx" />
<appSettings>
<add key="ExternalUrl" value="http://domain.com/samplepage.aspx?id={0}&action=xx" />
</appSettings>
However, it seems that when an ampersand (&) is included in an AppSettings value, ASP.NET throws the following error:
An error occurred while parsing EntityName.
Solution:
Replace & with &
<add
key="ExternalUrl"
value="http://domain.com/samplepage.aspx?id={0}&action=xx" />
Wednesday, August 5, 2015
What is new in BizTalk 2013
BizTalk 2013 includes many new features that make developing and deploying for BizTalk much more efficient. There are also many new features which expand on the already huge capabilities of a BizTalk Solution.
New Adapters
It has set of new adapters which allow for connectivity to other applications and protocols, such as Windows Azure and RESTful services.
- SB-Messaging Adapter: The SB-Messaging adapter allows BizTalk to send and receive messages form the Queues, Topics and Relays of a Service Bus such as Windows Azure.
- WCF-BasicHttpRelay Adapter: Allows BizTalk to communicate with an ASMX Web services using the WCF protocol.
- NetTcpRelay Adapater: Send and receive WCF calls using the secure NetTcpRelayBinding.
- WCF-WebHttp Adapter: The WCF-WebHttp adapter allows BizTalk to send and receive, or expose BizTalk artifacts using REST.
- SharePoint Services Adapter: Sends and Receives messages to SharePoint Services
- SFTP Adapter: Enables Biztalk to securely send and receive messages to FTP servers using SSH.
WCF-WebHttp, SFTP, SB-Messaging, WCF-BasicHttpRelay and the WCF-NetTcpRelay adapters allow for easy communication with Azure.
Configurable Dynamic Send Port
In BizTalk Server 2010 and previous versions, dynamic send ports used the default host instance, without the ability to change the host instance handler used by the dynamic send port.
Scenario
There are two ESB itineraries in an application. Itinerary1 uses a Dynamic Send Port to send data to a File share. Itinerary2 uses a Dynamic Send Port to send e-mail. In the past, Dynamic send ports execute in the adapter's default host. Itinerary1 is designed to target a low volume - big message size scenario. Itinerary2 targets a high volume - small message size scenario. Since there is only one default host for an adapter, all messages are routed using the same host, decreasing the performance.
The Change
To improve the performance of Dynamic Send Ports, an adapter Send Handler is configurable to use any host. In the ESB scenario, Itinerary1 uses HostA to send data to a File share. Itinerary2 uses HostB Port to send e-mail.
With BizTalk Server 2013, a new feature will be added allowing a send handler to be assigned for each dynamic send port, bringing it in line with the functionality of static send.
Viewing the Artifact Dependencies
A possible cause of frustration when dealing with larger BizTalk applications, or applications with a large number of artifacts, is determining what dependencies exists between artifacts. For example which ports an orchestration depends on, or which maps a port is using the transform messages.
With BizTalk 2013, a new feature has been added to easily show all of the dependencies between artifacts.
A BizTalk Server application may contain a bunch of artifacts such as send ports, receive locations, orchestrations, schemas, transforms, etc. Moreover, sometimes these artifacts can be shared between more than one BizTalk Server application. So, it becomes very difficult for BizTalk Server admins to come up with a “dependency tree” that provides information on both the aspects of dependencies, which are:
Pick an artifact in the BizTalk Server Administration console, for example, a receive location. Right-click the artifact, and select View Dependencies.
There’s a new Dependency Statistics pane at the bottom of the page that now lists the dependencies, categorizing it as Used by (which artifacts use this receive location) and Using (which artifacts are used by this receive location). This is how the pane looks like
- How a given artifact “uses” other artifacts.
- How a given artifact is “used by” other artifacts.
Pick an artifact in the BizTalk Server Administration console, for example, a receive location. Right-click the artifact, and select View Dependencies.
The Dependency Pane shows that the ReceiveOppNotification receive location is used by one Receive Port and receive location in uses two pipeline components. Notice that the numbers are links, so you can click those to see the dependent/dependent on artifacts. So, if I click on the number 1 above, the top pane will refresh to show the receive port that uses the ReceiveOppNotification receive location. Similarly, if I click on 2, the top pane refreshes to list the two pipelines that are used by the receive location.
This feature should really be helpful for BizTalk Server Admins in tracking what other artifacts might get affected if they update a schema, for example. All this while the admins had to manually document all these dependencies but with this enhancement, hopefully it should become much simpler for them.
ESB Toolkit included ‘Out of the Box’
In previous versions of BizTalk Server, the Microsoft BizTalk ESB Toolkit has been a separate installation and required its own configuration procedure that took a considerable effort in order to correctly install and configure. In BizTalk 2013, the ESB Toolkit installer is contained within the BizTalk 2013 installation media, and can be installed from the start menu. Most of the remaining configuration is the same as in the previous version, however some of the ESB Toolkit configuration steps have been streamlined.
Friday, July 17, 2015
AngularJS $resource save() works in Chrome but gives a 415 (Unsupported Media Type) in IE
I've a basic Post in angular using $resource
angularFormsAPP.factory('accountService', function ($resource) {
return {
save: function (student) {
return $resource('/api/Account').save(student);
}
}
});
then i have used like this
accountService.save(student).$promise.then(function (data) {
alert('Student saved..');
$location.url("Registrations/Courses");
}, function (error) {
alert('Save student failed-' + error);
});
When I use it in Chrome it works. In IE(11.0.9) however I got a 415 (Unsupported Media Type) error.
The Problem solved. I needed to modify the service call like below:
angularFormsAPP.factory('accountService', function ($resource) {
return {
save: function (student) {
return $resource('/api/Account').save(student, {
headers: { "Content-Type": "application/json" }
});
}
}
});
Or
angularFormsAPP.factory('accountService', function ($resource) {
return {
save: function (student) {
return $resource('/api/Account').save(student, {});
}
}
});
angularFormsAPP.factory('accountService', function ($resource) {
return {
save: function (student) {
return $resource('/api/Account').save(student);
}
}
});
then i have used like this
accountService.save(student).$promise.then(function (data) {
alert('Student saved..');
$location.url("Registrations/Courses");
}, function (error) {
alert('Save student failed-' + error);
});
When I use it in Chrome it works. In IE(11.0.9) however I got a 415 (Unsupported Media Type) error.
The Problem solved. I needed to modify the service call like below:
angularFormsAPP.factory('accountService', function ($resource) {
return {
save: function (student) {
return $resource('/api/Account').save(student, {
headers: { "Content-Type": "application/json" }
});
}
}
});
Or
angularFormsAPP.factory('accountService', function ($resource) {
return {
save: function (student) {
return $resource('/api/Account').save(student, {});
}
}
});
Thursday, June 11, 2015
Beginners for AngularJS
AngularJS is a JavaScript framework. It is a library written in JavaScript. AngularJS extends HTML attributes with Directives. AngularJS expressions can be written inside HTML
AngularJS Extends HTML
AngularJS extends HTML with ng-directives (AngularJS directives are HTML attributes with an ng prefix. ) AngularJS lets you extend HTML with new attributes called Directives.
- The ng-app directive defines the root element of an AngularJS application(defines an AngularJS application).
It tells AngularJS that the <div> element is the "owner" of an AngularJS application.
Technically possible to have several applications per page, only one ng-app directive will be automatically instantiated and initialized by the Angular framework. we need to bootstrap the modules to have multiple ng-app within the same page.
- The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
It binds the value of the input field to the application variable name.
The ng-model directive can also:
Provide type validation for application data (number, email, required).
Provide status for application data (invalid, dirty, touched, error).
Provide CSS classes for HTML elements.
Bind HTML elements to HTML forms.
Provide status for application data (invalid, dirty, touched, error).
Provide CSS classes for HTML elements.
Bind HTML elements to HTML forms.
- The ng-bind directive binds application data to the HTML view.
It binds the innerHTML of the <p> element to the application variable name.
- The ng-init directive initialize AngularJS application variables. It initializes application data and defines initial values for an AngularJS application. Normally, we'll not use ng-init. We'll use a controller or module instead.
- The ng-controller directive defines the application controller.
AngularJS applications are controlled by controllers. It control the data of AngularJS applications.
A controller is a JavaScript Object, created by a standard JavaScript object constructor.
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
In the above example, ng-app="myApp" creates AngularJs application and the application runs inside the <div>. The ng-controller="myCtrl" defines a controller and myCtrl function is a JavaScript function. It invoke the controller with a $scope object. $scope is the application object. The controller creates two properties (variables) in the scope (firstName and lastName). The ng-model directives bind the input fields to the controller properties (firstName and lastName).
It is common to store controllers in external files:
<script src="{YourControllerFileName}.js"></script>
Controller Methods
The example above demonstrated a controller object with two properties: lastName and firstName.
A controller can also have methods (variables as functions):
<div ng-app="myApp" ng-controller="personCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
}
});
</script>
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
}
});
</script>
- The ng-repeat directive clones HTML elements once for each item in a collection (in an array).
Example:
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="" ng-init="firstName='John'">
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
OR
<p>{{name}}</p>
<p>The name is <span ng-bind="firstName"></span></p>
OR
<p>The name is {{firstName}}</p>
</div>
</body>
</html>
AngularJS modules define applications:
var app = angular.module('myApp', []);
AngularJS controllers control applications:
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
AngularJS expressions are written inside double braces: {{ expression }}.
AngularJS expressions binds data to HTML the same way as the ng-bind directive.
Example:
<p>The name is <span ng-bind="firstName"></span></p>
OR
<p>The name is {{firstName}}</p>
If we remove the ng-app directive, HTML will display the expression as it is, without solving it.
we can bind data to HTML in two ways:
<div ng-app="" ng-init="firstName='John';lastName='Doe'">
<p>The name is {{ firstName + " " + lastName }}</p>
</div>
OR
<div ng-app="" ng-init="firstName='John';lastName='Doe'">
<p>The name is <span ng-bind="firstName + ' ' + lastName"></span></p>
</div>
AngularJS Objects
AngularJS objects are like JavaScript objects:
<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
<p>The name is {{ person.lastName }}</p>
</div>
<p>The name is {{ person.lastName }}</p>
</div>
AngularJS Arrays
AngularJS arrays are like JavaScript arrays:<div ng-app="" ng-init="points=[1,15,19,2,40]">
<p>The third result is {{ points[2] }}</p>
</div>
In the above example, the {{ firstName }} expression is an AngularJS data binding expression.
{{ firstName }} is synchronized with ng-model="firstName", binds the value of the firstName input field to the application firstName variable name.
In the below example two text fields are synchronized with two ng-model directives:
<div ng-app="" ng-init="quantity=1;price=5">
Quantity: <input type="number" ng-model="quantity">
Costs: <input type="number" ng-model="price">
Total in dollar: {{ quantity * price }}
</div>
The ng-repeat directive repeats an HTML element and it used on an array of objects.
<div ng-app="" ng-init="names=[
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]">
<ul>
<li ng-repeat="x in names">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
AngularJS Filters
Filters can be added to expressions and directives using a pipe character.
AngularJS filters can be used to transform data. A filter can be added to an expression with a pipe character (|).
Filter in expression
The uppercase filter format strings to upper case:
<div ng-app="myApp" ng-init="lastName ='John'">
<p>The name is {{ lastName | uppercase }}</p>
</div>
<p>The name is {{ lastName | uppercase }}</p>
</div>
<div ng-app="myApp" ng-init="lastName ='John'">
<p>The name is {{ lastName | lowercase }}</p>
</div>
The currency filter formats a number as currency:
<div ng-app="myApp" ng-controller="costCtrl">
<input type="number" ng-model="quantity">
<input type="number" ng-model="price">
<p>Total = {{ (quantity * price) | currency }}</p>
</div>
Filter in directives
A filter can be added to a directive with a pipe character (|).
The orderBy filter orders an array by an expression:
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names | orderBy:'country'">
{{ x.name + ', ' + x.country }}
</li>
</ul>
<div>
The filter filter selects a subset of an array:
<div ng-app="myApp" ng-controller="namesCtrl">
<p><input type="text" ng-model="test"></p>
<ul>
<li ng-repeat="x in names | filter:test | orderBy:'country'">
{{ (x.name | uppercase) + ', ' + x.country }}
</li>
</ul>
</div>
AngularJS AJAX - $http
AngularJS $http is a core service for reading data from web servers.
$http.get(url) is the function to use for reading server data.
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in names">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function(response) {$scope.names = response.records;});
});
</script>
<ul>
<li ng-repeat="x in names">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function(response) {$scope.names = response.records;});
});
</script>
In the above example, $http is an XMLHttpRequest object for requesting external data.
$http.get() reads JSON data from http://www.w3schools.com/angular/customers.php. If success, the controller creates a property (names) in the scope, with JSON data from the server.
Display the Table Index ($index)
To display the table index, add a <td> with $index:
<table>
<tr ng-repeat="x in names">
<td>{{ $index + 1 }}</td>
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
<tr ng-repeat="x in names">
<td>{{ $index + 1 }}</td>
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
Using $even and $odd
To identify the even and odd rows in a table.
<table>
<tr ng-repeat="x in names">
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Name }}</td>
<td ng-if="$even">{{ x.Name }}</td>
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Country }}</td>
<td ng-if="$even">{{ x.Country }}</td>
</tr>
</table>
<tr ng-repeat="x in names">
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Name }}</td>
<td ng-if="$even">{{ x.Name }}</td>
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Country }}</td>
<td ng-if="$even">{{ x.Country }}</td>
</tr>
</table>
AngularJS HTML DOM
The ng-disabled directive binds AngularJS application data to the disabled attribute of HTML elements.
<div ng-app="myApp" ng-init="mySwitch=true">
<p>
<button ng-disabled="mySwitch">Click Me!</button><p>
</p>
<p>
<input type="checkbox" ng-model="mySwitch">Button
</p>
<input type="checkbox" ng-model="mySwitch">Button
</p>
<p>
{{ mySwitch }}
</p>
</div>
It binds the application data mySwitch to the HTML button's disabled attribute. The ng-model directive binds the value of the HTML checkbox element to the value of mySwitch.
If the value of mySwitch evaluates to true, the button will be disabled.
The ng-show directive shows or hides an HTML element. It shows (or hides) an HTML element based on the value of ng-show. It can also be used to set the visibility of a part of an application.
</p>
We can use any expression that evaluates to true or false:
<div ng-app="myApp" ng-init="hour=13">
<p ng-show="hour > 12">I am visible.</p>
</div>
The ng-hide directive hides or shows an HTML element. It can be used to set the visibility of a part of an application.
<div ng-app="myApp">
<p ng-hide="true">I am not visible.</p>
<p ng-hide="false">I am visible.</p>
</div>
<div ng-app="myApp" ng-controller="personCtrl">
<button ng-click="toggle()">Toggle</button>
<p ng-hide="myVar">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "John",
$scope.lastName = "Doe"
$scope.myVar = false;
$scope.toggle = function() {
$scope.myVar = !$scope.myVar;
};
});
</script>
The ng-if directive removes an HTML element. Instead of changing its visibility via the display css property, it completely removes element. When an element is removed using ng-If its scope is destroyed and a new scope is created when the element is restored.
If the value of mySwitch evaluates to true, the button will be disabled.
The ng-show directive shows or hides an HTML element. It shows (or hides) an HTML element based on the value of ng-show. It can also be used to set the visibility of a part of an application.
<div ng-app="myApp" ng-init="mySwitch=true">
<p>
<button ng-show="mySwitch">Click Me!</button><p>
</p>
<p>
<input type="checkbox" ng-model="mySwitch">Button
</p>
<input type="checkbox" ng-model="mySwitch">Button
</p>
<p>
{{ mySwitch }}
</p>
</div>
We can use any expression that evaluates to true or false:
<div ng-app="myApp" ng-init="hour=13">
<p ng-show="hour > 12">I am visible.</p>
</div>
The ng-hide directive hides or shows an HTML element. It can be used to set the visibility of a part of an application.
<div ng-app="myApp">
<p ng-hide="true">I am not visible.</p>
<p ng-hide="false">I am visible.</p>
</div>
<div ng-app="myApp" ng-controller="personCtrl">
<button ng-click="toggle()">Toggle</button>
<p ng-hide="myVar">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "John",
$scope.lastName = "Doe"
$scope.myVar = false;
$scope.toggle = function() {
$scope.myVar = !$scope.myVar;
};
});
</script>
The ng-if directive removes an HTML element. Instead of changing its visibility via the display css property, it completely removes element. When an element is removed using ng-If its scope is destroyed and a new scope is created when the element is restored.
<label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
Show when checked:
<span ng-if="checked" class="animate-if">
This is removed when the checkbox is unchecked.
</span>
By using ng-show/ng-hide, The element is shown or hidden by removing or adding the .ng-hide CSS class onto the element. The .ng-hide CSS class is predefined in AngularJS and sets the display style to none (using an !important flag).
Don't confuse with ng-if, ng-show/ng-hide, ng-if will remove elements from DOM. I.e anything else attached to those elements will be lost. For example, if we bound a click handler to one of child elements, when ng-if evaluates to false, that element will be removed from DOM and our click handler will not work any more, even after ng-if later evaluates to true and displays the element. You will need to reattach the handler.
ng-show/ng-hide does not remove the elements from DOM. It uses CSS styles to hide/show elements. This way our handlers that were attached to children will not be lost.
The ng-click directive defines an AngularJS click event.
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="count = count + 1">Click me!</button>
<p>{{ count }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
});
</script>
app.controller('MainCtrl', function() {
$scope.name = "Foo";
$scope.changeFoo = function() {
$scope.name = "Bar";
}
});
{{ name }}
<button ng-click="changeFoo()">Change the name</button>
Here we have only one $watch because ng-click doesn’t create any watches (the function is not going to change :P).
1. We press the button.
2. The browser receives an event which will enter the angular context (I will explain why, later in this article).
3. The $digest loop will run and will ask every $watch for changes.
4. Since the $watch which was watching for changes in $scope.name reports a change, if will force another $digest loop.
5. The new loop reports nothing.
6. The browser gets the control back and it will update the DOM reflecting the new value of $scope.name
The important thing here is that EVERY event that enters the angular context will run a $digest loop. That means that every time we write a letter in an input, the loop will run checking every $watch in this page.
Example -1:
When you will click on second button, the data binding is not updated. Since $scope.$digest() is not called after the second button's event listener is executed. In this way on clicking the second button the time will be updated in the $scope.data.time variable, but the new time will never displayed.
<script type="text/javascript">
document.getElementById("updateTimeButton").addEventListener('click', function () {
console.log("update time clicked");
$scope.datetime = new Date();
//to update $scope
$scope.$digest();
console.log($scope.datetime);
});</script>
To fix this issue you need to add a $scope.$digest() call to the second button event listener
Don't confuse with ng-if, ng-show/ng-hide, ng-if will remove elements from DOM. I.e anything else attached to those elements will be lost. For example, if we bound a click handler to one of child elements, when ng-if evaluates to false, that element will be removed from DOM and our click handler will not work any more, even after ng-if later evaluates to true and displays the element. You will need to reattach the handler.
ng-show/ng-hide does not remove the elements from DOM. It uses CSS styles to hide/show elements. This way our handlers that were attached to children will not be lost.
The ng-click directive defines an AngularJS click event.
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="count = count + 1">Click me!</button>
<p>{{ count }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
});
</script>
AngularJS Forms
An AngularJS form is a collection of input controls.
<html>
<body>
<div ng-app="myApp" ng-controller="formCtrl">
<form novalidate>
First Name:<br>
<input type="text" ng-model="user.firstName"><br>
Last Name:<br>
<input type="text" ng-model="user.lastName">
<br><br>
<button ng-click="reset()">RESET</button>
</form>
<p>form = {{user}}</p>
<p>master = {{master}}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
<form novalidate>
First Name:<br>
<input type="text" ng-model="user.firstName"><br>
Last Name:<br>
<input type="text" ng-model="user.lastName">
<br><br>
<button ng-click="reset()">RESET</button>
</form>
<p>form = {{user}}</p>
<p>master = {{master}}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
//Assign initial values to the master object
$scope.master = {firstName: "John", lastName: "Doe"};
$scope.master = {firstName: "John", lastName: "Doe"};
//Create reset().
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset(); //Calling reset(), to initialize the user data
});
</script>
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset(); //Calling reset(), to initialize the user data
});
</script>
</body>
</html>
In the above example, The ng-model directive binds two input elements to the user object in the model.
The formCtrl function sets initial values to the master object, and defines the reset() method. The reset() method sets the user object equal to the master object. The ng-click directive invokes the reset() method, only if the button is clicked The novalidate attribute is new in HTML5. It disables any default browser validation.
$rootScope
The $rootScope is the top-most scope. An app can have only one $rootScope which will be shared among all the components of an app. Hence it acts like a global variable. All other $scopes are children of the $rootScope.
<html>
<body ng-app="myApp">
<div ng-controller="Ctrl1" style="border:2px solid blue; padding:5px">
Hello {{msg}}!
<br />
Hello {{name}}!
(rootScope)
</div>
<br />
<div ng-controller="Ctrl2" style="border:2px solid green; padding:5px">
Hello {{msg}}!
<br />
Hey {{myName}}!
<br />
Hi {{name}}! (rootScope)
<br/>
<button ng-click="change()">Change root variable</button>
</div>
<br/>
<script src= "angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('Ctrl1', function ($scope, $rootScope) {
$scope.msg = 'World';
$rootScope.name = 'AngularJS';
});
app.controller('Ctrl2', function ($scope, $rootScope) {
$scope.msg = 'Dot Net Tricks';
$scope.myName = $rootScope.name;
$scope.change = function() {
$rootScope.name = "(root variable value modified)";
};
});
</script>
</body>
</html>
Angular Context
When the browser receives an event that can be managed by the angular context and the $digest loop will be fired.The $watch list
Every time we bind something in the UI angular insert a $watch in a $watch list. Imagine the $watch as something that is able to detect changes in the model it is watching
Exaple-1:
User: <input type="text" ng-model="user" />
Password: <input type="password" ng-model="pass" />
Here, we have $scope.user, which is bound to the first input, and we have $scope.pass, which is bound to the second one. Doing this we add two $watch to the $watch list.
Example-2:
app.controller('MainCtrl', function($scope) {
$scope.foo = "Foo";
$scope.world = "World";
});
Hello, {{ World }}
Here, even though we have two things attached to the $scope, only one is bound. So in this case we only created one $watch.
Example-3:
app.controller('MainCtrl', function($scope) {
$scope.people = [...];
});
<ul>
<li ng-repeat="person in people">
{{person.name}} - {{person.age}}
</li>
</ul>
How many $watch are created here? Two for each person (for name and age) in people plus one for the ng-repeat. If we have 10 people in the list it will be (2 * 10) + 1, I.e 21 $watch's.
Everything that is bound in our UI using directives creates a $watch.When our template is loaded, Also known as in the linking phase, the compiler will look for every directive and creates all the $watch that are needed.
we already know that every binding we set has its own $watch to update the DOM when is needed
The $scope.watch() function is used to observe changes in a variable on the $scope. It accepts three parameters : expression, listener and equality object
Example -4:
app.controller('MainCtrl', function($scope) {
$scope.name = "Angular";
$scope.updated = -1;
$scope.$watch('name', function() {
$scope.updated++;
});
});
<body ng-controller="MainCtrl">
<input ng-model="name" />
Name updated: {{updated}} times.
</body>
Here the first parameter can be a string or a function. In this case it is just a string with the name of what we want to $watch, in this case, $scope.name. The second parameter is what is going to happen when $watch says that our watched expression has changed. The first thing we have to know is that when the controller is executed and finds the $watch, it will immediately fire.
we have initialized the $scope.updated to -1, the $watch will run once when it is processed and it will put the $scope.updated to 0.
Example-5:
app.controller('MainCtrl', function($scope) {
$scope.name = "Angular";
$scope.updated = 0;
$scope.$watch('name', function(newValue, oldValue) {
if (newValue === oldValue) { return; } // AKA first run
$scope.updated++;
});
});
<body ng-controller="MainCtrl">
<input ng-model="name" />
Name updated: {{updated}} times.
</body>
The second parameter of $watch receives two parameters. The new value and the old value. We can use them to skip the first run that every $watch does. Normally you don’t need to skip the first run,
Example-6:
app.controller('MainCtrl', function($scope) {
$scope.user = { name: "Fox" };
$scope.updated = 0;
$scope.$watch('user', function(newValue, oldValue) {
if (newValue === oldValue) { return; }
$scope.updated++;
});
});
<body ng-controller="MainCtrl">
<input ng-model="user.name" />
Name updated: {{updated}} times.
</body>
We want to $watch any changes in our $scope.user object. Same as before but using an object instead of a primitive.
Here It doesn’t work. Because the $watch by default compares the reference of the objects. In example 4 and 5, every time we modify $scope.name it will create a new primitive, so the $watch will fire because the reference of the object is new and that is our change. In this new case, since we are watching $scope.user and then we are changing $scope.user.name, the reference of $scope.user is never changing because we are creating a new $scope.user.name every time we change the input, but the $scope.user will be always the same.
Example-7:
app.controller('MainCtrl', function($scope) {
$scope.user = { name: "Fox" };
$scope.updated = 0;
$scope.$watch('user', function(newValue, oldValue) {
if (newValue === oldValue) { return; }
$scope.updated++;
}, true);
});
<body ng-controller="MainCtrl">
<input ng-model="user.name" />
Name updated: {{updated}} times.
</body>
Now it'll work, we added a third parameter to the $watch which is a bool to indicate that we want to compare the value of the objects instead of the reference. And since the value of $scope.user is changing when we update the $scope.user.name the $watch will fire appropriately.
When the $digest loop finishes, the DOM makes the changes.
Example-4:
Exaple-1:
User: <input type="text" ng-model="user" />
Password: <input type="password" ng-model="pass" />
Here, we have $scope.user, which is bound to the first input, and we have $scope.pass, which is bound to the second one. Doing this we add two $watch to the $watch list.
Example-2:
app.controller('MainCtrl', function($scope) {
$scope.foo = "Foo";
$scope.world = "World";
});
Hello, {{ World }}
Here, even though we have two things attached to the $scope, only one is bound. So in this case we only created one $watch.
Example-3:
app.controller('MainCtrl', function($scope) {
$scope.people = [...];
});
<ul>
<li ng-repeat="person in people">
{{person.name}} - {{person.age}}
</li>
</ul>
How many $watch are created here? Two for each person (for name and age) in people plus one for the ng-repeat. If we have 10 people in the list it will be (2 * 10) + 1, I.e 21 $watch's.
Everything that is bound in our UI using directives creates a $watch.When our template is loaded, Also known as in the linking phase, the compiler will look for every directive and creates all the $watch that are needed.
we already know that every binding we set has its own $watch to update the DOM when is needed
The $scope.watch() function is used to observe changes in a variable on the $scope. It accepts three parameters : expression, listener and equality object
Example -4:
app.controller('MainCtrl', function($scope) {
$scope.name = "Angular";
$scope.updated = -1;
$scope.$watch('name', function() {
$scope.updated++;
});
});
<body ng-controller="MainCtrl">
<input ng-model="name" />
Name updated: {{updated}} times.
</body>
Here the first parameter can be a string or a function. In this case it is just a string with the name of what we want to $watch, in this case, $scope.name. The second parameter is what is going to happen when $watch says that our watched expression has changed. The first thing we have to know is that when the controller is executed and finds the $watch, it will immediately fire.
we have initialized the $scope.updated to -1, the $watch will run once when it is processed and it will put the $scope.updated to 0.
Example-5:
app.controller('MainCtrl', function($scope) {
$scope.name = "Angular";
$scope.updated = 0;
$scope.$watch('name', function(newValue, oldValue) {
if (newValue === oldValue) { return; } // AKA first run
$scope.updated++;
});
});
<body ng-controller="MainCtrl">
<input ng-model="name" />
Name updated: {{updated}} times.
</body>
The second parameter of $watch receives two parameters. The new value and the old value. We can use them to skip the first run that every $watch does. Normally you don’t need to skip the first run,
Example-6:
app.controller('MainCtrl', function($scope) {
$scope.user = { name: "Fox" };
$scope.updated = 0;
$scope.$watch('user', function(newValue, oldValue) {
if (newValue === oldValue) { return; }
$scope.updated++;
});
});
<body ng-controller="MainCtrl">
<input ng-model="user.name" />
Name updated: {{updated}} times.
</body>
We want to $watch any changes in our $scope.user object. Same as before but using an object instead of a primitive.
Here It doesn’t work. Because the $watch by default compares the reference of the objects. In example 4 and 5, every time we modify $scope.name it will create a new primitive, so the $watch will fire because the reference of the object is new and that is our change. In this new case, since we are watching $scope.user and then we are changing $scope.user.name, the reference of $scope.user is never changing because we are creating a new $scope.user.name every time we change the input, but the $scope.user will be always the same.
Example-7:
app.controller('MainCtrl', function($scope) {
$scope.user = { name: "Fox" };
$scope.updated = 0;
$scope.$watch('user', function(newValue, oldValue) {
if (newValue === oldValue) { return; }
$scope.updated++;
}, true);
});
<body ng-controller="MainCtrl">
<input ng-model="user.name" />
Name updated: {{updated}} times.
</body>
Now it'll work, we added a third parameter to the $watch which is a bool to indicate that we want to compare the value of the objects instead of the reference. And since the value of $scope.user is changing when we update the $scope.user.name the $watch will fire appropriately.
$digest loop
When the browser receives an event that can be managed by the angular context and the $digest loop will be fired.
This loop is made from two smaller loops. One processes the $evalAsync queue and the other one processes the $watch list,
The $scope.$digest() function iterates through all the watches in the $scope object, and its child $scope objects (if it has any - isolated scopes).
Hey $watch, what is your value? //Watch-1
It is 9
Alright, has it changed? ///Watch-1
No, sir.
(nothing happens with this one, so it moves to the next)
You, what is your value? //Watch-2
It is Foo.
Has it changed? //Watch-2
Yes, it was Bar.
(good, we have a DOM to be updated)
This continues until every $watch has been checked.
The above checking is called dirty-checking. Now that all the $watch have been checked there is something else to ask: Is there any $watch that has been updated? If there is at least one of them that has changed, the loop will fire again until all of the $watch report no changes. This is to ensure that every model is clean. Have in mind that if the loop runs more than 10 times, it will throw an exception to prevent infinite loops.
When the $digest loop finishes, the DOM makes the changes.
Example-4:
$scope.name = "Foo";
$scope.changeFoo = function() {
$scope.name = "Bar";
}
});
{{ name }}
<button ng-click="changeFoo()">Change the name</button>
Here we have only one $watch because ng-click doesn’t create any watches (the function is not going to change :P).
1. We press the button.
2. The browser receives an event which will enter the angular context (I will explain why, later in this article).
3. The $digest loop will run and will ask every $watch for changes.
4. Since the $watch which was watching for changes in $scope.name reports a change, if will force another $digest loop.
5. The new loop reports nothing.
6. The browser gets the control back and it will update the DOM reflecting the new value of $scope.name
The important thing here is that EVERY event that enters the angular context will run a $digest loop. That means that every time we write a letter in an input, the loop will run checking every $watch in this page.
Example -1:
<html>
<head>
<title>AngularJS Digest</title>
<script src="lib/angular.js"></script>
<script>
var myapp = angular.module("myapp", []);
var myController = myapp.controller("myController", function ($scope) {
$scope.datetime = new Date();
$scope.updateTime = function () {
$scope.datetime = new Date();
}
// This block of code updating model outside of the Angular. so, we are using $scope.$digest() to refresh.
document.getElementById("updateTimeButton").addEventListener('click', function () {
console.log("update time clicked");
$scope.datetime = new Date();
console.log($scope.datetime);
});
});
</script>
</head>
<body ng-app="myapp" ng-controller="myController">
<button ng-click="updateTime()">Update time - ng-click</button>
<button id="updateTimeButton">Update time</button>
<br />
{{datetime | date:'yyyy-MM-dd HH:mm:ss'}}
</body>
</html>
When you will click on second button, the data binding is not updated. Since $scope.$digest() is not called after the second button's event listener is executed. In this way on clicking the second button the time will be updated in the $scope.data.time variable, but the new time will never displayed.
<script type="text/javascript">
document.getElementById("updateTimeButton").addEventListener('click', function () {
console.log("update time clicked");
$scope.datetime = new Date();
//to update $scope
$scope.$digest();
console.log($scope.datetime);
});</script>
To fix this issue you need to add a $scope.$digest() call to the second button event listener
$apply
When we do change in any model outside of the Angular context (like browser DOM events, setTimeout, XHR or third party libraries), then we need to inform Angular of the changes by calling $apply() manually. When the $apply() function call finishes AngularJS calls $digest() internally, so all data bindings are updated.
<script>
document.getElementById("updateTimeButton").addEventListener('click', function () {
$scope.$apply(function () {
console.log("update time clicked");
$scope.datetime = new Date();
console.log($scope.datetime);
});
});
</script>
In the above $digest example, instead of calling $digest() function inside the button listener function we can used the $apply() function like this
The main differance between the $digest and $apply:
1. $digest() is faster than $apply(), since $apply() triggers watchers on the entire scope chain while $digest() triggers watchers on the current scope and its children(if it has).
2. When error occurs in one of the watchers, $digest() can not handled errors via $exceptionHandler service, In this case you have to handle exception yourself. While $apply() uses try catch block internally to handle errors and if error occurs in one of the watchers then it passes errors to $exceptionHandler service.
Subscribe to:
Posts (Atom)
