Καλώς ορίσατε στο dotNETZone.gr - Σύνδεση | Εγγραφή | Βοήθεια

C# and .NET Tips and Tricks

Quests in programming in .NET

Παρουσίαση με Ετικέτες

Porting a WPF application to Windows8

That is, our class implements the INotifyPropertyChanged interface and also raises the notification for the “Description” property whenever the Id or the Name properties are changed in order for the Listbox contents (databound to Description) to be refreshed. Our ViewModel for the application is as follows:

 

public class MainWindowViewModel : INotifyPropertyChanged
{
   private List<Client> _clients;
   public List<Client> Clients
   {
      get { return _clients; }
      set { _clients = value; 
         if (PropertyChanged != null) 
             PropertyChanged(this, new PropertyChangedEventArgs("Clients")); }
    }
    private Client _selectedClient;
    public Client SelectedClient
    {
       get { return _selectedClient; }
       set { _selectedClient = value; 
          if (PropertyChanged != null) 
              PropertyChanged(this, new PropertyChangedEventArgs("SelectedClient")); }
     }
     public MainWindowViewModel() {}
     public void Validate() {
        if (SelectedClient != null) {
           if (String.IsNullOrWhiteSpace(SelectedClient.Name))
              MessageBox.Show("Name cannot be empty for client");
           else
              MessageBox.Show("All ok");
        }
     }
     public event PropertyChangedEventHandler PropertyChanged;
}

 

Again, the ViewModel implementes the INotifyPropertyChanged interface and has the Clients property which will be databound to the ItemSource of the Listbox and the SelectedClient property which will be databound to the SelectedItem of the Listbox and to the detail Textboxes at the bottom of the window. Moreover, it provides the Validate method for validating the results. The XAML file describing the UI of the window is as follows:

 

<Window x:Class="AskADev.Article1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Demo WPF porting to Windows8" Height="400" Width="544" Loaded="Window_Loaded">
    <DockPanel>
        <Canvas DockPanel.Dock="Bottom" Height="100" Background="Beige">
            <TextBlock Text="Id" Canvas.Left="6" Canvas.Top="12" />
            <TextBox Text="{Binding SelectedClient.Id}" Canvas.Left="79" 
                                                        Canvas.Top="9" Width="72" />
            <TextBlock Text="Name" Canvas.Left="6" Canvas.Top="40" />
            <TextBox Text="{Binding SelectedClient.Name}" Canvas.Left="79" 
                                                          Canvas.Top="37" Width="311" />
            <Button x:Name="ButtonSubmit" Height="31" Width="73" Canvas.Left="443" 
                   Canvas.Top="63" Click="ButtonSubmit_Click">Validate</Button>
        </Canvas>
        <ListBox DockPanel.Dock="Top" ItemsSource="{Binding Clients}" 
                 SelectedItem="{Binding SelectedClient}" DisplayMemberPath="Description"/>
    </DockPanel>
</Window>

 

Where you can see the data bound properties. Finally the XAML.cs file initializes the ViewModel, attaches it to the DataContext and also provides the event handler for the button:

 

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    ViewModel = new MainWindowViewModel();
    DataContext = ViewModel;
}
private void ButtonSubmit_Click(object sender, RoutedEventArgs e)
{
   ViewModel.Validate();
}
 

We compile this and run it on a Windows7 machine and it runs correctly. Now we start the Windows8 Virtual Machine (instructions on how to install Windows8 on your desktop can be found in this post), get the executable we have created and run it on Windows8 “as is”:

image

Obviously, as expected, the application runs without any problems. But it runs on “Desktop” mode, while we want to make it run on the nice new Metro-Style UI. We open Visual Studio 2011 from within Window8 and select New Project/Templates/Visual C#/Windows Metro Style/Application:

image

The windows in this project template are more “Silverlight” like having as their root content a UserControl and not a Window. Therefore we leave the root declaration intact and copy/paste the inner contents of the original XAML.cs file. The changes we need to make are as follows (all changes are characterized as major/moderate/minor based on the time it will take you to make the changes in a full blown WPF app):

 

  • 1 (moderate) The Window must be converted to UserControl.
  • 2 (major) The “Dockpanel” is not supported (which is kinda expected since we will have a fixed size full screen application) and therefore we change it to a “Canvas” layout.
  • 3 (major) The default mode for the binding in now “One Way”. Therefore we need to specify the binding explicitly to “TwoWay”.
  • 4 (major) Textboxes get enlarged in the new “Metro” style (since they are intended for touch UIs) therefore we need to increase the spacing between the Textboxes (add approximately 10pixels). Of course if we had initially used a Stackpanel for the placement of our controls this would not be needed (good design always handles change more easily Smile)
  • 5 (minor) We need to change the colors to reflect the new style (I chose darker shades)

 

The new XAML is as follows (changes in yellow):

 

<UserControl x:Class="AskADev.Article1.Windows8.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" Loaded="Window_Loaded"
    d:DesignHeight="768" d:DesignWidth="1366">

    <Canvas>
        <Canvas Canvas.Top="668" Width="1366" Height="100">
            <TextBlock Text="Id" Canvas.Left="6" Canvas.Top="12" />
            <TextBox Text="{Binding SelectedClient.Id,Mode=TwoWay}" 
                     Canvas.Left="79" Canvas.Top="9" Width="72" />
            <TextBlock Text="Name" Canvas.Left="6" Canvas.Top="50" />
            <TextBox Text="{Binding SelectedClient.Name,Mode=TwoWay}" 
                     Canvas.Left="79" Canvas.Top="47" Width="311" />
            <Button x:Name="ButtonSubmit" Height="31" Width="73" Canvas.Left="443" 
                    Canvas.Top="63" Click="ButtonSubmit_Click">Validate</Button>
        </Canvas>
        <ListBox Background="Black" Foreground="White" Width="1366" Height="668" 
                 ItemsSource="{Binding Clients}" 
                 SelectedItem="{Binding SelectedClient,Mode=TwoWay}" 
                 DisplayMemberPath="Description"/>
    </Canvas>
</UserControl>
 

The XAML.CS file (apart from some minor changes in the name) remains the same.

Finally, the ViewModel’s file is added as is to the application. The issues that we encounter here are the following:

 

  • 6 (major) The MessageBox is not supported. Therefore you will need to find another way to inform your users about the result (probably from within a special place of the UI). In this app we will just comment it out and do nothing. In real life we would have to change the UI to have a “Messages” area.
  • 7 (minor – but annoying until you discover it) Your application will compile if you leave the INotifyPropertyChanged interface to be defined in the System.ComponentModel assembly as it is for WPF. But the binding will not work! You need to replace the “using System.ComponentModel” statement with “using Windows.Ui.Xaml.Data” which also defines the INotifyPropertyChanged interface and the bindings will magically work!

 

We recompile and run the up and we are in “Metro”!

image

 

Shout it

