Archive for the ‘Uncategorized’ Category

string objects are immutable in C#

Posted: August 2, 2012 in C#, Uncategorized
Tags: ,

All string objects are immutable in C#. Objects of the class string, once created, can never represent any value other than the one they were constructed with. All operations that seem to “change” a string instead produce a new one. This is inefficient with memory, but extremely useful with regard to being able to trust that a string won’t change out form under you- because as long as you don’t change your reference, the string being referred to will never change.

A mutable object, by contrast, has data fields that can be altered. One or more of its methods will change the contents of the object, or it has a Property that, when written into, will change the value of the object.

If you have a mutable object- the most similar one to String is StringBuffer- then you have to make a copy of it if you want to be absolutely sure it won’t change out from under you. This is why mutable objects are dangerous to use as keys into any form of Dictionary or set- the objects themselves could change, and the data structure would have no way of knowing, leading to corrupt data that would, eventually, crash your program.

However, you can change its contents- so it’s much, much more memory efficient than making a complete copy because you wanted to change a single character, or something similar.

Generally, the right thing to do is use mutable objects while you’re creating something, and immutable objects once you’re done. This applies to objects that have immutable forms, of course; most of the collections don’t. It’s often useful to provide read-only forms of collections, though, which is the equivalent of immutable, when sending the internal state of your collection to other contexts- otherwise, something could take that return value, do something to it, and corrupt your data.

Just Trying To Explain string Concept ūüôā

Hope This Post Will Help you Somehow . . :) . Feel Free To Ask Anything You Need.

Waiting For Your Valuable Feedback.

Sometimes we require to invoke postback of a control but cannot set AutoPostBack property to true. In such case we can make use of __doPostBack method of Javascript. 

