Posts tagged "download different Types Of Compilers in C#"

Getting elevated privileges on demand using C#


With going on stage Windows Vista and Windows 7 later on and new user security paradigm introduction (UAC), it becomes necessary to support such behavior when elevated privileges are required to perform some portion of code base, i.e. writing to registry, modifying files under system protected folders, etc.

So, in general, there are two ways to implement such behavior:

Embed a manifest info executable to indicate that the application requires elevated privileges from the beginning and can’t be run without gaining administrative rights at all. Here’s an example of such manifest:
Separate the code base into two parts: the first doesn’t require elevated privileges and the second – does, so call one from another. The article covers a case when the calling application is a console with a number of command line arguments: some of them can be run in normal mode and some – only with administrative rights.

Usually the part of the program requires elevated privileges is a settings form which writes to Windows registry when the core functionality – don’t.

Another case – a console application where core functionality requires elevated privileges and some helpers – such as help message displaying – don’t.

Let’s declare the skeleton of such console application.

Entry point method parses input command line arguments and branches the flow control relying on the parse results wrapped into a object:

static void Main(string[] args){ // wrap command line arguments to an object Core.Settings = ApplicationSettingsParser.Parse(args); if (Core.Settings.UsageFlag || (args.Length == 0)) { // run without elevated privileges PrintUsage(); } else if (!Core.Settings.EngageFlag) { // runs with the same arguments plus flag mentioning the main action performing var info = new ProcessStartInfo( Assembly.GetEntryAssembly().Location, String.Join(” “, Enumerable.Concat(args, new[] { “–engage” }))) { Verb = “runas”, // indicates to eleavate privileges }; var process = new Process { EnableRaisingEvents = true, // enable WaitForExit() StartInfo = info }; process.Start(); process.WaitForExit(); // sleep calling process thread until evoked process exit } else if (Core.Settings.EngageFlag) { // do stuff under elevated privilegesConsole.WriteLine(“Elevated privileges gained={0}”, Core.IsElevated); }}

Here’s a method just displaying a sample help message:

private static void PrintUsage(){ Console.WriteLine(“Usage: ElevatedPrivilegesOnDemand.exe –do [--engage] | -?”);}

Parsing method is placed into a dedicated helper:

public static ApplicationSettings Parse(string[] args){ var settings = new ApplicationSettings(); for (int i = 0; i < args.Length; i++) { var param = args[i]; switch (param) { case "-?": { // stop further parsing and return only meaning flag return new ApplicationSettings() { UsageFlag = true }; } case "--do": { settings.DoFlag = true; break; } case "--engage": { settings.EngageFlag = true; break; } } } return settings;}

Which returns a POCO object keeping settings:

class ApplicationSettings{ public ApplicationSettings() { // default settings setup } public bool DoFlag { get; set; } public bool EngageFlag { get; set; } public bool UsageFlag { get; set; }}

Internal singleton setting instance is attached to a pivot class. It also contains an addition helper method to check elevated privileges obtaining:

static class Core{public static bool IsElevated{get{return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);}}public static ApplicationSettings Settings { get; set; }}

The executing flow is being separated to the two parts: in the first it’s being determined whenever elevated privileges are required relying on command line arguments specified or not. And if yes – an additional parameter is being added and passed to the same application but started with administrative rights and redirected  console output.
And in the second, the core functionality is being executed with full privileges gained.

Now there is no needs to run the whole application under elevated privileges mode when it is not necessary.

Unfortunately it seems that it’s not possible to hide child process window and elevate its privileges in the same time:

ProcessStartInfo.Verb will only have an effect if the process is started by ShellExecuteEx() which requires UseShellExecute = true Redirecting I/O and hiding the window can only work if the process is started by CreateProcess() which requires UseShellExecute

I’m investigating this behavior and will update my article as far will find a solution to hide a window of started elevated process. 

Reader can find next links to be interesting: 

Questions tagged UAC and manifest on Stack Overflow, especially this and related. 

28/08/2010 – version 1.0.1 – Initial release.  

29/08/2010 – version 1.0.2 – Fix of example source code.

30/08/2010 – version 1.1.3 – Code change and remark addition considering hiding window of process started with elevated previliges.

View the original article here



Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - September 3, 2010 at 12:59 am

Categories: C#   Tags: demand, download different Types Of Compilers in C#, elevated, embed manifest in VC .0 program elevated privileges, Getting, privileges, Using

Programming WCF Services Released

Programming WCF Services, Third Edition is the authoritative, bestselling guide to Microsoft’s unified platform for developing modern service-oriented applications on Windows.

“I’ve included my ServiceModelEx library, a framework of useful utilities, tools, and helper classes that let you simplify and automate many tasks, and extend WCF,” says author, speaker, and Master Architect Juval Löwy.

Löwy revised this edition to include the newest productivity-enhancing features of .NET Framework 4 and the Azure AppFabric Service Bus, as well as the latest WCF ideas and techniques. By teaching you the why and the how of WCF programming, Programming WCF Services will help you master WCF and make you a better software engineer.

This book will help you:

• Learn about WCF architecture and essential building blocks, including key concepts such as reliability and transport sessions

• Use built-in features such as service hosting, instance and concurrency management, transactions, disconnected queued calls, security, and discovery

• Master the Windows Azure AppFabric Service Bus, the most revolutionary piece of the new cloud computing initiative

• Increase your productivity and the quality of your WCF services by taking advantage of relevant design options, tips, and best practices in Löwy’s ServiceModelEx framework

• Discover the rationale behind particular design decisions, and delve into rarely understood aspects of WCF development

Hailed as the definitive treatment of WCF, Programming WCF Services provides unique insight, rather than documentation, to help you learn the topics and skills you need for building WCF-based applications that are maintainable, extensible, and reusable.

Juval Löwy is the principal of IDesign, a company specializing in .NET architecture consulting and advanced training. Juval is Microsoft’s Regional Director for the Silicon Valley, and he participates in the Microsoft internal design reviews for future versions of .NET and related technologies. Juval is one of the world’s top .NET experts and industry leaders—and a Microsoft Software Legend.

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - September 2, 2010 at 1:28 am

Categories: Press Releases   Tags: download different Types Of Compilers in C#, Juval Lowy, Microsoft Software Legend, Microsoft's Regional Director, oreilly, Programming WCF Services

Transform Data into Interactive Dashboards with ReportsMaestro

ReportsMaestro has announced the immediate availability of its web report and chart builder. Powerful and flexible, ReportsMaestro makes creating and sharing fully customizable interactive dashboards a mater of a few minutes.

Designed to give your website a competitive advantage through improved data visualization, the ReportsMaestro offers a set of tools for building interactive reports, charts and queries. The software features Web Reports Builder enabling you (or your users, for that matter) to create real-time data-driven reports, generate them based on a table or query, and tailor for the specific needs with the built-in visual style editor.

With ReportsMaestro, no coding is required to convert those huge amounts of data into the interactive, professional-looking charts. The smart solution provides Web Charts Builder with 15+ chart types and styles, from popular pie and bar charts to sophisticated 3D diagrams. It also offers Query Builder to enhance the look of your database joining tables, grouping, sorting and filtering data.

What’s more, the program allows determining access rights for users and give charts and reports private or public status. This option provides authorized users with a handy collaboration tool, while ensuring the necessary data security. ReportsMaestro supports MS Access, MySQL, PostgreSQL, Oracle, Firebird, SQLite and SQL Server, and can be installed on any ASP or PHP-enabled web server.

Pricing and Availability

ReportsMaestro is available in Standard, Gold and Platinum editions valid for 1, 10 and unlimited number of websites respectively. The price for the product starts from $79. Licensed users are entitled to free updates and support via e-mail within 1 year from the date of purchase. Further information on ReportsMaestro is available at the product website.

Links

Program website: http://reportsmaestro.com
Screenshots: http://reportsmaestro.com/screenshots.htm

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - September 1, 2010 at 12:30 am

Categories: Press Releases   Tags: download different Types Of Compilers in C#, Firebird, Interactive Dashboards, interactive dashboards ms access, MS Access, mysql, oracle, oracle interactive dashboards, PostgreSQL, ReportsMaestro, sql server, SQLite

Avoid Hidden Controls – ASP.NET

Web Application is stateless. To maintain the state of the page we have many solutions like query string, session, hidden controls and more..


Hidden controls are primarily used to keep some kind of key value pairs for the page. To maintain multiple key value pairs, we need to have multiple hidden controls on the page and hidden control name will be used as key. Basically the concept behind the hidden control is sharing the values between server and client.


But sometimes single hidden control will be used for multiple values; it’s not a good way to do because of improper delimited character handling or data type conversions.


I have come up with the solution to maintain the states using a single hidden control and isolate the complication inside this component.


This solution is like an enhancement of ViewState provided by Microsoft. Though it solves the purpose to retain the server side values, it is not possible to manipulate those values in the client side as it’s designed for handling the retaining of server side object.
URL : http://msdn.microsoft.com/en-us/library/system.web.ui.control.viewstate.aspx


ViewState Sample :

public partial class ViewStatePage : System.Web.UI.Page { [Serializable] public class Employee { public string Name; public int Age; } private Employee currentEmployee; protected override void SavePageStateToPersistenceMedium(object state) { ViewState["CurrentEmployee"] = currentEmployee; base.SavePageStateToPersistenceMedium(state); } protected override void OnLoad(EventArgs e) { currentEmployee = ViewState["CurrentEmployee"] as Employee; base.OnLoad(e); }}

To solve this problem, I have created a Web Control in my one of old ASP.NET project called as ExtentedViewState Control. Here I have added some more advanced way to handle this problem.
Basically, this control will hold a collection object which will allow the user to add a key value pair. At the time of rendering of this web control, this will generate a single hidden control and holds the key value pairs as base 64 encoded values.
Once the page is loaded into the browser, this control uses a simple Javascript wrapper to allow the user to manipulate the key value pairs from the client side.
When the user submits the page, this Javascript wrapper will send these updated values as base 64 string to the server. In the server side, it will get parsed and object is built on the server side.


Here I have included a sample project in a more simplified way to avoid the hidden controls.


It contains 3 different files for avoiding the hidden controls, from the server side, I have created a simple object to work like ASP.NET ViewState object – named “CustomViewState.cs”


CustomViewState Class contains the implementation of server side key value pair accessing and manipulations. This object will be added as the property to the parent UI.Page class.
User can access the Key value pairs using the property as like the normal collections.


StateManager.js script file serve the same functionality of CustomViewState Class in Client side.


Step 1: Inherit your asp.net page class from FrameWorkBasePage
Step 2: Add your key/values using CustomViewState property of the current UI.Page.
Step 3: Use StateManager object in from client side to manupulate the key value pairs

public partial class _Default : ApplicationFrameWork.FrameWorkBasePage { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { int intvalue = 10; decimal decvalue = 10; DateTime dtvalue = DateTime.Now; DateTime dvalue = DateTime.Now.Date; bool bvalue = true; CustomViewState.SetValue(“integer”, intvalue); CustomViewState.SetValue(“decvalue”, decvalue); CustomViewState.SetValue(“dtvalue”, dtvalue); CustomViewState.SetValue(“datevalue”, dvalue); CustomViewState.SetValue(“boolean”, bvalue); CustomViewState.SetValue(“strvalue”, “Elayaraja”); } } }

View the original article here

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - August 31, 2010 at 8:15 pm

Categories: C#   Tags: ASP.NET, Avoid, controls, download different Types Of Compilers in C#, Hidden

Create RESTful WCF Service API : Step By Step Guide

Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for your services, enabling you to expose CLR types as services, and to consume other services as CLR types. In this article I am going to explain you how to implement restful service API using WCF 4.0 . The Created API returns XML and JSON data using WCF attributes.

What is REST? 

Based on Roy Fielding theory “Representational State Transfer (REST), attempts to codify the architectural style and design constraints that make the Web what it is. REST emphasizes things like separation of concerns and layers, statelessness, and caching, which are common in many distributed architectures because of the benefits they provide. These benefits include interoperability, independent evolution, interception, improved scalability, efficiency, and overall performance.”

Actually only the difference is how clients access our service. Normally, a WCF service will use SOAP, but if you build a REST service clients will be accessing your service with a different architectural style (calls, serialization like JSON, etc). 

REST uses some common HTTP methods to insert/delete/update/retrive infromation which is below: 

a) GET -  Requests a specific representation of a resource

b) PUT - Create or update a resource with the supplied representation

c) DELETE - Deletes the specified resource

d) POST - Submits data to be processed by the identified resource 

Why and where to use REST?  

Few days back i was writing a service which was suppose to access by heterogeneous language/platform/system. It can be used by iPhone, Android, Windows Mobile, .NET web application, JAVA or PHP. Using web service it was bit complex for me to expose it to everyone using uniform system. Then we decided to use REST, which was easily espoused over cloud. This was a great example which shows the capability of SIMPLE RESTful SERVICE Create RESTful WCF Service API : Step By Step Guide .  Below is some point which will help you to understand why to use the RESTful services.

1) Less overhead (no SOAP envelope to wrap every call in)

