Sunday, September 20, 2015

Visual C# Technical Guru - August 2015

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category.

The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
image
Visual C# Technical Guru - August 2015
Happy Coding.

Regards,
Jaliya

Tuesday, September 15, 2015

Wrote a TNWiki Article Spotlight at Official Blog of TechNet Wiki

In this week’s TNWiki Article Spotlight, I wrote a post highlighting an article won the July month's TechNet Guru Awards under Windows Presentation Foundation (WPF) Category, an article created by Andy ONeill titled WPF: Inheriting Property Values Considered.

image
TNWiki Article Spotlight - WPF: Inheriting Property Values Considered
Read the post on,
TNWiki Article Spotlight - WPF: Inheriting Property Values Considered

Happy Coding.

Regards,
Jaliya

Wednesday, September 9, 2015

ReadOnlyCollection<T> in C#, Is It Really Read Only?

With .NET 2.0 ReadOnlyCollection<T>  was introduced and I have seen this question “Is ReadOnlyCollection<T> really read only?”. Well the simple answer is, it is, but you need to understand how this works and otherwise you will be surprised with some results. In this post, let’s see how  ReadOnlyCollection<T> works.

For example, let’s take following List of type string.
List<string> strings = new List<string>()
{
    "Visual Studio 2010","Visual Studio 2012","Visual Studio 2013"
};
So basically there is two ways that I can create a ReadOnlyCollection<T> from this.
ReadOnlyCollection<string> readOnlyStrings = strings.AsReadOnly();
// or
ReadOnlyCollection<string> readOnlyStrings = new ReadOnlyCollection<string>(strings);
One from calling List<T>.AsReadOnly() method which will return a ReadOnlyCollection<T> or by calling the constructor of ReadOnlyCollection<T>. Both of this will achieve the same.

Now if you try to modify the readOnlyStrings collection, you can’t. Because it is read only. But what about modifying strings collection which is of type List<T>. Well you should be able to modify it for example by adding a new item.
strings.Add("Visual Studio 2015");
Now let’s see what do we have on the readOnlyStrings collection.
foreach (string item in readOnlyStrings)
{
    Console.WriteLine(item);
}
image
Result
Surprisingly you will see that your readOnlyStrings collection has been modified. But did you add an item to readOnlyStrings, No, but you did add an item to strings.

So what happened here is nicely described on MSDN.

“An instance of the ReadOnlyCollection<T> generic class is always read-only. A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes.”

Now let’s take another scenario.

Here I have a simple class named VisualStudio and there I have a helper method which will return new instance of List<VisualStudio>.
class VisualStudio
{
    public string Version { get; set; }
 
    public static List<VisualStudio> GetVisualStudios()
    {
        return new List<VisualStudio>()
        {
            new VisualStudio() { Version = "Visual Studio 2010" },
            new VisualStudio() { Version = "Visual Studio 2012" },
            new VisualStudio() { Version = "Visual Studio 2013" },
        };
    }
}
Now I have the following ReadOnlyCollection<T> where T is VisualStudio.
ReadOnlyCollection<VisualStudio> readOnlyVisualStudios = new ReadOnlyCollection<VisualStudio>(VisualStudio.GetVisualStudios());
Now let’s try to modify an item in the readOnlyVisualStudios and see the content of readOnlyVisualStudios.
readOnlyVisualStudios[0].Name = "Microsoft Visual Studio 2010";
 
foreach (VisualStudio item in readOnlyVisualStudios)
{
    Console.WriteLine(item.Name);
}
image
Result
Again it seems readOnlyVisualStudios has been modified. This shows another feature of ReadOnlyCollection<T>. That is when the T in ReadOnlyCollection<T> is a complex type, the individual items of ReadOnlyCollection<T> can be modified either by changing the values of it’s properties or by calling the methods of complex type. But the following is illegal and will throw an error.
readOnlyVisualStudios[0] = null;
// or
readOnlyVisualStudios[0] = new VisualStudio() { Name = "Microsoft Visual Studio 2010" };

So that’s it.  Keep in mind that when working with ReadOnlyCollection<T>, you need to make sure, you are not letting the underline collection to be modified or only let the class that contains the underline collection to modify  it and not others for instance like below.
private List<string> strings;
public ReadOnlyCollection<string> Strings
{
    get { return new ReadOnlyCollection<string>(strings); }
}
If you want your strings which is of List<T> to be read only, make it private so you (containing class) can do what ever you want and expose as a public ReadOnlyCollection<T> to consumers.

