multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed

This message will come when you have already connected to a network machine earlier using some credential and now you are trying to access the same machine using a different set of credentials. The reason is, windows keep the connection open once we open a network path using a particular credential and does not close until we shutdown.

Solution is we remove those connections manually and a simple trick is following command which deletes all “saved” connections:

net use * /delete

Or, you can delete a specific by using :

net use \\192.168.1.100 /delete

Sending an email from C# winforms application is exactly same as we do in webapps using System.Net.Mail namespace. Here is a sample code which sends out an email with an attachment (again it is not specific to winforms can be used in webapps as it is).

MailMessage msg = new MailMessage();
SmtpClient client;
Attachment attach = new Attachment(filepath);

if (varEmailID.IndexOf(',') > 0)
{
    string[] iDs;
    iDs = varEmailID.Split(',');
    for (int i = 0; i <= iDs.Length - 1; i++)
    {
        msg.To.Add(new MailAddress(iDs.GetValue(i).ToString()));
    }
}
else
{
    msg.To.Add(new MailAddress(varEmailID));
}

msg.Attachments.Add(attach);
msg.Subject = varSubject;
msg.Body = varBody;
msg.IsBodyHtml = false;
msg.Priority = MailPriority.Normal;

string FromEmail = ConfigurationSettings.AppSettings["SystemMailID"];
string SmtpServer = ConfigurationSettings.AppSettings["SmtpServer"];
string UserName = ConfigurationSettings.AppSettings["UserName"];
string Password = ConfigurationSettings.AppSettings["Password"]; 
client = new SmtpClient(SmtpServer);
client.UseDefaultCredentials = false;
System.Net.NetworkCredential creds = new System.Net.NetworkCredential(UserName, Password);
client.Credentials = creds;

msg.From = new MailAddress(FromEmail);

client.Send(msg);

Having more than 150 tables and even more SPs in a database and then using LinqToSql for that is proving to be a bottleneck. 

LinqToSql is an awesome technology but working in a team of more than 5 developers, all trying to update a single dbml at the same time is not a good idea. You won’t notice this while working on a team of 1 or 2 developers , I still think subsonic or NHibernate would have been a better solution at least for the reason being they generate separate class files for each entity.

Asp.Net 4 (aka Framework 4.0 ) with VS 2010 now supports URL routing for webforms.

It would be a cool thing since Asp.net MVC was already supporting it out of box and this is just a sign that webforms are going to be a supported as prime platform for developments by MS.

Check here for more details.

Found an interesting piece of code here.

When sending an email in your ASP.NET application there are times when you do not want the user experience to slow just to wait for an email to be sent.  The code sample below is how to send a System.Net.Mail.MailMessage asynchronously so that the current thread can continue while a secondary thread sends the email.

public static void SendEmail(System.Net.Mail.MailMessage m)
{
    SendEmail(m, true);
}

public static void SendEmail(System.Net.Mail.MailMessage m, Boolean Async)
{

    System.Net.Mail.SmtpClient smtpClient = null;

    smtpClient = new System.Net.Mail.SmtpClient("localhost");

        if (Async)
        {
            SendEmailDelegate sd = new SendEmailDelegate(smtpClient.Send);
            AsyncCallback cb = new AsyncCallback(SendEmailResponse);
            sd.BeginInvoke(m, cb, sd);
        }
        else
        {
            smtpClient.Send(m);
        }
}

private delegate void SendEmailDelegate(System.Net.Mail.MailMessage m);

private static void SendEmailResponse(IAsyncResult ar)
{
        SendEmailDelegate sd = (SendEmailDelegate)(ar.AsyncState);

        sd.EndInvoke(ar);
}

To use this just call the SendEmail() method with System.Net.Mail.MailMessage object.

