A Place for C Sharpers/.Netters

I Will do coding till last moment of life-Kiran Patil

Nunit results to HTML

Posted by kiranpatils on March 23, 2013

Challenge:

Are you searching for a solution to covert your Nunit results in to HTML format? Then this post is for you! Because couple of weeks back, we were also doing same as you, and after bit of research we found a way to do it! To make your life easy, sharing it here:

Solution:

1. Run your test using Nunit [For batch file we can use nunit-console].

2.  It will create XML result “TestResult.xml”

3. Now using Nunit2Report Console application we can convert XML in to HTML.

e.g. “”c:\test\NUnit2Report.Console.Release.Mixed Platforms.v1.0.0.0\NUnit2Report.Console.exe” –fileset=”C:\test\TestResult.xml””

https://github.com/jupaol/NUnit2Report.Console/

NUnit2Report Console is a tool to transform the NUnit xml results file to an Html user-friendly report using XSL files, the tool was originally designed to be integrated with NAnt as a NAnt task and it was created by Gilles Bayon. This version converts the original NUnittoReportTask to a console version to be able to use it freely without the use of NAnt

Good to read:
http://weblogs.asp.net/thangchung/archive/2010/12/17/generating-report-for-nunit.aspx
http://sourceforge.net/projects/nunit2report/

Happy conversion! :-)

Posted in Nunit | Tagged: | Leave a Comment »

Fast and furious way to LoadXML document

Posted by kiranpatils on March 23, 2013

Challenge:

While loading XMLDocument using LoadXML method we found that sometimes it takes a long time to load xml. Is is a same challenge you are facing? Then this post is for you!

Solution:

http://codinglight.blogspot.in/2009/06/how-to-load-xmldocument-and-completely.html

This article helped us to do so! Basically, when you hit LoadXml Method it, internally validates XML by loading it’s DTD — and if your DTD server is busy it may take time to load.

So, the solution (If it is not breaking your functionality) is set XmlReaderSetting’s — Set XmlResolver to null, and ProhibitDtd to false.

That’s it!

Happy XML Loading! :-)

Posted in .NET, ASP.NET | Tagged: , | Leave a Comment »

Uploadify (Session and authentication) with ASP.NET

Posted by kiranpatils on March 23, 2013

Challenge:

Sorry, comrades for not sharing anything with you since so long. But was bit occupied with other stuff, and as told you earlier that currently my main focus is on my Sitecore blog and yes, with your good wishes and god’s grace — got awarded as Sitecore MVP for the year of 2013! – Thank you!

