Thursday, November 29, 2007
Export table and data using SqlBulkCopy
method to export
generate a sql script with having the sql schema
use this program simple sql bulk copy downloadable from http://projects.c3o.com/files/default.aspx
ref:
http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx
Sunday, October 14, 2007
What programming language is the best?
Tuesday, August 14, 2007
Create a serch engine with linq
The techniques needed in constructing search engine are regular expression, Linq, Generic, C#, sort and ranking algorithm.
Here is the code:
using System;
using System.Collections.Generic;
using
System.Text;
using System.Text.RegularExpressions;
using
System.Query;
namespace search
{
public class Search
{
private
List_SearchRelevance = new
List();
public List
SearchRelevence
{
get
{
return
_SearchRelevance;
}
}
private List_Results =
new List();
public List
Results
{
get
{
return
_Results;
}
}
public Search(string input, string[]
text)
{
for (int i = 0; i < text.Length; i++)
{
SearchRelevance
sr = new SearchRelevance(input,
text[i]);
sr.Calculate();
_SearchRelevance.Add(sr);
}
Sort();
}
private
void Sort()
{
var relevences =
from w in _SearchRelevance
orderby
w.RelevancePoint descending
select w;
foreach (SearchRelevance sri in
relevences)
{
_Results.Add(sri);
}
}
}
public class
SearchRelevance
{
public SearchRelevance(string input, string
text)
{
_OriginalText = text;
_UserInput = input;
}
public
override string ToString()
{
return _RelevancePoint.ToString() +" "+
_OriginalText ;
}
internal void Calculate()
{
string[] splitedinput
= UserInput.Split(new char[] { ' ' });
Dictionary
relevency = new Dictionary();
//initialize the relevency
dic.
for (int i = 0; i < splitedinput.Length;
i++)
{
relevency.Add(splitedinput[i], 0);
}
for (int i = 0; i <
splitedinput.Length; i++)
{
Regex reg = new Regex(splitedinput[i],
RegexOptions.IgnoreCase);
if (reg.IsMatch(OriginalText))
{
int
point;
relevency.TryGetValue(splitedinput[i], out
point);
relevency.Remove(splitedinput[i]);
relevency.Add(splitedinput[i],
++point);
}
}
_Relevancy = relevency;
//sum the relevency
int
rpoint = 0;
foreach (KeyValuePairkv in
relevency)
{
rpoint += kv.Value;
}
_RelevancePoint =
rpoint;
}
private string _UserInput;
public string
UserInput
{
get
{
return _UserInput;
}
}
private string
_OriginalText;
public string OriginalText
{
get
{
return
_OriginalText;
}
}
private int _RelevancePoint;
public int
RelevancePoint
{
get
{
return _RelevancePoint;
}
}
private
Dictionary_Relevancy = new Dictionary int>();
public Dictionary
Relevancy
{
get
{
return _Relevancy;
}
}
}
public class
Program
{
static void Main(string[] args)
{
string[] sb = new
string[4];
sb[0] = "Relevance cassida shell theory may be seen as an
attempt";
sb[1] = "registered by NSF (Class H1) cassida for use
where";
sb[2] = "Shell Cassida Silicone Fluid is";
sb[3] = "to work out in
detail one of Grice’s central claims";
string input = "nsf shell central h1
sillicone fluid";
Search sr = new Search(input, sb);
SearchRelevance[] res
= sr.Results.ToArray();
}
}
}
Thursday, August 9, 2007
XML as data storage, query with Linq
However, there is a problem that storing data in database always seem to be bulky for small application. Imagine that, you are creating a subsystem as a service of a larger system, which has is own database implementation. Logically, it is not advisable that the sub system use it own database or share the data store with the larger system mainly because having a it own database is too bulky and has environment limitation. And, if data store is shared meaning that integration will be too costly and complicated.
The solution is to use XML as isolated data storage. We have to build services around the data and expose it as interface for larger system integration. Having using xml as data, the integration is much simpler and less impact on the overall larger system.
Most people i would say do not like to query XML data because of the complicated query and it is not SQL liked. However, now the situation has changed, you can query data having SQL liked by using linq to XML. Developer can use linq to query XML data. In the next discussion, I will show you how you can play around with this Linq to XML technique.
Frackyly, i do not like XML as data store until i found that Linq has so much to promise.
for more information on the linq technology, please visit
http://msdn2.microsoft.com/en-us/netframework/aa904594.aspx
Read XML data and bind to datagridview .NET
dataSet1.ReadXml("kwyProducts.xml");
dataGridView1.DataSource =
dataSet1;
dataGridView1.DataMember = "KWYProducts";
Notes: please specify your DataMember correctly else will throw you this error:
Child list for field KWYProduscts cannot be created.
Wednesday, July 25, 2007
How to restore a sql server database backup?
Use Master
RESTORE DATABASE DinnerNow FROM
DISK = 'C:\DinnerNow.bak' WITH MOVE
'DinnerNownew' TO
'F:\Program Files\Microsoft SQL
Server\MSSQL.4\MSSQL\Data\DinnerNownew.mdf', MOVE 'DinnerNownew_log' TO
'F:\Program Files\Microsoft SQL
Server\MSSQL.4\MSSQL\Data\DinnerNownew.ldf'
GO
How to enumerate Generic Dictionary .NET list
//instantiate a dictionary list
Dictionary_PointDic = new
Dictionary();
public Dictionary
PointDic
{
get { return _PointDic; }
set { _PointDic = value; }
}
//add value to named key
public void AddPoints(int point, string
ruleName)
{
int temp = 0;
if (!_PointDic.TryGetValue(ruleName, out
temp))
{
_PointDic.Add(ruleName,
point);
}
else
{
_PointDic.Remove(ruleName);
_PointDic.Add(ruleName,
point);
}
}
//sum up the values in the dictionary list
public int
CalculatePoints()
{
int totalpoints = 0;
foreach
(KeyValuePairs in _PointDic)
{
totalpoints +=
(int)s.Value;
}
return totalpoints;
}
Monday, July 16, 2007
ConfigurationManager .Net
//Read settings
public static string ReadConfig(string key)
{
return ConfigurationManager.AppSettings.GetValues(key)[0];
}
//Update Settings & get immediate changes
public static void SetConfig(string key, string value)
{
Configuration con = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
con.AppSettings.Settings[key].Value = value;
con.Save(ConfigurationSaveMode.Full);
ConfigurationManager.RefreshSection("appSettings");
}
Thursday, June 14, 2007
Create a distributable workflow enabled smart client
We wanted to develop a windows application which has to be distributed to multiple computers and having multiple users. Here we have one challenge, we need to host the Workflow. The most simple implementation is to host workflow in a dedicated server where many clients can access to it. Next we have to expose the workflow as webservice, this is important because workflow as webservice can give you the maximum flexibility in connectivity and interoperability. For example, connect a mobile device that runs java application. Sound interesting?
I will post the tutorial on building your first smart client workflow enabled application here for your reference.
Wednesday, June 6, 2007
Short hand using if else for ADO.NET
command.Connection.Open();
ccommand.Parameters.Add("@AddressID", (object)AddressID?? DBNull.Value );
SQL Compact return new insertion identity
Try this code it will help.
public Int64 AddCustomer(string LastName, string FirstName, int?
AddressID, string MembershipUsername, string PhoneNumber, string
MobilePhoneNumber)
{
SQLCeHelper sqlce = new
SQLCeHelper(Properties.Settings.Default.CarServ3DB4ConnectionString);
string
queryString =
"INSERT INTO Customer" +
"(LastName, FirstName, AddressID,
MembershipUsername, PhoneNumber, MobilePhoneNumber)" +
"VALUES
(@LastName,@FirstName,@AddressID,@MembershipUsername,@PhoneNumber,@MobilePhoneNumber)";
Int64
newIdentity = 0;
using (SqlCeConnection connection = new
SqlCeConnection(
Properties.Settings.Default.CarServ3DB4ConnectionString))
{
SqlCeCommand
command = new SqlCeCommand(queryString,
connection);
command.Connection.Open();
command.Parameters.Add("@LastName",
LastName);
command.Parameters.Add("@FirstName",
FirstName);
command.Parameters.Add("@AddressID", (object)AddressID??
DBNull.Value );
command.Parameters.Add("@MembershipUsername",
MembershipUsername);
command.Parameters.Add("@PhoneNumber",
PhoneNumber);
command.Parameters.Add("@MobilePhoneNumber",
MobilePhoneNumber);
command.ExecuteNonQuery();
SqlCeCommand command1 = new
SqlCeCommand("select @@identity ", connection);
newIdentity =
Convert.ToInt32(command1.ExecuteScalar());
}
return
newIdentity;
}
Thursday, May 31, 2007
FileNotFoundException was unhandled
Could not load file or assembly 'System.Data.SqlServerCe, Version=9.0.242.0,
Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies.
The system cannot find the file specified.
You might encountered this error when the System.Data.SqlServerCe version has redirected to another newer version due Visual Studio 2005 generated code on your application config file.
To solve this problem, you have to delete something like below in you app.config file.
xmlns="urn:schemas-microsoft-com:asm.v1"> name="System.Data.SqlServerCe" publicKeyToken="89845DCD8080CC91"
culture="neutral"/>newVersion="9.0.242.0"/>
hope this helps
Saturday, May 26, 2007
You are trying to access an older version of a SQL Server Compact Edition database. If this is a SQL Server CE 1.0 or 2.0 database, run upgrade.exe.
To repair it you must use the
System.Data.SqlServerCe.SqlCeEngine class, version 9.0.242.0 or 3.5.0.0
Here is the example of the implementation.
File.Copy(@"F:\northwind.sdf",@"F:\northwind.sdf.temp");
File.Delete(@"F:\northwind.sdf");
SqlCeEngine
engine = new SqlCeEngine(@"Data Source
=F:northwind.sdf.temp");
engine.Compact(@"Data
Source=F:\northwind.sdf");
File.Delete(@"F:\northwind.sdf.temp");
A repaired northwind.sdf is produced and now you should not be getting this error again. Any other alternative? Please let me know. :)
Friday, May 25, 2007
Before trying to solve, think first
Do your research and gather as much information as you can.
Any question, don't wait... ask Google.
Give yourself various alternative solutions.
Be creative and don't afraid to break the rules.
If you could follow all these mention above, you could be a better problem solver.
Wednesday, May 23, 2007
software user interface design.
A great UI must always have these criteria:
simple and does the job right.
good navigation and proper UI arrangement
easy accessible functions and customized menu for the user
fast and responsive UI
please keep in mind that UI design is the first user impression of the software.
Thursday, April 5, 2007
Keep application performance design in first place.
Assume that we design a small program called Sales Reporting to be used in an organization. Since the program has just only a few modules, we ignore the performance design. Over the time, we might be adding some functionality, hence the complexity of the program increase. Maintainability of the program also an issue if the program is not well designed. One day, you are requested to improve the performance of the program because users are keep complaining that the slow loading program keep them not be patient anymore. Users are fed up and their work is always distracted. The company are not going to invest to redesigned the program because over the year many time and money was spent in maintaining the program. The program is reliable and the problem is just lack of performance. You as a software consultant is hired to perform this task, what is the first thing you would do?
You might be run test the program at the first place to see which area need to be improved. You had identify that some areas need to be redesigned for significant performance gain. You had just planned the initial strategy. Secondly, you are looking to the source code, you are over surprise that most part of the code could be very difficult to be modify for performance gain because the original designer do not keep the best practise in coding hence lead to performance issue. Another concern is that the application is extremely tedious to convert to threaded application because initially the program is very difficult to maintain and the structure the application is not well understood by anyone.
You see, the scenario above has demonstrated that application tend to be extremely difficult to gain performance when the application aged. To solve this problem we must keep performance design in the first place during application planning and design phase.
Wednesday, April 4, 2007
Format default date in SQL Server 2005
CONVERT(CHAR(11), getdate(), 106) AS Date
Thursday, March 8, 2007
Framework 3.5 linq rocks inside .NET 2.0
Great job!
Thursday, March 1, 2007
SQL Server 2005 Compact Edition - Internal Error: Invalid reconciler parameter
For more detail explanation, please go to
http://pluralsight.com/blogs/jimw/archive/2006/06/18/28427.aspx
SQL Server 2005 Compact Edition Tutorial
N Computing vs Personal Computing - my point of view
After i had done my researches and I found that the device is not as cheap as i thought. In the US it is sold at USD50 per device however in Malaysia, it is sold at USD162. NComputing in Malaysia pricing is so ridiculous and unreasonable since today computing is so cheap that i could built a PC with a 2.8GHz processor, motherboard V+L+S, 512 RAM, DVDRW drive and casing (a PC really need a protection), which cost me at USD151 only. That is US10 cheaper and I could get a real computer rather that just a simple station box. I could upgrade my PC over time with more functionality but I have limited or no upgradable ability with the NComputing station box.
Are you wondering how i could built the PC so cheap? The reason is the PC has no hard disk inside because i want to compare between "Apple X" and "Apple Y". The concept of using N computing is to connect the station box (client) with the host (server) in multi-user session scenario using a network connection. However it also can be done by a PC without a hard disk since I could use a open source Linux OS distribution such as KNOPPIX (http://www.knopper.com/) to be loaded by just a CD or DVD!. Inside the distribution DVD, it comes with plenty of useful software including Open Office 2.1 and a FireFox Internet browser. In this case I could remote access to my Windows Server 2003 host which supports multi-concurrent user via the Internet browser. Therefore, I have no problem running Windows application such as Ms Office 2007.
As my conclusion, I would consider the station box if it is less than US50 else it should be an obsolete technology if the cost of making it is too high. Since today computing is so cheap, in which an unused CPU resources could be used as distributed computing purposes but not the station box.
Wednesday, February 28, 2007
Extreme Programming Part 1 - Introduction
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
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
- Install ADAM. Download ADAM from http://www.microsoft.com/downloads/details.aspx?FamilyId=9688F8B9-1034-4EF6-A3E5-2A2A57B5C8E4&displaylang=en
- Install into your Windows Server 2003 (recommended).
- After the installation you need to follow this tutorial presented here. [Download Pdf]
- You need to configure web.config, please follow the http://msdn2.microsoft.com/en-us/library/system.web.security.activedirectorymembershipprovider(VS.80).aspx
- 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
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
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:
- Students and tutor membership management
- Class scheduling, course booking and students & tutors' timetable management.
- Students performance ranking and enrollment statistics.
- Automated e-exam creation by selecting question from questions' bank.
- Custom personal web pages for students and tutors.
- Course materials management. File sharing, upload and download facilities.
- Course enrollment system.
- Voting and suggestion system.
Optional features.
- Thesis plagiarism detection.
- Automated timetable scheduling system.
- 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
Friday, February 23, 2007
How to enable Secure Soket Layer SSL in IIS 5.0/6.0 Server using VeriSign?
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:
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
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?
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?
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
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.
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
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?
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?
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?
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?
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 tempstrstring 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 datatempstr += 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
<*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.
How to get assembly infomation?
int buildnum = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Build
Custom serial number key generator 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-C5D3here's the one line of code :
string serialNumber =
RandomSNKGenerator.GetSerialKeyAlphaNumaric(SNKeyLength.SN16);
or if you want to generate random number only :
Simple?string serialNumberNumberOnly =
RandomSNKGenerator.GetSerialKeyNumaric(SNKeyNumLength.SN12);
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?
Learn more:
Linq to SQL get started snippet example