Posted: Τετάρτη, 19 Οκτωβρίου 2011 6:18 μμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία: ,
A first encounter with Windows8 Development (C#, XAML, JavaScript)
Yesterday I have watched the Keynote speech presenting to developers around the world the new Windows8 development ecosystem. And in my opinion the basic idea on what is going to happen, which programing skills we need to master and what we can carry with us from the .net world is summarized in the following basic figure:
 
image
 
In this figure with light-blue we have the “old” paradigm and with light-green the “new” one. And as I see it in this “new” era XAML is there, C# is there and also HTML5 and JavaScript are now more “natively” supported, being two more than welcome additions to the picture. So if I tried to summarize the awaited change I would say: a new underlying API (WinRT) that understands more developers and provides richer functionality out-of-the-box along with a big set of new UI interaction ideas at the hands of the developer. Of course there are hundreds of features in this new ecosystem for the developer to harness and master but this for me is the general idea. Myself being a WPF enthusiast I was happy to see that XAML is still there and also the fact that VS 2011 and Expression Blend are the two IDEs that will handle the development workload for the developer. Having said that I wanted to get a “hands-on” experience on how it is to develop in this new ecosystem.
 
So in order to have some insight I have installed Windows8 on a virtual machine and tried to implement a very basic app in C# , XAML and then in JavaScript using VS2011 and Expression Blend 5. Below are my first thoughts/encounters/guidelines on how this can go:
 
Installing Windows8
Initially go ahead and download the .iso image for the Windows8 Developer preview from this link. Download the 64bit edition with VS2011 and Expression Blend 5. My approach then was to download VirtualBox from this link ,install it and then do the following:
Run VirtualBox, select New, name the VM Windows8, select Microsoft Windows as your OS and Windows 7 64bit as the OS Version. Specify that the VM will use 4GB of memory and create a virtual HDD of fixed size of at least 30GB. Once the VM is created mount the .iso you have downloaded and Windows8 will be up and running in no time!
 
Developing the Unit Converter in Windows 8 (XAML + C#)
At that point I was ready for development. I switched to Desktop in Windows8 and started VS 2011. We will create a simple Unit Converter in XAML,C# so we select Visual C#/Windows Metro Style/Application:
 
image
 
The first thing to notice is that the files created for us in the project are well known to the WPF/Silverlight enthusiasts. The usual XAML, XAML.CS files are holding the UI graphics and the code-behind file that supports its operations:
 
image
 
Trying to run Expression Blend 5 and open the project got me an error that “EB does not support the Target Framework” and therefore UI design will be performed only in VS 2011. I suppose this is due to the early stage of these tools. The UI to create is as follows:
 
image
 
The XAML has a canvas element for the basic layout which is as follows:
image
 
And a sample of the event handler of a button at the XAML.cs file is as follows:
 
image
 
One thing I realized is that apart from some small issues (I could not find the MessageBox class to display a modal Message Window), the code is exactly the same for WPF and Windows8.Of course this is a small example and therefore the likelihood of finding big differences is small. But it felt like I was developing in WPF and this is the most important thing.
I have built and run the application and got the following result along with the fact that the app appeared on the Windows8 ecosystem (the one with the star) having its own box shape!
 
image image
The code of this project can be downloaded
The project does not open in VS 2010 and therefore if you want to see it outside of VS 2011 use a simple text editor.
 
Developing the Unit Converter in Windows 8 (JavaScript)
Then I thought of trying to implement the same thing using JavaScript. Therefore I have created a new VS project but now I selected(JavaScript/Windows Metro Style/Blank Application):
 
image
 
The project is created for us and we see the following:
 
image
 
This is pretty much what we would expect from a HTML5+JavaScript application. The good thing is that Expression Blend works with these projects and therefore we can create the UI there. I have experienced some issues when moving the elements with the mouse around but I am not sure whether those were caused by EB or by the fact that the OS was running on the VM. Additionally I did not find any Designer for html from within VS2011. Below a screenshot of Expression Blend with the new app opened.
 
image
I wrote the following simple code in default.html:
 
image
 
Which is pretty much the same application with the one I have developed in XAML+C#. I again run the project and the Unit Converter (JavaScript) version run smoothly in Windows8 and got its own box in the main screen!
 
image
The JavaScript version of the project can be downloaded
 
I conclusion I would say that having the knowledge of both technologies, I did not have any problems adapting to the new tools. XAML is well supported (or will be I suppose in EB) as it is today and I was impressed by the way those tools started to support the HTML5+JavaScript languages. Of course this is a today’s draft study. I hope I can be more elaborate on those in the future.

Shout it

ASP.NET MVC HTML5 Before and After: The “semantic” markup of HTML5

In this series of posts, we are going to implement a simple website using ASP.NET MVC initially in HTML4 and demonstrate what changes and why in HTML5 for exactly the same implementation.

 

Featuring in this post: The semantic markup/value of HTML5 In this post, we see how the new semantics of HTML5 alter the HTML generated for the homepage of a simple site and why this is important. Imagine you want to implement a website that every day displays a special offer of some kind. In our example, the site is featuring a special offer for a place to go for the weekend. The homepage is as follows:

 

image

 

That is, you have your header where the company’s logo and tagline are displayed (yellow area), a left area where you have some sponsored banners and exactly below an area with previous offers (orange area), your main page where you show the current offer (green area) and the footer with a small navigation menu and information on the site’s creators (white area at the bottom).

Imagine that you have a view model of the following form:

public class HomePageViewModel
{
public Offer CurrentOffer { get; set; }
public IEnumerable<Offer> PreviousOffers { get; set; }

public string BannerImage1File { get; set; }
public string BannerImage1Link { get; set; }

public string BannerImage2File { get; set; }
public string BannerImage2Link { get; set; }
}

The view model consists of the featured offer (the current one) along with a list of the previous offers. Moreover, it has the link and the image file path of the two banners on the left of the homepage. Each offer is represented by an object of the class Offer which has some basic properties related to is such as the Title, Description, Date, Initial price etc. An object of type HomePageViewModel is returned in your “Index” Action of the “Home” controller and is being rendered in the View (Index.cshtml) using Razor. Prior to HTML5 your _Layout.cshtml file defining the main areas of your website as described above would be as follows (body part):

<body>
<div id="container">
<div id="header">
<img style="float:left;width:100px;height:100px" alt="Site Logo" src="../../Images/SiteLogo.png" />
<div style="float:left">
<h1>Good Deals!</h1>
<h4>tagline</h4>
</div>
</div>

<div id="mainContent">
<div id="leftArea">
@RenderSection("LeftArea",false)
</div>
<div id="mainArea">
@RenderBody()
</div>
</div>

<div id="footer">
<div id="menu">
Home | Previous Offers | About | Join us
</div>
&copy; 2011 - Ioannis Panagopoulos - HTML5 Demo Series from
<a href="http://www.progware.org">http://www.progware.org</a>
For more information call: 210666666666
</div>
</div>
</body>

(a visual representation of the site’s structure can be found at the end of the post)

That is, you have each one of the areas defined with a div element carrying a unique id so that you can apply positioning and styling rules through the Site.css file. This is the pretty straightforward approach of developing the visual structure of the homepage of the website. Similarly, the view template for the homepage (Index.cshtml - a strongly-typed View using the HomePageViewModel object returned from the Index action) is as follows (sections only displayed here):

 

@section LeftArea
{
<a href="@Model.BannerImage1Link"><img alt="Ad1" src="@String.Format("Images/{0}", Model.BannerImage1File)" width=170 height=100 /></a><br />
<a href="@Model.BannerImage2Link"><img alt="Ad2" src="@String.Format("Images/{0}", Model.BannerImage2File)" width=170 height=100 /></a><br />
<h1>Previous Deals</h1>
@foreach (var PrevDeal in Model.PreviousOffers)
{
<h2>@PrevDeal.Title</h2>
<img alt="Deal" src="@String.Format("Images/Places/{0}", PrevDeal.RelativePhotoPath)" width=100 height=60 /><br />
@:from: <p>@PrevDeal.InitialPrice.ToString("C")</p>
@:to: <p>@PrevDeal.Price.ToString("C")</p>
@Html.ActionLink("View", "Index", "Offer", new { Id = @PrevDeal.Id }, null)
}
}

<h1>Current Deal!</h1>
<h2>@Model.CurrentOffer.Title</h2>
<img alt="Deal" src="@String.Format("Images/Places/{0}",Model.CurrentOffer.RelativePhotoPath)" width=300 height=180 /><br />
<p>@Model.CurrentOffer.Description.Substring(0, 100)+"..."</p>
from: <p>@Model.CurrentOffer.InitialPrice.ToString("C")</p>
to: <p>@Model.CurrentOffer.Price.ToString("C")</p>
posted on: <p>@Model.CurrentOffer.Date.ToShortDateString() time: @Model.CurrentOffer.Date.ToShortTimeString() </p>
@Html.ActionLink("View","Index", "Offer", new { Id = @Model.CurrentOffer.Id },null)

 

As you may have already realized, all the divs and ids of the divs, are strictly for display-rendering purposes. The HTML of the page does not give any indication whatsoever on the “meaning” of each area of the page. Any crawler or automated process visiting our site will not be able to deduce anything for the content. HTML5 introduces tag elements to use in the place of the divs that have more “semantic” meaning. Therefore the main objective of this post is the replacement of the divs of the page with HTML5 tag elements that give a meaning to the content apart from the strict visual arrangement governing the use of divs in HTML4.

 

So, the first key element of HTML5 is learning this new semantic markup and using it appropriately. And this is exactly what we will do. Actually, the first thing is changing the header of the site enclosed in a div with id=header to the following:

<header class="mainSiteHeader">
<img style="float:left;width:100px;height:100px" alt="Site Logo" src="../../Images/SiteLogo.png" />
<hgroup style="float:left">
<h1>Good Deals!</h1>
<h4>tagline</h4>
</hgroup>
</header>

As you see we define in markup that this is the header of the site (tag header) and within we define the logo and tagline as a group accompanying the header (tag hgroup). In other words we have given semantic information for the header content of our website.

Considering now the main content, we see that there are three semantic sections. One that contains the main offer, one that contains previous offers and one that comprises of the banners. In HTML5, semantic areas are defined with “section” tags. Individual pieces of information within the same section (such as each offer in the previous offers section) are defined with “article” tags. Each article can also have a header and sections. Finally since the area of the two banners is not directly related to the content of the website in HTML5 it should be enclosed within an “aside” tag. The footer of the homepage in HTML5 has its own “footer” tag and the navigation menu is enclosed in “nav” tags. Finally, note that some specific information such as the date of the offer are semantically defined  with specific HTML5 tags such as the “time datetime” tag.

 

The new _Layout.cshtml, using HTML5 markup is as follows:

<body>
<div id="container">
<header class="mainSiteHeader">
<img style="float:left;width:100px;height:100px" alt="Site Logo" src="../../Images/SiteLogo.png" />
<hgroup style="float:left">
<h1>Good Deals!</h1>
<h4>tagline</h4>
</hgroup>
</header>

<section class="mainContent">
<section class="leftArea">
@RenderSection("LeftArea",false)
</section>
<section class="mainArea">
@RenderBody()
</section>
</section>

<footer>
<nav>
Home | Previous Offers | About | Join us
</nav>
&copy; 2011 - Ioannis Panagopoulos - HTML5 Demo Series from <a href="http://www.progware.org">http://www.progware.org</a>
For more information call: 210666666666
</footer>
</div>
</body>

And the Index.cshtml which works with the same controller but with HTML5 markup is as follows:

@section LeftArea
{
<aside>
<a href="@Model.BannerImage1Link"><img src="@String.Format("Images/{0}", Model.BannerImage1File)" width=170 height=100 /></a><br />
<a href="@Model.BannerImage2Link"><img src="@String.Format("Images/{0}", Model.BannerImage2File)" width=170 height=100 /></a><br />
</aside>
<section>
<header class="sectionHeader"><h1>Previous Deals</h1></header>
@foreach (var PrevDeal in Model.PreviousOffers)
{
<article>
<header class="sectionHeader">
<h2>@PrevDeal.Title</h2>
</header>
<img src="@String.Format("Images/Places/{0}", PrevDeal.RelativePhotoPath)" width=100 height=60 />
<br />
from: <p>@PrevDeal.InitialPrice.ToString("C")</p>
to: <p>@PrevDeal.Price.ToString("C")</p>
@Html.ActionLink("View", "Index", "Offer", new { Id = @PrevDeal.Id }, null)
</article>
}
</section>
}
<header><h1>Current Deal!</h1></header>
<article>
<header class="sectionHeader">
<h2>@Model.CurrentOffer.Title</h2>
</header>
<img alt="Deal Image" src="@String.Format("Images/Places/{0}",Model.CurrentOffer.RelativePhotoPath)" width=300 height=180 /><br />
<p>@Model.CurrentOffer.Description.Substring(0, 100)+"..."</p>
from: <p>@Model.CurrentOffer.InitialPrice.ToString("C")</p>
to: <p>@Model.CurrentOffer.Price.ToString("C")</p>
posted on: <time [email protected]("yyyy-MM-dd") pubdate>@Model.CurrentOffer.Date.ToShortDateString() </time> time:<time>@Model.CurrentOffer.Date.ToShortTimeString()</time> </p>
@Html.ActionLink("View","Index", "Offer", new { Id = @Model.CurrentOffer.Id },null)
</article>

Graphically in HTML4 the structure of the site was defined as follows:

 

image

 

And after with HTML5:

image

The two sites with the help of styling with .css are visually the same but the second in HTML5 carries a lot more semantic information.

 

The first step for making  an ASP.NET MVC site using HTML5 is searching for the new HTML5 semantic tags and introducing them to your Views where appropriate. You will find a lot of sites in the web describing which are those new tags and where it is appropriate to use them in your page.

Shout it

Posted: Σάββατο, 25 Ιουνίου 2011 8:16 πμ από iwannis | 2 σχόλια
Δημοσίευση στην κατηγορία: ,
Inversion of Control (IoC) and Dependency Injection (DI) and why they are important.

In this blog post, we are going to see how and when  Dependency Injection (DI) and Inversion of Control(IoC) can be applied for writing nice and maintainable code. Note that although there are plenty of tools out there that give you the ability to apply DI out of the box, in this post we are going to implement such a tool on our own gaining valuable insight on the workings of IoC and DI.

 

Suppose that in your code you have two classes (A,B) like the following:

public class A
{
public A(){}
public void Method1(){ }
public void Method2() { }
}

public class B
{
private A _a;
public B()
{
_a = new A();
_a.Method1();
_a.Method2();
}
}

 

That is, we have a class A that has two methods and class B that has a field of type A which is initialized and used in the constructor. Whenever we have such situation we say that “B depends on A” since B needs to create and use A directly. Also, B “has the control” of the creation of A. We will show that dependency graphically with an arrow as follows:

 

image

 

If you implement a new class A1 with the same functionality as A and want to use A1 in B, then you would need to change in B the type of field _a to A1 and its instantiation and recompile the project. If you use A only in one class in your program and your program is a single .exe file (no .dlls) then the merits of IoC cannot be shown and in my opinion you may introduce an unnecessary overhead if you apply it. But let’s see how this changes if the previous condition does not apply.

 

Suppose now that your app is a single .exe file but you have more than one class using A, say B,C,D. Each one of those classes (B,C,D) have a field of type A and use it in their code (B,C,D depend on A).

 

image

 

Switching now from A to A1 requires you to go to “each and every one” of the classes that use A (in a big project this also means that you have to remember which classes are those-in our example B,C,D) and make the appropriate changes. As you must have realized, such process, is error prone and takes time. This problem is created because B,C,D depend on A and B,C,D have the control of creating instances of A.

 

When you use Inversion of Control in the previous situation (changing A to A1) you only need to change a single line of code. So lets see how this works:

 

  1. We create an interface (IA) that has the methods of A. A and A1 should implement this interface.
  2. All classes that use (depend on) A now should use (depend on) IA.
  3. We either need to pass an instance that implement IA in the constructor of those classes or we need to implement a third class Creator that creates objects that implement IA and B,C,D should use this class to get instances that implement IA.

 

If we pass instances that implement IA in the constructors the code looks like the following:

interface IA {
void Method1();
}

public class A:IA {
public A(){}
public void Method1(){ }
}

public class B {
private IA _a;
public B(IA AImplementation) {
_a = AImplementation;
_a.Method1();
}
}

 

In the initial implementation “B had the control of creating A and B depended on A”. In this implementation “the user of B has the control of creating A and B does not depend on A but on IA”. This is Inversion of Control. Now if C,D also follow the same implementation changing from A to A1 does not affect them at all as long as you pass to their constructors and object of type A1 instead of an object of type A. Therefore the previous issue of having to change B,C,D to switch from A to A1 has been solved by using Ioc.

 

Of course, a lot of you would argue that you still have to change the instantiation of A to A1 to each and every one of the classes that create B,C,D to pass the correct parameter in the constructor. For this reason you can use a creator class (a factory) that returns objects that implement IA and use this to create your classes.

 

If we use a creator class and not pass the IA object in the constructor, the code looks like the following:

interface IA {
void Method1();
}

public class A:IA {
public A(){}
public void Method1(){ }
}

public static class Creator {
public A GetIA() {return new A();}
}

public class B {
private IA _a;
public B() {
_a = Creator.GetIA();
_a.Method1();
}
}

See that now _a in B is of type IA and B asks the Creator to get an instance of A. A implements IA. C,D classes would also use IA and the Creator to get an instance that implements A. A1 would need to implement IA also and switching from A to A1 would only require changing the method GetIA in the creator to return a new instance of A1 instead of A. This “Creator” class is usually called a “factory”.

 

Inversion of Control has enabled such a change to be fast, efficient and error free. You can change from A to A1 by changing one line and you can use a new A2 easily by making it implement IA. The drawback is that the amount of code we have written has tripled.

 

Inversion of Control has also another very important benefit in the case where your project uses a .dll. Imagine that you have your ASP.NET MVC project using a class library project which is your business layer. Then, your final deployment consists of the web app and the library dll. If your class A is part of your library and B is part of your web app and you do not use IoC, each time you change from A to A1 you need to recompile the whole project. On the contrary if you use IoC and a factory, the interface IA resides in the library the creator class (factory) resides also in the library and your B class in the web app uses IA. Therefore changing from A to A1 requires you to recompile only the library (.dll) and not all the project facilitating easy and fast deployment in changes.

 

Now wouldn’t  it be nice if we didn’t have to recompile even the library when changing from A to A1? Just have a way to do that by just changing a setting? Can we inject that dependency (A,A1) somehow without having to recompile? This is what we call “Dependency Injection”. How would we implement this without the help of any other libraries?

 

We could keep in a file the class type that needs to be instantiated for the interface and have our “Creator” class (factory) read this file, find out the name of the class that needs to be instantiated and create it by reflection. This would inject the required class in the dependency and thus the term “Dependency Injection”. This means that with dependency injection you do not have to recompile your app when switching from A to A1. The implementation of the creator class for IA should follow the steps below (full code in the project you can download at the end of the post):

 

  1. Open the file with the pairs (interface to implementation).
  2. Find the class name to instantiate
  3. Use reflection to instantiate class from the assembly
  4. Return new object implementing the interface

 

And the file that holds the pair can contain entries as follows:

 

DIandIOCDemo.IA=DIandIOCDemo.A

 

So when should you use Inversion of Control and Dependency Injection?

 

The general rule of thumb is to use it when you have many classes using the methods of a single one and this one may have more than one different “versions”. For example, you are creating your DB Access repositories and you also need to have some fake ones for your tests. Or you have to versions of a class one with lots of debugging info and one without and want to switch between the two at a deployed application.

 

Note that there are fully blown libraries that handle dependency injection such as spring.netthat you should also check out.

 

The project can be downloaded here

.

Shout it

Posted: Πέμπτη, 9 Ιουνίου 2011 7:45 μμ από iwannis | 1 σχόλια
Δημοσίευση στην κατηγορία: ,
Are you ready to test?

Microsoft Hellas is holding a very interesting event in two weeks, on Thursday 12th of May, regarding application testing.

 

Left Outer Join in LINQ to Entities (for Entity Framework 4)

In this post we will explore the most practical ways of performing left outer joins in LINQ to Entities. The same principles applying to LINQ to Entities for EF 4 also apply to LINQ2SQL. This was not the case before EF 4 mainly due to the absence of the DefaultIfEmpty() method in the Entity Framework. In an case, in this post we focus on EF4.

For our test we will use the following demo database/conceptual model:

 

imageimage

 

As you can see, Master records may have 1 or more Detail records and Detail records may have one or more DetailOfDetail records. Left outer joins are translated as follows:

 

“Bring me all records/entities from the Master table along with their corresponding Detail records. The Master records should always exist in the result set even if there are no related records/entities in the Detail table”.

 

The first approach is using the navigation property Details in the query as follows:

 

from p in ctx.Masters.Include("Details") select p

Query1() method in the project

 

This approach is the simplest possible. It only applies when you have the “Details” Navigation Property on your model (enabling the property just to be able to perform left outer join queries is not an option) and it also suffers from the fact that the data are not flattened  (which you may need since your data are feeding a report for example). You get a list of Master objects each one with a list of 0 or more Detail objects.

But you have a way of flattening your results. Using the following LINQ will flatten your results but unfortunately will perform an inner join:

 

var Result2 = from p in ctx.Masters
              from q in p.Details
              select new {Id = p.Id, m1 = p.MasterField1,m2 = p.MasterField2,
                  d1=q.DetailField1,d2=q.DetailField2};

Query2() method in the project

 

To do a left outer join you just need to do the following:

 

var Result2 = from p in ctx.Masters
              from q in p.Details.DefaultIfEmpty()
              select new {Id = p.Id, m1 = p.MasterField1,m2 = p.MasterField2,
                  d1=q.DetailField1,d2=q.DetailField2};

Query3() method in the project

 

That is, the only difference is the addition of the .DefaultIfEmpty() method (this one was missing in previous versions of EF). Now you have a flattened result set for your needs.

 

The second approach does not require the navigation property:

If you do not have the “Details” navigation property then you can still get a left outer join. Using the following will give you an inner join:

 

var Result3 = from p in ctx.Masters join q in ctx.Details on p.Id equals q.MasterID
              select new {Id = p.Id,m1 = p.MasterField1,m2 = p.MasterField2,
                  d1 = q.DetailField1,d2 = q.DetailField2};

Query4() method in the project

 

Changing this to the followinq:

 

var Result3 = from p in ctx.Masters 
              join q in ctx.Details on p.Id equals q.MasterID into Details
              select new {Id = p.Id,d=Details};

 

Will give you the same result as if you had the navigation property. All you have to do for the left outer join is to flatten it as before:

 

var Result3 = from p in ctx.Masters 
              join q in ctx.Details on p.Id equals q.MasterID into Details
              from m in Details.DefaultIfEmpty()
              select new {Id = p.Id,m1 = p.MasterField1,m2 = p.MasterField2,
                  d1 = m.DetailField1,d2 = m.DetailField2};

Query5() method in the project

 

Now let’s extend it a little further and require to get results from the third table as well. We will distinguish again between the two previous approaches (obviously we would like to avoid a nasty foreach loop at the end where the data are collected with SELECT statements creating a wonderful SELECT N+1 issue).

 

Using the Navigation Property Approach

To include the data from the third table in your result you just follow the same principle by adding the third table:

 

var Result2 = from p in ctx.Masters
              from q in p.Details.DefaultIfEmpty()
              from l in q.Details.DefaultIfEmpty()
              select new {Id = p.Id, m1 = p.MasterField1,m2 = p.MasterField2,
                  d1=q.DetailField1,d2=q.DetailField2,dd1=l.DetailOfDetailField1,dd2=l.DeailOfDetailField2};

Query6() method in the project

 

Without the Navigation Property

The same applies here by following the same approach as before:

 

var Result3 = from p in ctx.Masters 
                              join m in ctx.Details on p.Id equals m.MasterID into Details
                              from q in Details.DefaultIfEmpty() join o in ctx.DetailOfDetails 
                                   on q.Id equals o.DetailID into DetailsOfDetail
                              from l in DetailsOfDetail.DefaultIfEmpty()
                              select new
                              {
                                  Id = p.Id,
                                  m1 = p.MasterField1,
                                  m2 = p.MasterField2,
                                  d1 = q.DetailField1,
                                  d2 = q.DetailField2,
                                  dd1 = l.DetailOfDetailField1,
                                  dd2 = l.DeailOfDetailField2
                              };

Query7() method in the project

 

 

The project can be downloaded here

(Note that since in the project we are not using the database the DefaultIsEmpty method gets a parameter defining the default object.)

Shout it
Posted: Σάββατο, 12 Φεβρουαρίου 2011 8:45 πμ από iwannis | 1 σχόλια
Δημοσίευση στην κατηγορία:
XNA for Windows Phone 7 and Physics

In this post, we will see how easy it is to create an XNA world for Windows Phone 7 that obeys the laws of physics. To our quest, our weapon will be the Farseerphysics engine. You will be amazed when you realize how interesting a simple circle on the phone’s display becomes when you add some physics to its world! So let our quest begin…

Download the zip file from the project’s site. Unzip its contents and locate the folder containing the sources of the Farseer engine (at the time of this writing the folder is named “Farseer Physics Engine 3.2 XNA”).

Open Visual Studio and create a new project of “Windows Phone Game'” type (important note: if you are a newbie in XNA game development you are strongly encouraged to follow thisseries of blog posts and also download the developer tools from here).

The game we will be making will be as follows: The user sees a sprite on the screen and it gives momentum to the sprite (yellow ball) by applying a gesture to the phones display. The sprite should be bouncing at randomly placed obstacles on the display and it should hit the randomly placed silver balls (ouaou that’s interesting!)

 

SpaceGame

 

In an XNA Game for WP7 your canvas is 800x480 pixels size. Therefore we have created a background image in Photoshop of this size. The sprites that will be used in our game are the following:

 

Sprites

 

And now it is time to get started. When you have created your “Windows Phone Game” project, Visual Studio has created an extra project where you will add your sprites. We add all the aforementioned images (sprites) there following the well known “Add Item” procedure:

image

 

Now go to your solution’s folder and copy the Farseer project you have located before along with its containing folder to your solution folder. Right-click on your solution and select “Add/Existing Project”. Select the .csproj file for WP7 of the Farseer physics engine located in the folder you ‘ve just copied. Finally add a reference at your XNA game project to the engine (if you feel lost download the project at the end of this post and you will see the final state of the folders/projects). If you did everything correctly the solution will compile successfully. And this is all the plumbing you have to do. Now, let us do some physicz!

 

First we create the definitions of our sprites along with some lists of the positions of the obstacles and balls:

 

private Texture2D _background;
private Texture2D _myBall;
private Texture2D _floor;
private Texture2D _otherBall;
private Texture2D _obstacle;

private List<Vector2> _otherBallPositions;
private List<Vector2> _obstaclePositions;

private Random _r;

 

The definition of the random number generator will be used in the creation of the scene. In the LoadContent() method we create out Textures and select their positions on the display (note the random creation of a number of obstacles and balls and their positions):

protected override void LoadContent()
{
    spriteBatch = new SpriteBatch(GraphicsDevice);
    
    _background = Content.Load<Texture2D>("Background");
    _floor = Content.Load<Texture2D>("Floor");
    _myBall = Content.Load<Texture2D>("MyBall");
    _obstacle = Content.Load<Texture2D>("Obstacle");
    _otherBall = Content.Load<Texture2D>("OtherBall");

    _obstaclePositions = new List<Vector2>();
    for (int i = 0; i < _r.Next(1, 6); i++)
        _obstaclePositions.Add(new Vector2(_r.Next(100, 700), _r.Next(100, 400)));

    _otherBallPositions = new List<Vector2>();
    for (int i = 0; i < _r.Next(1, 6); i++)
        _otherBallPositions.Add(new Vector2(_r.Next(100, 700), _r.Next(100, 400)));

}

Initially we will draw everything on the display in the Draw() method as follows:

 

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);
    spriteBatch.Begin();
    spriteBatch.Draw(_background, new Vector2(0, 0), Color.White);
    spriteBatch.Draw(_floor, new Vector2(0, 459), Color.White);
    spriteBatch.Draw(_myBall, new Vector2(40, 432), Color.White);
    for (int i = 0; i < _obstaclePositions.Count; i++)
        spriteBatch.Draw(_obstacle, _obstaclePositionsIdea, Color.White);
    for (int i = 0; i < _otherBallPositions.Count; i++)
        spriteBatch.Draw(_otherBall, _otherBallPositionsIdea, Color.White);
    spriteBatch.End();
    base.Draw(gameTime);
}

 

