Wednesday, July 1, 2009

Regex for strong password implementation

Advance password

(?=^.{12,}$)((?=.*\d)(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$

Passwords will contain at least (1) upper case letter
Passwords will contain at least (1) lower case letter
Passwords will contain at least (1) number or special character
Passwords will contain at least (12) characters in length

Basic password

(?=^.{12,}$)((?=.*\d)(?=.*\W+))(?![.\n])(?=.*[a-z]).*$

Passwords will contain at least (1) letter
Passwords will contain at least (1) number or special character
Passwords will contain at least (12) characters in length

Monday, May 11, 2009

how to add mata keyword & meta description in ASP.NET?

There is no easy way to add but I have a simple method to introduce


pageEx.cs

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

public class PageEx : System.Web.UI.Page
{

private HtmlMeta
metaDescription = new HtmlMeta();
private HtmlMeta metaKeywords = new
HtmlMeta();

public string Description
{
get { return
metaDescription.Content; }
set { metaDescription.Content = value; }
}


public string[] Keywords
{
get
{
if
(metaKeywords.Content == null)
{
return new string[] { "" };
}
else
{
return metaKeywords.Content.Split(new char[] { ',' });
}
}

set
{
if (value != null)
{
metaKeywords.Content =
string.Join(",", value);
}
}
}


public PageEx()
{
Init += new EventHandler(PageEx_Init);
}

void PageEx_Init(object
sender, EventArgs e)
{
//Add the description Meta control
metaDescription.Name = "description";
Page.Header.Controls.Add(metaDescription);
//Add the keywords Meta
control
metaKeywords.Name = "keywords";
Page.Header.Controls.Add(metaKeywords);
}


}



someasp.aspx


protected void Page_Load(object sender, EventArgs e)
{

this.Description = "the power 123";
this.Keywords = new string[] {
"Enquiries", "enquiry", "contact", "contacts", "email", "tel" };

}




Hope this helps :)

Tuesday, April 28, 2009

a simple method to manipulate data using sql using .net

public static DataTable ExecuteSQL(string sql, Dictionary parameters)
{
DataTable dt = new DataTable("DataTable");
using (SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["localConnectionString"].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;
}
//insert a tag record
Dictionary param = new Dictionary();
param.Add("@TagName", txtTagName.Text);
ExecuteSQL("INSERT TOP (200) INTO Tag(TagName) VALUES (@TagName)", param);

Friday, March 27, 2009

add or modify table column using sql server database script

it is always recommended that you use script to run for modifucation rather set by using interface for this case.

Here is the trick


To add new column:
ALTER TABLE Customer ADD IsFeatured bit not NULL default 0

To modify existing column such as data type:

ALTER TABLE news ALTER COLUMN title VARCHAR(150) NOT NULL

Thursday, March 26, 2009

How to run VB code and C# code in appCode folder?

In the web.config, under compilation

<compilation debug="true" strict="false" explicit="true">

add,
<codeSubDirectories>
<add directoryName="VBCode" />
<add directoryName="CSCode" />
</codeSubDirectories>


VBCode and CSCode are the folders in the AppCode.

Thursday, March 19, 2009

ASP.NET move to next record or move to previous record

Basically, ASP.NET does not have move next or move previous function, therefore you need to manually use a for loop to determine the position of the target index and then use position + 1 or position -1 to get the next or previous record.

If you are developing a windows form then you are lucky you can use BindingContext[dataTable].Position + 1 or BindingContext[dataTable].Position - 1.

Well, we are talking about ASP.NET here, if we are populating a few hundreds items and use for loop to get the position and I think it is fine. Or u might be using datatable something like

DataTable dt = new DataTable();
dt.Rows.IndexOf(datarow);

to get the index and from there u manipulate it.

However what if we have 1 million of records in the table? That would be crazy!

The more efficient way is to use over keyword which only available in SQL Server 2005 or later. The idea is to get the previous record and the next record given the record identity. I just have to get 2 records and I just want the first record as previous and second record as next. So here is the trick.

subcategoryid, name


31Game Downloads


32Computers & Accessories


33Software


34PC Games


35Computer Components


36Office Products & Supplies





select top(1) row_number() over (order by subcategoryid desc) row, subcategoryid, name from subcategory where subcategoryid<33
union
select top(1) row_number() over (order by subcategoryid) row, subcategoryid, name from subcategory where subcategoryid>33
results:

1 32 Computers & Accessories
1 34 PC Games

p/s please note that this solution only applicable for int column having auto numbering enabled only. the subcategoryid is the primary key, auto number and numaric

Wednesday, March 18, 2009

SQL upcoming date

if you want to get the up coming listing such as event you can do a SQL query like this:

SELECT EventID, EventName, StartDate, EndDate, EventTime, EventLink
FROM Events
WHERE (StartDate BETWEEN GETDATE() AND GETDATE() + 45) AND (GETDATE() BETWEEN StartDate AND EndDate + 1)
ORDER BY StartDate

Thursday, March 12, 2009

get data from excel using linq .net

You might want to read excel file and import the data from the excel into your .net application. Therefore you need a service that provide you this functionality. Here is the class that you can use it.

I suggest you to import the data and store into a DataTable and from there you can start to manipulate it. You can also use a linq to query the data. Is that simple and easy?

Initialization
PrivatePropertyExcel ppe;
DataTable currentExcelDataTable;

private void btnTestConnection_Click(object sender, EventArgs e)
{
try
{
if (openFileDialog1.ShowDialog() == DialogResult.OK && txtSheetName.Text != "")
{

ppe = new PrivatePropertyExcel(openFileDialog1.FileName, txtSheetName.Text);
currentExcelDataTable = ppe.ExcelProvider.GetDataTable();
gridSource.DataSource = currentExcelDataTable;
gridTarget.DataSource = null;


btnValidate.Enabled = true;
txtStatus.Text = "";
}
else
{
if (txtSheetName.Text == "")
{
MessageBox.Show("Please enter sheet name");
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}


Calling function
public List<string> GetPropertyType(int columnIndex)
{
List<string> propertyTypeList = new List<string>();

var propertyTypes =
(from e in ppe.ExcelProvider
where e.GetString(columnIndex).Trim() != ""
select e.GetString(columnIndex).Trim()).Distinct();

foreach (string pt in propertyTypes)
{
if (!propertyTypeList.Contains(pt))
{
propertyTypeList.Add(pt);
}
}

return propertyTypeList;
}


Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Collections;
using System.Data;

namespace ReplicatorServices
{
public class ExcelRow
{
List<object> columns;

public ExcelRow()
{
columns = new List<object>();
}

internal void AddColumn(object value)
{
columns.Add(value);
}

public object this[int index]
{
get { return columns[index]; }
}

public string GetString(int index)
{
if (columns[index] is DBNull)
{
return null;
}
return columns[index].ToString();
}

public int Count
{
get { return this.columns.Count; }
}
}

public class ExcelProvider:IEnumerable<ExcelRow>
{
private string sheet;
private string filePath;
private List<ExcelRow> rows;
private string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties= ""Excel 8.0;HDR=YES;""";

public ExcelProvider()
{
rows = new List<ExcelRow>();
}

public static ExcelProvider Create(string filePath, string sheet)
{
ExcelProvider provider = new ExcelProvider();
provider.sheet = sheet;
provider.filePath = filePath;
return provider;
}

public DataTable GetDataTable()
{
DataTable dt= new DataTable();
connectionString = string.Format(connectionString, filePath);
rows.Clear();
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select DISTINCT * from [" + sheet + "$] ";
using (OleDbDataReader reader = cmd.ExecuteReader())
{
dt.Load(reader);
}
}
}

return dt;
}

public DataTable GetDataTable(string sqlCommand)
{
DataTable dt = new DataTable();
connectionString = string.Format(connectionString, filePath);
rows.Clear();
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sqlCommand;
using (OleDbDataReader reader = cmd.ExecuteReader())
{
dt.Load(reader);
}
}
}

return dt;
}
public List<string> GetColumnsName()
{
List<string> columnlist = new List<string>();
connectionString = string.Format(connectionString, filePath);
rows.Clear();
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from [" + sheet + "$]";
using (OleDbDataReader reader = cmd.ExecuteReader())
{
for (int i = 0; i < reader.FieldCount; i++)
{
columnlist.Add(reader.GetName(i).Trim());
}
}
}
}

return columnlist;
}

private void Load()
{
connectionString = string.Format(connectionString, filePath);
rows.Clear();
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from [" + sheet + "$]";
using (OleDbDataReader reader = cmd.ExecuteReader())
{

while (reader.Read())
{
ExcelRow newRow = new ExcelRow();
for(int count = 0; count < reader.FieldCount; count++) {
newRow.AddColumn(reader[count]);
}
rows.Add(newRow);
}
}
}
}
}

public IEnumerator<ExcelRow> GetEnumerator()
{
Load();
return rows.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
Load();
return rows.GetEnumerator();
}

}
}

Get html tag using regex .net

Let say you want to get a specific tag from the html, you need to use regex to scan and grab it. here is the example :)


private string FixedImgHtml(string html, int fixedwidth)
{
string input = html;
MatchCollection mc = Regex.Matches(input, "<img[a-zA-Z0-9_\\^\\$\\.\\\\{\\[\\}\\]\\(\\)\\*\\+\\?\\\\~`!@#%&-=;:'\",/\\n\\s]*>", RegexOptions.IgnoreCase);
foreach (Match m in mc)
{
input = input.Replace(m.Value, m.Value + " onload='AutoImageResizing(this, "+ fixedwidth.ToString()+")'");
}
return input;
}

Friday, March 6, 2009

dynamic sql generated column using data

Sometimes we want dynamically create a column by using data and not having table structure. You can do it having this sql statement

select *, LFV1.Description as DevName,LFV2.Description as Location
from
listing L
LEFT OUTER JOIN ListingFieldValue LFV1 ON L.ListingID =
LFV1.ListingID AND LFV1.ListingFieldTypeID = '1'
LEFT OUTER JOIN
ListingFieldValue LFV2 ON L.ListingID = LFV2.ListingID AND
LFV2.ListingFieldTypeID = '2'
WHERE L.listingid = 1

Friday, February 27, 2009

using jquery to create check box for each item

if you want to create a check box each of the item with toggle functionality use this code snippet

<script type="text/javascript">
$(document).ready(function() {

$("#<%=btnSendEnquiryList.ClientID%>").click(function(event) {
var hasItemSelected = false;
$("#<%=dlNewDev.ClientID%> :checkbox").attr("checked", function() {
if ($(this).attr("checked") == true) {
hasItemSelected = true;
$(this).preventDefault();
} else {
hasItemSelected = false;
}
});


if (hasItemSelected == false) {
alert("There is no listing selected. Please select at least 1 listing.");
return false;
}
});

$("#<%=chkCheckedAll.ClientID%>").click(function() {
$("#<%=dlNewDev.ClientID%> :checkbox").attr("checked", function() {
if ($(this).attr("checked") != true) {
$(this).attr("checked", "checked")
} else {
$(this).removeAttr("checked")
}
});

});

});
</script>

set/get selected value from select option / dropdownlist using jquery

Here is an example of how to set/get selected value from select option / dropdownlist using jquery

To get a selected value

var selectedItemText = $('#<%=ddlCurrency.ClientID%>
option:selected').val();


To set an option value to be selected

$('#<%=ddlLocation.ClientID%> option:contains(' + location +
')').attr("selected", true);

Wednesday, February 25, 2009

Failed to load viewstate.

if you encounter this error


Failed to load viewstate. The control tree into which viewstate is being loaded
must match the control tree that was used to save viewstate during the previous
request. For example, when adding controls dynamically, the controls added
during a post-back


Make sure the related control is set to false

EnableViewState="false"



Create thumbnail image using jquery or javascript

If you want to maintain the proportion of the image when creating thumbnail for your website, please use this tested script

<script src="js/jquery-1.2.6.min.js"
type="text/javascript"></script>
<style
type="text/css">
.thumbnail
{
vertical-align:middle;
}
</style>
<script type="text/javascript" >
$(document).ready(
function AutoImageResizing(src, fixedSize) {
var
width = src.width;
var height = src.height;
var ratio = width / height;
if (width > fixedSize) {
src.width = fixedSize

}
if
(height > fixedSize) {
var sizedwidth = fixedSize / ratio;
var
sizedheight = fixedSize / ratio;
if (height > width) {
if (height
> sizedwidth) {
src.height = fixedSize
}
if (sizedwidth
> fixedSize) {
src.width = src.width * ratio;
} else {
src.height = src.height * ratio;
}
} else {
src.width =
fixedSize
}
}
}
);
</script>
HTML


<img class="thumbnail"
src="http://latimesblogs.latimes.com/photos/uncategorized/2008/10/05/love.jpg"
onload="AutoImageResizing(this,100)" />
<img class="thumbnail"
src="http://images.google.com.my/intl/en_ALL/images/images_hp.gif"
onload="AutoImageResizing(this,100)"/>



Do you find this useful, please let me know! :)

Tuesday, February 24, 2009

Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.

if you got this error dealing with XML


{"Namespace Manager or XsltContext needed. This query has a prefix, variable, or
user-defined function."}


You need to make sure that you include the XmlNamespaceManager

//Setting up NSManager
XmlNamespaceManager man = new XmlNamespaceManager(rssDoc.NameTable);
man.AddNamespace("msncp", "urn:schemas-microsoft-com/contentpublishing/content");

take a look at the example here
http://carso-owen.blogspot.com/2009/02/how-to-get-data-from-msn-navigation.html

string manipulation websites you must know as web designer or perhaps blogger

Some times some web editor doesn't allow you to post certain characters. Here u can hack it by encode the html
http://www.string-functions.com/htmlencode.aspx

You got a string put you want it a one line sentance, here is the best website to remote the breaks
http://www.textfixer.com/tools/remove-line-breaks.php

You u want to generate dummy text here is the
Lorem ipsum site
http://www.lipsum.com/

How to get data from msn navigation feed rss using .net

I have a project to develop a website for MSN and I have to read the feed (Microsoft own schema). Here is the code to save ur time :)



Let say i want to get a feed from this link

http://sg.msn.com/rss/navfeedrssensg.aspx



By using few lines of codes to get the feed:

MSNNavFeedMenu feedmenu = new
MSNNavFeedMenu("http://sg.msn.com/rss/navfeedrssensg.aspx");
string feedLinkMenu =
feedmenu.CreateNavLinks(feedmenu.GetNavLinks(4), 5);
string feedToolLinkMenu =
feedmenu.CreateNavToolLinks(feedmenu.GetNavToolLinks(), 5);


Here is the class:


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.Web.Security;
using System.Net;
using System.IO;
using System.Xml;
using System.Collections.Generic;


public class NavFeedRss
{

private string _Title;
private string _Link;
private string _Icon;
private string _Description;

public string Description
{
get
{
return _Description;
}
}

public string Title
{
get
{
return _Title;
}
}

public string Link
{
get
{
return _Link;
}
}

public string Icon
{
get
{
return _Icon;
}
}


public NavFeedRss(string title, string description, string link, string icon)
{
_Title = title;
_Link = link;
_Icon = icon;
_Title = title;
_Description = description;
}

}

/// <summary>
/// Summary description for MSNNavFeedMenu
/// </summary>
public class MSNNavFeedMenu
{
private string rssUrl;


public MSNNavFeedMenu(string rsslink)
{
rssUrl = rsslink;
}


public string CreateNavLinks(List<NavFeedRss> RssNavMenu, int columns)
{
string itemTitles = String.Empty;

if (RssNavMenu.Count > 0)
{
//Create list


//Create dynamic row with specified fixed column
int row = Convert.ToInt32(Math.Floor(Convert.ToDouble(RssNavMenu.Count / columns)));
int reminder = RssNavMenu.Count % columns;

int c = 0;
int temp = 0;
for (int r = 1; r <= row; r++)
{
itemTitles += "<ul class='linklist1'>";
for (c = temp; c < (columns * r); c++)
{
if (r == 1)
{
itemTitles += "<li class='first'>";
}
else
{
itemTitles += "<li>";
}

itemTitles += "<a href='" + RssNavMenu[c].Link + "'>" + RssNavMenu[c].Title + "</a>";
itemTitles += "</li>";

}
temp = columns * r;
itemTitles += "</ul>";
}


//Add reminder item
itemTitles += "<ul class='linklist1'>";

for (c = temp; c < temp + reminder; c++)
{
if (c == temp)
{
itemTitles += "<li class='first'>";
}
else
{
itemTitles += "<li>";
}

itemTitles += "<a href='" + RssNavMenu[c].Link + "'>" + RssNavMenu[c].Title + "</a>";
itemTitles += "</li>";
}
itemTitles += "</ul>";


//Closing list


}



return itemTitles;
}


public string CreateNavToolLinks(List<NavFeedRss> RssNavMenu, int columns)
{

string itemTitles = String.Empty;

if (RssNavMenu.Count > 0)
{

//Create dynamic row with specified fixed column
int row = Convert.ToInt32(Math.Floor(Convert.ToDouble(RssNavMenu.Count / columns)));
int reminder = RssNavMenu.Count % columns;

int c = 0;
int temp = 0;
for (int r = 1; r <= row; r++)
{
itemTitles += "<ul class='linkedimglinklist1 cf'>";
for (c = temp; c < (columns * r); c++)
{
if (r == 1)
{
itemTitles += "<li class='first'>";
}
else
{
itemTitles += "<li>";
}



itemTitles += "<a href='" + RssNavMenu[c].Link + "'><img src='" + RssNavMenu[c].Icon + "' width='25' height='20' alt='Windows Live Messenger' /><span><strong>" + RssNavMenu[c].Title + "</strong></span></a>";
itemTitles += "</li>";

}
temp = columns * r;
itemTitles += "</ul>";
}


//Add reminder item
itemTitles += "<ul class='linkedimglinklist1 cf'>";

for (c = temp; c < temp + reminder; c++)
{
if (c == temp)
{
itemTitles += "<li class='first'>";
}
else
{
itemTitles += "<li>";
}

itemTitles += "<a href='" + RssNavMenu[c].Link + "'><img src='" + RssNavMenu[c].Icon + "' width='25' height='20' alt='Windows Live Messenger' /><span><strong>" + RssNavMenu[c].Title + "</strong></span></a>";

itemTitles += "</li>";
}
itemTitles += "</ul>";


//Closing list


}



return itemTitles;
}

public List<NavFeedRss> GetNavToolLinks()
{

List<NavFeedRss> rsstitles = new List<NavFeedRss>();

WebRequest myRequest = WebRequest.Create(rssUrl);
WebResponse myResponse = myRequest.GetResponse();

Stream rssStream = myResponse.GetResponseStream();
XmlDocument rssDoc = new XmlDocument();
rssDoc.Load(rssStream);



//Setting up NSManager
XmlNamespaceManager man = new XmlNamespaceManager(rssDoc.NameTable);
man.AddNamespace("msncp", "urn:schemas-microsoft-com/contentpublishing/content");


XmlNodeList rssItemsImg = rssDoc.SelectNodes("rss/channel/msncp:gtl/msncp:networklists/msncp:toollist/msncp:tool/msncp:imagelink/msncp:image", man);
XmlNodeList rssItemsLnk = rssDoc.SelectNodes("rss/channel/msncp:gtl/msncp:networklists/msncp:toollist/msncp:tool/msncp:imagelink/msncp:link", man);


string title = "";
string link = "";
string description = "";
string enclosure = "";




for (int i = 0; i < rssItemsLnk.Count; i++)
{
XmlNode rssDetail;


rssDetail = rssItemsImg.Item(i).SelectSingleNode("msncp:src", man);
if (rssDetail != null)
{
enclosure = rssDetail.InnerText;
}
else
{
enclosure = "";
}



rssDetail = rssItemsImg.Item(i).SelectSingleNode("msncp:alternatetext", man);
if (rssDetail != null)
{
description = rssDetail.InnerText;
}
else
{
description = "";
}



rssDetail = rssItemsLnk.Item(i).SelectSingleNode("msncp:text", man);
if (rssDetail != null)
{
title = rssDetail.InnerText;
}
else
{
title = "";
}


rssDetail = rssItemsLnk.Item(i).SelectSingleNode("msncp:url", man);
if (rssDetail != null)
{
link = rssDetail.InnerText;
}
else
{
link = "";
}

rsstitles.Add(new NavFeedRss(title, description, link, enclosure));

}





return rsstitles;
}


public List<NavFeedRss> GetNavLinks(int start)
{

List<NavFeedRss> rsstitles = new List<NavFeedRss>();

WebRequest myRequest = WebRequest.Create(rssUrl);
WebResponse myResponse = myRequest.GetResponse();

Stream rssStream = myResponse.GetResponseStream();
XmlDocument rssDoc = new XmlDocument();
rssDoc.Load(rssStream);

XmlNodeList rssItems = rssDoc.SelectNodes("rss/channel/item");

string title = "";
string link = "";
string description = "";
string enclosure = "";

for (int i = start; i < rssItems.Count; i++)
{
XmlNode rssDetail;

rssDetail = rssItems.Item(i).SelectSingleNode("title");
if (rssDetail != null)
{
title = rssDetail.InnerText;
}
else
{
title = "";
}

rssDetail = rssItems.Item(i).SelectSingleNode("enclosure");
if (rssDetail != null)
{
enclosure = rssDetail.Attributes["url"].InnerText;
}
else
{
enclosure = "";
}


rssDetail = rssItems.Item(i).SelectSingleNode("link");
if (rssDetail != null)
{
link = rssDetail.InnerText;
}
else
{
link = "";
}

rssDetail = rssItems.Item(i).SelectSingleNode("description");
if (rssDetail != null)
{
description = rssDetail.InnerText;
}
else
{
description = "";
}


rsstitles.Add(new NavFeedRss(title, description, link, enclosure));

}

return rsstitles;
}

}

Sunday, February 22, 2009

using store procedure is not my style in .net

During the past I am quite excited about using store procedure and I used it quite often for some performance reason and right now I found out that performance gain is a big trade off of the code maintainability and flexibility in my system. The reason I say so is because when i want to perform a select statement for instance, I need to create a new store procedure and over the time I have a hard time to maintain it. Actually, putting SQL statements inside application code is far more better than having storing store procedure over the server. Just think about by concatenate sql in a string with some condition and forget about store procedure which create so much complication. What do you think? Is life more simpler?

Friday, February 20, 2009

jquery get and set value dealing with asp.net control

this demo show that how I get value from the lblSearchType (Label) and populate data into txtKeyword (TextBox) asp.net control when I click different radio button using jquery

$('#<%=rdKeywordSearch.ClientID%>').click(function() {
$('#<%=lblSearchType.ClientID%>').text("Keyword");
$('#<%=txtKeyword.ClientID%>_input').attr("value", "Keyword");
$('#<%=txtKeyword.ClientID%>_input').attr("value", "Enter keyword here...");
});

$('#<%=rdLocationSearch.ClientID%>').click(function() {
$('#<%=lblSearchType.ClientID%>').text("Location");
$('#<%=txtKeyword.ClientID%>_input').attr("value", "Location");
$('#<%=txtKeyword.ClientID%>_input').attr("value", "Enter location here...");
});

Wednesday, February 18, 2009

Resize picture function in C#


using System.Drawing;
using System.Drawing.Drawing2D;

//w means the output size of the image width


public static bool ResizePhoto(string src, string dest, int w)
{
System.Drawing.Image imgTmp = default(System.Drawing.Image);
double sf = 0;
System.Drawing.Bitmap imgFoto = default(System.Drawing.Bitmap);
imgTmp = System.Drawing.Image.FromFile(src);
if ((imgTmp.Width > w))
{
sf = imgTmp.Width / w;
imgFoto = new System.Drawing.Bitmap(w, (int)(imgTmp.Height / sf));
Rectangle recDest = new Rectangle(0, 0, w, imgFoto.Height);
Graphics gphCrop = Graphics.FromImage(imgFoto);
gphCrop.SmoothingMode = SmoothingMode.HighQuality;
gphCrop.CompositingQuality = CompositingQuality.HighQuality;
gphCrop.InterpolationMode = InterpolationMode.High;
gphCrop.DrawImage(imgTmp, recDest, 0, 0, imgTmp.Width, imgTmp.Height, GraphicsUnit.Pixel);
}
else
{
imgFoto = (Bitmap)imgTmp;
}
System.Drawing.Imaging.Encoder myEncoder = default(System.Drawing.Imaging.Encoder);
System.Drawing.Imaging.EncoderParameter myEncoderParameter = default(System.Drawing.Imaging.EncoderParameter);
System.Drawing.Imaging.EncoderParameters myEncoderParameters = default(System.Drawing.Imaging.EncoderParameters);
System.Drawing.Imaging.ImageCodecInfo[] arrayICI = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
System.Drawing.Imaging.ImageCodecInfo jpegICI = null;
int x = 0;
for (x = 0; x <= arrayICI.Length - 1; x++)
{
if ((arrayICI[x].FormatDescription.Equals("JPEG")))
{
jpegICI = arrayICI[x];
break;
}
}
myEncoder = System.Drawing.Imaging.Encoder.Quality;
myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(myEncoder, 60L);
myEncoderParameters.Param[0] = myEncoderParameter;
try
{
imgFoto.Save(dest, jpegICI, myEncoderParameters);
}
catch (Exception ex)
{
throw ex;
}
imgFoto.Dispose();
imgTmp.Dispose();
return true;
}

Tuesday, February 17, 2009

ajax json jquery call with passing parameters using ASP.Net

If you want to load a content faster than before, you need to use ajax to load content. To get started you need to:

HTML

<div id="EventContent" class="loading"/>

SCRIPT


$.ajax({
type: "POST",
url: "RSSReader.asmx/GetRSSReader",
data:
"{controlName:'events.ascx'}",
contentType: "application/json;
charset=utf-8",
dataType: "json",
success: function(data)
{
$('#EventContent').removeClass('loading').html(data);
}
});



APP_CODE

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo
=
WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public
class RSSReader : System.Web.Services.WebService {
[WebMethod]
public
string GetRSSReader(string controlName)
{
Page page = new
Page();
UserControl ctl =
(UserControl)page.LoadControl("~/controls/" +
controlName);
page.Controls.Add(ctl);
StringWriter writer = new
StringWriter();
HttpContext.Current.Server.Execute(page, writer,
false);
return writer.ToString();
}

}



Notice that the bold text is the parameter name and it have to be same. It is recommended to be string

Wednesday, January 14, 2009

check string contains chinese character or not in C#

string word = "是集室內";


char fo = word[0];

UnicodeCategory cat = char.GetUnicodeCategory(fo);
if (cat == UnicodeCategory.OtherLetter)
{
//chinese char
}
else
{
//english char
}