Tag Archive for c

Represent int as hex with leading zeros

Console.WriteLine("|0123456789|
|{0,10}|", 47.ToString("X4"));
// produces the output
// |0123456789|
// |      002F|

source

C# proxy for JavaScript applications

<%@ WebHandler Language="C#" Class="proxy" %>
/*
This proxy page does not have any security checks. It is highly recommended
that a user deploying this proxy page on their web server, add appropriate
security checks, for example checking request path, username/password, target
url, etc.
*/
using System;
using System.Web;

public class proxy : IHttpHandler {

public void ProcessRequest (HttpContext context) {

string uri = context.Request.QueryString[0];
System.Net.WebRequest req = System.Net.WebRequest.Create(new Uri(uri));
req.Method = context.Request.HttpMethod;

byte[] bytes = new byte[context.Request.InputStream.Length];
context.Request.InputStream.Read(bytes,0,(int)context.Request.InputStream.Length);
req.ContentLength = bytes.Length;
req.ContentType = "application/x-www-form-urlencoded";
System.IO.Stream outputStream = req.GetRequestStream();
outputStream.Write(bytes, 0, bytes.Length);
outputStream.Close();

System.Net.WebResponse res = req.GetResponse();
context.Response.ContentType = res.ContentType;

System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream());
string strResponse = sr.ReadToEnd();
context.Response.Write(strResponse);
context.Response.End();
}

public bool IsReusable {
get {
return false;
}
}

}

source

Clean up braces in many languages

/([s	]*[
]+[s	]*{)/ {/gi

source

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