This will generate a nice scene but everything will be static. Here is where we apply out physics engine to bring everything to life. Define a World object and create it in the Initialize method:

 

private World _world;

protected override void Initialize()
{
    _r = new Random();
    _world = new World(new Vector2(0,9.81F));
    base.Initialize();
}

 

The parameter is the gravity which we set it as a vector perpendicular to our x-axis (as is in real life). Now for every sprite in your world  you need to define its Body (mass, physical properties) and its Shape (its geometry). In the Farseer physics world you have to define the two and then connect them (to represent a single object) with a Fixture, actually saying that a body with mass X will be represented as a rectangle (for example) with Y,Z dimensions. Since this may be too much code to write, you may use a factory to do the job for you. For example for the floor (a rectangular body at the bottom of our game scene) we define:

In the LoadContent() method we create the Fixture for the floor which automatically defines a body of mass with density 1 and a rectangular shape of size the same as the floor’s texture:

 

private Fixture _floorFixture;
protected override void LoadContent()
{
    (…)
    _floor = Content.Load<Texture2D>("Floor");
    (…)
    _floorFixture=FixtureFactory.CreateRectangle(_world,_floor.Width,_floor.Height,1);
    _floorFixture.Body.BodyType = BodyType.Static; 
    _floorFixture.Body.Position=new Vector2(0, 459);

    (…)
}

 

