A nice XMLSerialize sample using C#

The code sample is from the book “C# Design and Development: Expert One on One“:

First, we have a Names class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace XMLSerialize
{
   [Serializable()]
   public class Names
   {
      public String FirstName{get;set;}
      public String LastName{get;set;}

      // The default constructor.
      public Names()
      {
      }

      // A contructor that accepts inputs.
      public Names (String NewFirstName, String NewLastName)
      {
         FirstName = NewFirstName;
         LastName = NewLastName;
      }
   }
}

then we have a Setting class which uses XML Serialize:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace XMLSerialize
{
   public class Settings
   {
      // A list of names stored by the program.
      public Names[] NameList{get;set;}

      // The last date the user used the program.
      public DateTime LastVisit{get;set;}

      public static Settings LoadSettings()
      {
         // Create a user-specific settings string.
         String UserPath =
            Environment.GetFolderPath(
               Environment.SpecialFolder.ApplicationData) +
            @"\XMLSerialize";

         // Determine whether the application settings exist.
         if (!File.Exists(UserPath + @"\AppData.CONFIG"))
            return null;

         // Define an XML serializer.
         XmlSerializer DataRead =
            new XmlSerializer(typeof(Settings));

         // Create a stream writer to read the data.
         StreamReader Input =
            new StreamReader(UserPath + @"\AppData.CONFIG");

         // Load the settings.
         Settings Current;
         Current = (Settings)DataRead.Deserialize(Input);
         Input.Close();

         // Return the current settings.
         return Current;
      }

      public static void SaveSettings(Settings Current)
      {
         // Uncomment the following lines to see LINQ sorting at work!

         //// Sort the Current data so it appears sorted on disk.
         //IEnumerable<Names> Sorted =
         //   Current.NameList.OrderBy(
         //      Names => Names.FirstName + Names.LastName);
         //Current.NameList = Sorted.ToArray<Names>();

         // Create a user-specific settings string.
         String UserPath =
            Environment.GetFolderPath(
               Environment.SpecialFolder.ApplicationData) +
            @"\XMLSerialize";

         // Determine whether the directory exists.
         if (!Directory.Exists(UserPath))
            Directory.CreateDirectory(UserPath);

         // Define an XML serializer.
         XmlSerializer DataWrite =
            new XmlSerializer(typeof(Settings));

         // Create a stream writer to output the data.
         StreamWriter Output =
            new StreamWriter(UserPath + @"\AppData.CONFIG");

         // Save the settings.
         DataWrite.Serialize(Output, Current);

         // Flush and close the output file.
         Output.Flush();
         Output.Close();
      }
   }
}

then we can use the Setting class somewhere . All detail code please read the book I mentioned.

WPF or Windows Forms ?

Windows Presentation Foundation (WPF) is a next-generation presentation system for building Windows client applications with visually stunning user experiences. WPF supports UI, media, documents, hardware acceleration, vector graphics, scalability to different form factors, integration with Windows, interactive data visualization, and superior content readability. Read all about recent updated and additions to WPF here.

Windows Forms is a set of classes in the .NET Framework that enables rapid development of rich Windows client applications, with powerful, extensible libraries for user-interface controls and graphics.

You can incorporate WPF in your Windows Forms applications through WPF-Windows Forms interoperability in the .NET 4 Framework.

— From Microsoft

You might heard about that Microsoft never said WPF is the future and Windows Forms will be washed out.

So, if you don’t know how Microsoft will do, just watch their official site: windowsclient.net, and check the home page at “Articles of the Day” section, how many articles are about WPF or Silverlight ? how many articles are about Windows Forms ?

Let me say: Obviously, WPF should be the future, Microsoft might no more spend too much cost and time on the new stuff for Windows Forms , they might combine all features of Windows Forms to WPF.

Windows Forms is legacy.  Microsoft should label Windows Forms as legacy (as it has done with COM), only offer bug fixes and concentrate 100% on WPF.  WPF is the future.  I’ve had more fun building WPF UI than I’ve ever had with Windows Forms.
— From mdavey.wordpress.com

Also, here is another article about WPF vs Windows Forms

A sample using union in C

This sample code is for testing some data type border value using C union. Worked on Linux OS.

#include
#include

