Technical Insights: Azure, .NET, Dynamics 365 & EV Charging Architecture

Category: .NET Page 2 of 4

Dotnet general

Dependency Injection using Simple Injector Tutorial

This is a simple tutorial in how to use Dependency Injection using SimpleInjector (You can get this package from NuGet)

In this case, I use SimpleInjector to manage my Data Context – I want my Data Context to be per request (Unit of Work per request). The concept of this dependency Injection is to have a global container where you can resolve your object from

1. Create an extension method to the Simple Injector

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using SimpleInjector;
  6. using System.Diagnostics;
  7. using System.Linq.Expressions;
  8. ///<summary>
  9. /// Extension methods for registering types on a per web request basis.
  10. ///</summary>
  11. public static partial class SimpleInjectorPerWebRequestExtensions
  12. {
  13.     [DebuggerStepThrough]
  14.     public static void RegisterPerWebRequest<TService, TImplementation>(
  15.         this Container container)
  16.         where TService : class
  17.         where TImplementation : class, TService
  18.     {
  19.         Func<TService> instanceCreator =
  20.             () => container.GetInstance<TImplementation>();
  21.         container.RegisterPerWebRequest<TService>(instanceCreator);
  22.     }
  23.     [DebuggerStepThrough]
  24.     public static void RegisterPerWebRequest<TService>(
  25.         this Container container,
  26.         Func<TService> instanceCreator) where TService : class
  27.     {
  28.         var creator =
  29.             new PerWebRequestInstanceCreator<TService>(instanceCreator);
  30.         container.Register<TService>(creator.GetInstance);
  31.     }
  32.     [DebuggerStepThrough]
  33.     public static void RegisterPerWebRequest<TConcrete>(this Container container)
  34.         where TConcrete : class
  35.     {
  36.         container.Register<TConcrete>();
  37.         container.ExpressionBuilt += (sender, e) =>
  38.         {
  39.             if (e.RegisteredServiceType == typeof(TConcrete))
  40.             {
  41.                 var transientInstanceCreator = Expression.Lambda<Func<TConcrete>>(
  42.                     e.Expression, new ParameterExpression[0]).Compile();
  43.                 var creator = new PerWebRequestInstanceCreator<TConcrete>(
  44.                     transientInstanceCreator);
  45.                 e.Expression = Expression.Call(Expression.Constant(creator),
  46.                     creator.GetType().GetMethod(“GetInstance”));
  47.             }
  48.         };
  49.     }
  50.     [DebuggerStepThrough]
  51.     public static void DisposeInstance<TService>() where TService : class
  52.     {
  53.         object key = typeof(PerWebRequestInstanceCreator<TService>);
  54.         var instance = HttpContext.Current.Items[key] as IDisposable;
  55.         if (instance != null)
  56.         {
  57.             instance.Dispose();
  58.         }
  59.     }
  60.     private sealed class PerWebRequestInstanceCreator<T> where T : class
  61.     {
  62.         private readonly Func<T> instanceCreator;
  63.         internal PerWebRequestInstanceCreator(Func<T> instanceCreator)
  64.         {
  65.             this.instanceCreator = instanceCreator;
  66.         }
  67.         [DebuggerStepThrough]
  68.         public T GetInstance()
  69.         {
  70.             var context = HttpContext.Current;
  71.             if (context == null)
  72.             {
  73.                 // No HttpContext: Let’s create a transient object.
  74.                 return this.instanceCreator();
  75.             }
  76.             object key = this.GetType();
  77.             T instance = (T)context.Items[key];
  78.             if (instance == null)
  79.             {
  80.                 context.Items[key] = instance = this.instanceCreator();
  81.             }
  82.             return instance;
  83.         }
  84.     }
  85. }

2. Modify Global.asax – The class name will be MvcApplication in MVC Project

Code Snippet
  1. #region “Dependency Injection”
  2.         private static Container Container;
  3.         public static T GetInstance<T>() where T : class
  4.         {
  5.             return Container.GetInstance<T>();
  6.         }
  7.         protected void RegisterDependency()
  8.         {
  9.             //Create a main containers
  10.             var container = new Container();
  11.             // 2. Configure the container (register)
  12.             container.RegisterPerWebRequest<IUnitOfWork>(() => new UnitOfWork(new PosDataContext()));
  13.             container.Register<ITableRepository, TableRepository>();
  14.             container.Verify();
  15.             Container = container;
  16.         }
  17.         #endregion
  18.         protected void Application_Start()
  19.         {
  20.             AreaRegistration.RegisterAllAreas();
  21.             RegisterGlobalFilters(GlobalFilters.Filters);
  22.             RegisterRoutes(RouteTable.Routes);
  23.             BundleTable.Bundles.RegisterTemplateBundles();
  24.             RegisterDependency();
  25.         }
  26.         protected void Application_EndRequest(object src, EventArgs e)
  27.         {
  28.             ServiceStack.MiniProfiler.Profiler.Stop();
  29.             SimpleInjectorPerWebRequestExtensions.DisposeInstance<IUnitOfWork>();
  30.         }

