Friday, November 25, 2011

YELP API in C#

Hi Every one,

Yelp is a power full API to get restaurants details and show it to your site and when it comes to c# most of users are pointed to API version @ YELP API and face a night mare of no support so i have used certain features of this API and added simple functionality to parse by JSON.net.

So First down load YELP API in c# and then download bineris form JSON.net include both in user visual studio solution and reference to your website.

Now open the YELP API code and add the following functions in class YelpSearchService.

public static string SearchLocationWithString(String location, String category, String term)
        {
            return SearchLocationWithString(location, category, term, MaxResultCount);
        }

        public static string SearchLocationWithString(String location, String category, String term, Int32 resultCount)
        {
            YelpRequest<SearchResult> request = new YelpRequest<SearchResult>(RequestUrl);

            request.Parameters.Add("location", location);
            request.Parameters.Add("category", category);
            request.Parameters.Add("term", term);
            request.Parameters.Add("num_biz_requested", resultCount.ToString());

            return request.ExecuteRequestWithString();
        }


After this add the following functions in class YelpRequest.


public string ExecuteRequestWithString()
        {
            this.CreateRequest();

            Monitor.Enter(YelpServices.GlobalLock);

            try
            {
                TimeSpan timeSinceLastRequest = DateTime.Now.Subtract(YelpServices.LastRequest);

                if (timeSinceLastRequest.TotalSeconds < 2.0)
                {
                    Thread.Sleep(2000 - (Int32)timeSinceLastRequest.TotalMilliseconds);
                }

                return this.getResponse((HttpWebResponse)this.m_HttpRequest.GetResponse());
            }
            finally
            {
                YelpServices.LastRequest = DateTime.Now;

                Monitor.Exit(YelpServices.GlobalLock);
            }
        }


        private string getResponse(HttpWebResponse WebResp)
        {

            Stream Answer = WebResp.GetResponseStream();
            StreamReader _Answer = new StreamReader(Answer);
            return _Answer.ReadToEnd();

        
        }

Now its time to go to page where you want to show restaurants Data just call the newly created functions and pass then over to JSON.NET



YelpServices.APIKey = "YOUR API KEY";
            string json = YelpSearchService.SearchLocationWithString("RESTURANT ADDRESS", "",
             "CATEGORY/NAME OF RESTURANT");
            bool hasReviews = false;
            List<Business> bList = new List<Business>();

            JObject o = JObject.Parse(json);

            IList<object> reviews = o.SelectToken("businesses").Select(s => (object)s).ToList<object>();
            foreach (Object j in reviews)
            {
                try
                {
                    Business deserializedProduct = JsonConvert.DeserializeObject<Business>(j.ToString());
                    //Review r = (Review)j;
                    bList.Add(deserializedProduct);
                }
                catch (Exception)
                {

                }

            }


And you will get all the business in the YELP API business class if you find Nulls in values try changing the property names in Business calls to the ones you find in JSON response.

Hope it helps.

Happy Coding.. :)

Friday, November 11, 2011

Migrating Existing .NET site to Umbraco

Hi Every one,

Its been long time since i have written any post item but today i am going to share a tip for users who want to Move an existing system to umbraco with minimal effort.

Benefits of this Practice:
1: You will have an admin section to manage out every content of the system including UI
2: If you are using any custom CMS it will work the same way as always.

Prerequisites:
1: Install Umbraco. [share me a comment if you need any help]
2: You Existing site with code.

Steps to follow:
1: Take a backup of your existing site.
2: Copy Master Pages to umbraco masterpages folder.
3: Copy Script files to scripts folder.
4: Copy css files to css folder.
5: Now convert all the pages in the site to user controls, the process is simple.
i: Rename the file extension from .aspx to .ascx
ii: If its a web application then go to designer and change the class name as well.
6: copy all the newly created user controls to usercontrol folder in umbraco directory.
7: run the site and go to yourdomain/umbraco/login.aspx and login to the admin site.
8: Go to the developer tab and add every control in macro section don't forget to Tick [Use in editor] property. [and you are half way there :)]
9: You will find your master pages in settings section under master pages; if you don't you can add them with same name over here.
10: In the same setting section Create a new document type and set its template to any one of the master pages.
11: Create a separate document type for each masterpage
12: In the Dcoument Type goto generic properties Tab and create a property for each content section of master page and set the type of property to rich text editor.
13: Now go back to template where you have created master pages and replace all the content Areas with Umbraco page field name, you will find the Properties you just created in that list. Simply add them.
14: Go to the content section add new content pages by selecting respective master page template for each.
15: you will find a Rick text editor in each content area.
16: Add a Macro to that content area. [And you are done]


