ASp.Net day

Micro blog



About Satalaj

www.satalaj.com

The best inline translator

Live lookup to see what asp.net developers are searching





net forms authentication       by Satalaj 8. January 2010 13:27
    

How quickly, I can set forms authentication to allow access for only one user!

In web.config authentication section you need to add below code

<authentication mode="Forms">
   <forms defaultUrl="~/accounts/authuser.aspx" loginUrl="login.aspx" slidingExpiration="true" >
    <credentials>
     <user name="admin" password="password"></user>
    </credentials>
   </forms>
  </authentication>

You can see here I have added credentials tag and added admin user their with password as password.

Now, I will let him login to system useing below code


        if(!FormsAuthentication.Authenticate( txtUserName.Text , txtPassword.Text ))
        {
             FormsAuthentication.RedirectToLoginPage();
        }
        else
        {
            // FormsAuthentication.SetAuthCookie( txtUserName.Text, true);
            FormsAuthentication.RedirectFromLoginPage(txtUserName.Text,true)
        }

FormsAuthentication.Authonticate will validate the user against Forms credentials stored in web.config file.

If user is not valid, you can redirect him back to LoginPage
FormsAuthentication.RedirectToLoginPage();


FormsAuthentication.RedirectFromLoginPage(txtUserName.Text,true)

It will redirect the user from login page to authorised page and it will set authontication cookie at client side browser.

Satalaj

     

Do you want to view only the webpage content that was delivered securely       by Satalaj 30. September 2009 08:25
    


If your page is requestiong data from Insecure zone http:// you will see below warning. 

"  Do you want to view only the webpage content that was delivered securely "

Those data can be from Script, images or Iframe.

If you are accesing web using Https:// make sure, all requests requested by your page are coming from Https:// and not from http://.


     

ASP.net read email hotmail       by Satalaj 29. September 2009 12:54
     kick it on DotNetKicks.com


    Days ago I come across the post saying hotmail is offering pop3. So I re-written my previos read gmail pop3 code to see how it works with hotmail.
This article will read your first hotmail email.  I have explained the commands that we can use with POP3.
I'm using ASP.net with C#.net and TcpIPClient to read email.
I saw many developers are searching for the code to read an email programatically.

I have created test user to use below code.

UserName:
satalajmore@hotmail.com
password:
Passw@rd


using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.IO;

using System.Net.NetworkInformation;

using System.Net.Security;

using System.Net.Sockets;

public partial class pop : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected void Button1_Click(object sender, EventArgs e)

{

try

{

// create an instance of TcpClient

TcpClient tcpclient = new TcpClient();

// HOST NAME POP SERVER and gmail uses port number 995 for POP

tcpclient.Connect("pop3.live.com", 995);

// This is Secure Stream // opened the connection between client and POP Server

System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream());

// authenticate as client

sslstream.AuthenticateAsClient("pop3.live.com");

//bool flag = sslstream.IsAuthenticated; // check flag

// Asssigned the writer to stream

System.IO.StreamWriter sw = new StreamWriter(sslstream);

// Assigned reader to stream

System.IO.StreamReader reader = new StreamReader(sslstream);

// refer POP rfc command, there very few around 6-9 command

sw.WriteLine("USER satalajmore@hotmail.com");

// sent to server

sw.Flush();

sw.WriteLine("PASS Passw@rd");

sw.Flush();

// RETR 1 will retrive your first email.

// It will read content of your first email.

sw.WriteLine("RETR 1");

sw.Flush();

// close the connection

sw.WriteLine("Quit ");

sw.Flush();

string str = string.Empty;

string strTemp = string.Empty; while ((strTemp = reader.ReadLine()) != null)

{

// find the . character in line

if (strTemp == ".")

{

break;

}

if (strTemp.IndexOf("-ERR") != -1)

{

break;

}

str += strTemp;

}

Response.Write(str);

Response.Write("<BR>" + "Congratulation.. ....!!! You read your first hotmail email ");

}

