Wednesday, February 28, 2007

Extreme Programming Part 1 - Introduction

Extreme programming or XP is a software development methodology that aim to improve software development productivity, reduce risk and cost. The main focus is to develop software in incrementally, rapid prototyping and communicate frequently that lead to accept requirement changes frequently ( most programmers hate it) and However XP doesn't work for all scenario specially for mission critical system and large system because those system normally needs highly formal specification whereas XP programming is just the opposite.

The main challenge of XP is real fun because you need to do everything yourself and you will deal with customers frequently and communicate with your peers frequently. You got to work out with a prototype very fast an usually you need a code generator to generate the whole application for you. Eg. Iron Speed http://www.ironspeed.com/ does the job. You got to test it and evaluate it for whatever reason to meet the requirements. XP is great if you have a small team around 2-6 people.

To be continued...

Tuesday, February 27, 2007

Concurrent Remote Desktop Sessions in Windows XP SP2

Since Windows XP does not allow multiple concurrent access at the same time using the remote desktop server, however here the link to workaround with.

As for me i applied the terminal server patch (Please follow the link to download the patch below) to the Windows XP pro and i works after restarted. However you need to do one extra step in order you can remote the client user.

Here the extra step

Go to Control Panel > Administrative Tools > Computer Management > Local User and Groups > right click the selected user (create a new user if you want) > properties > Member Of > Add > Advance > Find now > Choose Remote Desktop User > Click Apply and finally OK.

You migh need to change to different port by editing HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp\PortNumber

Now you have successfully turn your Windows XP pro into a terminal server which could support multi concurrent user using Remote Desktop.

Cheers!

http://sig9.com/articles/concurrent-remote-desktop

http://www.kood.org/terminal-server-patch/ (Recommended)

http://riccardo.raneri.it/blog/eng/index.php/2006/04/24/windows-xp-multiuser-remote-desktop/

http://www.golod.com/2005/10/enabling-multiple-remote-desktop-sessions-in-windows-xp-professional-and-media-center-edition-2005/

Monday, February 26, 2007

Get ready with your ASP.NET app using ADAM Membership using ActiveDirectoryMembershipProvider Class

If you want to manage storage of membership information for an ASP.NET application in Active Directory and Active Directory Application Mode servers, you need to do these thing:


  1. Install ADAM. Download ADAM from http://www.microsoft.com/downloads/details.aspx?FamilyId=9688F8B9-1034-4EF6-A3E5-2A2A57B5C8E4&displaylang=en
  2. Install into your Windows Server 2003 (recommended).
  3. After the installation you need to follow this tutorial presented here. [Download Pdf]
  4. You need to configure web.config, please follow the http://msdn2.microsoft.com/en-us/library/system.web.security.activedirectorymembershipprovider(VS.80).aspx
  5. That's it and you are ready to test drive!

Have you encountered this error before?

Unable to establish secure connection with the server using SSL

The reason is because you did not follow my tutorial. :)

Linq to SQL get started snippet example

Well, here the problem:

Given that you have 2 table in many to many relationship, how create using Linq?

First of all you need to normalize it to 1 to many format. Since you are using Linq, it is safer that each and every table has 1 identity autonumbered column to prevent any CRUD failures (Hope this will be fixed soon).

Now you got 3 tables, since you are dealing with > 1 table therefore you're recommended to create a transaction to perform any CRUD.


Here are the code snippet

using (System.Transactions.TransactionScope scope = new
System.Transactions.TransactionScope())
{
try
{
//initialize it and
the connection created
pfData = new PersonalFinanceDataContext();

//Create spending type, the first table
SpendingType
spendingType = new SpendingType();
spendingType.Name = accountName;


//Create Account, the second table
Account accPayable = new
Account();
accPayable.AccountName = accountName;


//Map them together, by a mapper table
SpendingAccount
spendingAccount = new SpendingAccount();
spendingAccount.Account =
accPayable;
spendingAccount.SpendingType = spendingType;

//remember to add into database context else everything will be
lost!
pfData.SpendingAccounts.Add(spendingAccount);

//Save it
pfData.SubmitChanges();

//commit it, everything is successfully done!
scope.Complete();
}
catch(Exception ex)
{
throw "Bad linq" + ex;
}
}

