Category: .NET

Dependency injection choice

For a personal pet project I have needed a DI framework . It relates to WebApi – I need to switch the provider for web api between a console and web – mostly authentication / logging different.

Some years ago was only StructureMap – but now there are a lot.

So I started to investigate to choose between the DI frameworks.

What I have wanted:

 

1. open license to use in a project – and source code too – to can upgrade.

2. Updated to the last .NET framework ( so , for .NET 10.0 , I will not be left to upgrade myself the source code – I am lazy too)

3. Speed

4. Last but not least:  easy to use – have some simple example to start me with

 

The first link found was:

http://fukyo-it.blogspot.ro/2012/10/comparing-net-di-ioc-frameworks.html  – it helps about license . Recomends Autofac. I was not very sure about.

Let’s see who have updated the source code to .NET 4.5 . I started looking at github and google code – and , yes, all are updating the source to the latest framework.

For speed I consider relevant http://www.palmmedia.de/Blog/2011/8/30/ioc-container-benchmark-performance-comparison  – if you look down , latest update was(quoting):

“17.11.2013: Added Grace. Updated several containers.”

Recommends  Simple Injector . And from his page seems simple to use.

So my choice is Simple Injector . If you use a DI, please say in the comments what DI and  why.

SameId – skip

In the previous post I have show how two users can see each other if they are editing the same product ( in my example , product id 5)

But not in all cases the users should be notified about each other – like in , let’s say, view product Id 5.

In this case we have an attribute to apply to the action [SameIdSkip]

A video will show you :

Same object edited by 2 users–proactively notifying users

This is a practical example about how two users that comes on the same page will be notified one about other( after an idea of Adrian Petcu) . See the picture :

image

With the NuGet package you can install in your application in this steps:

To run :
1. install package from Nuget
2. in Filter.Config add following line:  filters.Add(new SameIdAlert.SameIdFilter());
3. In Route.Config, after
routes.MapHubs();
GlobalHost.DependencyResolver.Register(typeof(IAssemblyLocator) ,() => new SameIdAlert.SameIdAssemblyLocator());
4. In the View that you want the user to be notified add the following lines in the @section scripts{
<!–Script references. –>
<!–The jQuery library is required and is referenced by default in _Layout.cshtml. –>
<!–Reference the SignalR library. –>
<script src=”~/Scripts/jquery.signalR-1.1.3.js”></script>  <!–or whatever signalr library version you have –>
<!–Reference the autogenerated SignalR hub script. –>
<script src=”~/signalr/hubs”></script>
<!–SignalR script to update the chat page and send messages.–>

and somewhere:

@{Html.RenderPartial(“SameId”);}

5. In _Layout  move jquery declaration
@Scripts.Render(“~/bundles/jquery”)

before RenderBody

6. If you decide to put into _Layout and you want to skip an action, please put  [SameIdSkipAttribute] to the action

7. If you want more action parameters than the default id , just put
[SameIdAttribute(“parameter name 1″,”parameter name2”)
to the action
8. If you decide that you want just several actions then modify
filters.Add(new SameIdAlert.SameIdFilter(false));
and put
[SameIdAttribute]
View online at http://SameId.apphb.com

Source code at https://github.com/ignatandrei/SameId

NuGet package at https://www.nuget.org/packages/sameid

Video demo at http://youtu.be/wjkoMs98Z8U

If you want to help me, see the issues that can be solved here:https://github.com/ignatandrei/SameId/issues

.tt files to maintain assembly version in sync

Let’s suppose you have a medium-big application and you have several dll-assemblies-component that the main application references( DAL, BLL). You have several deployments of the application at clients and , when a client , you must find each version of each assembly deployed.

I have developed a simple .tt file to  ensure that every component that you compile have the same version – you can run on the server on the automatic build(http://www.olegsych.com/2010/04/understanding-t4-msbuild-integration/) or by hand.

More, with this .tt file you can

    1. Have the date /time ( with minute) of the compile of the dll embedded into version information
    2. Read a text file and add same copyright to all projects( left as an exercise to the user) .

 

You can see the demo at http://youtu.be/PudBWl16308 .

You can download the project at https://github.com/ignatandrei/AssemblyInfoTT

Attach to IIS and Stop Build– packages for better VS2012

 

If you work in VS2012 and want to debug your site in  IIS with just CTRL+SHIFT+F1, then please see http://visualstudiogallery.msdn.microsoft.com/928617dc-d747-4577-bd19-8514d7efa8a7 

If you work in VS2012 and want to stop build for other projects right after an error for a project ,then please see http://visualstudiogallery.msdn.microsoft.com/a20bb171-0cab-453e-a64b-15197250f81f

The source are found under https://github.com/ignatandrei

( For VS2010 I have 2 macros – you can see them on my Romanian programming blog ).

MVC , JsonResult , DateTime and TimeZone

The jsonresult of date time is serializing to the string /Date and some integer value starting with 1970 . The problem is that the browser interprets this value accordingly to the LOCAL TimeZone – and thus the same date is going to be interpreted with a difference.

I was thinking that I can adjust from UTC time offset of the server( obtained with .NET from TimeZoneInfo.Local.BaseUtcOffset.TotalMinutes) and the UTC time offset of the client( obtained with (new Date()).getTimezoneOffset() + UTCServerMinutes; ). Unfortunately, the code does not work for SAMOA ( 13 hours difference).

Pay attention that the server is sending SAME data – just the browser is interpreting from the local user time zone.

So the solution is to convert the  date to a string ( I have chosed yyyy-MM-ddTHH:mm:ss) and interpret in javascript( see date2 below).

The server code – I have put my birthdate 16 april 1970

DateTime res = new DateTime(1970, 04, 16, 22, 0, 0);
[HttpPost]
        public JsonResult GetDateBirth()
        {

            var str = res.ToString("s");
            return Json(new { date =res, datestring=str, ok = true });

        }

The Javascript code:

function GetJsonDate() {
        $.ajax({
            type: "POST",
            url: '@Url.Action("GetDateBirth")',
            datatype: "JSON",
            contentType: "application/json; charset=utf-8",
            success: function (returndata) {
                if (returndata.ok) {
                    window.alert('The server is sending:' + returndata.date + " -- " + returndata.datestring);
                    var d = parseInt(returndata.date.substr(6));
                    var date1 = new Date(d);
                    var date2 = dateFromSortable(returndata.datestring);
                    var date3= getDateString(returndata.date);
                    window.alert('original: ' + date1  + '\r\n'  + ' iso correct:'+ date2 + '\r\n'+ ' utc difference not good:' + date3);

                }
                else {
                    //this is an error from the server
                    window.alert(' error : ' + returndata.message);
                }

            }
        }
        );
    }
    function dateFromSortable(dateStr) {
        var parts = dateStr.match(/\d+/g);
        return new Date(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);
    }
    
    function getDateString(jsonDate) {
        //does not work correctly for SAMOA - it have some hours difference
        var UTCServerMinutes = @serverMinutes;
        if (jsonDate == undefined) {
            return "";
        }
        var utcTime = parseInt(jsonDate.substr(6));

        var dateUtc = new Date(utcTime);

        var minutesOffset = (new Date()).getTimezoneOffset() + UTCServerMinutes;

        var milliseconds = minutesOffset * 60000;
        var d = new Date(dateUtc.getTime() + milliseconds)
        return d;
    }

How to test it:

Run the project. Click “Get Json Date” – and you will see the three dates equal.

image

Now change the time zone to Samoa ( or other, if you live in Samoa Winking smile)

image

Click again on “Get Json Date”  – the date will  same 16 april 1970 just for the date2  – obtained from dateFromSortable javascript function.

image

Please note that the local time zone is NOT affecting the values transmitted via ViewBag/ViewData/Model, but just the ones transmitted via Json.

The project can be downloaded from here

How to become a more skilled developer in .NET

I am a good developer in .NET . However, I will not be so good, if there will be not my tools – that allows me to save time and make projects faster.

I have published the tools that I work with in 2012 .

If you are interested in fast training to those tools , I am ready to have 2 days ( 4 sessions – each of 3 hours) with those tools

 

  1. Logging: Nlog
  2. Mocking tools: Moq
  3. Sending emails: smtp4dev
  4. Generating documents: stringtemplate
  5. Testing: xunit
  6. CSV reader: FileHelpers
  7. Database profiling: EF Profiler
  8. Web Scrapping: HtmlAgilityPack
  9. Exporting PDF: ItextSharp
  10. Jquery addons: numeric, datepicker, watermark, select2, tinymce
  11. Zip files : zipsharp
  12. Template generating: .tt files

( and you can ask for every item from http://msprogrammer.serviciipeweb.ro/programmer-tools/ )

 

For each item I will do a description , an example and a homework to be done..

After the training you will be more knowledgeable about those tools and you will have more items under your belt when solving programming problems.

For more than 11 trainees , the fixed price is 80 EUR / trainee ( VAT and travel expenses not included).

Please contact me on the comments and/or use my email address at upper right corner of this blog.