Saturday, November 13, 2010

Properties in C#


Today my friend asked me a question for which i provided a solution using properties of the class. but then he asked me what are these properties, why to use them and how to Implement them To answer these questions

Definition:
Properties are named members of classes, structs, and interfaces. They provide a flexible mechanism to read, write, or compute the values of private fields through accessors. or we can say Properties equip a class with a public way to expose its private members or to get and set values for those private members, while hiding implementation or verification code.
A property has two accessors
  • Get
  • Set

The get keyword
with the help of this keyword we can define an accessor method for a property or an indexer which retrieves the value of the property or the indexer element.
The Set Keyword
With the help of this keyword we can define which accessor is used to assign a new value to the property or indexer.
The value keyword is used to define the value being assigned by the set accessor. Properties which do not implement a set accessor are termed as read only Properties.

Let’s take the first example to demonstrate how to declare and use read/write properties.

Example 1
This sample shows a Car class that has two properties: Name (string) and Model (int). Both properties have read/write attributes.


//car.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
classCar
    {
privatestring CarName = "N/A";
privateint CarModelNo = 0;
// Declare a Name property of type string:
publicstring Name
        {
get
            {
//returns the Carname
return CarName;
            }
set
            {
//set the value od carname provided by the user
                CarName = value;
            }
        }
// Declare an Age property of type int:
publicint ModelNo
        {
get
            {
//returns the CarModelNo
return CarModelNo;
            }
set
            {
//sets the value for CarModelNo
                CarModelNo = value;
            }
        }
//Overriding the ToString function of the class for demonstration
publicoverridestring ToString()
        {
return"Name = " + Name + ", ModelNo = " + ModelNo;
        }
publicstaticvoid Main()
        {
Console.WriteLine("Simple Properties");
// Create a new Car object:
Car mycar = newCar();
// Print out the name and the modelno associated with the car:
Console.WriteLine("Car details - {0}", mycar);
// Set some values on the car object:
            mycar.Name = "Maurti";
            mycar.ModelNo = 1;
Console.WriteLine("Car details - {0}", mycar);
// Increment the modelno property:
            mycar.ModelNo += 1;
Console.WriteLine("Car details - {0}", mycar);
Console.Read();
        }

    }
}
Output
Simple Properties
Car details - Name = N/A, ModelNo = 0
Car details - Name = Maruti, ModelNo =
Person details - Name = Joe, ModelNo = 100

Code Discussion
  • Notice the way that the properties are declared, for example, consider the Name property:

publicstring Name
        {
get
            {
return CarName;
            }
set
            {
                              CarName = value;
            }
        }
  • After declaring the property Set and Get methods are contained inside the declaration. We can control a property is read/write, read-only, or write-only by controlling Get or Set methods. If we only include Get Method the property will be read only if only set method is used the property will be write only (Although very less scenarios I have seen this), and as in our example if both Get and Set are used that means property is read/write.
  • Once the properties are created or declared, they can be used as if they are the members of that class. The following statementssows both getting and setting the value of a property

mycar.Name = "Maurti";
mycar.ModelNo = 1;

  • If you have noticed that in a property’s Set method a special value variable is available which we have not declared anywhere. This variable contains the value that the user has specified, for example:

CarName = value;

  • You can see that these properties are used as other variables only see how we have incremented the ModelNo property

mycar.ModelNo += 1;

  • The ToString() method is overridden in this example:
publicoverridestring ToString()
        {
return"Name = " + Name + ", ModelNo = " + ModelNo;
}
Check that I have not used the ToString() explicitly. It is invoked by default by the WriteLine calls.


In my next article I will  discus Abstract Properties

you can read Properties in C# here

Thursday, October 7, 2010

ASP.NET Security Fix Now on Windows Update


ASP.NET Security Fix Now on Windows Update

via ScottGu's Blog by ScottGu on 9/30/10

Earlier this week I blogged about the availability of a patch on the Microsoft Download Center to fix the recent ASP.NET Security Vulnerability.

Today we also made it possible to update systems through Windows Update (WU) and Windows Server Update Services (WSUS).  This enables administrators to more easily streamline patch installs, and enables you to take advantage of the WU/WSUS infrastructure to detect which patches you should install based on what versions of .NET are on your system.

Please make sure to install these updates as soon as possible on your servers.  This will prevent attackers from using the vulnerability to attack your systems.

Using Windows Update

If you run Windows Update on your system you'll see the security updates listed if you haven't already installed them on your computer.  Note that you'll see a separate update available for each version of .NET you have installed on your system:

image

Please make sure all of the "Security Update for Microsoft .NET Framework" updates are selected and then apply them to keep your system secure.

Useful Notes and Frequently Asked Questions

In my blog post earlier in the week I answered a few commonly asked questions about the security updates.  Below are a few additional notes based on help we've provided a few customers who have applied the update:

Do I Really Need to Apply this Update?

Yes. This update fixes security vulnerabilities that are publically known. You must install this update patch to be safe.

Make Sure You Apply the Update on All Servers in a Web-Farm

Because the patch modifies the encryption/signing behavior of certain features in ASP.NET, it is important that you apply it to all machines in a web-farm.  If you have a mix-match of patched/un-patched systems you'll have forms-authentication, webresource.axd, and scriptresource.axd requests succeed/fail depending on which server they hit in the farm (since the encryption used would be different across them).

Persistent Forms Authentication Cookie Behavior

After you apply the security update, visitors who have a persistent forms authentication cookie (the "remember me" scenario on login) will no longer be logged into your site – and will need to login again.  The ASP.NET Forms Authentication system by default automatically handles this scenario for you – and will redirect visitors with a pre-patch forms-authentication cookie to the login page you've configured for your site.  No error page is displayed – the behavior the end-user sees is the same as if the cookie had timed out.  This is a good user experience and doesn't require you to take any additional steps to ensure un-interrupted traffic to your site.

Note: We have had a few customers report problems with persistent forms-auth cookies that turned out to be issues either in their application code, or in a third party logging component they used.  Specifically, this application code attempted its own decryption of the forms authentication cookie and threw exceptions when the cookie did not decrypt successfully. If after applying the security update you see issues with people who have saved forms authentication cookies visiting your site you might also be encountering this.  There are two ways you can fix it: 1) update your code to not throw exceptions to end-users in these cases, or 2) modify the name of the forms-auth cookie that ASP.NET's Forms Authentication system uses.  Approach #2 is easy and doesn't require any code changes - just modify the <forms name=".ASPXAUTH"/> configuration section in your web.config file and switch to a different cookie name.  This will prevent your code from throwing exceptions because the old cookie failed to decrypt (instead the system will ignore the old cookie and issue all new cookies under the new cookie name you've configured).

Forms Authentication can continue to work across ASP.NET Versions

ASP.NET supports the scenario where you have multiple applications on a server, and share the same forms-authentication cookie ticket across all of them. It also supports the scenario where different applications on the site use different versions of ASP.NET.  For example, one part of the site might be built with ASP.NET 2.0, another part with ASP.NET 3.5 SP1, and another part ASP.NET 4. This continues to be supported with the security update. 

Note: If you are going to share the forms-authentication ticket across .NET 2 and .NET 3.5 SP1 or .NET 4.0 sites, then we recommend having .NET 2.0 SP2 installed to do so.

Make sure servers in a Web Farm use the same service pack of .NET 2 on all machines

We have seen an issue with a customer where they were running a site distributed across multiple servers in a web-farm, and some of the servers were running .NET 2.0 SP1 and others were running .NET 2.0 SP2.  The URLs for webresource.axd and scriptresource.axd end up being different across the two Service Pack flavors when the security patch is applied – which can cause problems if your web-farm doesn't consistently use the same service pack.  You should make sure that the same service-pack of .NET 2.0 is installed across all the machines in a web-farm if they are running the same application across all of them. 

How to Get Help If You Need It

You can ask questions and get help with the security vulnerability and update in a special ASP.NET Forum that we have setup here

You can also contact Microsoft Customer Support for help with problems or questions (including support over the phone with a technical support engineer who can help you debug problems). 


Want a Windows Phone 7? Here’s your chance!



 Want a Windows Phone 7? Here's your chance!
via Pete Brown's Blog (POKE 53280,0) by Pete Brown on 10/4/10

You've heard the news by now: we're launching Windows Phone 7 on October 12th. We have a free full day MSDN Simulcast event you can sign up for; definitely worth it for developers interested in the platform.

In the US, there are also a lot of live in-person Free Events to learn Windows Phone 7 Development listed at http://www.msdnevents.com/wp7devlaunch. I encourage you to register now as they are filling up fast.

Jesse Liberty has also been creating a ton of new Windows Phone 7 training content (tutorials and videos) on Silverlight.net in preparation for the launch. Our MSDN Phone home (quit it with the ET jokes) hub has several introduction videos as well as links to other content.

In short, we're doing a ton to help you be successful with this new platform.

 

Now here's the "free phone" part

Scott Hanselman has made a deal where two people in the community (US only for now) will win a free Windows Phone 7. Check out his blog for more. Kudos to Scott for working that out, and good luck to everyone interested in winning a free phone.

It's simple, it's free, and you may win a cool new phone. Sounds like a win to me

Microsoft Future Vision Montage 2019 Office Labs

Techies must watch viedo :)



