Friday 19 July 2013

How .net application executes

Windows (the OS) will be running at Start; the CLR won't begin execution until Windows starts it. When an application executes, OS inspects the file to see whether it has a special header to indicate that it is a .NET application. If not, Windows continues to run the application.

If an application is for .NET, Windows starts up the CLR and passes the application to the CLR for execution. The CLR loads the executable assembly, finds the entry point, and begins its execution process.

The executable assembly could reference other assemblies, such as dynamic link libraries (DLLs), so the CLR will load those. However, this is on an as-needed basis. An assembly won't be loaded until the CLR needs access to the assembly's code. It's possible that the code in some assemblies won't be executed, so there isn't a need to use resources unless absolutely necessary.

As mentioned previously, the C# compiler produces IL as part of an assembly's output. To execute the code, the CLR must translate the IL to binary code that the operating system understands. This is the responsibility of the JIT compiler.

As its name implies, the JIT compiler only compiles code before the first time that it executes. After the IL is compiled to machine code by the JIT compiler, the CLR holds the compiled code in a working set. The next time that the code must execute, the CLR checks its working set and runs the code directly if it is already compiled. It is possible that the working set could be paged out of memory during program execution, for various reasons that are necessary for efficient operation of the CLR on the particular machine it is running on. If more memory is available than the size of the working set, the CLR can hold on to the code. Additionally, in the case of Web applications where scalability is an issue, the working set can be swapped out due to periodic recycling or heavier load on the server, resulting in additional load time for subsequent requests.

The JIT compiler operates at the method level. If you aren't familiar with the term method, it is essentially the same as a function or procedure in other languages. Therefore, when the CLR begins execution, the JIT compiler compiles the entry point (the Main method in C#). Each subsequent method is JIT compiled just before execution. If a method being JIT compiled contains calls to methods in another assembly, the CLR loads that assembly (if not already loaded).

This process of checking the working set, JIT compilation, assembly loading, and execution continues until the program ends.

The meaning to you in the CLR execution process is in the form of application design and understanding performance characteristics. In the case of assembly loading, you have some control over when certain code is loaded. For example, if you have code that is seldom used or necessary only in specialized cases, you could separate it into its own DLL, which will keep the CLR from loading it when not in use. Similarly, separating seldomly executed logic into a separate method ensures the code doesn't JIT until it's called.

Another detail you might be concerned with is application performance. As described earlier, code is loaded and JIT compiled. Another DLL adds load time, which may or may not make a difference to you, but it is certainly something to be aware of. By the way, after code has been JIT compiled, it executes as fast as any other binary code in memory.

One of the CLR features listed in Table 1.1 is .NET Framework Class Library (FCL) support. The next section goes beyond FCL support for the CLR and gives an overview of what else the FCL includes.

Monday 11 March 2013

How to implement pagging in Repeater OR Datalist



Repeater and DataList control does not provide default pagging so we need to implement it explicitly. this is very easy to implement our own pagging in Repeater or Datalist.
   Just follow the step and your pagging will implement very easily :

Step 1.  
           Follow these step for .aspx page:
         i. Copy and paste in .aspx page where you want to display Repeater Or DataList data
======================================================================

 <table>
                        <tr>
                            <td>
                                <asp:Repeater ID="dListItems" runat="server">
                                    <ItemTemplate>
                                        <asp:Label ID="Label1" runat="server" Text='<%#Eval("title") %>'></asp:Label>
                                        <br />
                                    </ItemTemplate>
                                </asp:Repeater>
                            </td>
                        </tr>
                    </table>
======================================================================
ii. Copy and paste this where you want display pagging in your page 
======================================================================

    <table>
                            <tr>
                                <td>
                                    <asp:LinkButton ID="lbtnFirst" OnClick="lbtnFirst_Click" runat="server">First</asp:LinkButton>&nbsp;<asp:LinkButton
                                        ID="lbtnPrevious" OnClick="lbtnPrevious_Click" runat="server"><<</asp:LinkButton>&nbsp;
                                </td>
                                <td>
                                    <asp:DataList ID="dlPaging" RepeatDirection="Vertical" RepeatColumns="10" runat="server"
                                        OnItemDataBound="dlPaging_ItemDataBound" OnItemCommand="dlPaging_ItemCommand">
                                        <ItemTemplate>
                                            <asp:LinkButton ID="lnkbtnPaging" Text='<%#Eval("PageText") %>' CommandArgument='<%#Eval("PageIndex") %>'
                                                CommandName="Paging" runat="server">LinkButton</asp:LinkButton>
                                        </ItemTemplate>
                                    </asp:DataList>
                                </td>
                                <td>
                                    &nbsp;<asp:LinkButton ID="lbtnNext" OnClick="lbtnNext_Click" runat="server">>></asp:LinkButton>&nbsp;<asp:LinkButton
                                        ID="lbtnLast" OnClick="lbtnLast_Click" runat="server">Last</asp:LinkButton>
                                </td>
                            </tr>
                        </table>