Note that there is no connection with the texture, at least in code. The only thing we use the texture for is when we draw it on the position of the body. In the update method, we tell our world to process the position of the bodies (the Step method gets a parameter defining how much time has passed since the last step for the world) and then in the draw we use the result to draw the floor. The time that has passed is the actual-real time:

 

protected override void Update(GameTime gameTime)
{
    (…)
    _world.Step(gameTime.ElapsedGameTime.TotalSeconds);
    base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
    (…)
    spriteBatch.Draw(_floor, _floorFixture.Body.Position, Color.White);
    (…)
    base.Draw(gameTime);
}

 

Here is the first tricky part. If you use the aforementioned placement, the position of the floor texture will not correspond to the position of the floor body. This is because FarSeer considers the local shape’s origin point (0,0) to be at the center of the rectangle while XNA considers the same point (0,0) to be at the top left cornet of the rectangle. This is illustrated in the following figure:

image

Due to this, the “FarSeer world” and the “Visible world” have different opinions on where the body is located since the position of a body/texture defines the position of its local origin:

image

To compensate for this you need to do two things. First, place the floor to location (400,469), which will place the body in the correct position in the FarSeer world (left) and then change the local origin when drawing the texture from (0,0) to (400,10) (right) which will also position correctly the texture in the “Visible world”:

