Amazon Ad

Friday, 14 February 2014

How To Create YouTube like website.

Hi Guys,

I recently used OpenTok API for my website to record videos and play videos. My requirement was met where users were able to record a video and play the same video in future without storing it on my server. This way i saved server space and bandwidth utilization of my server.

Here is the code

Wednesday, 5 February 2014

Get Browser and Operating System from the user agent stored in MySql database.

Here is how to get Browser and Operating System from the user agent stored in MySql database.

select 
user_agent,
CASE
WHEN user_agent REGEXP 'MSIE [[:alnum:]]+.[[:alnum:]]+' THEN SUBSTRING(user_agent, LOCATE('MSIE ', user_agent), LOCATE(';', user_agent, LOCATE('MSIE ', user_agent))-LOCATE('MSIE ', user_agent))
WHEN user_agent REGEXP 'Firefox/[[:alnum:]]+.[[:alnum:]]+' THEN SUBSTRING(user_agent, LOCATE('Firefox/', user_agent))
WHEN user_agent REGEXP 'Chrome/[[:alnum:]]+.[[:alnum:]]+' THEN SUBSTRING(user_agent, LOCATE('Chrome/', user_agent))
WHEN user_agent REGEXP 'Safari/[[:alnum:]]+.[[:alnum:]]+' THEN SUBSTRING(user_agent, LOCATE('Safari/', user_agent))
WHEN user_agent REGEXP 'SeaMonkey/[[:alnum:]]+.[[:alnum:]]+' THEN SUBSTRING(user_agent, LOCATE('SeaMonkey/', user_agent))
WHEN user_agent REGEXP 'Opera/[[:alnum:]]+.[[:alnum:]]+ ' THEN SUBSTRING(user_agent, LOCATE('Opera/', user_agent), LOCATE(' ', user_agent, LOCATE('Opera/', user_agent))-LOCATE('Opera/', user_agent))
WHEN user_agent REGEXP 'Dolfin/[[:alnum:]]+.[[:alnum:]]+ ' THEN SUBSTRING(user_agent, LOCATE('Dolfin/', user_agent), LOCATE(' ', user_agent, LOCATE('Dolfin/', user_agent))-LOCATE('Dolfin/', user_agent))
WHEN user_agent REGEXP 'AppleWebkit/[[:alnum:]]+.[[:alnum:]]+ ' THEN SUBSTRING(user_agent, LOCATE('AppleWebkit/', user_agent), LOCATE(' ', user_agent, LOCATE('AppleWebkit/', user_agent))-LOCATE('AppleWebkit/', user_agent))
ELSE 'Unknown'
END AS BROWSER,
case 
when instr(user_agent,'compatible')>0 && instr(user_agent,';')>0 && instr(user_agent,'Windows')>0 then CONCAT('Windows',(substring_index(substring_index(user_agent,'; Windows',-1),';',1))) 
when instr(user_agent,';')>0 && right(user_agent,1)!=')' then trim(substring_index(substring_index(user_agent,';',1),'(',-1)) 
when instr(user_agent,';')=0 && right(user_agent,1)=')' then substring_index(substring_index(user_agent,')',1),'(',-1) 
when right(user_agent,1)=')' then trim(substring_index(substring_index(user_agent,';',1),'(',-1)) 
else trim(substring_index(substring_index(user_agent,')',1),'(',-1)) end as 'OS'
from browsers
/*Fetch all records where user_agent is not null*/
where user_agent is not null 
/*Fetch those records whose user_agent is available*/
and instr(user_agent,'Mozilla/5.0')>0 
/*Exclude Google bots and other bots*/
and instr(user_agent,'http')=0

Thursday, 30 January 2014

Authorise Your User From StackOverFlow

Hi Guys!!,

Today i am going to tell you how to validate your user from StackOverFlow API, After tonns of effort i have developed this code.
You can use this code to authenticate your user from Stackoverflow and it also give you the relevant user details.But you need to create an app
in stackexchange.com website which will provide you a clientid and key.

Here is the code


Wednesday, 22 January 2014

How to create a GitHub Hook to update my website from GitHub Push.



Step 1 Generate a ssh key on the server and copy that ssh keys into the .ssh\id_rsa file. Also add the public key in file id_rsa.pub into your github repository under settings and ssh keys.

Step 2 On the server install git.

Step 3 On the github make sure you have a repository and create a branch named "development".

Step 4 Push all your project files onto your repository and in "development" branch.

Step 5 Pull the files from the github respository into your server's folder. Also make sure that you have sufficient rights for this folder i.e IUSR user should have sufficient rights.


Saturday, 18 January 2014

Get Deatils of Git user from Web API.


Hi Guys,

Today i am going to tell you how you can get the Git user details in Wep API.

Step 1. Go to global .asax file and add the following lines after the built in class i.e it should look like

