Friday, December 12, 2008

Remove HTML tags using regex .NET

private string StripTagsRegex(string text)
{
return Regex.Replace(text, "<.*?>", string.Empty);
}

Friday, November 28, 2008

ASP.NET validation problem with Response.Redirect

What is the correct why of doing validation? Why the the form doesn't validated if Response.Redirect code sit under the command button?


answer:

if(Page.IsValid){

Response.Redirect("abc.aspx");

}

Otherwise, the page do not have chance to be validated.

Put ASP.NET dynamic data into your existing application

Sometimes we might want to move the dynamic data folder to another directory so here is the tricks

http://msdn.microsoft.com/en-us/library/cc837197.aspx

http://msdn.microsoft.com/en-us/library/cc837200.aspx


Hope it helps

Thursday, November 27, 2008

Running .NET 3.5 in .NET 2.0 environment

If you love linq and want to get it runs in .NET Framework 2.0 environment, don't worry just copy those files below into your application bin and do some settings in the web.config and it will works.

System.Core.dll
System.Data.DataSetExtensions.dll
System.Data.Linq.dll
System.Web.dll
System.Web.Extensions.dll
System.Xml.Linq.dll


Where to find all these files?

C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5

Sunday, November 9, 2008

Globalization & Localization in ASP.NET

<strong><a href="http://www.blogger.com/post-edit.g?culture=en-US">English</a></strong> | 日本語 |<a href="http://www.blogger.com/post-edit.g?culture=zh-HK">中国</a> | Deutsch | 한국어


if (Request.QueryString["culture"] != null)
{
Session["Culture"] = Request.QueryString["culture"];
}

if (Session["Culture"] != null)
{

Thread.CurrentThread.CurrentUICulture = new CultureInfo(Session["Culture"].ToString());
Thread.CurrentThread.CurrentCulture = new CultureInfo(Session["Culture"].ToString());
}

Create Tag Cloud C# 2.0 - The simplest and fastest way

Output:

palad1 palad2 palad3 palad4

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.Text;

