Saturday 31 January 2015

How to create duplicate table in different schema name in Asp.net (create new table in different schema)

Process I am writting
1. First  open a wordpad File.
2.Next write a table which in your database on that word file.
       Example
     CREATE TABLE [dbo].[linku] (
    [Id]               INT          IDENTITY (1, 1) NOT NULL,
    [Pid]              INT          NULL,
    [Achievement_Name] VARCHAR (50) NULL,
    [Year]             VARCHAR (4)  NULL,
    [IsDeleted]        BIT          NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC),
    FOREIGN KEY ([Pid]) REFERENCES [dbo].[brahmananda_profile] ([Id])
    )


CREATE TABLE [dbo].[linku_education] (
    [Id]                 INT             IDENTITY (1, 1) NOT NULL,
    [Pid]                INT             NULL,
    [Education]          VARCHAR (60)    NULL,
    [BoardUniversity]    VARCHAR (70)    NULL,
    [Institution]        VARCHAR (60)    NULL,
    [Year_Of_Passing]    VARCHAR (4)     NULL,
    [Percentage_Secured] DECIMAL (18, 2) NULL,
    [IsDeleted]          BIT             NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC),
    FOREIGN KEY ([Pid]) REFERENCES [dbo].[brahmananda_profile] ([Id])
)
  comment:  you can add so much table you want to add

3. save this Wordfile on the name of table.sql.
4. Next copy that word file and paste on .Net Solution on App_Data folder.
5.Next add a web page on the .net solution.
6. and add a design  .

   example in design Source page.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Schema.aspx.cs" Inherits="TestSwash.Schema" %>

<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <telerik:RadScriptManager ID="RadScriptManager1" runat="server"></telerik:RadScriptManager>
    <div>
        <telerik:RadTextBox ID="RadTextBox1" runat="server"></telerik:RadTextBox><telerik:RadButton ID="RadButton1" runat="server" Text="Schema" OnClick="RadButton1_Click"></telerik:RadButton>
    </div>
    </form>
</body>
</html>

7. Next go to page behind C# file code.

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Text;

namespace TestSatya
{
    public partial class Schema : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void RadButton1_Click(object sender, EventArgs e)
        {
            string conn_str = WebConfigurationManager.ConnectionStrings["test"].ConnectionString;
            //Response.Write(conn);
            string sql_path = Path.Combine(Server.MapPath("~/App_Data"), "table.sql");
            string script = File.ReadAllText(sql_path);
          //  Response.Write(script);
            SqlConnection con = new SqlConnection(conn_str);
            script=script.Replace("[dbo]","["+RadTextBox1.Text+"]");
           // string sql_exe = "CREATE SCHEMA  " + RadTextBox1.Text + " " + script;

            //SqlCommand cmd=new SqlCommand()
            //Response.Write(sql_exe);
            con.Open();
          //  SqlCommand cmd = new SqlCommand("SELECT name FROM sys.tables WHERE  OBJECT_SCHEMA_NAME(object_id(name)) ='DBO'", con);
          //  //SqlCommand cmd = new SqlCommand(sql_exe, con);
          //  SqlDataReader rd = cmd.ExecuteReader();
          // // StringBuilder bld = new StringBuilder("");

          //  while(rd.Read())
          //  {
          //      bld.Append(rd["name"].ToString()+",");
          //      //rd.NextResult();
          //      //---------------------
          //      if (rd["name"].ToString().Equals("brahmananda_achievement") || rd["name"].ToString().Equals("brahmananda_education") || rd["name"].ToString().Equals("brahmananda_profile"))
          //      {
          //          script = script.Replace(rd["name"].ToString(), RadTextBox1.Text + "_" + rd["name"].ToString());
          //      }
          //      //----------------------
          //  }
          ////  cmd.ExecuteNonQuery();
          ////  Response.Write(bld.ToString());
          //  rd.Close();
            string sql_exe = "CREATE SCHEMA  " + RadTextBox1.Text + " " + script;
          //  Response.Write(sql_exe);
            SqlCommand cmd = new SqlCommand(sql_exe, con);
            //cmd.CommandText = sql_exe;
            cmd.ExecuteNonQuery();
            con.Close();
            Response.Write("Schema created");
        }
    }
}

=======================================================

After that you see.
  
