Sunday, October 11, 2009

How to import Yahoo Contact List using C#

Steps to import Yahoo Contact List using C#

Firtly define a class naming 'MailContact' as follows,

public class MailContact
{
private string _email = string.Empty;
private string _name = string.Empty;

public string Name
{
get { return _name; }
set { _name = value; }
}

public string Email
{
get { return _email; }
set { _email = value; }
}

public string FullEmail
{
get { return Email; }
}
}

public class MailContactList : List
{
}

Then just, make some changes as required and use the following code in your application to import the yahoo contact list,

using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace Gnilly.Syndication.Mail
{
public class YahooExtract
{
private const string _addressBookUrl = "http://address.yahoo.com/yab/us/Yahoo_ab.csv?loc=us&.rand=1671497644&A=H&Yahoo_ab.csv";
private const string _authUrl = "https://login.yahoo.com/config/login?";
private const string _loginPage = "https://login.yahoo.com/config/login";
private const string _userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3";

public bool Extract( NetworkCredential credential, out MailContactList list )
{
bool result = false;

list = new MailContactList();

try
{
WebClient webClient = new WebClient();
webClient.Headers[ HttpRequestHeader.UserAgent ] = _userAgent;
webClient.Encoding = Encoding.UTF8;

byte[] firstResponse = webClient.DownloadData( _loginPage );
string firstRes = Encoding.UTF8.GetString( firstResponse );


NameValueCollection postToLogin = new NameValueCollection();
Regex regex = new Regex( "type=\"hidden\" name=\"(.*?)\" value=\"(.*?)\"", RegexOptions.IgnoreCase );
Match match = regex.Match( firstRes );
while ( match.Success )
{
if ( match.Groups[ 0 ].Value.Length > 0 )
{
postToLogin.Add( match.Groups[ 1 ].Value, match.Groups[ 2 ].Value );
}
match = regex.Match( firstRes, match.Index + match.Length );
}


postToLogin.Add( ".save", "Sign In" );
postToLogin.Add( ".persistent", "y" );

string login = credential.UserName.Split( '@' )[ 0 ];
postToLogin.Add( "login", login );
postToLogin.Add( "passwd", credential.Password );

webClient.Headers[ HttpRequestHeader.UserAgent ] = _userAgent;
webClient.Headers[ HttpRequestHeader.Referer ] = _loginPage;
webClient.Encoding = Encoding.UTF8;
webClient.Headers[ HttpRequestHeader.Cookie ] = webClient.ResponseHeaders[ HttpResponseHeader.SetCookie ];

webClient.UploadValues( _authUrl, postToLogin );
string cookie = webClient.ResponseHeaders[ HttpResponseHeader.SetCookie ];

if ( string.IsNullOrEmpty( cookie ) )
{
return false;
}

string newCookie = string.Empty;
string[] tmp1 = cookie.Split( ',' );
foreach ( string var in tmp1 )
{
string[] tmp2 = var.Split( ';' );
newCookie = String.IsNullOrEmpty( newCookie ) ? tmp2[ 0 ] : newCookie + ";" + tmp2[ 0 ];
}

// set login cookie
webClient.Headers[ HttpRequestHeader.Cookie ] = newCookie;
byte[] thirdResponse = webClient.DownloadData( _addressBookUrl );
string thirdRes = Encoding.UTF8.GetString( thirdResponse );

string crumb = string.Empty;
Regex regexCrumb = new Regex( "type=\"hidden\" name=\"\\.crumb\" id=\"crumb1\" value=\"(.*?)\"", RegexOptions.IgnoreCase );
match = regexCrumb.Match( thirdRes );
if ( match.Success && match.Groups[ 0 ].Value.Length > 0 )
{
crumb = match.Groups[ 1 ].Value;
}


NameValueCollection postDataAB = new NameValueCollection();
postDataAB.Add( ".crumb", crumb );
postDataAB.Add( "vcp", "import_export" );
postDataAB.Add( "submit[action_export_yahoo]", "Export Now" );

webClient.Headers[ HttpRequestHeader.UserAgent ] = _userAgent;
webClient.Headers[ HttpRequestHeader.Referer ] = _addressBookUrl;

byte[] FourResponse = webClient.UploadValues( _addressBookUrl, postDataAB );
string csvData = Encoding.UTF8.GetString( FourResponse );

string[] lines = csvData.Split( '\n' );
foreach ( string line in lines )
{
string[] items = line.Split( ',' );
if ( items.Length < 5 )
{
continue;
}
string email = items[ 4 ];
string name = items[ 3 ];
if ( !string.IsNullOrEmpty( email ) && !string.IsNullOrEmpty( name ) )
{
email = email.Trim( '\"' );
name = name.Trim( '\"' );
if ( !email.Equals( "Email" ) && !name.Equals( "Nickname" ) )
{
MailContact mailContact = new MailContact();
mailContact.Name = name;
mailContact.Email = email;
list.Add( mailContact );
}
}
}

result = true;
}
catch
{
}
return result;
}
}
}

