Stable Sort with C#

Hi Guys before couple of days only i came to know that  the Sort methods used by the .NET collections are unstable. These sort methods, which include System.Array.Sort and System.Collections.Generic.List<T>.Sort, use the Quick Sort algorithm, which is relatively fast but in this case, unstable. However, there may be instances where you require a stable sort, so a custom solution is required. Let me explain you by an example:
Program.CS
[sourcecode language=”csharp”]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace GenericSortingDemo
{
class Program
{
static void Main(string[] args)
{
// 19 – May – 1977
Employee empHemang = new Employee(5, "Hemang Shah", DateTime.Parse("05/19/1977"));
// 19 – May – 1987
Employee empDarshak = new Employee(2, "Darshak Shah", DateTime.Parse("05/19/1985"));
// 30 – Jan – 1987
Employee empDevang = new Employee(1, "Devang Udeshi", DateTime.Parse("01/30/1987"));
// 30 – Jan – 1987
Employee empNilesh = new Employee(4, "Nilesh Thakkar", DateTime.Parse("01/30/1987"));
// 19 – Aug – 1987
Employee empKiran = new Employee(3, "Kiran Patil", DateTime.Parse("05/19/1987"));
Console.WriteLine("********************ArrayList***********************");
ArrayList empArrayList = new ArrayList();
empArrayList.Add(empHemang);
empArrayList.Add(empDevang);
empArrayList.Add(empNilesh);
empArrayList.Add(empDarshak);
empArrayList.Add(empKiran);
Console.WriteLine("ArrayList – Before sorting");
foreach (Employee emp in empArrayList)
{
Console.WriteLine(emp.ToString());
}
empArrayList.Sort(new MySorter());
Console.WriteLine(Environment.NewLine);
Console.WriteLine("ArrayList – After sorting");
foreach (Employee emp in empArrayList)
{
Console.WriteLine(emp.ToString());
}
Console.WriteLine(Environment.NewLine);
Console.WriteLine("********************Generics***********************");
// Genercis
List<Employee> lstEmployees = new List<Employee>();
lstEmployees.Add(empHemang);
lstEmployees.Add(empDevang);
lstEmployees.Add(empNilesh);
lstEmployees.Add(empDarshak);
lstEmployees.Add(empKiran);
Console.WriteLine("List<Employee> – Before sorting");
foreach (Employee emp in lstEmployees)
{
Console.WriteLine(emp.ToString());
}
// sort employees in asc order
lstEmployees.Sort(delegate(Employee emp1, Employee emp2)
{ return emp1.EmployeeBirthDate.CompareTo(emp2.EmployeeBirthDate); });
Console.WriteLine(Environment.NewLine);
Console.WriteLine("List<Employee> – After sorting");
foreach (Employee emp in lstEmployees)
{
Console.WriteLine(emp.ToString());
}
}
}
public class Employee
{
public Employee(int employeeID,string employeeName,DateTime employeeBirthDate)
{
EmployeeID = employeeID;
EmployeeName = employeeName;
EmployeeBirthDate = employeeBirthDate;
}
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public DateTime EmployeeBirthDate { get; set; }
public override string ToString()
{
return "Employee ID : " + EmployeeID + " Employee Name : " + EmployeeName + " Employee BirthDate : " + EmployeeBirthDate;
}
}
public class MySorter : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
Employee emp1 = x as Employee;
Employee emp2 = y as Employee;
DateTime dtEmpl = emp1.EmployeeBirthDate;
DateTime dtEmp2 = emp2.EmployeeBirthDate;
int num = dtEmpl.CompareTo(dtEmp2);//by default ascending order
return num;
}
#endregion
}
}
[/sourcecode]

Output

