Supertext Home
Chief of the System Blog

Archive for the 'C#' Category


Collection was modified; enumeration operation may not execute

Wednesday, July 29th, 2009

Ever tried to remove or change something in a C# Enumeration while you iterate over it? Yes, it does not work very well.

But there are ways around it.

foreach (Item item in items.ToArray())
{
    if (item.Visible == false)
    {
        items.Remove(item);
    }
}

The simplest way is to use ToArray(). No much coding, no complicated loops, but obviously not very efficient for larger lists.

A few alternatives are presented by Kevin Ransom.


Using Log4Net for a Windows Console Application

Wednesday, February 11th, 2009

Most examples with Log4Net are with ASP.NET, but it works perfectly fine with Windows Form and Console Applications too.

What you need is an App.config file that you add to your project.

<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" /> </configSections> <!-- Log4net Logging Setup --> <log4net debug="false"> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <param name="File" value="C:\\directory\\supertext_outsidetasks.log"/> <param name="AppendToFile" value="true"/> <maxSizeRollBackups value="10"/> <datePattern value="yyyy-MM-dd"/> <rollingStyle value="Date"/> <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/> <layout type="log4net.Layout.PatternLayout"> <header value="Date | Level | SessionID | Logger | Message | &#xA;"/> <param name="ConversionPattern" value="%date{ABSOLUTE}| %-5p | %-30logger| %m|%n"/> </layout> </appender> <root> <priority value="DEBUG"/> <appender-ref ref="RollingLogFileAppender"/> </root> </log4net> </configuration>

Then initialize it in your main() function:

using log4net; using log4net.Config; static void Main(string[] args) { log4net.Config.XmlConfigurator.Configure(); //your code }

And you can use it like in ASP.NET:

log.Info("Hello Logfile");

The only issue I had was that adding the configSection like this did not work:

<configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/> </configSections>

I had to add the whole shebang with Version, etc. to it. Then it started working. Anyone else had that problem?

Anyway, are people still using Log4Net? There is not much activity on the project anymore and the last version is getting pretty old.


Unknown server tag ‘asp:ListView’

Saturday, November 8th, 2008

If you get this message after you upgraded to ASP.NET 3.5 and possible SP1, make sure you have the following settings correctly in your web.config file:

 

<assemblies> <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <pages> <controls> <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </controls> </pages>

And by the way, there is no ASP.NET 3.5 Version on the ASP.NET tab in the IIS 6.0. It’s still running on 2.0. Just in case you were trying to figure out what was wrong with your installation (I was too).


Find checked Radio Button in ASP.NET

Friday, February 22nd, 2008

If you need a little more layout freedom than the RadioButtonList gives you in ASP.NET you have to resort to the normal RadioButton. Unfortunately there is no easy way to afterwards figure out which button has been checked.

Here is a simple recursive Script in C#:

/// <summary> /// Searches recursivly through the controls tree for the /// Checked RadioButton. /// </summary> /// <param name="parent"> /// Control that contains the RadioButtons, can be the Page object. /// </param> /// <param name="groupName"> /// Name of the RadioButton Group /// </param> /// <returns>The RadioButton, null if it is not found</returns> public RadioButton GetCheckedRadioButton( Control parent, string groupName) { foreach (Control ctrl in parent.Controls) { if ((ctrl is RadioButton) && ((RadioButton)ctrl).GroupName.Equals(groupName) && ((RadioButton)ctrl).Checked == true) { return (RadioButton)ctrl; } else if (ctrl.Controls.Count > 0) { Control fromChild; fromChild = GetCheckedRadioButton( ctrl, groupName); if (fromChild != null) return (RadioButton)fromChild; } } return null; }//end GetCheckedRadioButton

A function in VB would be very similar. Good luck!


See search results as you type - An ASP.NET Ajax Control

Tuesday, June 19th, 2007

Search as you type

Highrise and other new Ajax enabled tools have this feature that when you type in a search query, it automatically updates the search results below. It’s almost like a Auto-Complete Box, but with full results on the page instead of a drop down list below the control. Unfortunately I didn’t find anything like this in the Microsoft ASP.NET Ajax Toolkit.

So there was only one solution, build it myself.

Here is the result:

Live Demo
VS 2008 Solution with Source Code
There is some other stuff in there too, but the demo for this project is under /RemyExamples/DelayedSubmitExample and the source code for the Control under /DelayedSubmit.

It’s my first Ajax Control, so I’m sure there is room for improvements. I’ve tested it in IE7, FF and Safari. Seems to work fine in all of them.

I used the Membership Editor Example from Peter Keller and TextChangedBehavior.js from Garbin as my inspiration and resource, but started with a VS ASP.NET Ajax Control Project to get the framework up and running.

The only thing the code really does is start a time on the keyup event, stop the time on keydown and after the time fires, it executes the onchange method of the associated Textbox. This way we get a delayed postback after the user stopped typing and not tons of postbacks when he’s still writing something.

_onkeyup : function(ev) {
    var k = ev.keyCode ? ev.keyCode :
                ev.rawEvent.keyCode;
    if (k != Sys.UI.Key.Tab) {
        this._timer.set_enabled(true);
    }
},

_onkeydown : function(ev) {
    this._timer.set_enabled(false);
},

_onTimerTick : function(sender, eventArgs) {
    this._timer.set_enabled(false);

    if(this._text != this.get_element().value) {
        this._text = this.get_element().value;

        this.get_element().onchange();
    }
},

Everthing else is just setup and teardown code. In the ASP page, one can just add this Control like any other Extender and add an OnChange handler to the textbox.

<cc1:DelayedSubmitExtender ID="DelayedSubmit"
    runat="server" Timeout="1000"
    TargetControlID="TextBox1"/>
<asp:TextBox ID="TextBox1" runat="server"
    AutoPostBack="True"
    OnTextChanged="TextBox1_TextChanged"
    Columns="50"></asp:TextBox>

Please let me know how it goes and if it is of any use. Good luck!

 

kick it on DotNetKicks.com