Before couple of months back, we were trying to incorporate Uploadify [http://www.uploadify.com/documentation/] in to our solution. And while working on that we came across with Flash session bug, due to use Session, authentication and authorization — it means if your user is logged in and if your file upload operation wants that only logged in users can upload file then it won’t work with Uploadify by default. Don’t worry, we have a way to get out of it!

Solution:

I asked solution of this challenge to our common friend — Google, and found really interesting links:

http://joncahill.zero41.com/2009/11/problems-with-uploadify-aspnet-mvc-and.html

“Basically the issue is with flash where it will ignore the browser’s session state and grab the cookies from IE, which is a known and active bug. This means that both Chrome and Firefox won’t work with Uploadify and authorisation because flash will send no cookies! It also means it is entirely possible for it to have previously work for me while testing because I probably also had a IE window open and logged in while testing, which would have given me a valid cookie.”

http://trycatchfail.com/blog/post/2009/05/23/using-flash-with-aspnet-mvc-and-authentication.aspx

There is a well-known bug in Flash that causes it to completely ignore the browser’s session state when it makes a request.  Instead, it either pulls cookies from Internet Explorer or just starts a new session with no cookies.  GOOD CALL, ADOBE.  And when I say this bug is well-known, I mean it was reported in Flash 8.  It’s still sitting in the Adobe bug tracker.  It has been triaged, it seems to have high priority, yet it remains unfixed.  Again, GREAT job, Adobe.

http://geekswithblogs.net/apopovsky/archive/2009/05/06/working-around-flash-cookie-bug-in-asp.net-mvc.aspx

http://stackoverflow.com/questions/1729179/uploadify-session-and-authentication-with-asp-net-mvc

Big thanks to all these article writers. Because it only helped us to find a solution. Using this solutions we were able to make session working. But authentication and membership information was not working . But we modified a bit in Global.asax and it started working. So, let me share a final solution with you:

1.  Pass session related information from your upload page in your upload call:

Just a note : This javascript code also covers other challenges as well (Which are not in scope of this article. But you may find it helpful!) e.g. passing dynamic data via onUploadStart, sending formdata via settings, showing uploadresult etc. The main variables which does the trick are — RequireUploadifySessionSync,SecurityToken,SessionId

<script type="text/javascript">
var UploadifyAuthCookie = '<% = Request.Cookies[FormsAuthentication.FormsCookieName] == null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value %>';
var UploadifySessionId = '<%= Session.SessionID %>';

$("#file_upload").uploadify({
'buttonImage': '/MultipleUploads/_scripts/browse-btn.jpg',
'scriptData': { RequireUploadifySessionSync: true, SecurityToken: UploadifyAuthCookie, SessionId: UploadifySessionId },
'formData': { 'KeyA': 'AValue', 'KeyB': 1, RequireUploadifySessionSync: true, SecurityToken: UploadifyAuthCookie, SessionId: UploadifySessionId, UserName: UploadifyUserName }, // If some static data
'auto': false,
'multi': 'true',
'swf': '_scripts/uploadify.swf',
'uploader': '<%= ResolveUrl("FileUploads.aspx") %>',
'onUploadStart': function (file) {
// for all dynamic data
var objCheckUnPack = document.getElementById("chkUnpack");
var objCheckOverwrite = document.getElementById("chkOverwrite");
//                    alert(objCheckUnPack.checked);
//                    alert(objCheckOverwrite.checked);
$("#file_upload").uploadify("settings", "formData", { 'IsUnPack': objCheckUnPack.checked, 'IsOverwrite': objCheckOverwrite.checked });
//http://stackoverflow.com/questions/10781368/uploadify-dynamic-formdata-does-not-change

},
'onQueueComplete': function (queueData) {
alert(queueData.uploadsSuccessful + ' files were successfully uploaded. And there were few errors during upload for this number of files : ' + queueData.uploadsErrored);
window.open('<%= ResolveUrl("FileUploadResultPage.aspx") %>', 'Test', 'width=300,height=300');
}
});
});

2. Now, in Global.asax we have to handle this variables:

protected void Application_BeginRequest(Object sender, EventArgs e)
{
        // This check will ensure that we need to sync session only during uploadify upload!
if (HttpContext.Current.Request["RequireUploadifySessionSync"] != null)
UploadifySessionSync();
}

/// <summary>
/// Uploadify uses a Flash object to upload files. This method retrieves and hydrates Auth and Session objects when the Uploadify Flash is calling.
/// </summary>
/// <remarks>
///     Kudos: http://geekswithblogs.net/apopovsky/archive/2009/05/06/working-around-flash-cookie-bug-in-asp.net-mvc.aspx
///     More kudos: http://stackoverflow.com/questions/1729179/uploadify-session-and-authentication-with-asp-net-mvc
/// </remarks>
protected void UploadifySessionSync()
{
try
{
string session_param_name = "SessionId";
string session_cookie_name = "ASP.NET_SessionId";

if (HttpContext.Current.Request[session_param_name] != null)
UploadifyUpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
}
catch { }

try
{
string auth_param_name = "SecurityToken";
string auth_cookie_name = FormsAuthentication.FormsCookieName;

if (HttpContext.Current.Request[auth_param_name] != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(HttpContext.Current.Request.Form[auth_param_name]);

if (ticket != null)
{
FormsIdentity identity = new FormsIdentity(ticket);
                    // This helped us to restore user details
string[] roles = System.Web.Security.Roles.GetRolesForUser(identity.Name);
System.Security.Principal.GenericPrincipal principal = new System.Security.Principal.GenericPrincipal(identity, roles);
HttpContext.Current.User = principal;
}

UploadifyUpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]);
}
}
catch { }
}

private void UploadifyUpdateCookie(string cookie_name, string cookie_value)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
if (cookie == null)
cookie = new HttpCookie(cookie_name);
cookie.Value = cookie_value;
HttpContext.Current.Request.Cookies.Set(cookie);
}