Hope this helps.

Happy Coding.

Regards,
Jaliya

Sunday, August 30, 2015

Received Microsoft Community Contributor (MCC) Badge for the First Time!

Today I just noticed that I have received the Microsoft Community Contributor (MCC) badge for the first time and Thank you Microsoft!
2015-08-31_12-38-24
Microsoft Community Contributor
And if you want to become one, read the following to know how.

MICROSOFT COMMUNITY CONTRIBUTOR (MCC)

PROCESS: Microsoft automatically reviews the contributions of participants who offer their time and energy to online technical communities such as Microsoft Answers/Community, MSDN, and TechNet to identify those who make notable contributions for possible recognition as a Microsoft Community Contributor. Microsoft employees cannot become MCCs, but MVPs can become MCCs. MCC is an automatic reward (nobody can help you win it by nominating you). 

REWARD: The reward is a "small benefit": the award status in your profile on the online community (MSDN, TechNet, etc.) and your name on a list of MCC award recipients. The MCC badge ends after ninety days (three months) from the date found within the welcome email.

Tips to becoming an MCC (based on the FAQ)
1) Make an impact in the community, using tools like TechNet and MSDN Forums. Maintain quality and quantity in your contributions.
2) Rule the Forums. Find a technology's forum (on MSDN or TechNet) where there's a huge need for moderation and answerers. Become an expert in that technology. Then answer a ton of questions with quality answers, propose a lot of answers (especially ones that aren't from you), and then request to be made an Answerer or Moderator. See How to Become an MSDN or TechNet Forum Moderator. Try to get a lot of quality answers completed.
NOTE: This award is based on your contributions in the last 3 months. In other words, if you just started one week ago, you'll need to continue your efforts for a few more months.
NOTE: MCC is an automatic reward (nobody can help you win it by nominating you).

For more information,

Happy Coding.

Regards,
Jaliya

Thursday, August 20, 2015

Visual C# Technical Guru - July 2015

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category.

The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
image
Visual C# Technical Guru - July 2015
Happy Coding.

Regards,
Jaliya

Thursday, August 13, 2015

C# : String vs. string

I have seen this confusion over and over, and thought of writing a post about it. Basically String and string are both the same. If you go to definition (F12) on String or string, you will see that you will be navigated to the same String class. string is an alias for System.String.

So now you must be thinking, if these two are similar, when should we use String or string. Again there is no strict rule for which to use, but as a practice we are maintaining following standards. If you are using the string type for a variable, use string. If you accessing String classes' methods, then use String.

Let me show you what I mean.
class Program
{
    static void Main(string[] args)
    {
        string value1 = System.String.Empty;
        string value2 = System.String.Format("{0} {1}", "Hello", "World");
        string value3 = System.String.Concat("Hello", " ", "World");
 
        if (System.String.IsNullOrEmpty(value1))
        { 
            // some implementation
        }
 
        // etc.
    }
}
 
class String
{
 
}

Above code will be compiling fine. But it’s good to note one important thing. string is a reserved keyword and String is yet another class. So theoretically there is nothing wrong having an another class named String in your project. But that is highly unlikely.

Hope this helps.

Happy Coding.

Regards,
Jaliya

Friday, July 24, 2015

Setting a Default Value for Enums in C#

Enums can be very useful in cases like where you want to maintain a set of named constants. Imagine you have following values, “Daily, Weekly, SemiMonthly etc” and you want to display these inside a drop down list. And for the dropdown you need to set up a default value. You can easily use enum for this. Of course I am sure all of you must be aware of how to use enums and from this post let’s see how we can set up a default value for an enum and how to get that default value.

So I have the following enum and please note the DefaultValueAttribute which I used to decorate my enum "Period" with.
[DefaultValue(Monthly)]
public enum Period
{
    Daily,
    Weekly,
    SemiMonthly,
    Monthly,
    Quarterly,
    SemiAnnually,
    Annually
}
So only by decorating the enum with DefaultValueAttribute and setting the default value, now my enum "Period" has a default value which is “Monthly”. Now let’s see how I can retrieve it.
public static T GetEnumDefaultValue<T>() where T : struct
{
    DefaultValueAttribute[] attributes = typeof(T).GetCustomAttributes(typeof(DefaultValueAttribute), false) as DefaultValueAttribute[];

    if (attributes != null && attributes.Length > 0)
    {
        return (T)attributes[0].Value;
    }
    return default(T);
}
Here I have a generic method, I have applied a constraint on the type argument where T : struct and that’s because enums are of value types. Then after getting the type of type argument, I am getting the list of attributes applied to it. Since the only attribute applied is a DefaultValueAttribute, I can cast the result set into an array of DefaultValueAttribute. Then if the result is not null and if it is elements, I am getting the value of first element. Else I am returning the enum which has the value 0 which is the default by nature of course.

Now let’s see how we can call this method. It's pretty simple.
static void Main(string[] args)
{
   Period period = GetEnumDefaultValue<Period>();
   Console.WriteLine(period.ToString());
}
And the output is as expected.
image
Result
Happy Coding.

Regards,
Jaliya

Thursday, July 23, 2015

Visual Studio 2015 : Live Visual Tree and Live Property Explorer for XAML Debugging

One of the nicest features introduced with Visual Studio 2015 is Live Visual Tree and Live Property Explorer windows. These two windows can be quite handy when you are debugging WPF applications and mainly on UI aspect.

To show you how these two can be tremendously helpful, let me create a WPF application and that’s using Visual Studio 2015 and add a text block inside a StackPanel.
image
Basic UI Structure
<Grid>
    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
        <TextBlock x:Name="textBlock" Text="Hello World" FontSize="20"/>
    </StackPanel>
</Grid>

Now let’s run the application. While running the application from Live Visual Tree window, enable selection in the running application by clicking the below highlighted icon.
image
Live Visual Tree : Enable Selection in the Running Application
If you can’t find the Live Visual Tree window, go to Debug->Windows and click on Live Visual Tree.
image
Adding Live Visual Tree
Now from the running application when you move your mouse over the UI controls, they will be highlighted in Red color and you should be able to select the element just like you are Inspecting elements from the browser on web applications.

image
Selecting Elements on Running Application
Now when you click on a particular item, here in the example, “Hello World” text block, you can see that Live Visual Tree gets expanded and you will be landed directly on that particular TextBlock control. No matter how many controls you have this will work like a charm. Now let’s right click on the TextBlock and select Show Properties.

image
Live Visual Tree : Show Properties
Now Live Property Explorer window will be opened. Here from these properties you can change values of any of the properties, and those changes will be applied real time on the already running application.
image
Live Property Explorer
To see that in action, let’s change the value of FontSize property to 40.
image
Live Property Explorer
Do a quick save and from the Live Visual Tree, click back on the TextBlock. Now you can see that TextBlock containing the text “Hello World” has increased font size.

image
Increased Font Size
So Isn’t this great or what. Actually this feature is initially introduced with Visual Studio 2015 CTP 6 and Microsoft has mentioned that this feature will be available in Universal Windows Platform applications as well in the future.

And for that we will have to wait till 29th this month, till Windows 10 is out.

Happy Coding.

Regards,
Jaliya

Tuesday, July 21, 2015

Visual Studio 2015, Visual Studio 2013 Update 5, .NET 4.6, ASP.NET 4.6 and C# 6 is Now Officially Released

20th July 2015 was a big day I believe for all the developers who are on Microsoft stack out there, as Microsoft has released the newest version of Visual Studio which is Visual Studio 2015. Along with Visual Studio 2015, .NET 4.6, ASP.NET 4.6, C# 6, VB 14, F# 4, and one of my new favorites TypeScript 1.5 was released as well.

One significant change with the release of Visual Studio 2015 is, now there is no more Visual Studio 2015 Ultimate or Premium product line. Those two got merged into Visual Studio 2015 Enterprise and basically for Visual Studio 2015 mainly only three product offerings are available.
  • Visual Studio 2015 Enterprise with MSDN
  • Visual Studio 2015 Professional with MSDN
  • Visual Studio 2015 Community
Additionally Visual Studio 2015 Express editions, Test Professional edition and Team Foundation Server edition are available. For more information about Visual Studio 2015 Product Offerings, please visit the following link.
For Visual Studio 2013 product family, the newest release is Visual Studio 2013 Update 5. It has fixed number of bugs reported on Visual Studio 2013 Update 4 and you can find more information about bugs fixed and known issues from following knowledge base article.

Now it's time to start using these great set of tools.

Happy Coding.

Regards,
Jaliya

Monday, July 20, 2015

Visual C# Technical Guru - June 2015

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category.

The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
image
Visual C# Technical Guru - June 2015
Happy Coding.

Regards,
Jaliya