namespace WebApplication1
{

public class ItemFeq
{

private string _PhotoName;

public string PhotoName
{
get { return _PhotoName; }
set { _PhotoName = value; }
}
private int _Count;

public int Count
{
get { return _Count; }
set { _Count = value; }
}

private int _Size;

public int Size
{
get { return _Size; }
set { _Size = value; }
}

public ItemFeq(string photoname, int count, int size)
{
_PhotoName = photoname;
_Count = count;
_Size = size;
}
}

public class ItemTag
{
private int _ItemID;

public int PhotoID
{
get { return _ItemID; }
set { _ItemID = value; }
}
private string _Tag;

public string Tag
{
get { return _Tag; }
set { _Tag = value; }
}

public ItemTag(int itemid, string tag)
{
_Tag = tag;
_ItemID = itemid;
}
}

public class ItemTagComparer : IComparer<ItemTag>
{
public int Compare(ItemTag x, ItemTag y)
{
if (x.Tag == y.Tag) { return 0; } else { return x.Tag.CompareTo(y.Tag); }
}

}

public class ItemFeqByCountComparer : IComparer<ItemFeq>
{
public int Compare(ItemFeq x, ItemFeq y)
{
if (x.Count == y.Count)
{ return 0; }
else
{ return x.Count.CompareTo(y.Count); }
}

}

public partial class _Default : System.Web.UI.Page
{

public string CreateTagCloud(List<ItemTag> tags, int baseSize)
{

tags.Sort(new ItemTagComparer());

List<ItemFeq> photofeqlist = new List<ItemFeq>();

foreach (ItemTag ptag in tags)
{
if (photofeqlist.Exists(delegate(ItemFeq pf) { return pf.PhotoName == ptag.Tag; }))
{
photofeqlist.Find(delegate(ItemFeq pq) { return pq.PhotoName == ptag.Tag; }).Count += 1;
photofeqlist.Find(delegate(ItemFeq pq) { return pq.PhotoName == ptag.Tag; }).Size += 1;
}
else
{
photofeqlist.Add(new ItemFeq(ptag.Tag, 1, baseSize));
}
}

photofeqlist.Sort(new ItemFeqByCountComparer());
photofeqlist.Reverse();


StringBuilder sb = new StringBuilder();

int sum = 0;
foreach (ItemFeq pf in photofeqlist)
{
sum += pf.Count;
}


foreach (ItemFeq pf in photofeqlist)
{
sb.Append("<span style='font-size:" + (pf.Size / (sum / photofeqlist.Count)) * baseSize + "pt'>" + pf.PhotoName + " </span>");

}
return sb.ToString();
}

protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{

List<ItemTag> phototags = new List<ItemTag>();
phototags.Add(new ItemTag(121, "palad1"));
phototags.Add(new ItemTag(122, "palad1"));
phototags.Add(new ItemTag(123, "palad1"));
phototags.Add(new ItemTag(124, "palad1"));
phototags.Add(new ItemTag(125, "palad1"));
phototags.Add(new ItemTag(126, "palad2"));
phototags.Add(new ItemTag(122, "palad2"));
phototags.Add(new ItemTag(122, "palad2"));
phototags.Add(new ItemTag(121, "palad2"));
phototags.Add(new ItemTag(122, "palad2"));
phototags.Add(new ItemTag(121, "palad2"));
phototags.Add(new ItemTag(126, "palad2"));
phototags.Add(new ItemTag(121, "palad2"));
phototags.Add(new ItemTag(122, "palad2"));
phototags.Add(new ItemTag(121, "palad2"));
phototags.Add(new ItemTag(122, "palad3"));
phototags.Add(new ItemTag(123, "palad3"));
phototags.Add(new ItemTag(124, "palad3"));
phototags.Add(new ItemTag(125, "palad4"));
phototags.Add(new ItemTag(126, "palad4"));
phototags.Add(new ItemTag(121, "palad1"));
phototags.Add(new ItemTag(122, "palad1"));
phototags.Add(new ItemTag(121, "palad1"));
phototags.Add(new ItemTag(122, "palad1"));
phototags.Add(new ItemTag(121, "palad1"));
phototags.Add(new ItemTag(122, "palad1"));
phototags.Add(new ItemTag(121, "palad1"));
phototags.Add(new ItemTag(122, "palad1"));
phototags.Add(new ItemTag(121, "palad1"));
phototags.Add(new ItemTag(122, "palad1"));
phototags.Add(new ItemTag(121, "palad1"));
phototags.Add(new ItemTag(122, "palad1"));

Literal1.Text = CreateTagCloud(phototags, 12);

}
}
}

Encode HTML

do u know u need to encode some html code so that it will display correctly in some website because those website afraid you inject some dangerous scripts into their website.

Here is the translation:
http://demo.nickname.net/demo/testpak/encode.pl

The most simple way to group by in a list collection using .NET 2.0 (IEqualityComparer & IComparer) and .NET 3.5 (Linq) functions

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

