Wednesday 26 December 2012

Add News Feed in Web Page

 Write the below Javascript code in the source code of your web page :

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<
script src="http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.js"type="text/javascript"></script><
style type="text/css">@import
url("http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.css");#feedControl {margin-top : 10px;margin-left: auto;margin-right: auto;width : 205px;font-size: 12px;color: #9CADD0;}
</style><
script type="text/javascript">function
load() {
var feed = "http://rss.cnn.com/rss/edition_world.rss";new GFdynamicFeedControl(feed, "feedControl");}
google.load(
"feeds", "1");google.setOnLoadCallback(load);
</script>

---The variable Feed conatins the site from where the news are fetched. We can give some other sites too such as :
1. var feed =”http://feeds.bbci.co.uk/news/world/rss.xml”;
2. var feed =”http://rss.cnn.com/rss/edition_world.rss”;
3. var feed =”http://feeds.reuters.com/Reuters/worldNews “;
Now where ever you need the news feed in your page just write the below code :


<div id="feedControl" align="left" dir="ltr">Loading...&nbsp; </div>


You can see the page with active news feeds along with the link :

Thursday 20 December 2012

OLEDB: Extract The Data from Excel and Show it in Gridview or add to database table

Let the excel sheet contains the above data along with the header. Now in the application, take a fileupload control, a button and a gridview. In the botton click write the below code :

try
{DataSet ds = new DataSet();//file upload pathstring path = FileUpload1.PostedFile.FileName;
//Create connection string to Excel work bookstring excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;Persist Security Info=False";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);

//Create OleDbCommand to fetch data from ExcelOleDbCommand cmd = new OleDbCommand("Select [EID],[LOB],[Resource First Name],[Resource Middle Initial],[Resource Last Name],[Primary Role],[Input Type Code],[Financial Location],[Currency Code],[Actual Payable Hours] from [Sheet1$]", excelConnection);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);da.Fill(ds);
excelConnection.Open();

OleDbDataReader dReader;dReader = cmd.ExecuteReader();

//SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);////Give your Destination table name//sqlBulk.DestinationTableName = "Excel_table";//sqlBulk.WriteToServer(dReader);excelConnection.Close();GridView1.DataSource = ds;
GridView1.DataBind();
catch (Exception ex)
{
        Response.Write(ex.StackTrace);
}

The Result will look as below :

Now since we got the data in dataset from the excel, we can easily do anything we need with the data(modify) and insert it in the database table.

Wednesday 21 November 2012

Uploading and Downloading any file

upload

Create a table (UploadedFiles) having a column (upload) with datatype nvarchar(max).
In the application drag a fileupload control and a buton. In the click event write the below code:

SqlCommand cmm;

SqlConnection con;
SqlDataAdapter da;
string s;
protected void Button2_Click(object sender, EventArgs e){
cmm =
new SqlCommand("Insert into UploadedFiles values(@a)");con =
new SqlConnection("Data Source=Synaro01242;Initial Catalog=Test;uid=sa;Pwd=Password123$");cmm.Connection = con;
con.Open();
da =
new SqlDataAdapter(cmm);
if (FileUpload1.HasFile){

string fileExt = System.IO.Path.GetExtension(FileUpload1.FileName);
//if (fileExt == ".pdf" || fileExt == ".txt" || fileExt == ".docx")//{// //s = MapPath("img");
s = s + "/" + FileUpload1.FileName;
FileUpload1.SaveAs(s);

//}//else//{// Response.Write("Invalid Upload file format");//}}
cmm.Parameters.AddWithValue(
"@a",s);cmm.ExecuteNonQuery();
con.Close();
}


Download


In the gridview bind it with the database table (UploadedFiles). Now add a buttonfield named Download, and Command name as "Download"



In Gridview RowCommand Event write the below code:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e){

if (e.CommandName == "Download"){

int index = Convert.ToInt32(e.CommandArgument);
string url = GridView1.Rows[index].Cells[0].Text;System.IO.
FileInfo file = new System.IO.FileInfo(url);
if (file.Exists){
Response.Clear();
Response.AppendHeader(
"Content-Disposition:", "attachment; filename=" + file.Name);Response.AppendHeader(
"Content-Length", file.Length.ToString());Response.ContentType =
"application/octet-stream";Response.TransmitFile(file.FullName);
Response.End();
}

else{
Response.Write(
"NO FILE PRESENT");}
}
}


File will be downloaded having a wizard -Open or Save.

Sunday 5 August 2012

Read or Write connection strings in web.config file using asp.net

open web.config file in application and add sample db connection in connectionStrings section like this 

<connectionStrings>
<add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient"/>
</connectionStrings >

Example of declaring connectionStrings in web.config file like this

<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB" providerName="System.Data.SqlClient"/>
</connectionStrings >


After add dbconnection in connectionString we need to write the some code in our codebehind file to get connection string from web.config file for that add following namespace in codebehind file and write the following code

using System.Configuration;

 This namespace is used to get configuration section details from web.config file.

After add namespaces write the following code in code behind

C# code

using System;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{   
//Get connection string from web.config file
string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
//create new sqlconnection and connection to database by using connection string from web.config file
SqlConnection con = new SqlConnection(strcon);
con.Open();
}
}