image

 

This in code is translated as follows:

 

    (…)
    // The following is in the LoadContent() method!
    _floorFixture=FixtureFactory.CreateRectangle(_world,_floor.Width,_floor.Height,100);
    _floorFixture.Body.BodyType = BodyType.Static;
    _floorFixture.Body.Position=new Vector2(400, 469); //THIS IS DIFFERENT NOW
    (…)
    // The following is in the Draw() method! 
    spriteBatch.Draw(_floor, _floorFixture.Body.Position, null, Color.White, _floorFixture.Body.Rotation, 
                      new Vector2(_floor.Width / 2,_floor.Height/2), 1, SpriteEffects.None, 1);
        

 

When you compile and run the program now nothing seems to have changed but believe me the physics world is there. To prove this just change the definition of Body.BodyType from BodyType.Static to BodyType.Dynamic and the floor will just fall from its position obeying the Newtonian rule of gravity! Let’s now follow the same approach for the other sprites in our world (the principle is exactly the same so below is the complete listing):

 

protected override void LoadContent()
{
    spriteBatch = new SpriteBatch(GraphicsDevice);
    
    _background = Content.Load<Texture2D>("Background");
    _floor = Content.Load<Texture2D>("Floor");
    _myBall = Content.Load<Texture2D>("MyBall");
    _obstacle = Content.Load<Texture2D>("Obstacle");
    _otherBall = Content.Load<Texture2D>("OtherBall");

    _floorFixture=FixtureFactory.CreateRectangle(_world,_floor.Width,_floor.Height,1);
    _floorFixture.Body.BodyType = BodyType.Static;
    _floorFixture.Restitution = 0.7f;
    _floorFixture.Body.Position=new Vector2(400, 469);

    _otherBallFixtures = new List<Fixture>();
    for (int i = 0; i < _r.Next(1, 16); i++)
    {
        Fixture Temp = FixtureFactory.CreateCircle(_world, _otherBall.Height / 2, 1);
        Temp.Body.Position = new Vector2(_r.Next(100, 700), _r.Next(100, 400));
        Temp.Body.IsStatic = false;
        Temp.Restitution = 0.7f;
        _otherBallFixtures.Add(Temp);
    } 

    _obstacleFixtures = new List<Fixture>();
    for (int i = 0; i < _r.Next(1, 6); i++)
    {
        Fixture Temp = FixtureFactory.CreateRectangle(_world,_obstacle.Width,_obstacle.Height,100);
        Temp.Body.BodyType = BodyType.Static;
        Temp.Body.Position=new Vector2(_r.Next(100, 700), _r.Next(100, 400));
        Temp.Restitution = 0.7f;
        _obstacleFixtures.Add(Temp);
    } 
}

 