int main(void)
{
union
{
unsigned long int lms;
unsigned short shms[2];
unsigned char  bms [4];
} myms;

myms.lms = 0;

while (1)
{

printf(“long: %ld  short: %d  byte: %d\n”, myms.lms, myms.shms[0], myms.bms[0]);
usleep(900);
myms.lms++;
}
return 0;
}

How C# rounds decimal numbers

You might have known the following example:

Math.Round(3.44, 1); //Returns 3.4.
Math.Round(3.45, 1); //Returns 3.4.
Math.Round(3.46, 1); //Returns 3.5.

 
(code sample from Microsft msdn site)

So here you might find something is different. why 3.45 is 3.4 ? Yes, in C#, the Math.Round method normally (but not always, see more examples below) make all 0.5 and less down to 0, make all 0.6 and more up to 1, 0.5 will not be 1, but will be 0 !

So, in C#, we should know how decimal is handled in C#.

Here another strange example:

            double r;
            r = Math.Round(1.5);       // result = 2.0
            r = Math.Round(2.5);       // result = 2.0

Why above 2 lines all get 2 ?

Here is an important rule: Midpoint Rules:

1: “To Even” rule:  By default, when the number is 0.5 (number is rounded is exactly half way between two integers), Math.Round always select the closest even value;
2: “Away From Zero” rule: when the rounded value is midway between the two possible outcomes, always choose the value that is furthest from zero. For positive values this means rounding upwards and for negative numbers the result is rounded downwards.

Microsoft site provides a good example for above rules:

// This example demonstrates the Math.Round() method in conjunction
// with the MidpointRounding enumeration.
using System;

class Sample
{
    public static void Main()
    {
    decimal result = 0.0m;
    decimal posValue =  3.45m;
    decimal negValue = -3.45m;

// By default, round a positive and a negative value to the nearest even number.
// The precision of the result is 1 decimal place.

    result = Math.Round(posValue, 1);
    Console.WriteLine("{0,4} = Math.Round({1,5}, 1)", result, posValue);
    result = Math.Round(negValue, 1);
    Console.WriteLine("{0,4} = Math.Round({1,5}, 1)", result, negValue);
    Console.WriteLine();

// Round a positive value to the nearest even number, then to the nearest number away from zero.
// The precision of the result is 1 decimal place.

    result = Math.Round(posValue, 1, MidpointRounding.ToEven);
    Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)", result, posValue);
    result = Math.Round(posValue, 1, MidpointRounding.AwayFromZero);
    Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)", result, posValue);
    Console.WriteLine();

// Round a negative value to the nearest even number, then to the nearest number away from zero.
// The precision of the result is 1 decimal place.

    result = Math.Round(negValue, 1, MidpointRounding.ToEven);
    Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.ToEven)", result, negValue);
    result = Math.Round(negValue, 1, MidpointRounding.AwayFromZero);
    Console.WriteLine("{0,4} = Math.Round({1,5}, 1, MidpointRounding.AwayFromZero)", result, negValue);
    Console.WriteLine();
    }
}
/*
This code example produces the following results:

 3.4 = Math.Round( 3.45, 1)
-3.4 = Math.Round(-3.45, 1)

 3.4 = Math.Round( 3.45, 1, MidpointRounding.ToEven)
 3.5 = Math.Round( 3.45, 1, MidpointRounding.AwayFromZero)

-3.4 = Math.Round(-3.45, 1, MidpointRounding.ToEven)
-3.5 = Math.Round(-3.45, 1, MidpointRounding.AwayFromZero)

*/

When you are confused by Math.Round, please just give a MidpointRounding parameter in your Round method.

OR, you can use other methods:

Truncation

decimal.Truncate(2.3M);    // result = 2
decimal.Truncate(2.9M);    // result = 2
decimal.Truncate(1M);      // result = 1
decimal.Truncate(-2.3M);   // result = -2
decimal.Truncate(-2.9M);   // result = -2

Floor and Ceiling

decimal.Floor(2.2M);       // result = 2
decimal.Floor(2.9M);       // result = 2
decimal.Floor(-2.3M);      // result = -3

decimal.Ceiling(2.2M);     // result = 3
decimal.Ceiling(2.7M);     // result = 3
result = decimal.Ceiling(-3.3M);    // result = -3
result = decimal.Ceiling(-3.9M);    // result = -3

