Monday, April 11, 2011

SocketException on Windows XP home edition on connect: an invalid argument was supplied


Our software needs to connect to an server and we do that with use of an TCPclient. 50+ systems (all Windows XP pro) are using the software and have no problem with connecting. The software also has been tested on windows vista an Windows 7 beta.

Today there are some external people here for training and one of them has a laptop with Windows XP Home edition, which fails to connect to the server with SocketExeption "an invalid argument was supplied". (windows socket exception code: 10022)

However, when we try to telnet to that ip and port on the same laptop we can make a connection.

The code to connect is very basic:

m_client = new TcpClient();
m_client.Connect(System.Net.IPAddress.Parse(host), port);

Are there any additional socketoptions we have to set on Windows XP Home edition?

About his system: Windows XP Home edition version 2002 Service pack 2 One network-card active: Broadcom 440x 10/100 Integrated Controller

From stackoverflow
  • Just for people who wonder. We never got the time to further investigate the issue. It seemed to be a problem with the host's pc...

Use LINQ to concatenate multiple rows into single row (CSV property)

I'm looking for the LINQ equivalent to the Sybase's LIST() or MySQL's group_concat()

It'll convert:

User  Hobby
Bob   Football 
Bob   Golf 
Bob   Tennis 
Sue   Sleeping 
Sue   Drinking


User  Hobby
Bob   Football, Golf, Tennis 
Sue   Sleeping, Drinking
From stackoverflow
  • That's the GroupBy operator. Are you using LINQ to Objects?

    Here's an example:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    public class Test
        static void Main()
            var users = new[]
                new { User="Bob", Hobby="Football" },
                new { User="Bob", Hobby="Golf" },
                new { User="Bob", Hobby="Tennis" },
                new { User="Sue", Hobby="Sleeping" },
                new { User="Sue", Hobby="Drinking" },
            var groupedUsers = users.GroupBy(user => user.User);
            foreach (var group in groupedUsers)
                Console.WriteLine("{0}: ", group.Key);
                foreach (var entry in group)
                    Console.WriteLine("  {0}", entry.Hobby);

    That does the grouping - can you manage the rest yourself?

    Hosam Aly : It's also possible to replace the inner loop with `String.Join(", ", group.ToArray())`, as long as the number of elements is not very large.
    John Paul Jones : Thanks! I'm going to learn LINQ myself instead of constantly bugging you ;-)
    Carter : Am I the only one that noticed the man is into sports while the woman's hobbies are sleeping and drinking? You're terrible Jon Skeet!
    Jon Skeet : @Carter: They're not *my* examples...
    Carter : Ha, you're right, my bad. Still funny.
  • See if this solution helps you:

    List<User> users = new List<User>() 
        new User {Name = "Bob", Hobby = "Football" },
        new User {Name = "Bob", Hobby = "Golf"},
        new User {Name = "Bob", Hobby = "Tennis"},
        new User {Name = "Sue", Hobby = "Sleeping"},
        new User {Name = "Sue", Hobby = "Drinking"}
    var groupedUsers = from u in users
             group u by u.Name into g
             select new
                 Name = g.First<User>().Name,
                 Hobby = g.Select(u => u.Hobby)
    foreach (var user in groupedUsers)
        Console.WriteLine("Name: {0}", user.Name);
        foreach (var hobby in user.Hobby)
            Console.WriteLine("Hobby: {0}", hobby);
  • re the _concat aspect of your question, using:

    static class EnumerableExtensions 
        public static String AsJoined( this IEnumerable<String> enumerable )
            return AsJoined( enumerable, "," );
        public static String AsJoined( this IEnumerable<String> enumerable, String separator )
            return String.Join( separator, enumerable.ToArray() );

    The outputting foreach in bruno conde and Jon Skeet's answers can become:

    Console.WriteLine( "User:\tHobbies");
    foreach ( var group in groupedUsers )
        Console.WriteLine( "{0}:\t{1}", group.Key, group.Select( g => g.Hobby ).AsJoined( ", " ) );

    ... and you'll get the precise result output format you asked for (yes, I know the others have already solved your problem, but its hard to resist!)

  • To do it in one Linq Statement. There is no way I'd recommend the code, but it shows that it could be done.

                var groupedUsers = from user in users
                               group user by user.User into userGroup
                               select new
                                   User = userGroup.Key,
                                   userHobies =
                                       userGroup.Aggregate((a, b) => 
                                           new { User = a.User, Hobby = (a.Hobby + ", " + b.Hobby) }).Hobby
            foreach (var x in groupedUsers)
                Debug.WriteLine(String.Format("{0} {1}", x.User, x.userHobies));

How do I add a namespace while doing XmlSerialization with an XmlWriter?

I am using the XmlWriter in conjunction with Xml Serialization. I am able to output the XML fine, but how to include the xmlns attribute with the XmlWriter seems to be escaping me.

To write the start of the document I use the following:


With my XmlWriter created I then loop through SitemapNodes I have created them and write them to the underlying stringbuilder through serialization like this:

    foreach ( node in List)
        Serializer.Serialize(Writer, node);

As I say this works fine BUT the above namespace for the root element is not included. Every time I try to physically write the attribute, xmlns, I get an exception that the xmlns is reserved by the system for XML use, so basically I cannot use.

I know how to do this using the XmlTextWriter and also using the XmlDocument class but i need to understand how I achieve this using the XmlWriter and through Serialization.

The following attempt also throws the exception about that namespace being reserved.

foreach ( node in List)
      XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
      ns.Add("xmlns", "");

      Serializer.Serialize(Writer, node, ns);

