Pages

11/11/2014

c# and asp.net development on Ubuntu

MonoDevelop  is the tool used to develop .Net language applications on ubuntu
To install on Ubuntu use terminal with following command:

sudo apt-get install monodevelop


Show Windows Virtual Keyboard c#

The simplest way to show windows virtual keyboard using c# is as follows:

1. Create new windows form project.
2. Double Click on newly created form to create form load event.
3. Now start a process of virtual keyboard by following code on form load event:

System.Diagnostics.Process.Start("osk.exe");

4. Now create form closing event by right clicking the form view and clicking on events from properties windows. Now double click on formclosing event. It will create the form closing event. Add following code in it:

Process.GetProcessesByName("osk")[0].Kill();  

For any question you may contact me.


8/07/2012

Browse images from directory and Convert Colored Images to Gray Scale c#

Recently i have to convert colored bitmap/jpeg images to gray scale in my project. I found many solutions on Google but found one useful. This tutorial will help you browse images from directory and convert them to gray scale one by one.

First of all create a solution and windows form project in visual studio.

Then drag two picture boxes from toolbox on the left on to the form and two buttons also.

Name picture boxes pctColoredImage and pctGrayScale. Also the two buttons btnNext and btnPrevious and show text on them Next and Previous respectively.

Double click on each picture boxes and buttons to create their events.

Now create

List<string> FilesFromFolder = null; a global variable and in constructor initialize it like this

FilesFromFolder = new List<string>();

Now in form load add files from the folder to the list just initialized in the constructor.


string[] fileEntries = Directory.GetFiles("data/")
                foreach (string fileName in fileEntries)
                {
                    // add directory files to list
                    FilesFromFolder.Add(fileName);
                }

Declare int fileIndex = 0; as global variable to track count of index.

Now in event of onClick of btnNext write this code


if (FilesFromFolder.Count == fileIndex)
                fileIndex = 0;

            this.Text = FilesFromFolder[fileIndex];
            CalculateACCR(fileIndex);
            pctBoxMain.Image = new Bitmap(FilesFromFolder[fileIndex++]);

            pctBoxGrayScale.Image =  ConvertToGrayscale (new Bitmap(pctBoxMain.Image));

In event of onClick of btnPrevious write this code


if (fileIndex == 0)
                fileIndex = FilesFromFolder.Count;

            this.Text = FilesFromFolder[(fileIndex) - 1];

            CalculateACCR(fileIndex - 1);

            pctBoxMain.Image = new Bitmap(FilesFromFolder[(fileIndex) - 1]);
            fileIndex--;

            pctBoxGrayScale.Image = ConvertToGrayscale(new Bitmap(pctBoxMain.Image));

now to convert images to gray scale us this function


public static Bitmap  ConvertToGrayscale (Bitmap original)
        {
            //create a blank bitmap the same size as original
            Bitmap newBitmap = new Bitmap(original.Width, original.Height);

            //get a graphics object from the new image
            Graphics g = Graphics.FromImage(newBitmap);

            //create the grayscale ColorMatrix
            ColorMatrix colorMatrix = new ColorMatrix(
               new float[][] 
                              {
                                 new float[] {.3f, .3f, .3f, 0, 0},
                                 new float[] {.59f, .59f, .59f, 0, 0},
                                 new float[] {.11f, .11f, .11f, 0, 0},
                                 new float[] {0, 0, 0, 1, 0},
                                 new float[] {0, 0, 0, 0, 1}
                              });

            //create some image attributes
            ImageAttributes attributes = new ImageAttributes();

            //set the color matrix attribute
            attributes.SetColorMatrix(colorMatrix);

            //draw the original image on the new image
            //using the grayscale color matrix
            g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
               0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);

            //dispose the Graphics object
            g.Dispose();
            return newBitmap;
        }





Note: you may have to adjust slightly the index for next and previous image.


6/01/2012

HP g6 weak wireless issue resolved

I recently bought HP g6 i5 and very first day got issue of weak wireless signals. First i thought its  just the router issue but it kept as it is for week or so. 


Got frustrated with it and started googling it. Read some different posts so gonna conclude them.