And the Draw() is as follows:

 

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);
    spriteBatch.Begin();
        spriteBatch.Draw(_background, Vector2.Zero, Color.White);
        spriteBatch.Draw(_floor, _floorFixture.Body.Position, null, Color.White, 
                         _floorFixture.Body.Rotation, new Vector2(_floor.Width / 2,_floor.Height/2), 
                          1, SpriteEffects.None, 1);
        spriteBatch.Draw(_myBall, new Vector2(40, 432), Color.White);
        for (int i = 0; i < _obstacleFixtures.Count; i++)
            spriteBatch.Draw(_obstacle, _obstacleFixturesIdea.Body.Position, null, Color.White, 
                             _obstacleFixturesIdea.Body.Rotation, 
                             new Vector2(_obstacle.Width / 2, _obstacle.Height / 2), 1, 
                             SpriteEffects.None, 1);
        for (int i = 0; i < _otherBallFixtures.Count; i++)
            spriteBatch.Draw(_otherBall, _otherBallFixturesIdea.Body.Position, null, Color.White, 
                             _otherBallFixturesIdea.Body.Rotation, 
                             new Vector2(_otherBall.Width / 2, _otherBall.Height / 2), 1, 
                             SpriteEffects.None, 1);
    spriteBatch.End();
    base.Draw(gameTime);
}

 

Note that we have also defined the Restitution coefficient for our bodies which defines how much of the initial velocity is lost when the ball will bounce on the obstacle (1 for example will have the ball bouncing endlessly like being made from a very elastic rubber, while a 0 will make the ball behave like it is made from iron).

Now when you run the program all the balls will fall to the floor and will also bounce. But the first thing you will notice is that they are too slow. You can go experimenting by raising the gravity value or increasing the time in the Step() method but those approaches are all trial and error and you will not get to far by this. The actual problem is the fact that you are playing with very large numbers in the FarSeer engine. While gravity and mass are defined in Kg and m/sec2 without any issues, you are defining shapes like the floor that are 800 meters long and 20 meters tall since the pixel to meter ratio is 1:1. This causes the engine to overflow. To get more realistic results you need to define the pixels/meter ratio to something different. In our case, let’s say that 1 pixel is 50 meters. This means that our view will be 16m wide and 9,6m tall (800x480 pixels) which is fine. Define a new private field as follows:

 

private float _pixelsPerMeter = 50;

Now when you define a shape you need you divide by this. For example:

 

_floorFixture = FixtureFactory.CreateRectangle(_world, _floor.Width / _pixelsPerMeter, 
                                                       _floor.Height / _pixelsPerMeter, 1f);
_floorFixture.Body.BodyType = BodyType.Static;
_floorFixture.Restitution = 0.7f;
_floorFixture.Body.Position = new Vector2(400 / _pixelsPerMeter, 469 / _pixelsPerMeter);

 

That is you are translating everything from pixels to meters for the FarSeer world. When you draw you need to do the opposite as follows:

 

spriteBatch.Draw(_floor, _floorFixture.Body.Position * _pixelsPerMeter, null, Color.White, 
                         _floorFixture.Body.Rotation * _pixelsPerMeter, 
                          new Vector2(_floor.Width / 2, _floor.Height / 2) , 1, SpriteEffects.None, 1);

Now when you compile and run everything will make more sense. It takes approx. 1 sec for the ball to fall from the top to the bottom (4km) at 9.81 g. Well let’s see:

image

Well as you can see you have a perfectly realistic world that obeys the laws of physics without experimenting. If you change your ratio to 25 your world is bigger, your balls are higher and it will take them twice the time to reach the bottom. The only thing left to do is apply some force to the yellow ball by the use of gestures.

First we define the yellow ball as a body too, like we did for the other sprites and then we add in the Update() method the following:

 

while (TouchPanel.IsGestureAvailable)
{
    GestureSample gesture = TouchPanel.ReadGesture();
    if (gesture.GestureType == GestureType.Flick)
        _myBallFixture.Body.ApplyForce(Vector2.Divide(gesture.Delta, 2.0f));
}

 

This will constantly check for gestures and apply them as a force to the ball. The last thing to be done is to enable this type of gestures at the initialization method as follows:

 

