2012年12月30日日曜日

FOR Clause in Transact-SQL

This clause is very import in responding when in XML format.
http://msdn.microsoft.com/ja-jp/library/ms173812.aspx

The default return of
Select * From table_name For XML AUTO
is very ugly.

e.g,

Select * From dbo.Staff FOR XML AUTO

returns

<dbo.Staff Name="Bill" Age="10" Gender="M" Occupation="Children" Company="Home" />
<dbo.Staff Name="Bob" Age="23" Gender="M" Occupation="Driver" Company="Driver" />
<dbo.Staff Name="Jack" Age="30" Gender="M" Occupation="Doctor" Company="Microsoft" />
<dbo.Staff Name="Jim" Age="53" Gender="M" Occupation="Sniper" Company="SWAT" />
<dbo.Staff Name="Merry" Age="24" Gender="F" Occupation="Waitress" Company="DotClub" />
<dbo.Staff Name="Nathan" Age="33" Gender="M" Occupation="Driver" Company="Sagawa" />
<dbo.Staff Name="Shelly" Age="35" Gender="F" Occupation="Actress" Company="NHK" />
<dbo.Staff Name="Tracy" Age="30" Gender="F" Occupation="Accountant" Company="PG" />

Select * From dbo.Staff FOR XML PATH, ROOT('Staff')

returns

<Staff>
  <row>
    <Name>Bill</Name>
    <Age>10</Age>
    <Gender>M</Gender>
    <Occupation>Children</Occupation>
    <Company>Home</Company>
  </row>
  <row>
    <Name>Bob</Name>
    <Age>23</Age>
    <Gender>M</Gender>
    <Occupation>Driver</Occupation>
    <Company>Driver</Company>
  </row>
  <row>
    <Name>Jack</Name>
    <Age>30</Age>
    <Gender>M</Gender>
    <Occupation>Doctor</Occupation>
    <Company>Microsoft</Company>
  </row>
  <row>
    <Name>Jim</Name>
    <Age>53</Age>
    <Gender>M</Gender>
    <Occupation>Sniper</Occupation>
    <Company>SWAT</Company>
  </row>
  <row>
    <Name>Merry</Name>
    <Age>24</Age>
    <Gender>F</Gender>
    <Occupation>Waitress</Occupation>
    <Company>DotClub</Company>
  </row>
  <row>
    <Name>Nathan</Name>
    <Age>33</Age>
    <Gender>M</Gender>
    <Occupation>Driver</Occupation>
    <Company>Sagawa</Company>
  </row>
  <row>
    <Name>Shelly</Name>
    <Age>35</Age>
    <Gender>F</Gender>
    <Occupation>Actress</Occupation>
    <Company>NHK</Company>
  </row>
  <row>
    <Name>Tracy</Name>
    <Age>30</Age>
    <Gender>F</Gender>
    <Occupation>Accountant</Occupation>
    <Company>PG</Company>
  </row>
</Staff>

which can be readed like this

using System;
using System.Data.SqlClient;
using System.Xml;
 
namespace DataBaseDemoReadToXML
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var conn =
                new SqlConnection(connection_string);
            conn.Open();
            var command = new SqlCommand("Select * From dbo.Staff FOR XML PATH, ROOT('Staff')"conn);
            XmlReader reader = command.ExecuteXmlReader();
            reader.Read();
            Console.WriteLine(reader.ReadOuterXml());
            conn.Close();
 
            Console.ReadLine();
        }
    }
}



2012年12月27日木曜日

A Basic Workflow Console Application

1. Create a workflow console application in VS2012.
2 By default a Workflow1.xaml file is generated in the project.
3. Drag and drop a Flowchart, a Flowdecision, an Assign to the designer.
4. Add variables and argument in workflow environment, make it look something like this.
 5. Edit Program.cs.
using System;
using System.Activities;
using System.Collections.Generic;
 
namespace WorkflowConsoleApplication1
{
 
    class Program
    {
        static void Main(string[] args)
        {
            // Prepare argument name:value pair Dictionary<string,object>, 
            //      where string is the variable name
            //      and object is the value of the variable
            var inArg = (IDictionary<stringobject>)new Dictionary<stringobject>();
            inArg.Add("Gender","Female");
 
            // Initialize the workflow. 
            Activity workflow1 = new Workflow1();
            // Invoke it by passing the argument name:value pair
            // and get the result in the same way.
            // Extract the result by specifying the name of the variable.
            Console.WriteLine(WorkflowInvoker.Invoke(workflow1inArg)["Result"]);
            Console.ReadLine();
        }
    }
}
 6. Very ugly but simple enough and done.

One more thing, you can edit the Workflow1.xaml file in code by right-click the file and select view code.

2012年12月23日日曜日

Connect to MySql (XAMPP) from .Net by using C#

This note shows how to connect to a database "forcsharp"  created
in MySql (installed alongwith XAMPP) from a C# program in VS2012.

