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);
        public JsonResult GetDateBirth()

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


The Javascript code:

function GetJsonDate() {
            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.datestring);
                    var d = parseInt(;
                    var date1 = new Date(d);
                    var date2 = dateFromSortable(returndata.datestring);
                    var date3= getDateString(;
                    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.


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


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


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

Table press and searching

I have made my programming tools list with Excel, TablePress and script.

First, the list was existing in Excel – with columns as name, tag, description and url.

I have saved as CSV and imported in TablePress – with some modification for url as TablePress understands it ( you should have the a href embed in the cell).

The difficult part was searching – so I can have those headers that will complete the search:



So I was making my own javascript for that:

function b(a){
var $j = jQuery.noConflict();

$j("#tablepress-2_filter :input").val(a);

I do not know how to make a plugin for WordPress – but I think it is not so terrible. However, I let others make it .

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 )


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.

programming tools 2012

Those are the tools that I haved worked with in my previous year.
If you want to know how to utilize them, just ask me ;-).

All tools utilities


source code



Visual studio






(LocalDB) for sql server 2012programming tool;databasefinally, a deploy fast database
.tt filesprogramming toolprogrammer best fried to generate code from database
7-ZiputilitiesCan handle archive files (zip, rar, iso and many others)
all in one gesturesfirefox addonsclose - open pages fast
AutoFixtureframework; dataauto generating data
AutoMapperprogramming toolmapping from database models to ViewModels - to preserve database independence
azure providersazure toolsazure storage data access
azure storage explorerazure toolsazure acces demo
chrome developer toolschrome addondebugging js code, see html, modifying
CleanProjectutilities; visual studiocleans bin and zip a project
codeplexprogramming tool;source codesource code version system;just online
Coding4Fun Kinect Toolkitkinect toolsadditional helper for kinect
cvsprogramming tool;source codesource code version system;could be installed locally
datatablesframework;javascripttables on steroids
dosboxutilities;dosrunning old programs
Ef profilerdatabaseInstrumenting entity framework commands and seeing problems
ef rebinderprogramming toolcomposing expressions
entity framework 4.xframework;databasedatabase handling POCO
fiddlerprogramming toolintercepting http requests
file zillautilities;ftpupload sites and utilities
FileHelpersframework;readerRead in various file formats - csv, etc
Firefox addonsprogramming tool; addonsA collection of firefox addons
forecastfox weatherfirefox addonsweather
foxit readerutilitiespdf fast reader
free commanderutilitiesfile manager - 2 panels
ghost docaddon visual studiogenerating comments
githubprogramming tool;source codesource code version system;just online
github for windowsprogramming tool;accesing git fast
google chromeutilities;browserhtml viewer ;-)
html tidychrome addonverify html
html validatorfirefox addonsvalidate html corectness( first step in design)
HtmlAgilityPackframework;htmlHtml request as XML
ieutilities;browserhtml viewer ;-)
ie developer toosie addondebugging js code, see html, modifying
IIS 7programming tooldeveloping websites on local - make same as for deployment on serverWindows 7
IIS SEO Toolkitprogramming tool;iisseo done fast
imacros for firefoxfirefox addonsautomate testing
Internetutilities;programming toolprogrammer best fried to search for help; blog posts; knowledge sharing
itextsharpframework;pdfmaking pdf files
javascript date formatjavascriptdate time format
Jenkinsprogramming tool;continous integrationautomatically run tests
jqueryframework;javascriptjavascript on steroids
jquery alpha numericframework;javascriptalpha numeric for textbox
jquery numericframework;javascriptnumeric for textbox
jquery uiframework;javascripttab control;dialog;autocomplete;date picker
jquery watermarkframework;javascriptwatermark for textboxes
json2framework;javascriptfor old ie
kinect contribkinect tools;visual studiovisual studio template for kinect
kinect sdkkinect toolskinect sdk with demo
kinect toolboxkinect toolsdetection of gestures
knockoutframework;javascripttemplating on javascript
leech blockfirefox addonsproductivity - do not look at internet sites( facebook)
log4netframework;logginghelp to log various information; does not been imporved from some time
lumisoftframework;emailemail reader
magic diskutilitiesmounting iso
measure itfirefox addonsfind length in the browser
measure itchrome addonfind length in the browser
Microsoft Visual Studio Proffesional 2010 + 2012( +Express)IDEFavorite programming tool
Moqframework;mockingmocking tool ; testing
morning coffeefirefox addonsload sites on click
msbuildprogramming toolproviding actions to deploy autmoatically and many others
msbuildtaskprogramming tool;buildall kind of task run after build
mvc3 + mvc4framework;websiteFavorite developping websites framework
nlogframework;logginghelp to log various information; does not been imporved from some time
notepad ++utilities;programming tooleditor
nugetaddon visual studioAll kind of frameworks for vs
OfficeOpenXMLPart4reference; officeMarkupLanguageReference  for Office XML.(Excel, word)
page speed insightchrome addonmeasure web site performance
PowerCommandsaddon visual studiotransform tt templates per project
productivity power toolsaddon visual studiocommand prompt, may others
psrprogramming tool;helpgenerating helpWindows 7
RazorframeworkMVC simple write mixed code server /html
razor code generatormvc;addon visual studioput MVC views in a dll
Regulator and Regulazyhelpersregular expression helpers
resolution testchrome addontest in broser for different resolutions
reverse equalityaddon visual studioreversing data bound
Save_playlist_in_order_to_mp3_player_V3_2utilities;winamp addonsave playlist
select2javascriptdropdown list on steroids( ajax infinite completing…)
seleniumfast testing htmltesting html easy
send to kindlechrome addonread later various pages
skypeutilities;communicationvoice and video sharing
smtp4devframework;smtplocal email server;helps seeing messages;
Sql CE 4.0programming tool;databasefinally, a deploy fast database
sql search from RedGatesql server manager addonsearch text in columns names and stored proc content
sql serverprogramming tool;databaseExpress version free; database
sql server managerutilities;databaseExpress version free; database management
string templateframeworkgenerating codes from data and visualization; razor avant la letter; coulkd generate excel XML
structure mapprogramming tooldependency injection - code for testing
svnprogramming tool;source codesource code version system;could be installed locally
sysinternals explorer;blue screen;
T4MVCprogramming tool;mvcgenerating MVC names
table pressblogthis post was made with table press( and some modifs)
tfsprogramming tool;source codesource code version system;could be installed locally
tfs power toolsprogramming tool; source codeintegration with explorer
tiny mceframework;javascripthtml editor
tortoise svnprogramming tool;source codeintegration with explorer
TroyGoode-PagedListframeworkMVC provider for simple paging
trx2htmlutilities; visual studiotest results to html
vlc media playerutilitiesvideo player
vs2010 testgenerating data for .load testgenerating code for test ; could modify; database generated id's
web developerfirefox addonsinvestigate site html + css + js + …
Web Essentialsaddon visual studioJIT debugging for HTML - no refresh required
winamputilitiesmusic player
windows live writerutilities;bloggingblog made easy from desktop
winmergeprogramming tooldifference files /folders ( versions from source code)
wordpressblogthis blog
xunitframework;testingtesting programs; VS independent
yahoo messengerutilities; communicationvoice and video sharing
yahoo slowfirefox addonsmeasure web site performance
yahoo slowchrome addonmeasure web site performance
zip sharpframework;zipmaking zip files

