Bhavya

Code -> Break -> Fix -> Blog


1 Comment

C# 6.0 : Function & Property with Lambda expression (Expression Body)

Another C# 6.0 feature which simplifies the syntax is the use of Lambda expression with Functions.

Developers commonly overrides the ToString() method of the object class.

 public override string ToString()
 {
 return "\{LastName}, \{FirstName}";
 }

But with C# 6.0, this is made simple with the use of Lambda expression with Function (this can be implemented for any Function not restricted to ToString()).

public override string ToString() => "\{LastName}, \{FirstName}";

The same can also be done for Property.

public string FullName => "\{LastName}, \{FirstName}";

You will notice that return string is not in a familiar format for that I suggest you look at my String interpolation blog.

Let me know you thoughts.

~BS

Twitter Logo


1 Comment

C# 6.0 : nameof Operator

With the introduction of nameof operator, a developer can reduce the use of string literals for program elements like class, field, property etc.

Say we have a method which checks the Name property and if Name property has any numeric character then the method throws an ArgumentException stating “Name property is invalid.”

 // Code which checks if name holds only alphabets
 // and no numberic characters.
 // If name parameter has numeric characters then
 // throw Argument exception.
 ...
 ...
 catch(ArgumentException)
 {
 WriteLine("Name property is invalid.");
 }

If the developer modifies the Name property to FullName. The compiler will not warn the developer to update the string literal which will end up confusing the end-user or we will have an invalid entry in the log (if the string is used for logging).

With C# 6.0 and nameof operator, this can be avoided.

Console.WriteLine(nameof(FullName) + " property is invalid.");

nameof operator can be really useful when calling the OnPropertyChanged().

Instead of :

 public string FullName
 {
 get
 {
 return fullName;
 }
 set
 {
 fullName = value;
 // Call OnPropertyChanged whenever the property is updated
 OnPropertyChanged("FullName");
 }
 }

the developer can now use the nameof operator

  public string FullName
 {
 get
 {
 return fullName;
 }
 set
 {
 fullName = value;
 // Call OnPropertyChanged whenever the property is updated
 OnPropertyChanged(nameof(FullName));
 }
 }

The nameof operator takes a class, method, field, property or variable and returns a string literal.

Let me know your thoughts.

~BS

Twitter Logo


1 Comment

C# 6.0 : Null conditional Operator (?.)

Problem : Say we have an Employee class with EmpID, Name & PhoneNo properties.

 internal class Employee
 {
 public int EmpID { get; set; }
 public string Name { get; set; }
 public string PhoneNo { get; set; }
 }

Now if we want to print PhoneNo, we need to have a null check for the employee object as well as for PhoneNo property.

if (employeeObject != null && employeeObject.PhoneNo != null)
 {
 WriteLine(employeeObject.PhoneNo);
}

To avoid these checks C# 6.0 introduces a new operator called Null conditional (?.) operator.

Also known as Elvis operator.

The code is now much simpler with C# 6.0


WriteLine(employee?.PhoneNo ?? "No Phone Number available");

Oh man!!! This will surely reduce lots of null checks statements.

Also, the ?. operator makes working with Events much simpler.

For C# version < 6.0:

if (OnPhoneNoChanged != null)
 {
 OnPhoneNoChanged(this, e);
 }

C# 6.0, makes it simpler

OnPhoneNoChanged?.Invoke(this, e);

Let me know your thoughts.

~BS

Twitter Logo


2 Comments

C# 6.0 : String Interpolation

Using String.Format() can be error-prone and difficult to handle if we have lot of place holders, like,


Console.WriteLine(String.Format("{0} {1} {2}", firstName, middleName, lastName));

It will be helpful if we can eliminate the place-holders and use the values in-place.

This is possible with C# 6.0:


Console.WriteLine("\{firstName} \{middleName} \{lastName}");

The above code will in-turn call the String.Format() and do the needful.

This makes the developer’s life simple.

Let me know your thoughts.

~BS

Twitter Logo


1 Comment

C# 6.0 : Easy Dictionary Initializer

Below is the code to initialize a Dictionary object for C# version < 6.0:

Dictionary<int, string> employees = new Dictionary<int, string> {
{1, "Gabbar"},
{2, "Langda Tyagi"},
{3, "Mogambo"},
{4, "Kesariya Vilayt"},
{5, "Lotiya Pathan"}
};

But with C# 6.0 the above code can be made simple,

Dictionary<int, string> employees = new Dictionary<int, string>;
{
[1] = "Gabbar",
[2] = "Langda Tyagi",
[3] = "Mogambo",
[4] = "Kesariya Vilayt",
[5] = "Lotiya Pathan"
};

