Visual Studio – Attach to running local web site process to debug (and cannot see w3wp.exe?)

I had this problem where I wanted to attach my Visual Studio debugger to and already running website on local host.

From a bit of Googleing I found the process I needed to attach to was the IIS worker process called w3wp.exe, but this was not in my list. I noticed if I refreshed the site and then looked quickly in the process list it was there but then dissapeared shortly after – so a timeout I guessed.

This is what was happening, so I needed to stop it from timing out or at least delay it.

The answer was to change a setting in the applicaiton pool – ‘Shutdown Time Limit’.

Solution Summary:
– Goto IIS and find the website or application you want to modify.
– Click advanced settings to find the applicaiton pool it is using (or as I did create a new application pool and assign this website to use it)
– Goto your application pool list – selected advanced settings
– Change the ‘Shutdown Time Limit’ to something like 1000 (seconds) its default is 90

w3wp.exe should now hang around long enough to attach to it with the debugger 🙂

Multiple arguments with CommandArgument

Handy tip for passing as many arguments as you like with an OnCommand event.

Simply add the attributes you want to pass and the values:

<asp:LinkButton  ID=”LinkButton1″ runat=”server” OnCommand=”link_Clicked” CommandArgument='<%# Eval(“arg1”) %>’ NewArg='<%# Eval(“arg2”) %>‘>Link Here</asp:LinkButton>

Then in the event handler you can access them from the sender attributes:

protected void SubCatLink_Clicked(object sender, CommandEventArgs e)
{
LinkButton link = (LinkButton)sender;
String NewVal = link.Attributes[“NewArg”].toString();
}

Simple.

Rescale and save Image on the server using ASP.Net GetThumbnailImage

A quick function I use to save a rescaled version of an image during upload.

Handle the upload click and do the rescaling:

protected void UploadFileClick(object sender, EventArgs e)
{
    // get the upload control
    FileUpload FileUpload1 = (FileUpload)ColourFV.FindControl("FileUpload1");
    // get the filename
    String strFileName1 = FileUpload1.PostedFile.FileName;

    if (strFileName1 != "")
    {
        //Grab the file name from its fully qualified path at client 
        TextBox FilenameProfileTbx1 = (TextBox)ColourFV.FindControl("FilenameProfileTbx1");
        //only the attached file name not its path
        String fileName2 = System.IO.Path.GetFileName(strFileName1);

        //Save uploaded file to server 
        try
        {
            FileUpload1.PostedFile.SaveAs(Server.MapPath(ConfigurationManager.AppSettings["your setting"]) + fileName1);
        }
        catch (Exception ex)
        {
            // do any error handling u like here
        }

        // Now this function is called to rescale and save 
        RescaleAndSaveImge((Server.MapPath(ConfigurationManager.AppSettings["your setting"]) + fileName1),
            (Server.MapPath(ConfigurationManager.AppSettings["your setting"]) + "Thumbnails/" + fileName1), 155, 81);

    }

Here is the code for the function to rescale:

    public bool ThumbnailCallback()
    {
        // do any error handling here
        return false;
    }
    
    // TargetImgFile = filepath of image saved to the server which you want to rescale
    // DestImgFile = filepath of the new image you want to save to
    // NewWidth = new width in px 
    // NewHeight = new height in px
    public void RescaleAndSaveImge(String TargetImgFile, String DestImgFile, Int32 NewWidth, Int32 NewHeight)
    {
        System.Drawing.Image.GetThumbnailImageAbort myCallback = 
            new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback); 

        using(System.Drawing.Image TargetImage =
            System.Drawing.Image.FromFile(TargetImgFile))
        { 
            using (System.Drawing.Image Thumbnail = 
                TargetImage.GetThumbnailImage(NewWidth, NewHeight, myCallback, IntPtr.Zero)) 
            {
                Thumbnail.Save(DestImgFile); 
                Thumbnail.Dispose(); 
            } 
            TargetImage.Dispose(); 
        } 

    }

Checkbox OnCheckChanged within datalist/repeater/gridview controls do not fire ItemCommand event

I needed a checkbox inside a datalist to call a function when selected/unselected and found it would not fire. It did not raise the container controls itemcommand event.

Here’s a workaround that worked:

Next to your checkbox, create an asp:button with style=”display:none” so that it’s hidden, but enabled. I created a call with this one attribute and set the CssClass=”hider”.

In the codebehind, automate a click of the button when the checkbox (chk) is clicked by doing:

    chk.Add("onclick", "javascript:document.getElementById('" + btn.ClientID + "').click()");

When you check/uncheck the checkbox, the button’s click event will fire and also raise the ItemCommand event on its parent container and you can then do what you need to do here.

Using RadioButton Controls inside a Repeater (groupname problem)

Radio Buttons have the attribute ‘groupname’. The point of this attribute to to ensure any radio buttons in the same group are mutely exclusive (only one in the group can be selected).

This is the case when using them normally but as soon as you put them into a repeater control (e.g. datalist) .Net scrambles the group name value and it no longer works as a group. All can be selected.

This can be fixed with a bit of Javascript and some code during the list databinding event (provided by Microsoft).

See this link -> http://www.codeguru.com/csharp/csharp/cs_controls/custom/article.php/c12371/

Works for .Net 1.0 and 2.0.

