Experiments with the new SQL Data Services

The SQL Data Services that are part of the Windows Azure Service Platform just recently, and due to customer feedback, changed the way of working from a ACE (Authority, Container, Entity) model to a TDS (Tabular Data Stream) model.

Eugenio Pace in this post show how he changes the IssueTracker application from the old model to the new one, and also showing the things missing from one to the other and what needs to be done.

Very interesting reading indeed.

WPF Charting is already available in WPF Toolkit of June 2009

The long wait has finished as the WPF Charting was made available on the last WPF Toolkit release of June 2009 and now we can use all those great charts that were available for Silverlight, now also in WPF.

You can know more about this here.

Posted by NunoGodinho | with no comments
Filed under: , ,

Zodiac Signs: DateRange Class

This entry details the implementation of the DateRange class from this example in C#:

public class DateRange
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }

    // Constructor
    public DateRange(DateTime startdate, DateTime enddate)
    {
        this.StartDate = startdate;
        this.EndDate = enddate;
    }
}

This class uses the automatically implemented properties feature that was introduced to C# in .NET 3.5 to define the two DateTime properties.

The constructor in this example creates a DateRange with an appropriate start date and end date. Though this class was created for the Zodiac Signs example, it could be used anywhere a DateRange is needed.

Enjoy!

Posted by Deborah Kurata | with no comments
Filed under: , , ,

Zodiac Sign: ZodiacSigns Class

This entry details the implementation of the ZodiacSigns class from this example in C#:

public class ZodiacSigns : List<ZodiacSign>
{

}

Constructor

The following is the constructor defined in the ZodiacSigns class:

public ZodiacSigns()
{
    InitializeCollection();
}

This constructor ensures that the collection of zodiac signs is initialized when an instance of this class is created.

Methods

The following are the methods in the ZodiacSigns class:

public string FindSign(DateTime desiredDate)
{
    // Find the name of the Zodiak sign with the date within the ranges
    var query = from z in this
                from d in z.DateRanges
                where (desiredDate >= d.StartDate) &&
                       
(desiredDate <= d.EndDate)
                select z.Name;
    string name = query.FirstOrDefault();
    return name;
}

The FindSign method uses LINQ to find the date within the defined ranges. It returns the name of the appropriate sign.

private void InitializeCollection()
{
    // This could potentially read all of these from a file.
    // NOTE: This data may not be accurate
    this.Add(new ZodiacSign("Rat",
        new List<DateRange> {
            new DateRange(new DateTime(1996, 2,19),
                new DateTime(1997, 2,6)),
            new DateRange(new DateTime(2008, 2,7),
                new DateTime(2009, 2,25))}));
    this.Add(new ZodiacSign("Ox",
        new List<DateRange> {
            new DateRange(new DateTime(1997, 2,7),
                new DateTime(1998, 2,27)),
            new DateRange(new DateTime(2009, 2,26),
                new DateTime(2010, 2,13))}));
    this.Add(new ZodiacSign("Tiger",
        new List<DateRange> {
            new DateRange(new DateTime(1998, 2,28),
                new DateTime(1999, 2,15)),
            new DateRange(new DateTime(2010, 2,14),
                new DateTime(2011, 2,2))}));
    this.Add(new ZodiacSign("Rabbit",
        new List<DateRange> {
            new DateRange(new DateTime(1999, 2,16),
                new DateTime(2000, 2,4)),
            new DateRange(new DateTime(2011, 2,3),
                new DateTime(2012, 1,22))}));
    this.Add(new ZodiacSign("Drago",
        new List<DateRange> {
            new DateRange(new DateTime(2000, 2,5),
                new DateTime(2001, 2,23)),
            new DateRange(new DateTime(2012, 1,23),
                new DateTime(2013, 2,9))}));
    this.Add(new ZodiacSign("Snake",
        new List<DateRange> {
            new DateRange(new DateTime(2001, 1,24),
                new DateTime(2002, 2,11)),
            new DateRange(new DateTime(2013, 2,10),
                new DateTime(2014, 1,30))}));
    this.Add(new ZodiacSign("Horse",
        new List<DateRange> {
            new DateRange(new DateTime(2002, 2,12),
                new DateTime(2003, 1,31)),
            new DateRange(new DateTime(2014, 1,31),
                new DateTime(2015, 2,18))}));
    this.Add(new ZodiacSign("Sheep",
        new List<DateRange> {
            new DateRange(new DateTime(2003, 2,1),
                new DateTime(2004, 2,21)),
            new DateRange(new DateTime(2015, 2,19),
                new DateTime(2016, 2,7))}));
    this.Add(new ZodiacSign("Monkey",
        new List<DateRange> {
            new DateRange(new DateTime(2004, 1, 22),
                new DateTime(2005, 2, 8)),
            new DateRange(new DateTime(2016, 2, 8),
                new DateTime(2017, 1, 27))}));
    this.Add(new ZodiacSign("Rooster",
        new List<DateRange> {
            new DateRange(new DateTime(2005, 2, 9),
                new DateTime(2006, 1, 28)),
            new DateRange(new DateTime(2017, 1, 28),
                new DateTime(2018, 2, 15))}));
    this.Add(new ZodiacSign("Dog",
        new List<DateRange> {
            new DateRange(new DateTime(2006, 1, 29),
                new DateTime(2007, 2, 17)),
            new DateRange(new DateTime(2018, 2, 16),
                new DateTime(2019, 2, 4))}));
    this.Add(new ZodiacSign("Pig",
        new List<DateRange> {
            new DateRange(new DateTime(2007, 2, 18),
                new DateTime(2008, 2, 6)),
            new DateRange(new DateTime(2019, 2, 5),
                new DateTime(2020, 2, 21))}));
}

