# Thursday, August 06, 2009

I’m currently building a Silverlight 3.0 Business Application with a customer. I really like the ability of Blend to open the current solution in Visual Studio. But what about vice versa? nada!

So I hacked a small Visual Studio AddIn to do the job for me:

image

 Download

Thursday, August 06, 2009 7:26:47 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [0]  | 
# Sunday, June 14, 2009

Auch in diesem Jahr veranstaltet der Just Community e.V. wieder das größte Developer und IT-Pro Community Event. Unter dem Motto „Check-In zum Wissensvorsprung“ holen wir am 28.08.2009 zahlreiche nationale und internationale Speaker nach Wuppertal. Neben den Vorträgen haben Sie natürlich auch dieses Jahr wieder viel Zeit für das Networking mit anderen ITlern aus Nah und Fern.

Alle Informationen, wie die Agenda und eine Übersicht über die Speaker gibt es unter http://www.nrwconf.de/.

nrwconf09attendeebutton

Wir freuen uns, Ihnen auch dieses Jahr sowohl bekannte Gesichter, als auch neue Speaker vorstellen zu dürfen. Die Veranstaltung wurde in diesem Jahr möglich durch unsere Sponsoren: Hewlett Packard, devcoach, Microsoft Deutschland, Brockhaus AG, Itemis AG, sepago GmbH, MT AG, sowie weiteren Unternehmen.

Eine weitere Neuerung in diesem Jahr ist der Workshop Day, der am Vortag der eigentlichen Konferenz – sprich am 27.08.2009 – in den Räumlichkeiten unseres Sponsoren Ontaris GmbH stattfindet. Der Developer-Workshop befasst sich mit der Microsoft Web Platform und behandelt die Themen Rich Internet Applications mit Silverlight 3.0 und Web 2.0 Applikationen mit ASP.NET AJAX und JQuery. Die Workshops haben eine begrenzte Teilnehmerzahl (je acht) um den Lernerfolg zu garantieren. Also schnell einchecken…

Sunday, June 14, 2009 11:07:00 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [2]  | 
# Wednesday, June 10, 2009

Am 5. Juni war ich als Sprecher beim “Project Springboard” zu Gast. Dennis Zielke und das Student Partner Team haben ganze Arbeit geleistet und ein Spitzen Event auf die Beine gestellt – nochmal nochmal nochmal!

image

Mein Vortrag “IIS, PHP & WCF – Web Services InterOp” hat wirklich Laune gemacht und ist laut Feedback bester Vortrag der Konferenz – DANKE, IHR WARD EINE SUPER AUDIENCE!!!

image 

Hier nun wie versprochen das Slide und der Code (PHP gehostet über FastCGI im IIS 7.0 ruft über SSL und Basic Athentication einen WCF Service mit einer Complex-SOAP-Message auf…): springbreak_IIS_PHP_und_WCF.zip

C# | Event | Projects | Security | WCF
Wednesday, June 10, 2009 9:42:19 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [1]  | 
# Wednesday, November 12, 2008

image 

The user group met today at netzkern, a company in Wuppertal specialized in .net development and SiteCore - thanks the venue and drinks! Thanks to Matthias for the pic!

This time we had "Sliverlight 2 in the real world" as a topic presented by Florian Kruesch. He presented new visual features as well as use cases and projects he's working on. Because he didn't touch the non-visual stuff like Isolated Storage he invited me to show something that I've build with the bits:

The "Silverlight Cache" for javascript - most commonly used to cache json returned by web services.

image

A lovely way to reduce traffic :-)

Wednesday, November 12, 2008 10:23:58 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Saturday, October 18, 2008

What is life without security. In the last posts I told you how to do URLRewriting with the ASP.NET 3.5 RoutingEngine and how to pass query strings to the destination Web Form. In this post I'll add some authorization code to let ASP.NET Authentication mechanisms play well.

The first step is to figure out which authentication mechanism has taken place in the local configuration file. For the case of forms based authentication it would be nice to redirect to the configured login Web Form, for all other authentication mechanisms we can only throw a security exception and set a HTTP status code.

I only wanted this operation to be executed once and therefore I implemented as static and thread safe property with a backing field and a lock object:

private static string s_authenticationType;
private static object s_authenticationTypeLock = new object();
private static string AuthenticationType
{
    get
    {
        if (string.IsNullOrEmpty(s_authenticationType))
        {
            lock (s_authenticationTypeLock)
            {
                if (string.IsNullOrEmpty(s_authenticationType))
                {
                    var authenticationSectionObject =
                        WebConfigurationManager.GetSection(
                        "system.web/authentication");

                    var authenticationSection =
                        authenticationSectionObject
                            as AuthenticationSection;

                    if (authenticationSection != null)
                    {
                        s_authenticationType =
                            authenticationSection.Mode.ToString();
                    }
                }
            }
        }
        return s_authenticationType;
    }
}

 

Now its time to check the authorization on the target Web Form:

if (httpContext != null &&
    !UrlAuthorizationModule.CheckUrlAccessForPrincipal(
        VirtualPath,
        httpContext.User,
        httpContext.Request.HttpMethod))
{
    if (AuthenticationType.
        Equals("forms", StringComparison.OrdinalIgnoreCase))
    {
        VirtualPath = FormsAuthentication.LoginUrl;
        queryString =
            new StringBuilder(
                string.Concat(
                    "?ReturnUrl=",
                    requestContext.HttpContext.Server.UrlEncode(
                        requestContext.HttpContext.Request.RawUrl
                        )));
    }
    else
    {
        throw (new SecurityException());
    }
}

Next I will add a login Web Form to the site and drop a LoginControl to the form:

image

And add some code behind:

using System;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class login : Page
{
    protected void OnLoggingIn(object sender, LoginCancelEventArgs e)
    {
        //TODO: add some auth logic or use membership...
        FormsAuthentication.RedirectFromLoginPage(
            "lennybacon", 
            false);
    }
}

Authorization requires an authorization and therefore I enable ASP.NET forms based authentication that also is compatible to ASP.NET Membership in the configuration file:

<configuration>
  <system.web>
    <authentication mode="Forms"/>
...

 

I can configure the authorization settings for the destination Web Forms are also in the web.config file by adding location sections:

<configuration>
  ...
  <location path="Default2.aspx">
    <system.web>
      <authorization>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>
...

 

Running the web site and clicking the link to the route (/other) that targets the Default2.aspx results in showing up the login.aspx.

image

Notice that the address bar has not changed - the usual roundtrip for redirecting to the loginURL is also "rewritten" inside of ASP.NET.

 

This way the security is easily plugged into the RoutingHandler class - Cool stuff! 

Article | ASP.NET | C#
Saturday, October 18, 2008 8:56:33 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [1]  | 
# Thursday, October 16, 2008

In the last post I showed how to use the ASP.NET 3.5 Routing Engine for URLRewriting purposes. I want to go further in this post by adding the ability to add variables into a route path and forward and append query string variables to the destination Web Form request.

A route can contain one or more variables expressed by its {name}.

 
RouteTable.Routes.Add( 
    new Route(
        "articles/{id}", 
        new devcoach.Web.RoutingPageHandler()));

 

Inside of the RoutingHandler we can iterate through the variables by accessing them by the RouteData property on the parameter passing the RequestContext:

 

var queryString = new StringBuilder("?");
foreach (var aux in requestContext.RouteData.Values)
{
    queryString.Append(
        requestContext.HttpContext.Server.UrlEncode(aux.Key));
    queryString.Append("=");
    queryString.Append(
        requestContext.HttpContext.Server.UrlEncode(
            aux.Value.ToString()));
    queryString.Append("&");
}
queryString.Remove(queryString.Length - 1, 1);

 

The problem now is that the method CreateInstanceFromVirtualPath of the BuildManager class does not allow us to pass for instance a query string as a parameter (I had this discussion recently with Holger at the speakers party of the Basta! confrence):

 

var handler = 
    (IHttpHandler)BuildManager.CreateInstanceFromVirtualPath(
        VirtualPath,
        typeof(Page));

 

Passing URL Parameters (a query string) to the instance of the page created from its virtual path we can use the good old RewitePath method (which should be familiar for everyone who has rewritten URLs with ASP.NET 2.0):

 

HttpContext.Current.RewritePath(
    string.Concat(
        VirtualPath,
        queryString));

var handler =
    (IHttpHandler)BuildManager.CreateInstanceFromVirtualPath(
        VirtualPath,
        typeof(Page));

 

It feels a bit strange to use the old fashioned way of rewriting URLs just to pass a query string, but the routing handler will stay in control of the request and only the context  variables gets modified.

 Listening to: Elbow - Grounds for Divorce

Article | ASP.NET | C#
Thursday, October 16, 2008 5:26:29 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [2]  | 
# Wednesday, October 15, 2008

With ASP.NET MVC comes a component that is called the routing engine. In ASP.NET MVC it is responsible to assign a controller to an incoming request:

image

From an conceptional view the routing engine consists of two parts:

a) The RouteTable which stores the information which routes are defined

b) The UrlRoutingModule which finds matches to routes on incoming requests.

image

But the routing engine is not limited to MVC in its use. The ASP.NET 3.5 Routing Engine is a powerful instrument for URLRewriting.

Lets have a look how to use routing standalone or with classic ASP.NET (wow, now its already classic! Never dreamed that this would happen so fast... But hey, the .NET platform is nearly ten years old...):

