Tuesday, October 22, 2013

Garbage collector technique in C#

Garbage collector technique in C#

Garbage collection is a nice feature of .NET. It prevents memory leakage. In this tutorial we will discuss about garbage collection in C# and how to use GC class to collect object.
Generally garbage collection technique is automotive process. Means no one need to call garbage collection program. When it finds that there is need for memory, it runs itself and removes unused object from memory.
Generally we know that, we write destructor to destroy the object which is created by constructor. Bur in .NET destructor not runs automatically. Let us see how it works.
using System;
using System.Collections;
using System.Globalization;
using System.Data.SqlClient;
using System.Data;
 
namespace Test1
{
   public class Garbage   {
          public Garbage()
          {
            Console.WriteLine("Reserve memory");
          }
          ~Garbage()
          {
              Console.WriteLine("Free memory");
          }
 
   }
    class Program    {
        static void Main(string[] args)
        {
 
            {
                Garbage g = new Garbage();
  g = null;
 
            }
            Console.ReadLine();
        }
    }
}
 
Garbage collector technique in C#
Use GC.Collect to free memory
If we want to free all unused object from memory, we call garbage collector explicitly using GC.collect() method. Here is GC is garbage collector class. In below example we are removing all unused object from memory using GC.collect() .
using System;
using System.Collections;
using System.Globalization;
using System.Data.SqlClient;
using System.Data;
 
namespace Test1
{
   public class Garbage   {
          public Garbage()
          {
            Console.WriteLine("Reserve memory");
          }
          ~Garbage()
          {
              Console.WriteLine("Free memory");
          }
 
   }
    class Program    {
        static void Main(string[] args)
        {
 
            {
                Garbage g = new Garbage();
                g = null;
                GC.Collect();
            }
            Console.ReadLine();
        }
    }
}
  Garbage collector technique in C#
Memory free before and after collection
If we want we can measure how much memory got free after garbage collection using GetTotalMemory() function of GC class. Have a look on below example.
using System;
using System.Collections;
using System.Globalization;
using System.Data.SqlClient;
using System.Data;
 
namespace Test1
{
   public class Garbage   {
          public Garbage()
          {
            Console.WriteLine("Reserve memory");
          }
          ~Garbage()
          {
              Console.WriteLine("Free memory");
          }
 
   }
    class Program    {
        static void Main(string[] args)
        {
 
                
                Garbage g = new Garbage();
                g = null;
                Console.WriteLine("Total memory before free: - " +   GC.GetTotalMemory(false));
                GC.Collect();
                Console.WriteLine("Total memory before free:- " +   GC.GetTotalMemory(false));
            
         Console.ReadLine();
        }
    }
}
 
 
Garbage collector technique in C# 


forms authentication in asp.net

Introduction
In this article, I am going to explain how to Role based security using Forms Authentication.

forms authentication in asp.net
For the demo purpose, I have create a xml file and stored UserName, Passwod, and Roles in xml file and I will validate the user using that xml file data. In real scenario, you can use database to store username, password and roles into the database. Please note that you should store the roles of the user as comma separated values if a user have multiple roles (eg. "Admin, User" or "User" in case of single role).
Lets see how to create Role based security using Forms Authentication in easy to follow steps. I am assuming that you already have Login page ready after going through my previous article Forms Authentication in ASP.NET with C#: Basic
Create a New Project
Create a new project, you can use Visual Web Developer or Visual studio to do that and create folder structure like below.
forms authentication in asp.net
Notice that I have create Admin, Secure and User folder to differentiate the access based on roles of the user. In my case Admin folder will have access to only those request whose role is "Admin" and "User". User folder will have access to only those request whose role is "User" and Secure folder will have access to all users who are atleast authenticated, irrespective of what role they have. Every folder has an .aspx file showing Welcome message as shown in the 1st picture above.
Create Web.Config file setting
Add following Authentication setting into your web.config file under <system.web>.
< authentication mode = " Forms " >

< forms defaultUrl = " default.aspx " loginUrl = " ~/login.aspx " slidingExpiration = " true " timeout = " 20 " ></ forms >
</ authentication >
For every user if you want to secure a particular folder, you can place setting for them either in parent web.config file (root folder) or web.config file of that folder.
Specify Role settings for the folder in root web.config file (in this case for Admin)
< location path = " Admin " >

< system.web >

< authorization >

< allow roles = " admin " />
< deny users = " * " />
</ authorization >
</ system.web >
</ location >

Write this code outside <system.web> but under <configuration> tag in the root's web.config file. Here, I am specifying that if the path contains the name of folder Admin then only user with "admin" roles are allowed and all other users are denied.
Specify Role settings for the folder in folder specific web.config file (in this case for User)
< system.web >

< authorization >

< allow roles = " User " />
< deny users = " * " />
</ authorization >
</ system.web >
Write this code into web.config file user folder. You can specify the setting for the user in root's web.config file too, the way I have done for the Admin above. This is just another way of specifying the settings. This settings should be placed under <configuration> tag.
Specify setting for Authenticated user
< system.web >

