goldb.org home

AS OF MAY 2008, THIS BLOG IS NO LONGER BEING UPDATED.
Visit the new blog at: http://coreygoldberg.blogspot.com



 Friday, July 27, 2007

C# - Simple TCP Server

Most of network programming I do is Web/HTTP oriented. So it has been a while since I had to work with TCP and Socket programming directly. Yesterday I needed to write a quick TCP Server. C# and .NET made this really easy to do:


using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

public class TCPServer
{
    private static int port = 8001;

    public static void Main()
    {
        IPAddress ipAddress = IPAddress.Any;
        TcpListener listener = new TcpListener(ipAddress, port);
        listener.Start();
        Console.WriteLine("Server is running");
        Console.WriteLine("Listening on port " + port);
        Console.WriteLine("Waiting for connections...");
        while (true)
        {
            Socket s = listener.AcceptSocket();
            Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
            byte[] b = new byte[65535];
            int k = s.Receive(b);
            Console.WriteLine("Received:");
            for (int i = 0; i < k; i++)
                Console.Write(Convert.ToChar(b[i]));
            ASCIIEncoding enc = new ASCIIEncoding();
            s.Send(enc.GetBytes("Server responded"));
            Console.WriteLine("\nSent Response");
            s.Close();
    }
}

#    Comments [0] |
 Monday, March 05, 2007

.NET CLR - Covertly Throttling Thread Creation

Joe Duffy (from Microsoft) talking about the .NET 2.0 CLR:

"It's also worth noting that the threadpool throttles its creation of threads to 2/second once the count has exceeded the # of CPUs."


Yuck...  I don't like throttling like that behind the scenes.  It can make performance problems *very* hard to diagnose.

#    Comments [2] |
 Sunday, February 25, 2007

How To See Your Swallowed Exceptions In .NET (Visual Studio debugger)

Good to know..


See all the exceptions you are swallowing in .NET (Visual Studio debugger):

Turn on 'all exceptions' and watch the fireworks fly


One of the most glaring differences for me between Java and .NET is the difference between Checked/Unchecked Exceptions, so stuff like this has been helpful to me in figuring out how exception handling in C#/.NET really works.

#    Comments [0] |

IronPython Community Edition - Free IronPython

IronPython is the Python implementation that runs on the .NET platform... originally created by Jim Hugginin, but later backed (overtaken?) by Microsoft.

Microsoft's ambivalence towards Free software is a bit hard to follow sometimes and it really makes me question their entire approach to the software community  (wait.. have I ever *not* questioned that? :).

As a Python advocate and *nix geek trying to make my way working in a .NET shop, I am really excited about IronPython.  I was also initially impressed with Microsoft's embracement of the Python community and toe dipping into Open Source.  But then I hear Microsoft will not take patches from non-Microsoft developers and will not bundle IronPython with other applications which have certain Free licenses(LGPL, BSD). To me, this is really a shame. That is not how you approach a community.

Well... at least somebody has stepped up and is maintaining IronPython Community Edition (IPCE).

props.


So check out IPCE and the FePy Project!

#    Comments [0] |
 Thursday, February 22, 2007

Not Using ASP.NET Session State? Then Turn It Off

I am developing some small ASP.NET 2.0 web applications.  They are stateless and I am not doing anything with Session State.  However, I noticed that ASP.NET enables Session State by default (In-process mode is the default setting).  Therefore, if you have a truly stateless site or application, session state does nothing more than slow down performance.

In-process session state is still relatively fast, as the memory used to handle session is allocated by the same process on the local machine (no cross-process calls or data marshaling).  But this is needless overhead if you are not using your Session State.

So... to turn it off for the whole application, add the following line to your web.config, inside the system.web section:


<sessionState mode="Off" />


#    Comments [0] |
 Tuesday, February 06, 2007

Anders Hejlsberg on LINQ and Functional Programming

Anders Hejlsberg on LINQ and Functional Programming

This is a good video of an interview with Anders Hejlsberg on LINQ and Functional Programming.  He is the designer of C# and talks about some of the upcoming features in Orcas (the next Visual Studio with C# 3.0).

I think it is very interesting (and good) that Microsoft (and many other modern language designers) are adding functional programming features.  If functional programming, lambda expressions, list comprehensions, and set processing, are your bag.. watch this.

#    Comments [0] |
 Tuesday, January 23, 2007

SQL Server - How To Tell If There Is A Trace Running

Server-side tracing is the process of having your SQL Server machine save events to a physical file on that machine without using the Profiler client tool.  Server-side tracing is enabled and controlled by using SQL Server system-supplied stored procedures and functions. With these system-supplied processes, you can identify what to trace, when to start and stop tracing, what traces are running, and view trace information stored in the trace file.


Here is how you view the number of traces currently running:

SELECT count(*) FROM :: fn_trace_getinfo(default) WHERE property = 5 and value = 1


Here is how you can find more detail about the running traces:

SELECT * FROM :: fn_trace_getinfo(default)


You can terminate a trace with the 'sp_trace_setstatus' stored procedure using the traceid:

EXEC sp_trace_setstatus 1, @status = 0
EXEC sp_trace_setstatus 1, @status = 2

setting the status to 0 stops the trace
setting the status to 2 closes the trace and deletes its definition from the server

#    Comments [0] |
 Monday, January 22, 2007

StockQuote Google Gadget

I use Google Personalized Homepage a lot.  I wanted a gadget for getting stock quotes ("gadget" is Google's lingo for a module or widget), but I couldn't find one I particularly liked.  So I created my own:



Behind the gadget is a remote .NET/C# service I created which scrapes stock quotes and charts from Google Finance.

You can see it and play with the demo: cgoldberg.googlepages.com

- Add my gadget to your Google Personalized Homepage
- Add my gadget to your own web page

Caveat:  The service runs off my own server so I can't guarantee I'll host this thing forever.

#    Comments [2] |

C# Simple Multithreading Example

Here is a simple example of multithreading in C#

using System;
using System.Threading;

public class Test
{
    static void Main()
    {
        ThreadStart job = new ThreadStart(ThreadJob);
        Thread thread = new Thread(job);
        thread.Start();

        for (int i=0; i < 5; i++)
        {
            Console.WriteLine ("Main thread: {0}", i);
            Thread.Sleep(1000);
        }
    }

    static void ThreadJob()
    {
        for (int i=0; i < 10; i++)
        {
            Console.WriteLine ("Spawned thread: {0}", i);
            Thread.Sleep(500);
        }
    }
}

#    Comments [0] |

Calling A Command Line Program From C#

I often need to call external command line programs from within my C# code.  To do this, I use a Process object.  Here is some example code I use for calling a Python program:

private void Execute()
{
    Process proc = new Process();
    
    proc.StartInfo.WorkingDirectory = @"C:\scripts";
    proc.StartInfo.FileName = "python.exe";
    proc.StartInfo.Arguments = "foo.py";
    proc.StartInfo.UseShellExecute = false;
    proc.StartInfo.RedirectStandardOutput = false;
    proc.StartInfo.RedirectStandardError = true;
    proc.Start();
    proc.WaitForExit();
    proc.Close()
}


#    Comments [0] |
 Wednesday, January 03, 2007

Dojo JavaScript Toolkit with ASP.NET

Dojo is a free/open source JavaScript toolkit.  I wanted to add some its eye candy to one of my ASP.NET 2.0 applications, so I integrated the Fisheye menu (a menu that balloons out, similar to the launcher on OS X).






Here is how I did it:


First I downloaded Dojo and created a 'dojo' directory under my main project directory.  I dropped dojo.js and the entire Dojo 'src' directory here.

Then in my C# codebehind (.aspsx.cs), I add this to the Page_Load event:

protected void Page_Load(object sender, EventArgs e)
{
    HtmlGenericControl Include = new HtmlGenericControl("script");
    Include.Attributes.Add("type", "text/javascript");
    Include.Attributes.Add("src", "dojo/dojo.js");
    Page.Header.Controls.Add(Include);

    HtmlGenericControl Include2 = new HtmlGenericControl("script");
    Include2.Attributes.Add("type", "text/javascript");
    Include2.InnerHtml = "dojo.require('dojo.widget.FisheyeList');";
    Page.Header.Controls.Add(Include2);
}

(I do this in the codebehind because I am using a Master Page and I need to access the HTML header from an individual content page.)


Then inside my ASP.NET page (.aspx), I added this div:

<div class="fisheyelist">
    <div dojoType="FisheyeList"
        itemWidth="80" itemHeight="80"
        itemMaxWidth="200" itemMaxHeight="200"
        orientation="horizontal"
        effectUnits="2"
        itemPadding="10"
        attachEdge="center"
        labelEdge="bottom"
        conservativeTrigger="false"
    >
        <div dojoType="FisheyeListItem"
             onclick="window.location = 'item1.aspx';"
             caption="Item 1"
             iconsrc="img/item1.png">
        </div>
        <div dojoType="FisheyeListItem"
             onclick="window.location = 'item2.aspx';"
             caption="Item 2"
             iconsrc="img/item2.png">
        </div>
        <div dojoType="FisheyeListItem"
             onclick="window.location = 'item3.aspx';"
             caption="Item 3"
             iconsrc="img/item3.png">
        </div>
    </div>
</div>



.. and it works.

#    Comments [0] |
 Thursday, December 07, 2006

C# - Read Contents Of A Randomly Selected File

string[] fileList = Directory.GetFiles(@"c:\temp");
Random random = new Random();
string fileName = fileList[random.Next(fileList.Length)];
StreamReader sr = File.OpenText(fileName);
string contents = sr.ReadToEnd();



#    Comments [0] |
 Tuesday, November 14, 2006

MQSeries and .NET - Interacting With Message Queues from C#

Below is a C# Class that I use for interacting with MQSeries (reading/writing from/to queues). 

It contains 2 methods:
PutMessageOnQueue
GetMessageOffQueue

To use it, you must have IBM WebSphere MQ installed, and you must add an assembly reference to amqmdnet.dll (the .NET bindings that come with WebSphere MQ).

I am using:
.NET 2.0
VS 2005
WebSphere MQ 5.3.0




public class MQSeries
{
    string queueName;
    string queueManagerName;
   
    MQQueue queue;
    MQMessage queueMessage;
    MQQueueManager queueManager;
   

    public MQSeries()
    {
        queueName = "TESTQ";
        queueManagerName = "TESTQM";
        queueManager = new MQQueueManager(queueManagerName);
    }  


    public void PutMessageOnQueue(string message)
    {
        try
        {
            queue = queueManager.AccessQueue(queueName,
                    MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING);
            queueMessage = new MQMessage();
            queueMessage.WriteString(message);
            queueMessage.Format = MQC.MQFMT_STRING;

            queue.Put(queueMessage);
        }
        catch (MQException mqexp)
        {
            Console.WriteLine("MQSeries Exception: " + mqexp.Message);
        }
    }


    public string GetMessageOffQueue()
    {
        string message = "";
       
        queue = queueManager.AccessQueue(queueName,
                MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING);
        queueMessage = new MQMessage();
        queueMessage.Format = MQC.MQFMT_STRING;

        try
        {
            queue.Get(queueMessage);
            message = queueMessage.ReadString(queueMessage.MessageLength);
        }
        catch (MQException MQExp)
        {
            Console.WriteLine("MQQueue::Get ended with " + MQExp.Message);
        }

        return message;
    }

}
#    Comments [0] |
 Sunday, November 05, 2006

Dynamic Languages On The CLR - IronPython For ASP.NET

OK... Dynamic Languages on the .NET CLR are getting serious:
(especially Python)

IronPython

... and infiltrating the .NET stack further:

IronPython for ASP.NET

The New Dynamic Language Extensibility Model for ASP.NET

#    Comments [0] |