Showing posts with label Asp. Show all posts
Showing posts with label Asp. Show all posts

Thursday, November 8, 2012

Consume Asp Web Service With C# Step By Step

My last post was about creating a asp.net web services,now its time to consume the web services by C# web or desktop application ,to consume asp.net web services by C# project simply add a web reference.
The web references url must be your web services location,then add the references.

After adding the references you will get the method to call,this must the web methods.


After adding the web references you will get this view .





Then the question is how to use this methods,the following simple code will help you to consume asp.net web services.


Sample Code :




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
                 

          //WebServiceClient is the name of my project and localhost is the name what you named when add.


using WebServiceClient.localhost;

namespace WebServiceClient
{
    public partial class ArithMeticView : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button2_Click(object sender, EventArgs e)
        {
                             

               //ArithmaticOperation is the service name,where from I get the services.


            ArithmaticOperation ar = new ArithmaticOperation();
            if (DropDownList1.SelectedItem.Text.Equals("sumi"))
            {
                Label1.Text = "Resul = ";
                Label2.Text = ar.sums(TextBox1.Text, TextBox3.Text);
            }

            if (DropDownList1.SelectedItem.Text.Equals("muli"))
            {
                Label1.Text = "Resul = ";
                Label2.Text = ar.muls(TextBox1.Text, TextBox3.Text);
            }
            if (DropDownList1.SelectedItem.Text.Equals("divi"))
            {
                Label1.Text = "Resul = ";
                Label2.Text = ar.divs(TextBox1.Text, TextBox3.Text);
            }
            if (DropDownList1.SelectedItem.Text.Equals("mod"))
            {
                Label1.Text = "Resul = ";
                Label2.Text = ar.mod(Int32.Parse(TextBox1.Text), Int32.Parse(TextBox3.Text)).ToString();
            }
            if (DropDownList1.SelectedItem.Text.Equals("isnumber"))
            {
                Label1.Text = "Resul = ";
                if (ar.isnumber(TextBox1.Text))
                {
                    Label2.Text = "Yes This Is A Number";
                }
                else
                    Label2.Text = "No.This is not a number";
            
            }

            if (DropDownList1.SelectedItem.Text.Equals("validemail"))
            {
                Label1.Text = "Resul = ";
                if (ar.validemail(TextBox1.Text))
                {
                    Label2.Text = "This Email is Valid.";
                }
                else
                    Label2.Text = "This is not a valid email";

            }
            if (DropDownList1.SelectedItem.Text.Equals("sumarray"))
            {
                Label1.Text = "Resul = ";
                int []a={1,2,3,4,5,6,7,8,9,10};
                Label2.Text = ar.sumarray(a).ToString();

            }
        }
    }
}

Thats all,thanks.


Method Overloading in C# web services

There is a little bit problem when you want to overload a method in C# web services.
If you create methods in same name and different parameters , it will build successfully.
But when you want to debug or run it it will says you to ,


Use the MessageName property of the WebMethod custom attribute to specify unique message names for the methods.


So you should change some code to make method overloading.



use :  



[WebService(Namespace = "MYFIRSTWS")]
    [WebServiceBinding(ConformsTo = WsiProfiles.None)]
    [System.ComponentModel.ToolboxItem(false)]

and

[WebMethod(MessageName = "your_name_method")]


insted of : 

