IgorShare Thoughts and Ideas

Consulting and Training

Archive for the ‘C#’ Category

Roslyn: C# is cheating on me with JavaScript (or how to compile C# into JavaScript)

Posted by Igor Moochnick on 08/20/2012

imageWhile working extensively on development of the Single Page Applications (SPA) I was facing a fact that my server-side data models were evolving quicker than their JavaScript counterparts. Both the client-side and the server-side data models were getting quickly out of sync.

The brute force solution of using the T4 templating engine to emit both the client-side and the server side data models didn’t look that appealing to me. Primarily due to a simple fact that it’s not that easy to refactor the T4 templates. And, the ReSharper junkie like me, can’t tolerate this fact.

So I’ve decided to give the latest release of Roslyn compiler-as-a-service CTP another spin and use it as part of my build sequence and compile my C# models directly into the appropriate JavaScript ones. This was giving me the advantage of using the C# as a primary development environment and leaving the JavaScript to follow the “big-brother”.

Jinx C#-to-JavaScript compiler was created as a result of this exercise. You’re welcome to get the Jinx source from the GitHub. I’ll appreciate any collaboration on this project.

Note: all of the code is an intermediate solution that was answering my personal needs for the project I was running. It is in no-way represent the full fledge solution. If you want something bigger and more feature-reach, you can either contribute to my solution or look into projects like Script# or SharpKit.

Read the rest of this entry »

Posted in Architect, C#, Compiler, Javascript, Tutorials, Web | 3 Comments »

Adding Nancy to the existing ASP.NET MVC site

Posted by Igor Moochnick on 04/08/2012

There is an issue adding Nancy to the ASP.Net MVC site due to a simple fact that MVC controls the routes not through the web.config but through the routing table.

If you adding Nancy to the existing MVC site – make sure to remove the sub-route that controlled by Nancy from the routing table.

Here how it works:

1. Follow all the steps from the Nancy Documentation Wiki

2. Add your module and make sure that it has an “offset” path (via inheritance)

public Module() : base("/nancy")
{
   ...
}

3. Remove the “nancy” route from the Routing table in the Global.asax.cs

MvcApplication.RegisterRoutes(...)
{
   ...
   routes.IgnoreRoute("nancy/{*pathInfo}");
   ...
}

Posted in C#, Web | 5 Comments »

Interactive Data Dependency Visualizations

Posted by Igor Moochnick on 03/01/2012

There is nothing aids better in understanding your data than a great visualization. Today there is an abundance of different techniques and tools, but today I’d like to show what is readily available for you in .Net.

Let’s take a simple example of understanding dependencies between your assemblies.

If you’re running in a Visual Studio and you have a full access to the source code, it is possible to see the referenced assemblies but it’s pretty hard to track what assembly depend on the assembly you’re working on. [Note: if you’re really in need of a ready made tool for this purpose, you can check the “Architecture Tools” for Visual Studio 2010 or NDepend tool]

A visualization like this is priceless:

image

On this graph you can see a graph of the assemblies dependencies for the Paint.Net. The snapshot above highlights the dependencies of the PaingDotNet.SystemLayer (highlighted in blue) by showing all the assemblies it depends on in “yellow” and all the assemblies dependent on it in “green”. The rest is left in a “gray” color.

Let’s see how you can create interactive dependency graphs for your data.

In my case I chose to use the QuickGraph module from CodePlex that can be download from NuGet [PM> Install-Package QuickGraph]. It provides a very simple yet robust API that allows you to create the directional and non-directional graphs in memory and then save them in different formats.

Here is a small example of how to create 2 vertices (V1 and V2) and a directional edge (from V1 to V2):

var graph = new AdjacencyGraph();
graph.AddVertex("v1");
graph.AddVertex("v2");
var edge = new TaggedEdge("v1", "v2", "depends");
graph.AddEdge(edge); 

As soon as all the graph is created it can be serialized, for example, in a GraphML standard format like this:

using(var xwriter = XmlWriter.Create(...))
    g.SerializeToGraphML(xwriter);

This is it. GraphML files can be opened by a range of different tools, but, if you’d like to show these visualizations in your WPF applications you can use a Graph# from CodePlex.

Here is a sample WPF application rendering a GraphML dependency graph:

image

As you can see, you don’t have to be afraid of interactive data visualizations but you can make your applications shine and provide useful and easily digestible information for your users.

Note: Source code for this article you can download …here from the Git repo…

Posted in C#, Reflection | 4 Comments »

NWT – .Net Web Toolkit

Posted by Igor Moochnick on 10/26/2011

Now, after waiting for quite some time, we finally can implement the real solution for .Net <-> javascript conversion and bridge the impedance gap in the projects that heavily rely on the powerful rich web UI.