The InitializeCollection method does exactly what it sounds like … creating the set of date ranges associated with each zodiac sign. This code takes advantage of the list initializers now available in C#.

Enjoy!

Posted by Deborah Kurata | with no comments
Filed under: , , , ,

Interesting articles regarding .NET RIA Services

.NET RIA Services are here to make our life easier and they were introduced as part of the Silverlight 3.0 but are not only for Silverlight.

Some interesting reading about it is this:

Posted by NunoGodinho | with no comments
Filed under: ,

Zodiac Sign: ZodiacSign Class

This entry details the implementation of the ZodiacSign class from this example in C#:

public class ZodiacSign
{
    // Properties
    public string Name { get; set; }
    public List<DateRange> DateRanges { get; set; }

    // Constructor
    public ZodiacSign(string name, List<DateRange> dateranges)
    {
        this.Name = name;
        this.DateRanges = dateranges;
    }
}

This example uses the automatically implemented properties feature that was introduced to C# in .NET 3.5 to define the two properties: Name and DateRanges.

The constructor in this example creates a zodiac sign with an appropriate name and set of date ranges.

Enjoy!

Posted by Deborah Kurata | with no comments
Filed under: , , ,

Interesting reading about Entity Framework 4.0

Entity Framework has suffered great changes and in order to know more about them I recommend the following reading:

POCO (Plain Old CLR Object or Persistence ) in the Entity Framework 4.0

“Why is POCO important in Entity Framework? Is important because now we have the ability to really separate the Storage Model from the Conceptual Model, and being the Conceptual Model our normal CLR Objects, that was not possible in previous versions of Entity Framework. This is a huge breakthrough for this 4.0 version. Is not perfect, and in this technologies it never is but it’s very interesting”

I hope you enjoy the reading.

Applying OOP to Simple Situations: Chinese Zodiac Signs

Here is the story defining the simple use case for this application:

  1. The user picks a date between 2/19/1996 and 2/5/2019.
  2. The system displays the appropriate Chinese zodiac sign (Monkey, Dog, Rat, etc)

Seems simple enough. So how to implement this …

Defining the Classes

The first step in using OOP with a simple situation is the same as with any application … define the "nouns”.

These are the first nouns I came up with:

  • Zodiac sign
  • Date range

The next step is to think through each of these nouns and determine which make sense as classes for building the code to support this feature.

Zodiac Sign

This feature needs to work with a zodiac sign, so a ZodiacSign class makes sense.

In addition, this feature needs to retain the set of zodiac signs. So a ZodiacSigns (plural) class is also needed to track the list of ZodiacSign instances.

Date Range

Each zodiac sign is associated with a date range, so a DateRange class makes sense to track the dates.

Defining the Properties and Methods

The next step is to define what data that each class retains (called properties in OOP) and what functionality that the class provides (called methods in OOP).

