Archive for the ‘C#’ Category

Finally, my post after 3 months long. I’ve been really busy lately :(

This tutorial is about a multi-page application in WPF, in other words an application which just consists of one window but it has multiple pages.  Actually, this is the WPF version from multi-page Silverlight application.

The solution is quite cool but simple,  here’s the steps:

1. Create WPF Application project in Visual Studio (2008 or 2010)

2. Rename Window1 class into PageSwitcher

3. Your code in PageSwitcher.xaml.cs should be like below. there are two Navigate functions (overloading), if you want to pass information to other page, you should call one with object state parameter (i’ll explain this later).

using System;
using System.Windows;
using System.Windows.Controls;

namespace WPFPageSwitch
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class PageSwitcher : Window
    {
        public PageSwitcher()
        {
            InitializeComponent();
            Switcher.pageSwitcher = this;
            Switcher.Switch(new MainMenu());
        }

        public void Navigate(UserControl nextPage)
        {
            this.Content = nextPage;
        }

        public void Navigate(UserControl nextPage, object state)
        {
            this.Content = nextPage;
            ISwitchable s = nextPage as ISwitchable;

            if (s != null)
                s.UtilizeState(state);
            else
                throw new ArgumentException("NextPage is not ISwitchable! "
                  + nextPage.Name.ToString());
        }
    }
}

4. The next steps is creating ISwitchable Interface


namespace WPFPageSwitch
{
  	public interface ISwitchable
  	{
    	void UtilizeState( object state );
  	}
}

5. Create a static class,  name this class as Switcher


using System.Windows.Controls;

namespace WPFPageSwitch
{
  	public static class Switcher
  	{
    	public static PageSwitcher pageSwitcher;

    	public static void Switch(UserControl newPage)
    	{
      		pageSwitcher.Navigate(newPage);
    	}

    	public static void Switch(UserControl newPage, object state)
    	{
      		pageSwitcher.Navigate(newPage, state);
    	}
  	}
}

6. Each page is represented by a user control, implement all user controls with ISwitchable

7. If you want to navigate to other user control, use this code :

Switcher.Switch(new YourUserControl());

8. Then, you just have to call UtilizeState(Object state) … but you’ll need to parse transfered object

9. How the result looks like :

Download the solution here

Farseer Physic Engine merupakan 2D Physic engine (betul, hanya 2D) yang dapat digunakan pada platform silverlight, WPF, XNA, dan XBOX 360.
Farseer physics dirancang untuk mengontrol posisi dan rotasi suatu entitas dalam game tiap satuan waktu berdasarkan hukum fisika yang berlaku Dalam dunia nyata, benda bergerak dan berputar karena gaya diterapkan dan torsi. Begitupula dalam Farseer. Objek disebut “Body” mewakili suatu benda di dunia nyata. Seketika gaya dan torsi diberikan, “body” bereaksi sesuai dengan hukum 2D fisika. Posisi dan perputaran “body” ini kemudian digunakan untuk posisi dan rotasi suatu entitas pada game.

In this article, i will explain following below in Windows Workflow Foundation 4.0:

  • Simple sequence
  • Variables
  • Arguments
  • if-else activity

 

First, open your Visual Studio 2010, and create a new project and the template is “Workflow Console Application”

 

Then… you will see workfow designer, in toolbox, click “sequence” and drag it into workflow designer

 

In “Arguments tab” add these arguments :

(more…)

New Operators in .NET 4.0 ???

Posted: April 18, 2010 in C#, Programming
Tags:

There is two new operator in .NET 4.0, goes to and is approached by ( –> and <– ), Oh yeah… it is not pointer like in C++

Let see how it is working :

using System;

namespace TestNewOperator
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 10;
            while (x --> 0)
                Console.Write(x);

            Console.ReadKey();
        }
    }
}

The output is :
9876543210

using System;

namespace TestNewOperator
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 10;
            while (0 <-- x )
                Console.Write(x);

            Console.ReadKey();
        }
    }
}

The output is :
987654321

Okay…

Do you smell anything strage?
(more…)

Globally Unique Identifier

Posted: April 18, 2010 in C#, Programming
Tags: ,
A globally unique identifier or GUID is a special type of identifier used in software applications to provide a unique reference number. The value is represented as a 32 character hexadecimal character string, such as {ff478f2d-e398-449a-93d4-62b0727} and usually stored as a 128 bit integer.
The primary purpose of the GUID is to have a totally unique number. Ideally, a GUID will never be generated twice by any computer or group of computers in existence. The total number of unique keys (2^128) is so large that the probability of the same number being generated twice is extremely small, and certain techniques have been developed to help ensure that numbers are not duplicated.
GUIDs have a variety of applications. You can use a GUID as a primary key in your database table or in a several other scenarios. A good example would be, if you have a distributed application where data is generated and stored in various locations and you want to merge all those data at some intervals of time, you may use GUID as the primary key.

