Tag Archives: C#5.0

Using external config files in .NET applications


The config file is place where common variables, database connection strings, web page settings and other common stuff are placed. The config file is also dynamic, so you can change the value of the variable in the config file  without compiling and deploying the .NET app. In multi tenancy environment config file can be complicate for deployment, because  for each tenant different value must be set for most of the defined variables. In such a situation you have to be careful to set right value for the right tenant.

One way of handling this is to hold separate config file for each tenant. But the problem can be variables which are the same for all tenants, and also the case where some variables can be omitted for certain tenant.

One of the solution for this can be defining external config files for only connection strings or appSettings variables, or any other custom config section. In this blog post, it will be presenting how to define connection strings as well as appSettings section in separate config file.

Lets say you have appSettings and connectionStrings config sections, similar like code below:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>

	<connectionStrings>
		<add name="SQLConnectionString01" connectionString="Data Source=sourcename01;Initial Catalog=cat01;Persist Security Info=True;Integrated Security=true;"/>
		<add name="SQLConnectionString02" connectionString="Data Source=sourcename02;Initial Catalog=cat02;Persist Security Info=True;Integrated Security=true;"/>
	</connectionStrings>

	<appSettings>
		<clear />
		<!-- Here are list of appsettings -->
		<add key="Var1" value="Var1 value from config01" />
		<add key="Var2" value="Varn value from config01"/>
		<add key="Var3" value="Var3 value from main config file"/>
	</appSettings>

</configuration>

There are three appSetting keys Var1 , Var2 and Var3  and two connectionstrings in the app.config.

The config file above can be split in such a way that variables Var1 and Var2 be defined in separated file, but the Var3 can be remain in the main cofing file. Separate config file may be unique for each tenant.

Now the main config file looks like the following:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>

	<connectionStrings configSource="config\connString01.config"/>

	<appSettings file="config\config01.config">
		
		<add key="Var3" value="Var3 value from main config file"/>
	</appSettings>

</configuration>

In the Visual Studio Solution there is config folder in which we created two config files for appSettings section and two config files for Connectionstrings section, in case we have two separate environments for deployments.

exconfigfile01
The flowing code snippet shows the appSettings section implemented in the external file:

<appSettings file="appSettings.config">

	<!-- Here are list of appsettings -->
	<add key="Var1" value="Var1 value from config02" />
	<!-- ... -->
	<add key="Varn" value="Varn value from config02"/>
</appSettings>

The external config file for connection strings looks similar like the flowing:

exconfigfile02

The simple console application shows how to use this config variables in the code:

static void Main(string[] args)
{
    var var1Value= ConfigurationManager.AppSettings["Var1"];
    var var2Value = ConfigurationManager.AppSettings["Var2"];
    var var3Value = ConfigurationManager.AppSettings["Var3"];
    var conn1 = ConfigurationManager.ConnectionStrings["SQLConnectionString01"];
    var conn2 = ConfigurationManager.ConnectionStrings["SQLConnectionString02"];

    Console.WriteLine("Values from config01.config and connString01.config files");

    Console.WriteLine("Var1={0}",var1Value);
    Console.WriteLine("Var2={0}", var2Value);
    Console.WriteLine("Var3={0}", var3Value);
    Console.WriteLine("ConnStr01={0}", conn1);
    Console.WriteLine("ConnStr01={0}", conn2);

    Console.Read();
}

The complete source code can be downloaded from this link.

Advertisements

Add EULA to ClickOnce Installation using Visual Studio 2015


ClickOnce technology is very smart and useful when you want simple, small and smart piece of software for deploying your Windows Forms or WFP application. This is specially useful if you deliver application which doesn’t require administrator rights during installation. ClickOnce is very powerful if you wants automatic update of your product, you can decide whenever the update appears before or after app is run. Also by using certificate you can deliver reliable and secure product to your customers. Long time ago I wrote detailed blog post  how to make ClickOnce deployment.

But one big thing is missing in ClickOnce deployment and for most of dev community is the feature which should be included by default. The feature which missing is “End User License Agreement” (EULA).  There is no simple way to implement it. Searching the internet I have found one forum post on Microsoft site describing how to implement it. Only way you can get ELUA at the beginning of the ClickOnce installation proces is by using it as prererquested component. Actually you build a redistributable component which would be seen as prerequsites dialog box under the publish window. To build custom prerequisites component you need a three files:

  1. Product.xml. – which is the file for bootstrapper and Visual Studio to show  a component in prerequisites dialog,
  2. Package.xml – which is the file containing all information about the component to be installed,
  3. EULA.txt – your ELUA text for user to accept.

