C# - XPathNavigator class to navigate XML
Tuesday, December 29, 2009
Wednesday, December 16, 2009
Saturday, December 12, 2009
Visual Studio - Import and Export Settings
As you know we can customizing the IDE in Visual Studio, if you change the place of toolbox, properties window, server explorer, or some other features, you can save your setting to keep it for later and if you need to move to another machine or setting back to this point either if you changed something more and you didn't like it, just simply bring it back to your saved settings.
General settings, Browsers, Start page commands, Toolbox, help filters, options, and ... are all customizable and possible to save them all and assign a name to this set.
On the other hand, we can reload pre saved settings,
Good naming for saved settings will help a lot at this point
And at last we can reset all the customized settings to default state.
This feature is very useful but somehow hidden, customizing the environment will hep your productivity, then just using it and make it work the way you want it.
General settings, Browsers, Start page commands, Toolbox, help filters, options, and ... are all customizable and possible to save them all and assign a name to this set.
On the other hand, we can reload pre saved settings,
Good naming for saved settings will help a lot at this point
And at last we can reset all the customized settings to default state.
This feature is very useful but somehow hidden, customizing the environment will hep your productivity, then just using it and make it work the way you want it.
Visual Studio - Import and Export Settings
Friday, December 11, 2009
Wednesday, November 18, 2009
Silverlight 4 Beta - developer release
http://silverlight.net/getstarted/silverlight-4-beta/
"This latest version delivers hundreds of features and controls that, when combined with the continued innovation in Microsoft’s world-class tools for designers and developers — Microsoft Visual Studio and Microsoft Expression Blend – present the leading edge in rapid, powerful application development. With printing support, rich reporting and charting, and integration with back-end systems and server products including Microsoft SharePoint, Silverlight is ready for business."
"IMPORTANT DEVELOPER NOTE:
Visual Studio 2010 can be installed side-by-side with Visual Studio 2008 SP1. For Silverlight 4 development, you will need Visual Studio 2010. Please read the known issue on installing Visual Studio 2010 if you already have the Silverlight 3 SDK installed."
Videos and Samples
http://silverlight.net/learn/videos/silverlight-4-beta-videos/
"This latest version delivers hundreds of features and controls that, when combined with the continued innovation in Microsoft’s world-class tools for designers and developers — Microsoft Visual Studio and Microsoft Expression Blend – present the leading edge in rapid, powerful application development. With printing support, rich reporting and charting, and integration with back-end systems and server products including Microsoft SharePoint, Silverlight is ready for business."
"IMPORTANT DEVELOPER NOTE:
Visual Studio 2010 can be installed side-by-side with Visual Studio 2008 SP1. For Silverlight 4 development, you will need Visual Studio 2010. Please read the known issue on installing Visual Studio 2010 if you already have the Silverlight 3 SDK installed."
Videos and Samples
http://silverlight.net/learn/videos/silverlight-4-beta-videos/
Silverlight 4 Beta - developer release
Sunday, November 8, 2009
T-SQL - NULL does not equal NULL
Be careful of this when coding. NULL does not equal NULL, you can test it with following code, weird? No! because NULL does not present a value to be able to be equal to another value!
IF (NULL=NULL)
PRINT 'NULL is equal to NULL'
ELSE
PRINT 'NULL is not equal to NULL !'
IF (NULL=NULL)
PRINT 'NULL is equal to NULL'
ELSE
PRINT 'NULL is not equal to NULL !'
T-SQL - NULL does not equal NULL
Saturday, November 7, 2009
T-SQL - Aggregate functions and NULL values in numeric fields
Except COUNT(*), all other aggregate functions ignore NULLs. As an example if you have NULL value in a numeric field, the NULL value does not equal to zero. Look at the following code, it shows the AVG function ignores the records which their specific column has NULL value.
CREATE TABLE theTable
(
theId int IDENTITY NOT NULL,
theValue DECIMAL(10,2) NULL
)
INSERT INTO theTable
(theValue)
VALUES
(NULL), (0), (1), (2), (3), (NULL)
SELECT AVG(theValue) as AverageValue
FROM theTable
The result is 1.500000
It's important when you want to design your database and tables, because it will affect the queries result when you run them against the database.
On the other hand, it's possible to consider COALESCE function (http://msdn.microsoft.com/en-us/library/ms190349.aspx), it gives you a chance to select first non NULL expression among its arguments. Then you can send multiple field names and let the COALESCE find the first non NULL value for your aggregate function, it can be happen if you have alternative field but it's tricky and depends on business rules in your application.
CREATE TABLE theTable
(
theId int IDENTITY NOT NULL,
theValue DECIMAL(10,2) NULL
)
INSERT INTO theTable
(theValue)
VALUES
(NULL), (0), (1), (2), (3), (NULL)
SELECT AVG(theValue) as AverageValue
FROM theTable
The result is 1.500000
It's important when you want to design your database and tables, because it will affect the queries result when you run them against the database.
On the other hand, it's possible to consider COALESCE function (http://msdn.microsoft.com/en-us/library/ms190349.aspx), it gives you a chance to select first non NULL expression among its arguments. Then you can send multiple field names and let the COALESCE find the first non NULL value for your aggregate function, it can be happen if you have alternative field but it's tricky and depends on business rules in your application.
T-SQL - Aggregate functions and NULL values in numeric fields
Monday, October 26, 2009
ASP.NET - CSS ID selector vs. CSS class for custom server controls
To have a common use control, we do create custom ASP.NET server controls.
As a simple example let's have a side bar control. To do that, Add a Web User Control, it has .ascx extention and call it sideBarList.
<%@ Control Language="C#" AutoEventWireup="true"
CodeBehind="sideBarList.ascx.cs"
Inherits="AspAdvWrk01.sideBarList" %>
<asp:Panel ID="srchEnginePnl" runat="server">
<h4>Search Engines:</h4>
<a href="http://www.bing.com/">bing</a><br />
<a href="http://www.google.ca/">Google</a><br />
<a href="http://m.www.yahoo.com/">Yahoo</a><br />
<a href="http://www.msn.com/">MSN</a><br />
<a href="http://www.altavista.com/">Altavista</a>
</asp:Panel>
Then let's add the following CSS codes in a style sheet:
#srchEnginePnl
{
border-style:dotted;
border-width:1px;
padding: 5px;
font-size:small;
}
I tried the same ID name of asp Panel control in this style sheet as a CSS ID selector, To apply style to the asp Panel control with ID name of srchEnginePnl. Even though that we have CSS ID selector but it doesn't apply any style because the real ID name in HTML page is something else which you can find it by checking the html source of the page in your browser (in the test page it was #ctl00_ContentPlaceHolder1_sideBarList1_srchEnginePnl).
The solution, a CSS class selector and utilizing CssClass attribute as following:
.srchEnginePnl
{
border-style:dotted;
border-width:1px;
padding: 5px;
font-size:small;
}
a.srchEnginePnl
{
padding: 10px;
}
...
<asp:Panel ID="srchEnginePnl" CssClass="srchEnginePnl" runat="server">
...
otherwise you have to use the real ID of your panel control in html source and use that ID name to define the ID CSS selector in your style sheet:
#ctl00_ContentPlaceHolder1_sideBarList1_srchEnginePnl
{
border-style:dotted;
border-width:1px;
padding: 5px;
font-size:small;
}
...
<asp:Panel ID="srchEnginePnl" runat="server">
...
As a simple example let's have a side bar control. To do that, Add a Web User Control, it has .ascx extention and call it sideBarList.
<%@ Control Language="C#" AutoEventWireup="true"
CodeBehind="sideBarList.ascx.cs"
Inherits="AspAdvWrk01.sideBarList" %>
<asp:Panel ID="srchEnginePnl" runat="server">
<h4>Search Engines:</h4>
<a href="http://www.bing.com/">bing</a><br />
<a href="http://www.google.ca/">Google</a><br />
<a href="http://m.www.yahoo.com/">Yahoo</a><br />
<a href="http://www.msn.com/">MSN</a><br />
<a href="http://www.altavista.com/">Altavista</a>
</asp:Panel>
Then let's add the following CSS codes in a style sheet:
#srchEnginePnl
{
border-style:dotted;
border-width:1px;
padding: 5px;
font-size:small;
}
I tried the same ID name of asp Panel control in this style sheet as a CSS ID selector, To apply style to the asp Panel control with ID name of srchEnginePnl. Even though that we have CSS ID selector but it doesn't apply any style because the real ID name in HTML page is something else which you can find it by checking the html source of the page in your browser (in the test page it was #ctl00_ContentPlaceHolder1_sideBarList1_srchEnginePnl).
The solution, a CSS class selector and utilizing CssClass attribute as following:
.srchEnginePnl
{
border-style:dotted;
border-width:1px;
padding: 5px;
font-size:small;
}
a.srchEnginePnl
{
padding: 10px;
}
...
<asp:Panel ID="srchEnginePnl" CssClass="srchEnginePnl" runat="server">
...
otherwise you have to use the real ID of your panel control in html source and use that ID name to define the ID CSS selector in your style sheet:
#ctl00_ContentPlaceHolder1_sideBarList1_srchEnginePnl
{
border-style:dotted;
border-width:1px;
padding: 5px;
font-size:small;
}
...
<asp:Panel ID="srchEnginePnl" runat="server">
...
ASP.NET - CSS ID selector vs. CSS class for custom server controls
Sunday, October 25, 2009
Visual Studio 2010 and .NET Framework 4 Training Course
Links to new Interview videos and How Do I clips and new posts about Visual Studio 2010 Beta2 in Channel 9.
http://channel9.msdn.com/learn/courses/VS2010/
"The Visual Studio 2010 and .NET Framework 4 Training Course includes videos and hands-on-labs designed to help you learn how to utilize the Visual Studio 2010 features and a variety of framework technologies including:
- C# 4.0
- Visual Basic 10
- F#
- Parallel Computing Platform
- WCF
- WF
- WPF
- ASP.NET AJAX 4.0
- ASP.NET MVC Dynamic Data."
Visual Studio 2010 and .NET Framework 4 Training Course
Tuesday, October 20, 2009
Visual Studio 2010 and .NET Framework 4 Beta 2
The Visual Studio 2010 and .NET Framework Beta 2 is available to MSDN subscribers on Monday, October 19th. Visual Studio 2010 Beta 2 and Dot Net framework 4 Beta 2 will be made available to the general public on 21st October. Users will be able to get their hands on the final version of Visual Studio 2010 on 22nd March 2010.
http://msdn.microsoft.com/en-us/vstudio/dd582936.aspx
Visual Studio 2010 and .NET Framework 4 Beta 2 Walkthroughs
http://msdn.microsoft.com/en-us/vstudio/dd441784.aspx
Testers to get Visual Studio 2010 Beta 2 this week; final by March 2010
http://blogs.zdnet.com/microsoft/?p=4270&tag=content;col1
Other links:
Microsoft names Visual Studio 2010 dates
http://www.theregister.co.uk/2009/10/19/visual_studio_2010_second_beta_packaging/
http://msdn.microsoft.com/en-us/vstudio/default.aspx
http://www.microsoft.com/visualstudio/en-us/products/2010/default.mspx
Visual Studio 2010 and .NET Framework 4 Beta 2
Sunday, October 11, 2009
Visual Studio - An error occurred loading this property page
If you found out that the "Design, Split, Source" buttons are not available anymore, your first reaction would be to take a look at Tools->Options->HTML Designer, at this point probably you encounter with this error message:
"An error occurred loading this property page"
I encountered with the error and it was resolved by running "devenv /setup" in Visual Studio 2008 Command Prompt and restarting Visual Studio. The "Design, Split, Source" buttons came back to the right place after running that command.
"An error occurred loading this property page"
I encountered with the error and it was resolved by running "devenv /setup" in Visual Studio 2008 Command Prompt and restarting Visual Studio. The "Design, Split, Source" buttons came back to the right place after running that command.
Visual Studio - An error occurred loading this property page
Saturday, October 10, 2009
ASP.NET - Image handler to fetch and show Images from varbinary(MAX)
Imagine you want to get images from [Production].[ProductProductPhoto] table in AdventureWorks SQL sample database. The following code can be in a generic handler (.ashx) file.
public class ImgHandler : IHttpHandler
{
private string sqlCnStr =
ConfigurationManager.ConnectionStrings["CnStrAdvWrk"].ConnectionString;
public void ProcessRequest(HttpContext context)
{
string productId = context.Request.QueryString["PrdId"];
if (string.IsNullOrEmpty(productId))
productId = "1";
using (SqlConnection sqlCn = new SqlConnection(sqlCnStr))
{
StringBuilder cmd = new StringBuilder();
cmd.Append("SELECT PrdPhoto.[ThumbNailPhoto] as PrdPhoto ");
cmd.Append(" FROM [Production].[Product] as Prd ");
cmd.Append(" JOIN [Production].[ProductProductPhoto] as PPrdPhoto ");
cmd.Append(" ON Prd.ProductID = PrdPrdPhoto.ProductID ");
cmd.Append(" JOIN [Production].[ProductPhoto] as PPhoto ");
cmd.Append(" ON PPrdPhoto.ProductPhotoID = PPhoto.ProductPhotoID ");
cmd.Append(" WHERE Prd.[ProductID] = " + productId);
sqlCn.Open();
SqlCommand sqlCmd = new SqlCommand(cmd.ToString(), sqlCn);
SqlDataReader sqlDtaRdr = sqlCmd.ExecuteReader();
sqlDtaRdr.Read();
context.Response.BinaryWrite( (byte[]) sqlDtaRdr[0] );
sqlCn.Close();
context.Response.End();
}
}
public bool IsReusable
{
get { return false; }
}
}
Now you just need to call the handler.
If you have an image control and you know the ProductId:
<asp:Image ID="Image1" runat="server"
ImageUrl="~/ImgHandler.ashx?PrdId=1" />
or if you have a GridView and you want to have a column with product images, then you can use TemplateField with and Image control inside the ItemTemplate:
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server"
ImageUrl='<%# "ImgHandler.ashx?PrdId=" + Eval("PrdId") %>' />'
</ItemTemplate>
</asp:TemplateField>
public class ImgHandler : IHttpHandler
{
private string sqlCnStr =
ConfigurationManager.ConnectionStrings["CnStrAdvWrk"].ConnectionString;
public void ProcessRequest(HttpContext context)
{
string productId = context.Request.QueryString["PrdId"];
if (string.IsNullOrEmpty(productId))
productId = "1";
using (SqlConnection sqlCn = new SqlConnection(sqlCnStr))
{
StringBuilder cmd = new StringBuilder();
cmd.Append("SELECT PrdPhoto.[ThumbNailPhoto] as PrdPhoto ");
cmd.Append(" FROM [Production].[Product] as Prd ");
cmd.Append(" JOIN [Production].[ProductProductPhoto] as PPrdPhoto ");
cmd.Append(" ON Prd.ProductID = PrdPrdPhoto.ProductID ");
cmd.Append(" JOIN [Production].[ProductPhoto] as PPhoto ");
cmd.Append(" ON PPrdPhoto.ProductPhotoID = PPhoto.ProductPhotoID ");
cmd.Append(" WHERE Prd.[ProductID] = " + productId);
sqlCn.Open();
SqlCommand sqlCmd = new SqlCommand(cmd.ToString(), sqlCn);
SqlDataReader sqlDtaRdr = sqlCmd.ExecuteReader();
sqlDtaRdr.Read();
context.Response.BinaryWrite( (byte[]) sqlDtaRdr[0] );
sqlCn.Close();
context.Response.End();
}
}
public bool IsReusable
{
get { return false; }
}
}
Now you just need to call the handler.
If you have an image control and you know the ProductId:
<asp:Image ID="Image1" runat="server"
ImageUrl="~/ImgHandler.ashx?PrdId=1" />
or if you have a GridView and you want to have a column with product images, then you can use TemplateField with and Image control inside the ItemTemplate:
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server"
ImageUrl='<%# "ImgHandler.ashx?PrdId=" + Eval("PrdId") %>' />'
</ItemTemplate>
</asp:TemplateField>
ASP.NET - Image handler to fetch and show Images from varbinary(MAX)
Wednesday, October 7, 2009
Error 2738 - during installation of Adventure Works sample databases on Vista
Well, I downloaded Adventure Works sample databases from the here
but I encountered with error 2738 during installation.
I found the solution by a post in Mitch Denny blog:
http://notgartner.wordpress.com/2008/07/12/the-error-code-is-2738/
In brief the solution was to register VBSCRIPT.DLL on Vista which is not registered by default.
- Run "Command Prompt" as administrator
- Switch to "C:\WINDOWS\SysWOW64"
- Execute "REGSVR32.EXE VBSCRIPT.DLL"
but I encountered with error 2738 during installation.
I found the solution by a post in Mitch Denny blog:
http://notgartner.wordpress.com/2008/07/12/the-error-code-is-2738/
In brief the solution was to register VBSCRIPT.DLL on Vista which is not registered by default.
- Run "Command Prompt" as administrator
- Switch to "C:\WINDOWS\SysWOW64"
- Execute "REGSVR32.EXE VBSCRIPT.DLL"
Error 2738 - during installation of Adventure Works sample databases on Vista
Tuesday, October 6, 2009
ASP.NET - Do you need a GridView with scroll bars?
Sunday, September 20, 2009
CSS - height loose when all elements are float in a <div> block
When all the elements in a <div> block are float, Firefox can't keep the height of block, in this example the border appears just on top side:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<title>height loose</title>
</head>
<body>
<div style="margin:auto;width:350px;border:5px solid #CCC;">
<img style="float:left;margin-top:0.5em" src="Design.jpg" />
<span style="float:right;margin-top:1em; margin-right:0.5em">
<b>Development</b>
</span>
</div>
</body>
</html>
To solve the problem, it's necessary to explicitly set the height of block and it's better to use em for height size unit cuz of covering different font size of contents:
<style type="text/css">
#hdr {
height: 4em;
}
</style>
<div id="hdr" style="margin:auto;width:350px;border:5px solid #CCC;">
...
</div>
IE doesn't show such a behavior, it's yet another place that coder should consider cross browser development techniques.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<title>height loose</title>
</head>
<body>
<div style="margin:auto;width:350px;border:5px solid #CCC;">
<img style="float:left;margin-top:0.5em" src="Design.jpg" />
<span style="float:right;margin-top:1em; margin-right:0.5em">
<b>Development</b>
</span>
</div>
</body>
</html>
To solve the problem, it's necessary to explicitly set the height of block and it's better to use em for height size unit cuz of covering different font size of contents:
<style type="text/css">
#hdr {
height: 4em;
}
</style>
<div id="hdr" style="margin:auto;width:350px;border:5px solid #CCC;">
...
</div>
IE doesn't show such a behavior, it's yet another place that coder should consider cross browser development techniques.
CSS - height loose when all elements are float in a <div> block
Saturday, September 19, 2009
ASP.NET - URL Mapping in Web.config
The URL mapping feature uses configuration information stored in web.config to remap incoming requests to a different URL. The remapping occurs prior to any other processing for the inbound request. Although the sample below demonstrates remapping a page request, any arbitrary file type can have its request remapped to a different URL.
Imagine some body kept the URL of your web site in their bookmarks and you want to change the pages and structure of your site so that it affects the URLs, then you need to redirect the old ones to new correct destination, it works if you consider URL mapping.
The URL mapping feature uses to redirect incoming requests to a different URL. Prior to any other processing for the incoming request the remapping happens.
URL Mapping stores in web.config file, inside <system.web> tag, it's possible to add elements in <urlMappings>. In <add> tag there is url attribute which points to exact value of incoming url and mappedUrl attribute keeps value of rewritten url which is the exact redirected destination.
<configuration>
<system.web>
<urlMappings>
<add url="~/LCDs.aspx" mappedUrl="~/prds.aspx?prdCat=lcd" />
<add url="~/DVDs.aspx" mappedUrl="~/prds.aspx?prdCat=dvd" />
<add url="~/MP3s.aspx" mappedUrl="~/prds.aspx?prdCat=mp3" />
</urlMappings>
</system.web>
</configuration>
With URL mapping, the redirection works the same as the Server.Transfer() method, and browser will still show the original incoming request URL, not the mapped URL.
The Request.RawUrl property returns the original request URL.
The Request.Path property reflects the result of mapped URL.
Request.QueryString["yourQueryStringElement"] also return the result from the mapped URL.
If we have a site map provider in our web page, it first try to use the original request URL when looking for the node in the site map which is provided by Request.RawUrl, if it doesn't find the matched record, it uses the Request.Path property.
Incomming Request --->
Mapping available in Web.config?
--- YES ---> Use mappedUrl path --->
[Render requested path]
--- NO --------------------------------->
Imagine some body kept the URL of your web site in their bookmarks and you want to change the pages and structure of your site so that it affects the URLs, then you need to redirect the old ones to new correct destination, it works if you consider URL mapping.
The URL mapping feature uses to redirect incoming requests to a different URL. Prior to any other processing for the incoming request the remapping happens.
URL Mapping stores in web.config file, inside <system.web> tag, it's possible to add elements in <urlMappings>. In <add> tag there is url attribute which points to exact value of incoming url and mappedUrl attribute keeps value of rewritten url which is the exact redirected destination.
<configuration>
<system.web>
<urlMappings>
<add url="~/LCDs.aspx" mappedUrl="~/prds.aspx?prdCat=lcd" />
<add url="~/DVDs.aspx" mappedUrl="~/prds.aspx?prdCat=dvd" />
<add url="~/MP3s.aspx" mappedUrl="~/prds.aspx?prdCat=mp3" />
</urlMappings>
</system.web>
</configuration>
With URL mapping, the redirection works the same as the Server.Transfer() method, and browser will still show the original incoming request URL, not the mapped URL.
The Request.RawUrl property returns the original request URL.
The Request.Path property reflects the result of mapped URL.
Request.QueryString["yourQueryStringElement"] also return the result from the mapped URL.
If we have a site map provider in our web page, it first try to use the original request URL when looking for the node in the site map which is provided by Request.RawUrl, if it doesn't find the matched record, it uses the Request.Path property.
Incomming Request --->
Mapping available in Web.config?
--- YES ---> Use mappedUrl path --->
[Render requested path]
--- NO --------------------------------->
ASP.NET - URL Mapping in Web.config
Thursday, September 17, 2009
Free Web Hosting - Web Hosting Company Reviews
Free Web Hosting list by ABOUT.com
Web Hosting Company Reviews
The data is based on reviews by people who have used the web hosting services from the hosting companies.
Web Hosting Company Reviews
The data is based on reviews by people who have used the web hosting services from the hosting companies.
Free Web Hosting - Web Hosting Company Reviews
10 Best and Worst Web Hosting Providers!
Something interesting from ABOUT.com, at least it worth to take a look at the following lists, I don't want to say that I'm agree or disagree with the result which ABOUT.com collected, it's just interesting.
10 Best Web Hosting Providers
As Rated by About.com Readers
10 Worst Web Hosting Providers
As Rated by About.com Readers
Last updated 21 April 2009
10 Best Web Hosting Providers
As Rated by About.com Readers
10 Worst Web Hosting Providers
As Rated by About.com Readers
Last updated 21 April 2009
10 Best and Worst Web Hosting Providers!
Friday, September 11, 2009
ASP.NET - EventLog Class - Custom logs
It's a good idea to log errors and unexpected conditions in event log. But if you want to record user actions or other data which repeats a lot and consume considerable amount of space, the Event Log is not a good choice and may be it's better to log it in database tables or XML files, because Event log uses disk space and takes processor time and it will affect overall performance of machine and our application.
EventLog class in System.Diagnostics namespace allows us to utilize related functions in .NET, on the other hand, it's a good practice to make a custom errors log and record messages related to our application there. Then Event Viewer will collect messages in an individual place which allows us to keep track of them easily. the following sample code implements custom event logging idea.
try
{
// ...
// you code here
// ...
}
catch (Exception ex)
{
string logName = "myWebAppEventLog";
if (!EventLog.SourceExists(logName))
{
EventSourceCreationData escd =
new EventSourceCreationData("myWebAppSrc", logName);
escd.MachineName = System.Environment.MachineName;
EventLog.CreateEventSource(escd);
}
EventLog evntLog = new EventLog(logName);
evntLog.Source = "myWebApp";
evntLog.WriteEntry(ex.Message, EventLogEntryType.Error);
}
{
// ...
// you code here
// ...
}
catch (Exception ex)
{
string logName = "myWebAppEventLog";
if (!EventLog.SourceExists(logName))
{
EventSourceCreationData escd =
new EventSourceCreationData("myWebAppSrc", logName);
escd.MachineName = System.Environment.MachineName;
EventLog.CreateEventSource(escd);
}
EventLog evntLog = new EventLog(logName);
evntLog.Source = "myWebApp";
evntLog.WriteEntry(ex.Message, EventLogEntryType.Error);
}
To find more you can take a look at following URLs and or search online.
- EventLog Class
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog%28VS.71%29.aspx
- How to manage event logs using Visual C# .NET or Visual C# 2005
http://support.microsoft.com/kb/815314
- Security Ramifications of Event Logs
http://msdn.microsoft.com/en-us/library/4xz6w79h%28VS.71%29.aspx
ASP.NET - EventLog Class - Custom logs
Thursday, September 3, 2009
TypeDescriptor.GetConverter - unified way of converting types of values to other types
...
string[] brdrStyleAry = Enum.GetNames(typeof(BorderStyle));
rbtnBrdr.DataSource = brdrStyleAry;
rbtnBrdr.DataBind();
...
TypeConverter objCnvrtr =
TypeDescriptor.GetConverter(typeof(BorderStyle));
pnlCard.BorderStyle =
(BorderStyle) objCnvrtr.ConvertFromString(rbtnBrdr.SelectedItem.Text);
string[] brdrStyleAry = Enum.GetNames(typeof(BorderStyle));
rbtnBrdr.DataSource = brdrStyleAry;
rbtnBrdr.DataBind();
...
TypeConverter objCnvrtr =
TypeDescriptor.GetConverter(typeof(BorderStyle));
pnlCard.BorderStyle =
(BorderStyle) objCnvrtr.ConvertFromString(rbtnBrdr.SelectedItem.Text);
TypeDescriptor.GetConverter - unified way of converting types of values to other types
Tuesday, August 25, 2009
Partitioning utility - EASEUS Partition Master Home Edition (FREE)
"EASEUS Partition Master Home Edition is a FREE disk partitioning utility for extending system partition, better disk space management, settling low disk space problem under Windows 2000/XP/Vista"
http://www.partition-tool.com/personal.htm
Overview:
* Extend system partition to maximize computer performance.
* Main features for better managing hard disk and maximizing computer performance.
* Copy wizard to backup all data or copy entire hard disk to another without Windows reinstallation.
* Usability features allow you to operate directly on the disk map with the drag-and-drop and preview the changes.
Main Features:
* Resize/Move partitions without data loss
* Extend system partition easily and safely
* Create, Delete and Format partitions with simple steps
* Support up to 2TB partition or hard drive
* Disk Copy, Partition Copy, Dynamic Disk Copy to protect or transfer da
Partitioning utility - EASEUS Partition Master Home Edition (FREE)
Monday, August 17, 2009
SQL - How to rename a DATABASE physically in MS SQL Server 2008
As you know sp_renamedb stored procedure does not rename the database data files. I prefer to have the database data files contain a matching database name. If I have a database named [myDataBase], then the data files would typically be myDataBase.mdf and myDataBase_Log.ldf, simple and neat. In this way, just with take a look at the files, I can remember which SQL database they are talking about. Otherwise it's confusing.
SQL 2008 allows us to rename a database using T-SQL and the sp_renamedb stored procedure has been deprecated. ALTER DATABASE can do the job for us.
You can code as following to do the job:
1- Change your database name:
2- Rename master data file (.mdf):
3- Rename log file:
4- Assign new full path file name to renamed master data file:
5- Assign new full path file name to renamed log file:
6- Now you need to take the database offline (Tasks->Take Offline) and bring it back online (Tasks->Bring Online), then you don't need to detach and attach your database again.
SQL 2008 allows us to rename a database using T-SQL and the sp_renamedb stored procedure has been deprecated. ALTER DATABASE can do the job for us.
You can code as following to do the job:
1- Change your database name:
ALTER DATABASE oldDataBase
MODIFY NAME = newDataBase
GO
MODIFY NAME = newDataBase
GO
2- Rename master data file (.mdf):
ALTER DATABASE AutoMac
MODIFY FILE(NAME = 'oldDataBase', NEWNAME = 'newDataBase' )
GO
MODIFY FILE(NAME = 'oldDataBase', NEWNAME = 'newDataBase' )
GO
3- Rename log file:
ALTER DATABASE AutoMac
MODIFY FILE(NAME = 'oldDataBase_Log', NEWNAME = 'newDataBase_Log' )
GO
MODIFY FILE(NAME = 'oldDataBase_Log', NEWNAME = 'newDataBase_Log' )
GO
4- Assign new full path file name to renamed master data file:
ALTER DATABASE AutoMac
MODIFY FILE (NAME='newDataBase', FILENAME='C:\mySQLfiles\newDataBase.mdf')
GO
MODIFY FILE (NAME='newDataBase', FILENAME='C:\mySQLfiles\newDataBase.mdf')
GO
5- Assign new full path file name to renamed log file:
ALTER DATABASE AutoMac
MODIFY FILE (NAME='newDataBase_Log', FILENAME='C:\mySQLfiles\newDataBase_Log.ldf')
GO
MODIFY FILE (NAME='newDataBase_Log', FILENAME='C:\mySQLfiles\newDataBase_Log.ldf')
GO
6- Now you need to take the database offline (Tasks->Take Offline) and bring it back online (Tasks->Bring Online), then you don't need to detach and attach your database again.
SQL - How to rename a DATABASE physically in MS SQL Server 2008
Saturday, August 15, 2009
SQL Server 2008 - Warning: Saving Changes Not Permitted
If [Prevent saving changes that require table re-creation] option in [Table Options] of [Designers] in SSMS [SQL Server Management Studio] is ON, when you want to save a table that requires the table be dropped and recreated behind the scenes, you will see the following warning. It can happen if you want to modify a column data type, data type size, or to add a new column in a specific location, or ...
Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.
The solution is turn off the option in Tools -> Options then go to [Designers] page and uncheck [Prevent saving changes that require table re-creation] option.
Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.
The solution is turn off the option in Tools -> Options then go to [Designers] page and uncheck [Prevent saving changes that require table re-creation] option.
SQL Server 2008 - Warning: Saving Changes Not Permitted
Friday, August 14, 2009
SQL - How to rename a DATABASE in MS SQL Server 2005/2008
You could change the DATABASE name by calling sp_renameDB system stored procedure but it will be deprecated in future versions.
sp_renamedb (Transact-SQL)
http://msdn.microsoft.com/en-us/library/ms186217.aspx
According to MSDN document in above URL you better Use ALTER DATABASE MODIFY NAME Instead of sp_renameDB to rename.
"This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Use ALTER DATABASE MODIFY NAME instead. For more information, see ALTER DATABASE (Transact-SQL)."
ALTER DATABASE (Transact-SQL)
http://msdn.microsoft.com/en-us/library/ms174269.aspx
But none of above mentioned commands change Physical Name of database files, how can we change Physical file names of MS SQL Database files (DB and Log files) ? it comes in next blog entry, cheers.
EXEC sp_renameDB 'myOldDB','myNewDB'
sp_renamedb (Transact-SQL)
http://msdn.microsoft.com/en-us/library/ms186217.aspx
According to MSDN document in above URL you better Use ALTER DATABASE MODIFY NAME Instead of sp_renameDB to rename.
"This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Use ALTER DATABASE MODIFY NAME instead. For more information, see ALTER DATABASE (Transact-SQL)."
ALTER DATABASE (Transact-SQL)
http://msdn.microsoft.com/en-us/library/ms174269.aspx
/* Rename the Database myOldDB to myNewDB */
ALTER DATABASE myOldDB MODIFY NAME = myNewDB
GO
ALTER DATABASE myOldDB MODIFY NAME = myNewDB
GO
But none of above mentioned commands change Physical Name of database files, how can we change Physical file names of MS SQL Database files (DB and Log files) ? it comes in next blog entry, cheers.
SQL - How to rename a DATABASE in MS SQL Server 2005/2008
Sunday, August 9, 2009
Friday, August 7, 2009
Valid XHTML document
An XHTML document is technically an XML document. XML documents can include an XML declaration as the first line in the document, something like this:
<?xml version="1.0" encoding="UTF-8"?>
There are only a few major rules to consider, but you have to follow them if you want to create a valid XHTML document. Here they are in brief:
* In an XHTML document every tag must be closed.
* Empty elements without content, must be correctly closed with a closing slash.
For example, a break tag is formatted <br />.
* Tags must be nested correctly,
it works like a LIFO queue, the last tag you open must be closed first.
* All XHTML tags should be in lowercase.
* All attribute values are enclosed in quotation marks.
* A valid XHTML document needs a valid XHTML DOCTYPE declaration.
The DOCTYPE declaration works for several purposes:
* DOCTYPE helps your page to be validated as XHTML.
* DOCTYPE allows the browser knows the version of your page markup language.
* DOCTYPE references the specific DTD for your page markup language.
* DOCTYPE enables your page to be displayed properly in standard web browsers
(IE, Netscape Navigator, Mozilla, Firefox, Opera, Chrome, and ...).
For an XHTML 1.0 document, you can choose one of three different DOCTYPES:
- strict
- transitional
- frames
- strict DOCTYPE declaration:
If for presenting and styling your document you are using CSS.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
- transitional DOCTYPE declaration:
If your document includes any presentational or styling markup code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- frames DOCTYPE declaration:
If your document is in frames.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
The easiest to use is the transitional DOCTYPE declaration, but using CSS to present document sometimes is the best way.
After XHTML DOCTYPE declaration, it must have an additional line of markup:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
In XHTML, the above line works instead of the opening <html> in HTML document. It adds information about the XHTML namespace. (A namespace is basically a vocabulary of elements and attributes)
Valid XHTML document
Monday, August 3, 2009
.NET - Can I remove .NET Framework 1.0 or 1.1 now that I have 2.0 or later on my machine?
Yes, you can! cheeers, it's because of side by side execution manner in earlier versions (1.0, 1.1, 2.0). I keep it, cuz it doesn't occupy too much space.
- But there are some breaking changes in .NET Framework 2.0 if you have an application which wants to run on version 1.0 or 1.1 if you remove those versions.
Breaking Changes in .NET Framework 2.0
http://msdn.microsoft.com/en-us/netframework/aa570326.aspx
- Look at the .NET Framework 3.5 Architecture,:
http://msdn.microsoft.com/en-us/library/bb822049.aspx
"The relationship of the .NET Framework versions 2.0, 3.0, and 3.5 differs from the relationship of versions 1.0, 1.1, and 2.0. The .NET Framework versions 1.0, 1.1, and 2.0 are completely separate from each other, and one version can be present on a computer regardless of whether the other versions are present. When versions 1.0, 1.1, and 2.0 are on the same computer, each version has its own common language runtime, class libraries, compiler, and so forth. Application developers can choose which version to target."
- The .NET Framework 2.0 was a generational release over the .NET Framework 1.0 but .NET Framework 3.0 (and later) adds new technologies (additive release).
How .NET Framework 3.0 Relates to .NET Framework 2.0 and Earlier
http://msdn.microsoft.com/en-us/library/aa480198.aspx#netfx30_topic3
"The .NET Framework 3.0 adds new technologies to the .NET Framework 2.0, which makes the .NET Framework 3.0 a superset of the .NET Framework 2.0. You can think of .NET Framework 3.0 as an "additive" release to the .NET Framework 2.0, as contrasted with a generational release where software is revised across the board. (For example, the .NET Framework 2.0 was a generational release over the .NET Framework 1.0.)
Because .NET Framework 3.0 is an additive release and uses the core run-time components from .NET Framework 2.0, it is completely backward compatible with the earlier version. Your existing .NET Framework 2.0 based-applications will continue to run without any modifications and you can safely continue your investments using the technologies that shipped with .NET Framework 2.0."
The same question in social.msdn: Which version of Framework .net?
http://social.msdn.microsoft.com/Forums/en-US/netfxsetup/thread/0387a1d6-404b-48d4-9d8c-53aefcb75d7b
.NET Framework article in WiKiPedia is also interesting:
http://en.wikipedia.org/wiki/.NET_framework
.NET - Can I remove .NET Framework 1.0 or 1.1 now that I have 2.0 or later on my machine?
Sunday, August 2, 2009
One year Blog anniversary
Friday, July 31, 2009
C# - C++ - [StructLayout] to pass structures to unmanaged function
CLR rearranges the order of type members during runtime, it generates better performance, faster access to members, less memory consumption, and so. But when .NET wants to interoperate with unmanaged codes, it's necessary to keep the structure layout as is. For this purpose, it's possible to specify the layout of a structure by using the StructLayout attribute.
[StructLayout(LayoutKind.Sequential)] keeps the sequence of members in structure type as defined. The following sample gets the OS version by passing a pointer to structure to GetVersionEx function in unmanaged kernel32.dll:
OSVERSIONINFO Structure
http://msdn.microsoft.com/en-us/library/ms724834(VS.85).aspx
[StructLayout(LayoutKind.Sequential)] keeps the sequence of members in structure type as defined. The following sample gets the OS version by passing a pointer to structure to GetVersionEx function in unmanaged kernel32.dll:
...
using System.Runtime.InteropServices;
...
[DllImport("kernel32.dll")]
public static extern
bool GetVersionEx(ref OSVERSIONINFO lpVersionInfo);
[StructLayout(LayoutKind.Sequential)]
public struct OSVERSIONINFO
{
public int dwOSVersionInfoSize;
public int dwMajorVersion;
public int dwMinorVersion;
public int dwBuildNumber;
public int dwPlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public String szCSDVersion;
}
...
OSVERSIONINFO osVer = new OSVERSIONINFO();
osVer.dwOSVersionInfoSize = Marshal.SizeOf(osVer);
string osVersion = string.Empty;
if (GetVersionEx(ref osVer))
osVersion = string.Format("{0}.{1}.{2}",
osVer.dwMajorVersion,
osVer.dwMinorVersion,
osVer.dwBuildNumber);
MessageBox.Show("OS Ver: " + osVersion);
using System.Runtime.InteropServices;
...
[DllImport("kernel32.dll")]
public static extern
bool GetVersionEx(ref OSVERSIONINFO lpVersionInfo);
[StructLayout(LayoutKind.Sequential)]
public struct OSVERSIONINFO
{
public int dwOSVersionInfoSize;
public int dwMajorVersion;
public int dwMinorVersion;
public int dwBuildNumber;
public int dwPlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public String szCSDVersion;
}
...
OSVERSIONINFO osVer = new OSVERSIONINFO();
osVer.dwOSVersionInfoSize = Marshal.SizeOf(osVer);
string osVersion = string.Empty;
if (GetVersionEx(ref osVer))
osVersion = string.Format("{0}.{1}.{2}",
osVer.dwMajorVersion,
osVer.dwMinorVersion,
osVer.dwBuildNumber);
MessageBox.Show("OS Ver: " + osVersion);
OSVERSIONINFO Structure
http://msdn.microsoft.com/en-us/library/ms724834(VS.85).aspx
C# - C++ - [StructLayout] to pass structures to unmanaged function
CardSwap !
I received an email from a friend about cardswap.ca, perfect place to swap or sell your gift cards or buy one with discount. It's just started but I expect it grows pretty fast.
CardSwap is the premier online Canadian marketplace for gift card exchanges. Whether you want to buy gift cards at substantial savings, or sell them for cash, CardSwap offers the simplest way to get what you want.
http://www.cardswap.ca/
CardSwap !
Thursday, July 30, 2009
C# - How can we show Markup Language (HTML, XML, XSD, ... ) codes in blogger ?
Well, we need to encode ampersands and angle brackets:
< to <
> to >
& to &
I use a great tool in the following url:
http://centricle.com/tools/html-entities/
Encode / Decode HTML Entities
Convert text to HTML entities (and vice-versa)
< to <
> to >
& to &
I use a great tool in the following url:
http://centricle.com/tools/html-entities/
Encode / Decode HTML Entities
Convert text to HTML entities (and vice-versa)
C# - How can we show Markup Language (HTML, XML, XSD, ... ) codes in blogger ?
Monday, July 27, 2009
C# - Validate XML document against a Schema - XmlReaderSettings
Sample code for Validate XML document against a Schema:
The code line to call the method to validate XML against XSD:
bool retVal = myClass.XmlValidateByXsd(@"C:\employee.xml", @"C:\employee.xsd");
Sample XML file:
<?xml version="1.0" standalone="yes"?>
<Employees xmlns="http://iborn2code.blogspot.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://iborn2code.blogspot.com employee.xsd">
<Employee>
<SIN>525252525</SIN>
<FirstName>AB BA</FirstName>
<City>Vancouver</City>
<Zip>V1V</Zip>
</Employee>
<Employee>
<SIN>525252527</SIN>
<FirstName>BC CB</FirstName>
<City>Kelowna</City>
<Zip>V2V</Zip>
</Employee>
</Employees>
Sample XML Schema for above XML:
<div class="mycode">
<?xml version="1.0" encoding="ISO-8859-1" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Employee">
<xs:complexType>
<xs:sequence>
<xs:element name="SIN" type="xs:string"/>
<xs:element name="FirstName" type="xs:string"/>
<xs:element name="City" type="xs:string"/>
<xs:element name="Zip" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
</div>
...
using System.Xml;
using System.Xml.Schema;
...
public static bool XmlValidateByXsd(string xmlFile, string xsdFile)
{
bool retVal = false;
if( ! File.Exists( xmlFile ) || ! File.Exists( xsdFile ) )
return retVal;
try
{
XmlReaderSettings xmlRdrSettings = new XmlReaderSettings();
xmlRdrSettings.ValidationType = ValidationType.Schema;
xmlRdrSettings.Schemas = new XmlSchemaSet();
xmlRdrSettings.Schemas.Add(null, xsdFile);
xmlRdrSettings.ValidationEventHandler +=
new ValidationEventHandler(ValidationEventHandler);
using (XmlReader xmlRdr = XmlReader.Create(xmlFile, xmlRdrSettings))
{
while (xmlRdr.Read()) { }
}
retVal = true;
}
catch (XmlException xmlEx)
{
MessageBox.Show(xmlEx.Message);
}
return retVal;
}
private static void ValidationEventHandler(object sender, ValidationEventArgs args)
{
// Do error handling
// Console.WriteLine("Error: " + args.Message);
}
using System.Xml;
using System.Xml.Schema;
...
public static bool XmlValidateByXsd(string xmlFile, string xsdFile)
{
bool retVal = false;
if( ! File.Exists( xmlFile ) || ! File.Exists( xsdFile ) )
return retVal;
try
{
XmlReaderSettings xmlRdrSettings = new XmlReaderSettings();
xmlRdrSettings.ValidationType = ValidationType.Schema;
xmlRdrSettings.Schemas = new XmlSchemaSet();
xmlRdrSettings.Schemas.Add(null, xsdFile);
xmlRdrSettings.ValidationEventHandler +=
new ValidationEventHandler(ValidationEventHandler);
using (XmlReader xmlRdr = XmlReader.Create(xmlFile, xmlRdrSettings))
{
while (xmlRdr.Read()) { }
}
retVal = true;
}
catch (XmlException xmlEx)
{
MessageBox.Show(xmlEx.Message);
}
return retVal;
}
private static void ValidationEventHandler(object sender, ValidationEventArgs args)
{
// Do error handling
// Console.WriteLine("Error: " + args.Message);
}
The code line to call the method to validate XML against XSD:
bool retVal = myClass.XmlValidateByXsd(@"C:\employee.xml", @"C:\employee.xsd");
Sample XML file:
<?xml version="1.0" standalone="yes"?>
<Employees xmlns="http://iborn2code.blogspot.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://iborn2code.blogspot.com employee.xsd">
<Employee>
<SIN>525252525</SIN>
<FirstName>AB BA</FirstName>
<City>Vancouver</City>
<Zip>V1V</Zip>
</Employee>
<Employee>
<SIN>525252527</SIN>
<FirstName>BC CB</FirstName>
<City>Kelowna</City>
<Zip>V2V</Zip>
</Employee>
</Employees>
Sample XML Schema for above XML:
<div class="mycode">
<?xml version="1.0" encoding="ISO-8859-1" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Employee">
<xs:complexType>
<xs:sequence>
<xs:element name="SIN" type="xs:string"/>
<xs:element name="FirstName" type="xs:string"/>
<xs:element name="City" type="xs:string"/>
<xs:element name="Zip" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
</div>
C# - Validate XML document against a Schema - XmlReaderSettings
Thursday, July 23, 2009
C# - Error Message - 'This would cause two bindings in the collection to bind to the same property'
It shows the code is calling Control.DataBindings.Add two times to the same parameters.
May be duplicate binding to the DataBindings collection causes this error. Anyway one
solution is to clear Control.DataBindings before adding new binding:
this.txtAddress.DataBindings.Clear();
this.txtZipCode.DataBindings.Clear();
this.txtAddress.Text = string.Empty;
this.txtZipCode.Text = string.Empty;
this.txtAddress.DataBindings.Add("Text", myDtaTbl, "Address");
this.txtZipCode.DataBindings.Add("Text", myDtaTbl, "ZipCode");
May be duplicate binding to the DataBindings collection causes this error. Anyway one
solution is to clear Control.DataBindings before adding new binding:
this.txtAddress.DataBindings.Clear();
this.txtZipCode.DataBindings.Clear();
this.txtAddress.Text = string.Empty;
this.txtZipCode.Text = string.Empty;
this.txtAddress.DataBindings.Add("Text", myDtaTbl, "Address");
this.txtZipCode.DataBindings.Add("Text", myDtaTbl, "ZipCode");
C# - Error Message - 'This would cause two bindings in the collection to bind to the same property'
Tuesday, July 21, 2009
Sunday, July 19, 2009
Saturday, July 18, 2009
www.speedtest.net - to test the speed of your Internet connection
http://www.speedtest.net/index.php
What is Speedtest.net?
Use Speedtest.net to test the speed of your Internet connection. See if you are getting what you pay for or share your results with others!
Speedtest.net is a broadband speed analysis tool that allows anyone to test their Internet connection. Ookla provides this service for free to anyone curious about the performance of their connection to and from hundreds of locations around the world.
What is Speedtest.net testing?
Speedtest.net performs three key measurements used to determine the overall quality and performance of your Internet connection.
* Download Speed
* Upload Speed
* Ping (Latency)
(The time it takes in milliseconds for a small piece of data to be sent from your computer to the Internet and back)
www.speedtest.net - to test the speed of your Internet connection
CamStudio open source - Free Streaming Video Software
CamStudio is able to record all screen and audio activity on your computer and create industry-standard AVI video files and using its built-in SWF Producer can turn those AVIs into bandwidth-friendly Streaming Flash videos (SWFs).
It's a perfect, user friendly, free, and practical screen and audio recording app.
http://camstudio.org/
CamStudio open source - Free Streaming Video Software
Friday, July 17, 2009
SQL - Installing SQL Express 2008 - Restart Computer Failed problem
Repeatedly MS SQL Express 2008 installation package asked to restart computer when I wanted to install SQL 2008 Express on a machine.
I needed to check system's pending file rename operations registry key. It should be cleared after rebooting the system. If not, clear it and just click on Re-run or try it again.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations
HKEY_LOCAL_MACHINE
SYSTEM
CurrentControlSet
Control
Session Manager
PendingFileRenameOperations
I needed to check system's pending file rename operations registry key. It should be cleared after rebooting the system. If not, clear it and just click on Re-run or try it again.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations
HKEY_LOCAL_MACHINE
SYSTEM
CurrentControlSet
Control
Session Manager
PendingFileRenameOperations
SQL - Installing SQL Express 2008 - Restart Computer Failed problem
Wednesday, July 15, 2009
C# -ComboBox- How to move the selected item to top of the list?
In a ComboBox control, the .SelectedIndexChanged event fires when
we select an item then the following code moves the item to top:
...
private void cbo_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cboSender = (ComboBox)sender;
if ( cboSender.SelectedIndex > 0 )
{
string strToFind = cboSender.Items[cboSender.SelectedIndex].ToString();
cboSender.Items.RemoveAt( cboSender.SelectedIndex );
cboSender.Items.Insert(0, strToFind);
cboSender.SelectedIndex = 0;
}
}
...
we select an item then the following code moves the item to top:
...
private void cbo_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cboSender = (ComboBox)sender;
if ( cboSender.SelectedIndex > 0 )
{
string strToFind = cboSender.Items[cboSender.SelectedIndex].ToString();
cboSender.Items.RemoveAt( cboSender.SelectedIndex );
cboSender.Items.Insert(0, strToFind);
cboSender.SelectedIndex = 0;
}
}
...
C# -ComboBox- How to move the selected item to top of the list?
Tuesday, July 14, 2009
C# - How to scroll in RichTextBox control after searching?
To search a value in a TextRichBox control you can use .Find( ... ) method,
and if it can find a match then it returns the index of starting character.
To fit the text and show the found value, .ScrollToCaret() method do the job.
The sample code is as following:
...
int iIndx = this.rtbFileTxt.Find(strFind,
this.rtbFileTxt.SelectionStart,
RichTextBoxFinds.None);
if (iIndx < 0) return false;
this.SuspendLayout();
this.rtbFileTxt.SelectionStart = iIndx;
this.rtbFileTxt.SelectionColor = Color.Yellow;
this.rtbFileTxt.SelectionBackColor = Color.Black;
Point ptCharIndx =
this.rtbFileTxt.GetPositionFromCharIndex(this.rtbFileTxt.SelectionStart);
if (ptCharIndx.Y > this.rtbFileTxt.Height)
this.rtbFileTxt.ScrollToCaret();
this.ResumeLayout(true);
...
and if it can find a match then it returns the index of starting character.
To fit the text and show the found value, .ScrollToCaret() method do the job.
The sample code is as following:
...
int iIndx = this.rtbFileTxt.Find(strFind,
this.rtbFileTxt.SelectionStart,
RichTextBoxFinds.None);
if (iIndx < 0) return false;
this.SuspendLayout();
this.rtbFileTxt.SelectionStart = iIndx;
this.rtbFileTxt.SelectionColor = Color.Yellow;
this.rtbFileTxt.SelectionBackColor = Color.Black;
Point ptCharIndx =
this.rtbFileTxt.GetPositionFromCharIndex(this.rtbFileTxt.SelectionStart);
if (ptCharIndx.Y > this.rtbFileTxt.Height)
this.rtbFileTxt.ScrollToCaret();
this.ResumeLayout(true);
...
C# - How to scroll in RichTextBox control after searching?
C# - How to get the cursor position in a RichTextBox control
- Solution 1:
TextBoxBase.SelectionStart Property
Gets or sets the starting point of text selected in the text box.
* Inheritance Hierarchy
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.TextBoxBase
System.Windows.Forms.RichTextBox
.SelectionStart Property of a RichTextBox control gives you
the cursor position nonetheless you have a highlighted selected
text or not and it doesn't matter that SelectionLength property
is zero or greater than zero.
...
int iCrsrPos = this.rtbCntrl.SelectionStart
...
- Solution 2:
If you want to get character index when mouse moves, you can
get convert Cursor.Position to x and y values of a Point type
which are related to your control (RichTextBox) by calling
.PointToClient( ... ) method, and then call GetCharIndexFromPosition
method to find out the character position.
private void rtbCntrl_MouseMove(object sender, MouseEventArgs e)
{
Point rtbPos = this.rtbCntrl.PointToClient(Cursor.Position);
int iCharIndx = this.rtbCntrl.GetCharIndexFromPosition(rtbPos);
// ... do what ever want you do with the character position
}
TextBoxBase.SelectionStart Property
Gets or sets the starting point of text selected in the text box.
* Inheritance Hierarchy
System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.TextBoxBase
System.Windows.Forms.RichTextBox
.SelectionStart Property of a RichTextBox control gives you
the cursor position nonetheless you have a highlighted selected
text or not and it doesn't matter that SelectionLength property
is zero or greater than zero.
...
int iCrsrPos = this.rtbCntrl.SelectionStart
...
- Solution 2:
If you want to get character index when mouse moves, you can
get convert Cursor.Position to x and y values of a Point type
which are related to your control (RichTextBox) by calling
.PointToClient( ... ) method, and then call GetCharIndexFromPosition
method to find out the character position.
private void rtbCntrl_MouseMove(object sender, MouseEventArgs e)
{
Point rtbPos = this.rtbCntrl.PointToClient(Cursor.Position);
int iCharIndx = this.rtbCntrl.GetCharIndexFromPosition(rtbPos);
// ... do what ever want you do with the character position
}
C# - How to get the cursor position in a RichTextBox control
Tuesday, June 30, 2009
Tuesday, June 23, 2009
Came back after 4 weeks holiday
Monday, May 25, 2009
Visual Studio 2010 Beta 1
Visual Studio 2010 Beta 1 is ready to download since May 20
then it's ready to test (and also the .Net Framework 4) by public.
URL to download:
Visual Studio 2010 and .NET Framework 4 Beta 1
http://msdn.microsoft.com/en-us/vstudio/dd582936.aspx
Visual Studio 2010 Product Highlights
http://msdn.microsoft.com/en-us/library/dd547188(VS.100).aspx
Visual Studio 2010 and .NET Framework 4 Training Kit - May Preview
http://www.microsoft.com/downloads/details.aspx?FamilyID=752CB725-969B-4732-A383-ED5740F02E93&displaylang=en
Visual Studio 2010 Samples
http://msdn.microsoft.com/en-us/vstudio/dd238515.aspx
Visual Studio 2010 and .NET Framework 4 Beta 1 Walkthroughs
http://msdn.microsoft.com/en-us/vstudio/dd441784.aspx
then it's ready to test (and also the .Net Framework 4) by public.
URL to download:
Visual Studio 2010 and .NET Framework 4 Beta 1
http://msdn.microsoft.com/en-us/vstudio/dd582936.aspx
Visual Studio 2010 Product Highlights
http://msdn.microsoft.com/en-us/library/dd547188(VS.100).aspx
Visual Studio 2010 and .NET Framework 4 Training Kit - May Preview
http://www.microsoft.com/downloads/details.aspx?FamilyID=752CB725-969B-4732-A383-ED5740F02E93&displaylang=en
Visual Studio 2010 Samples
http://msdn.microsoft.com/en-us/vstudio/dd238515.aspx
Visual Studio 2010 and .NET Framework 4 Beta 1 Walkthroughs
http://msdn.microsoft.com/en-us/vstudio/dd441784.aspx
Visual Studio 2010 Beta 1
Tuesday, May 19, 2009
My 100th Blog Entry!
I made it to 100! and it's just starting to grow up, Thank all the readers, it's a try to share and there is a hope to help. I learned a lot from others,and I decided to share. Till now, it visited from 51 countries, this encourages me to try more, cheers.
Coming soon: Many more blog entries! it'll continue.
Coming soon: Many more blog entries! it'll continue.
My 100th Blog Entry!
Monday, May 18, 2009
C# - Generic dictionary Types - Dictionary
Dictionary
Represents a collection of keys and values.
Namespace: System.Collections.Generic
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
Sample code:
...
public Dictionary
new Dictionary
...
Some sample methods to work with Dictionary
// Fill the Dictionary
private void fillSeasonDic()
{
seasonDic.Add("Spring", Color.LightGreen);
seasonDic.Add("Summer", Color.Orange);
seasonDic.Add("Autumn", Color.LightYellow);
seasonDic.Add("Winter", Color.LightBlue);
}
// Using .TryGetType to find [value] corresponding to the [key]
private Color getSeasonColor(string seasonName)
{
Color retColor = Color.White;
if ( ! string.IsNullOrEmpty(seasonName))
if ( ! seasonDic.TryGetValue(seasonName, out retColor)
retColor = Color.White;
return retColor;
}
// Retrieve data from a Dictionary by Enumerator
private string getAllSeasons()
{
StringBuilder sbRetVal = new StringBuilder();
Dictionary
seasonDic.GetEnumerator();
while (sEnum.MoveNext())
sbRetVal.AppendLine(sEnum.Current.Key +
": " +
sEnum.Current.Value.Name);
return sbRetVal.ToString();
}
// Use [KeyValuePair] structure in a [foreach] loop
private string getAllColorSeasons()
{
StringBuilder sbRetVal = new StringBuilder();
foreach( KeyValuePair
sbRetVal.AppendLine(kvp.Value.Name + ": " + kvp.Key);
return sbRetVal.ToString();
}
private void btnGetAllSeason_Click(object sender, EventArgs e)
{
MessageBox.Show( this.getAllSeasons() +
"\r\n" +
this.getAllColorSeasons() );
}
C# - Generic dictionary Types - Dictionary
Friday, May 15, 2009
C# - Application.StartupPath - How to get the path for the executable file that started the application?
If you want to have access to the path of running application, there is a property that can give you the path. As an example this path can contain other files or folders to keep related data files to youe application and in this way you can work with those files without pointing to static directory addresses.
Application.StartupPath Property
Namespace: System.Windows.Forms
Application.StartupPath property gets the path for the executable file that started the application, not including the executable name.
Directory.SetCurrentDirectory Method
Sets the application's current working directory to the specified directory.
http://msdn.microsoft.com/en-us/library/system.io.directory.setcurrentdirectory.aspx
System.IO.Directory.GetCurrentDirectory()
A string containing the path of the current working directory.
http://msdn.microsoft.com/en-us/library/system.io.directory.getcurrentdirectory.aspx
Assembly.GetExecutingAssembly Method
Gets the assembly that contains the code that is currently executing.
http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getexecutingassembly.aspx
System.Reflection.Assembly.GetExecutingAssembly().Location
It returns the file name of the current binary
The following simple sample can show the result of aboved mentioned methods:
string dfltDir = @"C:\TEMP";
if( Directory.Exists( dfltDir ) )
Directory.SetCurrentDirectory( dfltDir );
StringBuilder sb = new StringBuilder();
sb.AppendLine("GetCurrentDirectory(): ");
sb.AppendLine( Directory.GetCurrentDirectory() );
sb.AppendLine();
sb.AppendLine( "Application.StartupPath: " );
sb.AppendLine( Application.StartupPath );
sb.AppendLine();
sb.AppendLine("Assembly.GetExecutingAssembly().Location: ");
sb.AppendLine( System.Reflection.Assembly.GetExecutingAssembly().Location);
sb.AppendLine();
MessageBox.Show(sb.ToString());
Application.StartupPath Property
Namespace: System.Windows.Forms
Application.StartupPath property gets the path for the executable file that started the application, not including the executable name.
Directory.SetCurrentDirectory Method
Sets the application's current working directory to the specified directory.
http://msdn.microsoft.com/en-us/library/system.io.directory.setcurrentdirectory.aspx
System.IO.Directory.GetCurrentDirectory()
A string containing the path of the current working directory.
http://msdn.microsoft.com/en-us/library/system.io.directory.getcurrentdirectory.aspx
Assembly.GetExecutingAssembly Method
Gets the assembly that contains the code that is currently executing.
http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getexecutingassembly.aspx
System.Reflection.Assembly.GetExecutingAssembly().Location
It returns the file name of the current binary
The following simple sample can show the result of aboved mentioned methods:
string dfltDir = @"C:\TEMP";
if( Directory.Exists( dfltDir ) )
Directory.SetCurrentDirectory( dfltDir );
StringBuilder sb = new StringBuilder();
sb.AppendLine("GetCurrentDirectory(): ");
sb.AppendLine( Directory.GetCurrentDirectory() );
sb.AppendLine();
sb.AppendLine( "Application.StartupPath: " );
sb.AppendLine( Application.StartupPath );
sb.AppendLine();
sb.AppendLine("Assembly.GetExecutingAssembly().Location: ");
sb.AppendLine( System.Reflection.Assembly.GetExecutingAssembly().Location);
sb.AppendLine();
MessageBox.Show(sb.ToString());
C# - Application.StartupPath - How to get the path for the executable file that started the application?
Wednesday, May 13, 2009
C# - GZipStream to Zip and UnZip with Base64 Encoding
First of all, you can find sample code about Encoding and Decoding based on Base64 in the following link:
C# - UTF8/Base64 Encoder/Decoder
http://iborn2code.blogspot.com/search?q=Base64
class fbBase64
{
public static string EncodeToBase64(string theString)
{
return Convert.ToBase64String(
System.Text.Encoding.UTF8.GetBytes(theString));
}
public static string DecodeBase64(string theString)
{
return System.Text.Encoding.UTF8.GetString(
Convert.FromBase64String(theString));
}
}
public static bool GetZipBase64( string str2Zip, out byte[] aryBase64Zip )
{
bool retVal = true;
aryBase64Zip = null;
try
{
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream gzs = new GZipStream(ms, CompressionMode.Compress))
{
using (StreamWriter sw = new StreamWriter(gzs))
{
sw.Write(fbBase64.EncodeToBase64(str2Zip));
}
}
aryBase64Zip = ms.ToArray();
}
}
catch (Exception ex)
{
retVal = false;
MessageBox.Show(ex.ToString());
}
return retVal;
}
public static bool GetUnZipUnBase64( byte[] zipData, out string strOrgnl)
{
bool retVal = true;
strOrgnl = null;
try
{
using (MemoryStream ms = new MemoryStream(zipData) )
{
using (GZipStream gzs = new GZipStream(ms, CompressionMode.Decompress))
{
using ( StreamReader sr = new StreamReader(gzs) )
{
strOrgnl = fbBase64.DecodeBase64( sr.ReadToEnd() );
}
}
}
}
catch (Exception ex)
{
retVal = false;
MessageBox.Show(ex.ToString());
}
return retVal;
}
C# - UTF8/Base64 Encoder/Decoder
http://iborn2code.blogspot.com/search?q=Base64
class fbBase64
{
public static string EncodeToBase64(string theString)
{
return Convert.ToBase64String(
System.Text.Encoding.UTF8.GetBytes(theString));
}
public static string DecodeBase64(string theString)
{
return System.Text.Encoding.UTF8.GetString(
Convert.FromBase64String(theString));
}
}
public static bool GetZipBase64( string str2Zip, out byte[] aryBase64Zip )
{
bool retVal = true;
aryBase64Zip = null;
try
{
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream gzs = new GZipStream(ms, CompressionMode.Compress))
{
using (StreamWriter sw = new StreamWriter(gzs))
{
sw.Write(fbBase64.EncodeToBase64(str2Zip));
}
}
aryBase64Zip = ms.ToArray();
}
}
catch (Exception ex)
{
retVal = false;
MessageBox.Show(ex.ToString());
}
return retVal;
}
public static bool GetUnZipUnBase64( byte[] zipData, out string strOrgnl)
{
bool retVal = true;
strOrgnl = null;
try
{
using (MemoryStream ms = new MemoryStream(zipData) )
{
using (GZipStream gzs = new GZipStream(ms, CompressionMode.Decompress))
{
using ( StreamReader sr = new StreamReader(gzs) )
{
strOrgnl = fbBase64.DecodeBase64( sr.ReadToEnd() );
}
}
}
}
catch (Exception ex)
{
retVal = false;
MessageBox.Show(ex.ToString());
}
return retVal;
}
C# - GZipStream to Zip and UnZip with Base64 Encoding
Monday, May 11, 2009
C# - How to read or modify value of a key in app.Config
using System;
using System.Text;
using System.Configuration;
using System.Collections.Generic;
namespace myApp
{
class theAppCnfg
{
public static string GetKey( string keyName )
{
string retVal = string.Empty;
AppSettingsReader appCnfgRdr = new AppSettingsReader();
retVal = (string) appCnfgRdr.GetValue(keyName,typeof(string));
return retVal;
}
public static void ModifyKey(string keyName, string keyValue)
{
Configuration cnfg =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None );
cnfg.AppSettings.Settings[keyName].Value = keyValue;
cnfg.Save(ConfigurationSaveMode.Modified);
}
}
}
C# - How to read or modify value of a key in app.Config
Sunday, May 10, 2009
C# - Graphics Object - Pie Chart
This one comes with a [Form] which contains a [PictureBox] who called [chart]
We have two classes:
- [piePart] that collects name, value, and color for each pie part in our pie chart
- [pieChart] contains a generic List collection based on [piePart] class and a method which draw the chart which called [public Image doPieChart(Size pieSize)] and returns a bitmap or generated pie chart.
Codes for pieChart and piePart classes:
using System;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections.Generic;
namespace PieChart
{
public class piePart
{
public string pieName;
public float pieVal;
public Color pieColor;
public piePart()
{
}
public piePart(string _pieName, float _pieVal, Color _pieColor)
{
pieName = _pieName;
pieVal = _pieVal;
pieColor = _pieColor;
}
}
public class pieChart
{
public List
public pieChart()
{
}
public Image doPieChart(Size pieSize)
{
if (lstPiePart.Count == 0) return null;
Bitmap pieBmp = new Bitmap(pieSize.Width, pieSize.Height);
Graphics grfx = Graphics.FromImage(pieBmp);
grfx.SmoothingMode = SmoothingMode.HighQuality;
float totalPieValues = 0;
foreach (piePart aPie in lstPiePart)
{
if (aPie.pieVal <= 0)
{
string errMag =
"A Pie must have a positive value";
throw new ArgumentException(errMag);
}
totalPieValues += aPie.pieVal;
}
if ( totalPieValues <= 0 )
{
string errMsg =
"At least one Pie must have a greater than Zero value";
throw new ArgumentException(errMsg);
}
Rectangle pieRect =
new Rectangle(1, 1, pieSize.Width - 2, pieSize.Height - 2);
Pen piePen = new Pen(Color.Black, 1);
float pieStartAngle = 0;
foreach (piePart aPie in lstPiePart)
{
Brush pieBrush =
new LinearGradientBrush(pieRect,
aPie.pieColor,
Color.White,
(float)45 );
float pieSweepAngle = (aPie.pieVal / totalPieValues) * 360;
grfx.FillPie(pieBrush, pieRect, pieStartAngle, pieSweepAngle);
grfx.DrawPie(piePen, pieRect, pieStartAngle, pieSweepAngle);
pieStartAngle += pieSweepAngle;
}
return pieBmp;
}
}
}
Codes for Form class:
using System;
using System.Text;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections.Generic;
namespace PieChart
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Draw(object sender, PaintEventArgs e)
{
Draw();
}
private void Draw()
{
pieChart myChart = new pieChart();
myChart.lstPiePart.Add(new piePart( "Spring",
(float) 118.79,
Color.Green ) );
myChart.lstPiePart.Add(new piePart( "Summer",
(float) 67.23,
Color.Red));
myChart.lstPiePart.Add(new piePart( "Autumn",
(float) 96.14,
Color.Yellow));
myChart.lstPiePart.Add(new piePart( "Winter",
(float) 121.92,
Color.Blue));
chart.Image = myChart.doPieChart( new Size(200, 200 ) );
}
}
}
C# - Graphics Object - Pie Chart
Friday, May 8, 2009
C# - System.Drawing namespace & Graphics Object
To have a graphic UI, .NET prepared many graphic classes to display graphical objects
on a form or other Windows Forms control.
The System.Drawing namespace is included in .NET Framework to deal with graphic stuff.
The System.Drawing namespace contains many classes and the most common ones are as following:
- [Graphics] is used to draw to display devices
- [Pen] is used to draw lines and curves
- [Brush] and other classes drived from it are used to fill shapes.
- ...
The System.Drawing namespace contains some structures too, and most important ones are as following:
- [Color] which represent a color
- [Point] that has x and y cordinates for a point in two dimensional plane.
- [Rectangle] it has four integer values that represent the location and size of
a rectangle.
- [Size] Stores width and height of a rectabgle by integer values.
- ...
How to draw a line or shape:
- Create a [Graphics] object, using System.Windows.Forms.Control.CreateGraphics method.
- Create a [Pen] object.
- Call a method from the Graphics object to draw a shape using the [Pen].
Some of the Graphics object methods:
- [Clear] Fills the entire drawing surface with a color.
- [DrawEllipse] Draws an ellipse or a circle by a pair of height and width.
- [DrawIcon] Draws image of an icon at specified coordinates.
- [DrawImage] Draws an image at specified coordinates.
- [DrawLine] Draws a line between two points.
- [DrawLines] Draws a series of lines by an array of Point structures.
- [DrawPath] Draws a series of connected lines and curves.
- [DrawPie] Draws a pie shape, it needs a upper-left coordinate pair, a width, a height, and two radial lines.
- [DrawPolygon] Draws a multi sides shape by an array of Point structures.
- [DrawRectangle] Draws a square shape by a coordinate pair, a width, and a height.
- [DrawRectangles] Draws multiple rectangles by Rectangle structures.
- [DrawString] Draws a text string at the specified location, and specified Brush and Font.
on a form or other Windows Forms control.
The System.Drawing namespace is included in .NET Framework to deal with graphic stuff.
The System.Drawing namespace contains many classes and the most common ones are as following:
- [Graphics] is used to draw to display devices
- [Pen] is used to draw lines and curves
- [Brush] and other classes drived from it are used to fill shapes.
- ...
The System.Drawing namespace contains some structures too, and most important ones are as following:
- [Color] which represent a color
- [Point] that has x and y cordinates for a point in two dimensional plane.
- [Rectangle] it has four integer values that represent the location and size of
a rectangle.
- [Size] Stores width and height of a rectabgle by integer values.
- ...
How to draw a line or shape:
- Create a [Graphics] object, using System.Windows.Forms.Control.CreateGraphics method.
- Create a [Pen] object.
- Call a method from the Graphics object to draw a shape using the [Pen].
Some of the Graphics object methods:
- [Clear] Fills the entire drawing surface with a color.
- [DrawEllipse] Draws an ellipse or a circle by a pair of height and width.
- [DrawIcon] Draws image of an icon at specified coordinates.
- [DrawImage] Draws an image at specified coordinates.
- [DrawLine] Draws a line between two points.
- [DrawLines] Draws a series of lines by an array of Point structures.
- [DrawPath] Draws a series of connected lines and curves.
- [DrawPie] Draws a pie shape, it needs a upper-left coordinate pair, a width, a height, and two radial lines.
- [DrawPolygon] Draws a multi sides shape by an array of Point structures.
- [DrawRectangle] Draws a square shape by a coordinate pair, a width, and a height.
- [DrawRectangles] Draws multiple rectangles by Rectangle structures.
- [DrawString] Draws a text string at the specified location, and specified Brush and Font.
C# - System.Drawing namespace & Graphics Object
Tuesday, May 5, 2009
C# - Sample code - System.Xml.Serialization and XML serialization attributes
[XmlRoot ("Produts")]
public class product2Sell
{
[XmlAttribute] public int prdId;
public string prdName;
public decimal prdPrice;
public int prdQty;
public DateTime prdLastOrderDate;
[XmlIgnore] public DateTime prdLastShipDate;
public product2Sell()
{
}
}
private void btnXmlSerialize_Click(object sender, EventArgs e)
{
List
for (int i = 0; i < 3; i++)
{
product2Sell prdItem = new product2Sell();
prdItem.prdId = i;
prdItem.prdName = "Product" + i.ToString();
prdItem.prdPrice = i * 10.75m;
prdItem.prdQty = i * 3 + 5;
prdItem.prdLastOrderDate = DateTime.Now.AddDays(-i * 3);
prdItem.prdLastShipDate = DateTime.Now.AddDays(i * 2);
lstProduct.Add(prdItem);
}
string fName = @"C:\FB\Tst.data";
using (FileStream fs = new FileStream(fName, FileMode.Create))
{
XmlSerializer xs = new XmlSerializer( typeof(List
xs.Serialize(fs, lstProduct);
}
}
private void btnXmlDeserialize_Click(object sender, EventArgs e)
{
string fName = @"C:\FB\Tst.data";
using (FileStream fs = new FileStream(fName, FileMode.Open))
{
XmlSerializer xs =
new XmlSerializer(typeof(List
List
(List
MessageBox.Show("# of products: " + lstPrdItem.Count.ToString());
}
}
C# - Sample code - System.Xml.Serialization and XML serialization attributes
Sunday, May 3, 2009
C# - System.Xml.Serialization namespace
Let's review something about XML serialization first:
- It provides interoperability and communicability with different platform and also flexibility to conform to XML schema as a pattern.
- XML serialization can not be used to serialize private data.
- A class which wants to be serialized by XML serialization should be public and all members should be defined as public too, and you have to create a parameterless constructor for that class.
- Arrays, collections, Data sets, instances of XmlElement or XmlNote class can be serialized with XmlSerializer
XML Serialization Attributes
It's possible to use attributes to create XML documents that conform to specific standards.
Example:
- [XmlIgnore] in front of a public properties and fields will cuase to ignore it when the class is serialized, it's similar to [NonSerialized] attribute in standard serialization.
- [AmlAttribute] will cause to consider the serialized member as XML attribute.
For more details and to see the list of attributes, please look at the following URL:
XmlAttributes Members
- It provides interoperability and communicability with different platform and also flexibility to conform to XML schema as a pattern.
- XML serialization can not be used to serialize private data.
- A class which wants to be serialized by XML serialization should be public and all members should be defined as public too, and you have to create a parameterless constructor for that class.
- Arrays, collections, Data sets, instances of XmlElement or XmlNote class can be serialized with XmlSerializer
XML Serialization Attributes
It's possible to use attributes to create XML documents that conform to specific standards.
Example:
- [XmlIgnore] in front of a public properties and fields will cuase to ignore it when the class is serialized, it's similar to [NonSerialized] attribute in standard serialization.
- [AmlAttribute] will cause to consider the serialized member as XML attribute.
For more details and to see the list of attributes, please look at the following URL:
XmlAttributes Members
C# - System.Xml.Serialization namespace
Saturday, May 2, 2009
C# - System.Runtime.Serialization namespace
Serialization is the process of converting data into a byte stream that can be stored or transferred. The rule is to use BinarryFormatter for the best efficiency and SoapFormatter when you require portability, SoapFormatter provides less efficient but more interoperable rather than BinaryFormatter. There are two classes for formatting serialized data in the System.Runtime.Serialization namespace:
* BinaryFormatter
It's the most efficient way to serialize objetcs that will be available to use just by .NET Frameworkbased applications. If you are sure that your client opens the serialized objects by a .NET Framework application, BinaryFormatter would be the best.
* SoapFormatter
it's located in System.Runtime.Serialization.Formatters.Soap, and is reliable way to serialize objects that will bbe transmitted across a network or read by a non .NET Framework based application. SoapFormatter can work instead of BinaryFormatter too but the serialized object consume considerabaly more space. SOAP WEB services were the primarily target for SoapFormatter and even though that it can format data using Xml, but the most flexible way to perform serialization is using XML serialization for such a kind of situations.
SoapFormatter is not included as default like BinaryFormatter and you need to add System.Runtime.Serialization.Formatters.Soap.dll as reference.
C# - System.Runtime.Serialization namespace
Friday, May 1, 2009
C# - How to implement OnDeserialization for [Serializable] class with [NonSerialized] members
[Serializable]
class ProductItem : IDeserializationCallback
{
#region Fields
private int prdId;
private string prdName;
private decimal prdPrice;
[NonSerialized] private decimal prdTax;
#endregion
#region Properties
public int PrdId
{
get { return prdId; }
set { prdId = value; }
}
public string PrdName
{
get { return prdName; }
set { prdName = value; }
}
public decimal PrdPrice
{
get { return prdPrice; }
set { prdPrice = value; }
}
public decimal PrdTax
{
get { return prdTax; }
set { prdTax = value; }
}
#endregion
public ProductItem(int _prdId, string _prdName, decimal _prdPrice)
{
PrdId = _prdId;
PrdName = _prdName;
PrdPrice = _prdPrice;
PrdTax = _prdPrice * 0.12m;
}
void IDeserializationCallback.OnDeserialization(object sender)
{
// Calculate tax after deserialization completes
PrdTax = PrdPrice * 0.12m;
}
}
private void btnSerializeCallBack_Click(object sender, EventArgs e)
{
ProductItem prdItemObj = new ProductItem(1, "Cranker", 10);
string fName = @"C:\FB\Tst.data";
using (FileStream fs = new FileStream(fName, FileMode.Create))
{
SoapFormatter sf = new SoapFormatter();
sf.Serialize(fs, prdItemObj);
}
}
private void btnDeSerializeCallBack_Click(object sender, EventArgs e)
{
string fName = @"C:\FB\Tst.data";
using (FileStream fs = new FileStream(fName, FileMode.Open))
{
SoapFormatter sf = new SoapFormatter();
ProductItem prdItemObj = (ProductItem)sf.Deserialize(fs);
}
}
C# - How to implement OnDeserialization for [Serializable] class with [NonSerialized] members
Thursday, April 30, 2009
C# - How to Serialize/Deserialize
As you know, when you want to send an object to another process, or transmit an object across the network (LAN, Intranet, WAN, Internet), you need to "serialize" the object. Serialization is the process of converting an object into a linear sequence of bytes and Deserialization is the process of converting a previously serialized sequence of bytes into an object.
Serialization has been a key part of .NET since version 1.0 and .NET Framework, implemented "Serialization" in the "System.Runtime.Serialization" namespace, and to serialize an object you can choose between, Binary, SOAP, XML, and custom serialization. There are libraries to serialize to special formats like comma delimited, etc ... too.
C# - How to Create a serializable (and deserializable) custom class
You need to add [Serializable] attribute to your class. The default handling of serialization, serialize all the members, including private members.
It's possible to customize and control serialization of your class depends on custom requirements either to improve efficiency.
C# - How to disable serialization of a member
Just add [NonSerialized] attribute in front of the specific member, it causes to exclude that member from serialized version of the object. sometimes, we need to reduce the size of our object to transfer it across the network then you can bypass calculable members and regenerate them all back in destination.
To enable your class to initialize the [NonSerialized] members automatically use OnDeserialization, this method will be called after deserializing is complete.
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
...
private void btnSerialize_Click(object sender, EventArgs e)
{
string fName = @"C:\FB\Tst.data";
using (FileStream fs = new FileStream(fName, FileMode.Create))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, txt4Serialization.Text);
}
}
private void btnDeSerialize_Click(object sender, EventArgs e)
{
string fName = @"C:\FB\Tst.data";
using (FileStream fs = new FileStream(fName, FileMode.Open))
{
BinaryFormatter bf = new BinaryFormatter();
txtDeserialized.Text = (string)bf.Deserialize(fs);
}
}
Serialization has been a key part of .NET since version 1.0 and .NET Framework, implemented "Serialization" in the "System.Runtime.Serialization" namespace, and to serialize an object you can choose between, Binary, SOAP, XML, and custom serialization. There are libraries to serialize to special formats like comma delimited, etc ... too.
C# - How to Create a serializable (and deserializable) custom class
You need to add [Serializable] attribute to your class. The default handling of serialization, serialize all the members, including private members.
It's possible to customize and control serialization of your class depends on custom requirements either to improve efficiency.
C# - How to disable serialization of a member
Just add [NonSerialized] attribute in front of the specific member, it causes to exclude that member from serialized version of the object. sometimes, we need to reduce the size of our object to transfer it across the network then you can bypass calculable members and regenerate them all back in destination.
To enable your class to initialize the [NonSerialized] members automatically use OnDeserialization, this method will be called after deserializing is complete.
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
...
private void btnSerialize_Click(object sender, EventArgs e)
{
string fName = @"C:\FB\Tst.data";
using (FileStream fs = new FileStream(fName, FileMode.Create))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, txt4Serialization.Text);
}
}
private void btnDeSerialize_Click(object sender, EventArgs e)
{
string fName = @"C:\FB\Tst.data";
using (FileStream fs = new FileStream(fName, FileMode.Open))
{
BinaryFormatter bf = new BinaryFormatter();
txtDeserialized.Text = (string)bf.Deserialize(fs);
}
}
C# - How to Serialize/Deserialize
Monday, April 27, 2009
C# - How to have a reverse ordered Generic SortedList collection
The folowing code sample creates a generic SortedList
A System.Collections.Generic.IComparer to sort based on DateTime in reverse order:
...
using System.Collections;
using System.Collections.Generic;
...
public class DecendingDateCompare : IComparer
{
public int Compare(DateTime x, DateTime y)
{
return x.CompareTo(y) * -1;
}
}
A sample code to test:
...
using System.Collections;
using System.Collections.Generic;
...
SortedList
new SortedList
aSortedList.Add(DateTime.Now.AddDays(-10), 100);
aSortedList.Add(DateTime.Now.AddDays(10), 10);
aSortedList.Add(DateTime.Now.AddDays(-5), 90);
aSortedList.Add(DateTime.Now.AddDays(5), 20);
aSortedList.Add(DateTime.Now.AddDays(-3), 80);
aSortedList.Add(DateTime.Now.AddDays(3), 30);
StringBuilder sb = new StringBuilder();
IDictionaryEnumerator iDicEnum =
(IDictionaryEnumerator) aSortedList.GetEnumerator();
while( iDicEnum.MoveNext() )
sb.AppendLine( iDicEnum.Key.ToString() +
", " +
iDicEnum.Value.ToString() );
MessageBox.Show(sb.ToString());
C# - How to have a reverse ordered Generic SortedList
Friday, April 24, 2009
Regex - Expresso - winning regular expression development tool
Expresso is a free regular expression development tool. It's full-featured development environment for the experienced programmer who wants to code with knowledge of regular expressions and needs to test, analyze, and generate applicable and accurate regular expressions. Expresso code by Jim Hollenhorst.
It's an integrated regular expression editor, tester, analyzer with rich library of regular expressions ready to use for different categories.
To find out its features, look at the following link:
http://www.ultrapico.com/Expresso.htm
To download:
http://www.ultrapico.com/ExpressoDownload.htm
More links:
Expresso in www.codeproject.com
http://www.codeproject.com/KB/dotnet/expresso.aspx
The 30 Minute Regex Tutorial (by Jim Hollenhorst)
http://www.codeproject.com/KB/dotnet/regextutorial.aspx
Regex - Expresso - winning regular expression development tool
Wednesday, April 22, 2009
C# - A class to fade a Form
.Opacity property of form is a number between 0 and 1 (default), then if you change it from 1 to some lower values, you reduced the opacity. In the following sample, the formFader class contains a Static FormFaderWithStep method which accept the target form and another argument between 0 to 255 that show the number of steps which you want to fade your form base on it.
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace tstBed
{
class formFader
{
public static void FormFaderWithStep(Form frm2Fade,
byte fadeNumOfSteps)
{
if ( (frm2Fade.Opacity != 1) || (fadeNumOfSteps < 1) )
return;
double fadeStep = frm2Fade.Opacity / fadeNumOfSteps;
for( byte iCntr = 0; iCntr < fadeNumOfSteps; iCntr ++ )
{
frm2Fade.Opacity -= fadeStep;
frm2Fade.Refresh();
}
}
}
}
Now just you need to find override version of Dispose event in your form designer code file for your form class (Example: form1.Designer.cs) and add a line to call the fader method, for example: formFader.FormFaderWithStep(this, 100);
protected override void Dispose(bool disposing)
{
formFader.FormFaderWithStep(this, 100);
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace tstBed
{
class formFader
{
public static void FormFaderWithStep(Form frm2Fade,
byte fadeNumOfSteps)
{
if ( (frm2Fade.Opacity != 1) || (fadeNumOfSteps < 1) )
return;
double fadeStep = frm2Fade.Opacity / fadeNumOfSteps;
for( byte iCntr = 0; iCntr < fadeNumOfSteps; iCntr ++ )
{
frm2Fade.Opacity -= fadeStep;
frm2Fade.Refresh();
}
}
}
}
Now just you need to find override version of Dispose event in your form designer code file for your form class (Example: form1.Designer.cs) and add a line to call the fader method, for example: formFader.FormFaderWithStep(this, 100);
protected override void Dispose(bool disposing)
{
formFader.FormFaderWithStep(this, 100);
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
C# - A class to fade a Form
Tuesday, April 21, 2009
C# - A custom DataGridView class with always vertical scroll bar visible
Depend on the data which you want to show in a DataGridView, sometimes you need to keep vertical scroll bars always visible. If you don't have enough row to fill the DataGridView vertically, and you aligned and configured the columns' width for situations which data show with vertical scroll bar, then it's better to show the bar always.
The only thing which you need to do the job, is to set the VerticalScrollBar.Visible property to "true" in VisibleChanged event. I added dgvSetVerticalBar to fix the position of scroll bar, and it's necessary to call it in Load event of form which contains this custom DataGridView.
using System;
using System.Text;
using System.Windows.Forms;
using System.Collections.Generic;
namespace myNameSpace
{
public partial class myCustomDGV : DataGridView
{
public myCustomDGV()
{
// InitializeComponent();
this.VerticalScrollBar.Visible = true;
this.VerticalScrollBar.VisibleChanged +=
new EventHandler(VerticalScrollBar_VisibleChanged);
this.AllowUserToOrderColumns = false;
this.AllowUserToResizeColumns = false;
this.AllowUserToResizeRows = false;
this.RowHeadersVisible = false;
}
void VerticalScrollBar_VisibleChanged(object sender, EventArgs e)
{
this.VerticalScrollBar.Visible = true;
}
public void dgvSetVerticalBar()
{
this.VerticalScrollBar.SetBounds(
this.Width - this.VerticalScrollBar.Width - 1,
this.VerticalScrollBar.Location.Y + 1,
this.VerticalScrollBar.Width,
this.Height - 2);
}
}
}
The only thing which you need to do the job, is to set the VerticalScrollBar.Visible property to "true" in VisibleChanged event. I added dgvSetVerticalBar to fix the position of scroll bar, and it's necessary to call it in Load event of form which contains this custom DataGridView.
using System;
using System.Text;
using System.Windows.Forms;
using System.Collections.Generic;
namespace myNameSpace
{
public partial class myCustomDGV : DataGridView
{
public myCustomDGV()
{
// InitializeComponent();
this.VerticalScrollBar.Visible = true;
this.VerticalScrollBar.VisibleChanged +=
new EventHandler(VerticalScrollBar_VisibleChanged);
this.AllowUserToOrderColumns = false;
this.AllowUserToResizeColumns = false;
this.AllowUserToResizeRows = false;
this.RowHeadersVisible = false;
}
void VerticalScrollBar_VisibleChanged(object sender, EventArgs e)
{
this.VerticalScrollBar.Visible = true;
}
public void dgvSetVerticalBar()
{
this.VerticalScrollBar.SetBounds(
this.Width - this.VerticalScrollBar.Width - 1,
this.VerticalScrollBar.Location.Y + 1,
this.VerticalScrollBar.Width,
this.Height - 2);
}
}
}
C# - A custom DataGridView class with always vertical scroll bar visible
Subscribe to:
Posts (Atom)