Cmdlets Extending Windows PowerShell

Coming across a nice article in MSDN about Extending Windows PowerShell With Custom Commands that I paste a short overview of it here :

 

There are some pretty significant differences between a Windows PowerShell cmdlet and commands in other standalone shell environments. For instance,

·         a cmdlet is an instance of a Microsoft® .NET Framework class; it is not a standalone executable.

·         Cmdlets generally output objects rather than text and should not format their output.

·         A cmdlet processes its input objects from an object pipeline rather than from a stream of text.

·         A cmdlet should not parse its own arguments and it should not specify a presentation for errors.

·         Finally, cmdlets are record-oriented and generally process a single object at a time.

 

To declare a .NET class as a cmdlet, you attribute the class with the CmdletAttribute attribute (which is the only required attribute for any cmdlet). When you specify the CmdletAttribute attribute, you must specify a verb and noun name pair, which will be used as the name of the cmdlet. This should describe what the cmdlet does and what sort of resource the cmdlet works with.

 

To declare parameters for a cmdlet, you must first define the properties that represent the parameters. To inform the Windows PowerShell runtime that a property is a cmdlet parameter, you add a ParameterAttribute attribute to the property definition.

 

In order to use these new cmdlets, you need to add them to the Windows PowerShell environment. Windows powerShell has the ability to dynamically add cmdlets to the session via a snap-in. To avoid potential confusion with MMC snap-ins, a Windows PowerShell snap-in is called a PSSnapIn.

To create a PSSnapIn, you need to write a bit of code that will perform two tasks. First, it provides identification for your snap-in so it can be distinguished from other snap-ins installed on your system. Second, it provides information for properly installing the snap-in and for creating the appropriate registry entries to allow Windows PowerShell to find the assembly.

Characteristics of a Leader

The following is coted from the book Analyzing Requirements and Defining Solution Architectures.

Finding Effective Leaders

For the person in charge of putting together a project team, the first task is to decide who will work on the project. This seemingly simple (but more often complex) decision can dramatically affect the project’s outcome.

Finding leaders within an organization is not a difficult process. By definition, leaders are recognized by those they work with. It’s important to remember that we are talking about leaders here, not bosses. Every organization has its share of managers, directors, and so on, but the hierarchical structure of an organization does not determine who the true leaders are. Actions and characteristics, rather than job titles, identify leaders.

Why do we need leaders? Because we have so many followers. It’s important to realize that labeling people as leaders and followers does not imply a value judgment. We must have leaders to be successful, but we must also have followers. Leaders provide direction for the team. Followers get the work done. The team needs to strike a balance between its leaders and followers. It must decide what to do and then must do it, so both leaders and followers are equally important and valuable. An absence of either leaders or followers will hinder the project’s success.

Certain characteristics are present in many leaders. Common qualities of leaders include:

  • Understanding and meeting the needs of others.
  • Communicating well with groups and individuals.
  • Earning the respect of internal and external customers.
  • Displaying commitment to well-defined purposes.
  • Making a positive difference.
  • Having confidence in his or her abilities.
  • Practicing good problem-solving skills.
  • Helping others to develop their skills.

Many people will read this list and say, "I do those things." More people will read this list and say, "I intend to do those things." But being a leader also means knowing the difference between intent and impact. When measuring their own success, people measure their intent; when measuring other people’s success, they measure their impact. The impact that leaders have on others may or may not be their intent, and leaders’ intent may not have the impact they were striving for. The proper way to measure people’s leadership skills is by the impact they actually have, not by their intent. We can summarize this concept by saying, "Other people’s perceptions are reality."

Total Participation in Design

Jim McCarthy summarizes the concept of total participation in design in Dynamics of Software Development:

The goal in any product design is to have the best ideas become the basis of the product. Everybody on the team should be working to accomplish that goal.

Each role participates in the generation of the Functional Specification because each role has a unique perspective of the design and tries to ensure that the design meets their role’s objectives, as well as the project team’s objectives.

 

Cannot modify members of ‘item’ because it is a ‘foreach iteration variable’

 I had a compile time issue with using my custom list. The code simply looks like the following:

 

foreach (ItemType item in listOfItems)

    item.CustomAccessor = "value";

 

And compiler complains with error:

            Cannot modify members of ‘item’ because it is a ‘foreach iteration variable’

 

This is because the ItemType is defined as a  struct and not as a class. Doing so the iteration of foreach will result to some copies of the heap that are not reflecting the real objects. The question that has often been asked is why did you define your ItemType as struct and not as a class…. which I will answer it in other discussion.

  

Attributes to consider applying when writing a custom control

The original author published this : Eilon Lipton’s Blog

 

Almost every custom control has at least one additional public property, and that public property as well as the control itself should probably have at least a few attributes applied to them. Attributes tell the designer host (Visual Studio) or the parser (ASP.NET) interesting things about your control that might not be evident from just its name and its type. Launch any decent class browser tool and you’ll see that every control that shipped in ASP.NET and ASP.NET AJAX has several attributes on it as well as their properties and events.

