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 :)

Introduction to Dapper.NET ORM in ASP.NET 5

Standard

Dapper.NET is an open source, high performance Micro-ORM supporting Sql Server, MySQL, Sqlite, SqlCE, Firebird etc, from Stack Overflow team. Drapper provides extension methods for IDbConnection, so you require an instance of IDbConnection to use Dapper. To use Dapper, you need to include Dapper in the project.json file. In this post I am using Repository pattern and injecting the repository to the controller via constructor injection.

Here is the project.json file, the EntityFramework.SqlServer reference is required to use IDbConnection interface.

{
  "dependencies": {
    "Microsoft.AspNet.Diagnostics": "1.0.0-beta2",
    "Microsoft.AspNet.Hosting": "1.0.0-beta2",
    "Microsoft.AspNet.Mvc": "6.0.0-beta2",
    "Microsoft.AspNet.Server.WebListener": "1.0.0-beta2",
    "EntityFramework.SqlServer": "7.0.0-beta2",
    "Microsoft.AspNet.StaticFiles": "1.0.0-beta2",
     "Dapper":"1.38.0-*"
  },
  "commands": {
    "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5010",
  },
  "frameworks": {
    "aspnet50": {}
  }
}

Here is the constructor of the respository class. In this I am creating the instance of SqlConnection.

private IDbConnection _connection;
public EmployeeRepository()
{
	_connection = new SqlConnection("Server=.\\SQLEXPRESS; Database=DemoDb; Integrated Security=SSPI");
	_connection.Open();
}

Dapper extends the IDbConnection with Query method, which you can use to execute a query and map the result to a strongly typed object or list of objects.

public Employee Get(int? id)
{
	return _connection.Query<Employee>("SELECT * FROM Employees WHERE Id = @Id", new{ Id = id }).FirstOrDefault();
}

public IEnumerable<Employee> FindAll()
{
	return _connection.Query<Employee>("SELECT * FROM Employees");
}

You can use Execute method to execute DML queries as well to the Database.

public void Save(Employee employee)
{
	_connection.Execute("INSERT INTO Employees(Name,Designation,JoiningDate,Remarks) VALUES(@Name,@Designation,@JoiningDate,@Remarks)", employee);
}

public void Delete(Employee employee)
{
	_connection.Execute("DELETE FROM Employees WHERE Id=@Id", employee);
}

Dapper also supports Stored Procedures as well. You need to provide the command type parameter.

public void Update(Employee employee)
{
	_connection.Query("usp_UpdateEmployee", employee, commandType: CommandType.StoredProcedure);
}

You can use Dapper in ASP.NET or any .net applications, for that you need to include the Dapper nuget reference. You can find more details about Dapper from Dapper wiki

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 :)