namespace WebApplication1
{
public class PhotoFeq
{
private string _PhotoName;

public string PhotoName
{
get { return _PhotoName; }
set { _PhotoName = value; }
}
private int _Count;

public int Count
{
get { return _Count; }
set { _Count = value; }
}

public PhotoFeq(string photoname, int count)
{
_PhotoName = photoname;
_Count = count;
}
}

public class PhotoTag
{
private int _PhotoID;

public int PhotoID
{
get { return _PhotoID; }
set { _PhotoID = value; }
}
private string _Tag;

public string Tag
{
get { return _Tag; }
set { _Tag = value; }
}

public PhotoTag(int photoid, string tag)
{
_Tag = tag;
_PhotoID = photoid;
}
}

public class PhotoTagEqualityComparer : IEqualityComparer<PhotoTag>
{
public bool Equals(PhotoTag x, PhotoTag y)
{
if (x.Tag == y.Tag )
{
return true;
}
else
{
return false;
}
}

public int GetHashCode(PhotoTag obj)
{
return base.GetHashCode();
}
}

public class PhotoTagComparer : IComparer<PhotoTag>
{
public int Compare(PhotoTag x, PhotoTag y)
{
if (x.Tag == y.Tag) { return 0; } else { return x.Tag.CompareTo(y.Tag); }
}

}




public partial class _Default : System.Web.UI.Page
{


protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
//output
//kiki 1
//gigi 2
//jojo 3
//sasa 3
//lala 6
//nini 6

List<PhotoTag> phototags = new List<PhotoTag>();
phototags.Add(new PhotoTag(121, "lala"));
phototags.Add(new PhotoTag(122, "lala"));
phototags.Add(new PhotoTag(123, "lala"));
phototags.Add(new PhotoTag(124, "lala"));
phototags.Add(new PhotoTag(125, "lala"));
phototags.Add(new PhotoTag(126, "lala"));

phototags.Add(new PhotoTag(127, "jojo"));
phototags.Add(new PhotoTag(128, "jojo"));
phototags.Add(new PhotoTag(129, "jojo"));


phototags.Add(new PhotoTag(120, "gigi"));
phototags.Add(new PhotoTag(1201, "gigi"));

phototags.Add(new PhotoTag(1202, "kiki"));


phototags.Add(new PhotoTag(1203, "sasa"));
phototags.Add(new PhotoTag(1204, "sasa"));
phototags.Add(new PhotoTag(1205, "sasa"));

phototags.Add(new PhotoTag(1206, "nini"));
phototags.Add(new PhotoTag(1207, "nini"));
phototags.Add(new PhotoTag(1208, "nini"));
phototags.Add(new PhotoTag(1209, "nini"));
phototags.Add(new PhotoTag(1211, "nini"));
phototags.Add(new PhotoTag(1212, "nini"));

//3.5 method
var feqTags = from n in phototags
group n by n.Tag into g
orderby g.Count()
select new { PhotoName = g.Key , Count = g.Count() };


foreach (var g in feqTags)
{
Response.Write(g.PhotoName + " " + g.Count + "<br/>");
}

//2.0 method
phototags.Sort(new PhotoTagComparer());

List<PhotoFeq> photofeqlist = new List<PhotoFeq>();

foreach (PhotoTag ptag in phototags)
{
if (photofeqlist.Exists(delegate(PhotoFeq pf) { return pf.PhotoName == ptag.Tag; }))
{
photofeqlist.Find(delegate(PhotoFeq pq) { return pq.PhotoName == ptag.Tag; }).Count += 1;
}
else
{
photofeqlist.Add(new PhotoFeq(ptag.Tag, 1));
}
}

//search object by comparison
int j = phototags.BinarySearch(new PhotoTag(1202, "kiki"), new PhotoTagComparer());
Response.Write(phototags[j].PhotoID);

//get distinct in list
List<PhotoTag> distinctPhotoTag = phototags.Distinct(new PhotoTagEqualityComparer()).ToList<PhotoTag>();


}
}
}

Wednesday, August 27, 2008

ADO.NET C# common error dealing with inserting NULL value

If you are using c# and you are trying to insert null value into a table by using a shorthand something like below

param.Add("@abc", strAbc == "" ? null : strAbc);

it will not work. And you will got this error such as below:
Parameterized Query '(@Type nvarchar(2),@GroupType nvarchar(1),@Keyword' expects parameter @Type, which was not supplied.

To solve this problem you need to do a trick something like this
param.Add("@abc", strAbc == "" ? (object)DBNull.Value : strAbc);


change from null to (object)DBNull.Value

However, in VB.NET you do not need to cast.

Wednesday, August 20, 2008

Query data using sql and return results as datatable. Super fast method for ADO.NET!

You need to an easy way to query data from the database and fill into the datatable. Here is quick, dirty and secured trick

