23 May 2010

Show Session Timeout countdown on ASP.NET page

Hi,

I came across a really nice feature that you can use in ASP.NET to show session timeout to users. This provides rich user experience. I used javascript to create this facility. Hope this will help someone looking for the solution.

 var timeout = '<%= Session.Timeout * 60 * 1000 %>';  
 var timer = setInterval(function() { timeout -= 1000; document.getElementById('countDown').innerHTML = time(timeout); if (timeout == 0) { clearInterval(timer); alert('Your session has expired!') } }, 1000);  
 function two(x) { return ((x > 9) ? "" : "0") + x }  
 function time(ms) {  
 var t = '';  
 var sec = Math.floor(ms / 1000);  
 ms = ms % 1000  
 var min = Math.floor(sec / 60);  
 sec = sec % 60;  
 t = two(sec);  
 var hr = Math.floor(min / 60);  
 min = min % 60;  
 t = hr+":"+two(min) + ":" + t;  
 return "You session will timeout in " + t ;  
 }  


add a span named countDown to the page where you want to display this session timeout message. If you want it to display on all the pages once user is logged in then put it in Master page and voila !!! Your session timeout message will be there to warn user.

 <span id="countDown">  
  </span>  

14 April 2010

Creating Custom Membership Provider for Login Control in ASP.NET

You may have came across the situation where you want to use .NET's membership provider facility but don't want to use tables and stored procedures generated by aspnet_regsql.exe . You want to use your own simple Users table in your own database with just few fields like UserID, Password and Role. It may seems like a big task to create your own Membership Provider to use your own login logic but it is not that hard. Just follow the steps below :

1 > Create your own Membership Provider Class and inherit it from base MembershipProvider class. If you are using VB.NET the needed methods are added automatically. If you are using C# just right click the MembershipProvider class and add the properties and methods . Don't forget to import System.Configuration.Provider namespace.

The IDE will generate all the methods and properties and you don't have to implement all of them.

The only method that you need to implement is ValidateUser(string username, string password)

You can leave all the other methods throw an exception unless you explicitly want the facility provided by non implemented method.


