How to identify static class using reflection

Standard

Today someone asked me, how to find static class from list of types. I was against the implementation he was doing, but still I couldn’t find how to find static class. Later I did some research and I found like you need to look for IsAbstract and IsSealed properties of the type.

Here is source code, which identify the static class from the list of available types in the assembly.

class Program
{
    static void Main(string[] args)
    {
        var types = Assembly.GetExecutingAssembly().GetTypes();
        types.Where(x => x.IsAbstract && x.IsSealed).ToList()
            .ForEach(Console.WriteLine);
    }
}

static class StaticClass { }

sealed class SealedClass { }

interface Interface { }

class NormalClass { }

abstract class AbstractClass { }

If you run the above code, it will print the StaticClass name.

Happy Programming :)

k web command and agile development environment

Standard

With the new version of ASP.NET, you can avail the flexibility of deploying your app via an agile app development methodology, where you can modify and save the C# file and refresh the browser, your changes will be updated automatically. You don’t need to go for any explicit compilation in Visual Studio. The in-built .NET Compiler Platform ROSLYN available with ASP.NET vNext handles app deployment transparently in either the server or the development machine. This feature is only available with Visual Studio, it won’t work with “k” command. The k command comes with –watch switch, documentation says “Watch file changes”, but it is also not working. When there is a file change, it will stop the server. I found few Node plugins for this purpose. Today I thought of writing a C# implementation.

Here is the implementation, I have a FileSystem watcher, which will monitor the files inside the directory, will raise events on file changes, if there is a change, it will restart the server. For some files, like project.json, if there is change, it will restore the packages and restart the server.

Implementation – File System watcher – Listening on file system change events

static void Main(string[] args)
{
    var currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
    var fileSystemWatcher = new FileSystemWatcher(currentDirectory);
    fileSystemWatcher.IncludeSubdirectories = true;
    fileSystemWatcher.NotifyFilter = NotifyFilters.LastAccess
        | NotifyFilters.LastWrite
        | NotifyFilters.FileName
        | NotifyFilters.DirectoryName;
    fileSystemWatcher.Changed += new FileSystemEventHandler(OnChanged);
    fileSystemWatcher.Created += new FileSystemEventHandler(OnChanged);
    fileSystemWatcher.Deleted += new FileSystemEventHandler(OnChanged);
    fileSystemWatcher.EnableRaisingEvents = true;

    Console.WriteLine("Starting server");
    StartProcess("k --watch web");
    Console.WriteLine("Press \'q\' to quit the web monitor.");
    while (Console.Read() != 'q') ;
}

Here is the implementation – Starting / Restarting server and restoring packages.

private static Process StartProcess(string arguments)
{
    var filename = "cmd.exe";
    var processStartInfo = new ProcessStartInfo(filename, " /C " + arguments);
    processStartInfo.RedirectStandardError = true;
    processStartInfo.RedirectStandardInput = true;
    processStartInfo.RedirectStandardOutput = true;
    processStartInfo.CreateNoWindow = true;
    processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    processStartInfo.UseShellExecute = false;
    var process = Process.Start(processStartInfo);

    process.EnableRaisingEvents = true;
    process.OutputDataReceived += (o, dre) =>
    {
        Console.WriteLine(dre.Data);
    };

    process.BeginOutputReadLine();
    return process;
}

And here is the core part – OnChanged, which will listen the file changes and based on the file type do the process.

private static void OnChanged(object source, FileSystemEventArgs e)
{
    DateTime lastWriteTime = File.GetLastWriteTime(e.FullPath);
    if (lastWriteTime != _lastRead)
    {
        var extension = Path.GetExtension(e.Name);
        if (extension.Equals(".json"))
        {
            Console.WriteLine("{0} file modified. Package restore starting", e.Name);
            var process = StartProcess("kpm restore");
            process.WaitForExit();
            if (process.ExitCode == 0)
            {
                Console.WriteLine("Package restore completed successfully. Restarting server.");
                process = StartProcess("k --watch web");
                process.WaitForExit();
            }
            else
            {
                Console.WriteLine("Package restore failed. Please make sure your {0} file is valid.", e.Name);
            }
        }
        else
        {
            Console.WriteLine("{0} file modified. Restarting server", e.Name);
            var process = StartProcess("k --watch web");
            process.WaitForExit();
            if (process.ExitCode != 0)
            {
                Console.WriteLine("Server restart failed. Please make sure you can compile {0} file.", e.Name);
            }
        }

        _lastRead = lastWriteTime;
    }
}

