Tag Archive for c

PropertyGrid values in hex/hexadecimal using class derived from TypeConverter

// Included...
// [1] Define TypeConverter class for hex.
// [2] use it when defining a member of a data class using attribute TypeConverter.
// [3] Connect the data class to a PropertyGrid.


// [1] define UInt32HexTypeConverter is-a TypeConverter
public class UInt32HexTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
else
{
return base.CanConvertFrom(context, sourceType);
}
}

public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
{
return true;
}
else
{
return base.CanConvertTo(context, destinationType);
}
}

public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string) && value.GetType() == typeof(UInt32))
{
return string.Format("0x{0:X8}", value);
}
else
{
return base.ConvertTo(context, culture, value, destinationType);
}
}

public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value.GetType() == typeof(string))
{
string input = (string)value;

if (input.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
{
input = input.Substring(2);
}

return UInt32.Parse(input, System.Globalization.NumberStyles.HexNumber, culture);
}
else
{
return base.ConvertFrom(context, culture, value);
}
}
} // UInt32HexTypeConverter used by grid to display hex.


// [2] define a class for data to be associated with the PropertyGrid.
[DefaultPropertyAttribute("Name")]
public class Data
.
.
.
public UInt32 stat;
[CategoryAttribute("Main Scanner"), DescriptionAttribute("Status"), TypeConverter(typeof(UInt32HexTypeConverter))]
public UInt32 Status
{
get { return stat; }
}
.
.
.
// [3] reference data for propertyGrid. (here, myData is a Data).
propertyGrid1.SelectedObject = myData ;

source

Break nsstring into array

Found this at <a href="http://borkware.com/quickies/one?topic=NSString" >http://borkware.com/quickies/one?topic=NSString</a> (useful link):

NSString *string = @"oop:ack:bork:greeble:ponies";
NSArray *chunks = [string componentsSeparatedByString: @":"];

Hope this helps!

Adam

source

Minimalist XSLT Transform Using Two Strings

public string TransformXML(string xml, string xslt)
{
string output = string.Empty;

XPathDocument xpd = new XPathDocument(new StringReader(xml));

XslCompiledTransform transform = new XslCompiledTransform(true);
transform.Load(new XmlTextReader(xslt, XmlNodeType.Document, null));

StringWriter sr = new StringWriter();
transform.Transform(xpd.CreateNavigator(), null, sr);
output = sr.ToString();

return output;
}


//Note that the XSL needs namespace prefixes to make .Net happy:

xsl = @"<xsl:stylesheet version='1.0'
xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:output method='text'/>
<xsl:template match='msg'>Found it!</xsl:template>
</xsl:stylesheet>";


xml = @"<msg/>";

source

Singleton

/**
* file Singleton.h
* rief The Singleton design pattern using templates.
* author Justin Chouinard <justin@chouinardconsulting.com>
*
***********************************************************************
* MyClass.h:
***********************************************************************
*
* class MyClass : public Singleton<MyClass>
* {
* ..
* }
*
***********************************************************************
* MyClass.cc
***********************************************************************
*
* MyClass *Singleton<MyClass>::inst = 0;
*
***********************************************************************
* Others
***********************************************************************
* Other files may access the instance by calling MyClass::getInstance().
*
**/


#ifndef __SINGLETON_H__
#define __SINGLETON_H__

template <class Type>
class Singleton
{
public:
static Type *getInstance(void);
private:
static Type *inst;
};	// end of class Singleton

template <class Type>
Type *Singleton<Type>::getInstance(void)
{
if (inst == 0)
inst = new Type;

return inst;
}

template <class Type>
Type *Singleton<Type>::inst = 0;

#endif // __SINGLETON_H__

source

DataGridView DataBind an Array of Arbitrary Objects

Foo[] foos = new Foo[2];
DataGridView1.DataSource = foos;


//This works.
public class FooGood
{
public string Bar { get; set; }
public string Baz { get; set; }
}
//This Doesn't
public class FooBad
{
public string Bar;
public string Baz;
}

source

Four Char Code From String in Python

def makeNumberFromCharCode(code):
return (ord(code[0]) << 24) | (ord(code[1]) << 16) | (ord(code[2]) << 8) | ord(code[3])

# In Carbon / Cocoa:
# FourCharCode code = 'abcd'
# In Python:
# code = makeNumberFromCharCode("abcd")

source

C# Call Web Service and Get String Result

