Thursday, December 2, 2010

BiDirectional Bubble Sort


Cocktail sort, also known as bidirectional bubble sort, cocktail shaker sort, shaker sort (which can also refer to a variant of selection sort), ripple sort, shuttle sort or happy hour sort, is a variation of bubble sort that is both a stable sorting algorithm and a comparison sort. The algorithm differs from bubble sort in that it sorts in both directions on each pass through the list. This sorting algorithm is only marginally more difficult to implement than bubble sort, and solves the problem with so-called turtles in bubble sort.

The first rightward pass will shift the largest element to its correct place at the end, and the following leftward pass will shift the smallest element to its correct place at the beginning. The second complete pass will shift the second largest and second smallest elements to their correct places, and so on. After i passes, the first i and the last i elements in the list are in their correct positions, and do not need to be checked. By shortening the part of the list that is sorted each time, the number of operations can be halved.

public IList BiDerectionalBubleSort(IList arrayToSort)
{

    int limit = arrayToSort.Count;
    int st = -1;
    bool swapped = false;
    do
    {
        swapped = false;
        st++;
        limit--;

        for (int j = st; j < limit; j++)
        {
            if (((IComparable)arrayToSort[j]).CompareTo(arrayToSort[j + 1]) > 0)
            {
                object temp = arrayToSort[j];
                arrayToSort[j] = arrayToSort[j + 1];
                arrayToSort[j + 1] = temp;
                swapped = true;
                RedrawItem(j);
                RedrawItem(j + 1);
                pnlSamples.Refresh();
                if (chkCreateAnimation.Checked)
                    SavePicture();

            }
        }
        for (int j = limit - 1; j >= st; j--)
        {
            if (((IComparable)arrayToSort[j]).CompareTo(arrayToSort[j + 1]) > 0)
            {
                object temp = arrayToSort[j];
                arrayToSort[j] = arrayToSort[j + 1];
                arrayToSort[j + 1] = temp;
                swapped = true;
                RedrawItem(j);
                RedrawItem(j + 1);

                pnlSamples.Refresh();
                if (chkCreateAnimation.Checked)
                    SavePicture();

            }
        }

    } while (st < limit && swapped);

    return arrayToSort;
}

Bubble Sort




Bubble sort, also known as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. The equally simple insertion sort has better performance than bubble sort, so some have suggested no longer teaching the bubble sort.

public IList BubbleSort(IList arrayToSort)
{
    int n = arrayToSort.Count - 1;
    for (int i = 0; i < n; i++)
    {

        for (int j = n; j > i; j--)
        {
            if (((IComparable)arrayToSort[j - 1]).CompareTo(arrayToSort[j]) > 0)
            {
                object temp = arrayToSort[j - 1];
                arrayToSort[j - 1] = arrayToSort[j];
                arrayToSort[j] = temp;
                RedrawItem(j);
                RedrawItem(j - 1);
                pnlSamples.Refresh();
                if (chkCreateAnimation.Checked)
                    SavePicture();
            }
        }
    }
    return arrayToSort;
}

Wednesday, December 1, 2010

How to convert BMP to GIF in C#



In this post I will show you how to convert bmp file to gif in C#. First step you must do is create Bitmap object. In this example I passed filename to constructor of this object. Next you need to create ImageCodecInfo and chose appropriate mime type of output format. You can set quality and compression of output image. In case you need to do this, you must create EncoderParameters object which represents list of EncoderParameter objects. This objects represent set of parameters which encoder uses for image encoding.

static void Main(string[] args)
        {
            Bitmap myBitmap=new Bitmap(@"test.bmp");
            ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/gif"); ;
            EncoderParameter encCompressionrParameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionLZW); ;
            EncoderParameter encQualityParameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 0L);
            EncoderParameters myEncoderParameters = new EncoderParameters(2);
            myEncoderParameters.Param[0] = encCompressionrParameter;
            myEncoderParameters.Param[1] = encQualityParameter;
            myBitmap.Save("Output.gif", myImageCodecInfo, myEncoderParameters);
        }

        private static ImageCodecInfo GetEncoderInfo(String mimeType)
        {
            int j;
            ImageCodecInfo[] encoders;
            encoders = ImageCodecInfo.GetImageEncoders();
            for (j = 0; j < encoders.Length; ++j)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }

Saturday, November 27, 2010

How to shuffle array items using C#

Here is a simple code of method which shuffle array items:


static Random rng = new Random();

public void Randomize(IList list)
{

    for (int i = list.Count - 1; i > 0; i--)
    {
        int swapIndex = rng.Next(i + 1);
        if (swapIndex != i)
        {
            object tmp = list[swapIndex];
            list[swapIndex] = list[i];
            list[i] = tmp;
        }
    }
}

Tuesday, November 23, 2010

How to Grant, Deny and Revoke server pesmissions using SMO