After reviewing the nouns, three classes were defined:

ZodiacSign

This class provides the definition of a single Chinese zodiac sign. The properties for this class include:

  • Name: Name of the sign such as “dog” or “monkey”.
  • DateRanges: Set of date ranges associated with the sign.

ZodiacSigns

This class manages the list of all zodiac signs. To leverage the .NET Framework List features, this class can inherit from the built in generic List class.

This class has two methods:

  • InitializeCollection: Builds the list with the set of zodiac signs and date ranges.
  • FindSign: Given a date, finds the sign.

DateRange

This class has two simple properties:

  • Start Date: First date of the date range.
  • End Date: End date of the date range.

Using the Classes

The user interface portion of the application creates an instance of the ZodiacSigns class and calls the FindSign method as needed.

Enjoy!

Posted by Deborah Kurata | with no comments
Filed under: , , , ,

Windows Azure Service Platform: July CTP Breaking Changes Announcement

The Windows Azure Team has just release a July CTP Breaking changes announcement since the already breaking changes in the Workflow Services, now there are changes also in the .NET Service Bus.

“(…)Queues and Routers data will NOT be persisted and restored after the maintenance. Users will need to back up their data if they wish to restore them after the July 2009 CTP release. Please see below for detail.

As previously announced, the existing Workflow Service will be removed from .NET Services in the July 2009 CTP release. Any solutions that currently rely on the Workflow Services will have to be modified on or before 7/7/2009 9am PST in order to continue functioning smoothly. Existing solution Workflow Service metadata such as Workflow Type will also be deleted and cannot be retrieved after the July 2009 CTP release. (…)”

Impacts on:

“(…)NET Services and the .NET Services Portal will be unavailable during this period.(…)

Read more here.

Curiosidade: SCOM R2 ou SP2?

Antes do SCOM 2007 R2 ser lançado a Microsoft pensava em lançar o SP2 para o SCOM, isso faz um ano mais ou menos. Porém o SP2 nunca foi lançado oficial, na época isso estava sobre o NDA (contrato que um MVP tem de manter sigilo sobre as informações de alguns produtos), mas agora isso já faz parte da história e não tem mais problemas comentar por aqui J

 

Tenho este SP2 aqui comigo, na época fiz a instalação dele algumas vezes, e posso garantir que ele mesmo se tornou o R2, com muitas outras melhorias e correções é claro. Mas a curiosidade aqui fica por conta do R2 mesmo, visto que o SP2 nunca veio ao público. Quando você termina a instalação do SCOM 2007 R2, vá até a pasta:

 

C:\Program Files\System Center Operations Manager 2007\Tools\TMF

 

Na pasta Tools nós temos alguns dos arquivos utilizados pelo TraceConfig.exe (Ferramenta de diagnóstico que o Microsoft Customer Support Services (CSS) geralmente utiliza em seus chamados de problemas no SCOM, mas este não é o assunto deste texto J). E é aqui que está o “legal” da coisa, a Microsoft manteve o seguinte nome para um dos arquivos:

 

MOMv3.SP2_7221_signed.cab

 

Onde o MOMv3 é a versão do SCOM 2007 (já que o MOMv1 é o MOM 2000 e o MOMv2 é o MOM 2005), 7221 é a versão da Build do SCOM 2007 R2 e por fim o SP2 está perdido ai no meio. Claro, tem coisas que só o time do produto pode explicar J

 

Abraços,

 

Cleber Marques

Microsoft Most Valuable Professional (MVP)
Projeto MOF Brasil: Simplificando o Gerenciamento de Serviços de TI
www.mof.com.br | www.clebermarques.com | www.clebermarques.com.br

Posted by Cleber Marques | with no comments
Filed under: ,

July User group meeting

This months meeting will be virtual.  I will arrange another virtual meeting for late August. 

We should have a physical meeting in September


When: Thursday, Jul 23, 2009 7:00 PM (BST)


Where: Virtual

*~*~*~*~*~*~*~*~*~*

Subject is PowerShell output. What we see. What we get. How we can change it. methods of output

Notes