Got a useful piece of here which I have implemented in following way to make a image preview form.

    private void frmPreview_Load(object sender, EventArgs e)
    {
        try
        {

            pboxMain.Image = Image.FromFile(_imagePath);
            pboxMain.Tag = Image.FromFile(_imagePath);
        }
        catch(Exception ex)
        {
           Log.Error(ex);                
        }
    }

    private void btFit_Click(object sender, EventArgs e)
    {

        if (btFit.Text == "Fit to Screen")
        {
            handleFitToWindow(true);
            btFit.Text = "Actual Size";
        }
        else
        {
            handleFitToWindow(false);
            btFit.Text = "Fit to Screen";
        }

    }

    private void handleFitToWindow(bool doFit)
    {
        try
        {
            /* Don’t perform any operation if no image is loaded. */
            if (this.pboxMain.Tag != null)
            {
                if (doFit)  /* We’re fitting it to the window, and centering it. */
                {
                    /* Create a temporary Image.

                     * Always work from the original image, stored in the Tag.
                     */

                    Image tempImage = (Image)this.pboxMain.Tag;

                    /* Calculate the dimensions necessary for an image to fit. */
                    Size fitImageSize = this.getScaledImageDimensions(
                        tempImage.Width, tempImage.Height, this.pboxMain.Width, this.pboxMain.Height);

                    /* Create a new Bitmap from the original image with the new dimensions.

                     * The constructor for the Bitmap object automatically scales as necessary.
                     */

                    Bitmap imgOutput = new Bitmap(tempImage, fitImageSize.Width, fitImageSize.Height);

                    /* Clear any existing image in the PictureBox. */
                    this.pboxMain.Image = null;

                    /* When fitting the image to the window, we want to keep it centered. */
                    this.pboxMain.SizeMode = PictureBoxSizeMode.CenterImage;

                    /* Finally, set the Image property to point to the new, resized image. */
                    this.pboxMain.Image = imgOutput;
                }

                else  /* Restore the image to its original size */
                {
                    /* Clear any existing image int he PictureBox. */
                    this.pboxMain.Image = null;

                    /* Set the resize more to Normal; this will place the image

                     * in the upper left-hand corner, clipping the image as required.
                     */

                    this.pboxMain.SizeMode = PictureBoxSizeMode.Normal;

                    /* Finally, set the Image property to point to the original image. */
                    this.pboxMain.Image = (Image)this.pboxMain.Tag;
                }
            }
        }
        catch (System.Exception e)
        {
            Console.WriteLine(e);
        }
    }

    private Size getScaledImageDimensions(
        int currentImageWidth,
        int currentImageHeight,
        int desiredImageWidth,
        int desiredImageHeight)
    {
        /* First, we must calculate a multiplier that will be used

         * to get the dimensions of the new, scaled image.
         */

        double scaleImageMultiplier = 0;

        /* This multiplier is defined as the ratio of the

         * Desired Dimension to the Current Dimension.
         * Specifically which dimension is used depends on the larger
         * dimension of the image, as this will be the constraining dimension
         * when we fit to the window.
         */

        /* Determine if Image is Portrait or Landscape. */
        if (currentImageHeight > currentImageWidth)    /* Image is Portrait */
        {
            /* Calculate the multiplier based on the heights. */
            if (desiredImageHeight > desiredImageWidth)
            {
                scaleImageMultiplier = (double)desiredImageWidth / (double)currentImageWidth;
            }

            else
            {
                scaleImageMultiplier = (double)desiredImageHeight / (double)currentImageHeight;
            }
        }

        else /* Image is Landscape */
        {
            /* Calculate the multiplier based on the widths. */
            if (desiredImageHeight > desiredImageWidth)
            {
                scaleImageMultiplier = (double)desiredImageWidth / (double)currentImageWidth;
            }

            else
            {
                scaleImageMultiplier = (double)desiredImageHeight / (double)currentImageHeight;
            }
        }

        /* Generate and return the new scaled dimensions.

         * Essentially, we multiply each dimension of the original image
         * by the multiplier calculated above to yield the dimensions
         * of the scaled image. The scaled image can be larger or smaller
         * than the original.
         */

        return new Size(
            (int)(currentImageWidth * scaleImageMultiplier),
            (int)(currentImageHeight * scaleImageMultiplier));
    }

}

CheckedListBox does not have a straight forward way of making checkbox selected using code, so here is some code which may save some Google searches.

For example if you have a data bound CheckedListBox and you need to make some of the items selected by iterating through them then we can do as follows:


For Each dtr As DataRow In dtpack.Rows
For i As Integer = 0 To cmbServices.Items.Count - 1
If DirectCast(cmbServices.Items(i), DataRowView)("ID") = dtr("ID") Then
cmbServices.SetItemCheckState(i, CheckState.Checked)
End If
Next
Next

For Each dtr As DataRow In dt.Rows

For i As Integer = 0 To clbServices.Items.Count - 1

If DirectCast(clbServices.Items(i), DataRowView)("ID") = dtr("ID") Then

clbServices.SetItemCheckState(i, CheckState.Checked)

End If

Next

Next

I just finished installing Windows 7 on my home laptop in dual boot mode with Windows XP.

To partition my hard drive, I used Partition Master 3.5 Home Edition, it’s a lesser known freeware but it works seamlessly.

Windows 7 has easier and quicker installation process , plus it got all the hardware drivers on my machine. . It certainly boots up faster than Vista (which was my biggest headache using it). Looks promising to me.

We know that cross domain ajax calls are not possible from javascript, but come’on we live in virtual world and every law can be bent if we can (remember Morpheus from ultra cool Matrix ;-) )

Ok, I found  here on this nice guy’s blog under Cross-Domain Communication with IFrames.

I have actually used it and it works like a charm. I made a simple javascript function to get the anchor values , actually I used anchors to pass values using URL as if passing URL variable.

For example if I want to pass one variable then I would do :

http://www.yourdomain.com#action=foo#

For two variables :

http://www.yourdomain.com#action=foo#action2=foo2#

Two JS function, one for getting anchor value and second for resetting URL to it’s original form.

function getAnchor(name) {

url = window.location.href;
var varlen = name.length + 2;
var start = url.indexOf(“#” + name) + varlen;
var length = url.indexOf(“#”, start) – start;

var value = url.substr(start, length);
return value;
}

function resetAnchor() {
url = window.location.href;
var hash = url.indexOf(“#”)
if (hash >= 0) {
url = url.substr(0, hash);
window.location.href = url + “#”;
}
}

I would be happy to help if you have any troubles.

Gmail in Firefox is my primary work and personal email client, so I try to make as much space available as possible for Gmail.

I use Hide Menubar add-on which hides the main menubar, then I hide all other extra toolbars and keeping only Address bar (which minimum you need anyways).

Then, recently I found Gmail Compactor Add-On which make further space available for Gmail and make it look little better than standard interface. Make sure you have Greasemonkey add-on installed before you try.

Next Page »