Friday, 22 January 2010

C# create read write XML file

Sample file

<?xml version="1.0" encoding="utf-8"?>
<root>
  <property name="One">One</property>
  <values>
    <value name="Two">Two</value>
    <value name="Three">Three</value>
  </values>
</root>

Creating/Writing XML file

public void TestXMLWriter()
{
  string filePath = @"c:\temp\sample.xml";
  List<string> values = new List<string>();
  values.Add("Two");
  values.Add("Three");
  XmlWriterSettings xmlSettings = new XmlWriterSettings();
  xmlSettings.Indent = true;
  xmlSettings.Encoding = Encoding.UTF8;
  using (XmlWriter writer = XmlWriter.Create(
    filePath,
    xmlSettings
    ))
  {
    writer.WriteStartDocument();
    writer.WriteStartElement("root");
    {
      writer.WriteStartElement("property");
      writer.WriteAttributeString("name", "One");
      writer.WriteString("One");
      writer.WriteEndElement();
      
      writer.WriteStartElement("values");
      {
        foreach (string value in values)
        {
          writer.WriteStartElement("value");
          writer.WriteAttributeString("name", value);                                    
          writer.WriteString(value);
          writer.WriteEndElement();
        }                            
      }
      writer.WriteEndElement();
    }    
    writer.WriteEndElement();
    writer.WriteEndDocument();
  }
}

Reading XML file

public void TestRead()
{
  string filePath = @"c:\temp\sample.xml";
  XPathDocument doc = new XPathDocument(filePath);
  XPathNavigator nav = doc.CreateNavigator();
  XPathNodeIterator nodeIterator = nav.Select("/root");
  foreach (XPathNavigator node in nodeIterator)
  {
    Console.WriteLine("Property Attribute: {0}",node.SelectSingleNode("property").Value);
    Console.WriteLine("Property Value: {0}",node.SelectSingleNode("property").GetAttribute("name",""));
    foreach (XPathNavigator subNode in node.Select("values/value"))
    {
      Console.WriteLine("Value Attribute: {0}", subNode.Value);
      Console.WriteLine("Value Value: {0}", subNode.GetAttribute("name", ""));
    }
  }            
}

Thursday, 21 January 2010

C# How to bind DataTable columns to DataGridView manually

image

dt = new DataTable();
dt.Columns.Add("Reference", typeof (string));
dt.Columns.Add("Version", typeof(string));
dt.Columns.Add("LatestVersion", typeof(string));
//5. Set AutogenerateColumns to false
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = dt;

C# Regex groups

public void TestRegex()
{
    //sample version regex
    string regexExpression = @"^(?<Major>\d+)\.(?<Minor>\d+)\.(?<Build>\d+)\.(?<Revision>\d+)$";
    string text = "1.0.0.0";
    Regex regex = new Regex(regexExpression);
    //case insensitive
    //Regex regex = new Regex(regextTextBox.Text, RegexOptions.IgnoreCase);
    Match match = regex.Match(text);
    if (match.Success)
    {
        foreach (string groupName in regex.GetGroupNames())
        {
            Console.WriteLine("{0}={1}", groupName, match.Groups[groupName]);
        }
    } 
}

Wednesday, 20 January 2010

C# Update GridView without redrawing, refreshing

gridView.SuspendLayout()
//do some stuff
gridView.ResumeLayout()

Windows user group permissions

net user <username> /domain

Friday, 15 January 2010

SQL Server get Date part from DateTime

SELECT DATEADD(dd,0, DATEDIFF(dd,0,GETDATE()))

Wednesday, 13 January 2010

Regular Expressions Cheatsheet, Regex

regularexpressions

Excel FaceID Viewer AddIn

http://www.dailydoseofexcel.com/archives/2004/11/23/faceid-viewer-addin/

C# Visual Studio Add-in Example

Create new VS Project (Other Project Types/Extensibility/Visual Studio Add-in)

image

If you get this error when building

image

Add this to Pre-build event command line:

IF EXIST $(TargetPath).LOCKED  
 (del $(TargetPath).LOCKED) 
ELSE 
 (IF EXIST $(TargetPath) 
   (move $(TargetPath) $(TargetPath).LOCKED))

Update Add-in location in SampleAddin.AddIn

<Assembly>SampleAddin/SampleAddin.dll</Assembly>

Add this to Post-build event command line to copy your Addin to subfolder

MKDIR "$(ProjectDir)bin\SampleAddin"
XCOPY "$(ProjectDir)bin\SampleAddin.dll" "$(ProjectDir)bin\SampleAddin" /Y /R
DEL "$(ProjectDir)bin\SampleAddin.dll"
DEL "$(ProjectDir)bin\SampleAddin.pdb"

Create New UserControl add add DTE2 property

public partial class SampleUserControl : UserControl
{
public DTE2 DTE { get; set; }

Update Connect.OnConnection method to open UserControl

if (connectMode == ext_ConnectMode.ext_cm_AfterStartup
|| connectMode == ext_ConnectMode.ext_cm_Startup)
{
string controlProgID = "SampleAddin.SampleUserControl";
string guid = "{2C73C576-6153-4a2d-82FE-9D54F4B6AD30}"; //unique per Addin

SampleUserControl obj = (SampleUserControl)Activator.CreateInstance("SampleAddin","SampleAddin.SampleUserControl").Unwrap();

AddIn addIn = _applicationObject.AddIns.Item(1);
EnvDTE80.Windows2 toolWins = (Windows2)_applicationObject.Windows;

Assembly asm = Assembly.GetExecutingAssembly();

object controlWindowRef = null;

Window controlWindow = toolWins.CreateToolWindow2(
addIn,
asm.Location,
controlProgID,
"Sample Addin",
guid,
ref controlWindowRef);

SampleUserControl control = (SampleUserControl)controlWindowRef;

control.DTE = _applicationObject;

controlWindow.Visible = true;

EnvDTE.SolutionEvents solutionEvents = _applicationObject.Events.SolutionEvents;
solutionEvents.Opened += new _dispSolutionEvents_OpenedEventHandler(solutionEvents_Opened);
}

Update Connect.Exec method to reopen your User Control if closed

if (commandName == "ReferencesAddin.Connect.ReferencesAddin")
{
if(!controlWindow.Visible)
{
controlWindow.Visible = true;
}
handled = true;
return;
}

Writing to Output Window from your app

private void LogToOutput(string text)
{
    OutputWindow ow = DTE.ToolWindows.OutputWindow;
    //this code should be in Connect class
    //ow.OutputWindowPanes.Add("SampleAddin");
    OutputWindowPane owp = ow.OutputWindowPanes.Item("SampleAddin");
    ow.Parent.AutoHides = false;
    ow.Parent.Activate();
    owp.Activate();
    owp.OutputString(text);
}

Accessing other tool windows

private void LogToOutput(string text)
{
Window win = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput);
OutputWindow ow = (OutputWindow)win.Object;
OutputWindowPane owPane;
for (int i = 1; i < ow.OutputWindowPanes.Count; i++)
{
owPane = ow.OutputWindowPanes.Item(i);
owPane.Activate();
owPane.OutputString(text);
}}