2) Less duplication (HTTP already represents operations like DELETE, PUT, GET, etc. that have to otherwise be represented in a SOAP envelope).

3) More standardized – HTTP operations are well understood and operate consistently. Some SOAP implementations can get finicky.

4) More human readable and testable (harder to test SOAP with just a browser).

5) Don’t need to use XML (well you kind of don’t have to for SOAP either but it hardly makes sense since you’re already doing parsing of the envelope).

6) Libraries have made SOAP (kind of) easy. But you are abstracting away a lot of redundancy underneath as I have noted. Yes in theory SOAP can go over other transports so as to avoid riding atop a layer doing similar things, but in reality just about all SOAP work you’ll ever do is over HTTP.

Step by step guide   

Generally developer scared to use WCF because lot of confusing configuration. I will try to use minimum configuration so that it will be easier to understand for us. We will develop Restful WCS API in 6 steps. So let’s start now.

STEP:1) First of all launch Visual Studio 2010. Click FILE->NEW->PROJECT. Create new “WCF Service Application“ .  

 

STEP-2) Once you create project, you can see in solution that By Default WCF service and interface file is already created. Delete By default created file as we will create our own interface and WCF service file.

STEP-3) now Right click on solution and create one new WCF service file. I have given name to the service file as “RestServiceImpl.svc”. 