======================================================================
iii. Copy and paste this where you want to display pagging info (i.e.currently displaying which number of page, total pages etc...)
======================================================================
 <asp:Label ID="lblPageInfo" runat="server" Text="Label"></asp:Label> ======================================================================
Above provided steps are for .aspx page .
now next step is for .aspx.cs page means for code behind.
Step 2:
          just and paste these function in code behind and run your page.
i. copy these all functions and paste in code behind : 
=======================================================================

 /// <summary>
    /// This will bind data into datalist
    /// </summary>
    private void BindItemsList()
    {
        PagedDataSource _PageDataSource = new PagedDataSource();

        DataTable dataTable = this.GetDataTable();
        _PageDataSource.DataSource = dataTable.DefaultView;
        _PageDataSource.AllowPaging = true;
        _PageDataSource.PageSize = 10;
        _PageDataSource.CurrentPageIndex = CurrentPage;
        ViewState["TotalPages"] = _PageDataSource.PageCount;

        this.lblPageInfo.Text = "Page " + (CurrentPage + 1) + " of " + _PageDataSource.PageCount;
        this.lbtnPrevious.Enabled = !_PageDataSource.IsFirstPage;
        this.lbtnNext.Enabled = !_PageDataSource.IsLastPage;
        this.lbtnFirst.Enabled = !_PageDataSource.IsFirstPage;
        this.lbtnLast.Enabled = !_PageDataSource.IsLastPage;

        this.dListItems.DataSource = _PageDataSource;
        this.dListItems.DataBind();
        this.doPaging();
    }
    /// <summary>
    /// Praparing table for filling into datalist
    /// </summary>
    /// <returns>Datatable</returns>
    private DataTable GetDataTable()
    {
        DataTable dtItems = new DataTable();

        DataColumn dcName = new DataColumn();
        dcName.ColumnName = "title";
        dcName.DataType = System.Type.GetType("System.String");
        dtItems.Columns.Add(dcName);

        DataRow row;
        for (int i = 1; i <= 100; i++)
        {
            row = dtItems.NewRow();
            row["title"] = "Sample Text: this is sample text " + i;
            dtItems.Rows.Add(row);

        }
        return dtItems;

    }
    /// <summary>
    /// Property
    /// </summary>
    private int CurrentPage
    {
        get
        {
            object objPage = ViewState["_CurrentPage"];
            int _CurrentPage = 0;
            if (objPage == null)
            {
                _CurrentPage = 0;
            }
            else
            {
                _CurrentPage = (int)objPage;
            }
            return _CurrentPage;
        }
        set { ViewState["_CurrentPage"] = value; }
    }
    /// <summary>
    /// Property
    /// </summary>
    private int fistIndex
    {
        get
        {

            int _FirstIndex = 0;
            if (ViewState["_FirstIndex"] == null)
            {
                _FirstIndex = 0;
            }
            else
            {
                _FirstIndex = Convert.ToInt32(ViewState["_FirstIndex"]);
            }
            return _FirstIndex;
        }
        set { ViewState["_FirstIndex"] = value; }
    }
    /// <summary>
    /// Property
    /// </summary>
    private int lastIndex
    {
        get
        {

            int _LastIndex = 0;
            if (ViewState["_LastIndex"] == null)
            {
                _LastIndex = 0;
            }
            else
            {
                _LastIndex = Convert.ToInt32(ViewState["_LastIndex"]);
            }
            return _LastIndex;
        }
        set { ViewState["_LastIndex"] = value; }
    }
    /// <summary>
    /// Fill pages with link in paggingdatalist
    /// </summary>
    private void doPaging()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("PageIndex");
        dt.Columns.Add("PageText");

        fistIndex = CurrentPage - 5;

        if (CurrentPage > 5)
        {
            lastIndex = CurrentPage + 5;
        }
        else
        {
            lastIndex = 10;
        }
        if (lastIndex > Convert.ToInt32(ViewState["TotalPages"]))
        {
            lastIndex = Convert.ToInt32(ViewState["TotalPages"]);
            fistIndex = lastIndex - 10;
        }

        if (fistIndex < 0)
        {
            fistIndex = 0;
        }

        for (int i = fistIndex; i < lastIndex; i++)
        {
            DataRow dr = dt.NewRow();
            dr[0] = i;
            dr[1] = i + 1;
            dt.Rows.Add(dr);
        }

        this.dlPaging.DataSource = dt;
        this.dlPaging.DataBind();
    }
    protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.Equals("Paging"))
        {
            CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
            this.BindItemsList();
        }
    }

    protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("lnkbtnPaging");
        if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
        {
            lnkbtnPage.Enabled = false;
            lnkbtnPage.Style.Add("fone-size", "14px");
            lnkbtnPage.Font.Bold = true;

        }
    }
    protected void lbtnNext_Click(object sender, EventArgs e)
    {
        CurrentPage += 1;
        this.BindItemsList();
    }
    protected void lbtnPrevious_Click(object sender, EventArgs e)
    {
        CurrentPage -= 1;
        this.BindItemsList();
    }
    protected void lbtnLast_Click(object sender, EventArgs e)
    {

        CurrentPage = (Convert.ToInt32(ViewState["TotalPages"]) - 1);
        this.BindItemsList();

    }
    protected void lbtnFirst_Click(object sender, EventArgs e)
    {
        CurrentPage = 0;
        this.BindItemsList();
    }
