CodeMirror basics

Challenge:

In our web application, we do provide HTML/CSS/JS editing functionality. We wanted to provide Syntax Highlighting feature for that, and after doing bit of our research we finalized to use:
Code Mirror — http://codemirror.net/  It’s just awesome!
We implemented and incorporated it with our application, and it was working fine, with FF, Chrome. But but here comes IE — (I know we all face lot of challenges with IE), it was causing following issues:

  1. Scroll bar flickering
  2. When we type anything it moves it’s position

What, you are also facing the same problem? Our solution might work with you as well

Solution:

After Investing a lot of time, we found that our page’s DOCTYPE was enforcing our page to run in Quirks mode, and CodeMirror and Quirks mode — are enemies! 🙂
See following excerpt from [Supported browsers section] : http://codemirror.net/

The following desktop browsers are able to run CodeMirror:

  • Firefox 3 or higher
  • Chrome, any version
  • Safari 5.2 or higher
  • Opera 9 or higher (with some key-handling problems on OS X)
  • Internet Explorer 8 or higher
  • Internet Explorer 7 (standards mode) is usable, but buggy. It has a z-index bug that prevents CodeMirror from working properly.

Note that CodeMirror is only supported in standards mode. So not quirks mode, but also not the quasi-standards mode that IE gives you when you specify a transitional doctype. Simply using the HTML5-style <!--doctype html> is recommended.

Now, the solution is simple, just change DOCTYPE to standards mode and you are done! But “life is not as easy as it seems to be” 🙂
Because if your application’s UI has been designed as per quirks mode than you can’t change it directly, Because it might make your CodeMirror working. But can break N number of things!
Don’t worry, we got a solution for you!
In our case our CodeMirror editor was in an I-Frame and using this trick, we resolved it! — http://stackoverflow.com/questions/5391495/can-i-have-doctype-in-iframe-different-from-hosting-page
Basically, change the DOCTYPE of your I-Framed page, and you are done!
Happy Coding! 🙂

XML XSLT Namespace gotcha

Challenge:

Before couple of weeks back we spent a good amount of time making XML and XSLT work, you must be thinking so easy then why this guy invested lot of time. Wait o minute coming to you.

Solution:

Basically, we had XML and we were trying to fetch few nodes via XSLT from it. But it was not working as expected. We verified everything our XPATH was correct and everything was correct then following link, pointed us towards a solution:
http://stackoverflow.com/questions/1730875/xslt-transform-xml-with-namespaces
Our XML was having xmlns deceleration,  and we were not using xmlns in our XSLT document. And that was the reason why XSLT was not able to XPATH nodes. Once, we added XMLNS to our XSLT document and changed our XPATH as per XMLNS then everything started working as expected!

Firebug with Internet Explorer

Challenge:

If you are a big fan of Firebug (So, as I!) which is available as an add-on with Firefox and when you have to work on particular challenge where you need to check it in IE only where Developer Toolbar is available. But unfortunately I never enjoyed working with it! (So, as you?)
So, was wondering is it possible to use Firebug with IE, and as it has been said, When there is a will, there is a way. And here’s the way to do it!

Solution:

The answer is – Firebug Lite — It is a lightweight version of Firefox to help you debug issues rapidly!
How to use it?

  1. Go to — https://getfirebug.com/firebuglite
  2. You will find Stable/Debug/Beta/Developer channel link — Will use Stable one!
  3. Open a page, which you would like to troubleshoot or if you are using master page concept in ASP.NET then have it in master page.
  4. Now, you can download firebug lite files and have it in your website directory and give relative path or to make things simple and faster you can give direct link to firebug lite
  5. Open your page and Include the given code at the top of the <head> of your page
  6. Run your page, and you are done!

Just a note: Sometime, I think that if Firebug would have not been around, then how tough web developer’s life would have been!
Happy Troubleshooting! 🙂
 

Nunit results to HTML

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! 🙂

Fast and furious way to LoadXML document

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! 🙂

Uploadify (Session and authentication) with ASP.NET

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
[sourcecode language=”html”]
<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’);
}
});
});
[/sourcecode]
2. Now, in Global.asax we have to handle this variables:
[sourcecode language=”csharp”]
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);
}
[/sourcecode]
Happy Uploading via Uploadify! 🙂

Two nice quality tools learnt during 2012

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! 🙂
 

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

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!

Thread synchronization basics!

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! 🙂

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

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