Happy Uploading via Uploadify! :-)

Posted in ASP.NET, ASP.NET Controls, GoodToKnow, IIS, Jquery | Tagged: , , | 2 Comments »

Two nice quality tools learnt during 2012

Posted by kiranpatils on January 13, 2013

Challenge:

During 2012, was searching for code quality tools [Yes, Because I believe that behind every successful project, there is always a quality code!], which should serve following purpose:

1.  It should give me how much duplicate, code lies inside your solution!

2. Easily find out few key metrics about your code. Like average and maximum complexity, average and maximum block depth etc.

Solution:

Found this two nice tools:

1. Simian [Also simian comes with XSLT. So, make your output in XML and simian guys provides you XSL. Using which you can see the output in HTML!]
http://typethinker.blogspot.in/2007/04/review-free-c-code-analysis-tools.html#simian
2. SourceMonitor
http://agileadvocate.blogspot.in/2009/11/sourcemonitor-for-net-code-quality.html

How to use it? Well, there is lot of article already written on the web. So, will not repeat it again! But yes, if you face any challenge(s) while following it. Feel free to give me a shout! I will be happy to help you!

Happy Quality Coding! :-)

 

Posted in Tools and Utilites | Tagged: , | 1 Comment »

“Check All” function when using Ryan Fait’s Checkbox

Posted by kiranpatils on January 13, 2013

Challenge:

During last year, we wanted to give Custom CSS Styles to checkboxes. And we found http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/ — Superb work! [Sometimes, not smooth experience with IE. But that's something I think because of IE's behavior. And you can live with it!]

But, we faced a lot of challenges, when we decided to give “Check All” functionality for it. As usual we did a Google search for it, and found this link — http://stackoverflow.com/questions/11352287/check-all-function-when-using-ryan-faits-custom-form-elements