By applying the proper set of attributes you can significantly increase the usefulness of your control in several ways. For example, the DescriptionAttribute provides helpful text to the person designing the page. The ValidationPropertyAttribute is required when the person designing the page wants to validate the value of your control. Following is a list of the most useful and important attributes you can apply to your control and its properties and events.

Control attributes:

  • ControlValueProperty
     – Used by data source parameters to get the "intrinsic" value of the control. For example, DropDownList’s "intrinsic" value is its SelectedValue property.
  • DefaultEvent
     – Set the event for which to create an event handler when double clicking the control in the designer.
  • DefaultProperty
     – Set the default selected property in the designer’s property grid.
  • NonVisualControl
     – Hide the control at design time when "Non Visual Controls" is unchecked from the View menu.
  • ParseChildren
     – The full name is really "parse children as properties".
     – Set to true if the inner contents of the control represent properties as opposed to child controls.
     – True by default on controls deriving from WebControl; false by default otherwise.
  • PersistChildren
     – The full name is really "persist child controls".
     – Set to true if the designer should persist child controls as the inner contents.
     – False by default on controls deriving from WebControl; true by default otherwise.
     – 99.9% of the time PersistChildren has the opposite value of ParseChildren.
  • SupportsEventValidation
     – Indicates that the control’s client-side calls to __doPostBack() should be validated on the server for security purposes.
  • Themable
     – Indicates that by default all the control’s properties can be customized via themes. Individual properties can also be marked with this attribute to override the behavior.
     – True by default for controls that derive from WebControl.
  • ValidationProperty
     – Required when a control can be validated.
     – Somewhat similar to the ControlValueProperty in that they often point at the same property.
  • ViewStateModeById
     – Indicates that viewstate should be loaded based on control IDs as opposed to being loaded based on the index of the control in the child controls collection.

Property attributes:

  • Bindable
     – Indicates at design time only whether the property should appear by default in the Edit Databindings dialog.
  • Browsable
     – Indicates whether the property is visible in the property grid at design time.
  • Category
     – Determines in which category the property will appear when the property grid is in category mode.
  • DefaultValue
     – Get-only property: Since get-only properties are never persisted anyway, no default value is needed.
     – Get/Set value type property: Must be set.
     – Get/Set reference type property: Must be null so that it shows up as non-bold in the property grid.
  • Description
     – Determines the help text that will show in the property grid’s lower help panel.
  • DesignerSerializationVisibility
     – Controls whether the property is persisted in the markup (see also PersistenceMode).
     – Use this to prevent get/set properties from being persisted at all.
  • EditorBrowsable
     – Affects whether the property appears in Intellisense.
  • IDReferenceProperty
     – Specifies that the property represents a control ID, and optionally the type of the target control. Not used by Visual Studio 2005.
  • MergableProperty
     – Affects whether the property shows up in the property grid when multiple controls are selected.
     – If the property is Browsable and is a reference type then set Mergable=false (except immutable reference types, such as string).
  • PersistenceMode
     – Controls how the property is persisted in the markup.
     – Simple-valued properties should use the default, which is Attribute.
     – Collection, template, and complex (e.g. styles) should use InnerProperty.
     – InnerDefaultProperty should never be used since it causes compatibility problems. For example, if in the next version of your control you want another inner property, it won’t work properly.
     – EncodedInnerDefaultProperty should also rarely be used for similar reasons as InnerDefaultProperty.
     – In ASP.NET 2.0 support was added for strings to be InnerProperties, which is good for large multi-line string values, such as XmlDataSource’s Data property.
  • Themable
     – Overrides the value of the attribute on the control to determine whether the property can be customized via themes.

Event attributes:

  • Browsable
     – Same as properties.
  • Category
     – Same as properties.
  • Description
     – Same as properties.
  • EditorBrowsable
     – Same as properties.

 

Customize attachment settings in outlook

I got a mail in my outlook and the application didn't let me open the attachment because it might be unsecure. The mail was from a know person and I want to access the attachment file. It appears that you can override the security level as described by Microsoft ( Customize attachment settings in Outlook 2007) and let some file types allowed to be opened.
 
To do this you have to tell the outlook which types of files are allowed. You do it in the registry:
HKCUSoftwareMicrosoftOffice12.0OutlookSecurityLevel1Remove
 
You simply mention the extentions seporated by a semicolon like this one :
pts;bat;reg;vbs
 
 

Read/Write files from/to an Image field in SQL-Server

In this example I have a table called Attachment having a field of time Image which holds binary value. In this field I am going to put any type of file in a byte array and read it back. I have defined a class called Attachment to read and write the records. This class has a variable called Data which is defined as byte[]

