Microsoft Technology, .Net, BizTalk, Sharepoint & etc.

Liedong(Ken) Zheng, Senior SharePoint Developer at SIMPLOT

Archive for July, 2008

Shortcut Keys Visual Studio

Posted by ken zheng on July 31, 2008

Just add a link to a super Shortcut list for Visual Studio

http://www.dofactory.com/ShortCutKeys/ShortCutKeys.aspx

Posted in VS2008 | Tagged: | Leave a Comment »

Switch SilverLight UserControl

Posted by ken zheng on July 30, 2008

Silverlight does not have the Page type, the term is currently used is RootVisual UserControl. RootVisual object is analogous to the root window in WPF and can only be set once for the lifetime of the app, and is effective once the Application’s Startup event is raised. But this not true, you can set RootVisual as many times you want. So Application_Startup can be used to call multiple Silverlight controls.

    <form id="form1" runat="server" style="height:100%;">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <div  style="height:100%;">
            <asp:Silverlight ID="Xaml1" runat="server" InitParameters="ControlId=Page" Source="~/ClientBin/SilverlightApplication1.xap" MinimumVersion="2.0.30523" Width="100%" Height="100%" />
        </div>
    </form>
		<object data="data:application/x-silverlight," type="application/x-silverlight-2-b2" width="100%" height="100%">
			<param name="source" value="ClientBin/SilverlightApplication1.xap"/>
			<param name="onerror" value="onSilverlightError" />
			<param name="background" value="white" />
			<param name="initParams" value="ControlId=BookStore" />

			<a href="http://go.microsoft.com/fwlink/?LinkID=115261" style="text-decoration: none;">
     			<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/>
			</a>
		</object>

and in the App.xaml.cs

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            if (e.InitParams.ContainsKey("ControlId"))
            {
                switch (e.InitParams["ControlId"])
                {
                    case "BookStore":
                        this.RootVisual = new BookStoreWithConverters();
                        break;

                    case "Page":
                        this.RootVisual = new Page();
                        break;
                }
            }
        }

Posted in Silverlight | Tagged: | 2 Comments »

Event Handling

Posted by ken zheng on July 30, 2008

Just like to post code for event handling for VB .NET and C# for reference
VB .NET

Imports System

Public Class CTimer

    Delegate Sub SecondDel(ByVal xintTime As Integer)
    Private evtSecond As SecondDel
    Public Event evtMinute As SecondDel
    Public Event evtHour(ByVal xHour As Integer)
    public Shared lngSeconds As Long

    Public Sub Register(ByVal objSecond As SecondDel)
        evtSecond = evtSecond.Combine(evtSecond, objSecond)
    End Sub

    Public Sub OnTimer()
        lngSeconds = lngSeconds + 1
        If lngSeconds Mod 5 = 0 Then
            evtSecond(lngSeconds)
        End If
        If lngSeconds Mod 10 = 0 Then
            RaiseEvent evtMinute(lngSeconds)
        End If
        If lngSeconds Mod 30 = 0 Then
            RaiseEvent evtHour(lngSeconds)
        End If
    End Sub

End Class

Public Class CClock

    Private WithEvents mobjTimer As CTimer

    Sub New()
        mobjTimer = New CTimer()
        mobjTimer.Register(New CTimer.SecondDel(AddressOf SecondEvent))
        AddHandler mobjTimer.evtMinute, AddressOf MinuteEvent
        While (mobjTimer.lngSeconds < 60)
            mobjTimer.OnTimer()
            System.Threading.Thread.Sleep(100)
        End While
    End Sub

    Private Sub SecondEvent(ByVal xintTime As Integer)
        Console.WriteLine("Second's Event")
    End Sub

    Private Sub MinuteEvent(ByVal xintTime As Integer)
        Console.WriteLine("Minute's Event")
    End Sub

    Private Sub mobjTimer_evtHour(ByVal xintTime As Integer) _
            Handles mobjTimer.evtHour
        Console.WriteLine("Hour's Event")
    End Sub

    Public Shared Sub Main()
        Dim cc1 = New CClock()
    End Sub

End Class

C#

using System;

public class CTimer
{

    public delegate void SecondDel(int xintTime);
    private SecondDel evtSecond;
    public event SecondDel evtMinute;
    public event evtHourEventHandler evtHour;
    public delegate void evtHourEventHandler(int xHour);
    public static long lngSeconds;

    public void Register(SecondDel objSecond)
    {
        evtSecond = evtSecond.Combine(evtSecond, objSecond);
    }

    public void OnTimer()
    {
        lngSeconds = lngSeconds + 1;
        if (lngSeconds % 5 == 0) {
            evtSecond(lngSeconds);
        }
        if (lngSeconds % 10 == 0) {
            if (evtMinute != null) {
                evtMinute(lngSeconds);
            }
        }
        if (lngSeconds % 30 == 0) {
            if (evtHour != null) {
                evtHour(lngSeconds);
            }
        }
    }

}

public class CClock
{

    private CTimer mobjTimer;