I`ll Give you A Simple Example How You Can Do This..

______________________________________________________________________________________

Include these 3 tags into your .aspx page.

<input type=”hidden” name =”__EVENTTARGET” value =”” />
<input type=”hidden” name =”__EVENTARGUMENT” value =”” />
<a id=”LButton3″ href=”javascript:__doPostBack(‘Button2′,’ ‘)”>LinkButton</a>

Here we have on anchor tag we want a server side event to fire on click of this link.

Now write this javascript function . Form1 is the id of your form.

<script type=”text/javascript”>

function __doPostBack(eventTarget, eventArgument) {
document.Form1.__EVENTTARGET.value = eventTarget;
document.Form1.__EVENTARGUMENT.value = eventArgument;
document.Form1.submit();
}
</script>

______________________________________________________________________________________

Now, Lets talk about Server Side operations . You Have To Write this code in your .cs file

protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form[“__EVENTTARGET”] == “Button2”)
{
//fire event
Button2_Click(this, new EventArgs());
}
}

protected void Button2_Click(object sender, EventArgs e)
{
Response.Write(“postback event fired”);
}

_______________________________________________________________________________________

this will fire your Button2_Click event..

This Is Basic , Now You Can Modify This Code as You Want ūüôā

Hope This Post Will Help you Somehow . . :) . Feel Free To Ask Anything You Need.

Waiting For Your Valuable Feedback.

To Get The Contacts first of all we have to create an application on windows live which you can create from Here   press create application button by which you can get API key and secret.

Now You Can Put This Tag Into Your aspx Page ..

<a href=”https://oauth.live.com/authorize?client_id=YOURCLIENTID&scope=wl.basic&client_secret=YOURCLIENTSECRET&response_type=code&redirect_uri=”Your aspx Page url” > Click To Get Msn Contacts </a>

Then You Have To Make One More Class..  You Can Say MsnImport.cs

public class MsnImport
{
private const string wlCookie = “wl_auth”;
private const string clientId = “YOURCLIENTID”;
private string Callback = “URL¬†Of Your Page Where You Want To Redirect From Msn”;
private const string clientSecret = “YOURCLIENTSECRET”;
private const string oauthUrl = “https://oauth.live.com/token&#8221;;
private List<string> emaillist = new List<string>();
public MsnImport(int agentid)
{
}
public List<string> GetMsnContacts(string code)
{

try
{
HttpContext context = HttpContext.Current;
string verifier = code;
OAuthToken token;
OAuthError error;

if (!string.IsNullOrEmpty(verifier))
{
RequestAccessTokenByVerifier(verifier, out token, out error);
}
}
catch (Exception ex) { }
return emaillist;
}
private void RequestAccessTokenByVerifier(string verifier, out OAuthToken token, out OAuthError error)
{
string content = String.Format(“client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&grant_type=authorization_code”,
HttpUtility.UrlEncode(clientId),
HttpUtility.UrlEncode(Callback),
HttpUtility.UrlEncode(clientSecret),
HttpUtility.UrlEncode(verifier));
RequestAccessToken(content, out token, out error);
}
private void RequestAccessToken(string postContent, out OAuthToken token, out OAuthError error)
{
token = null;
error = null;
HttpWebRequest request = WebRequest.Create(oauthUrl) as HttpWebRequest;
request.Method = “POST”;
try
{
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(postContent);
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response != null)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(OAuthToken));
token = serializer.ReadObject(response.GetResponseStream()) as OAuthToken;
if (token != null)
{
RequestContacts(token.AccessToken);
}
}
}
catch (Exception ex)
{

}

}
private void RequestContacts(string AccessToken)
{
string content = String.Format(“access_token={0}”, HttpUtility.UrlEncode(AccessToken));
string url = “https://apis.live.net/v5.0/me/contacts?&#8221; + content;
//string url = “https://apis.live.net/v5.0/me/contacts?access_token=&#8221; + AccessToken;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//request.Method = “POST”;
request.Method = WebRequestMethods.Http.Get;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
JavaScriptSerializer ser = new JavaScriptSerializer();
Dictionary<string, object> dictionary = ser.Deserialize<Dictionary<string, object>>(tmp);
DisplayDictionary(dictionary);
}
public bool DisplayDictionary(Dictionary<string, object> dict)
{
bool bSuccess = false;
string abc = string.Empty;
foreach (string strKey in dict.Keys)
{
string strOutput = “”;// “”.PadLeft(indentLevel * 8) + strKey + “:”;
object o = dict[strKey];
if (o is Dictionary<string, object>)
{
DisplayDictionary((Dictionary<string, object>)o);
}
else if (o is ArrayList)
{
foreach (object oChild in ((ArrayList)o))
{
if (oChild is string)
{
strOutput = ((string)oChild);
}
else if (oChild is Dictionary<string, object>)
{
DisplayDictionary((Dictionary<string, object>)oChild);
}
}
}
else
{
if (o != null)
{
strOutput = o.ToString();
if (strKey == “name”)
{
if (strOutput.Contains(“@”))
emaillist.Add(strOutput);
}
}
}
}
return bSuccess;
}
}
[DataContract]
public class OAuthToken
{
[DataMember(Name = OAuthConstants.AccessToken)]
public string AccessToken { get; set; }
[DataMember(Name = OAuthConstants.RefreshToken)]
public string RefreshToken { get; set; }
[DataMember(Name = OAuthConstants.ExpiresIn)]
public string ExpiresIn { get; set; }
[DataMember(Name = OAuthConstants.Scope)]
public string Scope { get; set; }
}
public static class OAuthConstants
{
public const string ClientID = “client_id”;
public const string ClientSecret = “client_secret”;
public const string Callback = “redirect_uri”;
public const string ClientState = “state”;
public const string Scope = “scope”;
public const string Code = “code”;
public const string AccessToken = “access_token”;
public const string ExpiresIn = “expires_in”;
public const string RefreshToken = “refresh_token”;
public const string ResponseType = “response_type”;
public const string GrantType = “grant_type”;
public const string Error = “error”;
public const string ErrorDescription = “error_description”;
public const string Display = “display”;
}
[DataContract]
public class OAuthError
{
public OAuthError(string code, string desc)
{
this.Code = code;
this.Description = desc;
}
[DataMember(Name = OAuthConstants.Error)]
public string Code { get; private set; }
[DataMember(Name = OAuthConstants.ErrorDescription)]
public string Description { get; private set; }
}

_______________________________________________________________________________________

In Your .aspx Page You Have To Write This Code in Page_Load()

if (Request.QueryString[“code”] != null)
{
GetMsnContacts(Request.QueryString[“code”].ToString());
}

You Can Call This Method In Method In Your .aspx Page

private void GetMsnContacts(string code)
{
MsnImport msnImport = new MsnImport();
List<string> emaillist = new List<string>();
emaillist = msnImport.GetMsnContacts(code);
}

_______________________________________________________________________________________

By Implementing The Above Code You Can Easily Import Msn Contacts ..

Hope This Post Will Help you Somehow . . :) . Feel Free To Ask Anything You Need.

Waiting For Your Valuable Feedback.

In Many Sites We Can See There Are Options Of Importing Contacts From Gmail,Yahoo,AOL, Msn ..To Invite Friends To Join your website Or Something Like That..

Importing Gmail Contacts Is Not A Real Big Task . Google Has Provided Few dll`s Through Which You Can Import Gmail Contacts ..