Currently we have solutions like Script# and CofeeScript and others. The pros in cons of these systems have been discussed countless times (ex: HanselminutesJavaScript is Assembly Language for the Web: Semantic Markup is Dead! Clean vs. Machine-coded HTML).

With the recently released project Roslyn (or alternatively Mono Compiler Services) it is possible to have a clean solution to the problem:  I write my data and data model in a language and an environment that allow solid validation and refactoring.

I’m ironing out some kinks in my implementation and, as soon as it’ll be in a stable state, I’m going to release a NWT (NeWT) project that will provide a similar to GWT (Google Web Toolkit) functionality.

Posted in C#, GWT, Javascript, jQuery, Web | 1 Comment »

Tip: Showing a Main view as a tray app with Caliburn.Micro

Posted by Igor Moochnick on 03/31/2011

The trick here is to make sure that the main view doesn’t pop-up right away in a visible form. After creation and resolving all the binding rules – the main view should be in a Hidden form.

This can easily be achieved with customizing the WindowManager by sub-classing it and adding one extra method:

[Export]
public class CustomWindowManager : WindowManager
{
    public Window MainWindow(object rootModel, object context = null)
    {
        return CreateWindow(rootModel, false, context);
    }
}

As soon as you’ll have the new WindowManager – the logic for the root view creation in the Boostrapper should be adjusted accordingly:

protected override void DisplayRootView()
{
    var viewModel = IoC.Get<IShell>();

    var windowManager = IoC.Get<CustomWindowManager>();

    _mainWindow = windowManager.MainWindow(viewModel);
    _mainWindow.Hide();
}

Here is a simple ShellView that uses a WPF TrayIcon implementation from CodeProject:

<UserControl ...
             xmlns:tb="clr-namespace:Hardcodet.Wpf.TaskbarNotification;assembly=Hardcodet.Wpf.TaskbarNotification"
             xmlns:cal="http://www.caliburnproject.org"
             Visibility="Hidden">
    <Grid>
        <tb:TaskbarIcon
            Visibility="Visible"
            x:Name="MyNotifyIcon"
            IconSource="/Resources/Images/Bulb.ico"
            MenuActivation="LeftOrRightClick" PopupActivation="DoubleClick">
            <!-- Set a simple context menu  -->
            <tb:TaskbarIcon.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Exit" cal:Message.Attach="AppExit" />
                </ContextMenu>
            </tb:TaskbarIcon.ContextMenu>
        </tb:TaskbarIcon>
    </Grid>
</UserControl>

The View Model for this view is very straight forward:

[Export(typeof(IShell))]
public class ShellTrayViewModel : Screen, IShell
{
    public void AppExit()
    {
        Application.Current.Shutdown();
    }
}

That’s it.

Posted in .NET, C#, Caliburn, MVVM, WPF | 5 Comments »

Teaching TFS custom activity to work with the Svn, Cvs, Git and other source control command line tools

Posted by Igor Moochnick on 12/27/2010

After the SharpSvn fiasco (described in the previous post), I’ve decided temporarily put this dependency loading issue aside and, instead of running native Svn client, to use one of the command-line Svn interfaces. I’ve tried to keep the activity interface generic enough so you can configure it to use any of the available command-line source control clients (not only Svn but Cvs, Git, Mercurial, etc…)

As a first step the following 4 common and mostly changed parameters were identified:

  1. Source location (usually a Url)
  2. Destination for check-out
  3. Username
  4. Password

This list defined all the input parameters for the Svn custom activity (plus extra one that carries the the command line template):

        [RequiredArgument]
        public InArgument<string> SvnToolPath { get; set; }

        [RequiredArgument]
        public InArgument<string> SvnCommandArgs { get; set; }

        [RequiredArgument]
        public InArgument<string> DestinationPath { get; set; }

        [RequiredArgument]
        public InArgument<string> SvnPath { get; set; }

        [RequiredArgument]
        public InArgument<svncredentials> SvnCredentials { get; set; }

The rest of the activity takes care of building a command line from a provided template by replacing the placeholders with the provided parameter values and executing the external process:

namespace SvnActivityLib
{
    [BuildActivity(HostEnvironmentOption.All)]
    [BuildExtension(HostEnvironmentOption.All)]
    [Designer(typeof(SvnActivityDesigner))] 
    public sealed class SvnActivity : CodeActivity
    {
        [RequiredArgument]
        public InArgument<string> SvnToolPath { get; set; }

        [RequiredArgument]
        public InArgument<string> SvnCommandArgs { get; set; }

        [RequiredArgument]
        public InArgument<string> DestinationPath { get; set; }

        [RequiredArgument]
        public InArgument<string> SvnPath { get; set; }