1. First I added the HttpModule to you configuration file:

<httpModules>
  <add 
   name="urlRouting"   
   type="System.Web.Routing.UrlRoutingModule, 
         System.Web.Routing, 
         Version=3.5.0.0, 
         Culture=neutral, 
         PublicKeyToken=31BF3856AD364E35"/>

2. Second I created a routing handler by implementing the IRouteHandler interface which comes from System.Web.Routing. I've put a simple if-else together to route to different pages:

using System.Web;
using System.Web.Compilation;
using System.Web.Routing;

namespace devcoach.Web
{
    public class RoutingPageHandler 
        : IRouteHandler
    {
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
         var VirtualPath = pathData.VirtualPath.Contains("articles") 
                ? "~/Default.aspx" 
                : "~/Default2.aspx";

            var handler = (IHttpHandler)BuildManager.CreateInstanceFromVirtualPath(
                VirtualPath,
                typeof(Page));

            return handler;
        }
    }
}
 

3. Third I registered the routes to the RouteTable from within the Global.asax file:

<%@ Import Namespace="devcoach.Web"%>
<%@ Import Namespace="System.Web.Routing"%>
<%@ Application Language="C#" %>
 
<script runat="server">  
static void RegisterRoutes()
{
    RouteTable.Routes.Add(
        new Route(
            "articles", 
            new RoutingPageHandler()));
            
    RouteTable.Routes.Add(
        new Route(
            "other", 
            new RoutingPageHandler()));        
}
void Application_Start(object sender, EventArgs e)
{
    RegisterRoutes();
} 
 
And here we go already:
image 
 
Basic URLRewiting in a few minutes. Quite neat, eh. Definitely worth a try... 
 
Now listening to: Flobots - Handlebars
Article | ASP.NET | C#
Wednesday, October 15, 2008 1:17:33 AM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [1]  | 
# Friday, October 19, 2007

A few days ago a developer at a customer asked me how he could simplify the following code as he identified a pattern: X tries and the error handling.

public PlanungsGruppenLesenA PlanungsGruppenLesen(
    PlanungsGruppenLesenF param)

{

    PlanungsGruppenLesenA ret = new PlanungsGruppenLesenA();

 

    if (ret.PlanungsGruppen == null)

    {

        throw new ArgumentNullException("param.PlanungsGruppen");

    }

    int nRetry = 0;

    while (nRetry < DBWerkzeug.MaxWiederholungen)

    {

        try

        {

            using (XXX_POC.POC db =

                new XXX_POC.POC(
                    DBWerkzeug.GetConnectionString()))

            {

                var q =

                    from p in db.Stammdaten_Planungsgruppe

                    orderby p.Name.ToLower()

                    select new PlanungsGruppeDM

                    {

                        ID = p.Rowid,

                        Name = p.Name

                    };

                ret.PlanungsGruppen = q.ToList<PlanungsGruppeDM>();

            }

        }

        catch (ChangeConflictException e)

        {

            nRetry++;

            if (nRetry >= DBWerkzeug.MaxWiederholungen)

            {

                ret.FehlerText = e.Message;

                ret.HatFehler = true;

                throw;

            }

        }

        catch (Exception e)

        {

            ret.FehlerText = e.Message;

            ret.HatFehler = true;

            throw;

        }

    }

    return ret;

}

I ended up with this:

public PlanungsGruppenLesenA PlanungsGruppenLesen(
    PlanungsGruppenLesenF param)

{

    PlanungsGruppenLesenA ret = new PlanungsGruppenLesenA();

 

    if (ret.PlanungsGruppen == null)

    {

        throw new ArgumentNullException("param.PlanungsGruppen");

    }

    ret.PlanungsGruppen = CatchExceptions<PlanungsGruppeDM>(

        delegate

        {

            using (XXX_POC.POC db =

                new XXX_POC.POC(
                    DBWerkzeug.GetConnectionString()))

            {

                var q =

                    from p in db.Stammdaten_Planungsgruppe

                    orderby p.Name.ToLower()

                    select new PlanungsGruppeDM

                    {

                        ID = p.Rowid,

                        Name = p.Name

                    };

                return q.ToList<PlanungsGruppeDM>();

            }

        },

        ret);           

    return ret;

}

What calls the encapsulated X tries and the error handling:

public delegate List<T> MachMal<T>();

 

public static List<T> CatchExceptions<T>(MachMal<T> machMichFertig, BasisA ret)

{

    int nRetry = 0;

    while (nRetry < DBWerkzeug.MaxWiederholungen)

    {

        try

        {

            return machMichFertig();

        }

        catch (ChangeConflictException e)

        {

            nRetry++;

            if (nRetry >= DBWerkzeug.MaxWiederholungen)

            {

                ret.FehlerText = e.Message;

                ret.HatFehler = true;

                throw;

            }

        }

        catch (Exception e)

        {

            ret.FehlerText = e.Message;

            ret.HatFehler = true;

            throw;

        }

    }

    return null;

}

But I'm not quite sure If this made stuff really easier ;-)

C# | Projects
Friday, October 19, 2007 4:20:12 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, April 04, 2007

My colleague Sergey is working on a really nice package around CardSpaces. Watch his blog for updates...

C# | Misc | Projects | Security
Wednesday, April 04, 2007 9:44:26 AM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [0]  | 
# Sunday, August 13, 2006

Microsoft introduces with Vista/IE7/Office2007 the Microsoft RSS Platform -

For some reasons my IE is not able to export the feeds that I read in IE7 and Outlook 2007 to OPML.

I had a look at the API and wrote this small console applictaion to export my feed list to the OPML format.

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Xml;
 
using Microsoft.Feeds.Interop;
using System.Collections.Generic;
 
namespace RssWindowsPlatformOpmlExporter
{
    class Program
    {
        static void Main(string[] args)
        {
            string pathToExport = "D:\\temp\\feeds.opml";
            if (args.Length > 0)
            {
                pathToExport = args[0];
            }
 
            FeedsManager mgr = new FeedsManager();
            Queue<IFeedFolder> queue = new Queue<IFeedFolder>();
            queue.Enqueue(mgr.RootFolder as IFeedFolder);
 
            while (queue.Count > 0)
            {
                IFeedFolder currentFolder = queue.Dequeue();
                IFeedsEnum subFolders = (IFeedsEnum)currentFolder.Subfolders;
 
                for (int i = 0; i < subFolders.Count; i++)
                {
                    queue.Enqueue((IFeedFolder)subFolders.Item(i));
                }
 
                using (XmlWriter opml = XmlWriter.Create(pathToExport))
                {
                    opml.WriteStartDocument();
                    opml.WriteStartElement("opml");
                    opml.WriteAttributeString("version", "1.0");
 
                    IFeedsEnum feeds = (IFeedsEnum)currentFolder.Feeds;
                    for (int i = 0; i < feeds.Count; i++)
                    {
                        IFeed feed = (IFeed)feeds.Item(i);
 
                        try
                        {
                            if (!string.IsNullOrEmpty(feed.Title) 
                                && !string.IsNullOrEmpty(feed.DownloadUrl))
                            {
                                opml.WriteStartElement("outline");
                                opml.WriteAttributeString("title", feed.Title);
                                opml.WriteAttributeString("xmlUrl", feed.url);
                                opml.WriteEndElement();
                            }
                        }
                        catch (COMException e)
                        {
                            Console.WriteLine(
                                "Error getting feed: {0}", 
                                e.Message);
                        }
                    }
 
                    opml.WriteEndElement();
                    opml.WriteEndDocument();
                }
            }
        }
    }
}
C# | Misc
Sunday, August 13, 2006 3:42:42 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [0]  | 
# Monday, July 17, 2006

thinktecture and newtelligence AG present a week of Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF) and Windows Workflow Foundation (WWF): TornadoCamp WinFX.

Christian, Ingo, Michael and me will present from the 16th - 20th of october in Bad Ems in GERMAN!

C# | Event | Indigo | WCF
Monday, July 17, 2006 1:57:23 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [0]  | 

I posted some Bits Michael and I wrote recently in a WCF Project:

The Constraints-Extensions let you easily define attribute based limitations for input, output and return parameters. Limitations can be set to service contracts operations as well as to data contract data member implementations. The constraints validation gets called at runtime by the WCF infrastructure and the behavior will throw a ConstraintViolationException with descriptive messages in case of a constraint gets violated/the validation fails.

The following constraint attributes have been implemented:

  • Between
  • BetweenExclusive
  • CompareAgainst
  • EarlierThanNow
  • EarlierThanToday
  • EqualTo
  • GreaterEqualTo
  • GreaterThan
  • LaterThanNow
  • LaterThanToday
  • LessEqualTo
  • LessThan
  • Match
  • MaxElements
  • MaxLength
  • MinElements
  • MinLength
  • NotBetween
  • NotEmpty
  • NotEqualTo
  • NotNull
  • Nullable
  • OneOff·    

Data Contract Sample:

[DataContract]
class
TestClass
{
    [DataMember]
    [LessEqualTo(CompareAgainst.FieldOrProperty,"EndDate")]
    public DateTime StartDate;

    [DataMember]
    [GreaterEqualTo(CompareAgainst.FieldOrProperty, "StartDate")]
    public DateTime EndDate;

    public TestClass(DateTime startDate, DateTime endDate)
    {
        StartDate = startDate;
        EndDate = endDate;
    }
}

 