====================================================================
ii. this is last step just call this function in page_load()


 if (!IsPostBack)
        {
            this.BindItemsList();
        }

Pagging preview :
your pagging will look like ....





Thursday 7 February 2013

Work on Your own Field rather then following somebody else

One mind blowing interview

Interviewer : Tell me about yourself.

Candidate: I ...am Rameshwar Kulkarni. I did my Tele Communication engineering from BabanRao Dhole-Patil Inst it ute of Technology.

Interviewer : BabanRao Dhole-Patil Inst it ute of Technology? I had never heard of this college before!
Candidate : Great! Even I had not heard of it before getting an admission into it ..
What happened is – due to cricket world cup I scored badly! in 12th.I was getting a paid seat in a good college. But my father said (I prefer to call him ‘baap’) – “I can not invest so much of money”.(The baap actually said – “I will never waste so much of money on you”). So I had to join this college. Frankly speaking this name – BabanRao Dhole-Patil, can at the most be related to a Shetakari Mahavidyalaya

Interviewer: ok, ok. It seems you have taken 6 years to complete your engineering.
Candidate : Actually I tried my best to finish it in 4 years. But you know, these cricket matches and football world cup, and tennis tournaments. It is difficult to concentrate. So I flunked in 2nd and 3rd year. So in all I took 4 + 2 = 7 years.

Interviewer: But 4+2 is 6.
Candidate: Oh, is it ? You know I always had KT in maths. But I will try to keep this in mind. 4+2 is 6, good, thanks. These cricket matches really affect exams a lot.. I think they should ban it .

Interviewer : Good to know that you want cricket matches to be banned.
Candidate : No, no… I am talking about Exams!!

Interviewer: Ok, What is your biggest achievement in life?
Candidate : Obviously, completing my Engineering. My mom never thought I would complete it . In fact, when I flunked in 3rd year, she was looking for a job for me in BEST (Bus
corporation in Maharashtra ) through some relative.

Interviewer : Do you have any plans of higher study?
Candidate: he he he.. Are you kidding? Completing ‘lower’ education it self was so much of pain!!

Interviewer : Let’s talk about technical stuff. On which platforms have you worked?
Candidate : Well, I work at SEEPZ, so you can say Andheri is my current platforms. Earlier I was at Vashi center. So Vashi was my platform then. As you can see I have experience of different platforms! (Vashi and Andheri are the places in Mumbai)

Interviewer : And which languages have you used?
Candidate : Marathi, Hindi, English. By the way, I can keep quiet in German, French, Russian and many other languages.

Interviewer: Why VC is better than VB?
Candidate : It is a common sense – C comes after B. So VC is a higher version than VB. I heard very soon they are coming up w it h a new language VD!