3. Consume it from the controller – Call the container in the Global.asax to resolve the object (GetInstance function)

Code Snippet
  1. public ActionResult Index()
  2.         {
  3.             ViewBag.Title = “Tables”;
  4.             return View(MvcApplication.GetInstance<IUnitOfWork>().TableRepository.Get(e => e.Active));
  5.         }

IoC Container Benchmarks

I found this benchmark for different IoC in .NET. Personally I’ve been using Unity, Ninject and SimpleInjector. I like SimpleInjector because it is very simple and surprisingly it is quite fast compared with the rest. Performance is just one of the aspect of IoC but it doesn’t always mean everything

http://www.palmmedia.de/Blog/2011/8/30/ioc-container-benchmark-performance-comparison

http://www.iocbattle.com/

How to Debug WCF Service Issue?

1. Change the app.config/web.config of your application that calls the WCF service by adding System.diagnostics detail as below

Code Snippet
  1. <system.diagnostics>
  2.     <sources>
  3.       <source name=System.ServiceModel switchValue=Verbose,ActivityTracing propagateActivity=true>
  4.         <listeners>
  5.           <add type=System.Diagnostics.DefaultTraceListenername=Default>
  6.             <filter type=“” />
  7.           </add>
  8.           <add name=ServiceModelTraceListener>
  9.             <filter type=“” />
  10.           </add>
  11.         </listeners>
  12.       </source>
  13.       <source name=System.ServiceModel.MessageLogging switchValue=Verbose,ActivityTracing>
  14.         <listeners>
  15.           <add type=System.Diagnostics.DefaultTraceListenername=Default>
  16.             <filter type=“” />
  17.           </add>
  18.           <add name=ServiceModelMessageLoggingListener>
  19.             <filter type=“” />
  20.           </add>
  21.         </listeners>
  22.       </source>
  23.     </sources>
  24.     <sharedListeners>
  25.       <add initializeData=MyWCFTraceLog.svclog
  26.       type=System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
  27.       name=ServiceModelTraceListenertraceOutputOptions=Timestamp>
  28.         <filter type=“” />
  29.       </add>
  30.       <add initializeData=MyWCFTraceLog.svclog
  31.           type=System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
  32.           name=ServiceModelMessageLoggingListenertraceOutputOptions=Timestamp>
  33.         <filter type=“” />
  34.       </add>
  35.     </sharedListeners>
  36.     <trace autoflush=true />
  37.   </system.diagnostics>

2. Run your application as usual until it throws the error or until the stage where you can reproduce your issue, once you are done, quit your application or take out the diagnostics section from the config file straight away so your log will not be growing too quickly/massively

3. The log file will be called as MyWCFTraceLog.svclog (as we define in the config file) and it will be located on the same folder as the executable – normally it is in the bin folder

4. How to open svclog file? Go to your program files (x86) or program files/Microsoft SDKs/Windows/v7.0A/Bin/SvcTraceViewer.exe

5. SVCTraceViewer will display you the story line of your WCF and it will help you to pinpoint the underlying issue

Umbraco Installation in Shared Web Hosting

I tried to install umbraco in shared webhosting from the control panel but instead the error that I’m getting is

The application could not be installed: Error occured in Web App Gallery module

From my research it seems that there is an error in the Web App Gallery module, some article it says that the Web App Gallery module is out of date. But this is shared web hosting so there is nothing much I can do to fix this. So how to install umbraco manually?

1. Create a blank DB in your SQL Server 2008 for your Umbraco

2. Create a SQL User for the Umbraco DB in the step 1

3. Download umbraco from http://umbraco.codeplex.com

4. Extract the content to the downloaded package to the root of your domain wwwroot folder via FTP

5. Make sure the default website is already created

6. Make sure the .NET framework is being set to .NET 4.0 (Integrated)

7. Run the installation through www.yourdomain.com/install/default.aspx

8. Follow the steps, it will ask you the database name and the database user along the way

9. Once the installation finished, please make sure you delete the install folder for security purpose

Cleanup File name from invalid characters

I have a function that is used to save a file base on the user input (basically the user can type whichever filename and whichever path) and the code is not handling the invalid filename or path hence what it does is just throwing .NET general exception like below

To fix it I created a new function that basically get the invalid path characters and invalid filename characters from the system and remove invalid character in the input (file name). By doing this the user does not need to replace the character.

If you use Path.GetFileName it will actually remove the illegal character automatically but the way it removes the illegal character is so aggressive

e.g Path.GetFileName(“c:\workflow\Clearance:Photo ID Badge:Access abc-123.ist”) will return Access abc-123.ist

Well this problem itself will give different argument like why do we let people put the garbage character in?and why don’t we give the validation?or the other argument is “why do we need to change the input from the user without letting them knowing it?

  236    ”’ <summary>

237     ”’ this function is used to clean up invalid/illegal characters from filename and replace it with blank