Service Contract Sample:

[ServiceContract, ConstraintsValidatorBehavior]
interface
ITestConstraints
{

    [OperationContract]
    [return:GreaterEqualTo(0)]
    int MethodA(
        [Between(0,100)]
        int a,
        [LessEqualTo(20)]
        double b,
        [NotEmpty]
        string c); 

    [OperationContract]
    int MethodB(
        [Between(0, 100)]
        int a,
        [LessEqualTo(20)]
        ref double b,
        [NotEmpty]
        out string c);

    [OperationContract]
    [return:LaterThanNow]
    DateTime MethodC(
        [GreaterThan(0)]
        int a);

 

    [OperationContract]
    void MethodD(
        [VerifyObject]
        TestClass a);
}


Download at wcf.netfx3.com

C# | Indigo | Projects | WebServices | WCF
Monday, July 17, 2006 1:43:28 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [1]  | 
# Tuesday, May 16, 2006

Two tools really useful if you work with AJAX

ASP.NET | C#
Tuesday, May 16, 2006 2:04:19 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, February 23, 2006

Sometimes it happens that a form is processing and you need to make sure that the users don't panic and run away before it finishes.

A splash screen with a "Loading..." indicator can help to calm down frightened users and make life easier for technical support staff.

Back in the days of classic ASP (VBScript) which used a linear programming approach we had to start by setting the response buffer to true:

This line does nothing but instructing the server NOT to send anything back to the client until the page has been finished processing.

An exception can be forced by calling the flush command:

Calling flush lets the server send everything to the client that is processed so far.

This will also speed up your page since the server doesn't have to switch back and forth between executing the page and sending bits to the browser.

Using this we were able to accomplish the following steps:

Send e.g. a div-layer containing a "Loading..." graphic to the client
Process the long running task.
Send the results of the long running task to the client
Send a client side script to the client, that hides the div-layer containing the "Loading..." graphic

   1: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   2: <html xmlns="http://www.w3.org/1999/xhtml">
   3: ...
   4: <body>
   5: <div id="splashScreen">
   6: <img src="wait.gif" width="75" height="15" />
   7: </div>
   8: <script type="text/javascript"></script>
   9: </body>
  10: </html>

I haven’t mentioned yet that client side Javascript initially checks what kind of browser we have to deal with (either up level like Internet Explorer 7.0, other Internet Explorer’s or Netscape 4.x).

But with ASP.NET we have got a complete different way of how the page is executed. Today we have a Page class, which has an event based execution model and controls – so how can this mechanisms be used in ASP.NET?

The difference between classic ASP and ASP.NET, that initially seems to be a problem, is really an advantage. It gives us the ability to write and store our code in a more structured manor.

This way we can separate infrastructure code form application logic code. It lets us focus on the things we, as application developers, really need to do – To get things done.

First of all we need to do a few initial steps:

· Start Visual Studio (or use notepad.exe)

· Creating a new Project of the type “Class Library” (on skip this if you are using notepad)

· Rename Class1.cs to WaitScreen.cs (or just save your file as WaitScreen.cs using notepad)

· Add a reference to the namespace “System.Web” (or remember to add the compiler switch /r pointing to the assembly System.Web.dll)

After our environment has been set up we can start writing the code. First we outline the class to use it as a WebControl by deriving it from the WebControl class.

   1: using System;
   2: using System.ComponentModel;
   3: using System.Web.UI;
   4: using System.Web.UI.WebControls;
   5:  
   6: namespace devcoach.Web.UI.Controls
   7: {
   8:     /// <summary>
   9:     /// The WaitScreen control displays a grafic while a long running operation 
  10:     /// is running.
  11:     /// </summary>
  12:     public class WaitScreen : WebControl
  13:     {
  14:     }
  15: } 
  16:  

Controls are reusable components so it is important to let the client side developer (the guy who uses the control in Visual Web Developer – this might also be you…) the opportunities to customize the layout of the control. In our case the only customization that can be done would be a different graphic that is displayed during the long running operation is executed on the server. Here is the code that allows the client side developer to easily set a URL, pointing to an graphics file, form an attribute on the ServerContol or by directly setting the value of the property from the code behind.

   1: // This field holds the URL pointing to an image
   2: private string m_ImageUrl = "~/images/busy.gif";

The private field m_ImageUrl is initialized with a default image on the instantiation of the class so – if the image exists – the client side developer mustn’t explicitly set anything.

   1: /// <summary>
   2: /// Gets/sets the URL pointing to an image.
   3: /// A string containing the URL pointing 
   4: /// to an image..
   5: /// This property gets/sets the URL pointing to an image.
   6: /// </summary>
   7: [Description("Gets/sets the URL pointing to an image.")]
   8: public string ImageUrl
   9: {
  10:     get { return m_ImageUrl; }
  11:     set { m_ImageUrl = value; }
  12: } 

The property ImageUrl just gives public access to the private field m_ImageUrl. Having (again) the client side developer in mind we provide the XML comments summary, value and remarks and additionally set the description attribute, which allows Visual Studio to display details in the properties window.

Delegates and events are one of the most powerful tools that come with .NET Framework and we can use them to let the client developer attach his/her custom long running operation as custom event handler code. Even more then one method can be attached so that all together are the “one long running task” that is processed while the graphic is displayed. Separated nicely from the infrastructure code (the control we are currently writing). Here is our event code:

   1: public delegate void ProcessHandler(object sender, EventArgs e);
   2:  
   3: public event ProcessHandler Process;

The OnProcess method triggers the event and invokes the attached custom long running operations.

Now that the ability is given that custom code can be executed using the event/delegate we need to actually raise the event and before that ensure that the response buffer is set to true and the graphic is send to the client. The load event of out control does this job for us.

   1: /// <summary>
   2: /// Triggers the Load event.
   3: /// </summary>
   4: protected override void OnLoad(EventArgs e)
   5: {
   6:     base.OnLoad(e);
   7:  
   8:     Page.Response.Buffer = true;
   9:  
  10:     #region Show splash screen
  11:     Page.Response.Write("...");
  12:     #endregion
  13:  
  14:     Page.Response.Flush();
  15:  
  16:     OnProcess();
  17:  
  18:     Page.Response.Flush();
  19:  
  20:     #region Hide splash screen
  21:     Page.Response.Write("...");
  22:     #endregion
  23: }

After OnProcess is called we call Flush like we did in classic ASP and send the piece of client side script to the client that will hide the div-layer containing the graphic indicating the user that something is happening.

On the client side the control can now be used as follows in the *.aspx-Page:

   1: <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
   2: <%@ Register Assembly="devcoach.Web.WaitScreen" Namespace="devcoach.Web.UI.Controls" TagPrefix="ctrl" %>
   3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   4:  
   5: <html xmlns="http://www.w3.org/1999/xhtml" >
   6: <head runat="server">
   7:     <title>Untitled Page</title>
   8: </head>
   9:  
  10: <body>
  11:     <form id="form1" runat="server">
  12:     <div>
  13:     
  14:     <ctrl:WaitScreen ID="WaitScreen" runat="server" OnProcess="WaitScreen_Process" />
  15:     
  16:     </div>
  17:     </form>
  18: </body>
  19: </html>

And the associated code behind page:

   1: using System;
   2: using System.Threading;
   3: using System.Web.UI;
   4:  
   5: public partial class _Default : Page 
   6: {
   7:     protected void WaitScreen_Process(object sender, EventArgs e)
   8:     {
   9:         // Put long running operation in here...
  10:         Thread.Sleep(4000);
  11:     }
  12: }

Design-time isn’t as easy as I would wish and therefore the functionality in this specific area is often kept short or even missing. One of the biggest problems is the missing HttpContext. Without it we cannot ask for example for the path of the current page, web environment variables, URL-parameters and so on…

Our control is really a good example to show how we can add this kind of functionality because it is quite simple. The goal is to show the image set by the control default or the client side developer in the designer of Visual Web Developer.

So we add a new class to our project and name it “WaitScreenDesigner.cs”. To access the built-in designer functionality we need to add reference to the “System.Design” assembly and a using declaration to the System.Web.UI.Design namespace on top of our control class. We also need to derive it from the ControlDesigner-class:

   1: /// <summary>
   2: /// The designer for the wait screen control.
   3: /// </summary>
   4: public class WaitScreenDesigner
   5:     : ControlDesigner
   6: {
   7:     /// <summary>
   8:     /// Retrieves the HTML markup that is used to represent 
   9:     /// the control at design time.
  10:     /// </summary>
  11:     /// <returns>
  12:     /// The HTML markup used to represent the control at design time.
  13:     /// </returns>
  14:     public override string GetDesignTimeHtml()
  15:     {
  16:         ...
  17:     }
  18: }

The designer of Visual Web Developer calls the method GetDesgnTimeHtml on the base class to generate the Html to display – If we override that method we can control what the designer shoes to the client side developer of our controls.

To display the defined image we need to access the property of our control from the designer’s class’s method. Visual Studio’s extensibility API’s enable us to cast form the Component property of the designer to our control and easily read values of properties. The following example gets the value of the control’s class property ImageUrl:

   1: string imageUrl = ((WaitScreen)this.Component).ImageUrl;