The method:
public static DataTable GetTable(string sql, Dictionary parameters)
{
DataTable dt = new DataTable("DataTable");
using (SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString))
{
myConnection.Open();
SqlCommand mySqlCommand = new SqlCommand(sql, myConnection);

if (parameters != null)
{
foreach (KeyValuePair p in parameters)
{
mySqlCommand.Parameters.AddWithValue(p.Key, p.Value);
}
}

using (SqlDataReader datareader = mySqlCommand.ExecuteReader())
{
dt.Load(datareader);
}
}
return dt;
}

The query:
Dictionary sqlParams = new Dictionary();
sqlParams.Add("@id", 123);
devReview = DataHelper.GetTable("select * from sometable where id = @id", sqlParams).DefaultView;


Sunday, August 3, 2008

Windows Vista Ultimate - bootmgr is compressed

Today i've tried to install the windows vista ultimate 64bit to build up a 64bit workstation so that i could test to program that runs 64bit. Guess what? A Mesaage shown to me after i finish my vista installation. It just

bootmgr is compressed

prompt a dummy message asking me to press ctrl+alt+del. This intruction does help because it just restarts my pc and appear the message next and over again.

Luckly, i found a solution to this problem. If you encounter this, please use the Vista DVD to boot up your pc and wait until you will see a option that says "Repair your computer" Just click on that.

Later you will see a button "Load Driver", click click on that and go to "My Computer". After all, just right click => Properties. And just make sure the drive is not compressed. Unchecked the "Compress drive to save more space" something like (counld't remember exactly). for just in case the drive is compressed. And you need to do it for each drive. This process take ages, which cause your pc seem to be hang for a long period of time but wait don't restart it until it finishes. It will return you to the main menu. Trust me!

Anyway, I am going to test out my new PC running AMD 5000+ 2.6Ghz dual core. Don't be surprise to see more updates on the tips to make a program that utilizing the multi core processor using PLINQ!

Friday, June 6, 2008

homepage takes too long to load

this is the most common problem we face and most often we keep the page small in size and use less images.

But, what if my homepages a lot of stuffs to get loaded which is a must requirement? The only thing you can do it to Ajax it! you need to separate a page into several html block of codes and load it separately.

What i did is using the ASP.NET AJAX update panel to warp the html code and use timer to load it later. I think this is not really a correct why but it is better then doing nothing.

What else i can do? do you have any solution suggest for me?

Sunday, June 1, 2008

A simple way to get a content from an URL over the internet

sometimes we want to get the content over the internet and process the content, here is a super simple method that i discovered.


using System.Net;
using System.IO;

public static string GetWebContentString(string
url)
{
HttpWebRequest httpReq =
(HttpWebRequest)WebRequest.Create(url);
HttpWebResponse httpRes =
(HttpWebResponse)httpReq.GetResponse();
Stream fs =
httpRes.GetResponseStream();
StreamReader sr = new
StreamReader(fs);
return sr.ReadToEnd();
}

Monday, May 26, 2008

How to call store procedure using .NET

This is how I call store procedure using .NET having passing input value and return by output value

public static int GetSearchCount(string country)
{
int count = 0;
using (SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["dbnamestr"].ConnectionString))
{
conn.Open();
SqlCommand objCmd = new
SqlCommand("sp_SearchCount", conn);
objCmd.CommandType =
CommandType.StoredProcedure;
SqlParameter paramTotal = new
SqlParameter("@Total", SqlDbType.Int);
paramTotal.Direction =
ParameterDirection.ReturnValue;
objCmd.Parameters.Add(paramTotal);
objCmd.Parameters.AddWithValue("@Country", country);
objCmd.ExecuteScalar();
count = (int)paramTotal.Value;
}
return
count;
}

Using stored procedure and inline sql in your application

Programmers always ask which is better and which should they choose. Is store procedure has better performance or inline sql with ORM is better at gaining productivity? Well depends who you are, what applications you develop, the answers are very different from person to person.

