Generating images of fancy fonts on the fly.

11/6/2008

IIS 6.0 application pool timeouts

IIS 6.0 has a web site running under an application pool with a default timeout time of 20 minutes.

Unless it is a high traffic site, the site will fall out of memory (memory is recycled) and need to be JIT’ted – for complex sites this time can lead to timeouts to the end user, even worse if a multitier application as the top tier calls the next and each has a JIT issue.

Unless you can change the application pool settings to suit yourself, (most servers expect you to share with other websites), then some keep-alive method is needed.

The website itself can be kept alive with a tool such as www.internetseer.com – at the same time providing a site uptime report but this is not useful to middle tier app servers for example – unless pinging a web page happens to call the middle tier code.

Therefore a keep alive service may need to be used for the app tier to keep it alive.

The issue is covered here:

http://www.eggheadcafe.com/software/aspnet/30313174/iis-60-application-pool.aspx

IIS 6.0 Application pool recycling – David Wang
14-Jul-07 06:29:00
The option exists because there are circumstances that make the option

useful. Idle timeout allows reclaim of resources so that you can

potentially run more code than you can simultaneously.

In the case of dedicated servers, if you have provisioned the server

hardware to be sufficient for your application, then idle timeout is

clearly unnecessary and probably detrimental to performance/

reliability.

However, in the case of shared hosting, idle timeout allows you to

pack thousands of users and their websites onto one box to maximize

utilization of resources by ACTIVE applications.

Since IIS6 is a generic and configurable server, it needs to have

options to handle these and MORE diverse workloads.

Obviously, not all options are optimal for all applications — if that

was the case, one never needs to tune settings. Nor are the defaults

guaranteed to be best for any given application.. In particular, the

defaults are tuned towards ASP/COM applications, which completely

contradict with hosting ASP.Net applications. Thus, you always have to

understand and tune such settings depending on your circumstance.

Basically, IIS assumes that for users that care about these settings,

they will figure out what to customize and with what values. If the

user does not care, then the defaults are by definition sufficient. It

doesn’t matter if the defaults are not optimal if the user does not

care about it either. Optimal behavior requires user interaction.

//David

http://w3-4u.blogspot.com

http://blogs.msdn.com/David.WangPosted at 10:35 AM by Dyball, Robert | Permalink | Email this Post | Comments (0)

10/29/2008

 

Finding event arguments

Not sure what to cast a value to in an event argument, but you can see it when debugging, here’s the trick:

Posted at 11:47 AM by Dyball, Robert | Category: C# coding tricks | Permalink | Email this Post | Comments (0)

7/23/2008

A cleaner way to add controls to a page dynamically

This is a cleaner way to add controls to a page dynamically, using ASP.Net tables, adding asp.net table columns and asp.net table rows:

Use this in the markup:
<asp:Table id=”tblDynamic” runat=”server”></asp:Table>

Then this in the code behind:

for ( int i = 0; i < 5; i++ )
{
    TableRow tr = new TableRow(); 

    // Create column 1 
    TableCell td1 = new TableCell(); 

    // Create a label control dynamically 
    Label _label = new Label(); 
    _label.ID = “lbl” + i.ToString(); 
    _label.Text = “Enter Value ” + i.ToString(); 

    // Add control to the table cell 
    td1.Controls.Add(_label);

    // Create column 2 
    TableCell td2 = new TableCell(); 
    TextBox _text = new TextBox(); 
    _text.ID = “txt_” + i.ToString();

    // Add control to the table cell 
    td2.Controls.Add(_text);

    // Add cell to the row 
    tr.Cells.Add(td1); 
    tr.Cells.Add(td2);

    // Add row to the table. 
    tblDynamic.Rows.Add(tr);
}

Posted at 3:55 PM by Dyball, Robert | Category: C# coding tricks | Permalink | Email this Post | Comments (0)