        [RequiredArgument]
        public InArgument<svncredentials> SvnCredentials { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            TrackMessage(context, "Starting SVN action");

            string destinationPath = context.GetValue(this.DestinationPath);
            string svnPath = context.GetValue(this.SvnPath);
            string svnToolPath = context.GetValue(this.SvnToolPath);
            string svnCommandArgs = context.GetValue(this.SvnCommandArgs);
            SvnCredentials svnCredentials = context.GetValue(this.SvnCredentials);

            string svnCommand = Regex.Replace(svnCommandArgs, "{uri}", svnPath);
            svnCommand = Regex.Replace(svnCommand, "{destination}", destinationPath);
            svnCommand = Regex.Replace(svnCommand, "{username}", svnCredentials.Username);
            TrackMessage(context, "svn command: " + svnCommand);

            // Never reveal the password!
            svnCommand = Regex.Replace(svnCommand, "{password}", svnCredentials.Password);

            if (File.Exists(svnToolPath))
            {
                var process = Process.Start(svnToolPath, svnCommand);
                if (process != null)
                {
                    process.WaitForExit();
                    process.Close();
                }
            }

            TrackMessage(context, "End SVN action");
        }
    }
}

To provide a nice UI element with the Svn logo, a custom designer was added (note the “Designer” attribude on top of the SvnActivity class). Here is the designer’s XAML:

<sap:ActivityDesigner x:Class="SvnActivityLib.SvnActivityDesigner"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sap="clr-namespace:System.Activities.Presentation;assembly=System.Activities.Presentation"
    xmlns:sapv="clr-namespace:System.Activities.Presentation.View;assembly=System.Activities.Presentation" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    Collapsible="False" 
    ExpandState="False" 
    UseLayoutRounding="False" 
    d:DesignHeight="22" d:DesignWidth="200" mc:Ignorable="d">
    <sap:ActivityDesigner.Icon>
        <DrawingBrush>
            <DrawingBrush.Drawing>
                <ImageDrawing>
                    <ImageDrawing.Rect>
                        <Rect Location="0,0" Size="16,16" ></Rect>
                    </ImageDrawing.Rect>
                    <ImageDrawing.ImageSource>
                        <BitmapImage UriSource="Resources\Subversion.png" ></BitmapImage>
                    </ImageDrawing.ImageSource>
                </ImageDrawing>
            </DrawingBrush.Drawing>
        </DrawingBrush>
    </sap:ActivityDesigner.Icon>
 </sap:ActivityDesigner>

 

The Build Template, hosting this activity, will requre the following addition to it’s Arguments list:

image

as well as a couple of extra entries in the metadata:

image

After the activity was build and checked in to the CustomActivities location (see the previous post) I was able to configure new values in the build definition:

image

Notice the “Svn arguments” parameter that provides a command line template.

In the build definition metadata I’ve configured only 2 parameters to appear during the build submission (SvnPath and SvnCredentials) so they can be configured in both places (during the editing and the submission), but the rest of the parameters are configured to appear only during the build editing step. This allows any developer to provide his own “patch” source location and his own credentials during the build submission. If your security model doesn’t allow this – make sure to modify the metadata section accordingly.

This is it for now – I’ll talk about the whole credentials mystery in the next post.

Posted in ALM, C#, Continous Integration, Source Control, TFS, Tutorials, Workflows | 1 Comment »

Can TFS be useful if the sources are in Subversion (SVN)? Or how to run integration and nightly builds on TFS from SVN?

Posted by Igor Moochnick on 12/26/2010

This is the question that I’ve been asked multiple times during my Microsoft ALM tools presentations and trainings. So I’ve decided to post a series of articles that will show the path that we had to walk to teach the TFS to run our builds from SVN.

This will be helpful for you especially if you have a similar configuration – source code location in SVN but the development tools are still Visual Studio and MSBuild. The projects are combined into the solution files (.sln), etc… I hope you got the picture.

[Disclaimer: To continue you should be familiar with the TFS build workflow and the basics of the TFS administration]

After quite some search I was unable to find any activities that enable the communication with the SVN (except for a custom MSBuild Svn task) so I’ve decided to build my own…

Read the rest of this entry »

Posted in C#, TFS, Tutorials, Workflows | 9 Comments »

Now I have ALL of the Microsoft developer certifications – long journey is over!!!

Posted by Igor Moochnick on 09/09/2009

Now I own the full deck of the Microsoft certifications and I can sit back and relax (beer is in order ;-). Unfortunately, in the startup world that I operate most of the time, it’s not very recognizable achievement, but it’s nice to put these logos on my presentation slide decks and, especially now, I have a very powerful bragging rights – I have ALL of the Microsoft developers certifications !!!