I use store procedure when I knew the query is complicated which requires multiple joins tables and I knew that i will query it very often, hence using store procedure will make a significant different in performance gains. For example, you run the optimized precompile sql statements. you delegate the computation of data within the sql server and minimize sql query back and forth and also you make your query pretty secured by using SP

Meanwhile using inline sql is not a good practise unless you are using Object Relational Mapping (ORM) tools to generate those inline sql for you and all you need is to use the objects created. It is the fastest and simple way to query and manipulate the database with the power of OOP. If you are using inline sql as a short cut way to query data, you gotta becareful and takes various precautions steps to overcome sql injection attacks. Sometimes a string of sql statement hard coded in your program can be a maintenance problem because it is quite difficult to test the validity of sql statement.

FYI, I use SP for complicated queries. I use inline sql (usually generated by ORM) for simple CRUD to direct display data that do not involve calculations. Query using ORM can be more complicated and requires more resources than using the SP, so just keep things simple and understandable.

I am not bias to one or another, I just want to point out that by using the right technology in your application will have a greater benefit of sticking to one technology. Tool is created for making us easier, if you found that the tool is great, just use it, otherwise get another alternative.

Thursday, April 3, 2008

Upload image to web server using webservice .NET

To transfer a file to the web server, it is not necessary to use FTP to upload. You can use webservice to do so. Here is the trick:

public string CreateFileToBase64String(string path)
{
Stream fs = new FileStream(path, FileMode.Open);
MemoryStream ms = new MemoryStream();
const int size = 4096;
byte[] bytes = new byte[4096];
int numBytes;
while ((numBytes = fs.Read(bytes, 0, size)) > 0)
ms.Write(bytes, 0, numBytes);
ms.Close();
fs.Close();
return Convert.ToBase64String(ms.GetBuffer());
}
public void CreateFileFromBase64String(string imageData, string path)
{
MemoryStream msf = new MemoryStream(Convert.FromBase64String(imageData));
Stream stem = new FileStream(path, FileMode.Create);
msf.WriteTo(stem);
msf.Close();
stem.Close();
}

you see things is so simple.

How to get web content from the web .NET

Sometimes I need to download the html content from the internet, therefore this method is very useful.


public static void GetWebContent(string url, string saveToPath)
{
if (IsValidUrl(url))
{
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse httpRes = (HttpWebResponse)httpReq.GetResponse();
Stream fs = httpRes.GetResponseStream();
FileStream fss = new FileStream(saveToPath, FileMode.Create);
const int size = 4096;
byte[] bytes = new byte[4096];
int numBytes;
while ((numBytes = fs.Read(bytes, 0, size)) > 0)
fss.Write(bytes, 0, numBytes);
fss.Close();
}
}

Find the image height and width using .NET

See as simple as this:

System.Drawing.Imaging.BitmapData bit = new
System.Drawing.Imaging.BitmapData();
int height = bit.Height;

Wednesday, March 26, 2008

ConnectionStrings for SQL Server 2005

ConnectionString for sql server 2005 look like this. Please remember dude...

<*connectionStrings>
<*add name="lala"
connectionString="server=user\sqlexpress;integrated
security=true;database=test"/>
<*/connectionStrings>

How to create xml document from database ado.net

I hate to code with xml because i always forgotten the methods, therefore i blog it here so that i could help someone like me. :)

The 0utput lala.xml