clip_image002
In their original order [Before sorting], Devang (1/30/1987) appears before Nilesh (also 1/30/1987). But because both objects have the same BirthDate, and the List<T>.Sort and Array.Sort method is unstable, the order of equal objects is reversed. Nilesh appears before Devang after sorting.
Q. Why it happens technically?
Ans: The Sort methods used by the .NET collections are unstable. These sort methods, which include System.Array.Sort and System.Collections.Generic.List<T>.Sort, use the Quick Sort algorithm [We all must have learnt in college days 🙂 DS lectures], which is relatively fast but in this case, unstable. However, there may be instances where you require a stable sort
[Source: http://msdn.microsoft.com/en-us/library/w56d4y5z.aspx], so a custom solution is required. – And the custom solution is “Stable Insertion Sort” – is the best way to do stable sorting [Source: http://www.csharp411.com/c-stable-sort/]
Happy Stable Sorting!

Setting up Dual wallpaper on dual monitors

if you are using dual monitors and you would like to set up dual wallpapers on both the monitors. Then it’s not directly possible. I know that there is something called NView from NVIDIA. But i didn’t liked it too much. It’s my personal view.
After googling a bit i found nice tool called “wallmaster” which is free and source is also available at codeplex :
http://wallmaster.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=23483
WallMaster 0.1.3 Download

Object dosen't support this property or method with showModalDialog

Challenge:

We’re trying to open Modal Window from Modal Window on button click which is inside update panel:
[sourcecode language=”csharp”]
protected void Button1_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(Button1, page.GetType(), "OpenModalDialog", "<script type=text/javascript>window.showModalDialog(‘http://www.gooogle.com, null, ‘dialogHeight:100px;dialogWidth:280px;status:no’); </script>", false);
}
[/sourcecode]
But it was giving an error Object dosen’t support this property or method

Solution:

Pls  check that pop-up blocker is not active. [Tools | Pop-Up Blocker|Turn-off Pop-up Blocker].

Exceeded storage allocation. The server response was: 5.7.0 Our system detected an illegal attachment on your message.

If you are genearting zip file runtime in memory and sending mail at run time. and you faced the error as shown below:
Exceeded storage allocation. The server response was: 5.7.0 Our system detected an illegal attachment on your message.
Then to fix it, you have to do the following change in your code(Pls note I’ve used SharpZipLib and Memory Stream for sending an email at run time using gmail server):
[sourcecode language=”csharp”]
MemoryStream zipFileStream = new MemoryStream();
zipOutputStream = new ZipOutputStream(zipFileStream);
..
..
..
//read from stream and add to zipoutputstream code should go here

..
// Seek to begining — IF YOU DON’ ADD BELOW LINE IT Will give above error
zipFileStream.Seek(0, SeekOrigin.Begin);
mailMessage.Attachments.Add(new Attachment(zipFileStream, "myzipfile.zip"));
[/sourcecode]
if you’ve seen the above code. Below line says MemroyStream to seek to Begining of the stream, So when SMTP Server scans the file before sending it gets perfect file.
zipFileStream.Seek(0, SeekOrigin.Begin);
Happy Mailing!

The Compressed (zipped) Folder is invalid or corrupted with SharpZipLib

I have generated Zip File using SharpZipLib. But when i try to access it using Windows XP extraction tool it shos following error:  Compressed (zipped) Folder is invalid or corrupted and it worked fine with 7zip. So, i did googling and found one nice solution from this link : http://blog.tylerholmes.com/2008/12/windows-xp-unzip-errors-with.html
Solution is — extracted from the above blog only.
[sourcecode language=”csharp”]

ZipEntry entry = new ZipEntry(Path.GetFileName(sourceFilePath));
entry.DateTime = DateTime.Now;
/* By specifying a size, SharpZipLib will turn on/off UseZip64 based on the file sizes. If Zip64 is ON
* some legacy zip utilities (ie. Windows XP) who can’t read Zip64 will be unable to unpack the archive.
* If Zip64 is OFF, zip archives will be unable to support files larger than 4GB. */
entry.Size = new FileInfo(sourceFilePath).Length;
zipStream.PutNextEntry(entry);

[/sourcecode]
If it works say thanks to Tyler Holmes — Above Blog author, for such a nice article!
Happy zipping!

UnSupported Compression method

Challenge:

I was writing a piece of code which generates zip file from the files read from Database and send  as an attachment mail to user. I used SharpZiLib library for that. And i completed writing my logic and mail goes fine to user’s mail box. So, far so good :). But when user tries to extract the attached zip file using 7Zip it shown following error and was working fine with winzip:
UnSupported Compression method for FILENAME.FILEXTENSION ERROR