Those three files must be installed in the location where all components are registered: C:\Program Files (x86)\Microsoft Visual Studio 14.0\SDK\Bootstrapper\Packages

For this blog post I have prepare demo sample which look like the following picture:

clickoncelicsl015

As can be seen, there is a two folders and one xml file. Each folder contains two files described earlier. Folders “en” and “de” means we are going to have EULA translated on two languages.

In order to successfully registered perquisites to be visible by Visual Studio we need to define proper content of the product.xml. The following xml code show content of our demo sample:

<?xml version="1.0" encoding="utf-8" ?>

<Product xmlns="http://schemas.microsoft.com/developer/2004/01/bootstrapper" ProductCode="EULA.Bootstrap.Component">
  <!-- Defines list of files to be copied on build -->
  <PackageFiles>
    <PackageFile Name="en/eula.txt"/>
  </PackageFiles>
  <Commands>
    <!-- Open eula.txt without any parameters -->
    <Command PackageFile="en/eula.txt" Arguments='' >
	
	  <!-- These checks determine whether the package is to be installed -->
	  <!-- No install conditions -->
      <InstallConditions>
        
      </InstallConditions>
	  
	   <!-- Exit codes -->
	   <ExitCodes>
        <ExitCode Value="0" Result="Success" />
        <DefaultExitCode Result="Fail" FormatMessageFromSystem="false" String="GeneralFailure" />
      </ExitCodes>

    </Command>
  </Commands>
</Product>

As we can see xml content is self-described, it contains product information, files to be installed, installation conditions and exit codes.

Each folder (en, de, …) contains package.xml file which holds localized messages and list of files to copied on build. The following xml content shows content of our en demo sample:

<?xml version="1.0" encoding="utf-8" ?>
<Package xmlns="http://schemas.microsoft.com/developer/2004/01/bootstrapper" Name="ClickOnceWithLicenseAgreement" Culture="Culture" LicenseAgreement="eula.txt">
  <!-- Defines list of files to be copied on build -->
    <PackageFiles>
        <PackageFile Name="eula.txt"/>
    </PackageFiles>

  <!-- Defines a localizable string table for error messages and url's -->
  <Strings>
    <String Name="DisplayName">ClickOnceWithLicenseAgreement 1.0 (x86 and x64)</String>
    <String Name="Culture">en</String>

    <String Name="CancelFailure">User Refuse to Accept to ClickOnceWithLicenseAgreement End User License Agreement.</String>
    <String Name="GeneralFailure">A fatal error occurred during the installation of ELUA Component Execution</String>
    <String Name="AdminRequired">You do not have the permissions required to install this application.  Please contact your administrator.</String>
  </Strings>    
</Package>

The EULA.txt file contains the text user need to accept in order to install the product.

For this demo we created folder EULAPackage, put product.xml and two folders en and de because we are going to support two installation languages (see picture above).

Copy the EULAPackage folder in to : C:\Program Files (x86)\Microsoft Visual Studio 14.0\SDK\Bootstrapper\Packages

Now we have set all necessary information about ELUA component and can be included in our demo sample.

  1. Open Visual Studio 2015 and create new WFP application.Name it as “ClickOnceWithLicenseAgreement

clickoncelicsl011

2. Right-Click on the Project and select Property menu option, then select Publish tab item of the Project Property window.

clickoncelicsl016

3. Click on Prerequisites Button, then you will see your prerequisite component in the standard prerequisites lists.

clickoncelicsl013

4. Select ClickOnceWithLicenseAgreement component and click Ok button. Afterwards click Publish button to build installation package.

5. Open publish folder from the disk. DoubleClick Setup.exe and the ELUA window should be appeared:

clickoncelicsl014

6. Now user has two choises to accept or Refuse the EULA, which means install or not install the app.

Prerequested demo sample component for EULA can be downloaded from here.

Happy programming.

 

How to convert your old sequential code in to async


