Quick way to check .NET Framework version in Powershell

Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse |
Get-ItemProperty -name Version,Release -EA 0 |
Where { $_.PSChildName -match '^[^0-9S]'} |
Select PSChildName, Version, Release, @{
name="Product"
expression={
switch -regex ($_.Release) {
    "378389" { [Version]"4.5" }
    "378675|378758" { [Version]"4.5.1" }
    "379893" { [Version]"4.5.2" }
    "393295|393297" { [Version]"4.6" }
    "394254|394271" { [Version]"4.6.1" }
    "394802|394806" { [Version]"4.6.2" }
    {$_ -gt 394806} { [Version]"Undocumented 4.6.2 or higher, please update script" }
    }
  }
}

Very useful tip to check .Net Framework version:

Run above commands in Windows Powershell to get .Net version currently installed in your windows.

Powershell check .Net Framework version

Powershell check .Net Framework version

References:

Reformat/Re-align code in Visual Studio

Found a useful tip when I looking for StyleCop essay.

How to: Reformat your code in Visual Studio

In brief, do these:

  1. Select the code you want to re-format (CTRL + A if want to re-format whole file).
  2. Press CTRL + K
  3. Press CTRL + F
  4. Done.

 

If work in VB.Net, it will auto set TitleCase and align the code, however in C#, it only re-align the code, but this is the feature I like the most since C# code never align for you again if the alignment was out.

 

Reference: How to: Reformat your code in Visual Studio

Keyword: Alignment, align, code style