[WebService(Namespace = "MYFIRSTWS")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

and

[WebMethod]


Thanks and regards.


Wednesday, November 7, 2012

Insert and Retrieve Image to mysql with C# Step by Step

The easy way to insert image in mysql and retrieve it from mysql.
To insert image data to mysql by C# just follow the step,

Step 1:

Create a database and a table with 3 field name,size,file column.

or use this sql code in your mysql database query.

sample code : 


CREATE DATABASE /*!32312 IF NOT EXISTS*/`image_test` /*!40100 DEFAULT CHARACTER SET latin1 */;

USE `image_test`;

/*Table structure for table `file` */

DROP TABLE IF EXISTS `file`;

CREATE TABLE `file` (
  `name` varchar(100) DEFAULT NULL,
  `size` varchar(100) DEFAULT NULL,
  `file` longblob
) ENGINE=InnoDB DEFAULT CHARSET=latin1;



Step 2 :

Create a C# windows form application>like this





Step 3 :

To insert image into mysql first we need to convert the image data to binary data then insert this data into mysql,we need to insert the size of that file to retrieve data.


Sample code to insert image into mysql by C#: 



private void button2_Click(object sender, EventArgs e)
        {
            //database connection
            MySql.Data.MySqlClient.MySqlConnection conn;
            MySql.Data.MySqlClient.MySqlCommand cmd;

            conn = new MySql.Data.MySqlClient.MySqlConnection();
            cmd = new MySql.Data.MySqlClient.MySqlCommand();
            //
            //image retrieve
            string SQL;
            UInt32 FileSize;
            byte[] rawData;
            FileStream fs;
            string strFileName = "";
            conn.ConnectionString = "server=127.0.0.1;uid=root;" +
                "pwd=;database=image_test;";
            try
            {
                fs = new FileStream(@"d:\image.png", FileMode.Open, FileAccess.Read);
                FileSize = (UInt32)fs.Length;
                rawData = new byte[FileSize];
                fs.Read(rawData, 0, (int)FileSize);
                fs.Close();
                conn.Open();
                SQL = "INSERT INTO file VALUES(@FileName, @FileSize, @File)";
                cmd.Connection = conn;
                cmd.CommandText = SQL;
                cmd.Parameters.AddWithValue("@FileName", strFileName);
                cmd.Parameters.AddWithValue("@FileSize", FileSize);
                cmd.Parameters.AddWithValue("@File", rawData);
                cmd.ExecuteNonQuery();
                MessageBox.Show("File Inserted into database successfully!",
                    "Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

                conn.Close();
            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                MessageBox.Show("Error " + ex.Number + " has occurred: " + ex.Message,
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


The image location is d:\image.png , you can change as your requirement.

Step 4 :

To retrieve image from mysql by C# just look out the code and easily you will get it.

use this code and the new retrieved file location is d:\newfile.png ;



Sample code for view image :



 private void button3_Click(object sender, EventArgs e)
        {
            MySql.Data.MySqlClient.MySqlConnection conn;
            MySql.Data.MySqlClient.MySqlCommand cmd;
            MySql.Data.MySqlClient.MySqlDataReader myData;
            conn = new MySql.Data.MySqlClient.MySqlConnection();
            cmd = new MySql.Data.MySqlClient.MySqlCommand();

            string SQL;
            UInt32 FileSize;
            byte[] rawData;
            FileStream fs;

            conn.ConnectionString = "server=127.0.0.1;uid=root;" +
                "pwd=;database=image_test;";

            SQL = "SELECT name, size, file FROM file";

            try
            {
                conn.Open();

                cmd.Connection = conn;
                cmd.CommandText = SQL;

                myData = cmd.ExecuteReader();

                if (!myData.HasRows)
                    throw new Exception("There are no BLOBs to save");

                myData.Read();

                FileSize = myData.GetUInt32(myData.GetOrdinal("size"));
                rawData = new byte[FileSize];

                myData.GetBytes(myData.GetOrdinal("file"), 0, rawData, 0, (int)FileSize);

                fs = new FileStream(@"d:\newfile.png", FileMode.OpenOrCreate, FileAccess.Write);
                fs.Write(rawData, 0, (int)FileSize);
                fs.Close();
                Image image = Image.FromFile(@"d:\newfile.png");
                pictureBox1.Image = image;
                MessageBox.Show("File successfully written to disk!",
                    "Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                myData.Close();
                conn.Close();
            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                MessageBox.Show("Error " + ex.Number + " has occurred: " + ex.Message,
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }



Download Full demo for this Project :


ImageInsertRetrieve.zip


Thanks all