Richard Siddaway has invited you to attend an online meeting using Live Meeting.
Join the meeting.
Audio Information
Computer Audio
To use computer audio, you need speakers and microphone, or a headset.
First Time Users:
To save time before the meeting, check your system to make sure it is ready to use Microsoft Office Live Meeting.
Troubleshooting
Unable to join the meeting? Follow these steps:

  1. Copy this address and paste it into your web browser:
    https://www.livemeeting.com/cc/usergroups/join
  2. Copy and paste the required information:
    Meeting ID: 94F2K5
    Entry Code: q.bhRK7Hs
    Location: https://www.livemeeting.com/cc/usergroups

If you still cannot enter the meeting, contact support

Notice
Microsoft Office Live Meeting can be used to record meetings. By participating in this meeting, you agree that your communications may be monitored or recorded at any time during the meeting.

Posted by RichardSiddaway | with no comments

BPOS – Update, interessantes aus der Exchange-Ecke

Wie ich auf dem letzten Exchange User Group Meeting noch verkündet habe ist der Umzug auf BPOS bisher eine Einbahnstraße. Einmal dorthin gezogene Emailkonten können lediglich mit Outlook exportiert und per Handarbeit wieder zurück auf einen eigenen Server umgezogen werden. Microsoft wird nun lt. dem Technet – Blog der Schweizer Technologieberater ein Update einspielen, so das die einmal zu BPOS migrierten Konten auch wieder zurückmigriert werden können. Gerade für Migrationen wird es damit für mich zu einem sehr geeigneten Mittel. Wie genau das aussehen wird in Kürze.

Viele Grüße

 

Walter Steinsdorfer

Posted by Wstein | with no comments
Filed under:

Multithreading: using VolatileXXX instead of the volatile keyword

In the previous post we’ve seen how we can use the C# volatile keyword to guarantee that those nasty load-load reordering stay away from our code. As I’ve said before, we can also use the static Thread.VolatileRead or Thread.VolatileWrite for having more control over the way fences are applied to our code. Going back to our previous volatile example, the question is: do we really need a fence whenever we access our instance variable?

Looking at the code, I guess that we can get  away by just using an acquire fence on the initialization of the instance. Recall that an acquire fence is an optimization of the full fence and ensures that no load or store that comes after the fence can be moved before the fence (it’s just what we need to ensure proper initialization and eliminate the possible load/load reorderings allowed by the CLR).

With this in mind, lets update our sample, ok? Btw, we’ll be using another variable for controlling initialization (we’re picking an integer). This is your best option for initializing value types since you can’t control it size or check it for null (don’t forget our previous discussion on word size, alignment and .NET). Here’s the final code:

class Lazy{
  private Object _locker = new Object();
  private SomeObject _instance = null;
  private Int32 _initialized = 0;
  public SomeObject SomeObject {
    get {
      if (Thread.VolatileRead(ref _initialized) == 0) {
        lock (_locker) {
          if (_initialized == 0) {
            _instance = new SomeObject();
          }
        }
        return _instance;
      }
    }
  }
}

This code is also correct and will behave properly in all the current architectures that run Windows and the CLR. There’s no need for running another VolatileRead on the inner comparison due to a thing called control dependency (check this post by Joe Duffy for more info). Notice that in these posts our main objective is ensuring that you end up getting only one instance of a specific type. As I’ve said, if you don’t care about creating multiple instances and only need to ensure that you’ll have only one active instance, you can only use the Interlocked.CompareExchange method for that. We’ll see how in the next post. Keep tuned!

Posted by luisabreu | with no comments
Filed under: ,

MasterMind: Peg Class

This entry describes the Peg class from this example in further detail:

Public Class Peg

End Class

Properties

The properties of the class are as follows:

Private _Column As Integer
''' <summary>
''' Gets the column of this peg.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property Column() As Integer
    Get
        Return _Column
    End Get
    Private Set(ByVal value As Integer)
        _Column = value
    End Set
End Property

The Column property defines the column of the board that contains this peg. The setter is private because once the peg is created, its location cannot be moved.

Private _Correct As Boolean?
''' <summary>
''' Gets or sets whether the peg is in a correct position.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property Correct() As Boolean?
    Get
        Return _Correct
    End Get
    Friend Set(ByVal value As Boolean?)
        _Correct = value
    End Set
End Property

The Correct property defines whether this peg denotes a correct answer. A correct answer requires that the peg be of the same color and column position as the correct answer.