hope you have some basic idea of how easy that linq to sql could do for you.

Sunday, February 25, 2007

ASP.NET skinning

I found this website really helps in skinning ASP.NET application. http://www.dotnettreats.com/SampleThemes/

Carso Virtual University Proposal

These are the proposed features of this project and I would invite you who are interested in realizing the Open Virtual University Program.

Core features:

  1. Students and tutor membership management
  2. Class scheduling, course booking and students & tutors' timetable management.
  3. Students performance ranking and enrollment statistics.
  4. Automated e-exam creation by selecting question from questions' bank.
  5. Custom personal web pages for students and tutors.
  6. Course materials management. File sharing, upload and download facilities.
  7. Course enrollment system.
  8. Voting and suggestion system.

Optional features.

  1. Thesis plagiarism detection.
  2. Automated timetable scheduling system.
  3. Subject's advisor expert

All these features would be implemented in Dotnetnuke module. Any other web framework such as using community server 2.1 is under consideration. Custom ASP.NET framework maybe suggested.

I need 2 web designers specializing in skinning ASP.NET user interface. 5 software developers, 1 database designer. i will be your project manager i this Carso's VU project.

Please drop me a line if you wish to participate.

Great codeproject articles for those interested in artificial intelligent

Today i came across this link http://www.codeproject.com/script/Articles/list_articles.asp?userid=1181072 and i found that the author Andrew Kirillov is wonderful in his those written articles. I have been a fan of artificial intelligent science since i was in high school. I would like to invite you guys 2-5 to work along with me a project called car parking system which is useful for finding empty car parking spaces. Besides, the system also suggest the shortest path and the most minimum time to obtain car parking space. The project would be implemented in Windows Mobile 5.0 and ASP.NET web application. Those who are interested please write some comment on this post.

Friday, February 23, 2007

How to enable Secure Soket Layer SSL in IIS 5.0/6.0 Server using VeriSign?

If you are a web developer or web administrator, you often ask this common question. How to enable Secure Soket Layer SSL in IIS 5.0/6.0 Server using VeriSign's certificates? What is SSL? Simply we can say that SSL is a security technology that secure the communication between the sender and the receiver by protecting the data with strong encrytion that hopefully no body could read the encypted data.

to enable the SSL in your IIS 5.0/6.0, you must follow these 10 steps shown below, no less and no more.

Step 1:

Click "Server Certificates" under IIS > Directory Security Tab




Step 2:

Please look at the screen which self explained.


Step 3:

Click Next, Next until you see this

Step 4:
Step 5:


Step 6:

After you have finished, you have to go to http://www.verisign.com/ to create your SSL certificate. Verisign 's SSL certificate is not FOC, however you could obtain a free 14 days trial for testing purposes. Please follow the instructions provided by verisign, you have to sign up as member before you could create your SSL certificate.

Step 7:

Assume that you are half way setup your SSL cert, you need to upload the certreg.txt which you just created in your IIS. Verisign will read your certreg.txt and confirm the information to you. After all, Verisign will send you an e-mail to you.

Step 8:

After you have received your e-mail, you will find that there is a funny string which look something like Ky456hJKLsM... printed at the end of your e-mail. Please copy and paste to a notepad and save it as vericert.cer. You will need this later.




Step 9:

You will see this screen and just click next.


Step 10:

Browse the vericert.cer which you had created in step 8:


Click next and you are done!

You can test drive your IIS server by typing https://localhost/ in your browser and please double click the security yellow color lock icon to preview the certificate information.



Tuesday, February 13, 2007

Send e-mail by c# coding

So simple as this:

using System.Net.Mail;

MailMessage msgMail = new MailMessage("spammer@haqckers.net","carso@cheeweng.com","Your subject","your message");
SmtpClient smtpC = new SmtpClient("localhost");
smtpC.Send(msgMail);

but you need to set your IIS smtp mail correctly. Check out below