There is a problem with FileSystemWatcher Changed event, when ever there is change, FileSystem watcher will raise the OnChanged event twice. To overcome this issue, the _lastRead and lastWriteTime variables used. Here is the screenshot of kmonitor.exe running on my system.

kmonitor - running

kmonitor – running

Here is the gist for kmonitor

Happy Programming :)

How Intercept HTTP calls from WCF client to service

Standard

Today I faced some problem, I had to intercept HTTP calls from WCF proxy to WCF service. I was using Fiddler 4. But unfortunely it was not working :( I tried many options.(It was not working for me, but it may work for you)

  1. By using system.net proxy setting – In the clientapp.exe.config, you need to add following configuration settings.
    <system.net>
      <defaultProxy enabled="true">
        <proxy proxyaddress="http://127.0.0.1:8888" bypassonlocal="False" />
      </defaultProxy>
    </system.net>
    
  2. By using useDefaultWebProxy attribute in the binding element.
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IService1" 
                 useDefaultWebProxy="false" />
      </basicHttpBinding>
    </bindings>
    

    For me it is also not working :(

  3. By using Hostname instead of localhost. – This is the only solution worked for me. :) Modify you clientapp.exe.config, and change the endpoint address from localhost to the actual host name.
    <client>
      <endpoint address="http://anurajp/WcfService1/Service1.svc" 
          binding="basicHttpBinding"
          bindingConfiguration="BasicHttpBinding_IService1" 
          contract="ServiceReference1.IService1"
          name="BasicHttpBinding_IService1" />
    </client>
    

    This is the proxy request and response captured using Fiddler.

    WCF Request and Response using Fiddler

    WCF Request and Response using Fiddler

    Happy Programming :)

Continuous Deployment (GitHub) with Azure Web Sites

Standard

Windows Azure websites supports Continuous Deployment. Continuous Deployment can be thought as an extension of continuous integration, where when ever users commit a changeset, build will be triggered. And in case of Continuous Deployment, the changes will be published to your live application directly from source control, when ever user commits a changeset. This is a fantastic automation feature that can be leveraged from a range of source control tools such as Visual Studio Online and others (GitHub, BitBucket, DropBox, CodePlex, or Mercurial) . Azure websites supports staged publishing (it is in Preview state) as well, so if you don’t want to publish your changes direcly to live, you can deploy it to staging and verify it. Once verification is completed, you can push the staging to live.

In this post I will be describing the deploying to direct live environment approach only. I am using GitHub as my source control. First you need to create Website. You can do it from Azure portal or from Visual Studio. Once you created website, go to the Dashboard and select the option “Set up deployment from source control”

Set up deployment from source control

Set up deployment from source control

Now select GitHub from the list.

GitHub from Source code repository list

GitHub from Source code repository list

Azure will popup GitHub authentication and authorization window, once you authorize, you need to select the source code repository.

Select GitHub repository

Select GitHub repository

Once you choose source code repository, if the repository contains source, it will be pushed to the live environment. To verify continues deployment, you can modify the source and publish the changes.

In this post I have enabled Continuous Deployment for a HTML5 single page application. Now I am integrating VisualStudio online Application Insights code to the HTML page.

Integrating application insight code to HTML Page

Integrating application insight code to HTML Page

Now commit the changes (I have added a description – “Application insights code added Application insights code added”) and publish the source code. You can verify the Deployments Tab in Azure portal and can see the changeset applied.

Deployments Tab in Azure portal

Deployments Tab in Azure portal

You can see the comment in the active deployment – “Application insights code added Application insights code added”

I will post about staging deployment later.

Happy Programming :)