TouchPanel.EnabledGestures = GestureType.Flick;

 

And this concludes our introduction to the physics engine. The project can be downloaded  

.

Posted: Τρίτη, 8 Φεβρουαρίου 2011 10:23 μμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία:
A simple REST service in C#

In this post, we will see a simple implementation of a REST service.The service will consist of only one method and it can be consumed from your websites, directly from your browser or from a Desktop application.

 

When implementing a service you need to specify the following:

 

  • The service contract (the methods it offers).
  • How do you know which one to access from the URL given (URL Routing).
  • The implementation of the service.
  • How you will host the service.

 

Defining the Contract

Create a new Class Library Project and call it “RESTService.Lib”. Add references to “System.ServiceModel” and “System.ServiceModel.Web”. Create an Interface class called IRESTDemoServices and add the definitions of the methods that represent the services offered. Our interface will offer just one service as follows:

 

public interface IRESTDemoServices
{
    string GetClientNameById(string Id);
}

 

In order to tell the framework to treat this interface as a service we need to decorate it as follows:

 

[ServiceContract(Name = "RESTDemoServices")]
public interface IRESTDemoServices
{
    [OperationContract]
    string GetClientNameById(int Id);
}

 

Apparently we could offer more than one methods in our service by adding more methods in the interface.

 

Defining the URL to be used to access the service (URL Routing)

Although you can actually specify the routing within the interface it is better to create a new static class that will hold all your routing paths. Create a new static class named Routing and provide the following:

 

public static class Routing
{
    public const string GetClientRoute = "/Client/{id}";
}

 

Note the {id} element which specifies that the value supplied there should be matched with a parameter of the method of the interface. The connection of the URL Route to the method in the interface is achieved by decorating the interface with an attribute as follows:

 

[ServiceContract(Name = "RESTDemoServices")]
public interface IRESTDemoServices
{
    [OperationContract]
    [WebGet(UriTemplate = Routing.GetClientRoute, BodyStyle = WebMessageBodyStyle.Bare)]
    string GetClientNameById(string Id);
}

 

The WebGet attribute also specifies that the method will be accessed by a typical GET request to the specified URL.

 

Implementing the service

Implementing the service is as simple as creating a class that implements the service’s interface and decorating it with two specific attributes:

 

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, 
                 ConcurrencyMode = ConcurrencyMode.Single, IncludeExceptionDetailInFaults = true)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class RestDemoServices:IRESTDemoServices
{
    public string GetClientNameById(string Id)
    {
        Random r = new Random();
        string ReturnString="";
        for (int i = 0; i < Id; i++)
            ReturnString += char.ConvertFromUtf32(r.Next(65, 85));

        return ReturnString;

    }
}

 

This is of course dummy code just to return a string. In real life this is the place to access the database and request for the name of the client with this id.

 

And this is it! Your service is ready to be hosted.

 

Hosting your service

The simplest solution is to create a console application that will act as the server of your service. Create a new project “Console Application” and add the same references as in the class library project along with the reference to the class library project itself. There is a possibility that you may need to change the “Target Framework” of your app to .NET Framework 4 from the one with the client profile in order to be able to include the “System.ServiceModel.Web” assembly. In the main method you host the service as follows:

 

static void Main(string[] args)
{
    RestDemoServices DemoServices = new RestDemoServices();
    WebHttpBinding binding = new WebHttpBinding();
    WebHttpBehavior behavior = new WebHttpBehavior();

    WebServiceHost _serviceHost = new WebServiceHost(DemoServices, 
                                                     new Uri("http://localhost:8000/DEMOService"));
    _serviceHost.AddServiceEndpoint(typeof(IRESTDemoServices), binding, "");
    _serviceHost.Open();
    Console.ReadKey();
    _serviceHost.Close();
}

 

That is you initialize the service and then you host it under the root URL of http://localhost:8000/DEMOService. And off you go! Run the application and open your browser and type the following:

 

image

 

That’s it. Of course in a production environment you may have to open the port your service communicates.

Alternatively you may host this service in IIS. Create a new Empty Web Application Project. Add a reference to the class library project containing the Demo service and create an empty .svc file with the following contents (when you add it from the Add Item menu you will get some extra cs flies which you can safely delete):

 

<%@ ServiceHost Language="C#" Debug="true" Service="RESTService.Lib.RestDemoServices" 
                Factory="System.ServiceModel.Activation.WebServiceHostFactory"%> 

 

This is it. Right Click on the svc file and select “View in Browser”. You will achieve the same result as before:

 

image

 

Deploying the .svc file to a web server is similar to deploying a webpage.

 

This was a very simple demonstration of creating a web service. I haven’t shown any POST requests neither I have demonstrated session management. But apart from those, I think you will see that there will be a lot of times that a simple web service with only GET Requests will be the only one thing needed and this approach will come in handy.

 

Again the project for this post can be downloaded here

Shout it
Posted: Σάββατο, 29 Ιανουαρίου 2011 10:51 μμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία: ,
Interception and Interceptors in C# (Aspect oriented programming)
In this post, we see how to define specific actions to be executed before or after the execution of every call to a method in our code. This is also known as “ intercepting ” the execution of a method and is related to AOP (Aspect Oriented Programming). We will explore two different ways of achieving this:   Using Microsoft’s Unity framework Using the PostSharp library   CastleDynamicProxy is another library allowing you to intercept methods and resembles a lot to the Unity framework’s approach so it will not be described here. You can also use .NET framewrok’s Emit namespace or CodeDom to create your intercepting Proxy objects from scratch but this approach is out of the scope of this post. Aspect Oriented Programming deals with horizontal concerns in the specifications of your programs. Horizontal concerns are requirements that span through every business logic or specific behavior of your system. Take for example the following figure displaying some typical modules of an e-shop application. The classes

Διαβάστε περισσότερα »

Posted: Κυριακή, 16 Ιανουαρίου 2011 10:38 πμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία:
ListBoxes with DataBound Images in WPF
In this post, we see how we can add a DataBound image in the DataTemplate of a WPF ListBox. We experiment with three different approaches of achieving that and discuss on which one to use depending on the situation. In all cases, the image files are embedded within the application as “Resource” files. Later in this post, we will see what needs to be changed in order to support having the image files in a folder outside of the application Assembly. Our object for binding will be the class named Item having the following properties: public class Item { public int PictureID { get ; set ; } public string Name { get ; set ; } } We want to display a specific image depending on the value of the property PictureID. The ListBox in the .xaml file be: < ListBox ItemTemplate ="{ DynamicResource DataTemplateItem }" ItemsSource ="{ Binding Items }" /> The definition of the DataTemplate for the items of the ListBox is: < DataTemplate x : Key ="DataTemplateItem"> < Canvas

Διαβάστε περισσότερα »