1. Create a project in VS.
In project, add reference, add "MySql.Data" and "MySql.Web".
If there is none of them, you should go to the following link,
download and install MySql Connector for .Net.
http://www.mysql.com/downloads/connector/

2. Create a database called "forcsharp" and a table called "Customer"
in MySql through XAMPP, MySql Admin.

3. Add using MySql.Data.MySqlClient.
Connect to database use connection string.
Server=myserver;Database=mydatabase;Uid=myuserid;Pwd=mypassword;"
using System;
using System.Data;
using MySql.Data.MySqlClient;
 
namespace XMLDemo2
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            // Connect by connection string.
            const string myConnectionString = "Server=localhost;Database=forcsharp;Uid=root;Pwd=";
            var connection = new MySqlConnection(myConnectionString);
            connection.Open();
 
            // Create command and fill dataset with result by using adapter.
            MySqlCommand cmd = connection.CreateCommand();
            cmd.CommandText = "Select * From Customer";
            var dataAdapter = new MySqlDataAdapter(cmd);
            var dataSet = new DataSet();
            dataAdapter.Fill(dataSet);
 
            Console.WriteLine(dataSet.GetXml());
            connection.Close();
            Console.ReadLine();
        }
    }
}

2012年12月20日木曜日

Compiling WPF

Several tips in compiling C# WPF files in command console.
1. If references are not setup in environment,
you have to refer to the assemblies in default directory:
C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\
2. Compile options /target:winexe is needed if you do not
want a console window appear behind your window.

Example:

// win.cs
using System.Windows;
using System.Windows.Controls;

public class MyClass:Window
{
 public MyClass()
 {
  this.Title = "Nat";
  this.Width = 300;
  this.Height= 200;
 }
}

// app.cs 
using System;
using System.Windows;
public class MyApp : Application
{
 [STAThread]
 
 static void Main()
 {
  MyApp app = new MyApp();
  app.Startup += app.Fireup;
  app.Run();
 }

 void Fireup(object sender, StartupEventArgs args)
 {
  MyClass wm = new MyClass();
  wm.Show();
 }
}

To compile, Compile.bat
csc /target:winexe app.cs win.cs /r:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationFrameWork.dll" /r:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationCore.dll" /r:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\WindowsBase.dll"

Create a simplest WPF application.

First, you need a xaml file to specify the application.
<!--  app.xaml  -->
<Application
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 StartupUri="win.xaml"/>

Second, you need to specify the window.
<!-- win.xaml -->
<Window
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 Title="Simplest XAML"
 Width="320"
 Height="230">
 Hello!
</Window>

Finally, a .proj file to tell the compile how to do everything.
<!-- hello.proj -->
<Project
 xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
 DefaultTarget="Build">
 <PropertyGroup>
  <AssemblyName>SimplestWPF</AssemblyName>
  <OutputType>winexe</OutputType>
  <OutputPath>.\</OutputPath>
 </PropertyGroup>
 <ItemGroup>
  <ApplicationDefinition Include="app.xaml" />
  <Page Include="win.xaml" />

  <Reference Include="System" />
  <Reference Include="WindowsBase" />
  <Reference Include="PresentationCore" />
  <Reference Include="PresentationFramework" />
 </ItemGroup>
 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
 <Import Project="$(MSBuildToolsPath)\Microsoft.WinFX.targets" />
</Project>

Navigate VS command console to the directory which holds these 3 files,
enter "msbuild".

Binding data to ListBox in WPF

It is simple to bind data to listbox in windows form.
Just drag a listbox control to the form and name it "listBox1".
Then assign data to the datasource ( here, I read an array of string from the file).

namespace DatatBindingDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.listBox1.DataSource = File.ReadAllText(@"C:\Users\Z\Desktop\DatatBindingDemo\Days.txt").Split();
        }
    }
}
In WPF, you have to do it in another way.
There is no datasource in listbox.
First, in MainWindow.xaml.cs

using System.IO;
using System.Windows;

namespace WpfDataBindingDemo
{
    public class MyData
    {
        public static string[] Days
        { get
            {
                return File.ReadAllText(@"C:\Users\Z\Desktop\WpfDataBindingDemo\Days.txt").Split();
            }
        }
    }

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

And in MainWindow.xaml

<Window x:Class="WpfDataBindingDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfDataBindingDemo"
        Title="MainWindow"
        Width="525"
        Height="350">
    <Grid>
        <ListBox ItemsSource="{Binding DataContext.Days, RelativeSource={RelativeSource Self}}">
            <ListBox.DataContext>
                <local:MyData />
            </ListBox.DataContext>
        </ListBox>
    </Grid>
</Window>

Notice that first you have to add reference to CLR by xmlns:local
then attach MyData to listbox datacontext. (obtained from local)
finally bind the itemsource to the datacontext by using {Binding...}

p.s. It is not necessary to use the word local. You can use any word you like in xmlns:local.