Let me know your thoughts.

~BS


1 Comment

C# 6.0 : using Static Class

Problem : Using the Static class name over and over in the code to access it’s static method.

Prior to C# 6.0, to use a static method the developer also have to specify the Static Class name.


using System;

namespace MyNameSpace
{

internal class MyClass
{
static void Main(string[] args)
{
var inputName = Console.ReadLine();
Console.WriteLine(&quot;Hello &quot; + inputName);

Console.ReadKey();
}
}
}

In the above code snippet, see the use of Console (static) class 3 times.

With C# 6.0, we can use the using keyword to refer to Console (static) class.


using System.Console;

namespace MyNameSpace
{

internal class MyClass
{
static void Main(string[] args)
{
var inputName = ReadLine();
WriteLine(&quot;Hello &quot; + inputName);

ReadKey();
}
}
}

Prior to C# 6.0 the using keyword was used to refer only namespaces, like,


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

But with C# 6.0, we can use the using keyword to refer static class as well, like System.Console


using System.Console;

namespace MyNameSpace
{

internal class MyClass
{
static void Main(string[] args)
{
var inputName = ReadLine();
WriteLine(&quot;Hello &quot; + inputName);

ReadKey();
}
}
}

New C# 6.0 features really help in writing clean code with the support of using keyword.

~BS

Twitter Logo


1 Comment

C# 6.0 : Getter-Only Auto-Property

Lets first discuss what would have lead to having this feature.

Problem: We want to have a read-only field and a property which encapsulates it.

In the previous version, this is what we would do:

private readonly int myProperty;

public int MyProperty
 {
 get
 {
 return myProperty;
 }
 }

The value of myProperty (because it is read-only) can only be set in the constructor.

Let’s try to achieve this with C# version < 6.0.

 internal class MyClass
 {
 public int MyProperty { get; }
 }

The above code will give the following error:

‘MySolution.MyClass.MyProperty.get’ must declare a body because it is not marked abstract or extern. Automatically implemented properties must define both get and set accessors.

Using C# 6.0:

 internal class MyClass
 {
 public int MyProperty { get; }
 }

The above code will generate a backing read-only field. As it is a read-only field we can set the value of this property in the constructor.

 public MyClass()
 {
 MyProperty = 100;
 }

We can also initialize the Auto-Property as below:

public int MyProperty { get; } =10;

If we try to access it in any class operation then we get compile time error.

 public void MyMethod(int passedValue)
 {
 MyProperty = passedValue;
 }

Error : Property or indexer ‘MyClass.MyProperty’ cannot be assigned to — it is read only

Getter-only Auto-Property will help the developer to write just 1 line of code instead of 4-5 lines.

Let me know your thoughts.

~BS

Twitter Logo


Leave a comment

Implementing Recipient List Pattern using Windows Azure Service Bus

Continuing the implementation of Message Routing Pattern, next inline is Recipient List Pattern (You can also visit my previous post for Dynamic Router Pattern)

Again as posted by Stephen Kaufman,

This pattern is related to the Content Based Router pattern in that the CBR pattern routes messages based on the message content.  The Recipient List pattern provides a means for the message to contain a list of one or more recipients to receive the message.  This differs from CBR in that we may want to submit a message to multiple order fulfillment suppliers in order to receive back prices thus allowing for the comparison of responses and the selection of the cheapest supplier.

Below is the implementation:

Person Class:


/// <summary>
/// Class Person
/// </summary>
[Serializable]
public class Person
{
/// <summary>
/// Initializes a new instance of the <see cref="Person" /> class.
/// </summary>
public Person()
{
}

/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
public string Name
{
get;
set;
}

/// <summary>
/// Gets or sets the hobbies.
/// comma separated hobby names.
/// </summary>
/// <value>The hobbies.</value>
public string Hobbies
{
get;
set;
}

/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>A <see cref="System.String" /> that represents this instance.</returns>
public override string ToString()
{
return Name;
}
}

Fields:


static string IssueName = string.Empty;
static string IssueKey = string.Empty;
static string ServicebusNamespace = string.Empty;

static NamespaceManager namespaceManager;
static MessagingFactory messagingFactory;
static TopicDescription topicDescription;

Utilities:


static TopicDescription CreateTopic(string topicName)
{
TopicDescription topicDescription = new TopicDescription(topicName);
topicDescription.EnableFilteringMessagesBeforePublishing = true;

//Check if already exists.
if (namespaceManager.TopicExists(topicDescription.Path))
{
namespaceManager.DeleteTopic(topicDescription.Path);
}

Console.WriteLine("Creating Topic : " + topicName);
return namespaceManager.CreateTopic(topicDescription);
}