Read Image Field

This example passes a reference to an object called record of type Attachment. The record object has an attribute called Data where the attachment file will be streamed into it.

/// <summary>
/// Read a TestLog record identified by the given parameter
/// </summary>
/// <param name="id">the record key</param>
/// <returns>a Attachment object that maps to the record</returns>
public static void Read(Attachment record)
{


if (record.Id < 1)
throw new ApplicationException("Invalid Record ID");

using (SqlConnection sqlConnection1 = Connection)
{
SqlCommand cmd
= sqlConnection1.CreateCommand();
cmd.CommandType
= CommandType.Text;
cmd.CommandText
= "SELECT TestLogId, Name, Description, CreatedBy, CreateDate, Data FROM Attachment WHERE ID=@Id";

SqlParameter par
= new SqlParameter("@Id", SqlDbType.Int);
par.Value
= record.Id;
cmd.Parameters.Add(par);


sqlConnection1.Open();
SqlDataReader dr
= cmd.ExecuteReader();
if (!dr.HasRows)
throw new ApplicationException(String.Format("Could not find TestLog '{0}'.", record.Id));

dr.Read();

if (!dr.IsDBNull(0))
record.TestLogID
= dr.GetInt32(0);
if (!dr.IsDBNull(1))
record.Name
= dr.GetString(1).TrimEnd();
if (!dr.IsDBNull(2))
record.Description
= dr.GetString(2).TrimEnd();
if (!dr.IsDBNull(3))
record.CreatedBy
= dr.GetString(3).TrimEnd();
if (!dr.IsDBNull(4))
record.CreateDate
= dr.GetDateTime(4);

// Read the bytes into the Data attribute of the record
int PictureCol = 5; // the column # of the BLOB field
record.Data = new Byte[(dr.GetBytes(PictureCol, 0, null, 0, int.MaxValue))];
dr.GetBytes(PictureCol,
0, record.Data, 0, record.Data.Length);

dr.Close();
sqlConnection1.Close();
}
}

Write File into the record

/// <summary>
/// Save the Attachment record. If Id doesn't exist, it will create a new one, otherwise it will update.
/// </summary>
/// <param name="record">the attachment record to save</param>
public static void Save(Attachment record)
{

using (SqlConnection sqlConnection1 = Connection)
{
SqlCommand cmd
= sqlConnection1.CreateCommand();
cmd.CommandType
= CommandType.StoredProcedure;
cmd.CommandText
= "SaveAttachment";

#region Add the input parameter and set its value

SqlParameter par
= new SqlParameter("@TestLogId", SqlDbType.Int);
par.Value
= record.TestLogID;
cmd.Parameters.Add(par);

par
= new SqlParameter("@Name", SqlDbType.NVarChar, 128);
par.Value
= record.Name;
cmd.Parameters.Add(par);

par
= new SqlParameter("@Description", SqlDbType.NVarChar, 320);
par.Value
= record.Description;
cmd.Parameters.Add(par);

par
= new SqlParameter("@Data", SqlDbType.VarBinary, record.Data.Length);
par.Value
= record.Data;
cmd.Parameters.Add(par);

#endregion

// Add the output parameter
par = new SqlParameter("@Id", SqlDbType.Int, 4);
par.Direction
= ParameterDirection.InputOutput;
par.Value
= record.Id;
cmd.Parameters.Add(par);

sqlConnection1.Open();
cmd.ExecuteNonQuery();
int id = Int32.Parse(cmd.Parameters["@ID"].Value.ToString());
record.Id
= id;
sqlConnection1.Close();
}
}

Read the file into the variable

/// <summary>
/// Read the file into the Data field
/// </summary>
/// <param name="path">A valid path to the file</param>
public void ReadFromFile(string path)
{
System.IO.FileStream fs
=
new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);

this.data = new Byte[fs.Length];
fs.Read(
this.data, 0, this.data.Length);
fs.Close();
}

Write the byte array to a File

This simple method is using the name of the file as is stored in the attachment record to save in the location specified by parameter.

/// <summary>
/// Save the content into a file
/// </summary>
/// <param name="path">the full path to write to</param>
public void SaveToFile(string path)
{
if (path.EndsWith("\"))
path
+= "\";

string DestFilePath = path + this.name;
System.IO.FileStream fs
=
new System.IO.FileStream(DestFilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write);

fs.Write(
this.data, 0, this.data.Length);
fs.Close();

}

Welcome

I have lost my blogs that I used to store on http://blogs.wdevs.com/a.Panahy/ The site is just gone down and made me desporate. I decided to start my own. Thanks to NiMS I got this subdomain up and running in short time and the idea is to build up my personal blogs in this blog site.
The site will start with my technical blogs to support my (leaking) memory. I might have a copy of them on other online site (maybe on codeproject.com or msn.Live) and later on probably some private blogs.
for now all I want to say is yoopy