http://codebetter.com/blogs/peter.van.ooijen/archive/2006/04/05/142331.aspx

How to get my motherboard serial number using C#?

Sometimes we might want to identity the unique user for some purposes by knowing the machine identity they are using. Software licensing for instance, we could use his machine processor Id or motherboard id to uniquely identify them.


So here are the tricks:

http://carsolife.blogspot.com/2007/02/how-to-get-my-motherboard-serial-number.html

Are you interested in taking part in open virtual university program?

This virtual university project had started about a year and the project is written in ASP.NET C#. We want to take one step further to port this whole project to dotnetnuke's modules. If you are interested in joining this program, please go to this link for more infomation.

http://babi.myftp.org/bbs/blogs/artifician/archive/2007/02/13/carso-s-open-virtual-university.aspx

EnableSessionState, ASP.NET most common error

Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <*configuration*>*\**\*<*httpModules*> section in the application configuration.


When you'll encounter this kind of error? This occur when u are using state in your ASP.NET pages. For instance, you might be using

Session["Username"] = "Carso Owen"; //in your c# code

The solution is you need to do these 3 things in your ASP.NET web.config:

1. locate under the <*system.web*> <*sessionState mode = "InProc"/*> ... <*/system.web*>

2. modify the <*httpModules*><*add name="session" type="System.Web.SessionState.SessionStateModule"/*>

3. modify <*pages enableSessionState="true" */>

P/s : plz ignore the those * in the above.

Sunday, February 11, 2007

Before you start your software project, what's the first thing you do?

Before you start your software project, what's the first thing you do? For me i will backup my project first before continuing. Why, simply because i could undo it if something goes wrong, at least i could save my preciuos time. Let say, you are hadling a project A and you have spend the first 2 hours doing something wonderful, later on you did something funny and your whole project corrupted. fortunetly after spending 20minutes to find the the cause of the problems, you got the solution and then you spend another 30minutes to fix it, complile it and test it. You almost got there just a few step to fully recover it and it takes another 30 minutes for through testing. Finally you just got to recover the whole thing. In this senario how much time you have spend to recover it? it is almost 1 and a half hour doing something which is not productive. imagine that if you had "rar" (backup) the project at the first place and later you recover it via unrar it. how long does "unrar" takes? 2minutes vs 90minutes. Got it?

Let me show you the simple and yet effective way of backup your software project.

Let say your project is save under ProjectA, now you pretty sure that ProjectA iteration task is completed and you wish to backup it. So just rar it to ProjectA_V1.rar, well this is your first version of backup. You continue again your development iteration, after each successful task is done you rar it again, and now you rar it as ProjectA_V2 and so on and so forth.

When you encountered a corruption on your project and now you wish to recover it, therefore you look for the lastest .rar that you have backup.

One interesting question, why rar it? rar it could save your disk space but this is not the main reason. The only reason is because you pretty sure that you do not accidently modify the file inside the folder in case you did not rar it.

A personal accounting needed is to keep track your money

I have a great and yet simple proposal to create a website to manage our personal accounting because i found that it is too tedious to enter my spending records in excel file. What is your opinion? I need a program that could validate data entries, tracking my spending and show some useful information regarding my spending habits. It must be web ready of course so that you all can be able to take advantage of it. Btw, it must be able to generate a report of account transactions at the end of the month. Any suggestion of my idea, please comment it.

FYI, I would like to invite you to have a preview of this project which is still in pre-release stage.

http://babi.myftp.org/bbs/PersonalSpending/ ( Beta 1 release)

Saturday, February 10, 2007

My ASP.NET pages corrupted when i changed my database structure.

We often heard about N-tier designs in software development and the reason of having this design is because we want to achieve the highest degree of software scalability. This comes with a price which means more development time has to be invested. Sometimes, because of budget and time constrains, we have to sacrifice in some way to trade of to productivity. Visual Studio 2005 has a very nice features which is known as table adapter and dataset that actually helps developers to gain significant productivity in data binding over user interface (UI) design. You will be amazed that only a few lines of code or without any coding, you could bind data from your database's table to your UI's control. This also means that, any changes in your database structure, it will actually corrupts or malfunctions your UI.