Interviewer: Do you know anything about Assembly Language?
Candidate: Well, I have not heard of it . But I guess, this is the language our ministers and MPs use in assembly.

Interviewer : What is your general project experience?
Candidate : My general experience about projects is – most of the times they are in pipeline!

Interviewer: Can you tell me about your current job?
Candidate: Sure, Currently I am working for Bata Info Tech ltd. Since joining BIL, I am on Bench. Before joining BIL, I used to think that Bench was another software like Windows.

Interviewer : Do you have any project management experience?
Candidate: No, but I guess it shouldn’t be difficult. I know Word and Excel. I can talk a lot. I know how to dial for International phone call and use speaker facility. And very important – I know few words like – ‘Showstoppers ‘ , ‘hot fixes’, ‘SEI-CMM’, ‘quality’, ‘version control’, ‘deadlines’ , ‘Customer Satisfaction’ etc. Also I can blame others for my mistakes!

Interviewer: What are your expectations from our company?
Candidate : Not much.
1. I should at least get 40,000 in hand..
2. I would like to work on a live EJB project. But it should not have deadlines. I personally feel that pressure affects natural talent.
3. I believe in flexi-timings.
4. Dress Code is against basic freedom, so I would like to wear t-shirt and jeans.
5. We must have sat-sun off. I will suggest Wednesday off also, so as to avoid breakdown due to overwork.
6. I would like to go abroad 3 times a year on short term preferably 1-2 months) assignments. Personally I prefer US, Australia and Europe. But considering the fact that there are Olympics coming up in China in the current year, I don’t mind going there in that period. As you can see I am modest and don’t have many expectations. So can I assume my selection?

Interviewer : he he he ha ha ha. Thanks for your interest in our
organization. In fact I was never entertained so much before. Welcome to INFOSYS.

The fellow was appointed in a newly created section ‘Stress Management’ in the HRD of Infosys.

So Excellence is not the only thing Needed. Its the Unique Quality of a Person which can let anyone to Success.
One mind blowing interview

Interviewer : Tell me about yourself.
Candidate: I ...am Rameshwar Kulkarni. I did my Tele Communication engineering from BabanRao Dhole-Patil Inst it ute of Technology.

Interviewer : BabanRao Dhole-Patil Inst it ute of Technology? I had never heard of this college before!
Candidate : Great! Even I had not heard of it before getting an admission into it ..
What happened is – due to cricket world cup I scored badly! in 12th.I was getting a paid seat in a good college. But my father said (I prefer to call him ‘baap’) – “I can not invest so much of money”.(The baap actually said – “I will never waste so much of money on you”). So I had to join this college. Frankly speaking this name – BabanRao Dhole-Patil, can at the most be related to a Shetakari Mahavidyalaya

Interviewer: ok, ok. It seems you have taken 6 years to complete your engineering.
Candidate : Actually I tried my best to finish it in 4 years. But you know, these cricket matches and football world cup, and tennis tournaments. It is difficult to concentrate. So I flunked in 2nd and 3rd year. So in all I took 4 + 2 = 7 years.

Interviewer: But 4+2 is 6.
Candidate: Oh, is it ? You know I always had KT in maths. But I will try to keep this in mind. 4+2 is 6, good, thanks. These cricket matches really affect exams a lot.. I think they should ban it .

Interviewer : Good to know that you want cricket matches to be banned.
Candidate : No, no… I am talking about Exams!!

Interviewer: Ok, What is your biggest achievement in life?
Candidate : Obviously, completing my Engineering. My mom never thought I would complete it . In fact, when I flunked in 3rd year, she was looking for a job for me in BEST (Bus
corporation in Maharashtra ) through some relative.

Interviewer : Do you have any plans of higher study?
Candidate: he he he.. Are you kidding? Completing ‘lower’ education it self was so much of pain!!

Interviewer : Let’s talk about technical stuff. On which platforms have you worked?
Candidate : Well, I work at SEEPZ, so you can say Andheri is my current platforms. Earlier I was at Vashi center. So Vashi was my platform then. As you can see I have experience of different platforms! (Vashi and Andheri are the places in Mumbai)

Interviewer : And which languages have you used?
Candidate : Marathi, Hindi, English. By the way, I can keep quiet in German, French, Russian and many other languages.

Interviewer: Why VC is better than VB?
Candidate : It is a common sense – C comes after B. So VC is a higher version than VB. I heard very soon they are coming up w it h a new language VD!

