I was developing C#/SQL code generator and i was struggling little bit how to add double quote (") in C# .. and this is how
string selectCommand = string.Format("command.CommandText = \"SELECT * FROM [{0}]\";", entity.TableName));
Tuesday, December 16, 2008
Wednesday, August 13, 2008
Descending sortedList by value
sorted lists are normally sorted by key not value in ascending order. this is how to create a sorted list by value in descending order
class DescendingComparer : IComparer
{
public int Compare(object x, object y)
{
try
{
return System.Convert.ToInt32(x).CompareTo(System.Convert.ToInt32(y)) * -1;
}
catch (Exception ex)
{
return x.ToString().CompareTo(y.ToString());
}
}
}
class KeySortedList : SortedList
{
public SortedList ReversedList = new SortedList(new DescendingComparer());
public new void Add(object key, object value)
{
ReversedList.Add(value, key);
base.Add(key, value);
}
}
class DescendingComparer : IComparer
{
public int Compare(object x, object y)
{
try
{
return System.Convert.ToInt32(x).CompareTo(System.Convert.ToInt32(y)) * -1;
}
catch (Exception ex)
{
return x.ToString().CompareTo(y.ToString());
}
}
}
class KeySortedList : SortedList
{
public SortedList ReversedList = new SortedList(new DescendingComparer());
public new void Add(object key, object value)
{
ReversedList.Add(value, key);
base.Add(key, value);
}
}
Thursday, August 07, 2008
Undefined function 'CONVERT' in expression issue in Office 12
you might get a "Undefined function 'CONVERT' in expression" in Crystal Reports if you are using Office 12 Access DB, to correct this you have to convert the left hand function,
eg,
Undefined function 'CONVERT' in expression "Crystal Reports"
CDATE({ERYTHROCYTE_SEDIMENTATION_RATE_HEADER.COLLECT_DATE}) >= cdate (2008, 07, 05)
to fix the problem, good luck
eg,
Undefined function 'CONVERT' in expression "Crystal Reports"
CDATE({ERYTHROCYTE_SEDIMENTATION_RATE_HEADER.COLLECT_DATE}) >= cdate (2008, 07, 05)
to fix the problem, good luck
Monday, August 04, 2008
snapshot C# using PaintEventArgs
In RichFocus we had a problem to get the control image. We used old print screen methods to do this before, and it captures the whole thing with the windows on top of the control ... so I decided to use the OnPaint method to re-draw it for us.
// Inside snapshot control ...
Rectangle rect = this.ClientRectangle;
//create an empty image with the same size of the control
Bitmap bmp = new Bitmap(rect.Width, rect.Height);
Graphics g = Graphics.FromImage(bmp);
PaintEventArgs p= new PaintEventArgs(g, rect);
// paint the background,
this.InvokePaintBackground(this, p);
// this will invoke the control paint method
this.InvokePaint(this, p);
// Inside snapshot control ...
Rectangle rect = this.ClientRectangle;
//create an empty image with the same size of the control
Bitmap bmp = new Bitmap(rect.Width, rect.Height);
Graphics g = Graphics.FromImage(bmp);
PaintEventArgs p= new PaintEventArgs(g, rect);
// paint the background,
this.InvokePaintBackground(this, p);
// this will invoke the control paint method
this.InvokePaint(this, p);
Thursday, July 24, 2008
Sends the mail message asynchronously
public static void SendMailMessageAsync()
{
ThreadStart threadStart = delegate { SendMailMessage(); };
Thread thread = new Thread(threadStart);
thread.Start();
}
{
ThreadStart threadStart = delegate { SendMailMessage(); };
Thread thread = new Thread(threadStart);
thread.Start();
}
Wednesday, July 23, 2008
?? operator in C#
I found this C# today it's rock !!
string thisIsANull = null;
string thisIsANullCheck = thisIsANull ?? "";
thisIsANullCheck is set to ""
string thisIsANull = null;
string thisIsANullCheck = thisIsANull ?? "";
thisIsANullCheck is set to ""
Friday, February 15, 2008
descending sorting in SortedList
by default when you add an element to SortedList it's added in ascending order, for descending for you have to use a small trick.
internal class DescendingComparer : IComparer
{
public int Compare(object x, object y)
{
try
{
return System.Convert.ToInt32(x).CompareTo(System.Convert.ToInt32(y)) * -1;
}
catch (Exception ex)
{
return x.ToString().CompareTo(y.ToString());
}
}
}
SortedList membersList = new SortedList(new DescendingComparer());
membersList.Add()
internal class DescendingComparer : IComparer
{
public int Compare(object x, object y)
{
try
{
return System.Convert.ToInt32(x).CompareTo(System.Convert.ToInt32(y)) * -1;
}
catch (Exception ex)
{
return x.ToString().CompareTo(y.ToString());
}
}
}
SortedList membersList = new SortedList(new DescendingComparer());
membersList.Add()
Monday, January 21, 2008
Tuesday, November 20, 2007
easy way to make money !!
One of my friends told me this, but i never though people are earning more than 25k USD for a day ??? idea is simple, buy credit say woth 500 USD, and exchange it against depreciating currencies... for an example $ is deprecating alot these days so, you can buy GBP against USD and exchange it then in real time basis. I brought 500 USD and made 750 USD in 5 mins !! ohh yeah in the demo mode ;) this grate software is "eToro".
Friday, October 26, 2007
Tuesday, October 23, 2007
How to write settings to App.config(Configuration in C# .NET 2.0)
System.Configuration.Configuration config =ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["IP"].Value = "3";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
yeap this is the microsoft example. doesn't work at all. !!! dont get caught this never works. I was trying hours and hours,
use this class .
public enum ConfigFileType
{
WebConfig,
AppConfig
}
public class AppConfig : System.Configuration.AppSettingsReader
{
public string docName = String.Empty;
private XmlNode node = null;
private int _configType;
public int ConfigType
{
get
{
return _configType;
}
set
{
_configType = value;
}
}
public bool SetValue(string key, string value)
{
XmlDocument cfgDoc = new XmlDocument();
loadConfigDoc(cfgDoc);
// retrieve the appSettings node
node = cfgDoc.SelectSingleNode("//appSettings");
if (node == null)
{
throw new System.InvalidOperationException("appSettings section not found");
}
try
{
// XPath select setting "add" element that contains this key
XmlElement addElem = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
if (addElem != null)
{
addElem.SetAttribute("value", value);
}
// not found, so we need to add the element, key and value
else
{
XmlElement entry = cfgDoc.CreateElement("add");
entry.SetAttribute("key", key);
entry.SetAttribute("value", value);
node.AppendChild(entry);
}
//save it
saveConfigDoc(cfgDoc, docName);
return true;
}
catch
{
return false;
}
}
private void saveConfigDoc(XmlDocument cfgDoc, string cfgDocPath)
{
try
{
XmlTextWriter writer = new XmlTextWriter(cfgDocPath, null);
writer.Formatting = Formatting.Indented;
cfgDoc.WriteTo(writer);
writer.Flush();
writer.Close();
return;
}
catch
{
throw;
}
}
public bool removeElement(string elementKey)
{
try
{
XmlDocument cfgDoc = new XmlDocument();
loadConfigDoc(cfgDoc);
// retrieve the appSettings node
node = cfgDoc.SelectSingleNode("//appSettings");
if (node == null)
{
throw new System.InvalidOperationException("appSettings section not found");
}
// XPath select setting "add" element that contains this key to remove
node.RemoveChild(node.SelectSingleNode("//add[@key='" + elementKey + "']"));
saveConfigDoc(cfgDoc, docName);
return true;
}
catch
{
return false;
}
}
private XmlDocument loadConfigDoc(XmlDocument cfgDoc)
{
// load the config file
if (Convert.ToInt32(ConfigType) == Convert.ToInt32(ConfigFileType.AppConfig))
{
docName = ((Assembly.GetEntryAssembly()).GetName()).Name;
docName += ".exe.config";
}
else
{
// docName = System.Web.HttpContext.Current.Server.MapPath("web.config");
}
cfgDoc.Load(docName);
return cfgDoc;
}
}
==========================
Eg
AppConfig a = new AppConfig();
a.ConfigType = 1;
a.SetValue("IP", "123132123123");
============================
config.AppSettings.Settings["IP"].Value = "3";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
yeap this is the microsoft example. doesn't work at all. !!! dont get caught this never works. I was trying hours and hours,
use this class .
public enum ConfigFileType
{
WebConfig,
AppConfig
}
public class AppConfig : System.Configuration.AppSettingsReader
{
public string docName = String.Empty;
private XmlNode node = null;
private int _configType;
public int ConfigType
{
get
{
return _configType;
}
set
{
_configType = value;
}
}
public bool SetValue(string key, string value)
{
XmlDocument cfgDoc = new XmlDocument();
loadConfigDoc(cfgDoc);
// retrieve the appSettings node
node = cfgDoc.SelectSingleNode("//appSettings");
if (node == null)
{
throw new System.InvalidOperationException("appSettings section not found");
}
try
{
// XPath select setting "add" element that contains this key
XmlElement addElem = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
if (addElem != null)
{
addElem.SetAttribute("value", value);
}
// not found, so we need to add the element, key and value
else
{
XmlElement entry = cfgDoc.CreateElement("add");
entry.SetAttribute("key", key);
entry.SetAttribute("value", value);
node.AppendChild(entry);
}
//save it
saveConfigDoc(cfgDoc, docName);
return true;
}
catch
{
return false;
}
}
private void saveConfigDoc(XmlDocument cfgDoc, string cfgDocPath)
{
try
{
XmlTextWriter writer = new XmlTextWriter(cfgDocPath, null);
writer.Formatting = Formatting.Indented;
cfgDoc.WriteTo(writer);
writer.Flush();
writer.Close();
return;
}
catch
{
throw;
}
}
public bool removeElement(string elementKey)
{
try
{
XmlDocument cfgDoc = new XmlDocument();
loadConfigDoc(cfgDoc);
// retrieve the appSettings node
node = cfgDoc.SelectSingleNode("//appSettings");
if (node == null)
{
throw new System.InvalidOperationException("appSettings section not found");
}
// XPath select setting "add" element that contains this key to remove
node.RemoveChild(node.SelectSingleNode("//add[@key='" + elementKey + "']"));
saveConfigDoc(cfgDoc, docName);
return true;
}
catch
{
return false;
}
}
private XmlDocument loadConfigDoc(XmlDocument cfgDoc)
{
// load the config file
if (Convert.ToInt32(ConfigType) == Convert.ToInt32(ConfigFileType.AppConfig))
{
docName = ((Assembly.GetEntryAssembly()).GetName()).Name;
docName += ".exe.config";
}
else
{
// docName = System.Web.HttpContext.Current.Server.MapPath("web.config");
}
cfgDoc.Load(docName);
return cfgDoc;
}
}
==========================
Eg
AppConfig a = new AppConfig();
a.ConfigType = 1;
a.SetValue("IP", "123132123123");
============================
Monday, October 22, 2007
weekend
It's been some time since my last post. Last weekend i spent most of the time watching One Tree Hill season 4. Nothing much interesting comparing to season 3 I guess. Brooke breaks up with Lucas, and move on with their life's.
Thursday, October 18, 2007
ClickOnce on Vista
I was assigned to check Richfocus on vista using ClickOnce installation. since we need administration rights on Vista pc to install keybordhooks, I deceied to use
inside the manifest.... after that lots of issues started
1. The requested operation requires elevation
2. Execution level requested by the application is not supported.
are two common error in this field.
When i googled it, it says due to some security issues, it's not allowed to have admin previlage user context inside.
only solution for this problem is to re-run the exe file using shell command. :)
hope you guys will not waste time on this.. !
inside the manifest.... after that lots of issues started
1. The requested operation requires elevation
2. Execution level requested by the application is not supported.
are two common error in this field.
When i googled it, it says due to some security issues, it's not allowed to have admin previlage user context inside.
only solution for this problem is to re-run the exe file using shell command. :)
hope you guys will not waste time on this.. !
Tuesday, October 16, 2007
Vista Crack
I wanted to install Vista 64 bit version on one of the testing PCs to test RichFocus. when i tried to apply the crack it fails. To make it work you have to disable "User Account Control (UAC)" which protects Registry, services ext,
Turn Off or Disable User Account Control (UAC) in Windows Vista
then you have to apply this crack :)
Turn Off or Disable User Account Control (UAC) in Windows Vista
then you have to apply this crack :)
Unicode bug in RichTextBox
i found this today so i though of blogging it. there is a bug in the "_doc.Append" in the extended richtextbox. you have to replace that from this to work
replace:
_doc.Append(_text.Replace("\n", @"\par "));
with this:
string Text = _text.Replace("\n", @"\par ");
char[] chars = Text.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
if ((int)chars[i] > 256)
{
_doc.AppendFormat(@"\u" + ((int)chars[i]).ToString() + "?");
}
else
{
_doc.Append(chars[i].ToString());
}
}
replace:
_doc.Append(_text.Replace("\n", @"\par "));
with this:
string Text = _text.Replace("\n", @"\par ");
char[] chars = Text.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
if ((int)chars[i] > 256)
{
_doc.AppendFormat(@"\u" + ((int)chars[i]).ToString() + "?");
}
else
{
_doc.Append(chars[i].ToString());
}
}
Thursday, October 04, 2007
top most control in .NET
well in VB 6 we had zorder? in .net it's not there any more. if you want to set the top most control you have to use Controls.SetChildIndex(control, 0)
Tuesday, October 02, 2007
System.InvalidOperationException:
if you get this error you are screwed !!. it causes at no point! you just get the error from no where. solution is simple ... remove all Application.DoEvents() from your application
System.InvalidOperationException: The Undo operation encountered a context that is different from what was applied in the corresponding Set operation. The possible cause is that a context was Set on the thread and not reverted(undone).
at System.Threading.SynchronizationContextSwitcher.Undo()
at System.Threading.ExecutionContextSwitcher.Undo()
at System.Threading.ExecutionContext.runFinallyCode(Object userData, Boolean exceptionThrown)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteBackoutCodeHelper(Object backoutCode, Object userData, Boolean exceptionThrown)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.ContextAwareResult.Complete(IntPtr userToken)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
System.InvalidOperationException: The Undo operation encountered a context that is different from what was applied in the corresponding Set operation. The possible cause is that a context was Set on the thread and not reverted(undone).
at System.Threading.SynchronizationContextSwitcher.Undo()
at System.Threading.ExecutionContextSwitcher.Undo()
at System.Threading.ExecutionContext.runFinallyCode(Object userData, Boolean exceptionThrown)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteBackoutCodeHelper(Object backoutCode, Object userData, Boolean exceptionThrown)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.ContextAwareResult.Complete(IntPtr userToken)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
Thursday, September 27, 2007
Flash/Blinking Window in C#
[DllImport("user32.dll")]
static extern Int32 FlashWindowEx(ref FLASHWINFO pwfi);
[StructLayout(LayoutKind.Sequential)]
public struct FLASHWINFO
{
public UInt32 cbSize;
public IntPtr hwnd;
public UInt32 dwFlags;
public UInt32 uCount;
public UInt32 dwTimeout;
}
//Stop flashing. The system restores the window to its original state.
public const UInt32 FLASHW_STOP = 0;
//Flash the window caption.
public const UInt32 FLASHW_CAPTION = 1;
//Flash the taskbar button.
public const UInt32 FLASHW_TRAY = 2;
//Flash both the window caption and taskbar button.
//This is equivalent to setting the FLASHW_CAPTION | FLASHW_TRAY flags.
public const UInt32 FLASHW_ALL = 3;
//Flash continuously, until the FLASHW_STOP flag is set.
public const UInt32 FLASHW_TIMER = 4;
//Flash continuously until the window comes to the foreground.
public const UInt32 FLASHW_TIMERNOFG = 12;
///
/// Flashes a window until the window comes to the foreground
/// Receives the form that will flash
///
/// The handle to the window to flash
///whether or not the window needed flashing
public static bool FlashWindowEx(Form frm)
{
IntPtr hWnd = frm.Handle;
FLASHWINFO fInfo = new FLASHWINFO();
fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo));
fInfo.hwnd = hWnd;
fInfo.dwFlags = FLASHW_ALL | FLASHW_TIMERNOFG;
fInfo.uCount = UInt32.MaxValue;
fInfo.dwTimeout = 0;
return (FlashWindowEx(ref fInfo) == 0);
}
static extern Int32 FlashWindowEx(ref FLASHWINFO pwfi);
[StructLayout(LayoutKind.Sequential)]
public struct FLASHWINFO
{
public UInt32 cbSize;
public IntPtr hwnd;
public UInt32 dwFlags;
public UInt32 uCount;
public UInt32 dwTimeout;
}
//Stop flashing. The system restores the window to its original state.
public const UInt32 FLASHW_STOP = 0;
//Flash the window caption.
public const UInt32 FLASHW_CAPTION = 1;
//Flash the taskbar button.
public const UInt32 FLASHW_TRAY = 2;
//Flash both the window caption and taskbar button.
//This is equivalent to setting the FLASHW_CAPTION | FLASHW_TRAY flags.
public const UInt32 FLASHW_ALL = 3;
//Flash continuously, until the FLASHW_STOP flag is set.
public const UInt32 FLASHW_TIMER = 4;
//Flash continuously until the window comes to the foreground.
public const UInt32 FLASHW_TIMERNOFG = 12;
///
/// Flashes a window until the window comes to the foreground
/// Receives the form that will flash
///
/// The handle to the window to flash
///
public static bool FlashWindowEx(Form frm)
{
IntPtr hWnd = frm.Handle;
FLASHWINFO fInfo = new FLASHWINFO();
fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo));
fInfo.hwnd = hWnd;
fInfo.dwFlags = FLASHW_ALL | FLASHW_TIMERNOFG;
fInfo.uCount = UInt32.MaxValue;
fInfo.dwTimeout = 0;
return (FlashWindowEx(ref fInfo) == 0);
}
Tuesday, September 11, 2007
"The search key was not found in any record." in dBase ?
i came up with this error "The search key was not found in any record." while reading a dbf file some time back. i was going thu microsoft support site and and they ask you to install some kind of patch that will never work. finally i found the solution
TEPS TO RESOLVE ISSUE:
========================
1. To Resolve that issue, In the Registry Editor, browse to the following
Registry key:
\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Eng ines\Xbase
2. On the Right Pane, Click on Deleted.
3. Right-Click on the Deleted and click on Modify.
4. Change the entry from
0000 01
to
0000 00
4. Click OK.
5. Close the Registry and then open Access and the file imports fine.
special thanks to Amy Vargo.
TEPS TO RESOLVE ISSUE:
========================
1. To Resolve that issue, In the Registry Editor, browse to the following
Registry key:
\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Eng ines\Xbase
2. On the Right Pane, Click on Deleted.
3. Right-Click on the Deleted and click on Modify.
4. Change the entry from
0000 01
to
0000 00
4. Click OK.
5. Close the Registry and then open Access and the file imports fine.
special thanks to Amy Vargo.
Monday, September 03, 2007
convert an object in to byte array or byte array to object
I was looking for a sample code snippet to convert an object in to byte array. finally i had to do it on my own.
public byte[] objectToByte(Object obj )
{
MemoryStream fs = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, obj);
return fs.ToArray() ;
}
catch (SerializationException e )
{
return null;
}
finally
{
fs.Close();
}
}
public object ByteArrayToObject(Byte[] Buffer )
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream(Buffer);
try
{
return formatter.Deserialize(stream);
}
catch
{
return null;
}
}
public byte[] objectToByte(Object obj )
{
MemoryStream fs = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, obj);
return fs.ToArray() ;
}
catch (SerializationException e )
{
return null;
}
finally
{
fs.Close();
}
}
public object ByteArrayToObject(Byte[] Buffer )
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream(Buffer);
try
{
return formatter.Deserialize(stream);
}
catch
{
return null;
}
}
Subscribe to:
Posts (Atom)