Now that we have the set path to an image we should be able to display the image in an <img>-Tag except the URL contains the useful „~/“, which tells ASP.NET that the path starts with the root path of the current application. To translate such an URL to a physical path that we can use we need an instance of the web application – as the control this can be achieved though casting with the Component property of the designer.

   1: IWebApplication webApp = 
   2:     (IWebApplication)Component.Site.GetService(
   3:         typeof(IWebApplication));

The next step is to find the image as project item of our web project. The IWebApplication interface provides the method GetProjectItemFromUrl, which fits our needs.

   1: IProjectItem item = webApp.GetProjectItemFromUrl(imageUrl);

On the interface IProjectItem we will now find a property called PhysicalPath that we can use as value for the src attribute of an <img>-Tag, which will be returned form the GetDesignTimeHtml method:

   1: return string.Concat(
   2:     "<img src=\"",
   3:     item.PhysicalPath,
   4:     "\" alt=\"Please wait...\" />");

Now its time to tell the Designer that our control should be rendered with our designer class we just created. This is done by assigning the DesignerAttribute to the control class.

   1: [Designer(typeof(WaitScreenDesigner))]
   2: public class WaitScreen : WebControl
   3: {
   4:     ...
   5: }

If you now look at the designer the page should look like the following screenshot:

To make it even more comfortable the control can be add to the Toolbox. But if you don’t want your control to be displayed as the “default 3rd party control grind” we still have one job to do.

Add a 16x16 pixel icon file names WaitScreen.ico to the root of the project as embedded resource. And add the following attribute to the control class:

   1: [ToolboxBitmap(
   2:     typeof(WaitScreen), 
   3:     "devcoach.Web.UI.Controls.WaitScreen.ico")]
   4: public class WaitScreen : WebControl
   5: {
   6:      ...
   7: }

The long name is in the format {default_namespace_of_project}.{filename_and_ext} just in case you wonder where the devcoach.Web.UI.Controls.” comes from.

Now you’ll see your icon instead of the “default 3rd party control grind”.

Download

Thursday, February 23, 2006 4:26:19 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [23]  | 
# Wednesday, February 01, 2006

I often get asked things through my messenger and today I decided to start sharing a few lines of the conversations...   

Frank:

Is there a way to connect a Validator to an Exception so that the validation summary can be used to display the exception message?

Lennybacon says:

1. build a Custom Validator

Frank:

Ok

Lennybacon says:

2. Use Page_Error or catch to set a "flag" to the Validator

Lennybacon says:

3. override the method EvaluateIsValid and return the state of the flag

Lennybacon says:

This way the validator (if called on the postback) indicates its validation as true and after the flag is set false.

Lennybacon says:

Here is some pseudo-code

Lennybacon says:

       try

       {

         CriticalOperation();

       }

       catch(MyException e)

       {

         MyValidator.SetInvalid();

         MyValidator.ErrorMessage = "bla bla: " + e.Message;

         Page.Validate();

       }

Lennybacon says:

       Validator : CustomValidator

       {

          bool flag = true;

          void setInvalid(){flag=false;}

          bool EvulateIsValid()

          {

               return flag;

          }

       }

 

http://www.staticdust.net/downloads/Web.ExceptionVisualizer.zip

ASP.NET | C#
Wednesday, February 01, 2006 12:05:07 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 
# Tuesday, January 24, 2006

In one of my current projects (yes, there are more at the moment and yes that is the reason why it's a bit quiet around here) i neede to write an encrypted file to the hard disc using DPAPI (Data Protection API). After I unsuccessfully searched the web and the msdn (the sample reads all bytes to the buffer at once - not so nice), I wrote the following sample app:

using System;

using System.IO;

using System.Security.Cryptography;

 

public class DataProtectionSample

{

    public static void Main()

    {

        using(MemoryStream ms = new MemoryStream())

        {

            StreamWriter swriter = new StreamWriter(ms);

            swriter.WriteLine("Text to encrypt to file.");

            swriter.Flush();

 

            Console.WriteLine("Protecting data ...");

            DataProtection.Protect("D:\\_temp\\DPAPI.dat", ms, false);

        }

        Console.WriteLine("Unprotecting data ...");

        using(MemoryStream ms2 =

            (MemoryStream)DataProtection.Unprotect("D:\\_temp\\DPAPI.dat", false))
        {

            StreamReader sreader = new StreamReader(ms2);

            Console.WriteLine("");

            Console.WriteLine("Decrypted string: " + sreader.ReadToEnd());

        }

        Console.ReadLine();

    }

}

 

public class DataProtection

{

    private static byte[] _additionalEntropy = { 9, 8, 7, 6, 5 };

    private static int _bufferLength = 1024;

 

    public static void Protect(string filename, Stream stream,

        bool machineLevel)

    {

        if (File.Exists(filename))

        {

            File.Delete(filename);

        }

        using (FileStream fs = new FileStream(filename, FileMode.CreateNew))

        {

            byte[] buffer = new byte[_bufferLength];

            long byteCount;

            stream.Position = 0;

            while ((byteCount =

               stream.Read(buffer, 0, buffer.Length)) > 0)

            {

                buffer = ProtectedData.Protect(buffer, _additionalEntropy,

                    ((machineLevel) ? DataProtectionScope.LocalMachine :

                    DataProtectionScope.CurrentUser));

                fs.Write(buffer, 0, buffer.Length);

                fs.Flush();

            }

        }

    }

 

    public static Stream Unprotect(string filename, bool machineLevel)

    {

        MemoryStream ms = new MemoryStream();

       

        using (FileStream fs = new FileStream(filename, FileMode.Open))

        {

            byte[] buffer = new byte[_bufferLength + 146];

            long byteCount;

 

            while ((byteCount =

               fs.Read(buffer, 0, buffer.Length)) > 0)

            {

                buffer = ProtectedData.Unprotect(buffer, _additionalEntropy,

                    ((machineLevel) ? DataProtectionScope.LocalMachine :

                    DataProtectionScope.CurrentUser));

                ms.Write(buffer, 0, buffer.Length);

                ms.Flush();

            }

        }

        ms.Position = 0;

        return ms;

    }

}

 

 

 

C# | Projects | Security
Tuesday, January 24, 2006 2:13:08 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Sunday, January 08, 2006

If you try to run a CREATE statement in a query (right click on a database in the Server Explorer) you receive this message.

So i wrote a small utility which will do the job for me.

using System;

using System.IO;

using System.Data.SqlClient;

using System.Collections.Generic;

using System.Text;

using System.Windows.Forms;

 

namespace MdfExec

{

    class Program

    {

        static void Main(string[] args)

        {

            string _cnStr;

 

            if (args.Length == 2)

            {

                _cnStr =

                    "data source=.\\SQLEXPRESS;Integrated Security=SSPI;" +

                    "AttachDBFilename=" + args[1] + ";User Instance=true;";

            }

            else

            {

                OpenFileDialog fd = new OpenFileDialog();

 

                fd.AddExtension = true;

                fd.DefaultExt = ".mdf";

                fd.ShowDialog();

 

                _cnStr =

                    "data source=.\\SQLEXPRESS;Integrated Security=SSPI;" +

                    "AttachDBFilename=" + fd.FileName + ";User Instance=true;";

            }

 

            using (SqlConnection _cn = new SqlConnection(_cnStr))

            {

            using(SqlCommand _cmd = _cn.CreateCommand())

                   {

                    using (StreamReader fs = File.OpenText(args[0]))

                    {

                        _cmd.CommandText = fs.ReadToEnd();

                        _cmd.Connection.Open();

                        _cmd.ExecuteNonQuery();

                    }

                   }

            }

        }

    }

}

 

You can now right click on a *.sql file choose "open with ..." and select MdfExec.exe to execute the SQL statement.

Since there is no second parameter (but needed to define to which database to connect) a OpenFileDialog will prompt:

 

Happy coding

Sunday, January 08, 2006 3:31:55 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [1]  | 

I'm quite busy with a project I'm on with Clemens (the last before he'll join the Indigo team at Microsoft) - just to explain why it got bit quiet around me :-)

Here is a modified version of the prop snippet that I want to share ( and remember :-P ).

<?xml version="1.0" encoding="utf-8" ?>

<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">

      <CodeSnippet Format="1.0.0">

            <Header>

                  <Title>prop</Title>

                  <Shortcut>prop</Shortcut>

                  <Description>Code snippet for property and

                  backing field</Description>

                  <Author>Microsoft Corporation</Author>

                  <SnippetTypes>

                        <SnippetType>Expansion</SnippetType>

                  </SnippetTypes>

            </Header>

            <Snippet>

                  <Declarations>

                        <Literal>

                             <ID>type</ID>

                              <ToolTip>Property type</ToolTip>

                             <Default>int</Default>

                        </Literal>

                        <Literal>

                             <ID>property</ID>

                             <ToolTip>Property name</ToolTip>

                             <Default>MyProperty</Default>

                        </Literal>

                        <Literal>

                             <ID>field</ID>

                             <ToolTip>The variable backing this

                             property</ToolTip>

                             <Default>myVar</Default>

                        </Literal>

                  </Declarations>

                  <Code Language="csharp"><![CDATA[#region $property$

     

      // This field holds the $property$

      private $type$ $field$;

 

      /// <summary>Gets/sets the $property$.</summary>

      /// <value>A <see cref="$type$">$type$</see>

      /// containing the $property$.</value>

      /// <remarks>This property gets/sets the $property$.</remarks>

      [System.ComponentModel.Description("Gets/sets the $property$.")]

      public $type$ $property$

      {

            get { return $field$;}

            set { $field$ = value;}

      }

      #endregion

      $end$]]>

                  </Code>

            </Snippet>

      </CodeSnippet>

</CodeSnippets>

Sunday, January 08, 2006 2:54:09 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Sunday, December 18, 2005

I just finished writing some ASP.NET code where I also typed the following lines: 

 <ItemTemplate>
	<asp:Image ID="IsOnline" 
	runat="server" 
	ImageUrl='<%# GetImageUrl((MembershipUser)Container.DataItem) %>' 
	/>
</ItemTemplate>

...

protected string GetImageUrl(MembershipUser user)
{
	if (user.IsLockedOut)
	{
		return "~/images/BadUser.gif";
	}
	else if (!user.IsApproved)
	{
		return "~/images/GreyUser.gif";
	}
	else if (user.IsOnline)
	{
		return "~/images/OnlineUser.gif";
	}
	else
	{
		return "~/images/OfflineUser.gif";
	}
}

Before I shutdown my machine I fetchted Mail and Feeds when i ran accross this posting by ScottGu pointing to Fritz Onions Blog.

;-)

Sunday, December 18, 2005 12:59:36 AM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, November 10, 2005

A short statement additional to my post against the spagetti code because I think Scott got me wrong:

The Object Data Source is one of the coolest things out there cause it's never been so easy to use n-tier applications and bind custom business objects to databound controls. And this is exactly what I tell the folks out there in my articles and talks.

ASP.NET | C#
Thursday, November 10, 2005 11:12:40 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  | 
# Monday, October 31, 2005

The most important thing to point out whenever I talk about ASP.NET 2.0 data-driven applications is:

    "With the SqlDataSource and GridView or
  DetailView controls you can
        quickly build up tiny applications that just 
     need to be set up asap.
       This has to do nothing with REAL
  best practice applications!"

Therefore I was pretty happy to read "The Code Spaghetti generation is back" in Pascal Leloup's Blog (Help .NET).

Here is my statement:

ASP.NET | C#
Monday, October 31, 2005 3:43:42 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [3]  | 
# Wednesday, October 26, 2005

[...]The .NET Framework 2.0 comes with a built-in webserver, based on the old Cassini web server. So I wanted to be able to easily set up any directory to have its contents served up on an as-needed basis. The result is an addition to the Windows Explorer right-click menu...[Robert McLaws]

Chris Fraizer wrote it thgether in a small app.

Here is my version with a few modifications:

using System;

using System.IO;

using System.Collections.Generic;

using System.Diagnostics;

using System.Windows.Forms;

using System.Text;

using System.Runtime.InteropServices;

 

namespace WebServerHere

{

    class Program

    {

        static void Main(string[] args)

        {

            if (args.Length >= 1)

            {

                string _path;

 

                string _command =

                    Path.Combine(

                    RuntimeEnvironment.GetRuntimeDirectory(),

                    "WebDev.WebServer.EXE");

 

                StringBuilder _commandArgs = new StringBuilder();

 

                Random _r = new Random();

 

                string _port = _r.Next(1024, 9000).ToString();

 

                if (args.Length == 2)

                {

                    _port = args[1];

                }

 

 

                //grab the original path

                _path = args[0];

 

                _commandArgs.Append(" /path:\"");

                _commandArgs.Append(_path);

                _commandArgs.Append("\"");

                _commandArgs.Append(" /port:");

                _commandArgs.Append(_port);

                _commandArgs.Append(" /vpath: \"/");

                _commandArgs.Append(_path.Substring(

                    _path.LastIndexOf('\\') + 1));

                _commandArgs.Append("\"");

 

                ProcessStartInfo _info =

                    new ProcessStartInfo();

 

                _info.Arguments = _commandArgs.ToString();

                _info.CreateNoWindow = true;

                _info.FileName = _command;

                _info.UseShellExecute = false;

                _info.WorkingDirectory =

                    _command.Substring(0, _command.LastIndexOf('\\'));

 

 

                Process.Start(_info);

 

                using (Control _c = new Control())

                {

                    Help.ShowHelp(_c, "http://localhost:" + _port + "/");

                }

            }

            else

            {

                MessageBox.Show("Usage:\n\tWebServerHere.exe <path> [port]",

                    "WebServerHere", MessageBoxButtons.OK,

                    MessageBoxIcon.Information);

            }

        }

    }

}

And the Non-Admin installation reg-file:

Windows Registry Editor Version 5.00

[HKEY_Current_User\SOFTWARE\Classes\Folder\shell\VS2005 WebServer]
@="ASP.NET 2.0 Web Server Here"

[HKEY_Current_User\SOFTWARE\Classes\Folder\shell\VS2005 WebServer\command]
@="\"%SystemRoot%\\System32\\WebServerHere.exe\" %1"

ASP.NET | C# | Misc | Projects
Wednesday, October 26, 2005 9:53:48 AM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [1]  | 
# Friday, September 30, 2005

Torsten Weber invited me to do one day of sessions at the .NET Summercamp: I introduced .NET 2.0 and C# 2.0 and talked about Visual Studio 2005 Team System.

It was the first time in Leipzig and i really liked it. Hopefully i'll be there next year too.

C# | Event | Team System
Friday, September 30, 2005 12:48:42 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, September 15, 2005

Cropper is a free Screen Capture Utility written in C#

http://www.thegridmaster.com/
C# | Misc
Thursday, September 15, 2005 12:34:21 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, August 10, 2005

Carefully said I do not like that sharepoint "hijacks" the Internet Information Server. When you create a virtual directory it is just not accessable because SharePoint took over IIS.

Funny fact: This is the second post how to fix issues with IIS and "extension" that cause issues :-)