This Is the most simple way to migrate any site in umbraco; if you need any help just let me know ill respond to your comments immediately.

Happy Coding. :)

Sunday, April 3, 2011

Stored Procedure to create Inserts Update procedure of table.

Hi All,

Today i am sharing a technique that is really a time savior for writing procedures for tables having lots of columns which require an ample of time to make the parameters for each column and then perform required insert update thing on them.

So here goes the technique, this is a simple procedure that takes the name of table and create its Insert update proc on execution.


CREATE procedure [CreateInsertUpdate] 
@tablename varchar(800)
AS

declare @vtblcolumns varchar(max)
declare @vcolumns1 varchar(max)
declare @vcolumns2 varchar(max)
declare @vtblDtypes varchar(max)
Declare @vstr varchar(max) 
declare @vColumns varchar(max)
Declare @vPKcol varchar(250)
declare @Sid varchar(200)
  SELECT @sid =  TABLE_NAME FROM information_schema.tables WHERE table_name = @tablename AND OBJECTPROPERTY(OBJECT_ID(TABLE_NAME), 'TableHasIdentity') =1

  Select @vPKcol = c.COLUMN_NAME 
 from  INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
         INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
         where  pk.TABLE_NAME = @tableName
            and CONSTRAINT_TYPE = 'PRIMARY KEY'
      and c.TABLE_NAME = pk.TABLE_NAME
      and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

  select @vtblcolumns =  COALESCE(@vtblcolumns+',','')+ COLUMN_NAME + '='+'@P'+ COLUMN_NAME + ' 'from information_schema.columns where TABLE_NAME= @tablename  AND COLUMN_NAME NOT IN (@vPKcol)
  
  if @sid = null 
    select @vcolumns1 =    COALESCE(@vcolumns1+',','')+ COLUMN_NAME,@vColumns2 = COALESCE(@vColumns2+',','') + '@p'+ Column_NAME from information_schema.columns where TABLE_NAME= @tablename 
  else 
 select @vcolumns1 =    COALESCE(@vcolumns1+',','')+ COLUMN_NAME,@vColumns2 = COALESCE(@vColumns2+',','') + '@p'+ Column_NAME from information_schema.columns where TABLE_NAME= @tablename and COLUMN_NAME <> @vPKcol
-- Select  from information_schema.columns where TABLE_NAME =@tablename

   
      
      Select @vColumns = COALESCE(@vColumns+',','') + 
     '@p'+ Column_NAME + ' ' + 
  Data_Type  + 
  case when Character_Maximum_length > 0 then
   '(' + cast(Character_Maximum_length as varchar(10)) + ')'
  else ''
  end from information_schema.columns where TABLE_NAME =@tablename
  


Select @vstr = 
'
IF Object_ID ( ''UP_'+@tablename+'_InsertUpdate '') IS NOT NULL
 DROP Procedure UP_'+@tablename+'_InsertUpdate
GO

SET ANSI_NULLS ON  
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:  '+system_user+'
-- Create date: '+convert (varchar (50),getdate(),103)+'
-- Description: This is Auto Generated Code for '+@tablename+' Insert and Update Record for Single Primary Key Table
-- =============================================
CREATE PROCEDURE UP_'+@tablename+'_InsertUpdate 
('+@vColumns+ ' 
)
As
BEGIN
SET NOCOUNT ON;

 IF EXISTS (Select '+@vpkcol+' from '+@tablename+ ' where '+@vpkcol+'='+'@p'+@vpkcol+ ')
 BEGIN
 UPDATE '+@tablename+' 
 SET '+@vtblcolumns+' 
 WHERE '+ @vPKcol + '='+'@p'+@vpkcol+ '
 END
 ELSE
 BEGIN
 INSERT INTO '+@tablename+ '('+@vcolumns1+') 
      VALUES ('+@vColumns2+')

    SET ' +'@p'+@vPKcol+' = Scope_Identity()
 END

RETURN  ' +'@p'+@vPKcol+'

End
GO
'
Print @vstr 



Suppose we have a table name test_table all we need to do is to pass the name in parameter.

exec CreateInsertUpdate test_table


just copy the text created in messages panel and execute.

Happy coding :)

Sunday, February 13, 2011

Calling authenticated WSE web service in Visual Studio 2008.

Hi All,

This time i was given a task to call a web service which was written in older technology WSE and as you all know that its obsolete and replaced by WCF services but still some old written services are to be used.

When i added the service reference in my application it auto generates the configuration file as shown below, but by using this configuration file i was not able to provide credentials to web service call.