Posted: Τετάρτη, 12 Ιανουαρίου 2011 9:19 μμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία:
ASP.NET MVC Binding to Lists–Enumerables on POST with JQuery
In this post we see how we can bind to editable IEnumerables-Lists in an ASP.NET MVC view and get the updated values in our HttpPost action. Moreover, we see how we can use JQuery to dynamically add/remove items from the list and have our updates transferred to the HttpPost action. We start by defining a simple class named Client which will be our list element: public class Client { public string FirstName { get ; set ; } public string LastName { get ; set ; } } We implement an Action method that creates a list of Client objects: public ViewResult Simple() { List < Client > Clients = new List < Client >(); Clients.Add( new Client { FirstName = "Giannis" , LastName = "Panagopoulos" }); Clients.Add( new Client { FirstName = "Kostas" , LastName = "Papadopoulos" }); Clients.Add( new Client { FirstName = "Petros" , LastName = "Georgiadis" }); return View(Clients); } The simple view renders the list as follows (with input elements of type text for

Διαβάστε περισσότερα »

Posted: Δευτέρα, 29 Νοεμβρίου 2010 12:15 μμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία:
I am in Teched2010 - Berlin
Another year in Berlin! Another chance to learn great things on Microsoft Technologies.  

Διαβάστε περισσότερα »

Code Generation with T4 Templates – A must have for developers
T4 Templates files have a .tt extension and are the input to VS2010’s code generation engine for automatically generating text files with all sorts of content (C# code, SQL Commands, XAML, HTML, XML etc). In this post, we will briefly see how we can create and use them and examine some very useful scenarios on situations where they may come in handy. Before starting with the tutorial it is recommended that you download the T4 Editor . It provides syntax highlighting when editing a .tt file from within

Διαβάστε περισσότερα »

Posted: Τρίτη, 26 Οκτωβρίου 2010 8:09 μμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία:
Entity Framework, the Context, ComboBoxes and Include Foreign Key columns.
How do they all connect? Well it boils down to the following questions: If I am using Entity Framework in a Desktop application when should I open the Context and for how long should I keep it open? I have ComboBoxes that will be used to select values for the Reference Properties of my Entity Framework objects. How am I going to achieve this? Should I bind to Reference Properties or should I include the Foreign Keys in my model (option named “Include Foreign Key columns in the model”) and bind to

Διαβάστε περισσότερα »

Posted: Πέμπτη, 9 Σεπτεμβρίου 2010 7:48 πμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία: ,
Autosuggest Textbox for WPF
Here is an implementation of a nice Textbox in WPF that suggests possible values based on the current user’s input. It is different from WPF’s native editable Combobox since it does not load all possible values at initialization (saving time and memory). The Textbox calls a method that returns the suggested values as soon as it detects a specific amount of idle time in the user’s typing. This method will probably access the database using the value entered so far in the Textbox as the criterion

Διαβάστε περισσότερα »

Posted: Πέμπτη, 1 Ιουλίου 2010 7:57 μμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία:
Domain Specific Languages with M - Part 3/3 Consuming the DSL at runtime in C#
In this last post of the small series we will see how we can load the syntax of a DSL in C# and then feed it with an input text that we need to be parsed. In this post we have already described how to write the DSL syntax and in this post we have seen how to decorate it with productions. So following the process described in those posts we end up with a file containing the description of the syntax of our DSL, along with its productions (eg the file Renting_en.mg available for download in the zip file provided

Διαβάστε περισσότερα »

Posted: Πέμπτη, 20 Μαΐου 2010 7:52 πμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία:
Domain Specific Languages with M - Part 2/3 Attributes and Productions
In the previous post we have covered the basics of the M language concerning the development of a Domain Specific Language (DSL). In this post we will extent the syntax of the described DSL by adding attributes and production rules. On feature that is kinda interesting is the ability to use attributes to define syntax highliting to the left panel of Intellipad (where your input text appears). Those attributes decorate the tokens of the syntax and are introduced by the @{Classification["Keyword"]} ,

Διαβάστε περισσότερα »

Domain Specific Languages with M - Part 1/3 Defining the syntax
Say you are implementing software for a company that rents items. And you are presented with some bizarre and complex logic on the way renting fees are calculated. To be more specific requirements come to you in the following form: “I want a renting fee scenario where an item for the first month is charged 10$ per day. Then, the same item costs 5$ per week for the next two months. Finally, after this period of three months the fee will be 20$ per month. But this is just one scenario…” Clearly

Διαβάστε περισσότερα »

Posted: Σάββατο, 10 Απριλίου 2010 9:07 πμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία:
XNA 2D Basic Collision Detection with Rotation (Scene2Sprite)
In the previous post we have worked with collision detection between roated sprites. In this post we will deal with the situtation where we want to detect whether a specific sprite that can be rotated is in a specific area in the scene (eg a car is on the road in the scene). Suppose that you have the following scenario: A car is driven by the user around the scene. When the car hits the boundaries of the road, the car should lose all of its speed. The user uses the UP/DOWN keys to acelerate/break and LEFT/RIGHT

Διαβάστε περισσότερα »

Posted: Τρίτη, 16 Φεβρουαρίου 2010 7:54 πμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία:
XNA 2D Basic Collision Detection with Rotation (Sprite2Sprite)
(If you are in a hurry and do not want to no how it's done but just do it, dowload the project and extract the CollisionDetection2D.cs file to include in your project that contains the collision detection methods) In my previous post ,we have seen several collision detection techniques that can be used in 2D games in XNA. In that post, we have left out the changes that affect our code when textures can also be rotated . In this post, I intend to fill this gap by picking up from exactly where we stopped and adding

Διαβάστε περισσότερα »

Posted: Τετάρτη, 10 Φεβρουαρίου 2010 7:26 πμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία:
XNA 2D Basic Collision Detection
In this post we will explore some basic techniques in XNA for 2D collision detection. Our goal is to provide a solution to the two following scenarios: Detect the collision of two sprites Detect the collision of a sprite with specific areas in the scenery (eg detect when a car hits the boundaries of the road when viewed from the top) A sprite in XNA is usually realized by a DrawableGameComponent class (see previous posts 1 , 2 , 3 ). Therefore sprite collision detection is merely a DrawableGameComponent collision

Διαβάστε περισσότερα »

Posted: Κυριακή, 24 Ιανουαρίου 2010 9:17 μμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία:
XNA Game Development (Scenes and Game Services)
In the previous post , we have talked about decentralizing our XNA application by taking advantage of the GameComponent and DrawableGameComponent classes. In this post, we will explore two things: The way to decouple the GameComponents' interfaces from the main game logic by using "Game Services". The way to create "Scenes". Scenes in games are those displays that occur before the game starts with th game menu, the help screen, etc etc. Let's start with Game Services . In the project of the

Διαβάστε περισσότερα »

Posted: Παρασκευή, 15 Ιανουαρίου 2010 7:30 πμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία:
XNA Game Development (Decentralize)
In the previous post , we have talked about drawing and moving 2D textures on the XNA window. In this post, we will explore the basic architecture that XNA uses in order to separate the game logic from the sprite logic. So prior to reading this post, it is suggested to go through the previous one. The main code smell there, was the fact that we had to put all the game logic for moving the Ivan sprite to the Update and Draw methods of the game loop. Imagine how messed up those too methods would look if we placed

Διαβάστε περισσότερα »

Posted: Τετάρτη, 23 Δεκεμβρίου 2009 7:31 πμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία:
XNA Game Development (First Steps)
Welcome to a short introduction in game Development using the XNA Framework! Let's start with the basics by examining how different is Windows programming to XNA Game programming. As we know, windows programming is "event driven". This means that our logic resides in event handlers that get called when a resource or a Control needs to tell us that something happened. So our program is nothing more than a loop that awaits for events to happen and a bunch of event handlers that respond to those events.

Διαβάστε περισσότερα »

Posted: Σάββατο, 19 Δεκεμβρίου 2009 1:32 μμ από iwannis | 0 σχόλια
Δημοσίευση στην κατηγορία:
I am in Teched2009 - Berlin
I am happy to announce that this year I am attending Teched 2009. As soon as the conference ends, I wil write some posts with my view of the TechEd world. So stay tuned !

Διαβάστε περισσότερα »

Περισσότερες Δημοσιεύσεις « Προηγούμενη - Επόμενη »