There are plenty of ansyc samples over the internet, and most of them are different and not satisfy your requirements. Actually, async pattern depends of its creator, and can be implement on various ways. It is important to understand the async pattern in order to use it. Only on this way, you can stop searching for exact sample you need, and start coding your own async code.  More that year ago, I wrote simple blog post about async pattern (part 1 and part 2) (Bosnian language), and also wrote how to call Entity Framework with async pattern as well.

Today I am going to show you how old synchronous code block convert in to asynchronous. I think it is interesting because async pattern can improve your existing applications on various ways. First of all async pattern can increase responsiveness of  an application, performance, etc.

First of all, create simple Windows Forms sample and implement synchronous code.This will represent our old application, in which we are going to implement new programming paradigm.

1. Create Windows Forms Project, Name it “WinFormsAsyncSample

2. Design your main form (Form1.cs) exactly as picture shows below, and implement events.

As picture shows we have few labels, one text box, one progress bars, and two buttons.

Note: At the end of the blog you can download both versions (nonasync and async) of this sample.

The sample application calculates how many prime numbers exist in range. You need to enter number, press run button. The program starts counting. The progress bars informs user status of counting.

Lets see the implementation of runBtn_Click event:

private void btnRun_Click(object sender, EventArgs e)
{
    if(!int.TryParse(textBox1.Text,out m_number))
        m_number= 1000000;

    textBox1.Text = m_number.ToString();
    progressBar1.Maximum = m_number;
    progressBar1.Minimum = 0;
    progressBar1.Value = 0;

    //call start calculation
    startCounting();
}

At the beginning of the btnRun_Click we prepare progressBar, and also convert text from textbox in to int type.At the end of the function startConting method is called. Here is the source code of the method:

private void startCounting()
{
    int counter=0;
    for(int i=2;i<m_number; i++)
    {
        bool retVal= IsPrime(i);
        progressBar1.Value++;
        if (retVal)
        {
            counter++;
            label3.Text = "Result is: " + counter.ToString();
        }
    }
}

The method is very simple. It iterates from 2 to specified number by calling helper method IsPrime (see source code of the blog post) to check if certain number is prime. Then the method increased the counter variable and tried to update label about current count value.  If  you run the sample and press run button, you can see that the application is not responsive on user input, and represent classic sequential, synchronous single thread application.

Now I am going to show how this implementation can be converted in to async with minimum code changes.We are going to change only startCounting method, other code will remain the same. Explanation is divided in only 3 steps, which is enough to convert our code in to full async pattern.

  • Put async keyword right after public modifier of startCounting method.

Explanation: Every method which implements async patter needs to be decorated with async.

  • Put sequential implementation in to Task action, and wait.

Explanation: With this, you define a Task object which will run the code without blocking main thread. The simplest implementation is the following:

private async void startCalculation()
{
    var task = new Task(() =>
        {
            int counter = 0;
            for (int i = 2; i < m_number; i++)             {                 bool retVal = IsPrime(i);                 this.Invoke((Action)(()=>
                {
                    progressBar1.Value++;
                    if (retVal)
                    {
                        counter++;
                        label3.Text = "Result is: " + counter.ToString();
                    }

                }));
            }
        });

    task.Start();
    await task;
}

Now if you run the sample, you have fully asynchronous implementation. Main thread is free and can receive user input. So this is the simplest way how to convert your sync code in to async. This is the case when Task object create another thread in order to execute the code. That’s why we called this.Invoke method in order to set controls properties progressBar.Value and label3.Text. Everything else remain the same as in previous implementation.

  • Create global variable of type CancellationTokenSource and call Cancel method from Cancel Event handler.

Explanation: On this way we can cancel counting at any time.With this case we need to implements extra code in our previous implementation like the following.

private async void RunProces()
{
    if (m_IsRunning)
        return;
    m_IsRunning = true;
    int counter=0;
    if (m_ct != null)
    {
        m_ct.Dispose();
        m_ct = null;
    }
    m_ct = new CancellationTokenSource();

    var task = new Task(() =>
        {
            for (int i = 0; i < m_number; i++)             {                 bool retVal = IsPrime(i);                 this.Invoke((Action)(()=>
                {
                    progressBar1.Value++;
                    if (retVal)
                    {
                        counter++;
                        label3.Text = "Result is: " + counter.ToString();
                    }

                }));

                if (m_ct.IsCancellationRequested)
                {
                    m_IsRunning = false;
                    return;
                }
            }
        }, m_ct.Token);

    task.Start();
    await task;
}

With the last code implementation you have full of async patter in yur old application.

