Wednesday, 6 August 2014

Upload images to Imgur API version 3 using c#.

Find imgur API documentation at : http://api.imgur.com/

Step 1:

First register the application on the website(www.imgur.com) and collect Client-ID and Secret key.

Step 2:

Code to access the imgur api 

PostToImgur(@"E:\IMG.png","put client-id","put secret key");

            

imagFilepath : the path of the file on hard disk
apiKey : the client id received after registering the application
apiSecret : the secret key received
 public void PostToImgur(string imagFilePath, string apiKey, string apiSecret)
 {
            byte[] imageData;
            FileStream fileStream = File.OpenRead(imagFilePath);
            imageData = new byte[fileStream.Length];
            fileStream.Read(imageData, 0, imageData.Length);
            fileStream.Close();

            const int MAX_URI_LENGTH = 32766;
            string base64img = System.Convert.ToBase64String(imageData);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < base64img.Length; i += MAX_URI_LENGTH)
                {
                    sb.Append(Uri.EscapeDataString(base64img.Substring(i, Math.Min(MAX_URI_LENGTH,                         base64img.Length - i))));
                }

            string uploadRequestString = "client_id" + apiKey + "client_secret" + apiSecret + "&title=" + "imageTitle" + "&caption=" + "img" + "&image=" + sb.ToString();
   
            HttpWebRequest webRequest =                                                                                                    (HttpWebRequest)WebRequest.Create("https://api.imgur.com/3/upload.xml");                         
            //below : replace xxxxxxxxx with client id
            webRequest.Headers.Add("Authorization", "Client-ID xxxxxxxxx");                       
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ServicePoint.Expect100Continue = false;

            StreamWriter streamWriter = new  StreamWriter(webRequest.GetRequestStream());       

            streamWriter.Write(uploadRequestString);
            streamWriter.Close();

            WebResponse response = webRequest.GetResponse(); 
            Stream responseStream = response.GetResponseStream();
            StreamReader responseReader = new StreamReader(responseStream);
            string responseString = responseReader.ReadToEnd();

            //received response is a xml file. the link to the uploaded file is in between
               the tag<link></link>
           //using regular expression to retrive the link to the image.

            Regex regex = new Regex("<link>(.*)</link>");
            txtLink.Text = regex.Match(responseString).Groups[1].ToString(); 
           
        }





Get CSV Values in SQL

Query: DECLARE @CSVValue NVARCHAR(50)='100,101,102'                   DECLARE @eachValue NUMERIC(9,0)   while len(@CSVValue) ...