Dynamically adding controls to an ASP.Net page

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        // max = # of items in the list
        int max = 5;

        if (max > 0)
        {
            Literal topTbl = new Literal();
            topTbl.Text = “<table border=’1′ cellpadding=’1′ cellspacing=’1′>”;
            thing.Controls.Add(topTbl);

            for (int i = 0; i < max; i++)
            {
                Literal leftRow = new Literal();
                leftRow.Text = “<tr><td>”;
                thing.Controls.Add(leftRow);

                Label label1 = new Label();
                label1.ID = “xxx” + i.ToString();
                label1.Text = “hello world” + i.ToString() + ” “;
                thing.Controls.Add(label1);

                Literal midRow = new Literal();
                midRow.Text = “</td><td>”;
                thing.Controls.Add(midRow);

                CheckBox cb = new CheckBox();
                cb.ID = “yyy” + i.ToString();
                thing.Controls.Add(cb);

                midRow = new Literal();
                midRow.Text = “</td><td>”;
                thing.Controls.Add(midRow);

                Label label2 = new Label();
                label2.Text = ” {” + i.ToString() + “} “;
                label2.ID = “zzz” + i.ToString();
                thing.Controls.Add(label2);

                Literal rightRow = new Literal();
                rightRow.Text = “</td></tr>”;
                thing.Controls.Add(rightRow);
            }

            Literal bottomTbl = new Literal();
            bottomTbl.Text = “</table>”;

            thing.Controls.Add(bottomTbl);
        }
    }

}

Posted at 3:15 PM by Dyball, Robert | Category: C# coding tricks | Permalink | Email this Post | Comments (0)

5/15/2008

making client side modal popups in asp.net pages

making client side modal popups in asp.net pages

<script language=”javascript” type=”text/javascript”>
// <!CDATA[

function btnMakeCreditcardPayment_onclick() {
    var win = window.open(‘CreditCardPayment.aspx’, ‘popWin’, ‘left=100, top=100, width=550, height=420,toolbar=no,directories=no,status=no,linemenubar=no,scrollbars=no,resizable=no ,modal=yes’, true);

    win.opener = self;
    win.focus();
    return(false);
}

function btnMakeChequePayment_onclick() {
    var win = window.open(‘ChequePayment.aspx’, ‘popWin’, ‘left=100, top=100, width=550, height=400,toolbar=no,directories=no,status=no,linemenubar=no,scrollbars=no,resizable=no ,modal=yes’, true);

    win.opener = self;
    win.focus();
    return(false);
}

// ]]>
</script>

Posted at 10:12 AM by Dyball, Robert | Category: C# coding tricks | Permalink | Email this Post | Comments (0)

2/4/2008

Executing client side javascript from an asp:radiobutton control when there’s no onclientclick event

Some ASP.net controls have onclientclick events, making it easy to wire in client side javascript code – saving round trips for menial tasks.

Radio buttons seem to be missing this.

This is a way around the missing event:

(1) In your asp.net .aspx page add:

<script language=”javascript” type=”text/javascript”>

function rdChangeWithdraw_Click()
{
    var objrdChange = document.getElementById(“<%= objrdChange%>”); 
    var objrdWithdraw = document.getElementById(“<%= objrdWithdraw%>”); 
    var objtxtWithdrawalDetails = document.getElementById(“<%= objWithdrawalDetails%>”);

    if (!objrdChange) return (false); 
    if (!objrdWithdraw) return (false); 
    if (!objtxtWithdrawalDetails) return (false); 

    objtxtWithdrawalDetails.disabled = (objrdChange.checked);

    return (true);
}
</script>

for

for these radio buttons:

<asp:RadioButton runat=”server” GroupName=”ChangeWithdraw” ID=”rdChange” />
<asp:RadioButton runat=”server” GroupName=”ChangeWithdraw” ID=”rdWithdraw” />

to enable and disable this textbox

<ASP:Textbox runat=”server” ID=”txtWithdrawalDetails” Runat=”server”  />

(2) In your asp.net .aspx.cs code behing page add:
….