Tuesday, September 28, 2010

You are invited to register on

This is an e-mail from website sent by Meetu Choudhary. You are invited to register on this site: http://mynangal.com/component/user/?task=register&amp;referrer=AUPRS-4C46A300E6E73.

Monday, September 20, 2010

Buzz from Meetu Choudhary



 Link to this post:
 http://www.google.com/buzz/109834034077908872313/PwEx3FeyRaJ/Experience-the-web-development-with-a-new-tool-by

11:55 am Meetu Choudhary: Experience the web development with a new tool by microsoft and try it is it is absolutely free THe new generation of Web Development

http://www.microsoft.com/web/webmatrix/default.aspx?wt.mc_id=soc-in-wag-msp-arpititpro

An URGENT ASP.NET (all versions) security Vulnerability Found

Important: ASP.NET Security Vulnerability

A few hours ago we released a Microsoft Security Advisory about a security vulnerability in ASP.NET.  This vulnerability exists in all versions of ASP.NET.

This vulnerability was publically disclosed late Friday at a security conference.  We recommend that all customers immediately apply a workaround (described below) to prevent attackers from using this vulnerability against your ASP.NET applications.

What does the vulnerability enable?

An attacker using this vulnerability can request and download files within an ASP.NET Application like the web.config file (which often contains sensitive data).

At attacker exploiting this vulnerability can also decrypt data sent to the client in an encrypted state (like ViewState data within a page).

How the Vulnerability Works

To understand how this vulnerability works, you need to know about cryptographic oracles. An oracle in the context of cryptography is a system which provides hints as you ask it questions. In this case, there is a vulnerability in ASP.NET which acts as a padding oracle. This allows an attacker to send cipher text to the web server and learn if it was decrypted properly by examining which error code was returned by the web server.  By making many such requests (and watching what errors are returned) the attacker can learn enough to successfully decrypt the rest of the cipher text.

How to Workaround The Vulnerability

A workaround you can use to prevent this vulnerability is to enable the <customErrors> feature of ASP.NET, and explicitly configure your applications to always return the same error page - regardless of the error encountered on the server. By mapping all error pages to a single error page, you prevent a hacker from distinguishing between the different types of errors that occur on a server.

Important: It is not enough to simply turn on CustomErrors or have it set to RemoteOnly. You also need to make sure that all errors are configured to return the same error page.  This requires you to explicitly set the "defaultRedirect" attribute on the <customErrors> section and ensure that no per-status codes are set.

Enabling the Workaround on ASP.NET V1.0 to V3.5

If you are using ASP.NET 1.0, ASP.NET 1.1, ASP.NET 2.0, or ASP.NET 3.5 then you should follow the below steps to enable <customErrors> and map all errors to a single error page:

1) Edit your ASP.NET Application's root Web.Config file.  If the file doesn't exist, then create one in the root directory of the application.

2) Create or modify the <customErrors> section of the web.config file to have the below settings:

<configuration>        
 
   <system.web>
 
      <customErrors mode="On" defaultRedirect="~/error.html" />
 
   </system.web>        
 
</configuration>

3) You can then add an error.html file to your application that contains an appropriate error page of your choosing (containing whatever content you like).  This file will be displayed anytime an error occurs within the web application.

Notes: The important things to note above is that customErrors is set to "on", and that all errors are handled by the defaultRedirect error page.  There are not any per-status code error pages defined – which means that there are no <error> sub-elements within the <customErrors> section.  This avoids an attacker being able to differentiate why an error occurred on the server, and prevents information disclosure.

Enabling the Workaround on ASP.NET V3.5 SP1 and ASP.NET 4.0

If you are using ASP.NET 3.5 SP1 or ASP.NET 4.0 then you should follow the below steps to enable <customErrors> and map all errors to a single error page:

1) Edit your ASP.NET Application's root Web.Config file.  If the file doesn't exist, then create one in the root directory of the application.