namespace TestGit
{

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<TestGitContext, MyConfiguration>());
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }
    }
    public class MyConfiguration : System.Data.Entity.Migrations.DbMigrationsConfiguration<TestGitContext>
    {
        public MyConfiguration()
        {
            this.AutomaticMigrationsEnabled = true;
        }
    }
}

Step 2: In App_start folder open the file WebApiConfig.cs and add the following lines after routes i.e it should look like

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            //config.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //);

            config.Routes.MapHttpRoute(
                name: "DefaultApi1",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );


            var json = config.Formatters.JsonFormatter;
            config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
            config.Formatters.Remove(config.Formatters.XmlFormatter);

        }
    }

Step 3: Create a model class User, i.e

public class User
    {
        [Key]
        public int Id {get;set;}
        public string UserName { get; set; }
        public string Email { get; set; }
        public string Name { get; set; }
        public string Country { get; set; }
        public string Location { get; set; }
        public string Photo { get; set; }
        public string Languages { get; set; }
        public bool IsAvailableForHiring { get; set; }
    }

Step 4: Create a web api controller using the model class "User" and add a get action, It should look like

 [ActionName("GetUser")]
        // GET api/CodeVitae/5
        public User GetUser(string id)
        {

            id = RemoveSpecialCharacters(id);
            //User user = db.Users.Find(id);
            User user = (from u in db.Users where u.UserName == id select u).FirstOrDefault();
            if (user == null)
            {
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
                //throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
                string url = "https://api.github.com/users/" + id + "?client_id=xxxxxxxxxx&client_secret=xxxxxxxxxxxxxxxx";
                WebResponse webResponse = GetAPIData(url);
                User u=ReadFrom(webResponse,false);
                url = "https://api.github.com/users/" + id + "/repos" + "?client_id=xxxxxxxxx&client_secret=xxxxxxxxxx";
                WebResponse webResponse1 = GetAPIData(url);
                User u1 = ReadFrom(webResponse1,true);
                u.Languages = u1.Languages;
                db.Users.Add(u);
                db.SaveChanges();
                user = u;
            }

            return user;
        }

        public static string RemoveSpecialCharacters(string str)
        {
            StringBuilder sb = new StringBuilder();
            foreach (char c in str)
            {
                if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '-' || c == '_')
                {
                    sb.Append(c);
                }
            }
            return sb.ToString();
        }

        public User ReadFrom(WebResponse twitpicResponse,bool isMultiple)
        {
            User newUser = new User();
            using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
            {
                JavaScriptSerializer js = new JavaScriptSerializer();
                var objects = js.Deserialize<dynamic>(reader.ReadToEnd());
                String languages = "";
                foreach (var o in objects)
                {
                    if (isMultiple)
                    {
                        try
                        {
                            foreach (var g in o)
                            {
                                if (g.Key != null)
                                {
                                    if (g.Key == "language")
                                    {
                                        if (g.Value != null)
                                        {

                                              string t = g.Value;
                                              Technology tech = (from u in db.Technologies where u.Name == t select u).FirstOrDefault();
                                              if (tech == null)
                                              {
                                                  Technology te= new Technology();
                                                  te.Name = t;
                                                  db.Technologies.Add(te);
                                              }
                                                  if (!(languages.Contains(g.Value)))
                                                      languages = (string.IsNullOrEmpty(languages)) ? g.Value : languages + "," + g.Value;
                                             
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                    else
                    {
                        //Console.WriteLine(o["title"]);
                        if (o.Key == "login")
                        {
                            if (o.Value != null)
                                newUser.UserName = o.Value;
                        }
                        else if (o.Key == "name")
                        {
                            if (o.Value != null)
                                newUser.Name = o.Value;
                        }
                        else if (o.Key == "location")
                        {
                            if (o.Value != null)
                                newUser.Location = o.Value;
                        }
                        else if (o.Key == "email")
                        {
                            if (o.Value != null)
                                newUser.Email = o.Value;
                        }
                        else if (o.Key == "avatar_url")
                        {
                            if (o.Value != null)
                                newUser.Photo = o.Value;
                        }
                        else if(o.Key=="hireable")
                        {
                            if (o.Value != null)
                                newUser.IsAvailableForHiring = o.Value;
                        }
                    }
                }
                newUser.Languages = languages;
            }
            return newUser;
        }

        public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }


Thats it folks enjoy!!

Wednesday, 25 September 2013

WCF Could not find a base address that matches scheme https for the endpoint with binding MetadataExchangeHttpBinding. Registered base address schemes are [http].

Hi Guys,

I was facing a problem while invoking a WCF web service which was actually made for SSL (Secure Socket Layer) and runs on the https protocol. My task was to run the webservice without SSL i.e on http.

Here is how i did the same

1. Under bindings tag make sure you comment the line <security mode="Transport" /> i.e,

    <bindings>
      <webHttpBinding>
        <binding name="myBinding" maxBufferSize="2147483647"  maxReceivedMessageSize="2147483647" >
          <readerQuotas  maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647"
            maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
            <!--Commented This line-->
            <!--<security mode="Transport" />-->
        </binding>
      </webHttpBinding>

2. Comment the line <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/> i.e,

<services>
    <service behaviorConfiguration="Mine.Services.MyServiceBehavior" name="Mine.Services.MyService">
        <endpoint address="" binding="webHttpBinding" contract="Mine.Services.IMyService" bindingConfiguration="myBinding">
                <identity>
                <dns value="localhost" />
                </identity>
        </endpoint>
                     <!--Commented This line-->
                <!--<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>-->
    </service>
</services>

And that's it folks, The service now runs on HTTP protocol.

Thanks
Ritesh

Saturday, 14 September 2013

Url Routing For WebForms in ASP.NET 4.5

Hi guys,

Today i am going to tell you how to use URL Routing for ASP.NET Webforms in .net framework 4.0 and 4.5.

Step 1 : Your global.asax file should be like

public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            RegisterRoutes(RouteTable.Routes);
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.MapPageRoute("Default", "ritesh", "~/Default.aspx");
            routes.MapPageRoute("DefaultWithIdParam", "ritesh/{id}", "~/Default.aspx");
        }
    }

Step 2 : Create a page Default.aspx if it doesnt exists. Add the following lines on page_load event

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string data=Page.RouteData.Values["id"].ToString();
            }
            catch (Exception ex)
            {

            }
        }

Step 3: In browser type http://localhost:{port}/ritesh and http://localhost:{port}/ritesh/23. This would return you the page and the data also.

Thanks
Ritesh

Friday, 6 September 2013

How to setup Ruby On Rails on Windows 7 with MySql

Step 1: Install RailsInstaller (railsinstaller-2.2.1), It would create a folder RailsInstaller in the installed directory. Inside this folder go to Ruby1.9.3 folder and further inside bin folder. Right click on any file in the bin folder and select the path from the properties window. Copy this path and now we need to set this path inside PATH environment variable. Go to environment variables and edit PATH and embed the copied path inside the PATH value.


Step 2: Check Ruby and Rails versions. To check Rails version type the command "Rails --version" and press enter it would show you the Rails version. For Ruby use the command "ruby -v" and press enter it would show you the Ruby version. For rails it should be

3.2.13 or 3.2.14

Step 3: Using Ruby interpreter lets you run the ruby statements, You can run the Ruby interpreter using the command "irb". You can write ruby statements and can get the output. For ex. "Hello"*9 would print string "Hello" 9 times in irb.To exit from irb type "quit" and press enter.

Step 4: You can run ruby files (having extension .rb). Create a new file in any text editor and type the following code

myarr=[1,3,4,5,6]

myarr.each do |x|
p x
end

save this file with name "array.rb" and to run this file you need to type the command "ruby  array.rb".

Step 5: Getting started with rails environment. The rails commands are there to help you out in making web applications. To create a new web application project type "rails new firstproject". It would create a folder "firstproject" having default folders and files which are created by default by rails environment.

Step 6: Install MySql 2.8 adapter, Setting up "mysql" and linking it with rails is quite easy, If you follow some simple steps as mentioned. Edit .Gemfile inside the folder firstproject folder and add line gem "mysql". Then edit "database.yml" file present in db folder inside your project folder and add the following lines

development:
adapter: mysql

database: db_firstd

username: root

password: 1234

pool: 5

timeout: 5000

test:

adapter: mysql

database: db_firstt

username: root

password: 1234

pool: 5

timeout: 5000



production:

adapter: mysql

database: db_firstp

username: root

password: 1234

pool: 5

timeout: 5000


Here i am assuming that you have set 1234 as root password for your mysql.

Step 7:  Now we need a C-Connector for mysql, this is important as the rails will try to find the necessary dll to communicate with mysql. You can download it from http://dev.mysql.com/downloads/connector/c/6.0.html.

Step 8: Now since our database.yml file is all set, We can give command so that rails would automatically create the database in mysql database as per the configuration in database.yml file. Give the command

rake db:create

This command would create databases (Development, Production and Test database) in mysql. Now to create a model we would give the command

rails generate model Employee empcode:integer name:string email:string

This command would generate a model, The model is actually a class in RoR which actually represents the table in our database. A model is cretaed so that a table with same name (Employee) with columns (empcode,name,email) can be created in the database.

Step 9: Now we would generate a table using the model class just created by the command. To geneate a table from model we need to migrate it, To migrate the model we need to give the command

rake db:migrate

This would create the table i.e all the unmigrated model classes would be migrated into table using this command.

Step 10: Using scaffold tool is great, It creates CRUD operations by just a single command. Give the command

rails generate scaffold Student regno:string name:string email:string

This would create model, view and contorller classes. But the datbase would not be created. We need to migrate it using the command

rake db:migrate

After this run the command

rails s

to run the project. type http://localhost/students, It would give you all the CRUD operations linked with your mysql database.

Thursday, 29 August 2013

How to get duplicate values from table in MS SQL Server

Here are some of the t-Sql queries you can use to find duplicate values

1. Using group by and having

select CabTransactions.TransactionId,y.cabid,y.orderid from
(
select min(cabid) as cabid,orderid,action from CabTransactions
group by cabid,orderid,action
having count(transactionid)>1
) as y,CabTransactions where y.cabid=CabTransactions.CabId and y.OrderId=CabTransactions.OrderId

2. Using not in

select * from cabtransactions where transactionid not in
(
    select min(transactionid) from cabtransactions group by cabid,orderid
)

Thanks
Ritesh

Tuesday, 27 August 2013

How to send POST parameters from jquery $.ajax to Web API ASP.NET MVC

Hi Guys,

I was facing a strange problem while sending data from jquery $.ajax to ASP.NET MVC Web API. I had earlier made lot of web appliactions using $.ajax with SOAP based (asmx),WCF (svc) files. But this time i struggled to post data into the web api's action.

I was having an Action like

 // POST api/values
        public string Post([FromBody]string value)
        {
            return value;
        }

When i tried this

$.ajax({
                 type: "POST",
                 dataType: "json",
                 contentType: 'application/json;charset=utf-8',
                 url: "/api/values",
                 data: {'value':'Test'},
                 success: function (data) {
                     alert(data);
                 },
                 error: function (error) {
                     jsonValue = jQuery.parseJSON(error.responseText);
                 }
             });

The value passed into "value" parameter of post was "null".

This is due to the following

1. Since web api requires the data to be in the format "=yourvalue". The existing $.ajax was not passing the data in post action.
2. The content type in $.ajax here is application/json, Where as the format as stated above is not a json format.

I successfully passed the post parameter by using the following

        $.ajax({
                 type: "POST",
                 dataType: "json",
                 url: "/api/values",
                 data: '=' + 'Test',
                 success: function (data) {
                     alert(data);
                 },
                 error: function (error) {
                     jsonValue = jQuery.parseJSON(error.responseText);
                 }
             });

As you can see i have not included "contentType: 'application/json;charset=utf-8'" in $.ajax. Also i have passed the data in the

format "=yourvalue" i.e data:'='+'Test', This passed the value "Test" in my post parameter i.e "value" in this case.

For complex types you use JSON.stringify i.e you can pass like

var complexdata= { 'value': 'Test','id':'350','name':'Ritesh' };

$.ajax({
                 type: "POST",
                 dataType: "json",
                 contentType: 'application/json;charset=utf-8',
                 url: "/api/values",
                 data: JSON.stringify(complexdata),
                 success: function (data) {
                     alert(data);
                 },
                 error: function (error) {
                     jsonValue = jQuery.parseJSON(error.responseText);
                 }
             });

For PUT in WEB API with $.ajax you can use like

var obj = {'Id':'3','EmpCode':'E001','EmpName':'Ritesh'};

             $.ajax({
                 type: "PUT",
                 dataType: "json",
                 contentType: 'application/json;charset=utf-8',
                 url: "/api/values/8",
                 data: JSON.stringify(obj),
                 success: function (data)
                 {
                     alert(data);
                 },
                 error: function (error) {
                     jsonValue = jQuery.parseJSON(error.responseText);
                 }
             });

Where your put method looks like

        // PUT api/values/5
        //To update an existing record
        public void Put(int id, [FromBody]Employee value)
        {

        }

Thanks
Ritesh Tandon

Thursday, 22 August 2013

How to run SQL server job based on linked server T-SQL

Hi Guys,

I was facing problem while running a job based on the linked server. I was having two sql servers and was implementing the concept of distributed databases.

I created a stored procedures which takes the data from my server database to remote server database. I wanted to create a job for this so that after every 1 hour my database is synchronized.

I did the following -:

Check which user is associated with the SQL server agent service, usually it is

NT Service\SQLSERVERAGENT

Now Create a new job

1. Add mapping user as
NT Service\SQLSERVERAGENT and for remote server give the user name and password.

2. Make sure the owner user is the same user who is having
administrator rights.

3. Do not add any user in the run as user textbox.

4. Add your step and the T-SQL command.

5. Execute the Job

That's it folks

Thanks
Ritesh

How to implement Captcha v3 in ASP.NET

 I was facing an issue of dom parsing in my website. I finally resolved it by using Google Captcha V3. Step 1: Get your keys from https:...