Step 1 :  Download Google data API setup from the specified URL :

Step 2: Add These dll`s into Your Bin Folder ..
1.Google.GData.Apps.dll
2.Google.GData.Client.dll
3.Google.GData.Contacts.dll
4.Google.GData.Extensions.dll

Step 3 :Add These Namespace To Your Codebehind.
using Google.GData.Contacts;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.Contacts;

Step 4 : Add This Function Into Your Code behind :

public static DataSet GetGmailContacts(string App_Name, string Uname, string UPassword)

{

DataSet ds = new DataSet();

DataTable dt = new DataTable();

DataColumn C2 = new DataColumn();

C2.DataType = Type.GetType(“System.String”);

C2.ColumnName = “EmailID”;

dt.Columns.Add(C2);

RequestSettings rs = new RequestSettings(App_Name, Uname, UPassword);

rs.AutoPaging = true;

ContactsRequest cr = new ContactsRequest(rs);

Feed<Contact> f = cr.GetContacts();

foreach (Contact t in f.Entries)
{

foreach (EMail email in t.Emails)
{

DataRow dr1 = dt.NewRow();

dr1[“EmailID”] = email.Address.ToString();

dt.Rows.Add(dr1);

}

}

ds.Tables.Add(dt);

return ds;

}

By This Function You Can import Your Gmail Contacts . Your Contacts Will Be Saved In Dataset..You Can Bind that Dataset To Your .aspx File.

You Can Call This Method Like :

DataSet ds = GetGmailContacts(“Web Application!”, “UserName”, “Password”);

Hope This Post Will Help you Somehow . . :)

Waiting For Your Valuable Feedback.

Custom Facebook Share Button

Few Days Back I Was Making A Facebook Share Button For My Website But I Wanted To Make a Button With My Custom Design Like Custom Image ,  Summary , Title etc . But I Was Not Getting Any Proper solution . Then I Found Out A Simple Way To Customize Facebook Share Button . So Here I Am Sharing You What I Found.

To Make A Facebook Share Button You Just Need To Add This  Tag In Your HTML/ASP Page.

<a href=”http://www.facebook.com/sharer.php?s=100&amp;p%5Btitle%5D=My First Blog&amp;p[summary]=This Is First Geek Blog&amp;p[url]=https://dotnetgeekblog.wordpress.com/&amp;&p[images][0]=http://s.wordpress.org/about/images/logos/wordpress-logo-stacked-rgb.png”>Facebook Share</a>

Here You Can See That I have 4 Fields .

1.Title .. Here you Can Put The Title Of Your Link

2.Summary .. Here You Can Write Your Website Description.

3. URL..Here You Can Write The URL Of Your Website.

4.images .. Here You Can Give The URL Of Your Image.

Asp.Net Users Can Also Dynamically Bind The Data ..

<a id=”lnkFacebook” target=”_blank” runat=”server”>Facebook Share</a>

In c# ..

string title =”My First Blog”;
string url=”https://dotnetgeekblog.wordpress.com/&#8221;;
string summery=”This Is First Geek Blog”;
string image=”http://s.wordpress.org/about/images/logos/wordpress-logo-stacked-rgb.png&#8221;;

string facebooklink = “http://www.facebook.com/sharer.php?s=100&amp;p%5Btitle%5D=”+title;
facebooklink += “&amp;p[summary]=”+summery;
facebooklink += “&amp;p[url]=” + url;
facebooklink += “&amp;&p[images][0]=” + image;
lnkFacebook.HRef = facebooklink;

I have Just Shown an Example . Now You Can Play With This as Much as you Want..:)

I Have Also Attached  Image To Show How Your URL Will Be Displayed ..

Hope This Post Will Help you Somehow . . ūüôā

Waiting For Your Valuable Feedback.

Hello world!

Posted: July 25, 2012 in Uncategorized

Welcome to WordPress.com! This is your very first post. Click the Edit link to modify or delete it, or start a new post. If you like, use this post to tell readers why you started this blog and what you plan to do with it.

Happy blogging!