In my own experince, i was writting an ASP.NET application which uses SQL Server 2005 & Visual Studio 2005. Later, i discovered that i needed to update my database structure because i wanted to add some extra functionalities, so i need to add and delete a few database (db) tables, renaming some of my existing db's tables. Some changes had significant impact on my application while some had not. Therefore i needed to take this into consideration as well. After i had made the changes, I found that my data access logic layer seem to be useless because data access code actually maps back to the database structure, therefore it was no suprise. Luckly, my web application is 3-Tiers design which allows me to replace it with a new code generated data access layer (DAL). This is the most simplest part. Now it comes for modifying the business logic layer (BLL), because this layer actually calls your DAL, therefore changes need to be performed , you can't throw away your BLL and replaced it, you just need to spend your time modifying the calling object to your database.


Notes, renaming your tables and column names or deleting tables have the most
significant impact on yur BLL, on the other hand, adding new columns or tables
are not. (it depends how smart your ORM generator) .


After i'd made the changes and to make sure my BLL talks well with my DAL, then I need to make sure my UI calls my BLL well. Do i need to make changes to my UI code to make sure it talks well with my BLL? The answer is yes and no. if you expose your BLL as services interface then no changes nessary to your UI code, The answer is no and assuming that you want to preserve your previous functionality. If you do not have interface class, method overloading and constructor overloading presented in your BLL design, then the answer is yes and most problably that you need to make some changes to reflex your BLL :)

Finally, what if i am using this VS table adapter and dataset to bind data? The best answer is you have to check and make sure they are actually maps to your database's tables correctly, otherwise you need to regenerate or redesign your databinding again. However, this modification is not tredius and time consuming as you might think.

The question is how to eliminate these problems of code changes when database structure is being modified? In my personal opinion, i don't think we have the economically way to eliminate these problems. What we really care is try to make your UI design as simple as possible by abstracting the object calling either business layer or database layer. By this means, you are pretty save when disaster comes, you could easily solve it because you just made it simple.

Thursday, February 8, 2007

.NET deployment, i am stuck

Today i was nearly mad when i tried to deploy a CAB module. Initially, i need to deploy all the 10 modules however one of the module nearly make me crazy the whole day. What had happened was the module which I was deploying, could be installed successfully, however it was causing my application not to be loaded. I tried to figure out the causes of the problem and i found that during installation, some of my assemblies are replaced and therefore my application couldn't linked. Therefore i tried to deploy only those assemblies which are needed manually ( by default VS.NET will auto take care of it). There came another problem, the problem was that when i tried to deploy a assembly, let say moduleA.dll, all those dependencies of moduleA.dll will be auto deployed together with the moduleA. This is not what I wanted because the reason behind are those dependencies that causes the failure. I had tried various ways and I nearly going crazy. Suddenly i thought of one idea, what if i copied the assembly into another directory, let say I placed my moduleA.dll on to my desktop, and in hope that VS.NET is not so intelligent enough to detect those dependencies .dlls of moduleA.dll. Yahoo0o... now i managed to deploy those assembly that i want.

The conclusion is, way is always there, just be a bit creative when finding solutions. :)

Wednesday, February 7, 2007

Hash code, what the hack of that?

well u always heard of encryption and hashing in security context, if we have encryption to protect our data, then why we need to hash?