Let your database name is Sairam and table name is dbo.linku
i want to chane the schema means where dbo on that palace i want to change user.linku
There fore on runtime i input on the text box user  and after save .
Now you see in your database your schema will be change.


======================================


 Thanks
  Satyabrata behera




  

Tuesday 6 January 2015

How to Create Facebook Login In Asp.Net using JQuery

How to create App Id In Facebook
===========================================================



---------------------For Login Button and show facebook Login Screen---------------------------
<script src="../js/jquery-latest.js"></script>

     <script>
         window.fbAsyncInit = function () {
             FB.init({
                 appId: 'Your App Id',
                 xfbml: true,
                 version: 'v2.2'
             });
         };

         (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/sdk.js";
             fjs.parentNode.insertBefore(js, fjs);
         }(document, 'script', 'facebook-jssdk'));
</script>
    <script type="text/javascript">
        function loginByFacebook() {
            debugger;
            FB.login(function (response) {
                if (response.authResponse) {
                    FacebookLoggedIn(response);
                } else {
                    console.log('User cancelled login or did not fully authorize.');
                }
            }, { scope: 'user_birthday,user_about_me,user_hometown,user_location,email,publish_stream' });
        }

        function FacebookLoggedIn(response) {
            debugger;
            $.ajax({

                url: "Login.aspx/FetchUserList",
                data: "{ 'access_token': '" + response.authResponse.accessToken + "' }",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataFilter: function (data) { return data; },
                success: function (data) {
                    $.each(data.d, function (i, item) {

                        if (item.Regstatus == "Registered") {
                            var loc = '/FMSDashboard.aspx';
                            window.location.href = loc;
                        }

                        else {
                            var loc = 'FacebookRegistraion.aspx';

                            if (loc.indexOf('?') > -1)
                                window.location = loc + '&authprv=facebook&access_token=' + response.authResponse.accessToken;
                            else
                                window.location = loc + '?authprv=facebook&access_token=' + response.authResponse.accessToken;
                        }

                    });
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(textStatus);
                }
            });


        }
    </script>
------------------------------------LoginIn Design---------------------------------------------------------------------
 <a>  <input id="btnFbLogin" type="button" value="Facebook Login" class="btn btn-info pull-left" onclick="loginByFacebook();" /></a>

--------------------In Page Behind Write This Code Means C# Page----------------------------------------
  private static string GetFacebookUserJSON(string access_token)
    {
        string url = string.Format("https://graph.facebook.com/me?access_token={0}&fields=email,name,first_name,last_name,link,gender", access_token);

        WebClient wc = new WebClient();
        Stream data = wc.OpenRead(url);
        StreamReader reader = new StreamReader(data);
        string s = reader.ReadToEnd();
        data.Close();
        reader.Close();

        return s;
    }
    [WebMethod]
    public static List<FacebookUser> FetchUserList(string access_token)
    {
        //CloudStorageAccount account = new CloudStorageAccount(
        //            new StorageCredentials(EnumStorageCredentialsAccount1.StorageName, EnumStorageCredentialsAccount1.StorageKey), true);
        //CloudTableClient tableClient = account.CreateCloudTableClient();
        //CloudTable table = tableClient.GetTableReference("users");
        //table.CreateIfNotExistsAsync();
        //TableQuery<UserEntity> query = new TableQuery<UserEntity>();
        //List<UserEntity> lst = table.ExecuteQuery(query).ToList();

        List<FacebookUser> _AppUser = new List<FacebookUser>();
        string json = GetFacebookUserJSON(access_token);
        //and Deserialize the JSON response
        JavaScriptSerializer js = new JavaScriptSerializer();
        FacebookUser oUser = js.Deserialize<FacebookUser>(json);


        //if (lst.Where(x => x.PartitionKey == oUser.email).ToList().Count > 0)
        //{
        //    HttpContext.Current.Session["uname"] = oUser.email;
        //    oUser.Regstatus = "Registered";
        //}
        _AppUser.Add(oUser);
        return _AppUser;
    }
    public class FacebookUser
    {
        public long id
        { get; set; }

        public string email
        { get; set; }

        public string name
        { get; set; }

        public string first_name
        { get; set; }

        public string last_name
        { get; set; }

        public string gender
        { get; set; }

        public string link
        { get; set; }

        public DateTime updated_time
        { get; set; }

        public DateTime birthday
        { get; set; }

        public string locale
        { get; set; }

        public string picture
        { get; set; }

        public FacebookLocation location
        { get; set; }

        public string MobileNo
        { get; set; }

        public string Regstatus
        { get; set; }

    }

    public class FacebookLocation
    {
        public string id
        { get; set; }

        public string name
        { get; set; }
    }

    public class FBRegistrationDetails
    {
        public long id
        { get; set; }

        public string email
        { get; set; }

        public string name
        { get; set; }

        public string first_name
        { get; set; }

        public string last_name
        { get; set; }

        public string gender
        { get; set; }

        public string OrgName
        { get; set; }

        public string OrgUrl
        { get; set; }
        public string OrgDomain
        { get; set; }

        public string MobileNo
        { get; set; }

        public string ProfilePicUrl
        { get; set; }

    }
