Thursday, May 28, 2009

Panel Hit Test in C# winforms

Today i wanted to check whether user click in with in the context of the panel. Since panel doesnt provide hittest this is how to do it ..

private bool panel_hit_test(Panel panel, POINT point_test)
{

Rectangle rect = panel.RectangleToScreen(panel.ClientRectangle);


if ((point_test.x > rect.X && point_test.x < rect.X + rect.Width) &&
(point_test.y > rect.Y && point_test.y < rect.Y + rect.Height))
{
return true;
}
else
return false;
}

Tuesday, May 05, 2009

Light-weight Threading ..

Today i wanted to create a light weight UI thread to make a button bliking. here is the sample code.

ThreadPool.QueueUserWorkItem(BlinkChatButton);


private void BlinkChatButton(object state)
{

while (canBlink)
{

Thread.Sleep(1000);
}


}

Windows Media (WM) Screen capturing by window handle

There is a C++ interface MS has provided to do this but in .net C# interop it's not available.

You have to use the IPropertyBag class based on it's GUID

[Guid("55272A00-42CB-11CE-8135-00AA004BB851")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IPropertyBag
{
void Read(String propName, out object ptrVar, int errorLog);
void Write(string propName, ref object ptrVar);
}



and copy and past this code before starting

IPropertyBag ipb = (IPropertyBag)
object value = false;

ipb.Write("Screen", ref value);
ipb.Write("CaptureWindow", ref Int32OfHandler);


Also make sure when you set the handle to set the encoding also to screen capturing


object codecName;
int codec_index = 2;

for (int i = 0; i < Profile.VideoCodecCount; ++i)
{
lVid4cc = Profile.EnumVideoCodec(i, out codecName);

//Compare if the current codec is Windows Media Video 9 Screen
if (codecName.ToString().Equals("Windows Media Video 9 Screen"))
{
codec_index = i; exit for;
}
}

// Set the IWMEncAudienceObj
Audnc.set_VideoCodec(0, codec_index);

Friday, March 13, 2009

how to get the size of a byte array in C#

System.IO.MemoryStream stream = new System.IO.MemoryStream();

System.Runtime.Serialization.Formatters.Binary.BinaryFormatter objFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
objFormatter.Serialize(stream, byData);
long size = stream.Length;

Friday, March 06, 2009

The remote server returned an error: NotFound WCF

This is a very common error message. To solve this, first you need to enable loggin in WCF. (Search for WCF Logging on Google) . Make you in logging section you enable all the types of the error messages

Eg


logMessagesAtServiceLevel="false" logMessagesAtTransportLevel="false"
maxSizeOfMessageToLog="2147483647" />


then you can see the exception on the error log file..


I got this error message because i have not set max request length, you need to add this to the web.config file

Wednesday, March 04, 2009

400 - Bad Request response

I was getting this message on the newly created silverlight app and it was driving me crazy.

this is how to fix it

in the ServiceReferences.ClientConfig


and in the Web Site project. Web.config file




maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">






bindingConfiguration="MyBinding" contract="TranscriptViewerWebApp.IRFTranscriptService">

















Monday, February 02, 2009

Custom tool error: Failed to generate code for the service reference 'ServiceReference1'. Please check other error and warning messages for details.

Custom tool error: Failed to generate code for the service reference ''. Please check other error and warning messages for details.

this is another issue i was stuck for sometime.. reason was i created the silverlight project using the Blend 2 with SP1 and created the WCF project using the VS2008 SP1.

to solve this problem you have to create silverlight application also using VS2008

Error 11007: Entity type '' is not mapped.

Most of the time u will get this bug or the table will not get added to the model (.edmx file) if you don't have a Primary Key in the database table ! so watch out !

Tuesday, January 27, 2009

The remote server returned an error: NotFound

The remote server returned an error: NotFound exception is a bich. !!

this is a very common issue in SilverLight beta 2,

to solve this,

1. you have to enable includeExceptionDetailInFaults to true










2. Download firebug, and inspect the issue, or the error code.

3. Search the error code in google ;)

4. if it's "415 - Unsupported media type" then only thing u have to do it change the

binding="wsHttpBinding" to binding="basicHttpBinding" in .conig file ..

DISCO it works!!!

Tuesday, December 16, 2008

how to add double quote ( " ) in C# string..

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

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

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

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

Thursday, July 24, 2008

Sends the mail message asynchronously

public static void SendMailMessageAsync()
{
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 ""

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()

Monday, January 21, 2008

million $ worth lesson.

dont overtake if things r not clear in-front.

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

? Operator in C#

simple,

bool r = (somestring == "1" ? true : false);

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

============================