Wednesday, 20 November 2013

JSON With Web Service AJAX Call In c# Asp.NET

here i have created on service and called that service with use of ajax function from javascript.

the service is returning list as json

data to ajax function as a result.

(i have just explain you a basic example, you can return what ever you want to return)

 

WebService1.asmx.cs File

This file is having service method

 
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Web.Script.Services;
using System.Runtime.Serialization;
using Newtonsoft.Json;     ///Add the reference of JSON.NET Dll for the json converter used in program



namespace TestJavascriptServices
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public String HelloWorld()
        {


            Hashtable ht = new Hashtable();
            ht.Add("me", "jayesh");
            ht.Add("you", "CPU");
            ht.Add("My", "Mind");
            ht.Add("Your", "Processor");
            ht.Add("And", "Blast");

            List<String> ls = new List<string>();
            ls.Add("Jayesh");
            ls.Add("Jayesh1");
            ls.Add("Jayesh2");
            ls.Add("Jayesh3");
            ls.Add("Jayesh4");
            Test t = new Test();

            t.setData("me", "jayesh");
            
            //return "{\"me\":\"Hello this is jayesh\",\"u\":\"hsdh\",\"t\":\"dhdsfh\",\"s\":\"dsfhsdjh\"}";
            return JsonConvert.SerializeObject(t.getData());
            //return JsonConvert.SerializeObject(ls);
            //return JsonConvert.SerializeObject(ht);
            //return JsonConvert.SerializeObject(t);


        }
    }

    public class Test {
        public string Name;
        public string salary;

        public void setData(string n,string s)
        {
            this.Name = n;
            this.salary = s;
        }

        public Test getData() {
            return this; 
        }
      
    }

}


TestWebServiceHello.js

This file is having ajax functions which will call service 



var test;
function pageLoad() 
{
    test = new TestJavascriptServices.WebService1();
    test.set_defaultSucceededCallback(SucceededCallback);
    test.set_defaultFailedCallback(FailedCallback);
}


function SucceededCallback(result) {
    var RsltElem = document.getElementById("Results");

    var dd = $.parseJSON(result);
    alert(dd);
    RsltElem.innerHTML = dd.me;
}

function calll() {
alert("here");
    var greetings = test.HelloWorld();

}

function FailedCallback(error, userContext, methodName) {
    if (error !== null) {
        var RsltElem = document.getElementById("Results");

        RsltElem.innerHTML = "An error occurred: " +
            error.get_message();
    }
}

if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

Default.aspx

This file is having html inputs

 

 
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="TestJavascriptServices._Default" %>




<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js" ></script>
<asp:ScriptManager runat="server" ID="scriptManager">
                <Services>
                    <asp:ServiceReference path="~/WebService1.asmx" />
                </Services>
                <Scripts>
                    <asp:ScriptReference Path="~/TestWebServiceHello.js" />
                </Scripts>
            </asp:ScriptManager>

    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">www.asp.net</a>.
    </p>
    <p>
        You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&amp;clcid=0x409"
            title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
    </p>
    <span id="Results"></span>

    <input type="button" id="btn" onclick="calll();return false;" value="Click me" />






Download   
Newtonsoft plugin from here and add the reference to the project file

http://james.newtonking.com/json


Tuesday, 22 October 2013

Like button of facebook using javascript SDK

Facebook Like Button implementation code 



<div id="fb-root"></div>
<script>
(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id))return;
  js = d.createElement(s);
  js.id = id;
  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=your_API_id";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
//like button
<div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-width="16" data-height="16" data-colorscheme="light" data-layout="standard" data-action="like" data-show-faces="true" data-send="false">
</div>

Post on Facebook using javascript SDK


Post On facebook using javascript SDK

below id the code to create comment box on you page to post the comment on facebook page just you need to put your page facebook pageid/appid where you want to post the comment.

<script type=&quot;syntaxhighlighter&quot; class=&quot;brush: csharp&quot;>
<![CDATA[
function postOnFB()
{
      window.fbAsyncInit = function() {
   FB.init({
   // window.location.reload();console.log(response);    FB.getLoginStatus(function(response) {      appId: ' YOUR APP ID ',
   xfbml: true,
   status: true,
   cookie: true,
   oauth: true,
    channelUrl : 'CHANNEL URL / REDIRACT URL', // Channel File
});


FB.Event.subscribe("auth.authResponseChange", function(response) {
    });
      if (response && response.status == 'connected') {   

           FB.api('/me', function(response) {
      });
   
        } else if (response.status === 'not_authorized') {
      } else {
      }
     
     });
  
 };

 (function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/all.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));
              

      FB.login(
                function(response) {
                    if (response.authResponse) {
                    var access_token = FB.getAuthResponse()['accessToken'];
                    console.log("token:==>");
                    console.log(access_token);
                    FB.api(
                    'me/photos',
                    'post', {
                    name:"My Post",
                    message: 'here is yor post message',
                    status: 'success',
                    access_token: access_token,
                    url:$("#myimage").attr("src");    /// yourimage url is here
                    },
                    function(response) {
                        if (!response || response.error) {
                        console.log(response);
                        alert('Error occured:' + response);
                        } else {
                        // document.getElementById('imguploadheader').innerHTML="Status";
                        alert(Sucessfully posted);
                        }
                    });
                    } else {
                    errordisplay();
                    $("#appendtext").html(
                    "User cancelled login or did not fully authorize.");
                    $("#uploadingpregress")
                    .css("display","none");
                    successfullyupload();

                    }
                }, {
                scope: 'user_photos,photo_upload,publish_stream,offline_access'
          });
}
]]></script>