static void CreateSubscription(Dictionary<string, string> subscription)
{

if (null != topicDescription)
{
foreach (KeyValuePair<string, string> item in subscription)
{
if (string.IsNullOrEmpty(item.Value))
{
namespaceManager.CreateSubscription(topicDescription.Path, item.Key);
}
else
{
namespaceManager.CreateSubscription(topicDescription.Path, item.Key, new SqlFilter(item.Value));
}
}
}
}

static void SendMessage(Person message, KeyValuePair<string, object> item)
{
TopicClient topicClient = messagingFactory.CreateTopicClient(topicDescription.Path);

BrokeredMessage brokeredMessage = new BrokeredMessage(message);

if (null != item.Key && null != item.Value)
{
brokeredMessage.Properties.Add(item);
}

topicClient.Send(brokeredMessage);
}

static Person ReceiveMessage(string subscriptionName)
{
SubscriptionClient subscriptionClient = messagingFactory.CreateSubscriptionClient(topicDescription.Path, subscriptionName, ReceiveMode.ReceiveAndDelete);

BrokeredMessage receivedMessage = subscriptionClient.Receive(new TimeSpan(0, 0, 3));

return (null != receivedMessage) ? receivedMessage.GetBody<Person>() : null;
}

Main implementation:


static void Main(string[] args)
{
#region User details check
if (string.IsNullOrEmpty(IssueName) || string.IsNullOrEmpty(IssueKey) || string.IsNullOrEmpty(ServicebusNamespace))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("One of the below 3 values are missing...");
Console.WriteLine("ServicebusNamespace");
Console.WriteLine("IssuerName");
Console.WriteLine("IssuerKey");
Console.ResetColor();
Console.WriteLine("\nPress any key to receive the message...");
Console.ReadKey();
return;
}
#endregion

#region Create Topic & Subscription
Uri serviceBusUri = ServiceBusEnvironment.CreateServiceUri("sb", ServicebusNamespace, string.Empty);
TokenProvider tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(IssueName, IssueKey);

namespaceManager = new NamespaceManager(serviceBusUri, tokenProvider);
messagingFactory = MessagingFactory.Create(serviceBusUri, tokenProvider);

topicDescription = CreateTopic("RecipientListTopic");

Dictionary<string, string> subscriptionItems = new Dictionary<string, string>();
subscriptionItems.Add("Hobby1", "Hobby LIKE '%Hobby1%'");
subscriptionItems.Add("Hobby2", "Hobby LIKE '%Hobby2%'");
subscriptionItems.Add("Hobby3", "Hobby LIKE '%Hobby3%'");
subscriptionItems.Add("Hobby4", "Hobby LIKE '%Hobby4%'");

CreateSubscription(subscriptionItems);
#endregion

#region Create Messages
List<Person> personList = new List<Person>();
personList.Add(new Person() { Name = "Sam", Hobbies = "Hobby1,Hobby3" });
personList.Add(new Person() { Name = "Vicky", Hobbies = "Hobby2,Hobby4" });
personList.Add(new Person() { Name = "Graham", Hobbies = "Hobby1,Hobby2" });
personList.Add(new Person() { Name = "Vivin", Hobbies = "Hobby1,Hobby2,Hobby3,Hobby4" });
personList.Add(new Person() { Name = "Sammy", Hobbies = "Hobby3" });
#endregion

#region Send Message
foreach (Person item in personList)
{
KeyValuePair<string, object> property = new KeyValuePair<string, object>("Hobby", item.Hobbies);
SendMessage(item, property);
Console.WriteLine("Item " + item.Name + " sent to " + topicDescription.Path);
}
#endregion

Console.WriteLine("Press any key to receive the message...");
Console.ReadKey();

#region Receive Message
Console.WriteLine("Hobby1:");
while (true)
{
var hobby1 = ReceiveMessage("Hobby1");
if (null != hobby1)
{
Console.WriteLine(hobby1.ToString());
}
else
{
break;
}
}

Console.WriteLine("Hobby2:");
while (true)
{
var hobby2 = ReceiveMessage("Hobby2");
if (null != hobby2)
{
Console.WriteLine(hobby2.ToString());
}
else
{
break;
}
}

Console.WriteLine("Hobby3:");
while (true)
{
var hobby3 = ReceiveMessage("Hobby3");
if (null != hobby3)
{
Console.WriteLine(hobby3.ToString());
}
else
{
break;
}
}