=========================================================
When Login Successfull At that time login dat retrive from Facebook Database
============================================================
In View Page Design  And Code and the page name is FacebookRegistraion
------------------------------------------------------
    <div style="margin-left: 15px; margin-right: 15px">

                                    <div class="form-group">
                                          <input type="hidden" id="hdnfbid" />
                                        <input type="text" class="form-control" id="txtFirstname" placeholder="First name"/>
                                    </div>
                                    <div class="form-group">
                           
                                        <input type="text" class="form-control" id="txtLastname" placeholder="First name"/>
                                    </div>
                                    <div class="form-group">
                                         <input type="text" class="form-control" id="txtEmail" placeholder="Email address"/>
                                       
                                    </div>

                                    <div class="form-group">
                                       <input type="text" class="form-control" id="txtOrgName" placeholder="Organization Name"/>
                                    </div>

                                    <div class="form-group">
                                         <input type="text" class="form-control" id="txtOrgUrl" placeholder="Organization Url"/>
                                    </div>


                                    <div class="form-group">
                                   
                                        <select id="ddlgender" class="form-control">
                                            <option value="0" selected="" disabled="">Gender</option>
                                            <option value="1">Male</option>
                                            <option value="2">Female</option>
                                            <option value="3">Other</option>
                                        </select>
                                                 <i></i>

                                    </div>
                                    <div class="form-group">
                                         <input type="text" class="form-control" id="txtMobile" placeholder="Mobile No"/>
                                    </div>

                                    <div class="form-group">
                                        <div class="row" style="margin-left: 115px;">
                                             <img id="fbimgid" src="#" />
                                </div>
                                    </div>

                                    <div class="form-group">
                                        <div class="checkbox">
                                            <label>
                                             <input type="checkbox" id="chkSelect" name="checkbox"><i></i>I agree to the Terms of Service</label>
                                     
                                        </div>
                                    </div>

                                    <div class="form-group">
                                          <button type="button" class="button" id="btnSave">Submit</button>
                                    </div>
                         
                    </div>