    public CClock()
    {
        mobjTimer = new CTimer();
        mobjTimer.Register(new CTimer.SecondDel(SecondEvent));
        mobjTimer.evtMinute += MinuteEvent;
        while ((mobjTimer.lngSeconds < 60)) {
            mobjTimer.OnTimer();
            System.Threading.Thread.Sleep(100);
        }
    }

    private void SecondEvent(int xintTime)
    {
        Console.WriteLine("Second's Event");
    }

    private void MinuteEvent(int xintTime)
    {
        Console.WriteLine("Minute's Event");
    }

    private void mobjTimer_evtHour(int xintTime)
    {
        Console.WriteLine("Hour's Event");
    }

    public static void Main()
    {
        object cc1 = new CClock();
    }

}

Posted in Uncategorized | Tagged: | Leave a Comment »

Process Monitor v1.35

Posted by ken zheng on July 29, 2008

if it’s a simple permissions failure (which it is) – just find out which account is trying to do what. :) Download and run procmon (http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx). Filter its trace to only show file events in the d:\inetpub\wwwroot\ folder and then watch for the failure. If something is trying to access d:\inetpub\wwwroot\web.config and getting denied. Procmon will tell you a) which process tried, b) which account it tried as and c) what it tried to do.

Posted in Tools | Leave a Comment »

The type or namespace name ‘ScriptManager’ does not exist in the namespace ‘System.Web.UI’

Posted by ken zheng on July 28, 2008

If you get this error, make sure add reference to System.Web.Extensions assembly. If it does referenced, remove it and re-add.

Posted in Uncategorized | Leave a Comment »

Configure a service to start with the WinDbg debugger attached

Posted by ken zheng on July 28, 2008

Configure the “Image File Execution” options. To do this, use one of the following methods:

Method 1: Use the Global Flags Editor (gflags.exe)

    a. Start Windows Explorer.
    b. Locate the gflags.exe file on your computer.

    Note The gflags.exe file is typically located in the following directory: C:\Program Files\Debugging Tools for Windows.
    c. Run the gflags.exe file to start the Global Flags Editor.
    d. In the Image File Name text box, type the image name of the process that hosts the service that you want to debug. For example, if you want to debug a service that is hosted by a process that has MyService.exe as the image name, type MyService.exe.
    e. Under Destination, click to select the Image File Options option.
    f. Under Image Debugger Options, click to select the Debugger check box.
    g. In the Debugger text box, type the full path of the debugger that you want to use. For example, if you want to use the WinDbg debugger to debug a service, you can type a full path that is similar to the following: C:\Program Files\Debugging Tools for Windows (x86)\windbg.exe
    h. Click Apply, and then click OK to quit the Global Flags Editor.

Posted in Tools | Tagged: | Leave a Comment »

Start WINDBG

Posted by ken zheng on July 28, 2008

Install Windbg

Windbg is the tool for the ASP.NET support engineer. It is free and it’s available at www.microsoft.com/whdc/devtools/debugging/default.mspx. The learning curve is steep to say the least, but if you’re interested in finding out what is going on behind the scenes in your application, then Windbg is your new best friend. For information on how to configure windbg, please refer to the documentation. Pay special attention to the section concerning symbols.

There is an extension called SOS.dll that you will want to use. You’ll find it in the framework directory so for Framework 2.0 look in “C:\Windows\Microsoft.NET\Framework\v2.0.50727″. You might want to copy it into the same folder as windbg for easy access.
Get a memory dump

Windbg will allow you to either perform a post mortem analysis on a memory dump or to attach to a process during execution. I mainly deal with memory dumps, since it’s a lot easier to request a single file from a customer rather than access to their server. Maybe I’ll cover live debugging in another post, but for now we’ll just look at dump files.
Vista

If you’re running Windows Vista, then you can easily create a dump file from the task manager. Simply open up the “Processes”-tab, right-click the process you wish to dump and select “Create Dump File”.
Adplus

For any other system or if you want to specify certain conditions I’d recommend using a script called adplus. It comes with the Windbg installation and is run from the command prompt. Adplus will take a number of arguments, but for basic operation there are two things you need to specify:

1. When to take the dump
2. The name or process ID of the process you wish to take a dump of

The dumps generated by adplus will be saved to a subfolder of the folder where you’ve installed windbg.

For example:
adplus -crash -pn w3wp.exe

This will generate a full memory dump right before any process named w3wp.exe terminates or recycles. This will also generate minidumps on all first chance exceptions.

adplus -crash -pn w3wp.exe -NoDumpOnFirst

Same as above, but without the minidumps.

adplus -hang -p 2960

This will immediately get a full dump of the process with ID 2960. Commonly used when the process has hung, or is generally unresponsive. Hence the name.

Advanced Adplus

If you’re trying to pin down the cause of a specific exception, then you can use a config file. This is a sample config file that will create a full memory dump once a System.Runtime.InteropServices.COMException occurs. Simply copy the code below into notepad and save it as MyConfig.cfg.

CRASH

!load clr10\sos

NoDumpOnFirstChance
NoDumpOnSecondChance