Facebook login using javascript SDK

 FACEBOOK Login Example

index.html  /// 

<html><body>
<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
  FB.init({
      appId: '490986011016528', // App ID
      channelUrl: 'http://localhost:8000/', // Channel File
      status: true, // check login status
      cookie: true, // enable cookies to allow the server to access the session
      xfbml: true  // parse XFBML
  });
        
FB.Event.subscribe('auth.authResponseChange', function(response) 
{
   if (response.status === 'connected') 
   {
   document.getElementById("message").innerHTML +=  "<br>Connected to Facebook";
   //SUCCESS
       }  
else if (response.status === 'not_authorized') 
{
     document.getElementById("message").innerHTML +=  "<br>Failed to Connect";
//FAILED
        } 
else 
  { document.getElementById("message").innerHTML +=  "<br>Logged Out";
       //UNKNOWN ERROR
      }
});
    };
    
    function Login(){
FB.login(function(response) {
   if (response.authResponse) 
{
     getUserInfo();
    }
 else 
{
         console.log('User cancelled login or did not fully authorize.');
    }
 },
   {scope: 'email,user_photos,user_videos'});
}
  function getUserInfo() {
    FB.api('/me', function(response) {
  var str="<b>Name</b> : "+response.name+"<br>";
     str +="<b>Link: </b>"+response.link+"<br>";
     str +="<b>Username:</b> "+response.username+"<br>";
     str +="<b>id: </b>"+response.id+"<br>";
     str +="<b>Email:</b> "+response.email+"<br>";
     str +="<input type='button' value='Get Photo' onclick='getPhoto();'/>";
     str +="<input type='button' value='Logout' onclick='Logout();'/>";
     document.getElementById("status").innerHTML=str;         
    });
    }
function getPhoto()
{
  FB.api('/me/picture?type=normal', function(response) {
  var str="<br/><b>Pic</b> : <img src='"+response.data.url+"'/>";
     document.getElementById("status").innerHTML+=str;
    });
}
function Logout()
{
FB.logout(function(){document.location.reload();});
}
  // Load the SDK asynchronously
  (function(d){
     var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement('script'); js.id = id; js.async = true;
     js.src = "//connect.facebook.net/en_US/all.js";
     ref.parentNode.insertBefore(js, ref);
   }(document));
</script>
<div align="center">
<h2>Facebook OAuth Javascript Demo</h2>
<div id="status">
 Click on Below Image to start the demo: <br/>
<img src="http://hayageek.com/examples/oauth/facebook/oauth-javascript/LoginWithFacebook.png" style="cursor:pointer;" onclick="Login()"/>
</div>
<br/><br/><br/><br/><br/>
<div id="message">
Logs:<br/>
</div>
</div>
</body>
</html>
 
channel.html  /// 
 
<script src="//connect.facebook.net/en_US/all.js"></script>

 


Change a port of the jetty server maven plugin

Below code you need to put inside plugins tag of pom.xml file. which will create a jetty server using maven jetty plugin and will also allow you specify port number instated of using default(8080). 

pom.xml


<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>${jetty.version}</version>
<configuration>
<scanIntervalSeconds>3</scanIntervalSeconds>
<contextPath>/</contextPath>
<connectors>
<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
<port>8090</port>   //put your new port here
<maxIdleTime>60000</maxIdleTime>
</connector>
</connectors>
</configuration>
</plugin>
This code will change the port of your jetty server to 8090 from default port 8080.

please follow the blog if you like it.
Thanks

Tuesday, 15 October 2013

Spring Security Login Using Hibernate Example

Spring Security with Authentication


First you need to create table in following structure

create table user_info( 
                       user_name varchar(50),
                       passwd varchar(200),
                       enabled int(1),
                       authority varchar(50) 
                     );

insert into user_info values('jayesh','password',1,'ROLE_USER');