Console.WriteLine("Hobby4:");
while (true)
{
var hobby4 = ReceiveMessage("Hobby4");
if (null != hobby4)
{
Console.WriteLine(hobby4.ToString());
}
else
{
break;
}
}
#endregion

Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}

~BS


Leave a comment

Implementing Singleton Pattern with/without Lazy instantiation

Implement Singleton with:

1. Thread-safe (not using Locks)

2. Not Lazy


public sealed class MySingleton
{
private static readonly MySingleton instance;

static MySingleton()
{
instance = new MySingleton();
}

private MySingleton()
{
}

public static MySingleton Instance
{
get
{
return instance;
}
}
}

Implement Singleton with:

1. Full Lazy

2. Thread-safe (not using Locks)

3. Not using System.Lazy<T> type.

4. .NET 3.5 and below.


public sealed class MySingleton
{
private class Nested
{
static Nested()
{
instance = new MySingleton();
}

internal static readonly MySingleton instance;
}

private MySingleton()
{
}

public static MySingleton Instance
{
get
{
return Nested.instance;
}
}
}

Implementation Singleton with:

1. Full Lazy

2. Thread-safe (not using Locks)

3. Using System.Lazy<T> type.

4. .NET 4.0 and above.


public sealed class MySingleton
{
private static readonly Lazy<MySingleton> instance = new Lazy<MySingleton>(() => new MySingleton());

private MySingleton()
{
}

public static MySingleton Instance
{
get
{
return instance.Value;
}
}
}


1 Comment

Implementing Dynamic Router Pattern using Windows Azure Service Bus

In my previous post, I have implemented Message Filter Pattern. In this post I will be implementing Dynamic Router Pattern which is well explained by Stephen Kaufman here.

Dynamic Router as explained by Kaufman,

This pattern provides for the scenario in that each recipient would register and list the conditions or rules for which messages or types of messages it can handle. The conditions or rules are stored so that when a message arrives, the rules run and the message parameters are evaluated against the rules and then the message is routed accordingly to the correct receiver. The benefit of this is that you can achieve predictive routing, with eased maintenance and less dependency on each receiver.

This pattern is implemented in Azure by default in both the Topic and the Queues. When you create a subscription and a receiver for a topic you are registering with the service and as part of that registration process you also provide rules or conditions for the types of messages or the value of properties that you want to filter for.

But what if we want to take this a step further and provide even more dynamic functionality. What if we could implement the functionality that is available in BizTalk called Promoted Properties but do it completely within the functionality of Azure. Promoted Properties is a way of taking data contained in the body of an object or message and put that in a properties collection that can then be used to route messages. When working with Azure, the BrokeredMessage object contains a properties collection that can be used to route however, you manually have to set these properties at design time. Our goal is to take the values of properties in the object body itself and promote those to the BrokeredMessage properties collection so that they can be assigned and routed at run time.

Below is the implementation:

ExposedProperty Attribute


[AttributeUsage(AttributeTargets.Property)]
internal class ExposedPropertyAttribute : Attribute
{
private string _name;

public ExposedPropertyAttribute(string name)
{
this._name = name;
}

public string Name
{
get
{
return this._name;
}
}
}

Person Class:


[Serializable]
public class Person
{
/// <summary>
/// Initializes a new instance of the <see cref="Person" /> class.
/// </summary>
public Person()
{
}

/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>The name.</value>
public string Name
{
get;
set;
}

/// <summary>
/// Gets or sets the gender.
/// </summary>
/// <value>The gender.</value>
[ExposedProperty("Gender")]
public string Gender
{
get;
set;
}

/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>A <see cref="System.String" /> that represents this instance.</returns>
public override string ToString()
{
return Name;
}
}

Fields :


// TODO : Set the IssueName, IssueKey and ServicebusNamespace variable with proper values before running the code.
static string IssueName = string.Empty;
static string IssueKey = string.Empty;
static string ServicebusNamespace = string.Empty;

static NamespaceManager namespaceManager;
static MessagingFactory messagingFactory;
static TopicDescription topicDescription;

Utilities:


/// <summary>
/// Creates the Topic.
/// </summary>
/// <param name="topicName">The topic name.</param>
/// <returns>TopicDescription</returns>
static TopicDescription CreateTopic(string topicName)
{
TopicDescription topicDescription = new TopicDescription(topicName);
topicDescription.EnableFilteringMessagesBeforePublishing = true;

//Check if already exists.
if (namespaceManager.TopicExists(topicDescription.Path))
{
namespaceManager.DeleteTopic(topicDescription.Path);
}

Console.WriteLine("Creating Topic : " + topicName);
return namespaceManager.CreateTopic(topicDescription);
}