Private _PegColor As Color?
''' <summary>
''' Gets or sets the peg color.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property PegColor() As Color?
    Get
        Return _PegColor
    End Get
    Set(ByVal value As Color?)
        _PegColor = value
    End Set
End Property

The PegColor property defines the color of this peg as defined by the user.

Private _Row As Integer
''' <summary>
''' Gets the row containing the peg.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property Row() As Integer
    Get
        Return _Row
    End Get
    Private Set(ByVal value As Integer)
        _Row = value
    End Set
End Property

The Row property defines the row of the board that contains this peg. The setter is private because once the peg is created, its location cannot be moved.

Constructor

The following is the constructor defined in the Peg class:

''' <summary>
''' Constructs a new instance in a specific position.
''' </summary>
''' <param name="columnIndex"></param>
''' <param name="rowIndex"></param>
''' <remarks></remarks>
Public Sub New(ByVal columnIndex As Integer, ByVal rowIndex As Integer)
    Me.Column = columnIndex
    Me.Row = rowIndex
    Me.PegColor = Nothing
End Sub

Download the sample code (that is currently only in VB) from here.

Enjoy!

Posted by Deborah Kurata | with no comments
Filed under: , ,

MasterMind: MasterMind Class

This entry describes the MasterMind class from this example in further detail:

Public Class MasterMind

End Class

Properties

The properties of the class are as follows:

Private _Answer As List(Of Color)
''' <summary>
''' Gets the answer.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property Answer() As List(Of Color)
    Get
        Return _Answer
    End Get
    Private Set(ByVal value As List(Of Color))
        _Answer = value
    End Set
End Property

The Answer property is a list of correct colors. This property has a Private setter because the answer itself is managed internal to the MasterMind class.

Private _Board As List(Of Peg)
''' <summary>
''' Gets or sets the board for the game.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property Board() As List(Of Peg)
    Get
        Return _Board
    End Get
    Private Set(ByVal value As List(Of Peg))
        _Board = value
    End Set
End Property

The Board property is a list of Pegs. This property also has a Private setter because the board is managed internal to the MasterMind class.

Private _CurrentTurn As Integer
''' <summary>
''' Gets or sets the number of the current turn.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks>
''' The user cannot go back to any prior turn.
''' </remarks>
Public Property CurrentTurn() As Integer
    Get
        Return _CurrentTurn
    End Get
    Private Set(ByVal value As Integer)
        _CurrentTurn = value
    End Set
End Property

The CurrentTurn property counts the number of guesses. This property also has a Private setter because it is managed internal to the MasterMind class.

Private Shared _GameColors As List(Of Color)
''' <summary>
''' Gets the game colors.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Property GameColors() As List(Of Color)
    Get
        If _GameColors Is Nothing Then
            _GameColors = New List(Of Color)
            _GameColors.Add(Color.Red)
            _GameColors.Add(Color.Yellow)
            _GameColors.Add(Color.Green)
            _GameColors.Add(Color.Purple)
            _GameColors.Add(Color.Blue)
            _GameColors.Add(Color.Black)
            _GameColors.Add(Color.Orange)
            _GameColors.Add(Color.Pink)
        End If
        Return _GameColors
    End Get
    Private Set(ByVal value As List(Of Color))
        _GameColors = value
    End Set
End Property

The GameColors property defines the set of available peg colors. These are hard-coded into the application, but could instead be settable by a game configuration feature (which is not implemented in this sample). Because the set of colors is the same for every game (at least in this implementation), they are defined using a Shared property.

Private _NumberOfRows As Integer = 8
''' <summary>
''' Gets the number of rows that should be allowed in the game.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property NumberOfRows() As Integer
    Get
        Return _NumberOfRows
    End Get
    Private Set(ByVal value As Integer)
        _NumberOfRows = value
    End Set
End Property

The NumberOfRows property defines the number of rows in the game. This implementation defines a default value of 8 rows. This could instead by set by the user with a configuration feature (which is not implemented in this sample).

Private _NumberOfHoles As Integer = 4
''' <summary>
''' Gets the number of holes in each row that should be allowed in the game.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property NumberOfHoles() As Integer
    Get
        Return _NumberOfHoles
    End Get
    Private Set(ByVal value As Integer)
        _NumberOfHoles = value
    End Set
End Property