Scrolling Image Gallery with Hover Over Controls

I recently needed to implement a scrolling gallery of images with hover over controls quickly without too much fuss. The result can be see here on the GUL Website in the history museum section.

I came across JCarousellite which is a lightweight version of JCarouselle.

This widget (based on JQuery) had pretty much everything I needed apart from handling mouse over for the previous and next controls.

Some quick modification allowed the controls to be clicked or hovered over and also provides a opacity change (JQuery fade) to add an effect as the user hovers over the controls.

There is probably a better way to get the continous scroll while the user hovers than using a timer to recall the scroll function but we needed a solution quick and it provides a nice way to pause slightly during the scroll so that the user can see the images.

The modifications required are made to the jcarousellite_1.0.1.js file as below:

          
            var t; 
            var d; 

            if (o.btnPrev)
                $(o.btnPrev).mouseover(function() {
                 t = setInterval(movePrev, 100);
                    $(this).fadeTo("fast", 1);
                });

            function movePrev() {
                go(curr - o.scroll);
            }

            if (o.btnPrev)
                $(o.btnPrev).mouseout(function() {
                    clearInterval(t);
                    $(this).fadeTo("fast", 0.5);
                });

            if (o.btnNext)
                $(o.btnNext).mouseover(function() {
                    d = setInterval(moveNext, 1);
                    $(this).fadeTo("fast", 1);
                });

            function moveNext() {
                go(curr + o.scroll);
            }

            if (o.btnNext)
                $(o.btnNext).mouseout(function() {
                    clearInterval(d);
                    $(this).fadeTo("fast", 0.5);
               });

Thats it, follow the instructions on the JCarousellite page to get it working, make these minor changes and that’s all there is to it.

Set CheckBox ‘checked’ from SQL DB if an entry exists without any code-behind

Found an interesting way to set the checked value of a checkbox as a databound control. Used in a datalist for example.

The checkbox in the datalist bound to a value in the usual way:

<asp:CheckBox ID=”MainCatCbx” runat=”server” Checked='<%# Eval(“Active”)%>’ CssClass=”smalltext12″ />

Then the query, this was fairly complicated as I wanted to join 2 tables and set the checkbox to ticked if a value was found and not-ticked if it wasn’t, but still display all the records.

The important part (bold) adds a column (active) which is detmind by the result of the case statement. If the DBID column is null the the active column is set to 0(zero) or 1 (one) and cast as a bit so that when the binding takes place it is evaluated as true or false for the checkbox checked value.

SelectCommand=”SELECT tb1.DBID, tb1.Title, tb2.DBID,
CASE WHEN tb2.DBID IS NULL THEN CAST(0 AS bit) ELSE CAST(1 AS bit) END AS Active,
tb1.ParentDBID FROM tb1 LEFT OUTER JOIN tb2 ON Specs_NavTbl.DBID = tb2.CatDBID
WHERE (tb2.DBID = ?) OR (tb2.DBID IS NULL)
AND (tb1.ParentDBID = 0)”

I found this to become usefull rather than writing codebehind to populate datasets from the DB and manually loop through and set the checkbox checked values etc.

 

Formview/Detailsview EditMode & FindControl

This stumped me for a bit today.

I changed a Formview to defaultmode=”edit” and found that FindControl would not work either in Page_Load or even in the FormView databound event – which I found very odd.

Anyway to solve it I just attached a function to the Prerender event for the controls I was trying to change values for (TextBox) and set it there.

Summary:

Page_Load or DataBound are no good for accessing controls on a Formview in Editmode.

Use the controls Prerender event to handle updating the control value before the page is displayed.

Using SqlBulkCopy to efficiently copy table from Access to SQL Server

SqlBulkCopy is a quick and efficient way to copy a whole table from a source to SQL Server, below shows how to copy from an Access DB to a table in SQL Server.

More info on SqlBulkCopy can be found in this link.

// Setup destination source and delete the table data if already exists

SqlConnection cnn = new SqlConnection(“Data Source=213.111.211.221; Password=pass;User ID=user;Initial Catalog=DB” providerName=”System.Data.OleDb”);

// delete backup data
SqlCommand cmd = new SqlCommand(“DELETE FROM LPH_ProductTable”, cnn);
cnn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
cnn.Close();
rdr.Close();

// Setup source data connection
String connString = (“Provider=Microsoft.Jet.OLEDB.4.0;” + “Data Source=” + Server.MapPath(“folder1/folder2/accessfile.mdb”));

// Create connection object by using the preceding connection string.
OleDbConnection objConn = new OleDbConnection(connString);

// Set command to get table data
OleDbCommand MDBCommand = new OleDbCommand(“Select * FROM LPH_ProductTable”, objConn);
OleDbDataReader rdr2;

// Open connection with the database.
objConn.Open();

// Read data
rdr2 = MDBCommand.ExecuteReader();

// Initializing an SqlBulkCopy object for destinaion
SqlBulkCopy sbc = new SqlBulkCopy(“Data Source=xxx.xxx.xxx.xxx; Password=pass;User ID=user;Initial Catalog=DB” providerName=”System.Data.OleDb”);

// Copying data to destination
sbc.DestinationTableName = “DestinationTableName”;
sbc.WriteToServer(rdr2);

// Closing connection and the others
sbc.Close();
rdr2.Close();
objConn.Close();