It was a lengthy path and, I should add, a very confusing one. It wasn’t very obvious what certification is a prerequisite to which one and, I must add, I’ve made a couple of mistakes on the road until I’ve discovered a developer’s certification map by Jorgen Thelin that put everything in order and cleared all the confusions.

ms-cert-path-mcpd_4[1]

Posted in .NET, ADO.Net, ASP.NET, C#, Community, Thoughts, WCF, Workflows, WPF | 6 Comments »

Building GWT web clients [Part 4.1] – How to create an Azure RESTful web service?

Posted by Igor Moochnick on 06/08/2009

Prerequisites: make sure that you have all the Azure SDK tools installed for your VS2008.

 

(1) Start by creating a new “Web Cloud Service” project in the Visual Studio. Give it a nice name.

(2) Add a new “WCF Service” to the WebRole project.

(3) Define a required contract:

The most important part here is to put attributes that will tell the WCF in what format to send/receive the message body (XML or JSON) …

[ServiceContract(Name = "service", Namespace = "http://www.igorshare.com")]
public interface IContactManagerService
{
    [OperationContract]
    [WebGet(UriTemplate = "/contacts", BodyStyle = WebMessageBodyStyle.Bare,
       ResponseFormat = WebMessageFormat.Json)]
    List GetAllContacts();

    [OperationContract]
    [WebGet(UriTemplate = "/contacts/{filter}", BodyStyle = WebMessageBodyStyle.Bare,
       ResponseFormat = WebMessageFormat.Json)]
    List GetContacts(string filter);
}

[DataContract]
public class Contact
{
    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }

    [DataMember]
    public string Company { get; set; }
}

(4) Implement the service logic:

public class ContactManagerService : IContactManagerService
{
    private static readonly List Contacts = new List() { ... };

    public List GetAllContacts()
    {
        return Contacts;
    }

    public List GetContacts(string filter)
    {
        string f = filter.ToLower();

        var contacts = from contact in Contacts
                       where contact.FirstName.ToLower().Contains(f) 
                            || contact.LastName.ToLower().Contains(f)
                            || contact.Company.ToLower().Contains(f)
                       select contact;

        return contacts.ToList();
    }
}

(5) Configure it to be exposed as a RESTful service:

To make it REALLY, REALLY simple for you, do this trick:

a) Comment out the system.serviceModel section in the Web.config file

b) Add the Factory attribute to the .svc file


(6) Build the service

 

You’re interested in 2 artifacts of the build:

  1. .cscfg file – configuration for the Cloud Service deployment
  2. .cspkg file – all the bits packaged (zipped)

 

At this moment you have 2 choices:

  1. Run your project in the local Development Fabric (for testing and debugging), or …
  2. Deploy it to the Azure Cloud (for staging or production)

 

To deploy your application to the cloud, do right-click on the CloudService project and select “Publish”.

Visual Studio will launch the Azure Service Developer Portal page. Log-in to your account, create a project and deploy your bits to the staging environment:

clip_image001

 

This is it!  You’re good to go.

BTW: make sure that your application works in the staging environment and then you can push it to Production by just switching it with the Staging.

 

 

Note: Check out a great explanation about the difference between the WCF REST Configuration for ASP.NET AJAX and plain REST Services by Rick Strahl.

Posted in .NET, Azure, C#, Cloud, JSON, REST, Tutorials, WCF | 2 Comments »

Data in the Cloud: Data Camp presentation in Waltham

Posted by Igor Moochnick on 01/30/2009

clip_image001

It was a lot of fun to present last Saturday at the very first Data Camp that was held in Waltham.

Almost every company I worked with needed some ways to store and process huge amounts of data on the cloud – that includes Intel, ICQ/AOL, Symantec and Broadserve. The latter was the worst case scenario – it was an online multimedia streaming on demand.

So, as you can guess, I’ve learned a great deal about this “trade” and, after release of Amazon AWS and, now, Azure, I’ve become a happy man – no more need in setting up and managing your own infrastructure.

In my view, the “DATA in the Cloud” is actually a mix of the following 3 main aspects (“pillars”):

  1. Data Storage
  2. Data Processing
  3. Data Delivery
  4. Access Control (Authentication + Authorization)

Yes, I know – it’s four, but where can you go without mentioning the last one? Nowhere – you’ll be eaten alive 😉

In this presentation I’ve tried to distill all the different ways that Azure Fabric (Platform and Services) helps you to address all the (first) 3 aspects of working with the “Data in the Cloud”.

Enjoy the presentation!        (URL is here) 

While at this: I’d like to thank the organizers of the Waltham Data camp and Microsoft for providing support and the great location!!!

Posted in Azure, C#, Cloud, Presentations, Thoughts, Tutorials | 1 Comment »