Solution:

Then i just started going through the code and i just commented following line of cod and it worked!
[sourcecode language=”csharp”]
//Crc32 crc = new Crc32();
//crc.Reset();
//crc.Update(buffer);
//zipEntry.Crc = crc.Value;
[/sourcecode]
Hope this helps you to resolve your problem and say happy zipping!

Performing a Long Running Task with ASP.NET

Challenge:

Suppose, you have one Web Page and it contains one Button on click of it you perform some long running task for instance Copying thousands of Selected Data from one database to another database or something which takes too much time.
Now, if you perform this type of operation what will happen that if after click of your button it goes to server and start executing the server code on server side and client waits for a long to hear a response from server. But as the Server side code has to do so many things it takes time and after sometime on client page you will see “Page Can not be displayed” screen or something like that which confuse end user whether the work is done or not.
So, you may say that why don’t you do the server side task in chunks[Means copying employees from one database to another in a 100/100 Chunks.] Yeap, you are correct we can do this. But it needs human interaction and the person who is going to do this will feel boring. [Work should be fun :)]. So, let me show you how can you perform long running task asynchronously without human interaction and show result at the end of process.

Solution:

After goggling a lot and finding a lot of options[UpdateProgess and some JS stuff which sounds bit complex and dirty solution to me] finally i got link of MSDN Site which i found the best option Clean,Clear and Not Complex. I’ve derived my solution from MS Solution only.
Follow the steps given as below:
1. Create one class file in your Solution with name as ThreadResult.cs and the copy-paste following code in it.
[sourcecode language=”csharp”]
/// <summary>
/// This class will be used to
/// store ThreadResult in a
/// HashTable which has been
/// declared as static.
/// </summary>
public class ThreadResult
{
private static System.Collections.Hashtable
ThreadsList = new System.Collections.Hashtable();
public static void Add(string key, object value)
{
ThreadsList.Add(key, value);
}
public static object Get(string key)
{
return ThreadsList[key];
}
public static void Remove(string key)
{
ThreadsList.Remove(key);
}
public static bool Contains(string key)
{
return ThreadsList.ContainsKey(key);
}
}
[/sourcecode]
2. On your LongRuning Task page – Where you have kept the button and on click of it you perform long running task. Go to it’s server side click event handler and amend the code as shown below:
Markup file’s Code – LongRuningTask.aspx
[sourcecode language=”xml”]
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd%22">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"</a>>
<html xmlns="<a href="http://www.w3.org/1999/xhtml%22">http://www.w3.org/1999/xhtml"</a>>
<head runat="server">
<title>Long Running Task Page</title>
<script language="javascript" type="text/javascript">
function OpenProgressWindow(reqid)
{
window.showModalDialog("ResultPage.aspx?RequestId="+reqid
,"Progress Window","dialogHeight:200px; dialogWidth:380px");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnLongRuningTask" runat="server" Text="Long Runing Task" OnClick="btnLongRuningTask_Click"
/>
</div>
</form>
</body>
</html>
[/sourcecode]
Code-behind file’s code — LongRuningTask.aspx.cs
[sourcecode language=”csharp”]
using System;
using System.Threading;
using System.Web.UI;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected Guid requestId;
protected void btnLongRuningTask_Click(object sender, EventArgs e)
{
requestId = Guid.NewGuid();
// Start the long running task on one thread
ParameterizedThreadStart parameterizedThreadStart = new ParameterizedThreadStart(LongRuningTask);
Thread thread = new Thread(parameterizedThreadStart);
thread.Start();
// Show Modal Progress Window
Page.ClientScript.RegisterStartupScript(this.GetType(),
"OpenWindow", "OpenProgressWindow(‘" + requestId.ToString() + "’);",true);
}
private void LongRuningTask(object data)
{
// simulate long running task – your main logic should   go here
Thread.Sleep(15000);
// Add ThreadResult — when this
// line executes it means task has been
// completed
ThreadResult.Add(requestId.ToString(), "Item Processed Successfully."); // you can add your result in second parameter.
}
}
[/sourcecode]
In Above code on click of Button we’ve create one new Thread and started the thread – means long runing method will be called and start processing on different thread without blocking current executing thread – your main web form page. and opened a new popup window which opens ResultPage.aspx with RequestId as a Query String[We will see it in Step 3] to check the progress and result of a process.
LongRuningTask Method will be called by Thread and it does main processing logic and on finish of the operation it adds the Result in ThreadResult – mapping table which we have created in step 1 for Mapping. Where RequestId is Key and Process result is value of HashTable. It’s main use will see shortly in step 3.
3. So far so good 🙂 Now we need one .aspx page which shows progress to end user and keep checking that is thread executed successfully or not. For that Create one .aspx page with the name “ResultPage.aspx”. for simplicity I’ve followed single file model for ResultPage.aspx and i would suggest the same to you.
ResultPage.aspx
[sourcecode language=”xml”]</pre>
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"</a>>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
string requestId = Request.QueryString["RequestId"];
if (!string.IsNullOrEmpty(requestId))
{
// if we found requestid means thread is processed
if (ThreadResult.Contains(requestId))
{
// get value
string result = (string)ThreadResult.Get(requestId);
// show message
lblResult.Text = result;
lblProcessing.Visible = false;
imgProgress.Visible = false;
lblResult.Visible = true;
btnClose.Visible = true;
// Remove value from HashTable
ThreadResult.Remove(requestId);
}
else
{
// keep refreshing progress window
Response.AddHeader("refresh", "2");
}
}
}
</script>
<html xmlns="<a href="http://www.w3.org/1999/xhtml&quot;">http://www.w3.org/1999/xhtml"</a>>
<head runat="server">
<title>Result Page</title>
<base target="_self" />
<style type="text/css">
.buttonCss
{
color:White;
background-color:Black;
font-weight:bold;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblProcessing" runat="server" Text="We are processing your request. Pls don’t close this browser." />
<br />
<center>
<img id="imgProgress" runat="server" src="Progress.GIF" width="50" height="50" />
</center>
<asp:Label ID="lblResult" runat="server" Visible="false" Font-Bold="true" />
<br />
<center>
<asp:Button ID="btnClose" runat="server" Visible="false" Text="Close" OnClientClick="window.close();" CssClass="buttonCss" />
</center>
</div>
</form>
</body>
</html>
<pre>[/sourcecode]
4. You are done with coding stuff. Let’s keep fingers crossed and F5 the code.
Long Runing Task
Long Runing Task
Long Runing Task
That’s it! I hope this article helped you to perform long running task in a good way.
Happy Long Running Task! 🙂

Access Internet/Local Website from Your Windows Mobile Device Emulators

Challenge

If you want to access any website Or You want your locally developed mobile application/web application to be viewed in Windows Device Emulator then you are at the right post.

Solution
  1. Download ActiveSync and install on your local machine where you would like to run Emulator. How to setup ActiveSync?
  2. Open Visual Studio and click on Tools | Connect to Device:

clip_image002

  1. Select Device emulator to run and say connect.

clip_image004

  1. It will open your device emulator:

clip_image006

  1. Verify that ActiveSync is up and running by its symbol in Notification Area.

clip_image008

  1. Open Device Emulator Manager

clip_image010

  1. Currently running Device Emulator Manager will be shown in Green.

clip_image012

  1. Right click and say “Cradle”

clip_image014

  1. As you click on Cradle ActiveSync window will popup. Select Guest Partnership[Or better do cancel it will by default to Guest Mode]. If your Emulator got synced with ActiveSync then Notification Icon will go Green.
  1. Now you are ready to access website.
    1. Internet – Enter your URL.

clip_image016

    1. Local – To Access your Local Website which is running on Cassini(Development Web Server). To access it you need to access it by IP ADDRESS:PORTNUMBER. Please note that you can’t access it by localhost:PORTNO Because localhost points to Emulator’s localhost and it will never go to your machine. You have to see both Emulator and your local machine as a two different devices even though they are running on same machine.

clip_image018
If this blog helped you. Say a big thanks to my friends who always give me a shout whenever they found something challenging like this and inspire me to learn a new things which finally inspires me to pen down on my blog and share with you 🙂
Happy Emulating!
Webliography
Setup ActiveSync
Nice blog – Thanks to this blog
If you have Windows Vista or Later
Accessing Device Emulator Without ActiveSync

Feedback

[polldaddy poll=2276650]

Delivering Multimedia

Now a days I’ve started preparing for my next Microsoft Certification exam 70-547. And it’s going on really well as i am learning the things which i was knowing but now i am coming in to know the PRO. use of it.
Anyways today i am going to show you how you can deliver Multimedia on your website. Because in this era everyone needs to have it 🙂
But before we delve in coding part which we all developers love to do. Let’s take a look at some basic things which is good to know.
Non-Streaming :- The Audi/Video files must be downloaded completely before playback can begin.
Non-Streaming Audio Formats are waveform(.wav), sound(.snd), Unix Audio(.au), Audio Interchange File format(.aif.aiff,.aifc)
Non-Streaming Video Formats are Audio-Video Interleaved(.avi)
Streaming :- The Audi/Video files can started playback and files keep downloading itself in background. This one gives better user experience.
Streaming Audio Formats are Moving Pictures Experts Group standard 1, Layer 1,2,3 (.mpa,.mp2,.mp3), Windows Media Audio(.wma)
Streaming Video Formats are Moving Pictures Experts Group standard 1 (.mpg,.mpeg,.mpv,.mpe), Windows Media Video (.wmv)
Hooh..too much theory. Let’s start how we can deliver multimedia on our page.
There are two ways of doing this:
1. Embedded Playback : you can embed Windows Media Player on your page directly. But client should have installed Windows Media Player on his/her computer to view your multimedia files.
The code looks like as below:
[sourcecode language=”html”]
<div class="csharpcode"><html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>MultiMedia Page</title>
<script type="text/javascript" language="javascript">
function StartPlayer()
{
//Using DOM play your MultiMedia File
document.player1.URL = "Resources/vande.avi";
}
function StartStreamingPlayer()
{
document.player1.URL = "Resources/Intro_to_ASP_.NET_3.5.wmv";
}
function StopPlayer()
{
document.player1.controls.stop();
}
function PausePlayer(buttonPauseOrPlay)
{
if(buttonPauseOrPlay.value == "Pause")
{
document.player1.controls.pause();
buttonPauseOrPlay.value = "Play";
}
else
{
document.player1.controls.play();
buttonPauseOrPlay.value = "Pause";
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<object id="player1" height="400" width="590" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6">
</object>
<br />
<br />
<input type="button" name="btnPlay" value="Start Non-Streaming File(.avi)" onclick="StartPlayer()" />
<input type="button" name="btnPlay" value="Start Streaming File(.wmv)" onclick="StartStreamingPlayer()" />
<input type="button" name="btnStop" value="Stop" onclick="StopPlayer()" />
<input type="button" name="btnPause" value="Pause" onclick="PausePlayer(this)" />
<br />
UI Mode :
<select id="selUIMode" onchange="this.document.player1.uiMode = selUIMode.value;">
<option value="invisible">Invisible</option>
<option value="none">None</option>
<option value="mini">Mini Player</option>
<option value="full">Full Player</option>
</select>
</div>
</form>
</body>
</html></div>
<div class="csharpcode">[/sourcecode]
Output of the above piece of code is as below: It will be real fun when you try on your own 🙂
Media Player In Browser
In above code the main things is :

[sourcecode language="html"]
 </span><object id="player1" height="400" width="590" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6">
 </object>
<pre> [/sourcecode]
 

2. Playing file with an External Player is easy. Just following piece of code does that for you:
this.document.location.replace(FILENAME.wma);
Hope you’ve enjoyed it!
Happy Video Playing!

MSDN got a new look!

One of my best friend MSDN – i guess yours too 🙂 got a new look! Few days back while i was searching for something on MSDN – Which i always do 🙂 i saw the new look of MSDN. It really looks a great and really few nice enhancements they did.

image

image

Switch View functionality is really great you can switch the views to Classic, Lightweight Beta and ScriptFree

Happy Reading!