2) Create or modify the <customErrors> section of the web.config file to have the below settings.  Note the use of redirectMode="ResponseRewrite" with .NET 3.5 SP1 and .NET 4.0:

<configuration>
 
   <system.web>
 
     <customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/error.aspx" />
 
   </system.web>
 
</configuration>

3) You can then add an Error.aspx to your application that contains an appropriate error page of your choosing (containing whatever content you like).  This file will be displayed anytime an error occurs within the web application.

4) We recommend adding the below code to the Page_Load() server event handler within the Error.aspx file to add a random, small sleep delay. This will help to further obfuscate errors.

VB Version

Below is a VB version of an Error.aspx file that you can use, and which has a random, small sleep delay in it.  You do not need to compile this into an application – you can optionally just save this Error.aspx file into the application directory on your web-server:

<%@ Page Language="VB" AutoEventWireup="true" %>
<%@ Import Namespace="System.Security.Cryptography" %>
<%@ Import Namespace="System.Threading" %>
 
<script runat="server">
    Sub Page_Load()
        Dim delay As Byte() = New Byte(0) {}
        Dim prng As RandomNumberGenerator = New RNGCryptoServiceProvider()
        
        prng.GetBytes(delay)
        Thread.Sleep(CType(delay(0), Integer))
 
        
        Dim disposable As IDisposable = TryCast(prng, IDisposable)
        If Not disposable Is Nothing Then
            disposable.Dispose()
        End If
    End Sub
</script>
 
<html>
<head runat="server">
    <title>Error</title>
</head>
<body>
    <div>
        Sorry - an error occured
    </div>
</body>
</html>

C# Version

Below is a C# version of an Error.aspx file that you can use, and which has a random, small sleep delay in it.  You do not need to compile this into an application – you can optionally just save it into the application directory on your web-server:

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Security.Cryptography" %>
<%@ Import Namespace="System.Threading" %>
 
<script runat="server">
   void Page_Load() {
      byte[] delay = new byte[1];
      RandomNumberGenerator prng = new RNGCryptoServiceProvider();
 
      prng.GetBytes(delay);
      Thread.Sleep((int)delay[0]);
        
      IDisposable disposable = prng as IDisposable;
      if (disposable != null) { disposable.Dispose(); }
    }
</script>
 
<html>
<head runat="server">
    <title>Error</title>
</head>
<body>
    <div>
        An error occurred while processing your request.
    </div>
</body>
</html>

How to Verify if the Workaround is Enabled

Once you have applied the above workaround, you can test to make sure the <customErrors> section is correctly configured by requesting a URL like this from your site: http://mysite.com/pagethatdoesnotexist.aspx

