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:

...
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
Share/Bookmark

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/
Share/Bookmark

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 &lt;
> to &gt;
& to &amp;

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)
Share/Bookmark

Monday, July 27, 2009

C# - Validate XML document against a Schema - XmlReaderSettings

Sample code for Validate XML document against a Schema:

...
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>

Share/Bookmark

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");

Share/Bookmark

Tuesday, July 21, 2009

.NET - Event Log


Share/Bookmark

Sunday, July 19, 2009

C# - Application Doman


Share/Bookmark

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)
Share/Bookmark

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/
Share/Bookmark

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

Share/Bookmark

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;
}
}
...

Share/Bookmark

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);
...

Share/Bookmark

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
}

Share/Bookmark