public class MyCustomMemershipProvider : MembershipProvider  
 {  
 public int TryLogin(string id, string pass) // My own login method  
 {  
 int roleId = 0;  
 DatabaseUtilityHelper databaseHelper = new DatabaseUtilityHelper();  
 SqlConnection con = databaseHelper.GetBBCDatabaseConnection();  
 SqlParameter[] agentParams = new SqlParameter[] {  
 new SqlParameter("@UserId",id),  
 new SqlParameter("@Password",pass)};  
 con.Open();  
 SqlDataReader reader = DatabaseUtility.ExecuteReader(con, "login_user", CommandType.StoredProcedure, agentParams);  
 if (reader.Read())  
 {  
 roleId = Int32.Parse(reader.GetSqlValue(1).ToString());  
 }  
 else  
 {  
 roleId = 0;  
 }  
 con.Close();  
 return roleId;  
 }  
 public override string ApplicationName  
 {  
 get  
 {  
 throw new NotImplementedException();  
 }  
 set  
 {  
 throw new NotImplementedException();  
 }  
 }  
 .....  
 ..... // Generated Code  
 ....  
 ....  
 public override bool ValidateUser(string username, string password)  
 {  
 int result = TryLogin(username, password);  
 if (result > 0)  
 {  
 return true;  
 }  
 else  
 {  
 return false;  
 }  
 } 


2 > Add CustomeMemberShip Provider to your web.config




 <membership defaultProvider="MyCustomMemershipProvider">  
 <providers>  
 <clear/>  
 <add  
 name="MyCustomMemershipProvider"  
 type="BBCApplication.BusinessLogic.MyCustomMemershipProvider"/>  
 </providers>  
 </membership>  


3.> Add Membership Provider for your login control on Login.aspx page.

In the Properties window of the Login control set MembershipProvider to your MyCustomeMembershipProvider class.

That is it.
Off you go to your own login logic with custom membership provider.

20 November 2009

Set NTFS folder permissions on remote machine using .NET and WMI

After considerable amount of efforts and trial I was finally able to hack the solution to set NTFS permissions on a remote machine using .NET. For local file system it is just couple of line of codes and it works like a charm but when it comes to remote machines it just gives you a nightmare . So here goes my solution. I am sure this will help someone.

public bool SetPermissions(string remoteDir, string MachineName, string UserName, string Password) // Username and Password is of Admin account on remote machine
{
string TempName = remoteDir;
int Index = TempName.IndexOf(":");
string DriveLetter = ConfigurationManager.AppSettings["ShareDriveLetter"]; // e.q. C
if (Index != -1)
{
string[] arr = TempName.Split(new char[] { ':' });
DriveLetter = arr[0];
TempName = TempName.Substring(Index + 2);
}

ManagementPath myPath = new ManagementPath();
myPath.NamespacePath = @"root\CIMV2";

ConnectionOptions oConn = new ConnectionOptions();
oConn.Username = UserName;
oConn.Password = Password;
oConn.EnablePrivileges = true;
myPath.Server = MachineName;

ManagementScope scope = new ManagementScope(myPath, oConn);
scope.Connect();
//without next strange manipulation, the os.Get().Count will throw the "Invalid query" exception
remoteDir = remoteDir.Replace("\\", "\\\\");
ObjectQuery oq = new ObjectQuery("select Name from Win32_Directory where Name = '" + remoteDir + "'");
using (ManagementObjectSearcher os = new ManagementObjectSearcher(scope, oq))
{
if (os.Get().Count == 0) //It don't exist, so create it!
{
ManagementPath path2 = new ManagementPath();
path2.Server = MachineName;
path2.ClassName = "Win32_Process";
path2.NamespacePath = @"root\CIMV2";
ManagementScope scopeProcess = new ManagementScope(path2, oConn);

using (ManagementClass process = new ManagementClass(scopeProcess, path2, null))
{
//Command line that you want to execute on remote machine
string commandLine = @"cmd /C cacls " + TempName +" /C /T /E /P "+"0909020:F"; // 0909020:F is username:permissions

using (ManagementBaseObject inParams = process.GetMethodParameters("Create"))
{
inParams["CommandLine"] = commandLine;
inParams["CurrentDirectory"] = DriveLetter + @":\\";
inParams["ProcessStartupInformation"] = null;
using (ManagementBaseObject outParams = process.InvokeMethod("Create", inParams, null))
{
int retVal = Convert.ToInt32(outParams.Properties["ReturnValue"].Value);

return (retVal == 0);
}
}
}



}
else
{
return true;//if exists, return true; you may want to return false, of course
}
}
return false;
}

08 October 2009

Microsoft launches Windows smartphones : My view on it

Microsoft is in a battle to reincarnate its dinosaur mobile OS with launch of its own smartphone.The phones, which combine the ability to make calls, surf the internet and view videos, carry Microsoft's Windows Mobile 6.5 operating system.I know you will go like Hey don't we already have that. Don't you think it is too little too late !!! The smartphone market is already saturated with lots of different OS and the major ones like Apple's iPhone system, Plam OS, Google's Android (which is a free platform) and Symbian OS. The new venture Microsoft is attempting is just a desperation to gain market that it already lost to big guys like Google and Apple. In a official launch Mr. Ballmer said "We have taken the Internet Explorer browser technologies, and we rebuilt them for the first time for these Windows phones. So you can get the same experience on these phones that you will get on your windows PC." (Hey watch out, The Blue Screen Of Death (BSOD) is coming to your smartphones !!!) Is that the way you promote your technology. A reincarnated IE ??? Lets face it IE is no where near the facilities provided by other browsers like Mozilla Firefox and with the new kid on the block called Crome which is improving at a speed of light (Well that is an exaggeration but you know what I mean !!!). Microsoft needs to come up with something new that is authentic and that can make others to follow it rather than just trying to get the market that is already saturated. Get a life Microsoft and you really needs some great minds to think of products Mr. Ballmer !!!

03 October 2009

Google Wave: What is it ?


There is a new Google product called Google Wave currently under limited preview. Some of you may have already tried it or at least looked at its video or you may not have any idea about whatsoever. In a simple term it a mashup of emails,documents and social networking. Don't scratch your head. Just go to google and google it! (How ironic !!!). You can look at a video on youtube that explains it in a simple terms. and if you want to get a detailed explanation of it go to Google Wave's website and spare yourself an hour of amazement.

Here is a simple explanation of what you can do with google wave.
For Example you want to know more about Sydeny Opera House. So you start a new wave with this topic and invite your friends. Once they join the wave they can comment on it and everyone who are in the wave can view it and provide their opinion. You will go so whats a big deal here ? You can also share photographs and documents. It can be a really good collaboration platform.

So head out to Google Wave and enjoy it.

30 May 2009

Microsoft's Bing search engine comming soon



Did you heard the news ? What news ? Hey don't worry its not new development in Swine Flue pandemic ! Microsoft is launching its new search engine. You will say don't they have one called "Live". "May be its time for Live to be dead and get reincarnation as a Bing." The reason they are coming up with new search engine is the Live search is not giving them revenue they are expecting and Google is dominating the search engine market and certainly making its more than 90% revenue out of it. So the big guy (Microsoft) want big chunk of the pie rather then just a piece.

Microsoft CEO Steve Ballmer in San Diego during D7 Conference officially launched its new search engine called Bing that previously code named as "Kumo". Microsoft is calling it a decision engine rather than a search engine. Hey don't worry it gives you the search result only not the decision on what to eat today !!!

I have a look at its video and first impression was really awesome.I am not exaggerating.Check out its video Here . You can get more information on Bing Here.


It may be the time for Google to worry a bit. Well it takes a really big effort to get people to use new search engine. "Google become more of a verb than a noun in last decade." Google will certainly reply back to Bing with whatever it takes to sustain its position. Microsoft is also launching $80 to $100 million advertising campaign to promote Bing. By the time, lets enjoy this new battle as it progress and get the most out of it.

17 May 2009

Google's new features : Wonder wheel


Hey, Did anyone noticed Google's new feature when you search something. It gives you more control over your search query. You can see the hyperlink came up when you search something called Show options.... You click on it and magic happens.... well you will say what is new with that options panel. But as you can notice it allows you to filter your result with regards to the time articles published, if you want to see only videos or forums or reviews and there is something very special called wonder wheel. You click on it and it gives you the options to further refine your result. It is really cool.!!!



For example you search for car dealers in sydney and click on the wonder wheel and it automatically refine your search result and allow you to pick up options to go for particular area in sydney and when you choose something it further gives you the options to choose type of car you want. I find it really cool and I am sure you will also enjoy it. Though it is a good option for end users it is a pain in ass for Search Engine Optimization (SEO) guys as they have to take into account this new feature and try to rank their websites for all possible keywords. It will certainly take time for people to get used to with this new feature and use it more frequently and by that time SEO guys needs to come up with solutions to fool this wonder wheel. I hope they will find out something very soon otherwise they are in trouble.
By the time enjoy coffee... and think of ideas.....