Reference site please visit here

Data Type Suffixes (Numeric Literals) in C#

Maybe you need to check .NET Data Type Suffixes, or call it Numeric Literals.

For example:  100L means long type, then what meaning of 100M ?

The following is all data type suffixes which I have found:

Type        Suffix    .NET Framework Type                 
——————————————
long        L or l    System.Int64
decimal     M or m    System.Decimal
double      D or d    System.Double
float       F or f    System.Single
int         [1]       System.Int32

———————————
Type  Suffix  Example
——————————
uint    U or u    50U
long    L or l     50L
ulong    UL or ul    50UL
float    F or f    23.45F
decimal    M or m    12.34M

(by the way: using 0x such as 0x100 means the number ‘100’ is Hexadecimal)

float ff = 23.56;     // error !!
float ff = 23.56f;    //OK

If you want to know how the suffix will be in VB.net, please visit this site: UnderMyHat, you will get more information for not only C# data suffixes but also for VB !

How to change VisualSVN log message after committing?

To make the VisualSVN server accept log message changes, a pre-revprop-change hook, that allows to change author or message, has to be installed for the repository. The default installation rejects changes to author and log message.

It is hard to find a sample hook script. but the following one is a solution but it need to put all script to a file and copy the file under /hooks folder in repository folder:

Just copy the following code to VisualSN Studio:  Select database you want to set hook, then click right mouse button and get a “New Task” menu item -> select “Manage Hook”, then select “Pre-revision proterty change hook” and edit ,  just copy  the following code into . 