STEP-4) As i explained in starting of the article that we will be writing an API which can return data in XML and JSON format, here is the interface for that. In IRestServiceImpl ,  add following code.

 

In above code, you can see two different method of IRestService which is XMLData and JSONData. XMLData Returns result in XML  whereas JSONData in JSON. 

STEP-5) Open the file RestServiceImpl.svc.cs and write following code over there..

STEP-6) Now let’s move to configuration part which is the last one. There will be two basic part of the configurations file which we must have to understand… 

The part contains information about the End Point. below is the code detail..

A)    

 This part contains details about service and endpoint behavior. 

 

And that’s it. Our Restful WCF service is ready for test purpose.

Now i launch the application in browser to see the result. I launch this service in IE and my URL is now http://localhost:35798/RestServiceImpl.svc . Now if i use http://localhost:35798/RestServiceImpl.svc/xml/123 URL, i get following response on the browser which an XML format and that was my task to achieve.

 

Now if i use http://localhost:35798/RestServiceImpl.svc/json/123 URL, i get following response on the browser which an XML format and that was my task to achieve.

 

Hope the article is useful for community. Comments, suggestions and criticisms are all welcome.

View the original article here

2 comments - What do you think?
Posted by Anand Narayanaswamy - August 30, 2010 at 6:39 pm

Categories: C#   Tags: Create, download different Types Of Compilers in C#, guide, RESTful, Service

WebService Routing (Soap Router)

This article describes content based web service routing using WSE 3.0. We can use webservice routing for load balancing or to hide internal web service from external world.


A background knowledge of Asp.Net 2.0, C#, WebService & WSE 3.0 is required.


In this sample application, I have three webservice 1) CBRoutingService 2) PremiumService 3) StandardService and client web application.


As per the above figure, client web application will consume CBRoutingService. SoapHeader will have user id stored in it. CBRoutingService will route the request to the StandardService or PremiumService based on the user id. If user id is less than 100 than it will route the request to the StandardService otherwise it will route it to PremiumService. So this is simple routing application which we will build.


Let’s do following steps in vs2005:


1) Create Standard service


2) Create Premium service


3) Create & configure Routing service


4) Create & configure client website


1) Create Standard service:


To create the StandardService as ASP.Net Web Service. Go to File -> New -> Web Site -> ASP.Net Web Service. Give the location as http://localhost/StandardService . Remove default Service.asmx and Service.cs file and add new web service StandardService.asmx. We will add new web method called GetServiceString in StandardService.cs as below.

[SoapHeader("authheader", Direction = SoapHeaderDirection.InOut)] [WebMethod] public string GetServiceString() { return “This is Standard Service Customer”; }

We also have to add AuthHeader class in StandardService.cs for passing user id in the SoapHeader and write SoapHeader attribute above GetServiceString web method.

public class AuthHeader : SoapHeader{ public string UserId;}

2) Create Premium Service:


Create PremiumService by same way, just give the location as http://localhost/PremiumService and web service name as PremiumService.asmx. We also need to change return string in GetServiceString web method of PremiumService.

[WebMethod] public string GetServiceString() { return “This is Premium Service Customer”; }

