Saturday, November 13, 2010

Abstract Properties


Please read my previous article on Properties

Now, let’s move on to the second example to demonstrate how to define abstract properties.
Few things to keep in mind while using abstract properties
1.   It does not provide an implementation of the property accessor
2.   It has to be override in subclasses.
Example 2
In this example I am making three files:
  • abstractshape.cs: The abstract Shape class that contains an abstract Perimeter property.
  • shapes.cs: The subclasses of the Shape class.
  • shapetest.cs: A test program to display the areas of some Shape-derived objects.

File 1 - abstractshape.cs
This file declares the Shape class that contains the Perimeter property of the type double

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

namespace ConsoleApplication1
{
    public abstract class Shape
    {
        private int myId;

        //Creating Constroctor with argument to set the id property
        public Shape(int shapeid)
        {
            Id = shapeid;   // calling the set accessor of the Id property
        }

        //craeting Id property for the shape class
        public int Id
        {
            get
            {
                return myId;
            }

            set
            {
                myId = value;
            }
        }

        // Perimeter is a read-only property - only a get accessor is needed:
        public abstract double Perimeter
        {
            get;
        }
        //overriding tostring() method
        public override string ToString()
        {
            return string.Format("{0}", Id) + " Perimeter = " + string.Format("{0:F2}", Perimeter);
        }
    }
}


Code Discussion
  • Property declaration itself contains the modifier, for example:
public abstract double Perimeter

  • While declaring an abstract property (in our example perimeter), we only need to indicate what will be the property accessors, without their implementation. In this example, only a Get accessor is available, so the property is read-only.

File 2 - shapes.cs
The following code shows three subclasses of Shape and how they override the Perimeter property to provide their own implementation.

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

namespace ConsoleApplication1
{
    public class Square : Shape
    {
        private int Side;

        public Square(int side, int id)
            : base(id)
        {
            Side = side;
        }

        public override double Perimeter
        {
            get
            {
                // Given the side, return the Perimeter of a square:
                return 4 * Side;
            }
        }
    }

    public class Circle : Shape
    {
        private int myRadius;

        public Circle(int radius, int id)
            : base(id)
        {
            myRadius = radius;
        }

        public override double Perimeter
        {
            get
            {
                // Given the radius, return the Perimeter of a circle:
                return 2 * System.Math.PI * myRadius;
            }
        }
    }

    public class Rectangle : Shape
    {
        private int mylength;
        private int mybreadth;

        public Rectangle(int length, int breadth, int id)
            : base(id)
        {
            mylength = length;
            mybreadth = breadth;
        }

        public override double Perimeter
        {
            get
            {
                // Given the length and breadth, return the Perimeter of a rectangle:
                return 2 * mylength * mybreadth;
            }
        }
    }

}
Code Discussion
  • Shape class is Inherited in all three classes Rectangle, circle, square and id is passed to the base class constructor:
public Rectangle(int length, int breadth, int id)
            : base(id)

  • Each Class extending, implementing or inheriting the shape class has overridden and implemented the perimeter property which was read only as only get assessor was set. According to their own needs.
public override double Perimeter
        {
            get
            {
                // Given the length and breadth, return the Perimeter of a rectangle:
                return 2 * mylength * mybreadth;
            }
        }


File 3 - shapetest.cs
This file will contain a test class in which we will implement the classes we have created above and will check their results. By creating no of shape derived objects and calculating their perimeters

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

namespace ConsoleApplication1
{
    class shapetest
    {
        public static void Main()
        {
            //creating an array of shape class
            Shape[] shapes =
         {
             //with an object of each subclass
            new Square(5, 1),
            new Circle(3, 2),
            new Rectangle( 4, 5, 3)
         };

            //writing on the console
            Console.WriteLine("Shapes Collection");
            //going through each object in shape class
            foreach (Shape s in shapes)
            {
                //as we have overriddin the tostring property so we can just write the object in the console.writeline
                Console.WriteLine(s);               
            }
            //waiting for user to press a key so that the screen (console) will be displayed till user press any key
            Console.ReadKey();
        }

    }
}



Output
Shapes Collection
1 Perimeter = 20.00
2 Perimeter = 18.85
3 Perimeter = 40.00



Code Discussion
  • An array of Shape class is created with 3 objects each of 3 different subclasses
Shape[] shapes =
         {
            new Square(5, 1),
            new Circle(3, 2),
            new Rectangle( 4, 5, 3)
         };
·         And then the perimeter property is used by tostring() of shape object to display on the console. Which is used in foreach loop to iterate through all shape objects?

foreach (Shape s in shapes)
            {
         
      Console.WriteLine(s);               
            }


Building and Running the Sample within Visual Studio
To build and run the Properties samples
  1. Open the solution.
  2. In Solution Explorer, right-click the project properties and click Application tab
  3. From Startup object select the shapetest as StartUp class.
  4. From the Debug menu, click Start without Debugging.
  5. Repeat the preceding steps for car class in example one.

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

Subscribe via email

Enter your email address:

Delivered by FeedBurner

MSDotnetMentor

MSDotnetMentor My Website http://msdotnetmentor.com