SMO allows you to grant, deny and revoke server permissions to and from SQL Server login account. ServerPermissionInfo object captures the set of server permission returned by EnumServerPermissions() metod. You can pass name of SQL Server login as parameter to this method. Than you will get permissions for this login.

ServerPermissionSet object represent set of SQL Server permissions you want to grant, deny or revoke.

Server permissions are required when granting, denying, or revoking server-level permissions on an instance of SQL Server. The ServerPermission object is used to specify the set of permissions that apply to the Grant, Deny, and Revoke methods of the Server object. Also, server permissions can be added to the ServerPermissionSet object, which can also be used with the Deny, Revoke, and Grant methods.

ServerConnection conn = new ServerConnection(@"SQL_SERVER_INSTANCE", "LOGIN", "PASSWORD");
try
{
    Server srv = new Server(conn);
    Database db = srv.Databases["AdventureWorks"];

    foreach (ServerPermissionInfo serverPermInfo in srv.EnumServerPermissions("LOGIN"))
    {
        Console.WriteLine(serverPermInfo.ToString());
    }
    Console.WriteLine("----------------");

    ServerPermissionSet sps;
    sps = new ServerPermissionSet(ServerPermission.CreateAnyDatabase);
    srv.Grant(sps, "slimak");

    foreach (ServerPermissionInfo serverPermInfo in srv.EnumServerPermissions("LOGIN"))
    {
        Console.WriteLine(serverPermInfo.ToString());
    }
    Console.WriteLine("----------------");

    sps = new ServerPermissionSet(ServerPermission.ViewAnyDatabase);
    srv.Deny(sps, "slimak");

    foreach (ServerPermissionInfo serverPermInfo in srv.EnumServerPermissions("LOGIN"))
    {
        Console.WriteLine(serverPermInfo.ToString());
    }
    Console.WriteLine("----------------");

    sps = new ServerPermissionSet(ServerPermission.ViewAnyDatabase);
    srv.Revoke(sps, "slimak");

    foreach (ServerPermissionInfo serverPermInfo in srv.EnumServerPermissions("LOGIN"))
    {
        Console.WriteLine(serverPermInfo.ToString());
    }
    Console.WriteLine("----------------");
}
catch (Exception err)
{
    Console.WriteLine(err.Message);
}

Sunday, November 14, 2010

Calling JavaScript function from WinForms and vice-versa



I'be been working on application that needs to load page and display it in WebBrowser control. Second requirement was to allow interaction between WinForms application and web page. After a couple of minutes of googling I found some important information that helped me to solve my problem. Here I will show a sample application where JavaScript function is called from WinForms application.

Hole process can be described by following steps:
  • Create Windows Forms application
  • Add WebBrowser control into Form
  • Create web page with JavaScript function you want to call

Calling JavaScript function from WinForms application isn't so difficult. WebBrowser constrol has property Document which gets an HtmlDocument representing the Web page currently displayed in the WebBrowser control.

You can use this property, in combination with the ObjectForScripting property, to implement two-way communication between a Web page displayed in the WebBrowser control and your application. Use the HtmlDocument.InvokeScript method to call script methods implemented in a Web page from your client application code. Your scripting code can access your application through the window.external object, which is a built-in DOM object provided for host access, and which maps to an object that you specify for the ObjectForScripting property.

<html>
     <head>
          <title></title>
          <script type="text/javascript">        

          function ShowMessage(message)
          {
               alert(message);
          }
        
          function ShowWinFormsMessage() {
               var msg = document.getElementById('txtMessage').value;
               return window.external.ShowMessage(msg);
          }
        
          </script>
     </head>  
     <body>
          <input type="text" id="txtMessage" />
          <input type="button" value="Show Message" onclick="ShowWinFormsMessage()" />
     </body>
</html>

Two JavaScript functions are in sample page. function ShowMessage(message) is called from WinForms application and function ShowWinFormsMessage call ShowMessage(msg) C# function.




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WebBrowserJavaScriptExample
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
            webBrowser1.ObjectForScripting = new ScriptManager(this);
        }

        private void btnShowMessage_Click(object sender, EventArgs e)
        {
            object[] o = new object[1];
            o[0]=txtMessage.Text;
            object result = this.webBrowser1.Document.InvokeScript("ShowMessage", o);
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            this.webBrowser1.Navigate(@"E:\Projects\2010\WebBrowserJavaScriptExample\WebBrowserJavaScriptExample\TestPage.htm");
        }

        [ComVisible(true)]
        public class ScriptManager
        {
            frmMain _form;
            public ScriptManager(frmMain form)
            {
                _form = form;
            }

            public void ShowMessage(object obj)
            {
                MessageBox.Show(obj.ToString());
            }
        }
    }
}

More information about WebBrowser object ju can find here:

http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.document.aspx