But without solution! :( What? you also need to do same? You also found same stack overflow link? Struggling with the way to do it? Don’t worry, this post is for you only!

Solution:

We got a solution of it from one of our colleague — Who is very expert in CSS,Javascript and Jquery concepts.

Demo — Check All with Ryan Fait’s Checkbox

Just download it and use it from above link!

I’m sure this solution, will save your day(s)!

Thank you Ankit Vasani for the solution!

Posted in Web Technology | Tagged: , , | 2 Comments »

Thread synchronization basics!

Posted by kiranpatils on January 13, 2013

Challenge:

My dear readers, happy new year to all of you! Sorry for being away from you since so long. But no worries. I’m back with new post — means a new thing to share with you!

Before few months back, was reading on .NET Locking mechanism. During that period learnt a lot. So, this post is to share it with you!

Solution:

So,  here we go:

1.  To clear your threading basics, I would recommend MCTS 70-536 book!

2.  Few best links, from the web:

http://www.aspnet101.com/2010/03/50-tips-to-boost-asp-net-performance-part-i/ [Tip#11]
http://msdn.microsoft.com/en-us/library/1c9txz50.aspx
http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx — lock basics! — I loved this example!
“lock (this) is a problem if the instance can be accessed publicly.” — So, if your class is public, Don’t use lock(this) else whole class will get locked by one thread and other threads will keep on waiting for it.

“Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.”
http://msdn.microsoft.com/en-us/library/system.collections.hashtable.synchronized.aspx — For syncing
http://thevalerios.net/matt/2008/09/using-readerwriterlockslim/ — Good to know “Under the hood, the lock statement is just syntactic sugar for Monitor.Enter() and Monitor.Exit().If you really want to see for yourself, write a simple lock statement like the one below and open the compiled assembly in Reflector, then look at the IL (not the C#, since Reflector automatically recognizes the underlying lock syntax) — you’ll see calls to [mscorlib]System.Threading.Monitor::Enter and [mscorlib]System.Threading.Monitor::Exit surrounding the code inside.”


While it is a good thing that only one operation can happen to the shared state at any given time, it can also be a bad thing. The whole purpose of the lock is to prevent the corruption of the shared state, so we obviously don’t want to be reading and writing at the same time — but what if two threads are only trying to read at the same time? That’s pretty harmless, right? Nothing can get corrupted if we’re just reading.
In light of this, the lock statement is too cautious and certainly not optimal. Imagine a scenario with 1 thread writing and 10 threads reading — if we use the lock statement then each of the 10 reading threads must execute exclusively when they could be interleaved, leading to inefficient use of resources and wasted effort.
http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim%28v=vs.90%29.aspx — New mechanism in .NET 3.5!
http://kenegozi.com/blog/2010/08/15/readerwriterlockslim-vs-lock
http://blogs.msdn.com/b/pedram/archive/2007/10/07/a-performance-comparison-of-readerwriterlockslim-with-readerwriterlock.aspx

http://www.heikniemi.net/hardcoded/2009/12/readerwriterlockslim-performance/
http://stackoverflow.com/questions/407238/readerwriterlockslim-vs-monitor
“For write-only load the Monitor is cheaper than ReaderWriterLockSlim, however, if you simulate read + write load where read is much greater than write, then ReaderWriterLockSlim should out perform Monitor.”

http://stackoverflow.com/questions/4217398/when-is-readerwriterlockslim-better-than-a-simple-lock
http://stackoverflow.com/questions/59590/lock-keyword-in-c-sharp
http://forums.asp.net/t/1765023.aspx/1
http://jachman.wordpress.com/2006/08/02/best-practices-readerwriterlock/

HashTable is thread-safe if “Hashtable is thread safe for use by multiple reader threads and a single writing thread. It is thread safe for multi-thread use when only one of the threads perform write (update) operations, which allows for lock-free reads provided that the writers are serialized to the Hashtable.” [Source : http://msdn.microsoft.com/en-us/library/system.collections.hashtable.aspx]

Happy Threading and Safe locking! :-)

Posted in .NET | Tagged: , , , , | Leave a Comment »

2012 in review

Posted by kiranpatils on December 31, 2012

The WordPress.com stats helper monkeys prepared a 2012 annual report for this blog.

Here’s an excerpt:

19,000 people fit into the new Barclays Center to see Jay-Z perform. This blog was viewed about 83,000 times in 2012. If it were a concert at the Barclays Center, it would take about 4 sold-out performances for that many people to see it.

Click here to see the complete report.

Posted in Uncategorized | Leave a Comment »

Export to Excel/CSV doesnt work on IE under SSL (https)

Posted by kiranpatils on October 4, 2012

Challenge:

We’ve one functionality where user can save CSV/Excel file. Which was working fine in all browsers when we check it via HTTP. But it doesn’t work under IE when we do it via HTTPS.

Solution:

Cause:

1. If your page is passing caching header – Response.AddHeader(“Cache-Control”, “no-cache”);

2. And having export to CSV/Excel — Via Response.Write code.

Then it will not work in IE6/7/8 — This KB article says that this issue is fixed in IE9 — http://support.microsoft.com/kb/323308

OR remove no-cache control header from your page. But it is also required to have it as you might not want to save sensitive pages on client side. And if you remove no-cache header then it will save sensitive pages on client side. Isn’t it a real fix? Don’t worry we have a solution for you!

We googled it and found following link:

http://aspnettechstuffs.blogspot.in/2010/05/export-to-excel-does-not-work-in-ssl.html

Which worked for us in IIS 6.0 But not in IIS 7.5. Also, we wanted to avoid IIS specific changes and wanted to fix it from code. So, it doesn’t affect full functionality and only affects related modules.

We added following line in top of our export to CSV/excel method:

Response.ClearHeaders();
// Following by Export to Excel and Response attribute’s logic

And it did a trick!

Happy Coding! :-)

Good to read:

http://stackoverflow.com/questions/4672073/export-to-excel-doesnt-work-on-ie-under-ssl-https

Posted in .NET, ASP.NET, IIS | Tagged: , | Leave a Comment »

Opening a Jquery UI Modal Dialog shows a scroll bar on parent page

Posted by kiranpatils on October 3, 2012

Howdy my dear readers, I hope you must be doing great!

Yes, I’m back here to write a new blog post after so long time. Sorry for not sharing anything with you since so long. But got busy with lot of bits and pieces. But it’s good to be busy, the busier you are the more you have to share!