VB.NET

Imports System.Data.SqlClient
Imports System.Configuration
Partial Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
'Get connection string from web.config file
Dim strcon As String = ConfigurationManager.ConnectionStrings("dbconnection").ConnectionString
'create new sqlconnection and connection to database by using connection string from web.config file
Dim con As New SqlConnection(strcon)
con.Open()
End Sub
End Class

Encrypt and Decrypt the password

Design your aspx like this 


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center">
<tr>
<td colspan="2">
<b>Encryption and Decryption of Password</b>
</td>
</tr>
<tr>
<td>
UserName
</td>
<td>
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Password
</td>
<td>
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr>
<td>
FirstName
</td>
<td>
<asp:TextBox ID="txtfname" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
LastName
</td>
<td>
<asp:TextBox ID="txtlname" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" />
</td>
</tr>
</table>
</div>
<div>
<table align="center">
<tr>
<td>
<b>Encryption of Password Details</b>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvUsers" runat="server" CellPadding="4" BackColor="White"
BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px">
<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"
HorizontalAlign="Left"/>
</asp:GridView>
</td>
</tr>
</table>
</div>
<div>
<table align="center">
<tr>
<td>
<b>Decryption of Password Details</b>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="gvdecryption" runat="server" BackColor="White"
BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4"
onrowdatabound="gvdecryption_RowDataBound">
<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" />
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

After that add System.Text namespace in code behind because in this namespace contains classes representing ASCII and Unicode character encodings

After that add following code in code behind and design one table in database with four fields and give name as "SampleUserdetails"

private const string strconneciton = "Data Source=MYCBJ017550027;Initial Catalog=MySamplesDB;Integrated Security=True";
SqlConnection con = new SqlConnection(strconneciton);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindencryptedData();
BindDecryptedData();
}
}
/// <summary>
/// btnSubmit event is used to insert user details with password encryption
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnSubmit_Click(object sender, EventArgs e)
{
string strpassword = Encryptdata(txtPassword.Text);
con.Open();
SqlCommand cmd = new SqlCommand("insert into SampleUserdetails(UserName,Password,FirstName,LastName) values('" + txtname.Text + "','" + strpassword + "','" + txtfname.Text + "','" + txtlname.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
BindencryptedData();
BindDecryptedData();
}
/// <summary>
/// Bind user Details to gridview
/// </summary>
protected void BindencryptedData()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from SampleUserdetails", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUsers.DataSource = ds;
gvUsers.DataBind();
con.Close();
}
/// <summary>
/// Bind user Details to gridview
/// </summary>
protected void BindDecryptedData()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from SampleUserdetails", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvdecryption.DataSource = ds;
gvdecryption.DataBind();
con.Close();
}
/// <summary>
/// Function is used to encrypt the password
/// </summary>
/// <param name="password"></param>
/// <returns></returns>
private string Encryptdata(string password)
{
string strmsg = string.Empty;
byte[] encode = new byte[password.Length];
encode = Encoding.UTF8.GetBytes(password);
strmsg = Convert.ToBase64String(encode);
return strmsg;
}
/// <summary>
/// Function is used to Decrypt the password
/// </summary>
/// <param name="password"></param>
/// <returns></returns>
private string Decryptdata(string encryptpwd)
{
string decryptpwd = string.Empty;
UTF8Encoding encodepwd = new UTF8Encoding();
Decoder Decode = encodepwd.GetDecoder();
byte[] todecode_byte = Convert.FromBase64String(encryptpwd);
int charCount = Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
decryptpwd = new String(decoded_char);
return decryptpwd;
}
/// <summary>
/// rowdatabound condition is used to change the encrypted password format to decryption format
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void gvdecryption_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string decryptpassword = e.Row.Cells[2].Text;
e.Row.Cells[2].Text = Decryptdata(decryptpassword);
}
}

Demo