Thursday 30 May 2013

Twitter Posting from Asp.net Website - Twitterizer Open Source Tutorial

Twitter Posting from Asp.net Website - Twitterizer Open Source Tutorial


Before started discussing about Twitter Programming.  Following is small description about Twitter.  "Twitter is a service for friends, family, and co–workers to communicate and stay connected through the exchange of quick, frequent answers to one simple question"  As Twitter is gaining more and more popularity, it is necessary for web master to put all the websites update on Twitter to attract more audience. 

This post will explain, How to post message from your asp.net website to Twitter.

To demonstrate this, I would be taking help of Open Source Project which easy, fast and efficient to use.  

Open Source Project for Twitter Programming in .Net : Twitterizer

Twitterizer is
.net project provides an easy to use, object-oriented interface to twitter's online API.  

Practical Example for Twitter Programming in .Net


Step2: Create New Asp.net Website. 

Step 3: Arrange the Web Controls as shown in Figure.
Step 4: Add Twitterizer Reference.
Right Click Website in Solution Explorer, and select "Add Reference" from Popup dialog.
Add the Twitterizer.Framework.dll which you have downloaded in Step1.

Step 5: Write Code.
Add Namespace: using Twitterizer.Framework;

Add following code on Shout button click event.
protected void btnShout_Click(object sender, EventArgs e)
{   
string TwitterUserName = "twitasp";
string TwitterPassword = "mypassword";
string TwitterMessage = txtShout.Text;

if (TwitterUserName != string.Empty && TwitterPassword != string.Empty)
{
try
{

Twitter twitter = new Twitter(TwitterUserName,TwitterPassword);

string TwitterMsg = txtShout.Text;
if (txtShout.Text.Length > 120)
{
TwitterMsg = TwitterMsg.Substring(0, 130) + "... For more update logon to DailyFreeCode.com";
}
else
{
TwitterMsg = TwitterMsg + "... For more update logon to DailyFreeCode.com";
}
twitter.Status.Update(TwitterMsg);
lblTwitMsg.Text = "Your have shout successfully on http://twitter.com/" + TwitterUserName;

}
catch (Exception ex)
{
Response.Write("<b>" + ex.Message + "</b><br>" + ex.StackTrace);
}
}
}

Lets Post one Message from Asp.net Website Developed.
Type your Message in Textbox and Press Shout button, you can then check your Twitter website to check whether update is applied or not.

Now Press "Shout on Twitter!" button

Now check the Twitter Website for Profile we have Shout on.
http://twitter.com/twitasp

Wednesday 29 May 2013

ASP.NET Authentication and Authorization


Authentication Authentication is the process of attaining identification credentials such as username and passwordfrom a user and validating those credentials against some authority.  If the credentials are valid, the entity that submitted the credentials is considered an authenticated identity. Once an identity has been authenticated, the authorization process determines whether that identity has access to a given resource.


Authorization : The purpose of authorization is to determine whether an identity should be granted the requested type of access to a given resource.

There are three types of Authentication.They are
1. Forms Authentication
2. Windows Authentication
3. Passport Authentication

Forms Authentication is cookie based, as ASP.NET places a cookie in the client machine in order to track the user. If the user requests a secure page and has not logged in, then ASP.NET redirects user to the login page. Once the user is authenticated, then user will be allowed to access the requested page. 

Windows Authentication can be used only in an intranet environment where the administrator has full control over the users in the network. 

Passport Authentication Passport authentication is a centralized authentication service that uses Microsoft's Passport Service to authenticate the users of an application. It allows the users to create a single sign-in name and password to access any site that has implemented the Passport single sign-in (SSI) service. 


In this example, we are showing how authentication and authorization works. We are taking 3 Roles ADMIN, USER and SECURE USER. When Admin logins he has permissions to access all the modules. When user logins he can access all modules except ADMIN module. And when the secure user logins he can access only the Secure module.

In this example we have taken one XML file (UserInformation.xml) for Users Information and Roles. This xml file works as the database file. And every Authenticate Requests Fires from the browser is from Global.asax file.
This is the best example of Authentication and Authorization.

Encrypt & Decrypt of Password in Asp.net

Encrypt & Decrypt of Password in Asp.net




In .aspx page:-