< authorization >

< deny users = " ? " />
</ authorization >
</ system.web >
Write this code into web.config file of the Secure folder. This is specifying that all anonymus users are denied for this folder and only Authenticated users are allowed irrespective of their roles.
Authenticating Users
Assuming you have gone through my previous article mentioned above, you have a login page. Now when user clicks Login button Authenticate method fires, lets see code for that method.
protected void Login1_Authenticate( object sender, AuthenticateEventArgs e)
{

string userName = Login1.UserName;
string password = Login1.Password;
bool rememberUserName = Login1.RememberMeSet;

// for this demo purpose, I am storing user details into xml file
string dataPath = Server.MapPath( "~/App_Data/UserInformation.xml" );
DataSet dSet = new DataSet ();
dSet.ReadXml(dataPath);
DataRow [] rows = dSet.Tables[0].Select( " UserName = '" + userName+ "' AND Password = '" + password + "'" );
// record validated
if (rows.Length > 0)
{

// get the role now
string roles = rows[0][ "Roles" ].ToString();

// Create forms authentication ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (
1, // Ticket version
userName, // Username to be associated with this ticket
DateTime .Now, // Date/time ticket was issued
DateTime .Now.AddMinutes(50), // Date and time the cookie will expire
rememberUserName, // if user has chcked rememebr me then create persistent cookie
roles, // store the user data, in this case roles of the user
FormsAuthentication .FormsCookiePath); // Cookie path specified in the web.config file in <Forms> tag if any.
// To give more security it is suggested to hash it
string hashCookies = FormsAuthentication .Encrypt(ticket);
HttpCookie cookie = new HttpCookie ( FormsAuthentication .FormsCookieName, hashCookies); // Hashed ticket
// Add the cookie to the response, user browser
Response.Cookies.Add(cookie);
// Get the requested page from the url
string returnUrl = Request.QueryString[ "ReturnUrl" ];
// check if it exists, if not then redirect to default page
if (returnUrl == null ) returnUrl = "~/Default.aspx" ;
Response.Redirect(returnUrl);
}
else // wrong username and password
{

// do nothing, Login control will automatically show the failure message
// if you are not using Login control, show the failure message explicitely
}
}

In the above method, I have used UserInformation.xml file that contains the credentials and role information for the user. The whole code is available as download (above)
I am reding the xml file and getting all the users credential into the DataSet and using DataTable.Select method, I am filtering the record based on username and password. If I found a record then I am adding the FormsAuthentication ticket into cookie after encrypting it and redirecting to the requested url if any otherwise on the default page. Notice that I have not used FormsAuthenticate standard method FormsAuthentication.RedirectFromLoginPage method to redirect from the login page after authenticating users, as this will not set the users role into the cookie and I will not be able to validate users based on the role. To add the roles of the user into the Authentication ticket, I have used FormsAuthenticationTicket class and passed required data as parameter (Notice that roles has been passed as UserData parameter of the FormsAuthenticationTicket constructor).
Till now we have set the Forms Authentication ticket with required details even the user roles into the cookie, now how to retrive that information on every request and find that a request is coming from which role type? To do that we need to use Application_AuthenticateRequest event of the Global.asx file. See the code below.
protected void Application_AuthenticateRequest( object sender, EventArgs e)
{

// look if any security information exists for this request
if ( HttpContext .Current.User != null )
{

// see if this user is authenticated, any authenticated cookie (ticket) exists for this user
if ( HttpContext .Current.User.Identity.IsAuthenticated)
{

// see if the authentication is done using FormsAuthentication
if ( HttpContext .Current.User.Identity is FormsIdentity )
{

// Get the roles stored for this request from the ticket
// get the identity of the user
FormsIdentity identity = ( FormsIdentity ) HttpContext .Current.User.Identity;
// get the forms authetication ticket of the user
FormsAuthenticationTicket ticket = identity.Ticket;
// get the roles stored as UserData into the ticket
string [] roles = ticket.UserData.Split( ',' );
// create generic principal and assign it to the current request
HttpContext .Current.User = new System.Security.Principal. GenericPrincipal (identity, roles);
}
}
}
}
In this even, after checking if user exists, he/she is authenticated and the identy type of th user is FormsIdentity, I am getting the current Identity of the user and getting the ticket I have set at the time of Authentiacting. Once I have the authenticated ticket, I just got the UserData from the ticket and split it to get roles (remember, we had stored the roles as comma separated values). Now, we have current users roles so we can pass the roles of the current user into the GenericPrincipal object along with the current identity and assign this to the curent user object. This will enable us to use the IsInRole method to check if a particular user belongs to a particular role or not.
How to Check if user has a particular role?
To check if a user belong to a particulr role, use below code. This code will return true if the current record is coming from the user who is authenticated and has role as admin.
HttpContext .Current.User.IsInRole( "admin" )