Exception Details: System.ArgumentException: Prefix "xmlns" is reserved for use by XML.
From stackoverflow
  • You can add the namespace to the XmlSerialization attributes, e.g.:

    ElementName = "Members",
    Namespace = "")]
    public Employee[] Employees;

    if you have control over the code.

    REA_ANDREW : I have included that now, but still the attribute is not output.
    REA_ANDREW : Right I am being DUMB, I was viewing the output in firefox, WHICH hides these attibutes. Viewing the source showed that my oriignal code actually works fine. :-( Thanks for your help.

How to architect DAL for WebService exposure?

We have a highly specialized DAL which sits over our DB. Our apps need to use this DAL to correctly operate against this DB.

The generated DAL (which sits on some custom base classes) has various 'Rec' classes (Table1Rec, Table2Rec) each of which represents the record structure of a given table.

Here is a sample Pseudo-class...

Public Class SomeTableRec
    Private mField1 As String
    Private mField1isNull As Boolean
    Private mField2 As Integer
    Private mField2isNull As Boolean

    Public Sub New()
        mField1isNull = True
        mField2isNull = True
    End Sub
    Public Property Field1() As String
            Return mField1
        End Get
        Set(ByVal value As String)
            mField1 = value
            mField1isNull = False
        End Set
    End Property
    Public ReadOnly Property Field1isNull() As Boolean
            Return mField1isNull
        End Get
    End Property
    Public Property Field2() As Integer
            Return mField2
        End Get
        Set(ByVal value As Integer)
            mField2 = value
            mField2isNull = False
        End Set
    End Property
    Public ReadOnly Property Field2isNull() As Boolean
            Return mField2isNull
        End Get
    End Property
End Class

Each class has properties for each of the fields... Thus I can write...

Dim Rec as New Table1Rec
Table1Rec.Field1 = "SomeString"
Table2Rec.Field2 = 500

Where a field can accept a NULL value, there is an additional property which indicates if the value is currently null.


Dim Rec as New Table1Rec
Table1Rec.Field1 = "SomeString"
If Table1Rec.Field1Null then 
    ' This clearly is not true
End If
If Table1Rec.Field2Null then 
    ' This will be true
End If

This works because the constructor of the class sets all NULLproperties to True and the setting of any FieldProperty will cause the equivalent NullProperty to be set to false.

I have recently had the need to expose my DAL over the web through a web service (which I of course intend to secure) and have discovered that while the structure of the 'Rec' class remains intact over the web... All logic is lost..

If someone were to run the previous piece of code remotely they would notice that neither condition would prove true as there is no client side code which sets null to true.

I get the feeling I have architected this all wrong, but cannot see how I should improve it.

What is the correct way to architect this?

From stackoverflow
  • Web services are designed to expose operation(methods) & data contracts but not internal implementation logic. This is a "good thing" in the world of service-oriented architecture. The scenario you describe is a remote/distributed object architecture. Web services will not support what you are trying to do. Please see this post for more information.

  • Not sure if I fully understand the question, but you can have nullable data types in XML.

    So this...

    Imports System.Web
    Imports System.Web.Services
    Imports System.Web.Services.Protocols
    <WebService(Namespace:="")> _
    <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
    <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
    Public Class Testing
         Inherits System.Web.Services.WebService
        <WebMethod()> _
       Public Function GetObjects() As Generic.List(Of TestObject)
            Dim list As New Generic.List(Of TestObject)
            list.Add(New TestObject(Nothing, "Empty ID Object"))
            list.Add(New TestObject(1, "Full ID Object"))
            list.Add(New TestObject(2, Nothing))
            Return list
        End Function
        Public Class TestObject
            Public Sub New()
                _name = String.Empty
                _id = Nothing
            End Sub
            Public Sub New(ByVal id As Nullable(Of Integer), ByVal name As String)
                _name = name
                _id = id
            End Sub
            Private _name As String
            Public Property Name() As String
                    Return _name
                End Get
                Set(ByVal value As String)
                    _name = value
                End Set
            End Property
            Private _id As Nullable(Of Integer)
            Public Property ID() As Nullable(Of Integer)
                    Return _id
                End Get
                Set(ByVal value As Nullable(Of Integer))
                    _id = value
                End Set
            End Property
        End Class
    End Class

    outputs this (with nullable areas)

    <?xml version="1.0" encoding="utf-8" ?> 
    <ArrayOfTestObject xmlns:xsi="" xmlns:xsd="" xmlns="">
      <Name>Empty ID Object</Name> 
      <ID xsi:nil="true" /> 
      <Name>Full ID Object</Name> 

Which Qt DLL's should I copy to make my program stand-alone?

Hi, I'm trying to make a distribution directory with my application. I've copied several Qt DLLs to that directory, and the program seems to be working, with one exception: it doesn't seem to find SQL plugin for SQLite. Copying qtsqlite.dll to the directory, doesn't allow my application to open or create SQLite files. What must be the direcotry structure or which additional files need to be copied so that the program can read the database?

From stackoverflow
  • Most probably, the qtsqlite.dll itself depends on original SQLite DLL's which you probably need to copy as well.

    Don't forget to include an LGP license copy in your distribution as well as pointers to the original download ressources of the libs you include and their sources. To stay with the law :-)

  • you can use depends.exe to see exactly what the dependencies of your exe are and make sure they're all included.

    Also, read this page about qt plugins. they are supposed to be in a specific directory called "plugins" and not in the main directory with all the other dlls.

    dwj : By default the application will use its start-up directory as the plugins directory; you need to put the drivers in a base class directory name: e.g., app_dir/sqldrivers.
  • Thanks to the link @shoosh provided, I was able to fix the problem. I needed to create sqldrivers subdirectory in the distribution dir with qsqlite.dll library inside. But that was just step one. Do you have any tips and resources on creating a full-blown Windows installer? I'm mainly a Linux programmer so this area is unknown to me.

    ypnos : Perhaps NSIS is a good starting point for you: It is open source and scriptable. Good for Linux programmers :-D

WiFi iPhone Application

Hi im working on an iPhone application which requires communication between 2 devices through WiFi.

Can somebody please help me by providing a simple iphone application code for the same which is able to communicate data between the devices...i hv gone through the "witap application" available on the developers site but wasnt able to understand it...

please help..

From stackoverflow

TextBox Validation in VB.NET and Windows Forms

I'm using the following code to validate the text entered by user. It works perfectly fine. But I want to add the backspace feature so as to allow the user to delete the wrongly entered number.

I have tried a couple of things and they worked but before last digit (after the decimal point) i.e. it does not allows to delete after the number has been completely entered. number is being entered in the format: 12313213.45

What shall I do?

Private Sub TextBox5_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox5.KeyPress

    'validation '
    Dim KeyAscii As Short = Asc(e.KeyChar)
    If Not ((KeyAscii >= System.Windows.Forms.Keys.D0 And KeyAscii <= System.Windows.Forms.Keys.D9) Or (KeyAscii = System.Windows.Forms.Keys.Back) Or Chr(KeyAscii) = "." Or (Chr(KeyAscii) Like "[ ]")) Then
        KeyAscii = 0
    End If
    If KeyAscii = 0 Then
        e.Handled = True
    End If

    If TextBox5.Text.IndexOf(".") >= 0 And e.KeyChar = "." Then
        e.Handled = True
    End If

    If TextBox5.Text.IndexOf(".") > 0 Then
        If TextBox5.SelectionStart > TextBox5.Text.IndexOf(".") Then
            If TextBox5.Text.Length - TextBox5.Text.IndexOf(".") = 3 Then
                e.Handled = True
            End If
        End If
    End If
End Sub
From stackoverflow
  • There is a much easier way to validate this. Try convert the text in the edit box to a floating point number. If you catch an exception, the number is not valid.

    Trying to validate keystroke by keystroke is going to cause you many headaches.

    dmce : Is it wise to use exceptions to perform a task?
    Pavel Minaev : No, which is why you use `Decimal.TryParse` instead.
  • Don't try and validate keystrokes one at a time.
    1) You have just found that backspace requires more code, now add support for cut/copy and paste, and the delete key and typing replaces selection. The code is not nice.
    2) It will only confuse the user. Or worse, they try and type a . seperated date into your field, you force that date into a legitimate number by ignoring the second . and they have now entered something totally wrong and your program won't tell them.
    The validating event of the textbox is where this sort of logic should go. It will fire when the focus moves to another control (whose CausesValidation property is true, this allows cancel buttons to be clicked even if the current control is not in a valid state).
    In the validating event you can do all the checks you need to and cancel the event if the data is not valid, as well as displaying whatever message you need to. To validate the value I would suggest Single.TryParse to start with, then if the conversion succeeds you can continue to do any range checks that you require. TryParse is better than @Bork's suggestion because it is easier to read and avoids the throwing/catching of un-necessary exceptions.

    EDIT: Just noticed you are also restricting the length of the entered text. You can do that by setting the MaxLength property of the TextBox.

  • An even better way is to use a control that supports decimals (if that is you're using something like infragistics, componentone, devexpress, etc.) The user gets visual cues and can do neat things like click the arrows to advance the numbers.

    If you're using plain old winforms, have a look at the masked edit control.

    Personally I find it HUGELY irritating when applications try to correct me and i'm not done entering data. It's much more user friendly to let the user finish and then notify them if there are any problems.

    Pavel Minaev : Actually, the stock `NumericUpDown` WinForms control can handle decimal fractions - but it requires you to specify how many decimal places to show, and won't let user input more than that.
  • I think the link below should give you exactly what you're after:

    Numeric TextBox

    Although it requires a fair amount of code to handle validation on each keypress, it's certainly possible, and the code above seems to handle delete, backspace, copy/pasting etc.

  • Or use a regular expression for the tough stuff

  • Yeah, or just make that nested if...then block look like this:

    If Textbox5.Text.IndexOf(".") > 0 Then
        If Textbox5.SelectionStart > Textbox5.Text.IndexOf(".") Then
            If Textbox5.Text.Length - Textbox5.Text.IndexOf(".") = 3 Then
                If KeyAscii <> System.Windows.Forms.Keys.Back Then e.Handled = True
            End If
        End If
    End If
  • txtMobil.Text = Format(txtMobil.Text, "###-###-####")

How to sort text in sqlite3 with specified locale?

Sqlite3 by default sorts only by ascii letters. I tried to look in google, but the only thing I found were informations about collations. Sqlite3 has only NOCASE, RTRIM and BIARY collations. How to add support for a specific locale? (I'm using it in Rails application)

From stackoverflow
  • SQLite supports integration with ICU. According to the Readme file, sqlite/ext/icu/README.txt the sqlite/ext/icu/ directory contains source code for the SQLite "ICU" extension, an integration of the "International Components for Unicode" library with SQLite.

    1. Features
        1.1  SQL Scalars upper() and lower()
        1.2  Unicode Aware LIKE Operator
        1.3  ICU Collation Sequences
        1.4  SQL REGEXP Operator
  • I accepted Doug Currie answer, but I want to add some "algorithm" how to do it, becouse sqlite3 documentation is very strange (at least for me).

    Ok, we have working sqlite3 and now:

    1. Download ICU extention for sqlite

    2. Compile it:

      gcc -shared icu.c `icu-config --ldflags` -o

      It is for Linux. I also needed to install additional ICU development package:

      sudo apt-get install libicu-dev

      I'm working on 64 bit architecture and I get error with __relocation R_X86_64_32S__ (whatever it means :). GCC suggested adding -fPIC to compile options and it helped.

    3. Run sqlite3. We can load extension with command:

      .load './'

      Assuming that it is in the current directory, we can also specify whole path.

    4. Create new collation:

      SELECT icu_load_collation('pl_PL', 'POLISH');

      The first parameter is desired locale and the second is it's (it can be whatever).

    5. Now we can sort data with our new locale:

      SELECT * FROM some_table ORDER BY name COLLATE POLISH;

      And it is case insensitive!

How do I get the Block Header Size in Oracle?

I'm trying to calculate the size of a few tables as stated here, but I can't find the block header size variable

How do I get it? Is it some kind of formula?

I'm using Oracle 10g

From stackoverflow
  • This page (for 10g) says it's 57 bytes.

    Juan Manuel : I saw that, but I think it's just one part of the "whole block header"
    paxdiablo : The block header size is 57 bytes, did you mean the block size?
    paxdiablo : Or the actual overhead which is discussed on that page as well (block header, transaction header, table directory, ...)?
  • This site has a good discussion on the format of the block header: Basically the block header = fixed header + transaction header + table directory + row directory. Here are the individual pieces:

    fixed header = 57 bytes

    transaction header = between 23*inittrans and 23*maxtrans

    table directory = 4*number of tables (usually 1 unless you're using clusters)

    row directory = 2*stored rows

    In short while you can come up with a rough estimate, it's not a fixed size for each data block.

    paxdiablo : Those "=" chars, I assume they're meant to be "+" chars, yes?
    Shawn Loewen : I edited the answer to make the formatting a bit clearer.
    paxdiablo : Okay, looks like that's what the Q'er was after, +1.

Persisting form data in Win forms applications.

In a C# winforms app what is the normal way to persist the data on form that is opened by another form? I'd planned on just keeping it all on the form object but when the form is closed it seems the that form object is disposed. meaning I loose all the data.

I could wrap the form up in another object which takes all the data off it but that seems like a lot of work.

Is there a way to just hide the form when it is closed rather than disposing of it?

From stackoverflow
  • 2 possibilities:

    1)catch the close event and just hide it. Create functions (to the hidden form) to get the input values using properties.

    private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        this.Visible = false;
        e.Cancel = true;

    2)And what Moj tells: if you close the form after you created it, the form object will still be alive and can be accessed

    I favor 2) + the properties

    Omar Kooheji : so catching the close event and hiding it will override the normal behaviour and stop it from being disposed?
    PoweRoy : is you close it it will not be disposed, only when it goes out of scope
    Jacob Adams : However, I don't believe you can reshow it after it has been closed. I think you instead need to hide it
  • Use public properties.

    • Before closing, fill up these properties with corresponding values (ie. this._userName = txtUsername.Text)
    • Close the form
    • In the parent object of the form, you can still call dialog.Username to read the values.
  • On closing a form is not Disposed. Generally this is how the data is managed.

      Result res;
      using (MyForm form = new MyForm())
          if(form.ShowDialog()== DialogResult.OK) 
             // In Myform, after the data collection is done, you can set  DialogResult=DialogResult.Ok and close form using form.Close(); 
             res = form.Result; // expose forms data as result.                              
    OregonGhost : You should be using using.
    Sung Meister : I second to using "using"
    OregonGhost : The Close() call is unnecessary, because ShowDialog() returns when the dialog has been closed. I removed the line in your post, but then felt dirty non-trivially editing someone else's post and revoked my change. Feel free to re-revoke it ;)
    nils_gate : Thanks, Learned and Done !
  • Accessing the child form's controls it is technically possible but not a good design. Here is how I do it:

    1) On Accept/Save button, you set the this.DialogResult to "OK", and get all the controls info. On the Close button or/and Closing event set this.DialogResult to "Cancel"

    2) If the data is mapped to an object (lets say "Customer") ... set the object properties. If not, just expose each control's data with a property, handling all the needing formating.

    3) Close the form using this.Close(); not dispose it.

    4) On your parent form check if dialog.ShowDialog() == DialogResult.OK and just then access the public properties you created in step 2... or if you load an object with the info just access that object in the form (by a Property also)

    5) THEN call the dialog.Dispose() method... either the user pressed OK or Cancel.

    Hope this helps you...

  • I recommend you to build a separate object contain the data. You can bind the form controls to its properties in a very simple way (designer supported, no code required). This keeps your data separated from the form.

    In case you don't know this document yet: How to: Create a Simple-Bound Control on a Windows Form


  • You could hide the form vs. disposing it but this is almost certainly not what you want. Forms take up resources in the process that will not be freed if you simply hide the form. They will only go away if you dispose of it. Keeping a bunch of Form instances around when they are not being used is just asking for a problem later down the road.

    What you likely want to do is pass back some result data from the Form after it's finished showing but before it's actually Closed. For example,

    MyDataObject data;
    using (var form = new SomeForm() ) {
      var dialogResult = form.ShowDialog(someWindow);
      data = form.InterestingData;

ADSI / IIS management and ASP.NET impersonation

I'm in the process of writing a small web app that would allow me to manage several IIS installations on different servers on our network. We have no domain controller.

I have written a small impersonation controller that uses the win32 api and its LogonUser method. I then use System.DirectoryServices and the IIS ADSI provider to create a new site.

I have the following routine (exchanged some values with clear-text strings for better readability):

            if (impersonationSvc.ImpersonateValidUser("Administrator@SRV6", String.Empty, "PASSWORD))

            string metabasePath = "IIS://" + server.ComputerName + "/W3SVC";
            DirectoryEntry w3svc = new DirectoryEntry(metabasePath, "Administrator", "PASSWORD");

            string serverBindings = ":80:" + site.HostName;
            string homeDirectory = server.WWWRootNetworkPath + "\\" + site.FolderName;

            object[] newsite = new object[] { site.Name, new object[] { serverBindings }, homeDirectory };

            object websiteId = (object)w3svc.Invoke("CreateNewSite", newsite);
            int id = (int)websiteId;


This routine works when I use the server the web app is hosted on (SRV6). A new site is created.

If I use SRV5 for instance, another Server on our network (with no domain), ImpersonateValidUser works, the DirectoryEntry is created, but w3svc.Invoke fails with the following error:

[COMException (0x80070005): Access denied]

System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +377678
System.DirectoryServices.DirectoryEntry.Bind() +36
System.DirectoryServices.DirectoryEntry.get_NativeObject() +31
System.DirectoryServices.DirectoryEntry.Invoke(String methodName, Object[] args) +53


Anyone knows how I could solve this?

From stackoverflow
  • I would look into the eventlog of SRV5 to check what privileges are used when you connect to that server. You may need to change your group policies to log failures in the security log.

    It sounds easier to setup webservices on your servers, preferably protected by logins and/or ip restrictions, that does these kind of operations.

  • You cannot use impersonation in this situation. The account you are impersonating needs login priveleges on the local machine.

    If your web servers are not part of a domain, I think Tant102's idea of web services is your only way to go.

    kitsune : You are right.. too much coffee

ASP.NET AJAX issues when using UserControls

Hi Stackoverflowers

I Have a UserControl called TenantList.ascx which contains a slightly modified GridView from DevExpress (Web.ASPxGridView). This control makes Callbacks without causing a postback which is exactly what I need. The specific event I need to react on is CustomButtonClicked. I have made my on OnCustomButtonClicked event on the usercontrol TenantList.ascx that fires when the the GridView CustomButtonClicked event fires.

I have an eventhandler on the page where I use the UC. When I debug using VS I can see that I get into the eventhandler as I am suppose to. My Eventhandler looks like this:

    protected void uc_TenantList_CustomButtonCallback(object sender, ASPxGridViewCustomButtonCallbackEventArgs e)
        Tenant tenant = (Tenant)uc_TenantList.GetGridView().GetRow(e.VisibleIndex);

        switch (e.ButtonID)
            case "btn_show":
            case "btn_edit":
            case "btn_delete":

    private void EditRow(Tenant tenant)

The EditRow function get's called and the UserControl TenantDetails.ascx gets filled with data correctly. However the UpdatePanel1.Update(); is not updating the panel where my TenantDetails UserControl is in.

However if i call UpdatePanel1.Update(); from a normal control registered to the ScriptManager it updates just fine.

        protected void Button1_Click(object sender, EventArgs e)

That works without a problem... I am 100% stuck and without any idea of what might be the problem here.

Any suggestion is welcome!!

Cheers The Real Napster - In real trouble :)

From stackoverflow
  • Make sure that your update panel is set to always update (not conditionally). You may also find the information in this articles useful:

    The first link will give you some history regarding Partial Page Rendering, the second gives you some more information about the Update method.

    From the documentation calling UpdatePanel.Update will cause an update panel to be re-rendered on the client after calling, but only if the UpdatePanel is set to Conditionally update. If it is set to always update this should throw an error.

    If your update panel is set to always update, could it be that it is nested in another UpdatePanel which has its update mode set to conditional?

    The real napster : I have had it set to Always instead of conditionally and it makes no difference. I use the Update(); function instead of "Always". "I would say it sounds like partial-page rendering is enabled." I want only to render the Updatepanel shouldn't it be on then?
    Chris : Sorry, will flesh out the answer - the link I posted says you will also need to make a modification on the script manager
  • Okay solved this issue

    What I needed to do was to enable postback on the gridview control inside my usercontrol. Then place the Gridview usercontrol in a updatepanel and still keep the details usercontrol in another updatepanel.

    That way it all worked out. Not impressed by the solution though. Looks a bit ugly.

Can I databind (2-way) dynamically generated RadioButtonLists?

I am trying to create a dynamic survey page. The idea seems simple, but trying to implement it in ASP.NET is getting me very frustrated...

Each user is linked to an individual list of (multiple-choice) questions. I have the following data tables:


User   | Question   | Rank
user-x | question-x |    1
user-x | question-y |    2
user-y | question-z |    1
user-y | question-x |    2


ID         | Text | Choices
question-x | Foo? | yes|no
question-y | Bar? | never|sometimes|always
question-z | Baz? | 1|2|3|4|5|6|7|8|9|10


User   | Question   | Answer
user-x | question-x |    0
user-x | question-y |    2
user-y | question-z |    5

So the answer choices are character-separated strings that need to be expended when databinding, and the answers are stored as a 0-based index to the answer. (So user-x answered "always" on question-y.)

Here is my first version of the code:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:dbconn %>" 
     SELECT Questions.Text AS Question, Questions.Choices, Answers.Answer 
     FROM Questions 
      INNER JOIN Surveys ON Surveys.Question = Questions.ID 
      LEFT OUTER JOIN Answers ON Questions.ID = Answers.Question 
       AND Users.ID = Answers.User 
     WHERE (Surveys.User = @User) 
     ORDER BY Surveys.Rank">
     <asp:QueryStringParameter Name="User" QueryStringField="id" />

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1" 
      <td><%# Eval("Question") %></td>
      <td><asp:Label runat="server" ID="ChoicesLabel"/></td>

<asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click"/>


protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
    if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) 

    DataRowView row = (DataRowView)e.Item.DataItem;
    RadioButtonList rbl = new RadioButtonList();
    rbl.RepeatDirection = RepeatDirection.Horizontal;
    string[] Choices = row["Choices"].ToString().Split('|');
    for (int n = 0; n < Choices.Length; n++)
     rbl.Items.Add(new ListItem(Choices[n], n.ToString()));
    if (row["Answer"] != DBNull.Value)
     rbl.SelectedIndex = (int)row["Answer"];

protected void Button1_Click(object sender, EventArgs e)

Now, the first problem was that after I click "Submit", I get a page in return which only contains the questions, not the radiobuttons with answers! After lots of searching, I fixed this by forcing the data binding to occur on page initialization:

public void Page_Init(Object sender, EventArgs e)

However, I am still completely in the dark if it is possible to do a 2-way databinding on the RadioButtonLists? (I mean with a <%# Bind() %> command.) Or do I have to write my own procedure for submitting the answers back to the database? To make things more complicated, on first visit the answers will have to be INSERTed into the Answers table, while on return visits the existing rows can be UPDATEd.

From stackoverflow
  • Yes, I have found a similar problem when I want to use Bind with the DropDownList. What I do is create a custom control, from your example, which inherits from a RadioButtonList. I give it one extra property called Value. When this is set I then code to set the selected item through the values. When I call the get I return the actual selected value so in essence you need a custom class which inherits from the RadioButtonList and give it an extra property

        using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI.WebControls;
    /// <summary>
    /// Summary description for BindingRadioButtonList
    /// </summary>
    public class BindingRadioButtonList : RadioButtonList
        public string Value
                return this.SelectedValue;
                if (this.Items.FindByValue(value) != null)
                    this.Items.FindByValue(value).Selected = true;
        public BindingRadioButtonList()
         // TODO: Add constructor logic here

    I can then easily use this:

    <cc1:BindingRadioButtonList ID="a1" runat="server" Value='<%#Bind("YourValue")%>'>


    paulwhit : Trying to figure out how to consume this. Do I need to compile as a DLL and add it to my toolbox?

Java library class to handle scheduled execution of "callbacks"?

My program has a component - dubbed the Scheduler - that lets other components register points in time at which they want to be called back. This should work much like the Unix cron service, i. e. you tell the Scheduler "notify me at ten minutes past every full hour".

I realize there are no real callbacks in Java.

Here's my approach, is there a library which already does this stuff? Feel free to suggest improvements, too.

Register call to Scheduler passes:

  • a time specification containing hour, minute, second, year month, dom, dow, where each item may be unspecified, meaning "execute it every hour / minute etc." (just like crontabs)
  • an object containing data that will tell the calling object what to do when it is notified by the Scheduler. The Scheduler does not process this data, just stores it and passes it back upon notification.
  • a reference to the calling object

Upon startup, or after a new registration request, the Scheduler starts with a Calendar object of the current system time and checks if there are any entries in the database that match this point in time. If there are, they are executed and the process starts over. If there aren't, the time in the Calendar object is incremented by one second and the entreis are rechecked. This repeats until there is one entry or more that match(es). (Discrete Event Simulation)

The Scheduler will then remember that timestamp, sleep and wake every second to check if it is already there. If it happens to wake up and the time has already passed, it starts over, likewise if the time has come and the jobs have been executed.

Edit: Thanks for pointing me to Quartz. I'm looking for something much smaller, however.

From stackoverflow
  • Lookup Quartz

  • Quartz scheduler is usually recommended.

  • Quartz is the big and obvious powerhouse in this area, but there are some alternatives to explore.

    Cron4j is a decent enough library, that is a little more lightweight than Quartz. It provides good documentation and will do what you want.

    Probably more interesting is if you want to use a library that fits better with Java's concurrency libraries (particularly Executors and ScheduledExecutors) then HA-JDBC has a CronExecutorService interface, implemented by its CronThreadPoolExecutor. Now, interestingly, it has a dependency on Quartz (to provide the CronExpression class), but I find that the two together work better than just Quartz alone. If you don't want large dependencies, its easy to extract the handful of classes from Quartz and HA-JDBC that make this happen.

    Since you want something much smaller (just noticed your edit), grab CronExpression from Quartz, and the two HA-JDBC classes I mentioned above. That'll do it.

  • If your objects know exactly the individual points in time which they wish to be executed, then you could use a java.util.concurrent.ScheduledExecutorService. Then they simple call:

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
    long timeToExecute = ... //read from DB? use CronTrigger?
    long delayToExecution = timeToExecute - System.currentTimeMillis();
    scheduler.schedule(aRunnable, delayToExecution, TimeUnit.MILLISECONDS);

    You'd only need to use Quartz if you want the scheduler itself to handle functionality like "execute every 5 seconds", or if you want complex behaviour around missed executions, or the persistence of the execution audit trail.

    You can actually trivially re-use Quartz's CronTrigger class to get a "next execution time". The class is completely standalone and does not depend on being invoked from within the Quartz "context". Once you have the next execution time as a Date or long, you can just use the Java ScheduledExecutorService as above

  • If your needs are simple, consider using java.util.Timer:

    public class TimerDemo {
      public static void main(String[] args) {
        // non-daemon threads prevent termination of VM
        final boolean isDaemon = false;
        Timer timer = new Timer(isDaemon);
        final long threeSeconds = 3 * 1000;
        final long delay = 0;
        timer.schedule(new HelloTask(), delay, threeSeconds);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 1);
        Date oneMinuteFromNow = calendar.getTime();
        timer.schedule(new KillTask(timer), oneMinuteFromNow);
      static class HelloTask extends TimerTask {
        public void run() {
      static class KillTask extends TimerTask {
        private final Timer timer;
        public KillTask(Timer timer) {
          this.timer = timer;
        public void run() {
          System.out.println("Cancelling timer");

    As has been noted, the ExecutorService of java.util.concurrent offers a richer API if you need it.

  • Can't believe java.util.Timer was voted as the answer. Quartz is really a much better choice.

    A big advantage of quartz over java.util.Timer is that with quartz the jobs can be stored in the db. As a result one jvm can schedule and another can execute. Also (obviously) the request survives across jvm restarts.

    Hanno Fietz : Yeah, but I needed something really simple, without additional dependencies. I've got persistence handled in my app anyway, the scheduler doesn't need it itself. I've got Quartz on my list though, should I need more power later on.
    Alex Miller : In the most recent release, you can now cluster Quartz jobs with Terracotta in addition to a database.
    StaxMan : It's funny that Quartz persistence features are touted as a big advantage: in many/most cases they are just a big PITA.
    Pat : Depends if you are scheduling a one-shot job or a repeated job. For repeated jobs, I agree db persistence is a PITA.
  • Probably more interesting is if you want to use a library that fits better with Java's concurrency libraries (particularly Executors and ScheduledExecutors) then HA-JDBC has a CronExecutorService interface, implemented by its CronThreadPoolExecutor. Now, interestingly, it has a dependency on Quartz (to provide the CronExpression class), but I find that the two together work better than just Quartz alone. If you don't want large dependencies, its easy to extract the handful of classes from Quartz and HA-JDBC that make this happen.

    I just wanted to say that I tried extracting these classes, and it worked! I needed these three classes:

    • CronExpression (quartz)
    • CronThreadPoolExecutor (ha-jdbc)
    • DaemonThreadFactory (ha-jdbc)

    And I only had to do these minor tweaks:

    • Removing the logger from CronThreadPoolExecutor (it was created but never used)
    • Moved the constant YEAR_TO_GIVEUP_SCHEDULING_AT from CronTrigger to CronExpression

    I was thrilled that I didn't get stuck pull in a tangle of dependencies. Congrats to the class authors!

    And it's been working like a champ.

  • I would strongly recommend cron4j (already mentioned) over Quartz, unless you absolutely need some of more advanced and complex features of Quartz. Cron4j focuses nicely on what it is supposed to do, has decent documentation, and is not a kitchen-sink solution.

Event Handling With Dynamic ToolStripItem


I'm trying to dynamically add items to a toolstrip with the following code:

contextMenuStrip.Items.Add(string.Format("{0} kB/s", currSpeed), null, new EventHandler(Connection.SetSpeed));

The problem is that I need to pass a parameter to Connection.SetSpeed: currSpeed (int). How can I do that?

Thanks for your time. Best regards.

From stackoverflow
  • Calling add will return you a ToolStripItem, if you set it's Tag property to the currSpeed variable you should be able to pull that ToolStripItem out via the sender argument in the Connection.SetSpeed method when the item gets clicked...

    ToolStripItem item = contextMenuStrip.Items.Add(string.Format("{0} kB/s", currSpeed), null, new EventHandler(Connection.SetSpeed));
    item.Tag = currSpeed;
    void Connection.SetSpeed (object sender, EventArgs e)
        ToolStripItem item = (ToolStripItem)sender;
        int currSpeed = (int)item.Tag;
        // Do stuff...
    Matías : thanks! that is what i was looking for

How do I improve performance of winforms application in Mono?

I have a remoting application (2 player Magic the Gathering Game) using windows form in C# and I am seeing very poor performance in mono. One thing I can think of that might affect the performance is that I have custom images for button background and form backgrounds(.png). Moreover I heavily use card images (.jpg). Lastly I have stuck very strictly to .NET 2.0.

What can I look for to improve windows Form performance in mono? If this is not possible is there a quick winforms to gtk# converter or tool that helps in converting?

From stackoverflow
  • Have you tried profiling it? Mono has a built-in profiler. There's a page on the mono website about the mono profiler and other performance tips.

  • Did you try to profile your code. Maybe that shows you where the bottlenecks are...

    I think one big problem is

    Whereas the .Net implementation is a binding to the Win32 toolkit, the Mono implementation is written in C# to allow it to work on multiple platforms

    as mentioned here and

    System.Windows.Forms in Mono is implemented using System.Drawing. All controls are natively drawn through System.Drawing. System.Windows.Forms implements its own driver interface to communicate with the host OS windowing system.

    as described here.

    I don't know of a converter from winforms to gtk#..., but if you really want to bother with converting your game to gtk#, this might be a good starting point.

  • It would be useful if you could detail exactly what the performance problems are that you are observing.

    Mono's Windows.Forms implementation is a bit slower today due to some of the requirements imposed by trying to support the WndProc model embedded into it properly.

    It is an area that could be improved and likely many of the lessons from Wine could be applied to Mono's Winforms implementation.

    kthakore : Hi Miguel The exact problems are unknown to even me... Its just really slow. I have even compiled mono myself. I can send you my program if u would like to run it and see.

Storing SHA1 hash values in MySQL

Hi. I have a simple question which occured when I wanted to store the result of a SHA1 hash in a MySQL database:

How long should the VARCHAR field be in which I store the hash's result?

From stackoverflow
  • A SHA1 hash is 40 chars long!

    Douglas Leeder : In hex encoding...
  • I wouldn’t use VARCHAR with a variable length but a type with a fixed length. Because a SHA-1 value is always 160 bit long. The VARCHAR would just waste an additional byte for the length of the field that would always be the same.

    And I also wouldn’t store the value the SHA1 is returning. Because it uses just 4 bit per character and thus would need 160/4 = 40 characters. But if you use 8 bit per character, you would only need a 160/8 = 20 character long field.

    So I recommend you to use BINARY(20) and the UNHEX function to convert the SHA1 value to binary.

  • Output size of sha1 is 160 bits. Which is 160/8 == 20 chars (if you use 8-bit chars) or 160/16 = 10 (if you use 16-bit chars).

  • So the length is between 10 16-bit chars, and 40 hex digits.

    In any case decide the format you are going to store, and make the field a fixed size based on that format. That way you won't have any wasted space.

Removing non-numeric characters in T-SQL

I'm using the function sp_spaceused to get the details of all the tables in a DB. The index_size column is VARCHAR returned complete with ' KB' on the end, however I want to to display in MB. All I need to know is how to strip out the KB, I can do the rest! :D

From stackoverflow
  • My first thought would be to just store in in a variable and just use substring to remove the last characters.

    -- Setup
    DECLARE @data VARCHAR(50)
    SET @data = '159736 KB'
    -- Computation
    SET @data = SUBSTRING(@data, 1, LEN(@data)-2)
    -- Conversion
  • REPLACE(column, 'KB', ''). No need for LEN and other stuff

    On SQL 2005, this will give you the "reserved" value:

        SUM(au.total_pages) / 128.0 AS UsedMB
        sys.allocation_units au

    Some more investigation should allow you to read index vs data space out of the catlog views too

  • More generic solution:

    -- Test data
    DECLARE @StrIn VARCHAR(100), @StrOut VARCHAR(100), @I INT, @Len INT
      SELECT @StrIn = '123m43 5m409', @StrOut = '', @I = 0, @Len = Len(@StrIn)
    -- Answer
    WHILE (@I < @Len) BEGIN 
      SELECT @I = @I + 1, 
        @StrOut = @StrOut + 
            WHEN (CAST(ASCII(SUBSTRING(@StrIn, @I, 1)) AS INT) BETWEEN 47 AND 58) 
            THEN SUBSTRING(@StrIn, @I, 1) ELSE '' 
    SELECT @StrIn, @StrOut
  • Thanks for the script, it was very helpful. Only one minor issue. The WHILE loop needs to be <= @Len. Otherwise the last digit may be lost.

Elegant way to read business rules stored in XML file

I have to read business rules stored in XML file (I am using VC++/MFC/MSXML). XML consists of rules. Each rule has a set of conditions and actions. What would be an elegant OOP design for such system? What design patterns would you use if you where a designer of such system?

Rules are put in sequence and executed one buy one if all conditions of rule are met.

example of xml:

      <!--  rule no. 1 -->
      <rule name="rule no. 1">
            <condition name="condition no. 1" type="ATTR_EMPTY">
                  <parameter name="attribute_name">ttt</parameter>
                  <parameter name="workflow_id">3</parameter>
                  <parameter name="workflow_state_id">5</parameter>
            <condition name="condition no. 2" type="ATTR_EMPTY">
                  <parameter name="attribute_name">ttt</parameter>
                  <parameter name="enviroment_id">3</parameter>
            <action name="action no. 1" type="ATTR_CLEAR">
                  <parameter name="attribute_name">ttt</parameter>
From stackoverflow
  • XML is really just the low level transport layer, is the any higher level format on top of it you using? That way you can get recommendations to specific libraries.


    OK a downvote so this wasn't the answer you were looking for.

    You could probably get an oo design but you will need to post a snippet of the xml or a detailed specification.

    Darius Kucinskas : Down vote was not from me, I am interesting in all opinions equally...
  • How do you intend to model these rules in memory?

    One way of representing these rules in memory is using a higher-level programming language (e.g. python). Translate your XML rules into python code with the equivalent flow of control that invokes your C++ objects when it is executed. I've actually done that in the past to implement a rule system. I used JavaScript as both the serialization format of the rules (much easier to define rules in JS than in XML, and much more readable) and also as the actual executed code (I used SpiderMonkey to do C++<->JS). But you can do it basically in any popular script language that has C++ binding.

  • Difficult to tell from such a brief description, but I would make each rule an object which manages its own conditions and actions. The rules would be created by a factory from the XML and stored in some sort of dictionary.

  • There are two designs I'd consider, one is the one shot evaluator (your application runs once with a set of rules versus data and then exits) in this case I'd use an XML SAX parser with callbacks that handle the data

    The other is a DOM parser that caches rules in memory using a Rule Class that's a composite of a Condition(Check) class and an Action class.

  • The rules part looks a little like Schematron:

    which is an XML validation language written in XML and an ISO standard.

    Assuming the source data (that is being validated) is also in XML, one approach would be to transform your set of rules into Schematron (which would not be hard in XSLT) and then use the Schematron "infrastructure" (ie, stylesheets) to validate your content against the Schematron file.

    This would produce a result XML file showing which rule has been satisfied and which has not; you may then perform the "actions" (transformations?) associated with each verified rule.

  • Also check out RulesML...

  • Writing business rules in XML is clunky. Besides, C++ is also not a good language for XML processing.

    Your application can expose its properties through Active Scripting, and write rules in VBScript/JScript. In this way you can evaluate rules at run time.

    If XML is required for defining rules, I would write the processor separately in a high level language such as Java, JavaScript or XSLT. Run the processor at background and grabs the return value in your C++ application.