One post said remove the back cover and check if wireless antennas are not connected to the wireless card. This may be one of the issue. It resolved the issue of the person who posted it.


Another said that just update the wlan broadcomm drivers. It can be done by going into the device manager and clicking expand on the network adapters. Find wireless there and right click on it and update drivers. It works on windows 7. You can also download the drivers from hp site. 


Both are the solutions. I followed the second one n got my laptops signal strength to maximum.


Also there is an option in device manager about the wireless signal. Do check it if its 100% or not.


If none of above works then pray your laptop is in warranty :)


4/10/2012

Use Morse Code to write text in Desktop Apps

First of all create a windows form project in visual studio and drag three buttons on the form and a textbox(you can add further controls but these are minimum controls needed).

Declare following global variables.\

private string inputString = "";
        private int count = 0;

        private static readonly Dictionary<string, string> mapping = new Dictionary<string, string>() {
        {  ".-","a" },
        {  "-...","b" },
        {  "-.-.", "c"},
        {  "-..","d" },
        {  "." ,"e"},
        {  "..-.","f" },
        {  "--.","g" },
        {  "....","h" },
        {  "..","i" },
        {  ".---","j" },
        {  "-.-" ,"k"},
        {  ".-.." ,"l"},
        {  "--" ,"m"},
        {  "-." ,"n"},
        {  "---" ,"o"},
        {  ".--." ,"p"},
        {  "--.-" ,"q"},
        {  ".-." ,"r"},
        {  "..." ,"s"},
        {  "-" ,"t"},
        {  "..-" ,"u"},
        {  "...-" ,"v"},
        {  ".--" ,"w"},
        {  "-..-" ,"x"},
        {  "-.--" ,"y"},
        {  "--.." ,"z"},
        {  "-----" ,"0"},
        {  ".----" ,"1"},
        {  "..---" ,"2"},
        {  "...--" ,"3"},
        {  "....-" ,"4"},
        {  "....." ,"5"},
        {  "-...." ,"6"},
        {  "--..." ,"7"},
        {  "---.." ,"8"},
        {  "----." ,"9"}
    };


Now name one button as "." and second as "-" as morse code depends on these two characters.

Name the third button as "space" which will be used to differentiate characters and letters.

On click event of button named "." write following line.

inputString += ".";

On click event of button named "-" write following line.

inputString += "-";

On click event of button named "space" write following lines. 

            count++;
            if (count == 1 && inputString != "")
            {
                textBox1.Text += GetLetter(inputString);
                count = 0;
            }
            else
            {
                textBox1.Text += GetLetter(inputString) + " ";
                count = 0;
            }

            inputString = "";


        public string GetLetter(string morseCode)
        {
            return mapping.ContainsKey(morseCode.ToString()) ? mapping[morseCode] : "";
        }


 Now build and run this project. 

If you want to differentiate between characters hit space once and if you want to add space hit space twice.

This can b very useful in mobile development where it could be used for typing.

Any suggestions and queries are welcome.


5/05/2011

Getting all databases from Sql Server 2005-2008 using c#

This code will help you in getting all databases of Sql Server and show them in the drop down list.

SqlConnection connection = new SqlConnection(connectionstring);

ServerConnection conn = new ServerConnection(connection);
Server myServer = new Server(conn);
foreach (Database db in myServer.Databases)
       ddlDatabases.Items.Add(db.Name);

Note: 'ddlDatabases' is the name of combobox. And db.Name contains the name of the database


4/19/2011

Paging through SQL Server

This query will help you in doing paging through SQL Server. You will need to pass just the starting and ending index and it will return the records..


DECLARE @startingindex int;

DECLARE @endingindex int

set @startingindex=10
set @endingindex=20

select * from Table_Name
where table_id in(

SELECT us.table_id
FROM (SELECT ROW_NUMBER() OVER (ORDER BY table_id) AS Row,
Table_id
FROM Table_Name) us
WHERE Row >@startingindex and Row<@endingindex
)


12/28/2010

Running SQL Server Compact on WINCE--Tutorial

Recently i had to use SQL server in WINCE which was installed on Friendly ARM device. I had to go through some R&D to find it. Got some errors in the beginning but finally was able to do so. Just to be simple on the new image of WINCE just copy these cab files from the pc and copy them to TEMP folder in the WINCE.