Interviewer: Do you know anything about Assembly Language?
Candidate: Well, I have not heard of it . But I guess, this is the language our ministers and MPs use in assembly.

Interviewer : What is your general project experience?
Candidate : My general experience about projects is – most of the times they are in pipeline!

Interviewer: Can you tell me about your current job?
Candidate: Sure, Currently I am working for Bata Info Tech ltd. Since joining BIL, I am on Bench. Before joining BIL, I used to think that Bench was another software like Windows.

Interviewer : Do you have any project management experience?
Candidate: No, but I guess it shouldn’t be difficult. I know Word and Excel. I can talk a lot. I know how to dial for International phone call and use speaker facility. And very important – I know few words like – ‘Showstoppers ‘ , ‘hot fixes’, ‘SEI-CMM’, ‘quality’, ‘version control’, ‘deadlines’ , ‘Customer Satisfaction’ etc. Also I can blame others for my mistakes!

Interviewer: What are your expectations from our company?
Candidate : Not much.
1. I should at least get 40,000 in hand..
2. I would like to work on a live EJB project. But it should not have deadlines. I personally feel that pressure affects natural talent.
3. I believe in flexi-timings.
4. Dress Code is against basic freedom, so I would like to wear t-shirt and jeans.
5. We must have sat-sun off. I will suggest Wednesday off also, so as to avoid breakdown due to overwork.
6. I would like to go abroad 3 times a year on short term preferably 1-2 months) assignments. Personally I prefer US, Australia and Europe. But considering the fact that there are Olympics coming up in China in the current year, I don’t mind going there in that period. As you can see I am modest and don’t have many expectations. So can I assume my selection?

Interviewer : he he he ha ha ha. Thanks for your interest in our
organization. In fact I was never entertained so much before. Welcome to INFOSYS.

The fellow was appointed in a newly created section ‘Stress Management’ in the HRD of Infosys.

So Excellence is not the only thing Needed. Its the Unique Quality of a Person which can let anyone to Success. Work on Your own Field rather then following somebody else's Path
Share this Story with your Friends and Inspire People ♥♥♥
else's Path
Share this Story with your Friends and Inspire People ♥♥♥

Saturday 2 February 2013

Colour coded digital clock

Big blur
 
Fortunately I have good enough eye sight that I can read the time on my alarm clock without needing my glasses. However, if you do, how do you see what time it is at 3am in the morning? Does your clock look like this at 3:24am?
Blurry image of 3.24am

Coloured digits
 
Mono-coloured number displays come from the days before multicoloured LED's were cheap and easily available. Now with a range of colours, surely someone could make a mutli-coloured version? The numbers could look like this.
Multicoloured digits

What time is it?
 
3.24am with coloured digits

You can't read the digits, but once you've become accustomed to the colours, you can quickly see what time it is.

Is it time to get out of bed?
 
7.58am not time to get out of bed yet!

What about now?

8.05am time to get up!

Enabling Single Sign-on Using ASP.NET