=================================================================
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            var access_token = GetParameterValues('access_token');
            //alert(name);
            var fbid = 0;
            $.ajax({
                //url: "FB_Registration.aspx/FetchUserList",
                url: "Login.aspx/FetchUserList",
                data: "{ 'access_token': '" + access_token + "' }",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataFilter: function (data) { return data; },
                success: function (data) {
                    $.each(data.d, function (i, item) {

                        if (item.Regstatus == "Registered") {
                            var loc = '/FMSDashboard.aspx';
                            window.location.href = loc;
                        }

                        else {
                            $("#txtFirstname").val(item.first_name);
                            $("#txtLastname").val(item.last_name);
                            $("#txtEmail").val(item.email);
                            $("#txtMobile").val('');
                            $("hdnfbid").val(item.id);

                            $('#txtFirstname').attr("disabled", "disabled");
                            $('#txtLastname').attr("disabled", "disabled");
                            $('#txtEmail').attr("disabled", "disabled");
                            $('#ddlgender').attr("disabled", "disabled");
                            var genderid = 0;
                            if (item.gender == "male") {
                                genderid = 1;
                            }
                            else if (item.gender == "female") {
                                genderid = 2;
                            }
                            $("#ddlgender").val(genderid);
                            //alert( item.id);
                            $("#fbimgid")[0].src = "http://graph.facebook.com/" + item.id + "/picture?height=110&type=normal&width=110";
                        }

                    });
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(textStatus);
                }
            });


            $("#btnSave").click(function () {
                // alert('click');
                var isValidated = true;
                $("#regErrors").html('');
                var fbid = $("hdnfbid").val();
                var txtOrgDomain = $("#txtOrgDomain").val();
                var txtFirstname = $("#txtFirstname").val();
                var txtLastname = $("#txtLastname").val();
                var txtEmail = $("#txtEmail").val();
                var txtOrgName = $("#txtOrgName").val();
                var txtOrgUrl = $("#txtOrgUrl").val();
                var txtMobile = $("#txtMobile").val();
                var ddlgender = $("#ddlgender").val();
                var ProfilePicUrl = $("#fbimgid").attr('src');
                var isChecked = $('#chkSelect:checked').val() ? true : false;
                var name = txtFirstname + ' ' + txtLastname;
                // alert(isChecked);
                if (isChecked) {
                    if (txtOrgName == "") {
                        $('#txtOrgName').focus();
                        isValidated &= false;

                    }
                    else if (txtOrgUrl == "") {
                        $("#txtOrgUrl").focus();
                        isValidated &= false;

                    }
                    else if (txtMobile == "") {
                        $("#txtMobile").focus();
                        isValidated &= false;

                    }

                    if (isValidated == true) {

                        var gender = "";
                        if (ddlgender == 1) {
                            gender = "Male";
                        }
                        else if (ddlgender == 2) {
                            gender = "Female";
                        }

                        var user = {};
                        //var str = [{ id: fbid, email: txtEmail, name: name, first_name: txtFirstname, last_name: txtLastname, gender: ddlgender, OrgName: txtOrgName, OrgUrl: txtOrgUrl, OrgDomain: txtOrgDomain, MobileNo: txtMobile, ProfilePicUrl: ProfilePicUrl }];
                        user.id = fbid;
                        user.email = txtEmail;
                        user.name = name;
                        user.first_name = txtFirstname;
                        user.last_name = txtLastname;
                        user.gender = gender;
                        user.OrgName = txtOrgName;
                        user.OrgUrl = txtOrgUrl;
                        user.OrgDomain = txtOrgUrl;
                        user.MobileNo = txtMobile;
                        user.ProfilePicUrl = ProfilePicUrl;
                        $.ajax({
                            type: "POST",
                            url: "FB_Registration.aspx/InsertFBDetails",
                            data: '{item: ' + JSON.stringify(user) + '}',
                            dataType: "json",
                            contentType: "application/json; charset=utf-8",
                            async: false,
                            success: function (data) {
                                //alert(data);
                                // alert(data.d);
                                // alhttp://www.c-sharpcorner.com/UploadFile/c4cfca/how-to-save-data-into-database-using-jquery-and-json-in-asp/Images/Result.jpgert(data);
                                if (data.d == "Saved") {
                                    // alert('saved');
                                    var loc = '/FMSDashboard.aspx';
                                    // if (loc.indexOf('?') > -1)
                                    //window.location = loc + '&authprv=facebook&access_token=' + response.authResponse.accessToken;
                                    window.location.href = loc;
                                }
                                else {
                                    alert('' + data + '');
                                }
                            }
                        });
                    }

                }
                else {
                    alert('Please check I agree to the Terms of Service.');
                }
            });



        });

        function GetParameterValues(param) {
            var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < url.length; i++) {
                var urlparam = url[i].split('=');
                if (urlparam[0] == param) {
                    return urlparam[1];
                }
            }
        }
    </script>

When Textbox text is blank at that time textbox border is red using Jquery

<script src="js/jquery.min.js"></script>

 <script type="text/javascript">
        $(function () {
            $("input[type='text'],Select").bind("keypress blur change", function () {
                if ($(this).val().length > 0) {
                    $(this).css("border-color", "gray");
                }
                else {
                    $(this).css("border-color", "red");
                }
            });

            $("#<%=Btnsave.ClientID%>").click(function (e) {
                if ($("#<%=txtfirstname.ClientID%>").val().length == 0) {
                    $("#<%=txtfirstname.ClientID%>").css("border-color", "red");
                    e.preventDefault();
                }
                else {
                    $("#<%=txtfirstname.ClientID%>").css("border-color", "gray");
                }
                if ($("#<%=txtlastname.ClientID%>").val().length == 0) {
                    $("#<%=txtlastname.ClientID%>").css("border-color", "red");
                    e.preventDefault();
                }
                else {
                    $("#<%=txtlastname.ClientID%>").css("border-color", "gray");
                }
                if ($("#<%=txtCompany.ClientID%>").val().length == 0) {
                    $("#<%=txtCompany.ClientID%>").css("border-color", "red");
                    e.preventDefault();
                }
                else {
                    $("#<%=txtCompany.ClientID%>").css("border-color", "gray");
                }
                if ($("#<%=txtEmailAddress.ClientID%>").val() == 0) {
                    $("#<%=txtEmailAddress.ClientID%>").css("border-color", "red");
                    e.preventDefault();
                }
                else {
                    $("#<%=txtEmailAddress.ClientID%>").css("border-color", "gray");
                }

            });

        });

    </script>