That's it now you will be successfully be able to extract the contact list from yahoo....

Fukat ka Gyan Phrase:

it is better to value what you have than to try to get more...

Friday, October 9, 2009

How to Add Auto Refresh Functionality to Web Application

Now in order to add auto refresh functionality for a gridview or in order to reload your session variables you can follow this following step.
Following example shows how you can add the auto refresh functionality to your Gridview:
For this you will require timer and Script manager need to be added in your code along with optional Update panel as shown below,


<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:Timer ID="Timer1" OnTick="Timer1_Tick" runat="server" Interval="30000">
</asp:Timer>
</div>
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Grid not refreshed yet."></asp:Label><br />
<asp:Label ID="Label4" runat="server" Text="(Grid Will Referesh after Every 30 Sec)"
Font-Bold="true"></asp:Label>
<br />
<br />
<asp:DataGrid ID="GridData" runat="server" Width="100%" HeaderStyle-BackColor="#999999"
AutoGenerateColumns="False">
<Columns>
<asp:BoundColumn DataField="Name" HeaderText="Employee ID"></asp:BoundColumn>
<asp:BoundColumn DataField="EffortsEstimated" HeaderText="First Name"></asp:BoundColumn>
<asp:BoundColumn DataField="EffortsRequired" HeaderText="Last Name"></asp:BoundColumn>
<asp:BoundColumn DataField="DefectsOpen" HeaderText="City"></asp:BoundColumn>
</Columns>
<HeaderStyle BackColor="#999999" />
</asp:DataGrid>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ProjectsDashboardConnectionString2 %>"
SelectCommand="SELECT [Name], [EffortsEstimated], [EffortsRequired], [DefectsOpen] FROM [Projects]">
</asp:SqlDataSource>
</ContentTemplate>
</asp:UpdatePanel>
</form>



In the .cs file i.e in the Code Behind file you have to include the following code which will be triggered by the timer after the specified interval( in this case 30 sec)


public void BindData()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ProjectsDashboardConnectionString2"].ConnectionString); SqlCommand cmd=new SqlCommand();
cmd.CommandText = "select * from Projects"; cmd.Connection = con; con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); cmd.ExecuteNonQuery(); GridData.DataSource = ds; GridData.DataBind();
}
protected void Timer1_Tick(object sender, EventArgs e)
{
Label1.Text = "Grid Refreshed at: " + DateTime.Now.ToLongTimeString(); this.BindData();
}

Now, after this run your code the application will refresh after every 30 sec...
Always find results on Fukat Ka Gyan !!! to save your time…

Tuesday, October 6, 2009

Calling a Javascript Function From Aspx.cs File

Javascript Methods are client side codes, so you can not call them in your server side code.

// FALSE FALSE FALSE

Yes, You can call the javascript function from the aspx.cs file. Try the following steps,

Suppose there is a javascript function in your aspx page as shown,

function revealModal(divID)
{
window.onscroll = function()
{
document.getElementById(divID).style.top = document.body.scrollTop;
};
document.getElementById(divID).style.display = "block";
document.getElementById(divID).style.top = document.body.scrollTop;
}
}

In order to call this method from .cs file, you have to use following method,

string str = @"<script language=javascript>revealModal('modalPage')</script>";
this.ClientScript.RegisterStartupScript(typeof(MyPage), "JAVASCRIPT", str);

where MyPage is the name of the class/page

Always find results on Fukat Ka Gyan !!! to save your time…