238     ”’ </summary>

239     ”’ <param name=”FileName”></param>

240     ”’ <returns></returns>

241     ”’ <remarks></remarks>

242     Private Function CleanFileName(ByVal FileName As String) As String

243         Dim invalid As String = New String(Path.GetInvalidFileNameChars()) + New String(Path.GetInvalidPathChars())

244         Dim originalPath As String = FileName.Substring(0, FileName.LastIndexOf(“\”) + 1)

245         FileName = FileName.Substring(FileName.LastIndexOf(“\”))

246

247         For Each c As Char In invalid

248             FileName = FileName.Replace(c.ToString(), “”)

249         Next

250

251         ‘readd the path

252         FileName = originalPath + FileName

253

254         Return FileName

255     End Function

Web Service Tester

This is an application to access your Web Service/API without worrying to create your own client application for the sake of testing. Personally, I’m using soapUI (an open source application to test web service)

http://sourceforge.net/projects/soapui/files/

I’d prefer to use tool this because it provides you a transparent communication between the client and the Web Service and it’s really simple to use and configure. It’d save you a lot of time to debug the issue for your client. You can trace it down whether the issue is in the client or in the web service itself

Profiling CLR for .NET application

CLR Profiler can be used to analyse how your object is allocated in memory and which object has taken the most memory. It also can be used to detect memory leak

To download CLR profiler for .NET 2.0 please visit http://www.microsoft.com/download/en/details.aspx?id=13382 , there is another version for .NET framework 1.1

-Extract the file into your desired location

-you also need to run “regsvr32 ProfilerOBJ.dll” otherwise you will get dialog message that mentioned it’s waiting for the CLR and you will not get any result

– Run the CLRProfiler.exe in Binariesx86 if your app is 32 bit and Binariesx64 if your app is 64 bit

For profiling windows app, you can do the following steps:

1. Select the exe file

2. Do stuff/interact with your application

3. Once you are finished then you can close your application or select “Kill Application”

4. Upon completion it will give you the screen below

For profiling ASP.NET app, you can do the following steps:

1. Select Profile ASP.NET from file menu

2. It will restart your IIS with the necessary trace

3. Select “Start ASP.NET”

4. Once you are finished then select “Kill ASP.NET”

5. It will restart the IIS and remove the trace added before

6. Upon completion it will give you the screen below

*You can use this for service as well –

This is the information for GC

Remapping svc extension in IIS 7 extension handlers

If you open your WCF/ svc file in your localhost through browser and it just display blank page then what might happen is you don’t have handler associated with svc extension

To verify it, go to your IIS and go to IIS Handler Mappings and try to find an svc extension entry, but if you couldn’t find extension SVC exists on the list, then you can remap/re-add the svc extension by running

C:\Windows\Microsoft.NET\Framework64\v3.0\Windows Communication Foundation\ServiceModelReg.exe –i

*if you are still using 32 bit then you just need to replace Framework64 with Framework

Using Disposable object

First method is to use the “Using” keyword which is quite clean and simple

using (IDisposable obj = new DataTable())

{

//do your logic with obj variable

}

Second method is to use Try and finally keyword

IDisposable obj = null;

try

{

obj = new DataTable();

}

finally

{

if (obj != null)

{

obj.Dispose();

}

}

Remove UTF8 BOM Character from the file

Normally when you have a UTF8 encoded file then it might have BOM character that will be rendered when you read it using filestream even though when you open the file with the notepad it doesn’t have that character.

I’ve created a function to remove the BOM character from the file

private void removeBoms(string filePattern, string directory)

{

try

{

foreach (string filename in Directory.GetFiles(directory, filePattern))

{

var bytes = System.IO.File.ReadAllBytes(filename);

if (bytes.Length > 2 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF)

{

System.IO.File.WriteAllBytes(filename, bytes.Skip(3).ToArray());

}

}

MessageBox.Show(“Files have been processed completely!”);

}

catch (Exception ex)

{

MessageBox.Show(ex.ToString());

}

//uncomment this for recursive

//foreach (string subDirectory in Directory.GetDirectories(directory))

//{

//    removeBoms(filePattern, subDirectory);

//}

}

How to call it

private void btnProcess_Click(object sender, EventArgs e)

{

string extension = txtExtensions.Text;

if (extension.Trim().Length > 0 || folderBrowserDialog1.SelectedPath.Trim().Length > 0)

{

if (!extension.StartsWith(“*.”))

{

extension = “*.” + extension;

}

//just process the html files

removeBoms(extension, folderBrowserDialog1.SelectedPath);

}

else

{

if (extension.Trim().Length == 0)

{

txtExtensions.Focus();

MessageBox.Show(“Please specify the extension files”);

}

else if (folderBrowserDialog1.SelectedPath.Trim().Length == 0)

{

MessageBox.Show(“Please select target folder”);

}

}

}

Page 2 of 4

Powered by WordPress & Theme by Anders Norén