catch (Exception ex)

{

Response.Write(ex.Message);

}

}

}

Note* there are very few commands required to communicate with pop3 server.

You can use below commands to perform the operations on your pop3 server.

For more details about below command please refer RFC
http://www.ietf.org/rfc/rfc1939.txt 
 

 e.g.

1. LIST 
2.
RETR
3. 
STAT
4.
USER
5.
PASS
6.
DELE
7. QUIT


You can use above command instead of RETR

sw.WriteLine("STAT 1");

sw.Flush();


I'm using System.Net.Security.SslStream becaus hotmail accepts secure socket.


-Satalaj

     

Membership count online users       by Satalaj 10. September 2009 08:17
    

 Some time we need to count the online users 

If you are new to ASP.net Membership provider,

please refer
http://www.revenmerchantservices.com/page/ASpnet-20-step-by-step-Membership-Provider-.aspx

Below code will count online users

C# Code
MembershipUserCollection uc = Membership.GetAllUsers();

    int count=0; 
  foreach(MembershipUser u in uc)
  {
     if(u.IsOnline)
      count++;
  }


VB Code

Dim uc As MembershipUserCollection = Membership.GetAllUsers()
Dim count As Integer = 0
For Each u As MembershipUser In uc
    If u.IsOnline Then
        count += 1
    End If
Next
You can bind the online user names to ListBox using below code

C# code

System.Collections.Generic.List<string> lstUser = new System.Collections.Generic.List<string>();


        MembershipUserCollection uc = Membership.GetAllUsers();
       
        foreach (MembershipUser u in uc)
        {
            if (u.IsOnline)
               
                lstUser.Add(u.UserName);

        }

        ListBox1.DataSource = lstUser;
        ListBox1.DataBind();


VB code

 System.Collections.Generic.List<string> lstUser = new System.Collections.Generic.List<string>();


        MembershipUserCollection uc = Membership.GetAllUsers();
       
        foreach (MembershipUser u in uc)
        {
            if (u.IsOnline)
               
                lstUser.Add(u.UserName);

        }

        ListBox1.DataSource = lstUser;
        ListBox1.DataBind();


Satalaj

     

whois telnet port 43       by Satalaj 28. July 2009 04:07
    

  In this post we will see how simply we can get the WHOis  information using command prompt and Telnet command.
There are only five Regional Internet Registries

All Ip addresses are registered there. You can query their database using below steps.