So i decided to hack a small utility serving my needs:

ExcludeFromSharepoint.zip (3.46 KB)

Enables to exclude applications from sharepoint services through the directory context menu.
Install using the "-install" switch; Uninstall using "-uninstall" switch.

Because I'm running my machine under a LUA (Limited User Account) i wrote the tool in a way that you can install and uninstall it without administative rights - the contextmenu will be installed per user!

if(args[0]=="-install")

{

    RegistryKey _rkey = Registry.CurrentUser;

    _rkey = _rkey.OpenSubKey("SOFTWARE\\Classes",true);

    _rkey = _rkey.CreateSubKey("Folder").CreateSubKey("shell");

    _rkey = _rkey.CreateSubKey("Exclude from Sharepoint");

    _rkey = _rkey.CreateSubKey("command");

    _rkey.SetValue(null, App.Application.ExecutablePath + " \"%1\"");

}

else if(args[0]=="-uninstall")

{

    RegistryKey _rkey = Registry.CurrentUser;

    _rkey = _rkey.OpenSubKey("SOFTWARE\\Classes\\Folder\\shell",true);

    _rkey.DeleteSubKeyTree("Exclude from Sharepoint");

}

else

{

...

}

 

The Implementation works with the webserver extensions version 4.0 or higher

 

    RegistryKey _rkey = Registry.LocalMachine;

    _rkey = _rkey.OpenSubKey("SOFTWARE\\Microsoft\\Shared Tools\\" +

        "Web Server Extensions",true);

   

    foreach(string _subKeyName in _rkey.GetSubKeyNames())

    {

        try

        {

            int.Parse(_subKeyName.Replace(".",""));

            RegistryKey _fpKey = _rkey.OpenSubKey(_subKeyName,true);

            _fpDir = (string)_fpKey.GetValue("Location");

        }

        catch(Exception _ex)

        {

            string _err = _ex.ToString();

            break;

        }

    }

 

and uses the stsadm.exe from the shared tools of the server extensions.

    System.Diagnostics.Process _p = new System.Diagnostics.Process();

    _p.StartInfo.FileName = Path.Combine(_fpDir, "BIN\\stsadm.exe");

    _p.StartInfo.Arguments = "-o addpath -url http://localhost/" +

        _strProjectName + " -type exclusion";

    ...

    _p.Start();

 

ASP.NET | C# | Indigo | Misc | Projects | Security | WebServices
Wednesday, August 10, 2005 6:43:48 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [0]  | 

I develop with 1.1 and 2.0 - When VS 2003 creates a web solution it is configured to use the 2.0 runtime. Placeing the following code to the Global.asax's of your 1.1 projects and setting execute permissions on the aspnet_regiis.exe helps much.

protected void Application_Start(Object sender, EventArgs e)

{

      if(System.Environment.Version.Major==2)

      {

            System.Diagnostics.Process _p = new System.Diagnostics.Process();

            _p.StartInfo.FileName = "%WINDIR%\\Microsoft.NET\\Framework\\v1.1.4322\\aspnet_regiis.exe";

            _p.StartInfo.Arguments = "-s W3SVC/1/ROOT" + Request.ApplicationPath;

            _p.StartInfo.UseShellExecute = false;

            _p.StartInfo.RedirectStandardOutput = true;

            _p.Start();

      }

}

 

ASP.NET | C# | Misc
Wednesday, August 10, 2005 12:56:11 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [1]  | 
I got an E-Mail from a student this morning asking how to thumbnail an uploaded image. Here is a "quick" solution (there are a few things you can do to increase quality, set JPEG compression factor or keep gif transparency). If you like to dig deeper have a look at one of the articles i wrote for the DotNetPro magazine's #Talk column (dnp0305_Thumbnail.pdf [German])

 