FYI, we use hash code for 2 most common things, which are

  • Verify data integrity, to make sure the the data is always original and the right data
  • Used to store password, not original password but hashed
    password.
  • Verify data integrity (use keyed hash code for better security)

    let say a person A wants to send a file via e-mail to person B. person B wants to ensure that the file in the e-mail has not been intercepted, therefore person B need to generate hash code of the file received by him (person B) and compare it with the hash code of the file generated which sent together with the original text by the person A. if both the hash codes are equal in comparison, then the file is original and had not been altered, otherwise the data had been corrupted or intercepted.

    example of keyed hash code :

    you can use HMACSHA1 or MACTripleDES, using HMACSHA1 has better flexibility since it can support any key size in bits and up to 160bits of hash code size.

    HMACSHA1 haHMACSHA1 = new
    HMACSHA1(Encoding.Unicode.GetBytes("secretKey"));
    byte[] hashedData =
    haHMACSHA1.ComputeHash(Encoding.Default.GetBytes("My important
    data."));
    string hashedCode = BitConverter.ToString(hashedData);

    since the sender and the receiver knows the "secretKey"; only the right "secretKey" can produce the right hash code comparing the hash code of the file from the sender, therefore transmitting file will be more secure to avoid someone intercepting the file in case the hacker had created a faked data with hash code of its faked data. In this way, you not only be able to ensure the data is unchanged during transmission and it also ensure you that the data integrity.

    Used to store password

    Do you know that hashed password is quite impossible to compute back to original password? How to derive this
    4B-E1-ED-D7-38-8A-AF-D5-A4-BD-D0-30-41-A8-34-7E-A1-84-E1-79-87-E8-7A-AA-79-2F-6D-7B-71-BA-01-A7 back to original data? The fact it is nearly impossible with any advance algorithm. Hash code is one way cryptographic functions. Therefore, if your customer said that he has lost the password and would like to retrieve it, the solution is to create a new password for him. That's all.

    In real world, security expert will suggests that storing hashed password instead of plain text password in their database for security reason; system uses the stored hash code to compare with the computed hash code of password by the user. First the reason is because, no one could know what the user real password in the database even the database administrator. Secondly, a small different in password will result significant different in hash code of password, therefore it will be very hard to guess the hash code pattern given the relationship between a list of hash codes.

    example of hash code :

    you can use MD5 (128bits), SHA1(160bits), SHA256(256bits)....SHA512(512bits) algorithms.

    HashAlgorithm haSHA256 = HashAlgorithm.Create("SHA256");
    byte[] password =
    Encoding.Default.GetBytes("MyPasSWoRd");
    string hashedPassword =
    BitConverter.ToString(haSHA256.ComputeHash(password));

    simple? Next i will discuss about applying encryption into your code.

    How to start a command prompt by coding using C# .NET?

    Try this:

    using System.Diagnostics;

    ProcessStartInfo psi = new ProcessStartInfo("sqlcmd", "calc");
    Process proc
    = Process.Start(psi);
    proc.Start();
    proc.Close();



    Guess what program will show up?

    Why toggling control?

    A good software need be simple and able to hide those complexity contains in the software. User interface (UI) design is extremely important to make sure your software look simple. One of the tips that i find very useful technique is 'toggling control' to be applied in your UI design. What does this means? We toggle control because we want to limit a user to access of some controls (mind his business). if fewer choices means fewer mistakes made by user. We can either disable or enable those controls ; or we can visible or invisible them.

    Here is a good example:

    Create a method so that it can be used again and again


    public void ToggleControl(bool enableToggle)
    {
    if (enableToggle)
    {
    txtEmail.Enabled = true;
    txtUsername.Enabled =
    true;
    }
    else
    {
    txtEmail.Enabled = false;

    txtUsername.Enabled = false;
    }
    }


    so u can call this method as simple as ToggleControl(true) to enable the control otherwise ToggleControl(false) to disable it.

    How to get the file from OpenFileDialog and copy the file in another directory?

    Sometimes, your boss might ask you to read a product pricing file and manipulate it such as extracting the infomation and format it accordingly and save it back to a text file. In this case, the code below show you how u can use the .NET win control using OpenFileDialog class to provide a standard windows' open file dialog for your user to select a file and use the file to be manipulated. Here is the example:


    using System.IO;

    private void CopyFile2DirA()
    {


    // Create an OpenFileDialog
    to request a file to open.
    OpenFileDialog openFile1 =
    openFileDialog1;


    //Open the file and extract the infomation into tempstr

    string tempstr = "";
    using
    (FileStream fs = (FileStream)openFile1.OpenFile())
    {
    byte[] b = new
    byte[fs.Length];
    UTF8Encoding temp = new UTF8Encoding(true);
    while
    (fs.Read(b, 0, b.Length) > 0)
    {
    tempstr += temp.GetString(b);
    }
    fs.Close();
    }


    //update the extracted data

    tempstr += tempstr + " here some modified data.";

    //save the file inside your executing directory
    DirectoryInfo dinfo =
    new
    DirectoryInfo(openFile1.FileName);
    File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory
    + "\\" + dinfo.Name,tempstr);
    }

    That's it, now check the newly created file.

    Monday, February 5, 2007

    learn Dotnetnuke skining the fastest possible speed!

    Dotnetnuke is a content management open source project which has been established for many years. Many efforts had been contributed by the community to this popular project and guess what? it is available for free download. If you are interested, please go to http://www.dotnetnuke.com/. Most often web designers want their dotnetnuke's website to be as unique as possible and therefore skinning is a very important subject for them. They have to skin to meet their client business objective, client's request and etc. A web designer always ask, how much efforts and time needed to create a skin for dotnetnuke and will programming skill needed? If you want to design skin only, usually no programming is necessary needed.

    FYI, dotnetnuke is considered a web development framework which u can easily reuse the code and as well to extend it. Programmers often extend it by creating a plug in module which can be deployed and installed easily to the dotnetnuke core framework. Since, dotnetnuke is architected in such a way, skinning has no exceptions. We can easily setup the skin by uploading the skin.zip file. Now the interesting problem comes, How do I create the skin.zip? Well the easiest and fastest way is to find an example of anyskin.zip file over the net and extract it and dig into it. There is a very good website that provides free skin. just visit http://www.xd.com.au/ and download your favourite skins.


    Steps:
    1. Install the skin that you have downloaded.

    2. locate the skin folder. usually it located in wwwroot\dotnetnuke\Portals\_default\skins\yourdownloadedSkin\

    3. you will see those .jpg, .gif, .css , .ascx and .etc . FYI, .jpg and .gif is those image files that used in constructing the skin and therefore if you modify those images in your favourite Photoshop and save it, you will be amazed that your dotnetnuke's website image will change accordingly. So just play around with it.

    4. .css is the most interesting part for styling, if you are used to .css then you are great, however if you are not, then don't worry. Most of the time the .css tags used is all self explained, so learn by examples! For example, if you want to change the background color of the particular .class, just look for those '#FFFFFF' kind of value and try experimenting it by changing different value and see the result, i guess it is fun too. If you want your life much easier, get a Macromedia Dreamweaver to help you up with those alien .css tag.

    5. Yeah, you are not .NET developer right? well .ascx is a ASP.NET web control file, so what the hack it is related to skinning? Simply the answer is that, it is used to specified the container of your webpages or in another words it is used to specified the layouts of your website. Initially, most skin file comes with HorizontalMenuFixed.ascx and HorizontalMenuFull.ascx for instance. fHorizontalMenuFixed.ascx as it sell explained it fixed the width of the web page and on the other hand HorizontalMenuFull.ascx means it fill up the page and it can auto adjust the size itself according to your LCD screen resolution. Continue... the next and let's get started now!

    6. Normally you will see those contentpane, bottomPane, topPane leftPane and rightPage which are the most basic. If you look carefully, it is actually HTML table's elements. So how does the dotnetnuke know which or which is top, bottom or left pane? The answer is the ID that specifies the name of the column. for example, ContentPane is specifiied as <*td id="ContentPane" runat="server"*><*/td*> , if you specify in such a way, dotnetnuke will know that it is a content container and it will create a contentpane for you in all your web pages in your website consistently. If you want to style the ContentPane? no problem, just add a class attribute into it for example <*td id="ContentPane" runat="server" class="contentStyle" *><*/td*> contentStyle will references the .css file to get the styling info. The .css might look like

    .contentStyle { width: 100%

    background-color: transparent;

    }

    So do you get a clear picture of how people skin? This is the most simple method if not what can i say... Well , enjoy skinning and always learn by experimenting examples! Cheers :)

    Saturday, February 3, 2007

    XML Manipulation the Linq way. Simple and clean

    Most often people found that manipulating XML can be quite troublesome. Recently i'd found a very simple way to manipulate XML. Let say i want to create an XML file having this format:


    <*musiccollection*>
    <*album>
    <*Title name="DisneyWorld"*>
    <*location*>http://www.artifician.com/mp3/disneyworld.mp3<*/location*>
    <*/album*>
    <*/musiccollection*>

    use this code:

    XDocument doc = new XDocument("music.xml");

    doc.Add(XElement("MusicCollection",
    new XElement("Album", new object[] {
    new XElement("Title", new XAttribute("Title", "DisneyWorld")),
    new XElement("Location", "http://www.fakeurl.com/mp3/disneyworld.mp3") }));

    doc.Save();

    that's it, the music.xml has created.

    btw, u wish to read it. Let say we want to get the value of "Location" we can use this code:

    string location = doc.XElement("MusicCollection").XElement("Album"). XElement("Location").Value;

    how about Title's name?

    string titlename = doc.XElement("MusicCollection").XElement("Album"). XElement("Title").XAttribute("name").Value;

    what if i want to motify the Title's name?

    doc.XElement("MusicCollection").XElement("Album"). XElement("Title").XAttribute("name").Value = "Superman";


    remove the Title's name?
    doc.XElement("MusicCollection").XElement("Album"). XElement("Title").XAttribute("name").Remove();


    Xml 's CRUD example enough? btw i am using System.Xml.Linq. To discover more please go to http://msdn2.microsoft.com/en-us/netframework/aa904594.aspx

    Please keep updated with VS Orcas this month!

    p/s plz don't confuse with the '<*', please imagine it as '<' . The reason i type it as because XML is prohibited

    Friday, February 2, 2007

    High temperature will causes your server down.

    High temperature will causes your server down. This actually true because high heat will affects your most part of your hardwares and therefore performance go slow and even worst, it will causes your hardware fail. Today i was shocked that my server went down because my harddisk failed. i tried to restart but at the moment it couldn't detect my harddisk. I tried the second time and third but still the same. why? of yeah, i didn't turn on my fan while i was away, the heat air not circulate enough. I quickly turned on the fan and waited for 10minutes. Guess what?, my server went back to normal. This also suggest that servers' room always air conditioned.

    How to get assembly infomation?

    The code function is self explained. :)

    int buildnum = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Build

    Custom serial number key generator in C# .NET

    I googled for sometime but i couldn't get what i want therefore i decided to write a Custom serial number generator class in C# .NET.

    I try to figured out the method that return the following serial number format such as



    SN = xxxx-xxxx-xxxx-xxxx-xxxx-xxxx

    e.g : 85F7-1DF2-BB23-4C32-A684-C5D3

    here's the one line of code :

    string serialNumber =
    RandomSNKGenerator.GetSerialKeyAlphaNumaric(SNKeyLength.SN16);

    or if you want to generate random number only :

    string serialNumberNumberOnly =
    RandomSNKGenerator.GetSerialKeyNumaric(SNKeyNumLength.SN12);

    Simple?

    if you want to produce a complicated serial number key for your product, i think using
    GetSerialKeyAlphaNumaric() method would be great. If you are very simple minded GetSerialKeyNumaric() still sufficient enough. :)


    Here the class :


    using System;
    using System.Collections.Generic;
    using
    System.Text;

    namespace SNGenerator
    {
    public enum
    SNKeyLength
    {
    SN16 = 16, SN20 = 20, SN24 = 24, SN28 = 28, SN32 = 32
    }
    public enum SNKeyNumLength
    {
    SN4= 4 , SN8 = 8, SN12 =
    12
    }
    public static class RandomSNKGenerator
    {
    private static string
    AppendSpecifiedStr(int length, string str, char[] newKey)
    {
    string
    newKeyStr = "";
    int k = 0;
    for (int i = 0; i < length; i++)
    {
    for
    (k = i; k < 4 + i; k++)
    {
    newKeyStr += newKey[k];
    }
    if (k ==
    length)
    {
    break;
    }
    else
    {
    i = (k) - 1;
    newKeyStr +=
    str;
    }
    }
    return newKeyStr;
    }
    ///


    /// Generate
    standard serial key with alphanumaric format
    ///

    ///
    the supported length of the serial
    key
    /// returns formated serial
    key

    public static string GetSerialKeyAlphaNumaric(SNKeyLength
    keyLength)
    {
    Guid newguid = Guid.NewGuid();
    string randomStr =
    newguid.ToString("N");
    string tracStr = randomStr.Substring(0,
    (int)keyLength);
    tracStr = tracStr.ToUpper();
    char[] newKey =
    tracStr.ToCharArray();
    string newSerialNumber = "";
    switch (keyLength
    )
    {
    case SNKeyLength.SN16:
    newSerialNumber = AppendSpecifiedStr(16,
    "-", newKey);
    break;
    case SNKeyLength.SN20:
    newSerialNumber =
    AppendSpecifiedStr(20, "-", newKey);
    break;
    case
    SNKeyLength.SN24:
    newSerialNumber = AppendSpecifiedStr(24, "-",
    newKey);
    break;
    case SNKeyLength.SN28:
    newSerialNumber =
    AppendSpecifiedStr(28, "-", newKey);
    break;
    case
    SNKeyLength.SN32:
    newSerialNumber = AppendSpecifiedStr(32, "-",
    newKey);
    break;
    }

    return newSerialNumber;
    }
    ///

    /// Generate serial key with only numaric
    ///

    /// the supported length of
    the serial key
    /// returns formated serial
    key

    public static string GetSerialKeyNumaric(SNKeyNumLength
    keyLength)
    {
    Random rn = new Random();
    double sd =
    Math.Round(rn.NextDouble() * Math.Pow(10, (int)keyLength) + 4);
    return
    sd.ToString().Substring(0,(int)keyLength);
    }
    }
    }



    Good luck!

    Get all the days during the months - SQL datetime problems

    Sometimes we want to get all the days in the particular month and what's the tricks using SQL query?


    This is the tricks used in SQL Server 2005 for returning results for the current month.

    SELECT SUM(Amount) AS TotalAmount, CONVERT(CHAR(11),
    Date, 106) AS DateFROM
    dbo.SpendingGROUP BY DateHAVING (Date >=
    CONVERT(DATETIME, dbo.Date(YEAR(GETDATE()), MONTH(GETDATE()), 1), 102)) AND
    (Date < CONVERT(DATETIME, DATEADD(month, 1,

    dbo.Date(YEAR(GETDATE()), MONTH(GETDATE()), 1)), 102))

    what is 102? it is a formating number in which returns only date from datetime value.

    dbo.Date? yes this is custom function which you have to add into your database to simplify the data manipulation.

    "Create function Date(@Year int, @Month int, @Day int) begin return dateadd(day, @Day-1, dateadd(month, @Month-1, dateadd(year, (@Year-1900),0))) end"

    Need more date functions?

    go to http://weblogs.sqlteam.com/jeffs/archive/2007/01/02/56079.aspx thanks to Jeff of the dbo.Date function

    Thursday, February 1, 2007

    Nhibernate or Linq?

    i had been working using NHibernate since last year, however recently, i switched to Linq. The reason is because the Linq is tightly integrated with Visual Studio Orcas. I found that manipulating data is so simple and having implement linq doesn't complicate your application architecture. Additionally, linq and VS introduce signification productivity gain while minimizing investment on producing and maintaining the software. Well, NHibernate does do the job well but the query language is awkward compare to Linq which I need to double check the NHibernate query 's string that i entered is always correct. So will Linq the future choice? Yes but not at the moment, however you can start try NHibernate while waiting the full release of VS Orcas which support Linq. Right now, using NHibernate allows you to switch database provider model on the fly which linq not support (at the moment), meaning that you can switch between MySQL and Oracle by changing the xml file. So no matter what database you use, you are still dealing with the one and only one way of CRUD the database. Btw, you need to use some tool to work with Nhibernate such as MagicDraw (www.magicdraw.com) and AndroMDA (www.andromda.org).

    Learn more:
    Linq to SQL get started snippet example