In this blog post I have tried to explain as simple as possible the way how you can convert you old sync code in to new async programming pattern.

Source code sample used in this blog post:

On this link you can find sequential version of the sample.

On this link you can find the final solution of async pattern.


					

Developing Windows Store App Part 1: Database Model


This is the first of several blog posts about developing Windows 8 Store app. The first blog post will show how to implement database model which will be used in our application. If you want to get more information about the application we are developing please see the previous announcment post. Before we start with the tutorial, several requirements must be satisfied:

1. You need to have installed at least Visual Studio 2012 Express

2. You need to have at least SQL Server 2008 or 2012 Express.

Our database model is very simple. We have three tables: Places, Dishes and Towns. Relation of those tables shows the picture below.

SQL database will also be provided by the end of the blog post. Now that we have database model on the paper, we can start with implementation. We will use Entity Framework 5, and Code First technology in order to implement db model.
Start Visual Studio 2012, choose File->New->Project. Choose ClassLibrary similar as picture below.

After we created the empty Class Library project, we can start with implementation of the entities. According to db model shoed earlier, we are going to create three .NET classes: Dish, Town, Place. In order to do that:

  • Right Click at the Project
  • Add New Class
  • Give name: Dish

Repeat the process for Town and Place. Text below shows the implementation of classes.
Town class:

public partial class Town
{
public int? TownID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Image { get; set; }
//relation 0-oo
//many places can be in one Town
public ICollection Places { get; set; }
}

Dish class:

public partial class Dish
{
    public int? DishID { get; set; }
    public string Name { get; set; }
    public string Slogan { get; set; }
    public string Description { get; set; }
    public string Image { get; set; }
    //relation 0-oo
    //many places can have one dish
    public ICollection<Place> Places { get; set; }
}

Place class:

public partial class Place
{
    public int? PlaceID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int? DishID { get; set; }
    public string Slogan { get; set; }
    public string Type { get; set; }
    public int? TownID { get; set; }
    public string Image { get; set; }
    //one relation to Dish
    public Dish PlaceDish { get; set; }
    //one relation to Dish
    public Town PlaceTown { get; set; }
}

Since we are using Code First, we need to specify the relation between entities too. That’s why we have put the last two properties in Place class, and also IColletion property of the previos classes. This is enough information that Code First make relation between tables on SQL Server.  By default PlaceID is primary key for Place table, as well as DishId and TownID for corresponded tables.
Now that we have entities, we need to implement DBContex, central class for handling all operation and transaction against database. Before we implement DBContext we need to add Entity Framework reference. Since EF is separated from the .NET we can use NuGet to accomplish this.
1. Right click on Reference, choose Manage NuGet package

In Search box type: Entity Framework and hit enter. Package will appear in the list. Click Install button. Picture below shows Manage NuGet Package dialog. Accept license agreement, and close the dialog.

CExplorer DataContext class:

public class CExplorerContext: DbContext
{
    public CExplorerContext() : base("cexplorer_db")
    {
        Configuration.LazyLoadingEnabled = false;
    }

    //entity sets
    public DbSet<Place> Places { get; set; }
    public DbSet<Dish>  Dishes  { get; set; }
    public DbSet<Town>  Towns  { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //crating one to many relation between Town and Place
        modelBuilder.Entity<Place>()
            .HasRequired(x => x.PlaceTown)
            .WithMany(d => d.Places)
            .WillCascadeOnDelete(true);

        ////crating one to many relation between Dish and Place
        modelBuilder.Entity<Place>()
            .HasRequired(x => x.PlaceDish)
            .WithMany(d=>d.Places)
            .WillCascadeOnDelete(true);

        base.OnModelCreating(modelBuilder);
    }
}

As you can see, we have overridden ModelCreation virtual method and implement relation between entities. This is classic one to many relation.

At the end of the implementation, we need to provide connection string to SQL Server, it must be with the same name as we specified in the implementation od the DBContext.

1. Add New Item: App.config file and put the following configuration.

Based on SQL instance name, change the connection string. Database could not exist on the SQL server. If there is a database on the SQL with the same name, EF will add table in to existing database.

Before we end the today’s post, lets quickly create Console Test application to make sure we implemented correct model.

1. File->New->Add New Project
2. Console Application

Like previous add Entity Framework by NuGet.
Add reference of EFModel.
Open Program.cs and put the following implementation:

class Program
{
    static void Main(string[] args)
    {

        CExplorerContext ctx = new CExplorerContext();

        var dish = new Dish() { DishID = 1, Description = "Description", Name = "DishName", Slogan = "Slogan", Image = "Default.jpg" };
        var town= new Town(){TownID=1, Name= "TownName", Description="Description", Image=""};
        ctx.Dishes.Add(dish);
        ctx.Towns.Add(town);
        ctx.SaveChanges();
        var place = new Place() { PlaceID = 1, Name = "Place Name", Description = "DEscription", Image = "default.jpg", Slogan = "Slogan title", DishID = 1, TownID = 1 };
        ctx.Places.Add(place);
        ctx.SaveChanges();

        var plc = ctx.Places.FirstOrDefault();
        Console.WriteLine("Place from Database");
        Console.WriteLine("Place from database Name:{0}", plc.Name);
        Console.Read();

    }
}

After we run, output console shows that the entities are inserted successively on database.

In other words Cexplorer_DB database is created on the SQL server, and entities are inserted from the test.

Code First approach is very powerful, we only need to specified connection string, and everything is created just like we do, in Model First approach.  Complete source code for this Demo can be found here.

MSCommunity BiH Session: Developing Windows Store LOB apps


After great 3 days of KulenDayz and CEE MVP Summit in Baranja (north-east part of Croatia), the next conference I will be speaking is MSCommunity BiH konferencija in Sarajevo.
For the first time, Microsoft Community in Bosnia and Herzegovina is organizing the event dedicated for launching new Microsoft products Windows 8, Windows Server 2012 and Visual Studio 2012. For this conference I prepared a session about developing Windows Store LOB apps. This presentation has a lot of cool demos integrated in to one app called ĆevapExplorer.
Through the session I will be presenting how to design Windows Store app, by describing main design requirements of each WinStore app. Beside design feature, Win Store app requires data and connection to data source. Through the demo it will be presenting how to develop data model by using the latest Microsoft ORM Entity Framework V5.
After DB model is implemented, we need some way to provide data to Windows Store app. Windows Store app is running in some kind of isolated storage provided by Windows Run-Time, so there is no way to connect EF model directly to Win Store app. The only way to provide EF data to Win Store app is by implementing some kind of web service (REST or WCF in our case).
The second part of the demo will be presenting how to implement WCF service by using the latest version of the .NET 4.5 and WCF 4.5. If you want to develop lighter service infrastructure, beside WCF, you can use ASP.NET Web API to implement RES service.
The further demo will be presenting how to implement REST service that will be used by Win Store app. Implementation of REST service by using ASP.NET Web API is very popular MS Technology today, and it is recommended for developing this kind of services.
After backend infrastructure is presented, the main demo can starts using data of EF Model through REST or WCF service. In the first part of the main demo it will be presenting how to develop UI for presenting data, by describing how to use predefined visual studio 2012 templates, how to use HttpClient and how to integrated our app with Windows 8, by implementing Windows 8 contracts. By implementation Search Contract, demo will show how to integrate Windows 8 Search mechanism in to our app.
As the last part of demo, it will be presenting how to implement data source without using .NET infrastructure, but using only WinRT. For this we will use SQLite library. SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. SQLite is the most widely deployed SQL database engine in the world. Because of native support of WinRT, this library can be easily compiled and built in Windows RunTime, so we used it as a C/C++ class library in our C# WinStore app. This part of demo present how to used native nature of WinRT to use C/C++ library in our C# application, without complex implementation seen in .NET with P/Invoke and DLL Import.

Because of importance of accepting new Windows 8 develop technology in the future development, this blog post is part of several post which will give detail information about each mentioned part of the demo. Each blog post will be describe in form of tutorial one part of the demo. The name of demo is ĆevapExplorer. Ćevap stands for the most populate Bosnian national dish which can be found in every restaurant, but only few of them serve the best Ćevap. The application is collecting data about the best restaurants around the Bosnia not only for Ćevap, but the main Bosnian dishes. The app present location about restaurants serving the best dish.
After conference event, blog post will be published periodicaly.
See you in Sarajevo.

With .NET 4.5, 10 years memory limit of 2 GB is over