public string getServiceResult(string serviceUrl) {
HttpWebRequest HttpWReq;
HttpWebResponse HttpWResp;
HttpWReq = (HttpWebRequest)WebRequest.Create(serviceUrl);
HttpWReq.Method = "GET";
HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
if (HttpWResp.StatusCode == HttpStatusCode.OK)
{
//Consume webservice with basic XML reading, assumes it returns (one) string
XmlReader reader = XmlReader.Create(HttpWResp.GetResponseStream());
while (reader.Read())
{
reader.MoveToFirstAttribute();
if (reader.NodeType == XmlNodeType.Text)
{
return reader.Value;
}
}
return String.Empty;
}
else
{
throw new Exception("Error on remote IP to Country service: "+ HttpWResp.StatusCode.ToString());
}
}

source

SqlTransaction

SqlConnectionStringBuilder DarthServerConnection = new SqlConnectionStringBuilder();

DarthServerConnection.DataSource = "DarthServer";
DarthServerConnection.InitialCatalog = "DeathStarDB1";
DarthServerConnection.UserID = "tk421";
DarthServerConnection.Password = "tr00p3r";

using ( SqlConnection DeathStarDatabase = new SqlConnection( DarthServerConnection.ToString() ) )
{
// The using statment will call dispose and close the connection.
DeathStarDatabase.Open();

SqlTransaction SaveHeroes = DeathStarDatabase.BeginTransaction();

string ShutDownSql = "UPDATE GarbageDisposal SET Status = 'Shut Down'";
string OpenDoorSql = "UPDATE GarbageDisposal SET Door = 'Open' WHERE GarbageDisposalID = 3263827";

try
{
// Shut down the garbage disposal units on the detention level! No! Shut them all down!
SqlCommand ShutDown = new SqlCommand( ShutDownSql, DeathStarDatabase, SaveHeroes );
ShutDown.ExecuteNonQuery();

// We're alive. Open the door to 3263827.
SqlCommand OpenDoor = new SqlCommand( OpenDoorSql, DeathStarDatabase, SaveHeroes );
OpenDoor.ExecuteNonQuery();

SaveHeroes.Commit();
}
catch ( Exception error )
{
SaveHeroes.Rollback();

MailMessage RescueEmail = new MailMessage( "R2D2@YavinIV.org", "Rebels@YavinIV.org" );

RescueEmail.Subject = "Error while Saving Heroes";
RescueEmail.Body = "An error has occured while attempting to save the following heroes:

"
+ "Luke, Leia, Han, and Chewbacca.

"
+ "The SQL statements that attempted to execute were:

"
+ ShutDownSql + "

"
+ OpenDoorSql + "

"
+ "The error:

"
+ error.ToString() + "

"
+ "Result:

"
+ "The heroes were not saved.

"
+ "Action Item:

"
+ "Please rescue R2D2 and C3PO from the Death Star.";

SmtpClient YavinIVMail = new SmtpClient();

YavinIVMail.Host = "mail.yaviniv.org";
YavinIVMail.Credentials = CredentialCache.DefaultNetworkCredentials;
YavinIVMail.Send( RescueEmail );
}
}

source

C# String Formats

int MySalary = 123456;

String.Format( "{0:C}", MySalary ); // $123,456.00
String.Format( "{0:D}", MySalary ); // 123456
String.Format( "{0:E}", MySalary ); // 1.234560E+005
String.Format( "{0:F}", MySalary ); // 123456.00
String.Format( "{0:G}", MySalary ); // 123456
String.Format( "{0:N}", MySalary ); // 123,456.00
String.Format( "{0:X}", MySalary ); // 1E240
String.Format( "{0:#%}", MySalary ); // 12345600%
String.Format( "{0:#,###}", MySalary ); // 123,456
String.Format( "{0:#,###.00}", MySalary ); // 123,456.00
String.Format( "{0:#,###.##}", MySalary ); // 123,456
String.Format( "{0:'$'#,###.00}", MySalary ); // $123,456.00
String.Format( "{0:#,###' lbs'}", MySalary ); // 123,456 lbs

MySalary = -123456;
String.Format( "{0:#0}", MySalary ); // -123456
String.Format( "{0:#0;(#0)}", MySalary ); // (123456)

DateTime.Now.ToString( "yyyy-MM-ddTHH:MM:ss" ); // XSD:DateTime format 2009-05-16T10:05:46

source

C# Reading a File

string DeathStarPlans = @"C:DeathStarPlans.txt";

StringBuilder R2D2 = new StringBuilder();

using ( StreamReader PrincessLeia = new StreamReader( DeathStarPlans ) )
{
while ( PrincessLeia.Peek() >= 0 )
{
R2D2.Append( PrincessLeia.ReadLine() );
}
}

source