<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table style="" width="50%">
            <tr>
                <td colspan="2" style="font-family: 'Times New Roman', Times, serif; font-size: large;
                    font-weight: bold; text-decoration: underline; color: #800000">
                    Encryption and Decryption of Password.
                </td>
            </tr>
            <tr>
                <td align="right">
                    UserName :
                </td>
                <td>
                    <asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                        ControlToValidate="txtUsername" ErrorMessage="Enter User Name">*</asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td align="right">
                    Password :
                </td>
                <td>
                    <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
                        ControlToValidate="txtPassword" ErrorMessage="Enter Password">*</asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td align="right">
                    Email Id :
                </td>
                <td>
                    <asp:TextBox ID="txtEmailId" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td />
                <td>
                    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
                </td>
            </tr>
        </table>
    </div>
    </br></br>
    <table cellspacing="10" width="60%">
        <tr>
            <td align="center">
                Encrypted Password.
            </td>
        </tr>
        <tr>
            <td>
                <asp:GridView ID="gvUsers" runat="server" CellPadding="4" BackColor="White" BorderColor="#CC9966"
                    BorderStyle="None" BorderWidth="1px" Width="480px">
                    <RowStyle BackColor="White" ForeColor="#330099" />
                    <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
                    <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
                    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
                    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
                    <SortedAscendingCellStyle BackColor="#FEFCEB" />
                    <SortedAscendingHeaderStyle BackColor="#AF0101" />
                    <SortedDescendingCellStyle BackColor="#F6F0C0" />
                    <SortedDescendingHeaderStyle BackColor="#7E0000" />
                </asp:GridView>
            </td>
        </tr>
        <tr>
            <td align="center">
                Decrypted Password.
            </td>
        </tr>
        <tr>
            <td>
                <asp:GridView ID="gvdecryption" runat="server" BackColor="White" BorderColor="#CC9966"
                    BorderStyle="None" BorderWidth="1px" CellPadding="4"OnRowDataBound="gvdecryption_RowDataBound"
                    Width="480px">
                    <RowStyle BackColor="White" ForeColor="#330099" />
                    <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
                    <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
                    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
                    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
                    <SortedAscendingCellStyle BackColor="#FEFCEB" />
                    <SortedAscendingHeaderStyle BackColor="#AF0101" />
                    <SortedDescendingCellStyle BackColor="#F6F0C0" />
                    <SortedDescendingHeaderStyle BackColor="#7E0000" />
                </asp:GridView>
            </td>
        </tr>
    </table>
    </form>
</body>

In .aspx.Cs Page:-

SqlConnection ConnString = newSqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    DataSet Ds;
    SqlDataAdapter Da;
    String SqlString = "SELECT * FROM [UserTable]";

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridBindEncryptedData();
            GridBindDecryptedData();
        }
    }

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string StrPwd = Encryptdata(txtPassword.Text);
        ConnString.Open();
        SqlCommand SqlCmd = new SqlCommand("INSERT INTO [UserTable]([Username],[Password],[EmailId])VALUES('" + txtUsername.Text + "','" + StrPwd + "','" + txtEmailId.Text + "')", ConnString );
        SqlCmd.ExecuteNonQuery();
        ConnString.Close();
        GridBindEncryptedData();
        GridBindDecryptedData();
    }

    #region " G R I D V i e w  D I S P L A Y "
    //Binding Encrypted data To GridView1
    protected void GridBindEncryptedData()
    {
        ConnString.Open();
        SqlCommand SqlCmd = new SqlCommand(SqlString, ConnString);
        Da = new SqlDataAdapter(SqlCmd);
        Ds = new DataSet();
        Da.Fill(Ds);
        gvUsers.DataSource = Ds;
        gvUsers.DataBind();
        ConnString.Close();
    }
    //Binding Decrypted data To GridView2
    protected void GridBindDecryptedData()
    {
        ConnString .Open();
        SqlCommand SqlCmd = new SqlCommand(SqlString, ConnString);
        Da = new SqlDataAdapter(SqlCmd);
        Ds = new DataSet();
        Da.Fill(Ds);
        gvdecryption.DataSource = Ds;
        gvdecryption.DataBind();
        ConnString .Close();
    }
    //RowDataBound event fires on binding the data to the row
    protected void gvdecryption_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string decryptpassword = e.Row.Cells[1].Text;
            e.Row.Cells[1].Text = Decryptdata(decryptpassword);
        }
    }   
    #endregion
    #region " F U N C T I O N S "
    // Function is used to Encrypt the Password   
    private string Encryptdata(string Password)
    {
        string strPwd = string.Empty;
        byte[] toEncode = new byte[Password.Length];
        toEncode = System.Text.Encoding.UTF8.GetBytes(Password);
        strPwd = Convert.ToBase64String(toEncode);
        return strPwd;
    }
    // Function is used to Decrypt the Password   
    private string Decryptdata(string encryptpwd)
    {
        string strPwd = string.Empty;
        UTF8Encoding EncodePwd = new UTF8Encoding();
        System.Text.Decoder utf8Decode = EncodePwd.GetDecoder();
        byte[] toDecode = Convert.FromBase64String(encryptpwd);
        int StrCount = utf8Decode.GetCharCount(toDecode, 0, toDecode.Length);
        char[] decodedStr = new char[StrCount];
        utf8Decode.GetChars(toDecode, 0, toDecode.Length, decodedStr, 0);
        strPwd = new String(decodedStr);
        return strPwd;

    }
    #endregion

In Web.Config:-

<connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=Manjeeth;Initial Catalog= Manjeeth;User ID=sa;Password=****" providerName="System.Data.SqlClient"/>
  </connectionStrings>


Database Script for a table UserTable:-

CREATE TABLE [dbo].[UserTable](
      [Username] [varchar](50) NOT NULL,
      [Password] [nvarchar](100) NULL,
      [EmailId] [varchar](50) NULL,
 CONSTRAINT [PK_UserTable] PRIMARY KEY CLUSTERED
(
      [Username] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  =ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO


Happy Programming.....