The NumberOfHoles property defines the number of holes in each row in the game. This implementation defines a default value of 4 holes. This could instead by set by the user with a configuration feature (which is not implemented in this sample).

Constructors

The following are the constructors defined in the MasterMind class:

''' <summary>
''' Construct the game with the default holes and rows
''' </summary>
''' <remarks></remarks>
Public Sub New()
    ' Initialize the game
    InitializeGame()
End Sub

''' <summary>
''' Construct the game with a defined number of holes and rows.
''' </summary>
''' <param name="holesPerRow"></param>
''' <param name="rows"></param>
''' <remarks></remarks>
Public Sub New(ByVal holesPerRow As Integer, ByVal rows As Integer)
    Me.NumberOfHoles = holesPerRow
    Me.NumberOfRows = rows

    ' Initialize the game
    InitializeGame()
End Sub

When a new instance of the game is created, the InitializeGame method is called to set up the board and define an answer.

Methods

The following are the MasterMind class methods:

#Region " CreateAnswer"
    ''' <summary>
    ''' Creates the answer for the game
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub CreateAnswer()
        Dim maxColorIndex As Integer = GameColors.Count - 1
        Dim colorIndex As Integer

        ' Clear the answers
        Answer = New List(Of Color)

        ' Set up for random numbers
        Dim randomColor As New Random()

        ' Build the answer
        For hole As Integer = 0 To NumberOfHoles - 1
            colorIndex = randomColor.Next(0, maxColorIndex)

            Answer.Insert(hole, GameColors(colorIndex))
        Next hole

    End Sub
#End Region

The CreateAnswer method uses the Random .NET Framework class to create a valid answer. Notice that this is a private method and cannot be called directly.

#Region " CreateBoard"
    ''' <summary>
    ''' Creates the board for the game.
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub CreateBoard()
        ' Create the board as a list of potential pegs
        Board = New List(Of Peg)

        Dim peg As Peg

        ' Build a control for each hole in the board.
        For rowIndex As Integer = 0 To NumberOfRows - 1
            For pegIndex As Integer = 0 To NumberOfHoles - 1
                ' Create a peg
                peg = New Peg(pegIndex, rowIndex)

                ' Add it to the board
                Board.Add(peg)
            Next
        Next

    End Sub
#End Region

The CreateBoard method builds the structure of the board with the defined number of rows and holes. Notice that this is a private method and cannot be called directly.

#Region " InitializeGame"
    ''' <summary>
    ''' Initialize the game.
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub InitializeGame()
        ' Create the board
        CreateBoard()

        ' Create the answer
        CreateAnswer()

        ' Initialize the try
        CurrentTurn = 1
    End Sub
#End Region

The InitializeGame method creates the board and defines the answer. It is also a private method that is called when the game is constructed.

#Region " ProcessGuess"
    ''' <summary>
    ''' Processes the user's guess.
    ''' </summary>
    ''' <remarks></remarks>
    Public Function ProcessGuess() As Boolean
        ' Row is 0-based; turns are 1-based
        Dim row As Integer = CurrentTurn - 1
        Dim allCorrect As Boolean = True

        ' Get the pegs for the row
        Dim rowPegs = Board.Where(Function(p) p.Row = row)

        For Each p As Peg In rowPegs
            If p.PegColor = Answer(p.Column) Then
                ' This answer is correct
                p.Correct = True
            Else
                ' This answer is incorrect
                p.Correct = False
                allCorrect = False
            End If
        Next

        ' Increment the turn
        CurrentTurn += 1

        Return allCorrect
    End Function
#End Region

The ProcessGuess method is a public method that is called by the UI each time the user is finished with a row and wants to submit it as a guess.

Download the sample code (that is currently only in VB) from here.

Enjoy!

Posted by Deborah Kurata | with no comments
Filed under: , ,

Applying OOP to Simple Games: MasterMind

Someone on the MSDN forums recently asked how to apply object-oriented programming (OOP) principles to a basic game. So I thought it would be an interesting project to develop a very simple sample game using OOP.

I selected MasterMind because it is a relatively simple game. If you are not familiar with the game, you can find a description and picture here.

Defining the Classes

The first step in using OOP with a game is the same as with any application … define the "nouns”.