<*Library>
<*Book id="1">
<*Name>Programming
<*Author>L.L Yee
<*Book id="2">
<*Name>Mathematics
<*Author>Jason Lee
<*/Library>
You need this code:
using System;
using System.Collections.Generic;
using
System.Text;
using System.Data.SqlClient;
using
System.Configuration;
using System.Xml;
namespace TobyXML
{
class
Program
{
static void Main(string[]
args)
{
ReadCustomerFromDB();
}
public static void
ReadCustomerFromDB()
{
string sql = "Select * from library";
string
output = "";
using (SqlConnection myConnection =
new
SqlConnection(ConfigurationManager.ConnectionStrings["lala"].ConnectionString))
{
myConnection.Open();
SqlCommand
mySqlCommand = new SqlCommand(sql, myConnection);
SqlDataReader datareader =
mySqlCommand.ExecuteReader();
XmlDocument xmlDoc = new
XmlDocument();
xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlNode
nodeLibrary =
xmlDoc.CreateElement("Library");
xmlDoc.AppendChild(nodeLibrary);
while(datareader.Read())
{
XmlNode
nodeBook = xmlDoc.CreateElement("Book");
XmlAttribute attId =
xmlDoc.CreateAttribute("id");
attId.Value =
datareader["bookid"].ToString();
nodeBook.Attributes.Append(attId);
XmlNode
nodeName =
xmlDoc.CreateElement("Name");
nodeName.AppendChild(xmlDoc.CreateTextNode(datareader["bookName"].ToString()));
nodeBook.AppendChild(nodeName);
XmlNode
nodeAuthor =
xmlDoc.CreateElement("Author");
nodeBook.AppendChild(nodeAuthor);
nodeAuthor.AppendChild(xmlDoc.CreateTextNode(datareader["author"].ToString()));
nodeLibrary.AppendChild(nodeBook);
}
datareader.Close();
xmlDoc.Save(@"c:\lala.xml");
}
}
}
}

Tuesday, March 18, 2008

How to get HTML tag with regex?

Regex this is the best one!

