Tag: coding
WCF Resolving error ‘The caller was not authenticated by the service.’
by brian on Sep.17, 2009, under .NET, WCF, c#, coding
I ran across an easy way to get wsHttpBinding to work on a remote machine. This involves just a little bit of code on the client side to complete the authentication.
VPortalDataServiceClient client = new VPortalDataServiceClient();
client.ClientCredentials.Windows.ClientCredential.UserName = "btomas";
client.ClientCredentials.Windows.ClientCredential.Password = "password123";
The UserName is the windows account user name that is hosting the service. This user may just need to be one on the domain that the machine can see — not exactly sure though. And the Password is the password of that user.
c# finding those blasted predefined IEqualityComparer classes!
by brian on Apr.14, 2009, under .NET, c#, coding
Why there isn’t any reference in the IEqualityComparer documentation to pre-implmented classes that override the function I don’t know.
But here’s one for string comparisons:
StringComparer
This static class contains many different predefined IEqualityComparer instances to be used in functions like “Contains”. Enjoy.
c# Getting your machine’s IP addresses.
by brian on Mar.17, 2009, under .NET, c#, c# coding GUI, coding, networking
Here is the simple way to get all of the IP addresses for you machine. This code filters out everything but IPv4 address, but to truly get everything just remove the if statement.
string hostName = Dns.GetHostName();
var addrs = Dns.GetHostAddresses(hostName);
bool hasIP = false;
for (int i = 0; i < addrs.Length; i++)
{
IPAddress addr = addrs[i];
if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
si.DataIP = addr.ToString();
hasIP = true;
break;
}
}
MS SQL Delete all the data from the tables.
by brian on Nov.21, 2008, under coding, mmsql, sql
Here’s a helpful, and perhaps dangerous, little tidbit of code for SQL Server 2005. It deletes all of the data from all of the tables. To be completely effective, the command may need to be run more than once because of foreign keys. Basically run it until there aren’t any errors. Then the db is clean and empty of all data.
exec sp_MSForeachTable "delete from ?"
the sp_MSForeachTable is a very useful system stored procedure.
c# dynamically picking the search direction with linq
by brian on Sep.30, 2008, under .NET, c#, linq, sql
I’ve recently been writing an application that builds a linq to sql query dynamically. For instance:
MyDataContext dc() = new MyDataContext; var query = dc.MyTables; query = query.Where( t=>t.id > 10);
and so I want to order it by a certain column:
query = query.OrderBy( t=>t.id )
but the problem is the order direction isn’t know before hand so at first I was stuck with the following:
if ( descending )
query = query.OrderByDescending( t=>t.id);
else
query = query.OrderBy(t=>t.id);
Now if there is only a few possible columns to sort against it isn’t too bad. But when you have 10 different possible columns it really makes a lot of extra work just to control to sort direction. So I made a little helper class that allows the following. It works with linq and linq to sql:
query = query.OrderByAscDec( t=>t.id, descending );
here’s the static class that implments the OrderByAscDec function:
static class VPLinqExtensions
{
public static IOrderedQueryable<TSource> OrderByAscDes<TSource, TKey>(
this IQueryable<TSource> source,
System.Linq.Expressions.Expression<Func<TSource,
TKey>> keySelector, bool IsDescending)
{
if (IsDescending)
return source.OrderByDescending(keySelector);
else
return source.OrderBy(keySelector);
}
}
c# Reading the contents of a web page
by brian on Sep.10, 2008, under .NET, c#, coding
Reading the contents of a web page can be very useful. Here’s some code I’m developing to read the historical stock prices from http://finance.google.com
string uri = "http://finance.google.com/finance/historical?cid=667226&startdate=Sep+9%2C+2007&enddate=Sep+10%2C+2008&output=csv";
WebRequest request = WebRequest.Create(uri);
WebResponse response = request.GetResponse();
var stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("utf-8"));
string page = reader.ReadToEnd();
There you go. Very simple isn’t it? Just got to love .Net
c# timing functions
by brian on Jun.12, 2008, under .NET, c#, coding
Here are some timing functions that come in the .Net framework. I’ve used these for moderately accurate timing code — at least down to the millisecond level. For any timing less than about 30 milliseconds these work much better than timer events piled on each other which tend to get inaccurate.
int begin = System.Environment.TickCount ... do something int end = System.Environment.TickCount int elapsed = end - begin;
c# getting a list of files from a directory
by brian on Jun.04, 2008, under .NET, c#, coding
Here’s how to get an array of file descriptors (name and other information).
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Program.DataDirectory);
System.IO.FileInfo[] files = di.GetFiles("*.txt");
c# force uppercase lettering in a ComboBox
by brian on Apr.28, 2008, under .NET, GUI, c#, c# coding GUI, coding
I recently changed from a TextEdit control to a ComboBox and was somewhat annoyed that there wasn’t a property that forced the input characters to all be uppercase. So I dug around and came up with the following method using the KeyPress event.
private void productNumber_KeyPress(object sender, KeyPressEventArgs e)
{
char c = e.KeyChar;
// make it uppercase only
if (c >= 'a' && c <= 'z')
{
int digit = (int)c;
digit = digit - 'a' + 'A';
e.KeyChar = Convert.ToChar(digit);
}
}
When the event handler is called it gives you a chance to edit the hit character. Just by changing e.KeyChar you change the actual input character. This is a nifty trick to have under your belt.
c# getting rid of the jitter!
by brian on Apr.18, 2008, under .NET, GUI, c#, c# coding GUI, coding, graphics
I recently was getting greatly annoyed with some drawing code in my program. I was drawing a photo that I could zoom and move around. When I zoomed with the wheel though it would briefly draw the image in two positions. The first position after it was zoomed, and the second position after it was re-centered on the screen. Well this looked awful. Not exactly professional looking. So I tried a hundered different things. I tried setting a bool variable in the control to tell the paint function not to draw. No good. The drawing was done with asynchronous messages. Then I tried BeginInvoke. That didn’t work also. I tried SuspendLayout and ResumeLayout functions of the Control class: No good. Finally I just used the Visible property which kind of worked, well I didn’t get the double picture, but my background was light color and the foreground dark, so there was still a bad looking flicker. After a couple of hours I finally found the solution at: http://weblogs.asp.net/jdanforth/archive/2004/03/12/88458.aspx. I worked on the example a little and boiled it down to two functions: StopDrawing and StartDrawing.
The techinque basically turns of drawing and events to the object on the win32 level underneath .Net. This is very handy and it worked very very well. Here is the code.
using System.Runtime.InteropServices;
private const int WM_SETREDRAW = 0x000B;
private const int WM_USER = 0x400;
private const int EM_GETEVENTMASK = (WM_USER + 59);
private const int EM_SETEVENTMASK = (WM_USER + 69);
[DllImport("user32", CharSet = CharSet.Auto)]
private extern static IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, IntPtr lParam);
IntPtr eventMask = IntPtr.Zero;
public void StopDrawing()
{
if (drawStopCount == 0)
{
// Stop redrawing:
SendMessage(this.Handle, WM_SETREDRAW, 0, IntPtr.Zero);
// Stop sending of events:
eventMask = SendMessage(this.Handle, EM_GETEVENTMASK, 0, IntPtr.Zero);
}
drawStopCount++;
}
public void StartDrawing()
{
drawStopCount--;
if (drawStopCount == 0)
{
// turn on events
SendMessage(this.Handle, EM_SETEVENTMASK, 0, eventMask);
// turn on redrawing
SendMessage(this.Handle, WM_SETREDRAW, 1, IntPtr.Zero);
Invalidate();
Refresh();
}
}