/// <summary>
/// Creates the subscription.
/// </summary>
/// <param name="subscription">The subscription.</param>
static void CreateSubscription(Dictionary<string, string> subscription)
{

if (null != topicDescription)
{
foreach (KeyValuePair<string, string> item in subscription)
{
if (string.IsNullOrEmpty(item.Value))
{
namespaceManager.CreateSubscription(topicDescription.Path, item.Key);
}
else
{
namespaceManager.CreateSubscription(topicDescription.Path, item.Key, new SqlFilter(item.Value));
}
}
}
}

/// <summary>
/// Sends the message.
/// </summary>
/// <param name="message">The message.</param>
static void SendMessage(Person message)
{
TopicClient topicClient = messagingFactory.CreateTopicClient(topicDescription.Path);

BrokeredMessage brokeredMessage = new BrokeredMessage(message);

brokeredMessage = ExposeProperties(brokeredMessage, message);

topicClient.Send(brokeredMessage);
}

/// <summary>
/// Receives the message.
/// </summary>
/// <param name="subscriptionName">Name of the subscription.</param>
static Person ReceiveMessage(string subscriptionName)
{
SubscriptionClient subscriptionClient = messagingFactory.CreateSubscriptionClient(topicDescription.Path, subscriptionName, ReceiveMode.ReceiveAndDelete);

BrokeredMessage receivedMessage = subscriptionClient.Receive(new TimeSpan(0, 0, 15));

return (null != receivedMessage) ? receivedMessage.GetBody<Person>() : null;
}

/// <summary>
/// Exposes the properties.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="obj">The obj.</param>
static BrokeredMessage ExposeProperties(BrokeredMessage message, object obj)
{
PropertyInfo[] properties = obj.GetType().GetProperties();

foreach (PropertyInfo property in properties)
{
foreach (ExposedPropertyAttribute exposedProperty in property.GetCustomAttributes(typeof(ExposedPropertyAttribute), false))
{
var value = property.GetValue(obj, null);
message.Properties.Add("Gender", value);
}
}

return message;
}

Main Implementation:


static void Main(string[] args)
{
#region User details check
if (string.IsNullOrEmpty(IssueName) || string.IsNullOrEmpty(IssueKey) || string.IsNullOrEmpty(ServicebusNamespace))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("One of the below 3 values are missing...");
Console.WriteLine("ServicebusNamespace");
Console.WriteLine("IssuerName");
Console.WriteLine("IssuerKey");
Console.ResetColor();
Console.WriteLine("\nPress any key to receive the message...");
Console.ReadKey();
return;
}
#endregion

#region Create Topic
Uri serviceBusUri = ServiceBusEnvironment.CreateServiceUri("sb", ServicebusNamespace, string.Empty);
TokenProvider tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(IssueName, IssueKey);

namespaceManager = new NamespaceManager(serviceBusUri, tokenProvider);
messagingFactory = MessagingFactory.Create(serviceBusUri, tokenProvider);

topicDescription = CreateTopic("DynamicRouterTopic");
#endregion

#region Create Subscription
Dictionary<string, string> subscriptionItems = new Dictionary<string, string>();
subscriptionItems.Add("Male", "Gender='Male'");
subscriptionItems.Add("Female", "Gender='Female'");

CreateSubscription(subscriptionItems);
#endregion

#region Create Message
List<Person> personList = new List<Person>();
personList.Add(new Person() { Name = "Tom", Gender = "Male" });
personList.Add(new Person() { Name = "Ira", Gender = "Female" });
personList.Add(new Person() { Name = "Julie", Gender = "Female" });
personList.Add(new Person() { Name = "Jim", Gender = "Male" });
personList.Add(new Person() { Name = "Anna", Gender = "Female" });
personList.Add(new Person() { Name = "Alan", Gender = "Male" });
#endregion

#region Send Messages
foreach (Person item in personList)
{
SendMessage(item);
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.WriteLine("Item " + item.Name + " sent to " + topicDescription.Path);
Console.ResetColor();
}
#endregion

Console.WriteLine("Press any key to receive the message...");
Console.ReadKey();

#region Receive Message
Console.WriteLine("\n\nFemale list:");
while (true)
{
var female = ReceiveMessage("Female");
if (null != female)
{
Console.WriteLine(female.ToString());
}
else
{
break;
}
}

Console.WriteLine("\n\nMale list:");
while (true)
{
var male = ReceiveMessage("Male");
if (null != male)
{
Console.WriteLine(male.ToString());
}
else
{
break;
}
}
#endregion

Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}

~BS