How to check if user is authenticated?
To check if the user is authenticated or not, use below code.
HttpContext .Current.User.Identity.IsAuthenticated
To get UserName of the Authenticated User
HttpContext .Current.User.Identity.Name

If you have followed steps, you should test it by runnig your application. Try logging in as Admin and you will be able to access all pages (Admin, User, Secure, Home). Try logging in as User and you will be able to access User, Secure, Home but not Admin. Try logging in as Secure and you will be able to access Secure, Home but not Admin, User. Try to visit all link and you will be able to access only Home link.
Please feel free to download the sample project from above link and use it. Hope this will be usefull for readers of this website. Please let me kow if you have any feedback or comments. Thanks and happy coding !!!


Source: http://dotnetfunda.com/articles/show/141/forms-authentication-in-aspnet-with-csharp-advance

Friday, October 4, 2013

Post on facebook wall

<a id="fb-share" style='text-decoration:none;' type="icon_link" onClick="window.open('http://www.facebook.com/sharer.php?s=100&amp;
p[title]=foo&amp;
p[summary]=bar&amp;
p[url]=https://www.foobar.com/&amp;
p[images][0]=https://www.foobar.com/thumb.gif','sharer','toolbar=0,status=0,width=580,height=325');"
href="javascript: void(0)">
Share on fb
</a>

Thursday, October 3, 2013

How to use fckeditor in asp.net

 How to use fckeditor in asp.net
1. Download Fckeditor source code from the following link:
2. Create new/ Open existing web project/ website:
How to use fckeditor in asp.net
3. Copy Fckeditor source code folder and paste it to website root directory:
How to use fckeditor in asp.net
4. Copy Fckeditor FredCK.FCKeditorV2.dll file from source code and paste it to website Bin folder:
How to use fckeditor in asp.net
5. You have to register FCKEditor to use it in your page. There are two ways to register it.
a) Manual: The following script will register it. You have add this script in every page where you want to use FCKEditor.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
 Inherits="FCKEditorDemo._Default" %>

<%@ Register TagPrefix="FCKeditorV2" Namespace="FredCK.FCKeditorV2" 
 Assembly="FredCK.FCKeditorV2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>FCKEditor Demo : Amit Shah</title>
</head>
<body>
    <form id="form1" runat="server">
      <div align="center" width="70%">
          <hr />
          <h1>
              FCKEditor Demo : By Amit Shah</h1>
          <hr />
      </div>    
      <div>
           <FCKeditorV2:FCKeditor ID="FCKeditor1" runat="server" 
  BasePath="~/fckeditor/" Height="300px"
               Width="70%">
           </FCKeditorV2:FCKeditor>
      </div>
     </div>
    </form>
</body>
</html>
b) From Toolbar: You can otherwise, you can browse FCKEditor by right clicking on Toolbar >> Choose Items. A dialog box will appear as shown in the following image. Select .NET Framework Components >> Click on Browse button located at right hand bottom. Choose the .dll of FCKEditor from the bin directory of your application. An item called FCKEditor will be added to your Toolbar. Now you are ready to drag and drop editor in your page. If you place editor in your page, it will also add same code in your web page as we have done in the manual method.
How to use fckeditor in asp.net
6. Run website, you can see the FCKEditor in your browser with default theme and default English language.
How to use fckeditor in asp.net

How to Apply Theme?

FCKEditor has a great theming feature. User can apply the theme in two ways. One way is dynamically and another statically. The site of FCKEditor provides 3 themes to be downloaded. There are many third party open source themes available to download. I have shared few themes with this article, which you can find in the demo project attached with this article.
Now, how can we assign default theme and apply dynamic theme?
The answer is here: First of all, you can set default theme from fckconfig.js placed in FCKEditor folder, look at the below code:
  FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/Default/';
//FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/silver/';
//FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/SilverNarrow/';
//FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/office2003/' ;
//FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/office2007/';
//FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/ChroomDeluxe/';
//FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/Aluminum/';
//FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/Obi-D_V1/';
//FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/Office2003Blue/';
You can also set the language from .aspx /html /php page where you have declared Fckeditor.
Just set the SkinPath Property.
Now run the application. You can view the office2003 theme in Fckeditor as you have set in the above page.
How to use fckeditor in asp.net

How to Apply Language?

Fckeditor provides a great multiple language support feature. User is able to change the language dynamically or set default language as per website language. 
Fckeditor provides 56 languages that you can use as per your requirement.
Now, how can we assign default language or apply dynamic language?
The answer is here: 
First of all, you can set default language from fckconfig.js, look at the below code:
FCKConfig.AutoDetectLanguage = false ;
FCKConfig.DefaultLanguage = 'en' ;
FCKConfig.ContentLangDirection = 'ltr' ;
You can also set the language from .aspx /.html /.php page where you have declare Fckeditor.
Just set the DefaultLanguage Property.
How to use fckeditor in asp.net
Now run the application. You can view the Arabic language in Fckeditor as you have set in the above page.

How to use fckeditor in asp.net