<%@ Page Language="C#" %>

 

<script runat="server" Language="C#">

 

    public void UploadFile(object sender, EventArgs e)

    {

        System.Drawing.Image _img =
             System.Drawing.Image.FromStream(
             this.InputTypeFile.PostedFile.InputStream);

 

        int _maxWidth = 100;

        int _maxHeight = 100;

 

        int _width = _img.Width;

        int _height = _img.Height;

 

        string _filename =

              System.IO.Path.GetFileName(

              this.InputTypeFile.PostedFile.FileName);

           

        string _uploadPath = System.IO.Path.Combine(

            Server.MapPath(".\\upload\\"),

            _filename);

       

        if (_width > _height)

        {

            width = Math.Abs((int)(height *

                        _img.Width /

                        _img.Height));

            _height = _maxHeight;

        }

        else

        {

            _height = Math.Abs((int)(_maxWidth *

                        _img.Height /

                        _img.Width));

            _width = _maxWidth;

        }

       

        System.Drawing.Image _newImg =

            _img.GetThumbnailImage(width, height, null, null);

           _newImg.Save(_uploadPath);

           _img.Dispose();

    }

 

</script>

<body>

    <form id="form1" runat="server">

 

    <input id="InputTypeFile" type="file" runat="server" />

    <asp:Button ID="Submit" OnClick="UploadFile" Text="Upload" />

 

    </form>

</body>

</html>

ASP.NET | C# | Misc
Wednesday, August 10, 2005 11:41:33 AM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [0]  | 
# Friday, July 22, 2005

Scott posted a solution to support httpOnly cookies in ASP.NET 1.1 but pointed out some problems when you run the code on 2.0(http://www.hanselman.com/blog/HttpOnlyCookiesOnASPNET11.aspx)

Here is a solution:

		
protected void Application_EndRequest(Object sender, EventArgs e)
{    
	if(System.Environment.Version.Major<2)
	{
		foreach(string cookie in Response.Cookies)    
		{        
			const string HTTPONLY = ";HttpOnly";        
			string path = Response.Cookies[cookie].Path;        
			if (path.EndsWith(HTTPONLY) == false)        
			{            
				//force HttpOnly to be added to the cookie            
				Response.Cookies[cookie].Path += HTTPONLY;        
			}    
		}
	}
}
ASP.NET | C# | Projects
Friday, July 22, 2005 3:43:24 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [21]  | 
# Friday, July 15, 2005
I just stumbled over roy's post and i think it would make sense to use smth like that as a capcha solution.
ASP.NET | C# | Misc | Projects
Friday, July 15, 2005 3:29:51 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [29]  | 
# Tuesday, May 31, 2005
public static bool IsWebInDebugMode
{
    get
    {
        bool _isDebug = false;
        

        if(HttpContext.Current.Cache["IsDebug"]==null)
        {
            XmlDocument _doc = new XmlDocument();
            string _cfgfile = HttpContext.Current.Server.MapPath("~/Web.Config");
                _doc.Load(_cfgfile);
            
            XmlNode _node = _doc.SelectSingleNode("configuration/system.web/compilation");

            if(_node==null || _node.Attributes["debug"]==null || 
               _node.Attributes[
"debug"].Value.ToLower()!="true")
            {
                _isDebug = false;
            }
            else
            {
                _isDebug = true;
            }
            HttpContext.Current.Cache.Insert("IsDebug", _isDebug, 
               
new System.Web.Caching.CacheDependency(_cfgfile), 
               DateTime.Now.AddDays(
1), 
               TimeSpan.Zero);

        }
        else
        {
            _isDebug = bool.Parse(HttpContext.Current.Cache["IsDebug"].ToString());
        }
        
        return _isDebug;

    }
}
ASP.NET | C#
Tuesday, May 31, 2005 4:45:03 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [12]  | 
# Thursday, April 21, 2005

While re-writing a few WebServices for .NET 2.0 i ran across following:

...
public static void WaitProc(object state, bool timedOut)
{
   MyAsyncResult myAsyncResult = (MyAsyncResult)state;
   myAsyncResult.OriginalCallback.Invoke(myAsyncResult);
}
...

This compiles without any problems in Visual Studio .NET 2003 but makes the compiler scream (Invoke cannot be called directly on a delegate) untill you change the lines to the following:

...
public static void WaitProc(object state, bool timedOut)
{
   MyAsyncResult myAsyncResult = (MyAsyncResult)state;
   myAsyncResult.OriginalCallback(myAsyncResult);
}
...

Thursday, April 21, 2005 3:12:24 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [18]  | 
# Tuesday, March 15, 2005

Miroslaw Maslyk has sent this small tutorial on how to use iFused with the FCKEditor. Thank you very much Miro ;-)

1. Rename file FCKeditor\editor\dialog\fck_image.html to fck_image.aspx.

2. On the top this file (fck_image.aspx) add this code:

<%@ Page Language="C#" %>
<%@ Register TagPrefix="Uploader"
 namespace="StaticDust.Web.UI.Controls"
 assembly="StaticDust.Web.UI.Controls.UploadDialog" %>
<script runat="server">
protected void Page_Load(Object source, EventArgs e)
{
   
StaticDust.Web.UI.Controls.UploadDialogButton _u =
     new StaticDust.Web.UI.Controls.UploadDialogButton();
   
_u.UploadDirectory = "~/images";
   
_u.ReturnFunction = "SetUrl()";
   
btnBrowse.Attributes["OnClick"] =
     "javascript:" + _u.JavascriptLink; }
</script>

3. Find btnBrowse input html tag , add runat="server" attribute and close tag (/>)

4. Replace in files FCKEditor\FCKeditor\editor\js\fckeditorcode_ie_2.js and fckeditorcode_gecko_2.js all fck_image.html sentence to fck_image.aspx

ASP.NET | C# | Projects
Tuesday, March 15, 2005 11:50:32 AM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [27]  | 
# Tuesday, February 15, 2005

Yesterday I arrived in Frankfurt with a delay of 2 hours (thanks to the Deutsche Bahn). Monday is Workshop day and so I just sat arround and did the same stuff that I would normally do in the office. I'm currently working on an ASP.NET project that uses v. 1.1 but will be converted to 2.0 with it's "Go-Live". So I need to make sure that I don't do things that will stand in the way in the next version.

Here are a few questions I'm currently asking myself:

  • Do i like the idea to save the properties of the Profile class in a ntext database column with the length of 6000?
  • Will i accept that i can only user MemberShip with MediumTrust or higher?

In germany we say: "Kommt Zeit, kommt Rat".

ASP.NET | C# | Projects | Security
Tuesday, February 15, 2005 4:43:23 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [40]  | 
# Sunday, January 30, 2005

[Dino Esposito] ...Introduced with ASP.NET 1.1, ViewStateUserKey is a string property on the Page class that only few developers admit to be familiar with. Why? Let's read what the documentation has to say about it.[...]

void Page_Init (object sender, EventArgs e) 
{ ViewStateUserKey = Session.SessionID; }

There will be a few more that are familiar with that now :-)

ASP.NET | C# | Security
Sunday, January 30, 2005 1:24:17 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [17]  | 
# Thursday, January 27, 2005

I currently working again on iFused (Internet File Upload Select and image Editing Dialog). Yesterday i released the version 2.3.1.10088:

  • support for "~" as palceholder for the application path
  • code optimization
  • performance optimization

I have a lot of things to do on based on the wishlist forum at staticdust and loads of mail in my inbox.

This is what i plan to catch until 1st. of february:

  • Use physical path outside of the application root as UploadDirectory
  • Database as source for files and directorys
C# | Projects
Thursday, January 27, 2005 9:14:03 AM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [18]  | 
# Wednesday, December 29, 2004
ASP.NET | C# | Misc | Projects
Wednesday, December 29, 2004 7:03:01 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [11]  | 
# Monday, December 27, 2004

What i really like about the days between x-mas and new year is that you have time for things that you usually don't have time for.

The stroy: I love my girlfriend. I likle C# and I like asciiart. So it happend that she showed me some ascii's. I asked myself if somebody has written some image to ascii in C#. I googled but found nothing. I did some image manipulation stuff for the company before x-mas and so I builded a basic image to ascii conversion library in C#.

http://www.lennybacon.com/image2ascii/

You can grab the source at :

http://www.codeproject.com/aspnet/ascii_art_with_c_.asp

ASP.NET | C# | Projects
Monday, December 27, 2004 7:33:16 AM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [47]  | 
# Sunday, November 28, 2004
A class that can be added...
public class Point
{
    private int x, y;
    
    public Point(){}

    public Point(int xPos, int yPos){ x = xPos; y = yPos; }

