Amazon Ad

Monday, 26 May 2014

jQuery ajax POST and saving value in local javascript variable


Hi Guys,

I was working on an ASP.NET page and found a strange problem. Whenever i
was calling the jquery ajax POST request, The data from webservice was
available in the success function but not after $.ajax request code. This
was strange i as wanted to access the data after calling the ajax POST
request.

Here is the problem

var localdata;
$.ajax({
data:"{'id':'1'}",
type:"POST",
dataType:"json",
contentType:"application/json",
url:"http://www.test.com/test.svc/HelloWorld",
success:function(data){localdata=data;alert("Inside Success "+localdata);},
error:function(a,b,c){}
});
alert("After ajax "+localdata);

After executing the above it gave me "Inside Success Hello", But the second
alert message gave me "After ajax undefined". This was due to the fact
that the first call was made inside success which was asynchronous, Whereas
the second alert was not asynchronous and didn't wait until the
$.ajax POST request executed.

To solve the same, I made it synchronous as i had to store the result of
webservice in a local variable, Here is the code

var localdata;
$.ajax({
data:"{'id':'1'}",
type:"POST",
dataType:"json",
        async:false, //setting this made it a synchronous call
contentType:"application/json",
url:"http://www.test.com/test.svc/HelloWorld",
success:function(data){localdata=data;alert("Inside Success "+localdata);},
error:function(a,b,c){}
});
alert("After ajax "+localdata);

Thanks
Ritesh Tandon

Thursday, 1 May 2014

Creating Asynchronous Thread in Global.asax in MVC

Hi guys,

I was facing a problem of creating asynchronous thread in Global.asax in MVC. I was able to create a thread which runs asynchrounsly without affecting the application. Here is how how i did it in global.asax.cs file. It also requires two namespaces 1. System.Threading 2. System.Threading.Tasks, Please do add them.

Step 1: Create a async Task, here in this example its MyThread.

private async Task<int> MyThread()
        {
            while (true)
            {
                string result = await Operations();
                await Task.Delay(5000);
            }
            return 1;
        }

Step 2: Create another async Task performing all the operations.

public async Task<String> Operations()
        {
            return "Hello";
        }
Step 3: Inside Application_Start call the thread.

protected async void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            AllSync();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }

Thanks
Ritesh Tandon

Monday, 21 April 2014

Creating Dependent DropDownList in MVC without jQuery.



Hi Guys,

I was given a task to generate dependent values in DropDownList without using jQuery. However this approach is not recommended but incase you still want to generate the dependent dropdownlist values based upon the parent dropdownlist value, Here are the steps to do so.

In my example i am using an example of Category, SubCategory and Product. Based on the category dropdown, subcategory dropdown list is generated and the product is then saved based on the category and subcategory values. In this example i have taken both category and subcategory reference in product table, However it can be done by taking only reference of subcategory table.

Step 1: Generate models
public class Category
    {
        [Key]
        public virtual int CategoryId { get; set; }
        public virtual string CategoryName { get; set; }
        public List<SubCategory> SubCategories { get; set; }
        public List<Product> Products { get; set; }
    }

Wednesday, 16 April 2014

How to get client's MAC Address from browser


Hi Guys,

I was having problem of finding out MAC address from browser. I finally achieved the same by using help from a blog and jQuery. The current code is tested on local LAN and it gives the MAC address based on the local LAN ip address.

Here is how i achieved it


Monday, 24 March 2014

Create In Browser Compiler For C#,Java,C,C++,Python, Ruby and many more using CodeMirror and IDEOne

Hi Folks!

I was given a task to create a website which can compile the code, the code can be c#,java,c,c++,ruby,python and other languages. I found a very good API(IDEONE), really simple to implement and gives fast result. I also used codemirror, which is a great code editor for different languages and provides real time environment like keyword recognition.

I built the same in asp.net, Please follow the steps.

Tuesday, 18 March 2014

MongoDB With ASP.NET

Hi Guys,

Today i am going tell you how to use MongoDB with ASP.NET

1. Create reference of MongoDB in c#

a. Download MongoDb from http://www.mongodb.org/downloads
b. Extract the zip file into c:\mongodb folder
c. Create another folder in c: drive with name "data"
d. Inside "data" folder create a new folder with name "db".
e. go to command prompt and execute the file c:\mongodb\mongod, this will run mongodb service.
f. run another command prompt window and execute c:\mongodb\mongo
g. Some commands
    i. show dbs (To show all the databases)
    ii. use [dbname] (to switch to the mentioned database) , This also creates a new database incase its not there when a collection(table) is created.
    iii. db.users.insert({name:"test",age:"32",department:"Computer"});
   The above command will create a table "users" in the database ([dbname]) name provided by the user.
    iv. db.users.findAll()
   The above command will show all the records in users table.

Wednesday, 5 March 2014

How To Pass List<> Into Web API WebMethod

Hi,

I was struggling with passing List<> type parameter in Web API webmethod. Here is how i was able to resovle it.

1. Here is my model class

public class Users
    {
        [Key]
        public int UserId { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

2. public List<Users> TestUsers([FromBody]List<Users> users)
        {
            try
            {
                return users;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

3. Here is my json which was passed using curl command, Here is the complete command

curl -H "Content-Type: application/json" -H "Accept: application/json" -X POST -d "[{\"Email\":\"test@test.com\",\"FirstName\":\"Ritesh\",\"LastName\":\"Tandon\",\"UserType\":\"Normal\"},{\"Email\":\"test12@test.com\",\"FirstName\":\"Vedansh\",\"LastName\":\"Tandon\",\"UserType\":\"FB\"}]" "http://localhost:3760/api/Users/TestUsers"

This is how i was able to pass List<> type object in Web API. You can also use HttpClient class for passing json array.

Thanks
Ritesh

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.


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:...