These are the first nouns I came up with:

  • Game
  • Board
  • Code maker player
  • Code breaker player
  • Answer pattern
  • Guess pegs
  • Key (or Feedback) pegs

The next step is to think through each of these nouns and determine which make sense as classes for building the game.

Game

The application will need to keep track of all of the facets of the game. So a game class makes sense. Since the class will only describe the MasterMind game, I selected to call this class “MasterMind”.

Board

Hmmm. Did the game need a separate board class? Other than defining the board layout, there was not much that the board itself needed to do. So the game could have a Board class with one method to create the board. Or the MasterMind class could have a Board property and the method to create the board. I selected to make the board a property to keep this “introduction to OOP” example as simple as possible.

Code Maker Player

This is the player that defines the pattern that is the correct answer. One of the nice things about playing MasterMind as a computer game is that you don’t need this player. The game itself can select a valid correct answer.

Code Breaker Player

This is the player that is guessing the pattern and is the user of your game. You could track the name of the player and their best score. In “phase 1” of this simple game, the decision was made not to implement a player class. This can be implemented in “phase 2”. For now, every player is a guest and no score is retained after a game is complete.

Answer Pattern

The pattern of pegs that defines the answer does not really need to perform any actions. It is more a property of a particular game.

Guess Peg

As the game progresses, the user puts pegs into the board as a guess. Pegs are a key part of the game, so I selected to include a “Peg” class.

Key (Feedback) Peg

With a board game, it is difficult to draw onto each guess peg to define whether it is correct or incorrect and still reuse the pegs in a new game. Instead, in the real-world game pegs are added to the sides to depict which are correct or incorrect. This is not necessary in the computer game because each guess peg can be marked as correct or incorrect.

Defining the Properties and Methods

The next step is to define what data that each class retains (called properties in OOP) and what functionality that the class provides (called methods in OOP).

After reviewing the nouns, only two classes were defined:

MasterMind

This class manages the basic game including the game board and game play. Because this game is on the computer, there is no need for the user to “pick up” a peg of the desired color and place it into a hole in the board. Rather, the board is a set of “blank” pegs. The user can select to color each peg in a row to form a guess. The correct pegs are left in tact. The incorrect pegs are x’ed out.

The MasterMind class needs properties such as:

  • Board: The board property defines the set of pegs that make up the game board. The user can then set the color of each peg in a row to form a guess.
  • NumberOfRows: The number of rows to display in the game.
  • NumberOfHoles: The number of holes per row to display in the game.
  • GameColors: The set of colors used by the game.
  • Answer: The list of colors that form the answer.
  • CurrentTurn: Keeps track of the number of turns required to find the answer.

The basic set of methods for the MasterMind class include:

  • CreateBoard: Creates the internal board structure based on the number of rows and number of holes per row. NOTE: Since good coding practice dictates separating our “business objects” from our UI, this code does not draw the board. Rather, it creates the internal data structures for managing the board.
  • CreateAnswer: Uses the Random .NET features to randomly pick a set of colors that form the correct answer.
  • ProcessGuess: Checks the colors that the user defined for pegs in a particular row and x’s out the incorrect pegs.

Peg

The Peg class manages a particular hole in the game board. The Peg class needs properties such as:

  • Column: Column on the game board.
  • Row: Row on the game board.
  • PegColor: Color of the peg as defined by the user.
  • Correct: Whether or not the peg color is correct.

Using the Classes

The user interface portion of the application creates an instance of the MasterMind class and calls its properties and methods as needed. The UI has the code that draws the game board using the MasterMind class and Peg class properties.

Download the sample code (that is currently only in VB) from here.

Enjoy!

Posted by Deborah Kurata | 2 comment(s)
Filed under: , , , ,

Amazon

My book has appeared on Amazon’s listings

http://www.amazon.co.uk/Powershell-Practice-Richard-Siddaway/dp/1935182005/ref=sr_1_1?ie=UTF8&s=books&qid=1246906667&sr=1-1

http://www.amazon.com/Powershell-Practice-Richard-Siddaway/dp/1935182005/ref=sr_1_1?ie=UTF8&s=books&qid=1246906789&sr=1-1

The dates are slightly optimistic   :-)

Thats nice.  Just need to finish the last chapter and it enters the final phase

Technorati Tags: ,
Posted by RichardSiddaway | with no comments
Filed under:

Playing with dates

I happened to notice that Sundays date was 5 July 2009.  Not particular astute you may think but I noticed it because I’d written it as 5/7/9.  English date format puts the day then the month so this may not make sense in other formats.

The fact that there was a difference to two between the day and the month and the same between the month and the year intrigued me.  It doesn’t take much. So I decided to look at other dates that follow that pattern

001
002
003
004
for ($i=3; $i -le 12; $i++){
    $date = Get-Date -Month $i -Day $($i -2) -Year $(2000 + $i +2)
    "{0} {1}" -f $date.DayOfWeek, $date.ToShortDateString()   
}

 

It doesn’t need much to do this.  A for loop – notice we start at 3 so we don’t get into negative days. Time travel by PowerShell now there’s a thought

Get-Date | Set-Now –Era Jurassic

gets us back to the dinosaurs.  OK I’ll stop.

We can use Get-Date and give it a month, day and year to create the date.  Note that I add 2000 to get the current sequence of dates. This sequence will happen every century.  One thing I noticed was that Get-Date takes the year you give it literally.  It doesn’t make any allowance for the century if you don’t supply the full year.  Compare

PS> Get-Date -Day 1 -Month 1 -Year 9

01 January 0009 19:46:48

PS> [datetime]"1/1/9"

01 January 2009 00:00:00

Finally I use a formatted string to display the date (in short form) and the day of the week.  The day of week doesn’t appear to add any more information but I was curious.

Technorati Tags: ,
Posted by RichardSiddaway | with no comments
Filed under:

SCOM: Monitorando espaço livre em disco

Aproveitando que estes dias eu respondi uma pergunta relacionada com a monitoração de espaço livre em discos com o SCOM eu resolvi escrever este tópico. Imagine que você queira monitorar o espaço em disco de servidores com o Windows 2003:

 

1. Importe o Management Pack Windows Server 2003 Operating System

http://www.microsoft.com/downloads/details.aspx?FamilyId=3529D233-5E3E-4B51-8F66-5D6F27005EC3&amp;displaylang=en

 

·         Se estiver usando o SCOM 2007 SP1 faça download do MP, instale e importe na console

·         Se estiver usando o SCOM 2007 R2 apenas busque o MP na console com acesso a internet

 

2. Aguarde cerca de 10 minutos para que os monitores sejam adequados aos seus servidores (o tempo de espera aqui depende do tamanho do seu ambiente)

 

Este MP tem um monitor chamado Logical Disk Free Space, que por padrão traz o seguinte:

 

ü  Gerar Erro para discos de sistema com 5% ou menos de espaço livre

ü  Gerar Erro para discos de sistema com 100 MB ou menos de espaço livre

 

ü  Gerar Erro para discos que não são de sistema com 5% ou menos de espaço livre

ü  Gerar Erro para discos que não são de sistema com 1 GB ou menos de espaço livre

 

ü  Gerar Aviso para discos de sistema com 10% ou menos de espaço livre

ü  Gerar Aviso para discos de sistema com 200 MB ou menos de espaço livre

 

ü  Gerar Aviso para discos que não são de sistema com 10% ou menos de espaço livre

ü  Gerar Aviso para discos que não são de sistema com 2 GB ou menos de espaço livre

 

E esta verificação será feita a cada 3600 segundos (1 hora).

 

Se quiser alterar algum destes padrões é só acessar: Painel Authoring > Management Pack Objects > Monitoring e buscar pelo monitor Logical Disk Free Space para fazer a sua Override (atenção para o escopo quando fizer a busca).

 

Abraços,

 

Cleber Marques

Microsoft Most Valuable Professional (MVP)
Projeto MOF Brasil: Simplificando o Gerenciamento de Serviços de TI
www.mof.com.br | www.clebermarques.com | www.clebermarques.com.br

Posted by Cleber Marques | with no comments
Filed under: ,

Microsoft Security Advisory Notification- July 6, 2009

Issued: July 6, 2009

Security Advisories Updated or Released Today

* Microsoft Security Advisory (972890)
- Title: Vulnerability in Microsoft Video ActiveX
Control Could Allow Remote Code Execution
- http://www.microsoft.com/technet/security/advisory/972890.mspx
- Revision Note: Advisory published.

Posted by Don | with no comments
More Posts Next page »