You can find these cab files in the Program Files/SQL Server Compact in ARM folder. You will also need a .NET cab file which you can get from Framework installed directory. If you have Visual Studio 2008 installed you can get them easily you don't need to download these.

The files are
1. NETCFv35.wce.armv4
2. sql.wce5.armv4i
3. sqlce.dev.ENU.wce5.armv4i
4. sqlce.repl.wce5.armv4i
5. sqlce.wce5.armv4i

After copying these files in TEMP folder in WINCE double click each of them to install them one by one. Install them on the default path (Recommended).

Now you can run SQLCE commands in your application using C# or any language . If any one of these files are not installed properly you may not be able to run the SQL Server Compact.

The database file is .sdf which will be used in WINCE. You can create this DB file in SQL Server Management 2008. On startup just select database engine type to compact and create the file. Then copy it to the WINCE and you are good to go.

How to connect to it will be in next tutorial....

Queries are welcomed..


11/21/2010

Image Store Save/Retrieve C# Web SQL Server using Handler/ Generic Handler

This tutorial is to guide you to save/retrieve image using C# in ASP.Net Web

The saving image process is same as the windows form saving image process. You can get detail on my other tutorial which i wrote earlier which guide you to save/retrieve image in Windows Forms. You can read that tutorial from Click Here

For you ease i will copy past the code to show you how you save image in SQL server using C#.

1. First of all we need a database in SQL Server which contains a table with only two columns one is 'id' of type 'int' and second is of 'image' of type 'image'.

2. Open SQL Server 2005 Express Management Studio and create new database. Name it according to your choice.

3. After successfully creating database create a table with two columns described in step 1.

4. Now Open Visual Studio 2008/2010.

5. Create a project of windows Web.

6.. In this event function of button you are using to save the image, create an object of FileStream, a string and byte array. Or you can simply paste the code below.


FileStream fs;
string path = "C:\\Sunset.jpg";
fs = new FileStream(path, FileMode.Open, FileAccess.Read);
//a byte array to read the image
byte[] picbyte = new byte[fs.Length];
fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length));
fs.Close();

7. Now below this create database connectivity and store this byte array(picbyte) to the image column in the database table you created in starting steps. OR you can use this code.

string cString = "Initial Catalog=DB NAME;Data Source=SQL SERVER INSTANCE;User ID=DB USER;Password=DB USER PASSWORD;";
SqlConnection connection = new SqlConnection(cString);
string query = "insert into TableName (ColumnName) values (@pic)";
connection.Open();
SqlParameter picparameter = new SqlParameter();
picparameter.SqlDbType = SqlDbType.Image;
picparameter.ParameterName = "pic";
picparameter.Value = picbyte;
SqlCommand cmd = new SqlCommand(query, connection);
cmd.Parameters.Add(picparameter);
if (cmd.ExecuteNonQuery() > 0)
MessageBox.Show("Image Saved");
connection.Close();

8. Now the image is saved in the database. You can see this by using query analyzer. Confirm it by the length of image column you will see when you will query it.

9. Now the image is successfully saved, its time to Retrieve it.

10. Retrieving and showing image in web is slightly different from windows form.

11. You need handler to show image.

12. You can add handler from right clicking the web project and adding new item.

13. Handler got the extension of .ashx. E.g. when you added handler from adding new item you get Handler.ashx. You can rename it to whatever you want.

14. Now you need a image control in the web page to show the image. You can use asp:image and in its ImageUrl attribute write handler's URl like

ImageUrl="~/Handler.ashx"

15. '~' sign is to get the project starting location. If its in any folder then write its name first after ~ sign.

16. In handler.ashx you will retrieve the image and show it. You can send the image id or user id to the handler if you want to show image at runtime depending on the user. Basically used in dynamic sites. You can send id like this

ImageUrl="~/Handler.ashx?id=1"

17. Handler code looks like