You can download as pdf my 2012 tools
If you want more explanations about those tools, I am ready to help you. Please contact me at . I was a teacher – so I can explain easy the programming aspects.
If you have used others, please propose in comments.

Generating Word XML – and error

When you generate Word XML file ( with StringTemplate ) or another tool, and you miss some content, Word does not display the error – instead it puts on a specific folder. And it is troublesome to find that file between more files.

So I create this small powershell program to delete all files from that folder – minus the error file, because the word is keep opening:

$folder = [environment]::getfolderpath(“LocalApplicationData “)
$folder = $folder + “\Microsoft\Windows\Temporary Internet Files\Content.MSO”
get-childitem $folder -include *.log -recurse | foreach ($_) {remove-item $_.fullname} # it will not remove the word error file
get-childitem $folder -include *.log -recurse | foreach ($_) { [System.Diagnostics.Process]::Start($_.fullname) }

MVC and auto persisting values

When you have a textbox in HTML (let’s say

<input name=”FirstName” type=”text” />

And it binds to “FirstName” Property of a Model, and in HttpPost Action you do modify the value and return the same view, the value shown in the textbox is the posted one, not the modified one. ( The first thought is that HttpPost is not executing – but it is a false impression!)
The solution is:

or, better

(and it’s not a bug, it’s a feature: classical example: numeric textbox/ numeric property and user enters “aaa” – the validation error appears and the textbox must have aaa, not 0 or default value for the property )

Redirect and Ajax Redirect in MVC

In the sample example I will have various methods to perform redirects from main page to “About” page of a simple MVC site. In my opinion, there are only 3 cases – 2 goods and one bad – to perform redirection with or without Ajax.


First case:  A sample redirect and a sample link:

The action is

 public ActionResult RedirectToAboutNoAjax()
            return RedirectToAction("About");

and in the View I call in a simple <a href, generated by :

@Html.ActionLink("Redirect no ajax to about", "RedirectToAboutNoAjax", "Home")

When you click the link, the following happens : a 302 Found answer is send to the browser with the new Location. The browser goes to the page requested.

Second case( not good ajax): Call same action from ajax – in hope that ajax will do the redirect alone, without coding further.Modified only the code that calls the action, transforming to ajax.

<a href="javascript:AjaxNotGoodForRedirect('@Url.Action("RedirectToAboutNoAjax", "Home")')">Redirect not good with ajax - returns the page</a>

 What it happens is the same: the ajax code calls the RedirectToAboutNoAjax , that redirects to about – and the result is the page. It is no redirect performed to the page itself – rather, on the ajax itself!And , to proof it, I will show the message of html returned in an message:image

Third case( good with ajax): Call a action that returns the new url as a json data parameter and make javascript know that.The action:

        public ActionResult RedirectToAboutWithAjax()
                //in a real world, here will be multiple database calls - or others
                return Json(new { ok = true, newurl = Url.Action("About") });
            catch (Exception ex)
                //TODO: log
                return Json(new { ok = false, message = ex.Message });

The javascript:

function AjaxGoodRedirect(urlAction) {
            type: "POST", // see
            url: urlAction,
            data: {}, //to send data see more at
            datatype: "JSON",
            contentType: "application/json; charset=utf-8",
            success: function (returndata) {
                if (returndata.ok)
                    window.location = returndata.newurl;


Note: You can combine the returning the RedirectToAction with Json by checking Request.IsAjaxRequest value and returning either FirstCase, either ThirdCase.

You can find the example for download here
If you want more details, please comment – and I will provide any further explanations.

MVC Browser history provider for azure–trying an implementation for 3 hours

first, implement  IBrowserUserHistoryRepository  – that means implement:

public void Save(IEnumerable<BrowserUserHistoryData> history)


Azure have PartitionKey/RowKey – I have to add a new class.

Also or connectiing, I have to put


connectionString="UseDevelopmentStorage=true;" /


I tried to add a bulk history :
The result was:
Unexpected response code for operation : 0
<add key="TableStorageEndpoint" value=""/>
And one hour has been gone.
Run dsinit to have storage emulator:
No connection could be made because the target machine actively refused it

modified code to old Azure code:

now the answer was:

One of the request inputs is out of range. – All letters in a container name must be lowercase.

Tried that – same result:

One of the request inputs is out of range.

Maybe timestam is wrong? No…

Now debug with Fiddler :



Added to connection string:


 And see this in Fiddler :



: base(UserName, UserName)
So the problem is that RowKey does not support url values.
Now , after removing url from the RowKey  - and put username, the error was:

The specified entity already exists

Another hour passes


Now, that it works, thinking about rowkey and partitionkey : no username + url => put date.ToString("yyyyMMdd_HHmmss_tttt")

0:The specified entity already exists.

Oh no, not again?

Look tables =>20121220_064024_AM -  ok, it should be


0:The specified entity already exists

Again? debug, please

The real problem:

Forget about sending whole items history - not just not saved ones…
Now it works – kind of

Server Error in ‘/’ Application.

The method or operation is not implemented.

public IEnumerable<KeyValuePair<string, int>> MostUsed(int Count, DateTime? date)
Line 80:         {
Line 81:             throw new NotImplementedException();
Line 82:         }
Line 83: 
Implementing MostUsed(int Count, DateTime? date) 
Research about filter with data -
Research about GroupBY – not supported!
So now thinking about a way to STORE the data in a convenient format to can retrieve…
 It must take into consideration Count for a date and Count for all dates( date can be null) – AND BOTH THE FACT THAT THE OPERATION WILL BE DONE PER USER.
Time to think – because another hour has passed!

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.