3) Create and configure Routing Service:
Now we will create routing service by same way with http://localhost/CBRouter as location. Add new web service and give name as CBRoutingService.asmx.


Keep the default setting as it is for now. We will change it latter.


Now we need to have handler which will intercept the request to CBRoutingService. So we need to add class library project for that by right click on solution -> Add -> New Project and select Class Library template. Now add new class called CBRoutingHandler.


Add following reference to your project.


1) Microsoft.Web.Services3


2) System.Web.Service


We have to derived Microsoft.Web.Services3.Messaging.SoapHttpRouter in CBRoutingHandler class and implement ProcessRequestMessage method to intercept the web service request.

using System; using System.Configuration; using System.Xml; using Microsoft.Web.Services3; using Microsoft.Web.Services3.Messaging;/// /// Summary description for CBRoutingHandler/// namespace CBRouter{ public class CBRoutingHandler : Microsoft.Web.Services3.Messaging.SoapHttpRouter { static readonly string PremiumNamespaceUri = “http://schemas.contoso.com/cbr”; static readonly string PremiumHeaderName = “authheader”; Uri premiumServiceUri; Uri standardServiceUri; public CBRoutingHandler() { string premiumServiceUrl = “http://localhost/PremiumService/PremiumService.asmx”; string standardServiceUrl = “http://localhost/StandardService/StandardService.asmx”; if (premiumServiceUrl == null || premiumServiceUrl.Length == 0) { throw new ConfigurationException(“There was no \”Premium Web Service\” entry in the section of the router’s configuration file.”); } this.premiumServiceUri = new Uri(premiumServiceUrl); this.standardServiceUri = new Uri(standardServiceUrl); } protected override Uri ProcessRequestMessage(SoapEnvelope message) { // Look for user id. if (!string.IsNullOrEmpty(message.Header.InnerText)) { if (Convert.ToInt32(message.Header.InnerText) > 100) { return premiumServiceUri; } } return standardServiceUri; } }}


Add CBRoutingHandler project reference in CBRouter web service.


Now you have to enable WSE based routing in CBRoutingService. To do this follow the below steps:


1) In Visual Studio 2005, right-click the CBRouter project and select WSE Settings 3.0.
2) On the General tab, select the checkboxes for the following options:
o Enable this project for Web Services Enhancements.
o Enable Microsoft Web Services Enhancement SOAP Protocol Factory
3)Click OK



Now click on Routing tab. Click Add to add routing handlers and give CBRoutingHandler information as below, type = “CBRouter.CBRoutingHandler, CBRouter” Path=” CBRoutingService.asmx” and Verb=”POST”


You can see the changes in web.config file. It has added httphandlers in web.config.


Now we have to give WSDL to the client so that they can generate the proxy and consume it.


Save wsdl of StandardService or PremiumService as .wsdl file. Open this file in editor and change the url to CBRoutingService url as below:


So now we have .wsdl file but it points to CBRouter.


4) Create and configure client website:


Now create client web site. Here, do not add web reference for StandardService instead create proxy class with wsdl.exe using modified wsdl file.


Open .net command prompt and give following command: Wsdl /out:C:/StandardServiceProxy.cs C:/Standardservice.wsdl


Now add this StandardServiceProxy.cs to your website project.


Add textbox and button on the page. On button click, we will pass the textbox value to web service call.

protected void Button1_Click(object sender, EventArgs e) { try { StandardService standardSer = new StandardService(); AuthHeader auth = new AuthHeader(); auth.UserId = txtUserId.Text; standardSer.AuthHeaderValue = auth; string str = standardSer.GetServiceString(); lbl.Text = str; } catch (Exception ex) { lbl.Text = ex.Message; } }

Now run the website and enter any user id. You will get the response based on user id as below.


Thus you can use WSE to route the web service call to other webservice.


Notes:


If you want to make StandardService & PremiumService as WSE enabled service then you have to apply SoapActor attribute above the service class name.

using Microsoft.Web.Services3.Messaging;/// /// Summary description for StandardService/// /// [SoapActor("*")][WebService(Namespace = "http://tempuri.org/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]public class StandardService : System.Web.Services.WebService{

SoapActor attribute indicates that this web service can handle routed messages, which is not originaly requested to it. ‘*’ means any service can route the messages to this webservice. You can give router service’s url to indicate service will handle routed message from particular url.


View the original article here

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - August 29, 2010 at 8:30 pm

Categories: C#   Tags: .SoapActor("*"), download different Types Of Compilers in C#, Router, Routing, soapactor attribute wcf, WebService, WSE router Web application

ASP.NET MVC – AuthorizeWithExemptionsAttribute

In this article, I’ll provide you with a solution for securing ASP.NET MVC application’s controllers in a way that all the actions are secured except those you define as unsecure (by default, all the actions are unsecure unless you define them as secure).


I encountered a problem in the ASP.NET MVC authorization model, which is built as opt-in. You can secure an action or a controller using the [Authorize] attribute. The problem is that if you want to secure a whole controller and make some actions in that controller as not secured – you can’t.


This article will explain to you how you can secure a whole controller and make some actions as not secured within it.


This project was written in Visual Studio 2010 as an ASP.NET MVC 2 project.


I was looking for a solution to that problem, and couldn’t find a reasonable one. Other solutions suggested to:

Move the unsecured actions to another controller (not secured)Write the AuthorizeCore method to be dependent on the Action’s namesPut the [Authorize] attribute on all the actions except the non-secured actions

In this article, I’ll provide you with my solution to this problem.


To use the code, you’ll need your controllers to put any [CustomAuthorize] attribute which inherits from AuthorizeWithExemptionsAttribute on your controllers. Calling any action on this controller will include an authorization check. If you want to mark an Action as non-secured, just put the [UnsecuredAction] Attribute above it.


The core of this solution is in the [AuthorizeWithExemptions] Attribute in the OnAuthorization method. This method checks if the called Action has the UnsecuredActionAttribute, and if it does, it marks filterContext.HttpContext.SkipAuthorization as true.