You can use single sign-on to log on once and then access other system resources without logging on again. You can access information in the Windows® Home Server server software through a Remote Access page, which requires you to log on to the system. When you develop Web applications, you can use the same logon information to provide single sign-on for your applications.
You can use the authentication system that is provided by ASP.NET to determine whether a user is authenticated and what to do if the user is not authenticated. You can easily enable single sign-on of applications by copying sections of the web.config file for Windows Home Server to the web.config file for your application. For more information about using ASP.NET for authentication, see “Explained: Forms Authentication in ASP.NET 2.0” at the Microsoft Web site (http://go.microsoft.com/fwlink/?LinkId=145524).

Enable single sign-on for your application

In order for your Web application to use the same authentication as the Remote Access page of Windows Home Server, you must copy the machineKey element and the authentication element from the web.config file that is used for Remote Access to the web.config file that is used by your Web application. The web.config file that is used for Remote Access is in the C:\inetpub\remote folder.
Dd577079.note(en-us,MSDN.10).gifNote
Several web.config files are provided with Windows Home Server, but only the web.config file that is in the C:\inetpub\remote folder can be used for single sign-on.
The authentication element specifies the type of authentication to use (forms), the name of the authentication cookie (RemotePortalAuth) that is created, and the page to use for users who are not authenticated (logon.aspx). The machineKey element defines the encryption keys to use. You must also change the loginUrl property to reference the logon page for Windows Home Server. The following example shows the machineKey and authentication elements from the web.config file:

<machineKey validationKey="<MachineKey>" 
decryptionKey="<DecryptionKey>"
validation="SHA1" decryption="AES" />
<authentication mode="Forms">
<forms name="RemotePortalAuth" loginUrl="../remote/logon.aspx" protection="All" path="/" timeout="12000" requireSSL="false"/>
</authentication>

Dd577079.note(en-us,MSDN.10).gifNote
<MachineKey> and <DecryptionKey> are unique values that have not been shown for clarity.
After making this change in your Web application, if users are not already logged on through the Remote Access page, they are automatically redirected to the logon page for Windows Home Server and then directed back to the Web application page after successfully logging on.

aspnet_regiis 0x80004005 Windows 7 IIS 7

Problem
"aspnet_regiis -i" crashes when executed from command giving error code 0x80004005 on Windows 7 with IIS7
My solution
I have UAC switched on, and launched the command prompt -as administrator-. Start -> cmd -> right click "Run as Administrator". Then aspnet_regiis worked fine.
Did this work for you? please comment below for the benefit of others.

Friday 1 February 2013

Facebook Chat Authentication in C-sharp

Facebook Chat Authentication in C#

Disclaimer
By viewing this webpage you have just agreed to the following; this article is not written or endorsed by Facebook, the information contained within it may or may not be accurate, your mileage may very and that I am in no way liable for your stupidity.
X-Facebook-Platform mechanism
In order to authenticate with Facebook's chat platform, you need to use either DIGEST-MD5 (a hash of the users username/password - old skool) or if your application uses OAuth, then use Facebook's X-FACEBOOK-PLATFORM mechanism. I outline here how I implemented this authentication as part of the XDA Facebook for Windows Mobile application, which will include Facebook chat.
This article is a repeat of the X-FACEBOOK-PLATFORM in VB.NET article which I found to be very useful.
Credit goes to Joel Day pointing me in this direction and getting me started.

XMPP Conversation
Xmpp is basically a XML document conversation, where client and server 'build' their documents in parallel. From a coding point of view, I found it easier to write my own XML parser [yes, insane I know!] One of the main motivators behind this, is that an XMPP conversation deals in XML fragments.
Open a connection to chat.facebook.com
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(
"chat.facebook.com", 5222);
Send 'stream:stream' You initialise a conversation by opening a stream with the server. This is a "hello server" step.
<?xml version='1.0'?>
<stream:stream
id='1'
to='chat.facebook.com'
xmlns='jabber:client'
xmlns:stream='http://etherx.jabber.org/streams'
version='1.0' >
You should then receive a response; "hello back" followed by "list of ways to authenticate". Notice that this includes <starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"/> which indicates that the server supports SSL communication. There is more information which we ignore for now.
<?xml version="1.0"?>
<stream:stream
id="90854922"
from
="chat.facebook.com"
version
="1.0" xmlns="jabber:client"
xmlns:stream
="http://etherx.jabber.org/streams" xml:lang="en">

<stream:features>
<starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>
<mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl">
<mechanism>X-FACEBOOK-PLATFORM</mechanism>
<mechanism>DIGEST-MD5</mechanism>
</mechanisms>
</stream:features>
We switch to Transport Layer Security by continuing our plain text conversation by sending StartTLS message
   <starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>
The expected plain text response is
   <proceed xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>
In my Connection class code (which has 3 public methods 'Send' 'Receive' and now 'StartTls') I also have NetworkStream and a SslSocket members.
private NetworkStream _networkStream;
private SslStream _sslStream;

public void StartTls()
{
UseSecure
= true;

if (_networkStream == null)
_networkStream
= new NetworkStream( _socket );

if (_sslStream != null)
return;

_sslStream
= new SslStream(_networkStream, false);
_sslStream.AuthenticateAsClient(
"chat.facebook.com",
new X509CertificateCollection(), SslProtocols.Tls, false);
}
Once you have the SslStream open, use this for the reading/writing to the socket. Begin a new stream <stream:stream... as above and get new stream:features which does not include StartTls since we are using TLS.
This time we are interested the //stream:stream/stream:features/mechanisms/mechanism X-FACEBOOK-PLATFORM element.

<?xml version="1.0"?>
<stream:stream
id="90854922"
from
="chat.facebook.com"
version
="1.0" xmlns="jabber:client"
xmlns:stream
="http://etherx.jabber.org/streams" xml:lang="en">

<stream:features>
<mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl">
<mechanism>X-FACEBOOK-PLATFORM</mechanism>
<mechanism>DIGEST-MD5</mechanism>
</mechanisms>
</stream:features>
Select authentication mechanism by telling the server we'll use X-Facebook-Platform authorisation.
<auth 
xmlns='urn:ietf:params:xml:ns:xmpp-sasl'
mechanism='X-FACEBOOK-PLATFORM' />
The service responds with...
<challenge
xmlns="urn:ietf:params:xml:ns:xmppasl">
dmVyc2lvbj0xJm1ldG....3NzlFRkJCMDVERUY2MEM=
</challenge>
This challenge ('dmVyc2...') is a Base64 Encoded string, which we can convert to a string by doing the following
string decoded = Encoding.UTF8.GetString( Convert.FromBase64String( challengeData ) );         
Which gives us: version=1&method=auth.xmpp_login&nonce=3B53CFB6EE...FB424B68 I parse this in my code by doing a Split('&') to get three name=value pairs, then Split('=') to get name / value.
We use these to create our response which includes the following fields (in & separated name=value pairs)

  • method - the Method field received in the challenge
  • api_key - your Facebook Application key
  • access_token - the Users OAuth Access Token
  • call_id - some unique value (i.e. seconds since 1970)
  • v - the Version field received in the challenge
  • nonce - the Nonce field received in the challenge
In this new version, we no longer need the to calculate a signature. We simply covert this string into a Base64 Encoded string and pass it back to the service in a response.
Convert.ToBase64String( Encoding.UTF8.GetBytes( response ) )

<response 
xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>
BpX2tleT1kN2Q5ZTEwODU14ZTdiYzAxY2
EwNSZjYWxsX2lkPTEzMTM0MTQwNDEm
....
bWV0aG9kPWF1dGgueG1wcF9sb2dpbiZu
25jZT1BQzQxRjE2QTBENEI0REE3ODcX2tlx

</response>
Assuming that your user has permitted xmpp_login permission during the OAuth process, you should get the response
<success xmlns="urn:ietf:params:xml:ns:xmpp-sasl"/>
Now you're ready to actually do something with the service!
NO SUPPORT COMMENTS
Feel free to comment below, but DO NOT expect answers to any questions. If you want WORKING CODE please visit the XDA Facebook project mentioned above and see my code there.

Quantum and Anti-Bugs

Anti bug
While refactoring one day, I couldn't work out why my code had broken. That's not unusual, and so I checked and re-checked the new code that I'd written. Nope, it was bug free!
This was when I discovered the Anti-Bug Pattern, which occurs when there are two bugs in a system, but which co-incidentally cancel each other out. Fixing one bug uncovers the other. Ruben Bartelink came up with the name.
Quantum / Heisenberg
This bug only occurs when you are not debugging your code. As soon as you look at your source code... the bug disappears.

Thursday 24 January 2013

we can not create multiple instances for string in c# .net

Hi All,

Now i am going to discuss a uncommon thing with you, which i saw during development.

All you know that in C# .Net we have a method as

public static bool ReferenceEquals(object objA, object objB)
// Summary:
        //     Determines whether the specified System.Object instances are the same 

                 instance.
        //
        // Parameters:
        //   objA:
        //     The first System.Object to compare.
        //
        //   objB:
        //     The second System.Object to compare.
        //
        // Returns:
        //     true if objA is the same instance as objB or if both are null references;
        //     otherwise, false.


To check this method i wrote a program as:

        int i1=0;
        int i2 = 0;
        Console.WriteLine(object.ReferenceEquals(i1, i2));
        //  Output: False (Nice)

        float f1 = 0;
        float f2 = 0;
        Console.WriteLine(object.ReferenceEquals(f1, f2));
        //  Output: False (Great)

        DateTime d1 = new DateTime();
        DateTime d2 = new DateTime();
        Console.WriteLine(object.ReferenceEquals(d1, d2));
        //  Output: False (Awesome)

        string s1 = string.Empty;
        string s2 = string.Empty;
        Console.WriteLine(object.ReferenceEquals(s1, s2)); 

        //  Output: True(What? how is it possible?)

In case of string's different instances comparison it gives me True, ideally it should give me False because both the instances are not same.

Can any one help me to short out this logic.

Waiting for reply.