Add New Field in MS Access Programmatically using ADOX (C#.Net)

You need to add reference before you start (Refer to my previous post – Rename Field in MS Access Programmatically using ADOX (C#.NET) )


using ADOX;

// Skipped namespace and public class here...

private void btnUpdate_Click(object sender, EventArgs e)
 {
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb;Persist Security Info=False";
   CatalogClass cat = new CatalogClass();

cat.let_ActiveConnection(connString)

   AddField(cat, "TargetTable", "Employee_Name_2", DataTypeEnum.adVarWChar, 50, string.Empty);
}

private void AddField(ADOX.CatalogClass cat, string tableName, string newFieldName, DataTypeEnum varType, int size, string defaultValue)
 {
   // #1
   // cat.Tables[tableName].Columns.Append(newFieldName, varType, size);

   ColumnClass col = new ColumnClass();
   col.Name = newFieldName;
   col.Type = varType;
   col.DefinedSize = size;

   // Make this field become nullable field.
   col.Attributes = ColumnAttributesEnum.adColNullable;

   // #2
   cat.Tables[tableName].Columns.Append((object)col, DataTypeEnum.adInteger, 0);
   // #3 - Assign default value after column appended.
   if (!string.IsNullOrEmpty(defaultValue))
   {
      col.Properties["Default"].Value = defaultValue;
   }
}

Issues when using Append() method

Issues when using Append() method

Issues when using Append() method (Refer #1 in source code above):

  1. You only can defines field name, variable type and size for the new field.
  2. New field are not allow NULL when created. (Tested in Access 2003).
  3. You cannot sets default value for new field.

In order to create nullable column with default value,  I use a ColumnClass object – col, and set the necessary properties.

Few things here:

  1. From reference #2, col object need to pass as object type in Append(…) method.
  2. When you pass col object into Append() method, the rest of the arguments in Append(…) actually do NOT overwrite the ‘Type’ and ‘DefinedSize’ properties in col object. So the 2nd argument and 3rd argument is just to fill up the extra places in Append(…).
  3. In reference #3, you only can assign the default value after appended the new field. (Refer to FIX: Cannot Use ADOX to Set Default Value for Column Property)

~~~ [ End ] ~~~

Reference:

  1. Rename Field in MS Access Programmatically using ADOX (C#.NET)
  2. FIX: Cannot Use ADOX to Set Default Value for Column Property

Keyword: ALTER COLUMNS, ALTER TABLE, Microsoft Access

Rename Field in MS Access Programmatically using ADOX (C#.NET)

MS Access is a lightweight database and lack of some database feature, for example it does not support the SQL query to rename the field. Therefore we need to workaround to rename the field in MS Access.

MS Access SQL reference: Microsoft Office Access – SQL Reference

Instead I never had VB6 in my PC but only .NET, so I looking for workaround in .NET. Below are the references:

  1. ADO.NET Programmer’s Reference – Chapter 16 – COM Interoperability (Just search for ‘ADOX’ in this article to check for ADOX usage).
  2. How to rename the column name in MS Access table (Reference in VB6, Main source for me to convert ADOX into .NET)

You need to add the ADOX COM reference into your .NET project because we are going to use ADOX to do the trick.

Add ADOX COM Reference from Solution Explorer

Add ADOX COM Reference from Solution Explorer

First you need to to go to Add Reference from Solution Explorer, add Microsoft ADO Ext.2.8 for DDL and Security from COM tab.

Then, use the code below,


using ADOX;

// Skipped namespace and public class here...

private void btnUpdate_Click(object sender, EventArgs e)
 {
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb;Persist Security Info=False";
   CatalogClass cat = new CatalogClass();
   // cat.ActiveConnection = connString    <-- Error here
   // Cannot assign to cat.ActiveConnection directly.
   // Use code at below to assign connection string in C#.

cat.let_ActiveConnection(connString);

RenameField(cat, "TargetTable", "Staff", "Employee");

}

private void RenameField(CatalogClass cat, string tableName, string originalFieldName, string newFieldName)
 {
    cat.Tables[tableName].Columns[originalFieldName].Name = newFieldName;
}

Run the button btnUpdate_Click to make the trick work, so the field Staff will rename to Employee.

Note that you cannot assign the connection string directly to cat.ActiveConnection since it is not a string object, and I guess it only accept Connection object from ADO. Use cat.let_ActiveConnection(connString) instead.

Micorsoft example on ADOX connection string – PRB: Unhandled Exception When You Set ADO Property to a String in Visual C# .NET

~~~ End ~~~

Upcoming article: Add New Field in MS Access Programmatically using ADOX (C#.Net)

Reference:

  1. Microsoft Office Access – SQL Reference
  2. ADO.NET Programmer’s Reference – Chapter 16 – COM Interoperability
  3. How to rename the column name in MS Access table
  4. http://support.microsoft.com/kb/309047

Keyword:  ALTER COLUMNS, ALTER TABLE, Microsoft Access

TryParse – out parameter cannot work with Property

Today I facing the exact situation written in reference #1, I tried to pass the property to TryParse out parameter.

Below is the sample code:

int i;

public int I
{
  get;
  set;
}

int.TryParse(str, out I);   // pass I (not i) as out parameter

But I got this error message:

A property or indexer may not be passed as an out or ref parameter.

Till now I cannot get any satisfactory explanation about this error, however I think the most acceptable answer for now is from reference #2.

The fact that a property looks and feels like a variable is deceiving. When compiled, a property becomes two methods: one for the Getter and one of the Setter. This is why the property fails when you try to use it in TryParse().

Solution is simple, just place the original variable as out parameter.

This question make me need to understand MSIL one day to find out what happen inside there…

Reference:

  1. Mano’s Tech Blog – Different ways to convert string to an integer in C#
  2. Why TryParse Can’t Get Property?

Keyword: Accessor, get,set,getter,setter,error

Commond Prompt for Visual Studio .Net

If you install Visual Studio 2005, you would not face this problem, because the commond prompt and other tools already appear in your classical Windows Start Menu.

However if you install Visual Studio Express Edition, you would not get any shortcuts for those tools, let say you need the command prompt which support Visual Studio .Net, you need to type “cmd” in ‘Run’ dialog, and change the directory to .NetFramework folder.

Unfortunately I using Express edition in office, therefore I need to work around to get the ‘Visual Studio Command Prompt’. After compare with ‘real’ Visual Studio command prompt, below is my work around, the key is:

  1. Call a new console screen from batch file.
  2. Attach necessary path for .Net in new console screen, so you do not need to change to .Net directory when u need the command in .Net.

Please refer to your own .Net Framework version when doing this, example below is just for .Net version 2.0 .

Steps:

  1. Create an empty batch file, insert line in # 2 into batch file, DO include double quote.
  2. cmd /K “path=%path%;C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727&&cls”
  3. Place the batch file in appropriate directory, create a shortcut for the batch file.
  4. Select Properties of the shortcut, change ‘Start in:‘ from current directory to ‘C:\(arbitrary directory)’
  5. Now double click the shortcut, Windows prompt up a clean cmd console screen which support .Net Framework command (since already setup in PATH).

 

Explaination for step # 2:

  • Command string after /K will be carry out and apply to new console process.
  • the ‘&&’ is the separator for seperated commands in same line, the line above consists two commands, first is append the path, second is clear the screen after append path.

 

Explanation for steps # 3 and # 4:

  • There are two ways to set the PROMPT in console window, the first way already show in steps 3 & 4, so you just put any startup directory you like in step 4.
  • The second way, you need to amend step 2 a bit, change it to below:

cmd /K “path=%path%;C:\WINDOWS\Microsoft.NET\Framework\

v2.0.50727&&PROMPT=C:\Windows$G&&cls”

Ya, it is just add in another command for new console screen (Set the PROMPT=C:\Windows$G).

 

Keyword: Visual Studio Console Window, Tool, Tools, IDE, Command prompt

Display forward slash (’/’) in date using C#

Still remember my previous post ? Display forward slash (’/’) in date under VB6

I face the same issue in C#, however the solution this time is slightly different with solution in VB6.

//
//   First solution : surround the desired date seperator
//   ('/' in this case) with single quote.
//
string date = DateTime.Today.Date.ToString("dd'/'M'/'yyyy");

//
//   Second solution : same like solution in VB6,
//   except add '@' in front of the string.
//
string date = DateTime.Today.Date.ToString(@"dd\/MM\/yyyy");

Referencehttp://authors.aspalliance.com/aspxtreme/sys/demos/datetimeformats.aspx

Keyword: Date seperator, date format, date pattern, C#, .Net, forward slash