<basicHttpBinding>
        <binding name="FsetServiceSoap" closeTimeout="00:01:00" openTimeout="00:01:00"
          receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
          bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
          maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
          messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
          useDefaultWebProxy="true">

          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="Transport">
            <transport clientCredentialType="None" proxyCredentialType="None"
              realm="">
              <extendedProtectionPolicy policyEnforcement="Never" />
            </transport>
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>


        </binding>
        <binding name="FsetServiceSoap1" closeTimeout="00:01:00" openTimeout="00:01:00"
          receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
          bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
          maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
          messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
          useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None" realm="">
              <extendedProtectionPolicy policyEnforcement="Never" />
            </transport>
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
      </basicHttpBinding>


so i replaced this basichttp binding with custom binding.


<customBinding>

        <binding name="FsetServiceSoap" >

          <textMessageEncoding messageVersion="Soap12WSAddressingAugust2004" />

          <security authenticationMode="UserNameOverTransport"></security>

          <httpsTransport/>

        </binding>

      </customBinding>

and when calling the web service passed the credentials and it worked like charm.

FsetServiceHeader header = new FsetServiceHeader();
FsetServiceSoapClient client = new FsetServiceSoapClient();
client.ClientCredentials.UserName.UserName = _userName;
client.ClientCredentials.UserName.Password = _password;
byte[] rawData = File.ReadAllBytes(_filePath);
TransmissionAcknowledgementType result = client.SendTransmission(header, SendType, rawData);

Hope it helps.

Happy coding.

Regards,
U

Calling OOyala player API using C#.

Hello Friends,

Some or any of you might have used OOyala tool for you projects as its one of the best video management tools i have ever seen.

Some days back i have given a task to get ooyala integrated to our project and i decided to do it via their API but all the samples given on site are eighter in PHP or in Ruby but i want things to be done in c# so by following their documentation i have finally got the response from ooyala site.

Here i am showing you two functions and two properties.

1. _params: i have used sorted dictionary because ooyala demands that all parameters should be in acceding order.

2. Query type: specify which API should be called.

3. send_request(): It does the required encoding of parameters by using the secret and partner code and generated the URL by which XML response can be fetched.

4. getXMLResponse(): Get all XML from URL.

#region Properties

        private string PARTNET_CODE = "PARTNET_CODE";
        private string PARTNET_SECRET = "PARTNET_SECRET";


        private string _queryType = string.Empty;
        public string QueryType
        {
            get
            {
                return _queryType;
            }

            set
            {
                _queryType = value;
            }

        }

        private SortedDictionary<string, string> _params;
        public SortedDictionary<string, string> Params
        {

            get
            {
                return _params;
            }
            set
            {
                _params = value;
            }

        }

        #endregion



        #region Public function



        public string getXMLResponse()
        {


            string sUrl = send_request();
            StringBuilder oBuilder = new StringBuilder();
            StringWriter oStringWriter = new StringWriter(oBuilder);
            XmlTextReader oXmlReader = new XmlTextReader(sUrl);
            XmlTextWriter oXmlWriter = new XmlTextWriter(oStringWriter);
            while (oXmlReader.Read())
            {
                oXmlWriter.WriteNode(oXmlReader, true);
            }
            oXmlReader.Close();
            oXmlWriter.Close(); 

            return oBuilder.ToString();


        }


        /// <summary>
        /// Returns the URL for request parameters 
        /// </summary>
        private string send_request()
        {

            string url = "http://api.ooyala.com/partner/" + QueryType + "?pcode=" + PARTNET_CODE;
            foreach (KeyValuePair<string, string> pair in _params)
            {
                PARTNET_SECRET += pair.Key + "=" + pair.Value;
                url += "&" + HttpUtility.UrlEncodeUnicode(pair.Key) + "=" + HttpUtility.UrlEncodeUnicode(pair.Value);
            }
            SHA256Managed sh = new SHA256Managed();
            byte[] request = System.Text.Encoding.ASCII.GetBytes(PARTNET_SECRET);
            sh.Initialize();
            byte[] b4bbuff = sh.ComputeHash(request, 0, request.Length);
            string hashString = System.Text.Encoding.ASCII.GetString(b4bbuff);

            string encryptedRequest = HttpUtility.UrlEncode((Convert.ToBase64String(b4bbuff)).Substring(0, 43));
            url += "&signature=" + encryptedRequest;

            return url;
        }
#endregion


Once you get the XMl response do what ever you want, Deserilise it and use it in c# code or parse it with jQuery choice is yours.

Hope it helps.

Happy coding.

Regards,
U