OR     save the following code   as file “pre-revprop-change.bat” and throw it in the hooks directory (

set userName=%3
set propertyName=%4
set action=%5

:: Only allow the log message to be changed, but not author, etc.
if /I not "%propertyName%" == "svn:log" goto ERROR_PROPNAME

:: Only allow modification of a log message, not addition or deletion.
if /I not "%action%" == "M" goto ERROR_ACTION

:: Make sure that the new svn:log message is not empty.
set bIsEmpty=true
for /f "tokens=*" %%g in ('find /V ""') do (
set bIsEmpty=false
)
if "%bIsEmpty%" == "true" goto ERROR_EMPTY

goto :eof

:ERROR_EMPTY
echo Empty svn:log messages are not allowed. >&2
goto ERROR_EXIT

:ERROR_PROPNAME
echo Only changes to svn:log messages are allowed. >&2
goto ERROR_EXIT

:ERROR_ACTION
echo Only modifications to svn:log revision properties are allowed. >&2
goto ERROR_EXIT

:ERROR_EXIT
exit /b 1

And also there is a sample here. Maybe they are the same one.

Set Port and Firewall to enable remote connect to SQL Server 2005 or 2008 Express Database

After 2 articles Remote connect to SQL Server 2005 Express or SQL Server 2005 and Change SQL Server or SQL Server Express Authentication Mode, the SQL Server remote connection still have more stuff to talk about.

Yes, we need to set Port and Firewall stuff to let remote computer can access.

Doug Kennard have given a nice instruction in his site and the article name is “How to Enable Remote Connection to SQL Server 2008 Express Database”.

We can follow his guide to finish all left things that we have to finish for the database remote connection.

Some day I will give my own experience if I have free time to record all my setting steps.

Change SQL Server or SQL Server Express Authentication Mode

When I installed SQL Server Express on my local PC, I used to select Windows Authentication mode only, but later I might have to change the Authentication mode for some reasons such as connect this SQL Server database from another computer and I don’t want to set a new windows user account for another computer to access current computer, So I have to select SQL Server Authentication mode then.

Actually in SQL Server Express, there are only 2 type of Authentication Modes:  Windows Authentication mode and SQL Server and Windows Authentication mode, there is no SQL Server Authentication mode only. So if you want to change from Windows Authentication mode to  SQL Server Authentication mode, it will be changed to SQL Server and Windows Authentication mode.

Steps:

1: In SQL Server Management Studio Express, right click on the DB Server name, then click Properties:

2: On the Security page, under Server authentication, select the new server authentication mode which you want, and then click OK :

3: In the SQL Server Management Studio dialog box, click OK to acknowledge the requirement to restart SQL Server.

To restart SQL Server from SQL Server Management Studio:    In Object Explorer, right-click your server, and then click Restart. If SQL Server Agent is running, it must also be restarted.

To enable the sa login by using Transact-SQL (from Microsoft website)

If Windows Authentication mode is selected during installation, the sa
login is disabled and a password is assigned by setup. If you later
change authentication mode to SQL Server and Windows Authentication
mode, the sa login remains disabled. To use the sa login, use the ALTER
LOGIN statement to enable the sa login and assign a new password.
 
Execute the following statements to enable the sa password and assign a password.

      ALTER LOGIN sa ENABLE ;
      GO
      ALTER LOGIN sa WITH PASSWORD = '' ;
      GO


To enable the sa login by using Management Studio
(from Microsoft website)

   1.      In Object Explorer, expand Security, expand Logins, right-click sa, and then click Properties.
   2.      On the General page, you might have to create and confirm a password for the sa login.
   3.      On the Status page, in the Login section, click Enabled, and then click OK.

Connection String:

Now you can get Connection string:

1: Windows Authentication (Trust Connection):

connectionString="Data Source=MyDBServerAddress\SQLEXPRESS2005;Initial Catalog=S800_DB_2010;Integrated Security=True"

2: SQL Server Authentication:

connectionString="Data Source=MyDBServerAddress\SQLEXPRESS2005;Initial Catalog=testDB;User ID=terminalDBA;Password=myPassword;

Page Not Found Multiple Language Text

When we build Web Applications, we need to give a 404 page when the url link dead or not work. So “Page Not Found” content should be put in the 404 page. It is so easy because you just put the text on that page.

However, how about multiple cultural web applications ? You have to give different languages. So do you know other languages for “Page Not Found ” ?

It is interesting that Microsoft site has just this kind of page which you might need, there are multiple languages “Page Not Found” on a single page:

http://social.microsoft.com/error/error404.aspx

All the content is just “Page Not Found” and a small section detail message. So you can find your languages which you want.

Page Not Found

We're sorry, but the page you requested could not be found. Please check your typing and try again, or use the search options on this page.

Page non trouvée

Désolé, la page demandée est introuvable. Vérifiez l'orthographe de l'URL ou utilisez les options de recherche de la page.

No se encontró la página

Lo sentimos, no se pudo encontrar la página solicitada. Revise el texto e inténtelo de nuevo, o use las opciones de búsqueda de esta página.

Seite nicht gefunden

Die von Ihnen angeforderte Seite wurde nicht gefunden. Überprüfen Sie Ihre Eingabe und versuchen Sie es erneut, oder verwenden Sie die Suchoptionen auf dieser Seite.

Pagina non trovata

Impossibile trovare la pagina richiesta. Controllare che il testo digitato sia corretto e riprovare oppure utilizzare le opzioni di ricerca disponibili in questa pagina.

ご指定のページが見つかりません。

申し訳ありません。指定されたページが見つかりませんでした。入力した内容をご確認のうえもう一度お試しいただくか、このページの検索オプションをご使用ください。

페이지를 찾을 수 없습니다.

죄송합니다만, 요청하신 페이지를 찾을 수 없습니다. 입력하신 문구를 확인하시고 다시 시도하시거나, 본 페이지의 검색 옵션을 사용하여 주십시오.

Página não encontrada

Infelizmente, a página solicitada não pôde ser encontrada. Verifique se você digitou o endereço da página corretamente e tente novamente ou use as opções de pesquisa nesta página.

Страница не найдена

Не удается найти запрошенную страницу. Проверьте правильность введенного адреса и повторите попытку или воспользуйтесь поиском на этой странице.

Stránka nebyla nalezena

Omlouváme se, ale požadovaná stránka nebyla nalezena. Ověřte, zda v zadané adrese stránky není chyba, a akci opakujte, nebo použijte možnosti vyhledávání na této stránce.

页面未找到

很抱歉,未能找到您请求的页面。请检查拼写是否正确并重试,或者使用本页面的搜索选项。

找不到網頁

很抱歉,找不到您所要求的網頁。請核對輸入是否正確並再試一次,或使用網頁上的搜尋選項。