public override void OnAuthorization(AuthorizationContext filterContext){ ActionDescriptor action = filterContext.ActionDescriptor; bool IsUnsecured = action.GetCustomAttributes( typeof(UnsecuredActionAttribute), true).Count() > 0; //If doesn’t have UnsecuredActionAttribute – then do the authorization filterContext.HttpContext.SkipAuthorization = IsUnsecured; base.OnAuthorization(filterContext);}

Then, CustomAuthorizeAttribute performs the authorization check only if SkipAuthorization is false.

protected override bool AuthorizeCore(HttpContextBase httpContext){ if (httpContext.SkipAuthorization) { return true; } // Do any authorization logic here return httpContext.Request.QueryString["password"] == “password”;}

* Of course, never provide the password in the QueryString, it was made like that just for the ease of the example.


So now, when you try to invoke the secured controller, you get the HTTP error code 401: Unauthorized.


View the original article here

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - August 29, 2010 at 2:07 am

Categories: C#   Tags: ASP.NET, AuthorizeWithExemptionsAttribute, download different Types Of Compilers in C#

Authenticate user by roles in asp.net

Forms authentication enables user and password validation for Web applications that do not require Windows authentication. With forms authentication, user information is stored in an external data source, such as a Membership database, or in the configuration file for an application. Once a user is authenticated, forms authentication maintains an authentication ticket in a cookie or in the URL so that an authenticated user does not need to supply credentials with each request. 

At my web site, I have a folder “Admin”, which I only want users with administration roles to be able to access them. I simply don’t want to check each user’s right on this folder, just depends on roles. This article is about this approach. 

In my case, I don’t care who have logged into my website, if they are not logged in, they can only browse my web site; if they registered and logged in, they can do certain things, like add a fire panel, delete the fire panel they created; if users logged in with administration roles, web site will grant them rights to access files under “admin” folder.   

Download the code, unzip it to a folder, create a virtual directory on IIS for it.  Root directory contains “login.aspx”,”logout.aspx”,”default.aspx”, and a folder called “admin”, at “admin” there is only one file, “default.aspx”, this is the file I will stop normal user from accessing it.

Forms authentication include several important parts you need to implement.

At my web.config file I set Authentication mode to “Forms”.

At web.config, I create a folder that I want to authenticate user.

Like following:


1 comment - What do you think?
Posted by Anand Narayanaswamy - August 28, 2010 at 5:15 am

Categories: C#   Tags: ASP.NET, Authenticate, download different Types Of Compilers in C#, roles

Windows PowerShell Cookbook, Second Edition

Do you know how to use Windows PowerShell to navigate the filesystem and manage files and folders? Or how to retrieve a web page? Windows PowerShell Cookbook (O’Reilly Media, $54.99 USD) gives you an introduction to the PowerShell language and scripting environment.

“This book focuses squarely on helping you learn PowerShell through task-based solutions to your most pressing problems,” says developer and author Lee Holmes. “Read a recipe, read a chapter, or read the entire book-regardless, you’re bound to learn something.”

The second edition provides even more task-oriented recipes to help you solve the most complex and pressing problems. The book also includes more than 100 tried-and-tested scripts that intermediate to advanced system administrators can copy and use immediately.

You’ll find hands-on tutorials on fundamentals, common tasks, and administrative jobs that you can apply whether you’re on a client or server version of Windows. You also get quick references to technologies used in conjunction with PowerShell, including format specifiers and frequently referenced registry keys to selected .NET, COM, and WMI classes. With Windows PowerShell Cookbook, you’ll get more done in less time.

.    Take a tour of PowerShell’s core features, including the command model, object-based pipeline, and ubiquitous scripting
.    Learn PowerShell fundamentals such as the interactive shell and fundamental pipeline and object concepts
.    Perform common tasks that involve working with files, Internet-connected scripts, user interaction, and more
.    Solve tasks in systems and enterprise management, such as working with Active Directory, the filesystem, registry, event logs, processes, and services

Lee Holmes is a developer on the Microsoft Windows PowerShell team, and has been an authoritative source of information about PowerShell since its earliest betas. His vast experience with Windows PowerShell enables him to integrate both the ‘how’ and the ‘why’ into discussions. Lee’s involvement with the PowerShell and administration community (via newsgroups, mailing lists, and blogs) gives him a great deal of insight into the problems faced by all levels of administrators and PowerShell users alike.

Additional Resources

For more information about the PowerShell book, including sample content, full table of contents, author bio, and cover graphic, see: http://www.oreilly.com/catalog/9780596801519.

Windows PowerShell Cookbook, Second Edition
Lee Holmes
ISBN: 978-0-596-80501-2, 888 pages

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - August 26, 2010 at 1:13 am

Categories: Press Releases   Tags: download different Types Of Compilers in C#, lee holmes, O'Reilly Media, PowerShell fundamentals, Solve tasks in systems and enterprise management, Windows PowerShell Cookbook

Employee Recognition Programs

Employee recognition is vital for performance-oriented companies that look for mobilizing all employees and stakeholders, prominently dealers and distributors, in the direction of clear business objectives ascertained by sales, profits, customer satisfaction, and productivity. Such performance driven companies need to regularly communicate and strengthen their dynamic aims. Nevertheless, recognition for such organizations goes beyond the conventional character of service awards. In spite of the fact that recognition and incentive seem interchangeable, the two terms should not be confused with one another. While the recognition includes all the means that draw attention to employees who perform, the incentives usually employ discerning means to persuade people to accomplish a particular objective like increasing sales. Recognition can be impromptu, indeed to the level that there is no ceremonial announcement that the organization has a recognition program, while the incentives are well known so as to build enthusiasm through material reward. The true beauty of the recognition programs based on performance is their nature of surprise that is in contrast to service-award programs that make necessary ceremonies holding on a routine basis. In this way the employees would be much more interested in performing better rather than just concentrating on the reward.

Employee recognition domain has become to gain recognition among organizations as they begin to judge the impact of downsizing on long-term productivity, profits, and the quality of products and services. Previously, employee recognition meant service awards, wherein recognition of their service years in a company people got an intensifying series of awards accompanying a mention in the employee newsletter, while staying until retirement, they might get a gold watch. From time to time, companies expanded these programs to comprise recognition for diverse actions like superlative customer service; nevertheless often these were limited to rewarding nature.

In the present era, no one just simply depends on the incentives and reward system, rather in a downsized company; employees would ridicule a service award if there were one. Thus, with more understanding of the employees’ needs, companies are becoming more proactive when it comes to the employee recognition. While the effective recognition include activities like day-to-day, informal, and formal. For example, commendation is an illustration of day-to-day recognition that costs nothing and can be given by any person, to anyone anytime. While the form of informal recognition can take a diversity of forms, it has certain limitations and oftentimes contains a low-cost, material beckoning of appreciation or congratulations, the formal recognition includes awards for achievements, service, etc., and the celebration episodes at which all contributing employees take part and get recognition. However, a formal recognition customarily has inevitable policy and legal requirements.

In “1001 Ways to Reward Employees” and the “1001 Ways to Energize Employees”, Bob Nelson and suggests the significance of awards and recognition and the reason that they are essential tool of employee motivation, team building and productivity. According to Nelson, the American organizations did not always identify or accept this, as for a much longer time corporate America thought that high salaries, cash bonuses and good employee benefits were all that was needed to motivate their employees. While these factors do in an effective way provide a form of short-term motivation, however, much research finding points out that money is not an effective long-term motivational tool. Before 1954, what termed corporate motivation was the formula of Frederick W. Taylor that encapsulates that money was the primary motivator for all performance. Contrary to this scientific management formula, in the Hierarchy of Needs Abraham Maslow in 1950′s denied this scientific management and originated that individuals were not machines as they in truth have various levels of motivational contentment that need to be appeased to a certain degree. Form this theory it becomes apparent that contentment on top of that degree could be better consummated by using other less expensive and increasingly effectual forms of reward.

In the 1995 issue of “Employee Relations Today”, Professor Kenneth Kovach reported that his most recent research proved the two most referred to factors of motivation by employees were not salary and benefits, but more or less, an interesting job and recognition for doing that job well. Frederick Herzberg also identified this importance of recognition by the employer in his finding that employee accomplishment and recognition are two motivating factors inherent to the job environment. Furthermore, he asserted that the job satisfaction is contingent on these factors over and above anything. Thus a well planned recognition program can, lessen turnover, assist in retaining competent people and elevate pride and loyalty in the company, which not only improves performance but also brings about positive attitudes and raise a productive and perpetual work environment.

The programs that are meant to serve the purpose of recognizing employees’ efforts must be designed in a manner that not just satisfies the importance of employees’ recognition, but also take into consideration the workforce diversity. Another thing is the involvement of the employees in this program downright the grassroots level. Once designed, it is the responsibility of the management to evaluate the existing program and make changes whenever and wherever feasible. Giving lapel pins or corporate logo jewelry where the employees already possess them would not create much of the sensation or motivation. Kovach (1995) accentuates that there definitely is a gap that exists between employee needs and employer’s understanding of those needs. This gap is widened as the management overlooks the differences in corporate culture and the consequent contrariety in personal tastes evident in distinct departments within an organization or at dormitories strewn across expansively “different demographic, psychographic and geographic areas”. Current research corroborates that a selection “program targeted at the employee’s lifestyle is the most appreciated and cost effective approach. The awards should be something that the employee wants, needs and will use and cherish. It should be something special to the recipient. People never forget who gave them something of personal value, nor do they ever forget why it was given.

The problem is that many recognition programs do not offer awards that employees really want. There is no validity in benchmarking the most popular items in most existing programs because the selections are often obsolete. The most expensive award you can give someone is something they didn’t want in the first place, have no use for and will not use” (Nicastro, 2002). Accordingly, Nicastro (2002) further researches in to the subject and narrates that the things that are considered practically accepted with today’s employees are “electronics, fashion jewelry, brand name timepieces and watches, collectibles, sporting goods and lifestyle targeted gifts. The most appreciated awards are items that the recipient would like to own, but has not or can not justify buying for themselves”. Nicastro (2002) further investigates that in a study of 3000 service recognition programs, it was found out that the awards that are most adored are when they are given on or near the employee’s employment anniversary date. The study also revealed that the “most common complaints by employees is that their anniversary came and went without any recognition. Whenever possible awards should be presented in front of peers, with someone from administration, who is known, recognized and respected making the presentation. This does not mean you need to have an awards banquet; a small departmental ceremony with cake and coffee can be just as effective. Recognize the achievement, talk about the recipients accomplishments, contributions to the company and a short work related anecdote. Make the recipient and the accomplishment special. It’s the timeliness, the respect and the special recognition that makes a lasting impression”.

In the article, “Consultant Dispels Myths About Award Programs”, Bob Nelson (2001) further elucidates most of recognition programs are outmoded. This Nelson references to the 10-year national study, the Independent National Study of Recognition Policies and Practices, by Perspectives Resources, Inc. This study finds out that the outmoded factors of recognition de motivates rather than motivates the employees as they no longer meet the employees needs and the corporate objectives. “Companies are spending more than $500 million annually on service award programs that don’t work,” says Edward L. Ford, recognition consultant, “and minor changes will not address the problems. At the same time, with all the downsizing and change taking place in business today, recognition is more important to the morale of employees than ever. It is imperative that companies take a fresh look at what constitutes effective recognition — including what the needs of the award recipient are.” Giving insights in to the less important award program as compared to reward program, Nelson assets that organizations are haunted by myths that were prevalent in 60′s and 70′s. The first one that he points out is that “Logo emblems of gold and diamonds make the best award”. Where for the myth he gives that the “Corporate emblems are outdated, and 95.8 percent of employees would rather have practical merchandise items as awards”.

The reason that he points out is that employees are used to these service awards and that these have little bearing as to the impact of the awards. Secondly, with the downsizing culture, employees in this era do not possess any corporate identity, which further yields it insignificant. In a study, that based on the Employee Needs and Wants Recognition Index (ENRI) only 4.2% of employees choose logo jewelry over merchandise for awards. The second myth highlighted is “Recognition programs incorporate award choices that employees really want”, wherefore, the fact is, “According to the ENRI, 70 percent of employees would choose something other than what they are offered”. The third myth outlined goes as “A simple change in selection or awards will substantially improve your recognition program”, where the fact “To address employees’ changing attitudes, more and more companies are reengineering their recognition policies”. Nelson suggests that the reengineering process actually do help companies salvage money “rather than spend more on recognition, while allowing them to provide awards that employees really want. For example, 117 companies that re-engineered their programs during 1994 and 1995 saved an average of 42.9 percent on their programs, and their average award cost per employee per year dropped from $17.66 before reengineering to $9.21 afterwards”. The fourth myth is “Companies should reduce or eliminate years of service awards”, where as the fact is “Companies should not cut programs at random. Instead, they need to make all recognition programs more effective by aligning them with shifting employee attitudes and updating them annually”. Nelson asserts that the companies must first “identify which types of awards are most appropriate in your present corporate culture. Employees may like the types or recognition your program offers. Their dissatisfaction may lie in the awards they are offered”.

Today, majority of the employee service programs involve giving an employee logo jewelry with a “jewelling sequence” for their consequential years of service in the organization. In spite of the fact that the cost of such programs can cost millions of dollars, unluckily, there are some deadly flaws regarding their effectiveness. For instance, oftentimes an employee’s anniversary date goes overlooked, though in the employee’s mind the specific anniversary date is important. The faults in the recognition programs can be eliminated thereby reducing the company’s cost and increasing the effectiveness of the employee recognition programs standardizing the activity of recognizing each employee’s anniversary, while consequently letting increased pliancy of choice on the part of the employee of items of similar value. “Each year a new selection of gifts would be made available so that with each significant anniversary, employees have a fresh selection of gifts to choose from” (Sims, 2001).

Thus, the center of the program is on the employee’s anniversary, and not on the increased value of a gift he receives. Nelson explains that the companies that have engineered this method have noticed remarkable improvement in their service program in terms of efficacy noted satisfaction and decreased costs. 500 of the Fortune 500 companies have formal Service Recognition Programs as they clearly accepts that these programs pay by yielding reduced turnover, improved safety performance and lower unscheduled absenteeism costs. These companies have come to know that the employee turnover is one of the greatest covert costs, where on an average you hire three and retain one each year. The training cost on the average for the newly trained employee comes out to be eight hours, as an example then the it costs at least $60 to train a new employee, excluding mistakes and poor quality costs. Resulting, in the actual training cost to be at the amount of $180 for one employee that stayed for one year. This amount will build up as you may hire at least 20 employee to keep one for five years costing $1,000.

Employee recognition programs save much for the company as no tax is levied on these programs, as tangible gifts above $400 attracts 40% tax. Recognition brings in social acclaim for the employee and is something “extra” for the employee.

By far, recognition is the “Number One” reward that employees react to and is far more significant than salary and benefits. Evelyn Clark designs and suggests a new way to recognize the employees’ efforts, which is by story telling. Clark asserts that the “managers who consistently tell stories of people “caught doing something right” discover that recognition is truly a highly valued reward. The benefits are numerous:

- “The employee is pleased that the manager noticed a job well done and took the time to acknowledge it

- Other employees learn more about the behavior that the company values

- Employees are motivated to enhance their performance

- Employees take more pride in their affiliation with the company

- Productivity and profitability increase”

David Saxby narrates, “I’m amazed by the number of companies that spend thousands of dollars to improve their technology, increase their marketing efforts and set up that next killer sales program. Yet they don’t quite see the benefit of making an investment in recognizing the most valuable asset they have: their front-line employees. These are the people who interact with the customer every day, handle customer-service conflicts and generate revenue for the company”. According to Saxby, recognition does not only means honoring the top performers, rather it is regarding recognizing people who better their skills all the time to give improved customer service and sell more product. Saxby points out that recognition does not talk only of money, rather it concerns about a mere hand-written thank-you note or an inscription that sits in the entryway for the world to look at. Further, recognition must not be limited to the annual event or the monthly meeting where people are acclaimed for their efforts, rather a positive attitude or an improved behavior must be recognized and praised immediately.

Recognition can come in different ways, like reinforcing positive performance, providing incentives and rewards, motivating with “high-impact” messages, rewarding extra efforts, honoring current employees and personalizing the work experience.

Hiam (2002) suggests, “If you recognize and make a bit of a fuss about the good things employees do, then you will find yourself spending a lot less time worrying about the bad things they do. They will do less of the negative, and they will strive to do more of the positive things you are recognizing. It is far, far easier to lead people to improved performances by thanking them when they do it right than giving them “grief” when they do it wrong”. Hiam (2002) further incorporates that employers must “praise and recognize” their “star performers”, and “recognize good effort, not just results”.

Handel in the employeessurvey.com reports, “In the business world, the greatest commodity to have is the best and brightest people. A recent survey by World at Work and the National Association for Employee Recognition (NAER) shows that companies are beginning to realize this more each day, as employee recognition programs are still used extensively in these tough economic times. According to the 2002 Employee Recognition Survey, 84 percent of the 391 responding companies have an employee recognition program. This shows that despite a tough economy, companies realize the importance of making sure their top performers are happy. In fact, although the economy has dipped substantially, employee recognition programs are gaining in popularity, as 41 percent of respondents indicate they are doing more with their recognition programs than they were 12 months ago. More than half (54 percent) of the respondents that said they do not currently have a program indicated they are considering implementing one in the next 12 months. Companies hope to achieve a number of things through their recognition programs, but creating a positive work environment is the top reason cited, with 84 percent of responding companies citing this as a goal of their program. Other goals include, reinforcing desired behaviors (76 percent) motivating high performance (73 percent), increasing morale (69 percent) and supporting organizational mission/values (68 percent). The most popular method of recognizing employees is through gift certificates and cash, with 63 percent and 58 percent of companies reporting they use these forms of recognition. The most common reason for giving a recognition award is “length of service,” (75 percent) followed by “above and beyond” performance (64 percent)”.

Emery (2000) reports that “In today’s fiercely competitive labor market, cash is key to attracting skilled technical employees, human resources managers and business experts agree. But spiraling salaries and mammoth bonuses don’t bind workers to their employers. What employees really want is recognition for a job well done.”

Experts maintain that it is not just the money that binds employees to the organization; rather it’s the recognition. However, if the awards are tied to the performance, then only the money matters but does not lessen the importance of recognition programs. Experts further elucidates that the “companies that offer cash bonuses tied to performance are using their money productively, but they need to offer other rewards and make sure those rewards are tailored to the organization and its employees”.

Why Good Employees Leave:

- 41% Feelings that opportunities for advancement are limited

- 25% Lack of recognition

- 15% inadequate salary and benefits

- 10% Unhappiness with Management

- 5% Bored with Jobs

- 4% don’t know/didn’t answer

(Source: Robert Half International Inc.)

In a NAER Regional Conference, Empowering Excellence Through Recognition, 2002, following factors were identified as to the significance and materiality of the employee recognition programs. The first factor that was identified was knowing whether the employee wants recognition in private or public keeping in place the cultural norms and etiquette. There was also a suggestion of creating a web site of generic recognition that can be individualized. There must be a cultural promotion of peer to peer recognition so as to make everyone responsible to recognize every other peer. Such sort of employee recognition programs and cultural initiates have no cost at all, and organizations need to worry about the cost that are or need to be incurred. Once embedded in the culture, it’s a free ride. Further it can be an easy way to retain and motivate, and may be a part of fun as recognizing for an accomplishment or improved performance may bring in surprises. This would not only makes the employee think they are valuable for the company but also ingrain in them a sense of belonging and association with the company. Involving employees in the design and implementation of the employee recognition programs also bring about great sense of valuation among the employees. It would certainly be more fun if the “employees tell YOU what they enjoy”.

An employee recognition program must incorporate both the formal and informal awards in the program, if given instantly have great significant value and esteem and pride. A just Thank you card would serve the purpose most often. Other forms of recognition identified in the conference were singing recognition that generates no cost to the company, an on-line thank you where the management gets a copy, meaningful and sincere feelings both by the giver and the presenter, and even more better if the nominator is involved.

But all this recognition efforts comes when the manager is well aware of the beneficial impacts of the employee recognition programs and the positive attitudinal effects it brings about. And training the managers can do this. Which involves cost. Managers must be made aware of how recognition makes people feel through statistics and survey results, and must have a control of recognition, even if they don’t have a budget. This is the only short-term cost that is and must be borne by the companies to carry out the recognition culture in the organization, and once ingrained in the company’s culture, the managers and the companies need only to harvest the fruit. Thus, concluding, recognition is a mean to set up a high performance team in addition to other methods. Nevertheless, it is not a mathematical formula of calculating how much must be spend on employee recognition per person. This would mean recognizing the poor performers too, and that would reduce the impact and the excitement of the recognition program. Of course, there must be a budget set for the awards and incentives, but when it comes to the recognition, there, as has been discussed not much investment to be made. Juts make the horse understand how to carry the cart and drink the water from the well. The rest is done automatically. However, the first part is admittedly hard to accomplish, and that depends upon the managers’ aptitude and competence. Some are charismatic and needs little training while some need not to train, as they are unchangeable.

References

Nicastro, Ric. The Best Ways to Motivate And Reward Employees, The Need For Recognition, San Diego Business Journal, reprinted in 2002

Nelson, Bob. Consultant Dispels Myths About Award Programs, 2001 Rewarding Employees Smarter. New Employee Recognition Ideas From Bill Sims! Reprinted with Permission from Bob Nelson, author of the Best Selling Book “1001 Ways to Reward Employees”. Topic: RECOGNIZE YEARS OF SERVICE, DON’T REWARD

Kovach, Professor Kenneth. Employee Relations Today, 1995

Clark, Evelyn. Retain Employees through Recognition–Tell Their Stories!

Ellender, David E. Employee Benefits: Asset or Expense? 2000

Saxby, David. Employee Recognition Can Make a Difference.

Hiam, Alex. Employee Recognition: Why It Matters. Rewarding employees for a job well-done will do wonders for their performance–and your bottom line, 2002

Handel, Jeremy. Employee Recognition Programs Increasing Despite Softer Economy, Oct. 29, 2002.

Emery, Gail Repsher. EMPLOYEES: Show Me the Recognition, Vol. 15 No. 14, 2000 “Empowering Excellence Through Recognition” NAER Regional Conference Summary, Seattle, WA September 20, 2002

Nelson, Bob. 1001 Ways to Energize Employees, 1995

Samreen Soomro is an SEO expert and a search engine marketing strategist based in Karachi, Pakistan. She provides SEO Services and Internet Marketing Consultancy for companies looking to maximize their return on investment by having their websites optimized. She can also manage all aspects of PPC campaigns.

Samreen holds a Master’s degree in Computer Science and is currently pursuing an MBA degree with concentrations in Management Information Systems and Marketing.

You can contact Samreen at samreen@samreensoomro.com

Be the first to comment - What do you think?
Posted by Anand Narayanaswamy - August 25, 2010 at 6:37 pm

Categories: Programming   Tags: download different Types Of Compilers in C#, Employee, Programs, Recognition

Next Page »