For  IP addresses belonging to Region America  you need query  whois.arin.net  database  (ARIN  Ameerican Registery for internet numbers https://www.arin.net/ )

For IP addresses in Acia region, query  whois.apnic.net  database  (APNIC Asia Pacific Network Information Centre   http://www.apnic.net/ )

Let us query my site IP 68.178.232.73

1. Open your command prompt and type Telnet to open connection with Database on port 43
   
   

 C:\>telnet whois.apnic.net  43       
     # ARIN WHOIS database, last updated 2009-07-27 20:00
     # Enter ? for additional hints on searching ARIN's WHOIS database.  
 

2. Now, we are connected with Arin Database. type the Ip address whos info you want to query in this case it is 68.178.232.73
   you will get below info  about where it is registererd 
   
 OrgName:    GoDaddy.com, Inc.
                  OrgID:      GODAD
               Address:    14455 N
Hayden Road
               Address:    Suite 226
                     City:    Scottsdale
             StateProv:  AZ
           PostalCode:  85260
               Country:    US
             NetRange:   68.178.128.0 - 68.178.255.255
                   CIDR:       68.178.128.0/17
              NetName:    GO-DADDY-SOFTWARE-INC
             NetHandle:  NET-68-178-128-0-1
                  Parent:  NET-68-0-0-0-0
               NetType:    Direct Allocation
        NameServer: CNS1.SECURESERVER.NET
        NameServer: CNS2.SECURESERVER.NET
        NameServer: CNS3.SECURESERVER.NET
            Comment:
             RegDate:    2005-04-12
             Updated:    2007-06-14
     OrgAbuseHandle: ABUSE51-ARIN
     OrgAbuseName:   Abuse Department
     OrgAbusePhone:  +1-480-624-2505
     OrgAbuseEmail: 
abuse@godaddy.com

     OrgNOCHandle: NOC124-ARIN
     OrgNOCName:   Network Operations Center
     OrgNOCPhone:  +1-480-505-8809
     OrgNOCEmail: 
noc@godaddy.com

     OrgTechHandle: NOC124-ARIN
     OrgTechName:   Network Operations Center
     OrgTechPhone:  +1-480-505-8809
     OrgTechEmail: 
noc@godaddy.com

                 # ARIN WHOIS database, last updated 2009-07-27 20:00
                                                                     # Enter ? f
or additional hints on searching ARIN's WHOIS database.

 
         

You can try my own developed whois lookup http://satalajwhois.codeplex.com/    using ASP.net with C#.
It can query almost all domain extensions. If it fails you can register it into whois server list  xml file in project.

Satalaj.

     

C# Online users       by Satalaj 11. June 2009 09:26
    

   You can get who is online and how many users online using ASP.net 
you need to configure your Database and Web application to use ASp.net membership provider
After configuring add lbOnlineUsers as a listbox in your page to display who is online

Below code will return number of users online and who is online 

 

System.Collections.Generic.List<string> lstUser = new System.Collections.Generic.List<string>();

int numberOfOnlineUsers = Membership.GetNumberOfUsersOnline();

foreach(MembershipUser u in Membership.GetAllUsers())
      
 // Membership.GetAllUsers will returm MembershipCollctions which holds individual Membership User objects 

 {
    if(u.IsOnline) 
   { 
     lbOnlineUsers.Items.Add(u.UserName); 
   } 
 } 
 

 This way online users will get added to listBox control on Page

Some cool stuff about Membership provider can be found at http://www.revenmerchantservices.com/search.aspx?q=membership

 

     

secure image       by Satalaj 10. October 2008 06:05
      In this post we will secure image /files  from being accessed by anonymous users.
In ASP.net 2.0 web.config  we will add 6 lines of code.
 Scenario: I have stored all images in images folder found at the root. I will add below web.config file to my images folder.
It will let the users who are in role Editor of  site to access and it will ban anonymous users . 
 
 <?xml version=
"1.0"?> 
    
<configuration>
    <appSettings
/>
    <connectionStrings
/>
      <system.web
>
            <authorization
>
                  <deny users=
"?"/>
                  <allow roles="Editor"/>
 
          </authorization>
      </system.web
>
  
</configuration> 

Eventually, whatever you store inside the images folder will not be accesible to users who are not in role Editor.


To see how we can use asp.net membershipprovider based model please refer http://revenmerchantservices.com/page/ASpnet-20-step-by-step-Membership-Provider-.aspx
     

formsauthenticationticket       by Satalaj 4. June 2007 04:09
    

Here Andrew Zhu, has explained how to generate  net formsauthentication asp.net.

Assume you are using FormsAuthentication.RedirectFromLoginPage() to direct user's request after loging in.

Now, you want the request to be redirected to different pages up to different users. you may need to write you own code to achieve this:

Validate user using Membersip

if (Membership.ValidateUser(TextBox1.Text, TextBox2.Text)) 
 
  {
   // Generate FormsAuthentication ticket
            FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(TextBox1.Text, true, 10);
   // FormsAuthntication encrypt ticket
            string cookiestring = FormsAuthentication.Encrypt(tkt);
   //Create cookie FormsAuthentication Cookie
            HttpCookie httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestring);
   // Give cookie FormsAuthnetication Cookie path
            httpCookie.Path = FormsAuthentication.FormsCookiePath;
   // Send cookie in response
            Response.Cookies.Add(httpCookie);

            //then, redirect whatever page you want here

            Response.Redirect("url");
}