you need to create a file named Spring-security.xml if not exists.
if you have the file than use below code to set up the spring log in configuration.
Spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
 xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/security
 http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http pattern="/resources/**" security="none" />

 <http auto-config="true" use-expressions="true">
  <intercept-url pattern="/login*" access="permitAll" /> 
  <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
  
 <form-login login-page="/login" authentication-failure-url="/loginfailed" default-target-url="/Home/"  />
  <logout logout-url="/logout" logout-success-url="/login"  invalidate-session="true"  />
  <session-management >
  <concurrency-control max-sessions="1" expired-url="/loginExp" />
  </session-management>
 </http>
 
 <authentication-manager>
 
  <authentication-provider>
        <jdbc-user-service data-source-ref="dataSource"

        users-by-username-query="
        select user_name,passwd,enabled
        from user_info where user_name=?"

        authorities-by-username-query="
        select user_name,authority from user_info         
        where user_name =?  " />
  </authentication-provider> 
  
 </authentication-manager>

 
</beans:beans>
 
 
login.jsp
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<html>
<head>
<title>Spring 3 MVC  - Spring Authentication Example</title>
</head>
<body>  
 <form action="j_spring_security_check" method="POST"> 
 
  UserName: <input type="text" name="j_username" /> 
 
  Password: <input type="password" name="j_password" />
  
  <input type="submit" value="Login" />
 
 </form>
</body>
</html>
 

Thursday, 3 October 2013

Simple Login With Spring Security

Spring Security

here i have used form-login to configure spring security login.

if you want to restrict user to access all url and want to allow specific url portion then you can use do that by <intercept-url />

and using form-login we can control the user authentication filer or success.and we can display our custom login form.

when you are using <http-basic /> then web browser is displaying a log in dialog for user authentication.

To enable HTTP basic, just change “form-login” to “http-basic” tag.
Spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
                       xmlns:beans="http://www.springframework.org/schema/beans" 
                       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                       xsi:schemaLocation="http://www.springframework.org/schema/beans
                       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                       http://www.springframework.org/schema/security
                       http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
 
 
 <http>
 <intercept-url pattern="/welcome*" access="ROLE_USER" />
<form-login login-page="/login" default-target-url="/welcome"
   authentication-failure-url="/loginfailed" />
<logout logout-success-url="/logout" />
 </http>
 <authentication-manager>
    <authentication-provider>
        <user-service>
  <user name="jayesh" password="jayesh" authorities="ROLE_USER" />
        </user-service>
    </authentication-provider>
 </authentication-manager>
 
</beans:beans> 
login.jsp
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<html>
<head>
<title>Spring 3 MVC Series - Contact Manager</title>
</head>
<body>
<form action="j_spring_security_check" method="POST">

UserName: <input type="text" name="j_username" />
Password:  <input type="password" name="j_password" />

<input type="submit" value="Login" />
</form>
</body>
</html>

HttpSessionListner implementation with service calls in spring

Here’s a simple “HttpSessionListener” example to do the login and logout time entry in the database.using service 

Java Source

package com.jayesh;
 
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class MySessionListener implements HttpSessionListener {
 
 private MyDbService myDbService;
  public static int getTotalActiveSession(){
 return totalActiveSessions;
  }
 
  @Override
  public void sessionCreated(HttpSessionEvent arg0) {
           ApplicationContext ctx = 
                WebApplicationContextUtils.
                      getWebApplicationContext(session.getServletContext());
 
          MyDbService  myDbService= 
                      (MyDbService) ctx.getBean("myDbServiceBeaniId");               
   myDbService.addLoginTime();                                                                                                                  System.out.println("session time is inserted in database");                   
  }
 
  @Override
  public void sessionDestroyed(HttpSessionEvent arg0) {
                                MyDbService  myDbService= 
                      (MyDbService) ctx.getBean("myDbServiceBeaniId"); 
                                System.out.println("sessionDestroyed and logout time inserted");
  } 
}

web.xml


<web-app ...>
       <listener>
              <listener-class>com.jayesh.SessionCounterListener</listener-class>
       </listener>
</web-app>
 
 
spring-secutity.xml
 
<beans:bean id="myBdServiceBeanId" class="com.jayesh.service.MyDbServices"></beans:bean>

How it work?

- If a new session is created , e.g “request.getSession();” , the listener’s sessionCreated() will be executed.
- If a session is destroyed, e.g session’s timeout or “session.invalidate()”, the listener’s sessionDestroyed() will be executed.
  HttpSession session = request.getSession(); //sessionCreated() is executed
  session.setAttribute("url", "mydomain.com"); 
  session.invalidate();  //sessionDestroyed() is executed

Saturday, 10 August 2013

Password Encryption

Encrypt Password in MD5,SHA,SHA-256 Format

if you want to encrypt password in different different format just you need to change accordingly in MessageDigest.getInstance('here is your Encryption Algorithm')


public String encryptPassword(){
MessageDigest md = MessageDigest.getInstance("MD5");
FileOutputStream fio = new FileOutputStream("c:\\loging.log");
fio.write(password.getBytes());
fio.close();
FileInputStream fis = new FileInputStream("c:\\loging.log");
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
}
;
byte[] mdbytes = md.digest();
// convert the byte to hex format method 1
StringBuffer sb = new StringBuffer();
for (int i = 0; i < mdbytes.length; i++) {
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16)
.substring(1));
}
fio.close();
System.out.println(sb.toString());
return sb.toString();
}