    public static Point operator + (Point p1, Point p2)
    {
       Point newPoint = new Point(p1.x + p2.x, p1.y + p2.y);
       return newPoint;
    }
}
I just wrote that down to have it writen once ;-)
C# | Misc
Sunday, November 28, 2004 8:59:21 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [10]  | 
# Wednesday, November 17, 2004
using System.Drawing;
using System.Drawing.Design;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace StaticDust.Web.UI.Controls
{
    [Designer(typeof(RadioButtonDesigner))]
    public class RadioButton : System.Web.UI.WebControls.RadioButton
    {
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
            System.IO.StringWriter stringWriter = new System.IO.StringWriter(stringBuilder);
            HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
            base.Render(htmlWriter);

            StringBuilder _javaScript = new StringBuilder();

            IEnumerator keys = this.Attributes.Keys.GetEnumerator();
            int i = 1;
            string key;
            while (keys.MoveNext())
            {
                key = (String)keys.Current;
                if(key.Substring(0,2).ToLower()=="on")
                {
                    stringBuilder.Replace(key + "=\"" + this.Attributes[key].ToString() + "\" """);
                    _javaScript.Append(key + "=\"" + this.Attributes[key].ToString() + "\" ");
                }
                i++;
            }
            stringBuilder.Replace("type=\"radio\" ""type=\"radio\" " + _javaScript.ToString());

            writer.Write(stringBuilder.ToString());
        }

    }
}

 

ASP.NET | C#
Wednesday, November 17, 2004 11:38:44 AM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [20]  | 
# Tuesday, October 26, 2004

In the past weeks i have looked at several template based solutions for ASP.NET 1.1, because i can't wait for .NET 2.0.

Region MasterPages and it's variations all around the web
No WYSIWYG/VS.NET support - No solution for me.

Masterpages reinvented
Nice try, but i don't want to add so much lines to the code behind.

I also realized SiteMesh.NET (http://joe.truemesh.com/blog/000275.html - hey Joe fix that damn JS error!!!), but i don't like that approach.

So i decided to think about other concepts and wrote something that solves following for me:

  • MasterPage
    • WYSIWYG in VS.NET
    • CodeBehind
  • Other pages
    • WYSIWYG in VS.NET
    • CodeBehind

... with one line of code in the client pages.

I'll talk about my solution on the VFL-NiederRhein UG Meeting in november or december. So if you are interested keep an eye open.

Tuesday, October 26, 2004 10:48:46 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [35]  | 
# Friday, October 01, 2004

I had a data crash a few weeks ago and lost a few lines of code my business objects.

Brent Moore reported me a error and so each line came back to my mind and back to the assembly managing the data of StaticDust.

Thanks Brent

ASP.NET | C# | Projects
Friday, October 01, 2004 9:40:37 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [23]  | 
# Wednesday, September 29, 2004

it's done - because of the loads of features i added in the last weeks (thanks to everybody who gave me feedback) it was necessary to redesign iFused from the architectural point of view and yes i polished the UI a bit. I hope you all like it - I LOVE FEEDBACK.

http://www.staticdust.net/

ASP.NET | C# | Projects
Wednesday, September 29, 2004 8:21:15 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [12]  | 
# Monday, September 20, 2004

Wegen der enormen Nachfrage ...

ValidationDemo.zip (20 KB)

ASP.NET | C# | Misc
Monday, September 20, 2004 1:04:21 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [24]  | 
# Monday, September 06, 2004
  • Fons Habes contributed a dutch translation.
  • I'm working with Mohsen Khani on the Farsi (Iran) version.
  • Matteo Spagnolo will do the italian ...
  • The image editing dialog has a "Save As..." now.
  • Liming Xu, Leon Schuurbiers and Xavier Larrea posted a
    bug to the Support Forum (that had a bug too that is
    fixed now so i'll be notified about posts and can aswear
    questions...) that occures if the UploadDirectory is
    outside of the current ApplicationDirectory - Fixed.
    Thanks guys.
ASP.NET | C# | Projects
Monday, September 06, 2004 8:39:24 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [27]  | 
# Friday, August 27, 2004

Read the series about the Machine Debug Manager:

Part 1 and Part 2.

 

ASP.NET | C# | Misc
Friday, August 27, 2004 6:07:36 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [25]  | 
# Thursday, August 26, 2004

O.K. as you'll see it's been a long night for me - i added a lot of features to iFused and fixed the sign up bug at staticdust.net.

  • Unlimited Directory browsing (limited by the memory of your box ;-) )
    • Directorys are now displayed in the file browser frame and onclick the directory is displayed.
    • The "move directory up" works with unlimited directorys (limited by the memory of your box ;-)
  • Filelist is now a DataTable and no more a Hashtable - yeah that kicks performace and prepairs my next step the "Detail View" (including file size, image width x image height, date created, date last modified and movable XP styled tabs...).
  • "Cancle" is now "Cancel" ;-).
  • "Selet" is now a "Select" ;-) ;-).
  • David Fawn contributed the Czech translation file - THANKS DAVID,  THAT'S GREAT MAN.
  • And my friend Miguel is currently translating the satellite assemblys to french and spanish.
  • Added MIME TYPES for all extensions followed.
  • File icons for following extensions (drop me a mail if you miss a filetype...)
    •  .acp
    •  .adp
    •  .aiff
    •  .as
    •  .asa
    •  .asax
    •  .asc
    •  .ascx
    •  .asf
    •  .asmx
    •  .asp
    •  .aspx
    •  .avi
    •  .bat
    •  .bmp
    •  .chm
    •  .cls
    •  .cmd
    •  .com
    •  .config
    •  .cs
    •  .csproj
    •  .css
    •  .ctl
    •  .dcr
    •  .dir
    •  .disco
    •  .dll
    •  .doc
    •  .dot
    •  .dsn
    •  .eml
    •  .exe
    •  .exp
    •  .fdf
    •  .fla
    •  .flp
    •  .frm
    •  .gif
    •  .gz
    •  .hhp
    •  .hqx
    •  .htm
    •  .html
    •  .icc
    •  .icm
    •  .ics
    •  .infopathxml
    •  .ini
    •  .java
    •  .jpeg
    •  .jpg
    •  .js
    •  .jse
    •  .jsfl
    •  .la1
    •  .lar
    •  .lavs
    •  .lib
    •  .log
    •  .lqt
    •  .manifest
    •  .mdb
    •  .mht
    •  .mid
    •  .midi
    •  .mnd
    •  .mns
    •  .mov
    •  .mp3
    •  .mpg
    •  .mpp
    •  .mpt
    •  .msg
    •  .msi
    •  .mxi
    •  .mxp
    •  .ocx
    •  .pct
    •  .pdf
    •  .pic
    •  .pict
    •  .png
    •  .pot
    •  .pps
    •  .ppt
    •  .ps
    •  .pub
    •  .qt
    •  .qti
    •  .qtif
    •  .r3t
    •  .ra
    •  .ram
    •  .rar
    •  .reg
    •  .resource
    •  .resx
    •  .rm
    •  .rmvb
    •  .rp
    •  .rt
    •  .rtf
    •  .rv
    •  .scc
    •  .sct
    •  .sdl
    •  .sln
    •  .smi
    •  .smil
    •  .sql
    •  .ssm
    •  .ste
    •  .swf
    •  .tar
    •  .tif
    •  .tiff
    •  .txt
    •  .unknown
    •  .vb
    •  .vbe
    •  .vbg
    •  .vbp
    •  .vbproj
    •  .vbs
    •  .vcproj
    •  .vcs
    •  .vdx
    •  .vjsproj
    •  .vpg
    •  .vsd
    •  .vss
    •  .vsscc
    •  .vssscc
    •  .vst
    •  .vxd
    •  .wab
    •  .wav
    •  .wip
    •  .wma
    •  .wsc
    •  .wsdl
    •  .xls
    •  .xml
    •  .xsd
    •  .xsl
    •  .xslt
    •  .zip

 

And as mentioned in the title of this post i hope to score at the contest "Make a developer's life easier and win" by devtrain.de.

So, please if there are any wishes for the wishlist DROP ME A MAIL.

If there is some interest to translate a resource file (61 words or short sentence) DROP ME A MAIL.

Ahh, did i tell you that im on hollydays? No i don't think so. Greetings to the rest of the pack @ the office and all you techies out there.

Download iFused

ASP.NET | C# | Misc | Projects
Thursday, August 26, 2004 4:26:02 AM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [16]  | 
# Monday, August 16, 2004

1. I fixed a lot of layout bugs for my friends who use mozilla.
2. The Uploaded image will now be selected after upload.
3. The "directory up" button disables if you are in the highest directory.
4. "Save in" is now translated to "Speichern in" (german).

ASP.NET | C# | Projects
Monday, August 16, 2004 2:07:08 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [27]  | 
# Friday, August 06, 2004

I just released version 1.2 - go get it.

FIX: Errors if the control is placed in a control.

New Features:
I just found out how to display all textboxes of the Form in the PropertyList

[TypeConverter(typeof(ValidatedControlConverter))] public string ControlToFill ...

ASP.NET | C# | Projects
Friday, August 06, 2004 4:13:35 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [21]  | 
# Monday, July 19, 2004

After over 350 downloads of the IFSUD (Internet File Select and Upload Dialog) in the

Take a look and get the IFSUD.

 

http://www.staticdust.net/

ASP.NET | C# | Projects
Monday, July 19, 2004 9:23:39 AM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [34]  | 

Ian Powell (Breeze IT) reported a bug that occures when dragging the control from VisualStudio's Toolbar. Ron Douglas (Synthesoftsolutions) did the same...

Now it's fixed and i added a Designer class.

ASP.NET | C# | Projects
Monday, July 19, 2004 9:20:57 AM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [22]  | 
# Tuesday, June 29, 2004

O.k. its done. I set up a new site on StaticDust.Net where you can download the Internet File Select and Upload Dialog. There are a few things i like to add to the component - so leave your e-mail address on downloading or keep reading my blog to stay up do date and to make sure that you always get the latest version.