Hot to Send mail and reply mail in Asp.net


using System.Net.Mail;
using System.Text;

 public string SendFromMail, SendToMail, Body, subject;
public void SendMail(string SendToMail, string SendFromMail, string subject, string Body)
    {
        try
        {
            MailAddress SendFrom = new MailAddress(SendFromMail);
            MailAddress SendTo = new MailAddress(SendToMail);
            MailMessage MyMessage = new MailMessage(SendFrom, SendTo);

       
            MyMessage.Subject = subject;
            MyMessage.Body = Body;
            MyMessage.IsBodyHtml = true;
            string mSMTPServer = "smtpout.secureserver.net";// ConfigurationSettings.AppSettings["smtpServer"].ToString();
            SmtpClient SmtpMail = new SmtpClient(mSMTPServer);
            System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential("hr@companyname.com ", "Password");//that mail where i send the mail
            SmtpMail.UseDefaultCredentials = false;
            SmtpMail.Credentials = SMTPUserInfo;
            SmtpMail.Send(MyMessage);
        }
        catch (Exception ex)
        {
            ex.ToString();
        }
    }

    void SendMailToUser()
    {
        SendFromMail = "hr@companyname.com";
        SendToMail = "hr@companyname.com";
     
     
        subject = "Enquiry";
        Body += "Dear Support," + "<br /><br />There was an enquiry from companyname.com. Following are the details:";
        Body += "<br /><br /> Name:&nbsp;&nbsp;" + txtfullname.Text;
        Body += "<br />Email Id:&nbsp;&nbsp;" + txtemailAddress.Text;
        Body += "<br />Mobile No:&nbsp;&nbsp;" + txtMobileno.Text;
        Body += "<br />Address:&nbsp;&nbsp;" + txtAddress.Text;
        Body += "<br />City:&nbsp;&nbsp;" + txtcity.Text;
        Body += "<br />Message:&nbsp;&nbsp;" + txttotalexperience.Text;
        Body += "<br /><br /><br />Regards";
        Body += "<br />System Admin";
        Body += "<br />companyname.com";

        //Body += "Name: <br /><br />Please use the following key to register your app upon the first run of the application:<br /><br /><div align=\"center\">";

        SendMail(SendFromMail, SendToMail, subject, Body);

    }

    void SetTheReplyToHeader()
    {
        StringBuilder builder = new StringBuilder();
        builder.Append("Dear");
        builder.Append(" ");
        builder.Append(txtfullname.Text).AppendLine().AppendLine();
        builder.Append("Thanks for your query. A HR executive will shortly contact you soon.").AppendLine().AppendLine();
        builder.Append("Regards").AppendLine();
        builder.Append("Support Team").AppendLine();
        builder.Append("xxxxxxxxxxxxxx").AppendLine();
        builder.Append("xxxxxxxxxxxxxx
        builder.Append("xxxxxxxxxxx
        builder.Append("xxxxxxxxxxxxxxxxx).AppendLine();

        MailMessage mail = new MailMessage();
        SmtpClient SmtpServers = new SmtpClient("smtpout.secureserver.net"); //Mail Server Name
        mail.From = new MailAddress("hr@companyname.us");
        mail.To.Add(txtemailAddress.Text);//Who save the data
        mail.Subject = "companyname";
        mail.Body += builder.ToString();
        SmtpServers.Port = 25;
        SmtpServers.UseDefaultCredentials = true;
        SmtpServers.Credentials = new System.Net.NetworkCredential("hr@companyname.com ", "Password");
        SmtpServers.Send(mail);
    }