Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, June 1, 2011

How to connect to a SQL server database in c#

The following code snippet will show you how to query an SQL Server database in C# using ADO.NET.
Namespaces you will need to include:
using System.Data;
using System.Data.SqlClient;

Source Code:
SqlConnection conn = new SqlConnection("Data Source=Server Name;UID=User Name;PWD=Password;Initial Catalog=Database Name");
           SqlCommand command = new SqlCommand("SELECT TOP 100 * FROM  tbl_Users",conn);
           DataTable dt = new DataTable();

            command.Connection.Open();
           SqlDataAdapter adapter = new SqlDataAdapter(command);
           adapter.Fill(dt);

           adapter.Dispose();
           command.Connection.Close();
           command.Dispose();

           foreach (DataRow dr in dt.Rows)
           {
               Console.WriteLine(dr["FirstName"].ToString()+" "+dr["LastName"].ToString());
           }

Breakdown
Initialize a SqlConnection object by passing you server connection string as a parameter. Then, initialize a SqlCommand object which you can use it to execute a SQL query or a stored procedure (We passed the SqlConnection object as an additional parameter).  I will be retrieving a set of data from the sample query; so, I need either a DataSet or DataTable object to store the result. Next, we initialize a SqlDataAdapter object that will serve us as a bridge between the SqlCommand and the DataTable (we passed the SqlCommand object as a parameter). Finally, we simply open a connection and call the Fill() method to retrieve our result. 

Tuesday, May 17, 2011

Remove read only attribute of a file in C#

To manipulate file attribute in C# we can use the System.IO.FileInfo class.
So, let’s say that we have a “Read Only” file located at C:\temp\test.jpg what we need to modify; however, we need to remove the “Read Only” attribute before we can continue.

Here is how to do it:

  FileInfo file = new FileInfo(@"C:\temp\test.jpg");
  file.Attributes = file.Attributes & ~FileAttributes.ReadOnly;

The above sample uses the bitwise operator in order to remove the “Read Only” attribute while ensuring that all other attributes that the file may have are not also removed during this operation.

Saturday, May 14, 2011

Create Thumbnails with the C# Image Class

Here is a quick tutorial on how to create thumbnail images using the System.Image class.

First let’s create a Windows Form project.




Then add a Button control and a PictureBox control.


Now add a click event to the Button control.


private void button1_Click(object sender, EventArgs e)
{
   Image img = Image.FromFile(@"C:\folder\sampleImage.jpg");
   this.pictureBox1.Image = img.GetThumbnailImage(120, 120,
new Image.GetThumbnailImageAbort(ThumbnailCallback),
IntPtr.Zero);

}

public bool ThumbnailCallback()
{
   return true;
}



First, we need an empty method (ThumbnailCallback)  to pass to the GetThumbnailImageAbort delegate. Then, we simply create an Image object (I am using the FromFile method referencing a local file). Finally, assign the image to the PictureBox control to display it.

Let's run it:

Now click "Load Image":

Monday, March 7, 2011

Bing API - Using the Bing Translator with C#


This will be the first post of a series about creating a class library for Microsoft Bing APIs in C#. I had ignore Microsoft offering in the past because Google APIs have always done the work for me; however, I recently worked in my first WP7 application and found Bing services to be really mature and capable of delivering results just as good as Google’s. 

Let’s Begin

NOTE:  You need to register and create an AppID at http://www.bing.com/developers.

Create a new project called .NET 4.0 Class Library called DeveloperCaster.Bing; we will wrap all API calls within this class library.




I want to be able to expand this library beyond the translation API so I will leave room to extend it in future posts.
We will begin by adding the following objects:

The Bing Parameter Class - It is a simple value pair class that will be used to represent request parameters to the API.










Source code:
    public class BingParameter
    {
        public string Name
        {
            set;
            get;
        }

        public string Value
        {
            set;
            get;
        }
    }



The IBingRequest Interface – Will be our datatype for request to the Bing service (see BingService class).









Source code:
  public interface IBingRequest
  {
     List<BingParameter> List { get; }
  }