http://www.staticdust.net/

It would be nice if you send me some feedback and wishes. If your product uses my component send me a mail with some details - i'll list products that use it on the StaticDust.Net product page.

ASP.NET | C# | Projects
Tuesday, June 29, 2004 3:07:11 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [19]  | 
# Monday, June 07, 2004

I'm running ...

  • Mozilla support: 100%
  • Opera support: 100%
  • Details View: 10%

Screenshots:

IE
Opera
Mozilla

ASP.NET | C# | Projects
Monday, June 07, 2004 9:44:58 AM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [28]  | 
# Friday, May 28, 2004

I fixed the alphabetical order of files and added the "IconView".

Take a look and give me some feedback.

http://www.lennybacon.com/samples/StaticDust.Web.UI.Controls.UploadDialog.aspx

ASP.NET | C# | Projects
Friday, May 28, 2004 12:50:54 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [27]  | 
# Friday, May 14, 2004

I fixed the problem of displaing the icon of a file with uppercas exetnsion and store the information about allowed maxmal/total/minimal pixels for images and filesizes for upload in a session now.

I fixed displaing image files that don't fit the defined pixels in the browse window on the internet server.

I fixed the message when triing to upload a file that already exists.

<asp:textbox id=Image1 runat="server"></asp:textbox> <ctrl:UploadDialogButton id=Image1Button runat="server" AllowCreateFolder="True" AllowDelete="True" DemoMode="True" FileTypes="gif,jpg" UploadDirectory="images/" ControlToFill="Image1" FileNameOnly="True"> </ctrl:UploadDialogButton>
ASP.NET | C# | Projects
Friday, May 14, 2004 2:08:34 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [26]  | 
# Wednesday, May 12, 2004

I finished my "Internet file select and upload Dialog". A HttpHandler and a WebControl.

Take a look at:

http://www.lennybacon.com/samples/StaticDust.Web.UI.Controls.UploadDialog.aspx

 

ASP.NET | C# | Projects
Wednesday, May 12, 2004 9:57:53 PM (W. Europe Daylight Time, UTC+02:00)  #    Disclaimer  |  Comments [20]  | 
# Saturday, March 06, 2004
 
from InfoWorld
C#
Saturday, March 06, 2004 9:18:15 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [18]  | 
C#
Saturday, March 06, 2004 9:10:08 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [21]  | 

I had some trouble with a WebForm, including a OleDbDataAdapter, a DataSet and uses the OleDbCommandBuilder to publish the CommandText property to the DataAdapter, that tries to update five Decimal columns in a Access database. No matter what i did the Update method of the DataAdapter threw a DBConcurrencyException. After googling a few minutes i found someting about the ODBC/JET data type limit.
So i canged the Decimal to a Double and now all works fine.

 

C#
Saturday, March 06, 2004 8:59:41 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [36]  | 
# Friday, February 13, 2004

I just wanted to write this down somewhere to keep it in mind but it may be useful for others to.     protected void Application_Start(Object sender, EventArgs e)
    {
        //Application
        //Request
    }

    protected void Session_Start(Object sender, EventArgs e)
    {
        //Application
        //Request
        //User
        //Session
        //Response
    }

    protected void Application_BeginRequest(Object sender, EventArgs e)
    {
        //Application
        //Request
        //Response*
    }
    
    protected void Application_PreSendRequestHeaders(Object sender, EventArgs e)
    {
        //Application
        //Request
        //User
        //Session
        //Response
    }

    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        //Application
        //Request
        //User
        //Response*
    }

    protected void Application_PostRequestHandlerExecute(Object sender, EventArgs e)
    {
        //Application
        //Request
        //User
        //Session
        //Response*
    }

    protected void Application_EndRequest(Object sender, EventArgs e)
    {
        //Application
        //Request
        //User
        //Response*
    }
    
    protected void Session_End(Object sender, EventArgs e)
    {
        //Application
        //Request
        //User
        //Session
        //Response
    }

    protected void Application_Error(Object sender, EventArgs e)
    {
        //Application
        //Request
        //User
        //Session
        //Response
    }

    protected void Global_Error(Object sender, EventArgs e)
    {
        //Application
        //Request
        //User
        //Session
        //Response
    }
    
    protected void Application_End(Object sender, EventArgs e)
    {
        //Application
        //Request
        //User
        //Session
        //Response
    }

* Produces output

ASP.NET | C#
Friday, February 13, 2004 2:54:56 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [18]  | 
# Friday, January 23, 2004

That was in short what was on my requirement list.
I had a few difficulties solving the problem of filling "this" and classes that fill them self in the constructor, but i finally figured it out.


public void Fill(ref object[] objCollection ...)
{
    ...
    System.Type type = objCollection[0].GetType();
    ArrayList arr = new ArrayList();
    ...
    object baseObject;

    // struct or struct[]
    if(type.IsValueType) 
    {
        baseObject = type.Assembly.CreateInstance(type.FullName);
    }
    // this or non serializable class
    else if(arr.Count==0)
    {
        baseObject = objCollection[0];
    }
    // class or class[]
    else if(type.IsSerializable) 
    {
        Stream _stream;
        BinaryFormatter _formatter = new BinaryFormatter();
        try
        {
            _stream = File.Open("Empdata.bin",
             FileMode.Create, FileAccess.Write);
            _formatter.Serialize(_stream, objCollection[0]);
            _stream.Close();

             _stream = File.Open("Empdata.bin",
              FileMode.Open, FileAccess.Read);
             object _desObj = _formatter.Deserialize(_stream);
             baseObject = Convert.ChangeType(_desObj, type);
             _stream.Close();
        }
        catch(Exception e)
        {
            throw new Exception(type.ToString() +
             " could not be serialized.", e);
        }
    }
    else
    {
        throw new NotImplementedException(type.ToString() +
         " is no value type and don't implements the" +
         "ISerializable interface.");
    }
    ...
    arr.Add(baseObject);
    ...
}

C#
Friday, January 23, 2004 10:44:36 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [27]  | 
# Tuesday, December 30, 2003
<%@ Page language="C#" %>
<script language="C#" runat="server">
  private void Page_Load(object sender, System.EventArgs e)
  {
    System.Data.OleDb.OleDbConnection _conn =
     new System.Data.OleDb.OleDbConnection();
    _conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
     "Data Source=D:\\WebRoot\\data\\data.mdb";
    System.Data.OleDb.OleDbCommand _cmd = conn.CreateCommand();
    _cmd.CommandType = System.Data.CommandType.Text;
    _cmd.CommandText = "SELECT Name FROM Users WHERE ID=1";
    System.Data.OleDb.OleDbDataAdapter _adapter =
     new System.Data.OleDb.OleDbDataAdapter();
    _adapter.SelectCommand = _cmd;
    System.Data.DataSet _dataset = new System.Data.DataSet();
    _conn.Open();
    _adapter.Fill(dataset, "UserTable");
    _conn.Close();
    if(_dataset.Tables["UserTable"].Rows.Count>0)
    {
      this.TextBox1.Text =
       _dataset.Tables["UserTable"].Rows[0][0].ToString();
    }
  }
</script>
<html>
<body>
<form ID="Form" runat="server">
 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</form>
</body>
</html>
ASP.NET | C#
Tuesday, December 30, 2003 2:47:51 AM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [24]  | 
<%@ Page language="C#" %>
<script language="C#" runat="server">
 private void Page_Load(object sender, System.EventArgs e)
 {
   System.Data.OleDb.OleDbConnection _conn =
    new System.Data.OleDb.OleDbConnection();
   _conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
    "DataSource=D:\\WebRoot\\data\\data.mdb";
   System.Data.OleDb.OleDbCommand _cmd = _conn.CreateCommand();
   _cmd.CommandType = System.Data.CommandType.Text;
   _cmd.CommandText = "SELECT Name FROM Users WHERE ID=1";
   _conn.Open();
   System.Data.OleDb.OleDbDataReader _reader = cmd.ExecuteReader();
   if(_reader.Read())
   {
     this.TextBox1.Text = _reader.GetString(0);
   }
   _reader.Close();
   _conn.Close();
}
</script>
<html>
<body>
<form ID="Form" runat="server">
 <asp:TextBox id="TextBox1" runat="server
"></asp:TextBox>
</form
>
</body>
</html
>
ASP.NET | C#
Tuesday, December 30, 2003 2:45:16 AM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [26]  | 
# Wednesday, December 24, 2003
C# | Misc
Wednesday, December 24, 2003 11:32:18 AM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [23]  | 
# Monday, December 15, 2003
Automatic globalization of the Label control
ASP.NET | C#
Monday, December 15, 2003 12:11:43 AM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [19]  | 
# Thursday, December 04, 2003

I just wrote an upload thru class that inherits IHttpHandler.

Joerg tried to help me (thx) but i had to get it by trying myself.

I'll post what i wrote in the next days, when i finished the rest of the code and the documentation.

C# | ASP.NET
Thursday, December 04, 2003 10:07:49 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [26]  | 
# Thursday, November 27, 2003
I started a new project. A e-commerce solution i wrote once in VB6 as a COM+ component and that is still used by Philips (Consumer Communications)
Thursday, November 27, 2003 8:46:59 PM (W. Europe Standard Time, UTC+01:00)  #    Disclaimer  |  Comments [21]  |