There are numerous new features coming with .NET 4.5 and here, on this blog, you can find several posts about it. But the feature we are goint to talk about today is very exciting, because we were waiting for it more than 10 years. Since .NET 1.0 the memory limit of .NET object is 2GB. This means you cannot for example create array which contains elements with more than 2GB in total. If try to create such array, you will get the OutOfMemoryException.
Let’s see an example how to produce OutOfMemoryException.

Before that Open Visual Studio 2012, and create C# Console Application, like picture below.

First lets create simple struct with two double members like example below:

public struct ComplexNumber
{
    public double Re;
    public double Im;

    public ComplexNumber(double re,double im)
    {
        Re=re;
        Im=im;
    }

}

As we know this structure consumes about 16 bytes of memory.  So if we want to create array of this type which consume more than 2GB we need to create array at least with 134217728 instances. So this sample program below creates 130000000 (about 1,97 GB) of array.

int maxCount = 130000000;
ComplexNumber[] arr=null;
try
{
    arr = new ComplexNumber[maxCount];

}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

So if we run this sample program the output will be like picture below:

Let’s try to create 140000000 instances. This is about 2.08 GB. The output produces exception:

The new feature of .NET 4.5 allows to create object beyond this magical number. To enable creation of object more than 2 GB, you only need to set proper variable in configuration file. The new gcAllowVeryLargeObjects
Element enables creation of array that are greater than 2 gigabytes (GB) in total size on 64 bit platform.  So the following configuration file allows us to create more that 140000000 instances of our sample.

Now,If we run our sample the output is:

Ok how about to create more than 3GB of instances. For that propose, we need to create at least 201326592 instances. If we include this number in our sample the output is:

Be careful with this feature, because it will suck all your computer memory.

This feature works only with 64bit OS, it will not work with 32 bit.

Before you use this feature please see official description, because it contains some limitation which you must know before you use.

Complete source code for this blog post can be downloaded from here.

Happy coding with .NET4.5

New feature in C# 5.0 – [CallerMemberName]


By releasing the beta version of Visual Studio 11 and .NET 4.5, Microsoft has also released the new version C# 5.0. C# 5.0 brings a new programming pattern called asynchronous programming with new keyworkds async an await. I have blog posted about it previously. C# 5.0 also brings new features which accelerate development specialy when you implementing bindable properties, and need to put OnPropertyChanged with property name as an argument in each setter block.

C# 5.0 introduce [CallerMemberName] attribute which you can put as an agrument of the method. It is very strange syntax for C# but very efficient. For example:

/// <summary>
/// Notifies when the property is changed
/// </summary>
/// <param name="propertyName">New Features in C# 5, that you can easely skip writing string of property name.</param>
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    //whatever you need to be called
}

The method above you can call in the following situation:

public string SomeProperty
{
    get
    {
        return _someProperty;
    }
    set
    {
        if (value != _someProperty)
        {
            _someProperty = value;
            //You dont need to pass string of the propertyname, compiler will do for us.
          //OnPropertyChanged("SomeProperty"); - no need any more
            OnPropertyChanged();
        }
    }
}

What hepends behind the scene is that the c# compiler resolve your property name and put on the right place. If you dont beleive  you can see the picture which has taken during the debuging:

The whole example is listed here.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace NewFeatureCsharp
{
class Program
{
    static void Main(string[] args)
    {

        SomeClass someClass = new SomeClass();

        someClass.SomeProperty = "Hello World";

        Console.ReadKey();
    }

    public static void CallAfterPropertyChanged()
    {
        Console.WriteLine("Property is changed!");
    }
}

/// <summary>
/// Class example with propertychanged
/// </summary>
public class SomeClass : INotifyPropertyChanged
{
    private string _someProperty;
    /// <summary>
    /// This is property with automatic implementation of getter and setter, but in C# 5.
    /// This is also automatic implermentation of propertychanged notification as well.
    /// </summary>
    public string SomeProperty
    {
        get
        {
            return _someProperty;
        }
        set
        {
            if (value != _someProperty)
            {
                _someProperty = value;
                //You dont need to pass string of the propertyname, compiler will do for us.
                OnPropertyChanged();
            }
        }
    }

    /// <summary>
    /// Notifies that the property is changed
    /// </summary>
    /// <param name="propertyName">New Features in C# 5, that you can easely skip writing string of property name</param>
    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        Program.CallAfterPropertyChanged();
    }
    public event PropertyChangedEventHandler PropertyChanged;
}
}

And output result is the following: