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.6C# 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

Friday, July 17, 2015

AngularJS ng-options Filter by Custom Function

In AngularJS when you are using ng-options, you can filter out the options by calling  a custom function you have in the controller.

Let’s say you have following set of employees and when you display all these employees inside HTML select using ng-options, you can see all the employees in a dropdown.
$scope.employees = [
    {
        name: "Jaliya Udagedara",
        department: "VS",
    },
    {
        name: "John Smith",
        department: "VS",
    },
    {
        name: "Jane Smith",
        department: "SQL",
    }
];
image
Result without Filter
And now let's say, you only need employees whose department is “VS”.

For that I am filtering the employees where department equals “VS” and that’s by calling a custom function. (here for this simple requirement I really don’t need to write a custom filter function, I can supply the filter even inline, but for the demonstration purposes, let’s call a custom function.)
<select ng-options="employee.name for employee in employees | filter:filterEmployeesByDepartment()"
        ng-model="selectedEmployee">
</select>
So here is the filter function inside the controller.
$scope.filterEmployeesByDepartment = function () {
    return function (item) {
        if (item.department == 'VS')
        {
            return true;
        }
        return false;
    };
};
Here the item is an employee inside my employees collection. If the employees’ department is “VS”, I should include it in the dropdown else I shouldn’t.

And this is my filtered employees.
image
Result with Filter
Even I can pass parameters to filterEmployeesByDepartment function.
<select ng-options="employee.name for employee in employees | filter:filterEmployeesByDepartment('Hello World')"
        ng-model="selectedEmployee">
</select>
And if I change the function accordingly,
$scope.filterEmployeesByDepartment = function (param) {
    return function (item) {
        console.log(param); // param->Hello World
    
        if (item.department == 'VS') {
            return true;
        }
        return false;
    };
};
Here, param will have the value “Hello World”.

Happy Coding.

Regards,
Jaliya

Wednesday, July 1, 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 that won the TechNet Guru Awards for month of May, 2015, and that’s under Universal Windows Apps Category, an article from Emiliano Musso titled Geolocalize a device and store coordinates on Webserver.

image
TNWiki Article Spotlight - Geolocalize a device and store coordinates on Webserver

Happy Coding.

Regards,
Jaliya

Wednesday, June 24, 2015

Entity Framework: Running Database Migrations without Visual Studio

When we are using Entity Framework, let’s say you want to run a database migrations on a machine which has no Visual Studio installed. In that kind of a scenario, you have two options.
  • Using SQL Script
  • Using migrate.exe
To show how these can be used, I am creating a console application and there I have the following.
public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
 
public class MyDbContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
}
Now I have enabled the migrations and added an initial migration and updated the database. Now I am adding a new property to Employee class.
public class Employee
{
   public int Id { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public DateTime Birthday { get; set; }
}
Now and I am adding a new migration named “AddedBirthdayToEmployee” and still I have not updated the database.


Using SQL Script

From the development machine which has Visual Studio installed, in the Package Manager Console, we can run the Update-Database command specifying  the –Script argument, so this time the changes will be written to a script rather than applied. Additionally we can specify the SourceMigration and the TargetMigration.
Update-Database -Script -SourceMigration: sourceMigrationName -TargetMigration: targetMigrationName
When you don’t specify a source migration, EF will use the last applied migration and when you don’t specify a target migration, EF will use the latest migration which has been created. For the demo, let’s just run Update-Database –Script command.

image
Result
And I will be prompted with a SQL script.

image
Migration Script
I can save this file, and run this script on the Database itself, so the database will get migrated.

image
Database Updated


Using migrate.exe

The next option is to use migrate.exe. You can find this tool inside {project}\packages\EntityFramework.{version}\tools. Copy migrate.exe to the folder where you have the assemblies. Now from the command prompt navigate to the folder where you have the assemblies along with migrate.exe and run the following command to see all the options of migrate.exe.
Migrate.exe /?
image
migrate.exe Options
You can see you a lot of options there. For the demo, I will just write execute the following command specifying the target connectionString and the connectionProviderName. Please note that /connectionString and /connectionProviderName must be specified together.
Migrate.exe EFMigrationsDemo.exe /connectionString="Data Source=.;Initial Catalog=EFMigrationsDemo.MyDbContext;Integrated Security=True" /connectionProviderName="System.Data.SqlClient"
image
Migrations Applied
You can see the migrations are getting applied and database is updated.

image
Database Updated

Happy Coding.

Regards,
Jaliya

Friday, June 19, 2015

Visual C# Technical Guru - May 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 - May 2015
Happy Coding.

Regards,
Jaliya

Wednesday, June 17, 2015

Wrote a TNWiki Article Spotlight at Official Blog of TechNet Wiki

It's true that Universal Windows Platform (UWP) Apps are getting more and more popular with upcoming Windows 10. But I believe Windows Presentation Foundation (WPF) is still the pioneer technology for creating enterprise applications for Windows.

In TechNet Wiki Ninja’s blog, Tuesday is the day of the week that Wiki Ninjas write a post highlighting a TechNet Wiki article. So In this week’s TNWiki Article Spotlight, I wrote a post highlighting an article about WPF and it has won the April month's TechNet Guru Awards under Windows Presentation Foundation (WPF) Category, an article from Andy ONeill titled Change Tracking.

image
TNWiki Article Spotlight - WPF: Change Tracking
Read the post on,
   TNWiki Article Spotlight - WPF: Change Tracking

Happy Coding.

Regards,
Jaliya

Wednesday, June 3, 2015

Wrote a TNWiki Article Spotlight at Official Blog of TechNet Wiki

Got the pleasure of writing a post in Wiki Ninjas - Official Blog of TechNet Wiki. The title of the post was TNWiki Article Spotlight - Local Files.

In TechNet Wiki Ninja’s blog, Tuesday is the day of the week that Wiki Ninjas write a post highlighting a TechNet Wiki article. In this week I wrote a post about the article that won the April month's TechNet Guru Awards under Visual C# Category, an article from Andy ONeill titled Local Files.

image
TNWiki Article Spotlight - Local Files
Read the post on,
   TNWiki Article Spotlight - Local Files

Happy Coding.

Regards,
Jaliya