So, keep visiting – going to share more with you in upcoming days! [Free advice: You can subscribe to this blog via EMAIL SUBSCRIPTION box given in right side – which means that whenever any new post gets posted here, you will get an email!]

Challenge:

I got a chance to use Jquery UI‘s Modal dialog in my application. Now, whenever we used to open a dialog and when we open it, it was showing scroll-bar on parent page.

Solution:

After doing a bit research and finally thought to use following solution, which worked for us:

http://forum.jquery.com/topic/opening-a-modal-dialog-shows-a-horizontal-scroll-bar [Main logic lies in open and close event!]

Basically, above solution sets body’s overflow to hidden in open event and auto in close event. Which works fine for all browsers except IE7.  What’s the solution? Why?

Solution is you need to set overflow hidden of html element as well along with body.

Why so?

Excerpt from http://stackoverflow.com/questions/4443006/body-overflow-hidden-problem-in-internet-explorer-7

Applying overflow-x:hidden or overflow-y:hidden; to the body element of the document will not work. The overflow-x:hidden or overflow-y:hidden must be applied to the html element, not body element.

Happy Coding! :-)

Posted in CSS, Javascript, Jquery, Jquery UI | Tagged: , , | Leave a Comment »

Is it necessary to recycle worker process periodically?

Posted by kiranpatils on June 20, 2012

Challenge:

By default IIS recycles your application pool after 1740 minutes (29 hours) which is default setting.  (Good to know that there are few other reasons due to which your application pool gets recycled automatically — What are they? read my earlier blog post) and this link is also good to read — http://lab.technet.microsoft.com/en-us/magazine/cc161040

Periodic recycling of your application pools is recommended. It helps to clean up memory fragmentation, memory leaks, abandoned threads and other clutter. Keep in mind that when an application pool recycles, session state information stored in-process is lost for that pool, but other pools are not affected. ASP.NET, however, does allow you to store your session state outside the worker process, so that session information is not lost during a recycle.
Notice that Recycle worker processes (in minutes) is set to 1740 minutes (29 hours) by default. This will cause an automatic recycling to occur every day, five hours later than the previous day. You may want to consider changing this to recycle at a specific time of day when your server load is the smallest. In a Web farm, you can stagger the settings.

http://lab.technet.microsoft.com/en-us/magazine/cc161040.fig02(en-us).gif

Okay, so it gets restart after 29 hours. If you have web farm then you can’t rely on this default setting. Because your server might get recycled during peak hour! (at the time when you expect your servers to server more and more number of requests!). So, to deal with this situation you can use schedule recycle for your application. Using which you can scheule your application pool to recycle during out of office hours.

We were also following scheduled recycling approach (We scheduled our application to recycle every day during OOH hours). But our application heavily relies on our caching layer which stores full data in memory.  Now, when we schedule our application to get recycled during office hours. Obviously, it will flush full cache and after recycle first request for each resource will be bit slow. (It might not be noticeable to an end users. But you can see that effect via your monitoring systems).

Then, question came to our mind that “Do we really need to recycle application pool daily?” Is it a same question you have? Then this post is for you!

Solution:

We did bit research and found few nice things and concluded few things, which sharing here with you:

http://sdn.sitecore.net/forum/showpost.aspx?PostID=19209

While I can see the advantages of restarting periodically, I actually think that the primary value of autorestart is to mask memory leaks and other defects in both ASP.NET and the solution. So if the quality of the code is high or the load is low, I think it’s probably not necessary to restart, but I would monitor the machine a little more closely for some time after making the change.

Nice article by Microsoft which helps you to Determining When to Use Worker Process Recycling– http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/3adc0117-3c7b-4bb9-a4a9-1d0592b84c9c.mspx?mfr=true

Basically, you should do recycle app pool, if your application is handling lot of issues, facing performance issues, having memory leak issues that could not be handled, and need sometime to fix it.

Okay, so if your application is not having memory leaks issues. You can disable application pool recycling! But how to find out whether your application has memory leak issues or not?

I also had same question and already wrote an article on it — http://kiranpatils.wordpress.com/2012/06/05/basics-of-memory-leak/

If this post helped you, then say thanks to Kate Butenko!

Happy Coding! :-)

 

Posted in ASP.NET | Tagged: , , | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.

Join 167 other followers