GUIDs can be generated in a number of ways; most often a hash of several things that might be unique at any given point in time like the IP address plus the clock date/time etc are used to generate Unique Ids. Each system may have slightly different algorithm to generate the Unique Id.

Here’s how to generate GUID in C# code :

using System;

namespace TestGuid
{
	class MainClass
	{
		static void Main(string[] args)
		{
			System.Guid guid=System.Guid.NewGuid();
			Console.WriteLine(guid.ToString());
			Console.ReadLine();
		}
	}
}

Note : Some content of this article was taken from here

Dynamic workflows provide some interesting possibilities for programs that want to generate business logic or make a runtime decision on which business logic to load and run.

In this tutorial, i will use exiting code that already created here.

Fisrt, in Solution Explorer, rename file Workflow1.xaml into MyWorkflow.xaml. Oh yeah, do not forget to change class name in xaml code, simply right click MyWorkflow.xaml and choose “View Code”.

Next step, you need to tell Visual Studio to treat MyWorkflow.xaml as content that must be deployed rather than code that must be built. To do this In Solution Explorer select MyWorkflow.xamland then in Properties Window, change the configuration :

Previously your class was compiled into a type. To invoke a workflow from a .xaml file you will need to modify Program.cs to be like this :

using System;
using System.Linq;
using System.Activities;
using System.Activities.Statements;
using System.Activities.XamlIntegration;

namespace WorkflowTest1
{
    class Program
    {
        static void Main(string[] args)
        {
            WorkflowInvoker.Invoke(ActivityXamlServices.Load("MyWorkflow.xaml"));
            Console.ReadKey();
        }
    }
}

Run the program…

Here i will create a simple “Hello World” application using Windows Workflow Foundation 4.0 or WF 4.0. Oh yeah, what is Windows Workflow Foundation ? Windows Workflow Foundation is a Microsoft technology for defining, executing, and managing workflows, the detail about Workflow Foundation is here.

First we will create new project, choose “Workflow Console Application” and name it “HelloWorkflow”

You will see workflow designer and toolbox tab in the left, just drag WriteLine Primitive Activity

Add Text with a string like “Hello World ! It is a Great Day !”

In your Program.cs must be like this :

using System;
using System.Linq;
using System.Activities;
using System.Activities.Statements;

namespace HelloWorkflow
{

    class Program
    {
        static void Main(string[] args)
        {
            WorkflowInvoker.Invoke(new Workflow1());
            Console.ReadKey();
        }
    }
}

And the last… run the program :

I get something weird when i want to test my silverlight application, my silverlight website is not loaded properly… when i run my application, it get stuck in loading animation.

Oh yeah… the other bad thing is, my Expression Blend 3 is not giving any error message (yup… Blend is very bad when we need to debug). So i try to run my silverlight application in Visual Studio and i get the error message :P

And then after searchin’ on google i get the wrong thing :D

Here’s the explanation when you get same error as me

  1. In your .xaml file, you have an attribute which is not supported by XAML parser.
  2. In your .xaml file you have declared an event for a control, but didn’t implement the event handler for the same in .xaml.cs or .xaml.vb file

For now, to better understand what is causing these errors you should take a careful look at your XAML to see if something declared is missing or wrong.

In this article, i will create a simple application that which implements NHibernate, in database side, i will use SQL Server 2008. What is NHibernate ? I will not explain it in there,  there are lot of explanations in the internet, like in here.

You can download latest NHibernate version here.

First, i will create a simple database that have just one table (and i added some record in there):

This is the DDL (Data Definition Language)

create table ACCOUNT (
   ACCID                int         identity(1,1)       not null,
   USERNAME             varchar(50)                     null,
   PASS                 varchar(50)                     null,
   constraint PK_ACCOUNT primary key nonclustered (ACCID)
)

Hmm.. what does this Identity(1,1)  mean ??? It is mean we will set ACCID attribute, the primary key, to become autonumbered, the value will be added automatically incrementing from 1, 2, 3, … and so on.

Next step, we will create simple solution in Visual Studio 2008 SP1 (remember … to connect to SQL Server 2008, your Visual Studio 2008 must be Service Pack 1 ).

Add some references

  1. NHibernate.dll (NHibernate library)
  2. NHibernate.ByteCode.LinFu.dll (for lazy loading)
  3. System.configuration

(more…)