The BingService class – We are going to use this class to execute all our requests to the Bing API.  BingService provide one method to perform a request and I also added an extra method that will take a IBingRequest plus an anonymous method to process a request using the Request(IBingRequest) method to send its return value to the ResponseHandler parameter (not really needed for core functionality). Our class will embed the Bing API URL (“http://api.bing.net/xml.aspx”); however, you may choose not to do so and pass it as a parameter.


















Source Code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;

namespace DeveloperCaster.Bing
{
    public delegate void ResponseHandler(HttpWebResponse response);

    public class BingService
    {
        private string _api = "http://api.bing.net/xml.aspx";
        private string _appId = "";

        /// <summary>
        /// Default constructor
        /// </summary>
        public BingService()
            : this("")
        { }

        /// <summary>
        /// Contructor with ApiId
        /// </summary>
        /// <param name="appId">AppId</param>
        public BingService(string appId)
        {
            _appId = appId;
        }


        /// <summary>
        /// Request with response handler
        /// </summary>
        /// <param name="r"></param>
        /// <param name="response"></param>
        public void ProcessRequest(IBingRequest r, ResponseHandler response)
        {
            response(Request(r));
        }

        /// <summary>
        /// Request from Api
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public HttpWebResponse Request(IBingRequest r)
        {
            StringBuilder req = new StringBuilder();
            req.Append(this.Api);

            foreach (BingParameter field in r.List)
            {
                req.Append("&" + field.Name + "=" + field.Value);
            }

            HttpWebRequest webRq = (HttpWebRequest)HttpWebRequest.Create(req.ToString());
            HttpWebResponse result = (HttpWebResponse)webRq.GetResponse();
            return result;

        }

        /// <summary>
        /// Get Api
        /// </summary>
        public string Api
        {
            get { return _api + "?AppId=" + _appId; }
        }

        /// <summary>
        /// Set/Get Api
        /// </summary>
        public string AppId
        {
            set { _appId = value; }
            get { return _appId; }
        }

    }

}




Translation Request Object
The translation request will be the first Bing request of our series so let’s being.  The Bing API allows us to request services based on SourceTypes. A SourceType is a source of information available by the API (see full documentation).
To work with the Bing Translation SourceType we will need the following two classes for our object:

The TranslationResponse Class – We will use this object to store our translation API results.











Source Code
using System;

namespace DeveloperCaster.Bing
{
    public class TranslationResponse
    {
        public string SearchedTerms
        {
            set;
            get;
        }

        public string TranslatedTerm
        {
            set;
            get;
        }
    }
}




The TranslationRequest Class – This is or main request object





















Note: Our request object must inherit from the IBingRequest Interface.

Source Code:
using System;
using System.Collections.Generic;
using System.Net;
using System.Xml;

namespace DeveloperCaster.Bing
{

    public class TranslationRequest : IBingRequest
    {

        private List<BingParameter> _items;
        private string _query;
        private string _sourceLanguage;
        private string _targetLanguage;
        private string _version;


        public static TranslationResponse ParseResponse(HttpWebResponse response)
        {
            TranslationResponse result = new TranslationResponse();

            XmlDocument doc = new XmlDocument();
            doc.Load(response.GetResponseStream());
            if (doc.HasChildNodes)
            {
                try
                {
                    if (doc.HasChildNodes)
                    {
                        if (doc["SearchResponse"] != null)
                        {
                            if (doc["SearchResponse"]["Query"]["SearchTerms"] != null)
                            {
                                result.SearchedTerms = doc["SearchResponse"]["Query"]["SearchTerms"].InnerText;
                            }

                            if (doc["SearchResponse"]["tra:Translation"] != null)
                            {
                                result.TranslatedTerm = doc["SearchResponse"]
                                    ["tra:Translation"]
                                    ["tra:Results"]
                                    ["tra:TranslationResult"]["tra:TranslatedTerm"].InnerText;
                            }
                        }

                    }
                }
                catch (NullReferenceException ex)
                {

                }
                catch (XmlException ex)
                {
                }

            }

            return result;
        }

        /// <summary>
        /// Default constructor
        /// </summary>
        public TranslationRequest()
            : this("", "", "", "") { }

        /// <summary>
        /// Second constructor
        /// </summary>
        /// <param name="query">query</param>
        /// <param name="sourceLanguage">source language</param>
        /// <param name="targetLanguage">target language</param>
        public TranslationRequest(string query, string sourceLanguage,
 string targetLanguage)
            : this(query, sourceLanguage, targetLanguage, "2.2") { }

       /// <summary>
       /// Third constructor
       /// </summary>
       /// <param name="query">query</param>
       /// <param name="sourceLanguage">source language</param>
       /// <param name="targetLanguage">target language</param>
       /// <param name="version">api version</param>
public TranslationRequest(string query, string sourceLanguage,
string targetLanguage, string version)
        {
            _items = new List<BingParameter>();
            _items.Add(new BingParameter
            {
                Name = "Sources",
                Value = "Translation"
            });

            if (!Exists("Query"))
            {
                _query = query;
            }
            if (!Exists("Translation.SourceLanguage"))
            {
                _sourceLanguage = sourceLanguage;
            }
            if (!Exists("Translation.TargetLanguage"))
            {
                _targetLanguage = targetLanguage;
            }
            if (!Exists("Version"))
            {
                _version = version;
            }
        }

        private void Add(string name, string val)
        {
            _items.Add(new BingParameter
            {
                Name = name,
                Value = val
            });
        }

        private bool Exists(string name)
        {
            bool result = false;
            foreach (BingParameter f in _items)
            {
                if (f.Name.ToLower() == name.ToLower())
                {
                    result = true;
                    break;
                }
            }

            return result;
        }

        public ResponseHandler Response;

        public string Query
        {
            set
            {
                if (!Exists("Query"))
                {
                    _query = value;
                    Add("Query", value);
                }
            }
            get { return _query; }
        }

        public string SourceLanguage
        {
            set
            {
                if (!Exists("Translation.SourceLanguage"))
                {
                    _sourceLanguage = value;
                    Add("Translation.SourceLanguage", value);
                }
            }

            get { return _sourceLanguage; }
        }

        public string TargetLanguage
        {
            set
            {
                if (!Exists("Translation.TargetLanguage"))
                {
                    _targetLanguage = value;
                    Add("Translation.TargetLanguage", value);
                }
            }

            get { return _targetLanguage; }
        }

        public string Version
        {
            set
            {
                if (!Exists("Version"))
                {
                    _version = value;
                    Add("Version", value);
                }
            }
            get { return _version; }
        }

        /// <summary>
        /// Set/Get Items
        /// </summary>
        public List<BingParameter> List
        {
            get
            {
                return _items;
            }
        }


    }


}




Usage
We will test our library by translating a phrase from English to Spanish. Create a console application, create a reference to our complied dll, and add the following code to test our library:


BingService bing = new BingService("ADD YOUR APPID HERE");

TranslationResponse response =TranslationRequest.ParseResponse(bing.Request(new            TranslationRequest{
                    Query = "Welcome to my blog",
                    SourceLanguage = "en",
                    TargetLanguage = "es"
                  })
);

Console.WriteLine("{0} = {1}", response.SearchedTerms, response.TranslatedTerm);

Console.ReadLine();


Output:
Welcome to my blog = Bienvenido a mi blog