<*/?\w+((\s+\w+(\s*=\s*(?:".*?"'.*?'[^'">\s]+))?)+\s*\s*)/?>

please ignore the * at the <*

Get data from the database stright away! .NET

Sometimes you want the most strightforward way to get data from the database without going through the N-tiers stuffs.

This technique have advantages and disadvantages,

Advantage:
The fastest data access beside store procedures.
Simple and strighforward.


Disadvantage:
Not strongly typed,
Possible of memory leak if not code propertly
Things get complicated if involve insert record or large table which have many columns.

public string ReadCustomerFromDB()
{

string sql = "Select
name, phone, age from Customers where customerid =
@customerId";

string output = "";

using (SqlConnection myConnection = new
SqlConnection(ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString))
{
myConnection.Open();

SqlCommand mySqlCommand = new SqlCommand(sql,
myConnection);

mySqlCommand.Parameters.AddWithValue("@customerId", 123456);

SqlDataReader datareader =
mySqlCommand.ExecuteReader();

while
(datareader.Read())
{

Output +=
datareader["name"];

Output +=
datareader["age"];
}

datareader.Close();
}
return output;
}

Format currency using Globalization .NET

There are some elegant way to format the currency such as

String.Format(“{0:c}”,100000”)

The output will be RM100,000.00 if your web.config file set as

<*system.web*>
<*globalization uiCulture="en" culture="en-MY" /*>

However this will not throw you an error if you are using windows vista. such as
The tag contains an invalid value for the 'culture' attribute.
if there is an error please refer to http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemGlobalizationCultureInfoClassTopic.asp to find out your own culture code.

in this case i should change it to

<*globalization uiCulture="ms" culture="ms-MY" /*>

....
If you set the culture to “en-US” then the output will changed to
$100,000.00
You can check your currency symbol by using this code

System.Globalization.RegionInfo myRI2 = new System.Globalization.RegionInfo(new CultureInfo("en-my", false).LCID);
Console.Write(myRI2.CurrencySymbol);

For more information on setting the culture for specific to your country, please refer the code from this website:
http://msdn2.microsoft.com/en-us/library/system.globalization.regioninfo.aspx

Alternatively, you can specify use string. Format (“{0:$#,##0.##}”,50000), you can replace the ‘$’ whaterver you like. however this is not a good practice.

Saturday, March 15, 2008

How to customize community server 2007?

Ever think of customize community server 2007? Yes, you can. However to teach you the whole thing will be long story, therefore keep thing simple. Just follow this guideline and try it yourself. Here the steps:

1. Download the SDK cs2007.1 from communityserver.org

2. Refer to short and tested step from doc.communityserver.org/wiki/page.aspx/399/how-to-create-new-themes/ (please follow the step from 1,2 and 3 only)

3. Install your cs2007.1 database

4. Compile and Run the SDK source code from VS 2005, note you have to do some setting in the property page such as running it from dynamic port rather than localhost ISS

5 .Copy the created theme from step 2 and paste the dir into the cs theme directory.

6. refresh and include the dir. Edit the pasted dir only.

7. try to edit the master.master such as remove the logo and run it and feel the different.

Good luck, i have tested it and it works!

Sunday, March 2, 2008

good design determine programmer productivity that create reliable system

An enterprise system is complex and it has to be able to handle day to day business processes and activities. The reliability of the system is so much dependent on how the system was designed and developed by the programmer. Programmer need to code well and able to create a system with the most reliable code. However, in practical to be able to achieve a highly reliable system is very costly to the organization. The reason is because a lot of testing need to be done to ensure that every source code is validated. Microsoft particuallary has been trying to improve the reliability of Windows by patches and patches after the final release. Why need to do in that way? Why not to produce a system which is 100% free of bugs? The answer of this question is too simple to say that it is very time consuming and costly to examine every possiblility of the failure in the system. We have no choice but keep complaining about the reliability of the system and luckly there are software developers who are keeps fixing it. This is how the software industry works. If some one were to change it, it is the last breakthrough of information technology.

To start to design a stable and reliable system, 3 things need to keep in mind at first. 3 rules: guidelines need to be followed, always keep things simple and last but not lease always keeps design a good database structure by having 3rd NF.

Guidelines are the findings and experinces of the system designer in which makes the best to design the system. It also covers the rules that draw the requirements. Guidelines are important because the things to be followed and the things to be avoided during the system development cycle, guideline are very depending on each organization, therefore you set your own rules.

KISS, keep it simple, the secret that always work in every situation in our life. Keep it simple does not means to ignore requirements but to avoid doing things in a hard way. We need to be smart in finding alternative which is elegant and simple enough to our self to accomplish thing. For example, i can save time by having alble to find 5Min's solution using Google. Smart isn't it?

Database design is very very important. We hardly see an enterprise system without using database. A large system particularly are very used to having a database server to serve everyday data intensive client. Moreover, an efficient and high performance database system is critical to the success of the system as a whole. Therefore database design is extremely critical to determine the reliability of the system and the productivity of the programmers. Why? The reasons are, programmer need to code less and perhaps it is easier to code if the database design is in properly designed. I once experience to do develop a system in which the database design is not in the proper way. In this case i had to write additional code which is not necessary to make it work and i had to spend much my time to check the data to ensure it was consistent across the system. Why we need to check by us since a relational database system is so good in enforcing constrain in every database manipulation that keep data integrity. Therefore a good database design must have this 3 things, 3rd NF, one primary key for each table and have relational constrain.

A lot of problem will happen during the system development if the initial system design is not good enough. The worst thing is that the database design is in bad shape, i wonder how many debugging time has been wasted during the system development.

Friday, February 15, 2008

check if url is valid and accessible .NET

This is a common problem for most of ASP.NET developer when we try to check if the url is valid or not. Here is a tip for you. :)

public static bool IsValidUrl(string url)
{
HttpWebRequest httpReq =
(HttpWebRequest)WebRequest.Create(url);
httpReq.AllowAutoRedirect =
false;
httpReq.Method = "HEAD";
httpReq.KeepAlive =
false;
httpReq.Timeout = 2000;
HttpWebResponse httpRes;
bool exists =
false;
try
{
httpRes = (HttpWebResponse)httpReq.GetResponse();
if
(httpRes.StatusCode == HttpStatusCode.OK)
{
exists =
true;
}
}
catch (Exception ex)
{
}
return exists;
}

Sunday, February 10, 2008

Google map program using .net

You can create a custom google map by using Google Maps Api which example found in http://code.google.com/apis/maps/documentation/examples/


However, those example is written in java script and it is not so stright forward to be used in ASP.NET code.... Anyway, to work with java script code with ASP.NET keep these in mind


let txtLongitude is a control which can be used inside javascript, u can called the txtLongitude by
""

txtLatitude.ClientID is used because is require if you are using ASP.NET master pages.

Thursday, February 7, 2008

confusing file path for web developer .net

Are you one of the developer always confuse whith this kind of path e "games/alien.jpg" or "../games/alien.jpg" or "/games/alien.jpg" ? Even if you know the meaning, i am sure you still have problem of this because the path is constructed as it depends how the caller is located. Seem to be over complicated here. :)

I am one of the developer that alwasys confuse with file path that looks like <*img src=".../love/app/basic.jpg" /*>". i really do not like because it can be problematic especially if you are ASP.NET developer that uses master pages across the pages.

if you are one of those guy that always experince broken links, I have an elegant solution to this problem.

Given a virtual directory named site, which can be accessibled as http://localhost/site and you have a file which located at http://localhost/site/games/alien.jpg

to effectively locate the alien.jpg, you got to use this

ResolveUrl("~/games/alien.jpg")

In this way, you won't be confused how the file is located. ~ represents the parent virtual path.

Ok, if you wish to upload the file to the server using the ResolveUrl don't give you the real path... in this case, replace the ResolveUrl method to MapPath method.

e.g:

MapPath("~/games/alien.jpg"). The file will be uploaded to the location of '~'.


Got it?

Different between web application and windows application

Obviously, by the name itself web application is built for web and can be viewed by internet browser. Whereas windows application is a program that runs under windows. People choose web application because web app can relatively easy to deloy and once deloy it is readily widely available to anywhere and anytime. The design itself is distrbuted and programmers do not need to worry so much about complicated deloyment consideration. Sometimes, programmers choose to write in windows application is because somethings cannot be possibly done by having web application. For example, extensive use of processing power such as graphic randering program, e.g 3D designer program. A special program that deals with hardware such as printer driver, have to be written in windows application. Usually "designer program" oftens built as windows application. Whereas business application that requires multi users such as inventory system is oftenly built as web application.

If you are unsure of which is the best choice to go with, please follow my guildline, -

first think of if the program can be easily built and deployed by having web application, if the answer meet these criteria, then go for web application.

Otherwise go for windows application. or perhaps a combination of web and windows which known as smart application which combinethe best of both.

As my own preference, i like web application because it is relatively easy to manage the communication between modules and because it support css which makes styling much easier and faster.

I had been building windows application by using the composite application block CAB... The framework is cool but deployment can be much hassle because you have to worry the security issues ( you do not want your files be hacked by the user because he got your files).

Last but not least, go for web if possible for business realated appplication.

Post me a comment if you are disaggree with me :)

Monday, February 4, 2008

Split camel casing using regex .NET

ever wonder any better apporoch to convert "BeMyLover" to "Be My Lover"? Here the function in C#.


private string SplitCamelCasing(string input)
{
string output =
"";
return output =
System.Text.RegularExpressions.Regex.Replace(
input,
"([A-Z])",
"
$1",
System.Text.RegularExpressions.RegexOptions.Compiled).Trim();
}

Sunday, February 3, 2008

An easy way to manipulate database using Subsonic

I had been using various tools to manipulate database. The only tool that i find very simple so far .net web development is subsonic. http://www.subsonicproject.com/.

Subsonic is really powerful to CRUD your database. SQL is not nessary and it is all object oriented. The best object realtional mapper for .net 2.0

Give a try :)

Thursday, January 17, 2008

dropdownlist postback problem ASP.NET

have you encounter that ASP.NET dropdownlist control have a problem of persistent the data in the items list after you had make a postback? The problem is actually you have disabled the EnableViewState. Therefore the control will not persist any data after an postback. To enable it back, just - EnableViewState="true".

This is a super tips, because you might disabled it, in this case turn it on!