If you see the custom error page appear (because the file you requested doesn't exist) then your configuration should be setup correctly.  If you see a standard ASP.NET error then it is likely that you missed one of the steps above.  To see more information about what might be the cause of the problem, you can try setting <customErrors mode="remoteOnly"/> – which will enable you to see the error message if you are connecting to the site from a local browser.

How to Find Vulnerable ASP.NET Applications on Your Web Server

We have published a .vbs script that you can save and run on your web-server to determine if there are ASP.NET applications installed on it that either have <customErrors> turned off, or which differentiate error messages depending on status codes.

You can download the .vbs script here.  Simply copy/paste the script into a text file called "DetectCustomErrors.vbs" and save it to disk.  Then launch a command window that is elevated as admin and run "cscript DetectCustomErrors.vbs" to run it against your local web-server.  It will enumerate all of the applications within your web server and verify that the correct <customErrors> configuration has been specified.

Description: command[1]

It will flag any application where it finds that an application's web.config file doesn't have the <customErrors> section (in which case you need to add it), or doesn't have it set correctly to workaround this attack (in which case you need to update it).  It will print "ok" for each application web.config file it finds that is fine.  This should hopefully make it easier to locate issues.

Note: We have developed this detection script over the last few hours, and will be refining it further in the future.  I will post an update in this section each time we make a change to it.

How to Find More Information about this Vulnerability

You can learn more about this vulnerability from:

Forum for Questions

We have setup a dedicated forum on the www.asp.net site to help answer questions about this vulnerability.

Post questions here to ask questions and get help about this vulnerability.

Summary

We will post more details as we learn more, and will also be releasing a patch that can be used to correct the root cause of the issue (and avoid the need for the above workaround).

Until then, please apply the above workaround to all of your ASP.NET applications to prevent attackers from exploiting it.


Re Post of : http://bit.ly/bcmwUo

Regards, May Lord Shiva Bless all of us 

Meetu Choudhary
Microsoft MVP (ASP.Net)

DNS MVM Awardee | Microsoft Certified Professional | Microsoft Certified Technology Specialist | 
Co-founder / Webmaster :
 
www.jaipurmentor.com | www.msdotnetmentor.com | www.indiaalt.net | Lead Editor / Webmaster : www.dotnetspider.com | www.silverlightclub.com  | interview.msdotnetheaven.com | forum.msdotnetheaven.com | My Blog : http://aspnetbymeetu.blogspot.com | My Profile : www.google.com/profiles/meetuchoudhary

Thursday, September 16, 2010

Count number of times day will fall in a month of a year

People who starts learning any programing language have the problem that how they can find out no. of days in a particular month of a year. Sometimes it has been given as assignments to them and sometimes our real world programming creates the situation where we have to do the same, recently I was surfing a forum site and stop by on the same question so thought to write an article about it.


I will write the function in two ways first the traditional approach and second will implement Linq in that

First: The traditional implementation:

Create a Function which will return an integer value of times the particular day will occur in a particular month of the year

/// <summary>
        /// Count number of times day will fall in a month of a year
        /// </summary>
        /// <param name="year">Year in which the month will fall</param>
        /// <param name="month">Month for which we need to count the no of days</param>
        /// <param name="dayOfWeek">day of week which we wnt to count</param>
        /// <returns>Number of times the day will fall in that month</returns>
        static int NumberOfParticularDaysInMonth(int year, int month, DayOfWeek dayOfWeek)
        {
            //create a variable to start from date i.e. 1st of that month in thta year which has passed as arrgument
            DateTime startDate = new DateTime(year, month, 1);
            //use the function of DateTime class which will return the no of days in thta particular month
            int days = DateTime.DaysInMonth(startDate.Year, startDate.Month);
            //create and initalize a variable with 0 which will hold no of occurnces in that month
            int weekDayCount = 0;
            //create a loop to count the number of occurncess of that day
            for (int day = 0; day < days; ++day)
            {
                //add days to the start date and check its day of week is what we are counting for if yes add 1 to our variable else add 0
                weekDayCount += startDate.AddDays(day).DayOfWeek == dayOfWeek ? 1 : 0;
            }
            //return the count variable
            return weekDayCount;
        }

Now what we need is just to call above function will be like this


int CountDayOfWeekInMonth = NumberOfParticularDaysInMonth(2010, 9, DayOfWeek.Friday);


The Linq Implementation of the same function will go like this


  /// <summary>
        /// Count number of times day will fall in a month of a year
        /// </summary>
        /// <param name="year">Year in which the month will fall</param>
        /// <param name="month">Month for which we need to count the no of days</param>
        /// <param name="dayOfWeek">day of week which we wnt to count</param>
        /// <returns>Number of times the day will fall in that month</returns>
        static int NumberOfParticularDaysInMonth(int year, int month, DayOfWeek dayOfWeek)
        {
            //create a variable to start from date i.e. 1st of that month in thta year which has passed as arrgument
            DateTime startDate = new DateTime(year, month, 1);
            //use the function of DateTime class which will return the no of days in thta particular month
            int days = startDate.AddMonths(1).Subtract(startDate).Days;
            //use Linq to get the no of occurance of that day
            int weekdaycount = Enumerable.Range(1, days)
                .Select(item => new DateTime(year, month, item))
                .Where(date => date.DayOfWeek == dayOfWeek)
                .Count();
            //return the count variable
            return weekdaycount;
        }


Now you can call this above function using the following statement

int CountDayOfWeekInMonth = NumberOfParticularDaysInMonth(2010, 9, DayOfWeek.Friday);


Regards, May Lord Shiva Bless all of us 
Meetu Choudhary
Microsoft MVP (ASP.Net)

DNS MVM Awardee | Microsoft Certified Professional | Microsoft Certified Technology Specialist |
Co-founder / Webmaster :
www.jaipurmentor.com | www.msdotnetmentor.com | www.indiaalt.net | Lead Editor / Webmaster : www.dotnetspider.com | www.silverlightclub.com  | interview.msdotnetheaven.com | forum.msdotnetheaven.com | My Blog : http://aspnetbymeetu.blogspot.com | My Profile : www.google.com/profiles/meetuchoudhary

Subscribe via email

Enter your email address:

Delivered by FeedBurner

MSDotnetMentor

MSDotnetMentor My Website http://msdotnetmentor.com