clr
Log
!clr10\sos.cce System.Runtime.InteropServices.COMException 1; j ($t1 = 1) ‘.dump /ma /u c:\dumps\exceptiondump.dmp;gn’ ; ‘gn’
GN
Void
GN

As you can see you can easily adjust the config so that it gets a dump on any other exception. The dump will be saved in c:\dumps, so you should also make sure that this folder exists. When you’re ready, run adplus with the following syntax:
adplus -c myconfig.cfg -pn w3wp.exe

Debugging through a Terminal Server session

If you don’t have direct access to the server you need to either attach noninvasively or schedule the command you wish to run. This can seem a bit complicated, but there’s a pretty good howto written in the knowledge base under the following article: http://support.microsoft.com/default.aspx/kb/323478

I followed the instructions in the article and they are pretty straight forward. However, there are a couple of caveats that are worth mentioning and hopefully might save you some time and agony:

* When running the command line “cscript adplus.vbs -crash -pn aspnet_wp.exe -o c:\crashdump” you might see a message regarding a missing environment variable _NT_SYMBOL_PATH.

To solve the problem you can add an environment variable and set it to the debugger symbol path (e.g.: C:\Symbols). You can add an environment variable by pressing the right button on my computer and choosing properties and then advanced/environment variables…

* To debug the asp.net process you will probably have to connect to your server remotely. If your server is running Windows 2000 and you are using a terminal services remote session, you can not debug a native process from another session. You can read Windows 2000 does not support cross-session debugging using a terminal server for more info. To solve this problem use the following trick. Although you can not debug the running process directly you can still make a snap shot of it and debug/examine the debug dump. The following command will take a snapshot of the asp net process:

“cscript adplus.vbs -hang -pn aspnet_wp.exe -o c:\crashdump”

Note the command line uses the –hang command line switch instead of the –crash.

* The article refers to using SOS extensions for debugging managed code. If you are running .Net 2.0 the following command “.load clr10\sos” will not work. Any command you try will give you the following descriptive message “Doesn’t work with 2.x”. To solve this problem use the “.loadby sos mscorwks” command instead. You can find more info about it here.

http://www.codeproject.com/KB/debug/WinDBGAndSOS.aspx#_Toc190680207

Posted in Uncategorized | Leave a Comment »

Debugging Attributes

Posted by ken zheng on July 28, 2008

My colleague Corneliu talk about the Debugging Attributes in the RDN, it is very useful.

Check it out on his blog http://www.acorns.com.au/blog/?p=128

Posted in Uncategorized | Leave a Comment »

Bring a Yes/No Dialog box when Back Button is clicked in Broswer

Posted by ken zheng on July 28, 2008

Add

<SCRIPT LANGUAGE="JavaScript1.2" TYPE="text/javascript">
<!--
window.onbeforeunload = unloadMess;
function unloadMess(){
	mess = "Thanks for visiting.\nYou will now be returned to our regularly scheduled program."
	return mess;
}
//-->
</SCRIPT>

before your html body.

But there is a issue as the the event can be invoked using the form submit method. which is
the ‘__doPostBack’ script and it contains the line
‘theform.submit()’.

And I just found a way you can detect if it is the Back button clicked by

 <script>
 function onBeforeUnloadAction(){
   return "Think twice before you leave!";
 }
 window.onbeforeunload = function(){
   if((window.event.clientX<0) ||
      (window.event.clientY<0)){
     return onBeforeUnloadAction();
   }
 }
 </script>

The way to avoid it is that you add a client click script to set event.cancelBubble property to true. Here is some code:

	Page.ClientScript.RegisterStartupScript(typeof(String), "ConfirmClose", @"
	<script>
                var postback= false;
		window.onbeforeunload = confirmExit;
		function confirmExit()
		{
		if(postback == true)
			event.cancelBubble = true;
		else
			return ""Please don't leave this page without clicking the 'Save Changes' or 'Discard Changes' buttons."";
		}
	</script>");

VB .NET

Page.ClientScript.RegisterStartupScript(GetType(String), "ConfirmClose", "" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "<script>" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "var postback= false; window.onbeforeunload = confirmExit;" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "function confirmExit()" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "{" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "if(postback == true)" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "event.cancelBubble = true;" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "else" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "return ""Please don't leave this page without clicking the 'Save Changes' or 'Discard Changes' buttons."";" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(9) & "" & Chr(13) & "" & Chr(10) & "" & Chr(9) & "" & Chr(9) & "} " & Chr(13) & "" & Chr(10) & "" & Chr(9) & "</script>")

then my save button contains the following aspx markup:

OnClientClick="postback=true;return true;"

http://www.hunlock.com/blogs/Mastering_The_Back_Button_With_Javascript

http://www.webreference.com/dhtml/diner/beforeunload/bunload4.html

Posted in Uncategorized | Tagged: | Leave a Comment »

WINDBG

Posted by ken zheng on July 25, 2008

If your WinDBG skills are lacking, I encourage you to take a little dip into WinDBG and get your feet wet by following the guide from Johan Straarup

Happy debugging!

Posted in Uncategorized | Tagged: | Leave a Comment »