public void ProcessRequest (HttpContext context)
{
try
{
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
context.Response.ContentType = "image/jpg";
conDB = new System.Data.SqlClient.SqlConnection("Data Source=SERVER Name;Initial Catalog=DB Name;Integrated Security=True;");
conDB.Open();
int id = 'id of the user or image You can get it from URL also if you send it to handler by REQUEST';
string str = "Select (Image) from TableName where UserID or ImageID =" + id;
System.Data.SqlClient.SqlCommand cmd = new SqlCommand(str, conDB);
System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
byte[] img = (byte[])reader["Image"];
reader.Close();
memoryStream.Write(img, 0, img.Length);
context.Response.Buffer = true;
context.Response.BinaryWrite(img);
memoryStream.Dispose();
conDB.Close();
context.Response.OutputStream.Write(img, 0, img.Length);
context.Response.BinaryWrite(img);
}
catch (Exception ex)
{
context.Response.Redirect("Error.aspx");
}
}

18. Now the Image will be shown in the asp:image after retrieval from Database.

19. One handler is enough to show as many images you want to show in the web site.

Queries are welcomed........


10/27/2010

Image Save/Retrieve C# Windows Form SQL Server

This tutorial will guide you to save or retrieve image from SQL Server in C#.

1. First of all we need a database in SQL Server which contains a table with only two columns one is 'id' of type 'int' and second is of 'image' of type 'image'.

2. Open SQL Server 2005 Express Management Studio and create new database. Name it according to your choice.

3. After successfully creating database create a table with two columns described in step 1.

4. Now Open Visual Studio 2008/2010.

5. Create a project of windows form.

6. In Design View of Form1(you can rename it to your choice) drag a control of picture box to the form with two buttons.

7. Change text of one button to Save and second to Retrieve.

8. Double click Save button to create event for double click.

9. In this event function, create an object of FileStream, a string and byte array. Or you can simply paste the code below.


FileStream fs;


string path = "C:\\Sunset.jpg";


fs = new FileStream(path, FileMode.Open, FileAccess.Read);


//a byte array to read the image


byte[] picbyte = new byte[fs.Length];


fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length));


fs.Close();

10. Now below this create database connectivity and store this byte array(picbyte) to the image column in the database table you created in starting steps. OR you can use this code.

string cString = "Initial Catalog=DB NAME;Data Source=SQL SERVER INSTANCE;User ID=DB USER;Password=DB USER PASSWORD;";


SqlConnection connection = new SqlConnection(cString);


string query = "insert into TableName (ColumnName) values (@pic)";


connection.Open();
SqlParameter picparameter = new SqlParameter();


picparameter.SqlDbType = SqlDbType.Image;


picparameter.ParameterName = "pic";


picparameter.Value = picbyte;


SqlCommand cmd = new SqlCommand(query, connection);


cmd.Parameters.Add(picparameter);
if (cmd.ExecuteNonQuery() > 0)
MessageBox.Show("Image Saved");
connection.Close();

11. Now the image is saved in the database. You can see this by using query analyzer. Confirm it by the length of image column you will see when you will query it.

12. Now the image is successfully saved, its time to Retrieve it.

13. Drag another picture box to the Designer.

14. Double click the Retrieve button to create the double click event.

15. You can simply use the code below to show the image you saved in the second picture box.

string cString = "Initial Catalog=DatabaseName;Data Source=SQL Instance Name;User ID=DB user;Password=Db User Password;";


SqlConnection connection = new SqlConnection(cString);


SqlCommand command = new SqlCommand("select ColumnName from tableName where ID=1", connection);


connection.Open();


SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();


sqlDataAdapter.SelectCommand = new SqlCommand("select userimage from UserImages where imageID=" + Convert.ToInt32(txtID.Text), connection);


DataSet dSet = new DataSet();


sqlDataAdapter.Fill(dSet);


if (dSet.Tables[0].Rows.Count > 0)
{
MemoryStream ms = new MemoryStream((byte[])dSet.Tables[0].Rows[0]["userimage"]);
pictureBox2.Image = new Bitmap(ms);
}

Note: ID in the command is the id you will see in the database of the image just stored. You can get this id form UI by just giving a textbox to the user.

Now you have successfully saved/retrieved image in the SQL Database using C#.

Any queries then you may ask....


Twitter Delicious Facebook Digg Favorites More