protected void Page_Load(object sender, EventArgs e)
{
// get rendered id’s of objects for use in client side javascript
objrdChange = this.rdChange.ClientID.ToString();
objrdWithdraw = this.rdWithdraw.ClientID.ToString();
objWithdrawalDetails = this.txtWithdrawalDetails.ClientID.ToString();
// add event handlers to radio buttons to fire client side javascript
this.rdChange.Attributes.Add(“OnClick”, “rdChangeWithdraw_Click();”);
this.rdWithdraw.Attributes.Add(“OnClick”, “rdChangeWithdraw_Click();”);

The page pre-renders the controls, assigning IDs, then in Page_load populates the server side variables embeded in the client side javascript, then the client side javscript ‘knows’ the names of the controls once rendered, and is then able to interact with the as-rendered controls at the client and without a round trip.

Posted at 12:19 PM by Dyball, Robert | Category: C# coding tricks | Permalink | Email this Post | Comments (0)

1/16/2008

Custom installer for deployment project

custom installer. create a class library project, add the DLL to your installer project.

eg,. converted to C# from http://weblogs.asp.net/rmclaws/archive/2003/11/18/38426.aspx

namespace Installers {
    using Microsoft.Win32;
    using System.Configuration.Install;
    using System.ComponentModel;
    
    
    [RunInstaller(true)]
    public class Installer : System.Configuration.Install.Installer {
        
        // Required by the Component Designer
        private System.ComponentModel.IContainer components;
        
        public Installer() {
            // This call is required by the Component Designer.
            InitializeComponent();
            // Add any initialization after the InitializeComponent() call
        }
        
        // Installer overrides dispose to clean up the component list.
        protected override void Dispose(bool disposing) {
            if (disposing) {
                if (!(components == null)) {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }
        
        // NOTE: The following procedure is required by the Component Designer
        // It can be modified using the Component Designer. 
        // Do not modify it using the code editor.
        [System.Diagnostics.DebuggerStepThrough()]
        private void InitializeComponent() {
            components = new System.ComponentModel.Container();
        }
        
        public override void Install(System.Collections.IDictionary stateSaver) {
            base.Install(stateSaver);
            //  Gets the parameter passed across in the CustomActionData.
            string KeyName = this.Context.Parameters.Item(“Key”);
            string Location = this.Context.Parameters.Item(“Location”);
            if ((KeyName == “”)) {
                throw new InstallException(“The Registry key was not specified. The Registry could not be modified.”);
            }
            if ((Location == “”)) {
                throw new InstallException(“The Path was not specified. The Registry could not be modified.”);
            }
            RegistryKey regKey;
            regKey = Registry.LocalMachine.OpenSubKey(“SOFTWARE\\Microsoft\\.NETFramework\\AssemblyFolders”, true);
            regKey.CreateSubKey(KeyName);
            regKey.SetValue(“”, Location);
            regKey.Close();
        }
        
        public override void Uninstall(System.Collections.IDictionary stateSaver) {
            base.Uninstall(stateSaver);
            //  Gets the parameter passed across in the CustomActionData.
            string KeyName = this.Context.Parameters.Item(“Key”);
            string Location = this.Context.Parameters.Item(“Location”);
            if ((KeyName == “”)) {
                throw new InstallException(“The Registry key was not specified. The Registry could not be modified.”);
            }
            if ((Location == “”)) {
                throw new InstallException(“The Path was not specified. The Registry could not be modified.”);
            }
            RegistryKey regKey;
            regKey = Registry.LocalMachine.OpenSubKey(“SOFTWARE\\Microsoft\\.NETFramework\\AssemblyFolders”, true);
            regKey.DeleteSubKey(KeyName);
            regKey.Close();
        }
    }
}

Posted at 11:09 AM by Dyball, Robert | Category: C# coding tricks | Permalink | Email this Post | Comments (0)

1/9/2008

Passing values between a parent form and a child form – using c# in winforms.

There’s a few ways to do this, here’s one method

(important bits shown in boldface):

(1) in the ‘parent’ form do this:

….
namespace OnlineNotificationsRegistration
{
    /// <summary>
    /// ONS pre-registration details capture program
    /// </summary>
    public partial class ONSRegoForm : Form
    {
          public string StrTest
          {
                get { return textBox1.Text; }
                set { textBox1.Text = value; }
          }

        public ONSRegoForm()
        {
        ….

and then when launching the child form, do this:

        …..
           DALSinfo d = new DALSinfo();
           d.MyParentForm = this;
        d.ShowDialog();
    }

(2) in the ‘child’ form, do this

…..
namespace OnlineNotificationsRegistration
{
    public partial class DALSinfo : Form
    {
    /// <summary>
    /// provides reference to parent form
    /// </summary>
    
     public ONSRegoForm MyParentForm;
….

then to reference parent form do this:

    private void DALSinfo_FormClosing(object sender, FormClosingEventArgs e)
    {
        MyParentForm.StrTest = rowCount.ToString();
    }

Posted at 11:31 AM by Dyball, Robert | Category: C# coding tricks | Permalink | Email this Post | Comments (0)

12/14/2007

Simple Email Address validation control

found this here:

http://vaultofthoughts.net/CategoryView,category,ASP.NET.aspx
lifted and duplicated below – so I do not lose it 🙂
“…. the EmailValidator control which validates user input with a pattern of an email:

public class EmailValidator

    : RegularExpressionValidator

{

    public EmailValidator()

    {

        ValidationExpression =

        @”^[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]@

        [a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.

        [a-zA-Z][a-zA-Z\.]*[a-zA-Z]$”;

        ErrorMessage = “Email is incorrect”;

    }

}

“Note that ValidationExpression is broken so it may be better displayed in the browser. As for how accurate, the expression is. It was taken from the Regular Expression Library page and I have had no problems with it.

Usage on a page after registration:”

<my:EmailValidator runat=”server” ID=”EmailCorrect”

    ControlToValidate=”Email” />

Posted at 4:19 PM by Dyball, Robert | Category: Validation | Permalink | Email this Post | Comments (0)

Generating images of fancy fonts on the fly.

problem: designer comes up with a nice looking design for a web page, the user sees the design but then insists on keep ing the designer’s unusual font (that no one else no the net has!) …

one answer: generate an image on the fly using a copy of the font on the web server. I thought this trick was mad, but after testing it out found it gets cached by the browser andperforms very well.  I’ve tested in a clustered web server environment, across 4 Server 2003 boxes running IIS, with many thousands of hits per day, and found it worked a treat.
You could use same code to automate building/saving images if you do not want to do on the fly, but did want flexibility and get around designer’s penchant to use weird one-off fonts (as they do 🙂 ..

you can call it up from another web page (can be static HTML) using regular html

<img src=”image_gen.aspx?text=Hello%20World&FontName=tahoma&FontSize=56″>  …

this is the code, save this as (say) image_gen.aspx

<% @Page Language=”C#” %>
<% @Import Namespace=”System.Web” %>
<% @Import Namespace=”System.Drawing” %>
<% @Import Namespace=”System.IO” %>
<% @Import Namespace=”System.Drawing.Imaging” %>
<%

// NOTE: this is test code only, not the real ‘production’ verison of it, but should still give you the idea.

Response.Expires = 0;
Bitmap newBitmap = null;
Graphics g = null ;
int loop1, loop2;
NameValueCollection coll;
string str2Render = Request.QueryString.Get(“Text”);
if (null == str2Render)
{
    str2Render = “LOREM IPSUM\nDOLOR SIT AMET : ” + Context.Request.ServerVariables[“REMOTE_ADDR”];
}

string strFont = Request.QueryString.Get(“FontName”);
if (null == strFont) strFont = “Arial”;
int nFontSize = 72;

try
{
    nFontSize = Int32.Parse(Request.QueryString.Get(“FontSize”));
}
catch
{
    // oops .. ignore the error – maybe it’ll go away 🙂
}

string strBackgroundColorname = Request.QueryString.Get(“HitBackgroundColor”);

Color clrBackground = Color.White;

try
{
    // Format in the URL: %23xxXXxx
    if (null != strBackgroundColorname)
        clrBackground = ColorTranslator.FromHtml(strBackgroundColorname);
}
catch
{
}

string strFontColorName = Request.QueryString.Get(“HitFontColor”);
Color clrFont = Color.Black;
try
{
    // Format in the URL: %23xxXXxx
    if (null != strFontColorName)
        clrFont = ColorTranslator.FromHtml(strFontColorName);
}
catch
{
}

try
{
    Font fontCounter = new Font(strFont, nFontSize);
    // calculate size of the string.
    newBitmap = new Bitmap(1,1,PixelFormat.Format32bppArgb);
    g = Graphics.FromImage(newBitmap);
    SizeF stringSize = g.MeasureString(str2Render, fontCounter);
    int nWidth = (int)stringSize.Width;
    int nHeight = (int)stringSize.Height;
    g.Dispose();
    newBitmap.Dispose();
    newBitmap = new Bitmap(nWidth,nHeight,PixelFormat.Format32bppArgb);
    g = Graphics.FromImage(newBitmap);
    g.FillRectangle(new SolidBrush(clrBackground), new Rectangle(0,0,nWidth,nHeight));
    g.DrawString(str2Render, fontCounter, new SolidBrush(clrFont), 0, 0);
    MemoryStream tempStream = new MemoryStream();
    newBitmap.Save(tempStream,ImageFormat.Png);
    Response.ClearContent();
    Response.ContentType = “image/png”;
    Response.BinaryWrite(tempStream.ToArray());
    Response.End();
}
catch (Exception e)
{
    Response.Write(e.ToString());
}
finally
{
    if (null != g) g.Dispose();
    if (null != newBitmap) newBitmap.Dispose();
}
%>

Advertisements