Exploring the depths and potentials of ASP.NET RSS 2.0 or Subscribe to .BenRush by Email
 Thursday, April 05, 2007

This exercise requires no C# or VB.Net code at all (unless you want to start getting fancy), and is relatively well documented on the internet. However, I like to recap things quickly through these little tutorials, so hopefully this might summarize how to quickly get up and running with parent<->child window script communication.

First, create two web forms (they don't need to be, but for our exercise they will be). We'll call the Default.aspx and Default2.aspx.

Second, open up Default.aspx and add the following script functionality:

        <input id="Button1" type="button" value="button" onclick="window.open('default2.aspx');" />
        <input id="Text_Value" type="text" />

...here you see that you open up default2.aspx when you click on the button.

Third, go to your Default2.aspx file and add the following HTML:

        Please Enter Some Data:&nbsp;
        <input id="Text1" type="text" />
        <input id="Button1" type="button" value="button" onclick="return Button1_onclick()" /></div>

Fourth...add the following script:

function Button1_onclick() {
    opener.document.getElementById('Text_Value').innerText =
        document.getElementById('Text1').value;
    self.close();
   
    return;
}

The result will be opening up the default2.aspx form from default.aspx, you can enter text into the Text1 field (see above), click the Button1 which calls the Button1_onclick method. This method communicates with the parent window, sets a text box in that window's document and closes itself.

This requries no .Net code to accomplish; this can all be done through JavaScript.


Recommended reading:


kick it on DotNetKicks.com
Thursday, April 05, 2007 12:32:07 AM (Central Standard Time, UTC-06:00)  #    Comments [0] - Trackback
ASP.Net | JavaScript | Programming
 Wednesday, April 04, 2007

Say you want to use the browser component to automate some form of web browser experience - for example, say you want to programmatically enter some value into a textbox and click a button using C# or VB.Net. To do this is actually quite simple (and, dare we say it, fun).

First, you simply add your browser component to your windows form.

Second, you register an event handler with the browser component for the DocumentCompleted event:

            this.webBrowser1.Url = new Uri("http://www.google.com");
            this.webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);

Third, you fill in the event handler with something that looks like this:

        void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (!_clicked)
            {
                _clicked = true;

                HtmlElement queryBox = this.webBrowser1.Document.All["q"];
                queryBox.SetAttribute("value", "hello world");

                HtmlElement goButton = this.webBrowser1.Document.All["btnG"];
                goButton.InvokeMember("click");
            }

            return;
        }

This will load the www.google.com homepage, fill in their submit text box and click the Search button.

In the golden days of MSHTML component reuse (before the niceness of .Net'ifying the browser DOM) you had to use a RCW (Runtime Callable Wrapper) around the MSHTML COM library. Everything is obviously implemented through IDispatch here (because you have to be able to do this stuff from VB6 or scripting environments), and so much of the invocation of methods (like click) was done by loosly picking the name for the method and building the stack frame through arrays, etc. The RCW made things a bit nicer for you (you didn't have to think about IDispatch), but you still had to think about COM.

It's been years since I've developed in COM and ATL and I'm glad I don't have to anymore.

Recommended reading:


kick it on DotNetKicks.com
Wednesday, April 04, 2007 10:55:24 AM (Central Standard Time, UTC-06:00)  #    Comments [0] - Trackback
Programming | WinForms and WPF

Say you have a master page and content page scenario, and from the content page you want to interact with DOM elements described from the master page (for example, the main body element). This is how I do it:

First, add the following attributes to your body element so that it is included in the server-side runtime and can be interacted with from there:

<body id="mainbody" runat="Server">

...notice how the body element now has an id and has the runat="server" attribute set.

Second, from code within the content page (I'm doing it in Page_Load) add code like this:

    protected void Page_Load(object sender, EventArgs e)
    {
        HtmlGenericControl ctrl = (HtmlGenericControl)this.Master.FindControl("mainbody");
        ctrl.Attributes.Add("onload", "alert('hello');");
        return;
    }

The key here is to now grab the body element, add some script to it, and then let it all run as normal. When I run the solution, the content page is loaded, its Page_Load called, the script injected into the body element (of the master page) and I see "hello".

Recommended reading:

kick it on DotNetKicks.com
Tuesday, April 03, 2007 11:47:56 PM (Central Standard Time, UTC-06:00)  #    Comments [2] - Trackback
AJAX | ASP.Net | Computing
 Tuesday, April 03, 2007

This is actually a variation on another post I made where I described how to detect when a partial postback has started and ended in ASP.Net AJAX. A great example of using this code is changing the mouse cursor when a partial postback occurs, and then resetting it when the postback completes. The following code will accomplish this:

            <script language="javascript">
                var req = Sys.WebForms.PageRequestManager.getInstance();
                req.add_endRequest(OnFinishedRequest);
                req.add_beginRequest(OnStartedRequest);
                function OnFinishedRequest(sender, args)
                {
                    document.body.style.cursor='default';
                }
                function OnStartedRequest(sender, args)
                {
                    document.body.style.cursor='wait';
                }
            </script>

...one thing to keep in mind when doing this is that the document body element doesn't necessarily take up the entire browser window; and so you will sometimes want to style the body element to make it the right size to take up the entire window.

Recommended reading:

kick it on DotNetKicks.com
Tuesday, April 03, 2007 10:50:33 PM (Central Standard Time, UTC-06:00)  #    Comments [0] - Trackback
AJAX | ASP.Net | Programming

If you look within the ASP.Net AJAX framework you will find no methods for registering UpdatePanels with the ScriptManager; why? The reason is because UpdatePanels register themselves with the page's ScriptManager control in their OnInit method:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    this.RegisterPanel();
    this.CreateContents(base.DesignMode);
}


What this means is that when an UpdatePanel responds to the Init event, it will register itself with the ScriptManager for that page. You can get the exception detailed above when you have inadvertantly registered an UpdatePanel (because it was added to the page), but it was never rendered to the page. What happens is locally (that is, within the browser) the ASP.Net AJAX script runtime will execute as if the UpdatePanel was in the page DOM; but since it isn't an exception gets thrown, which is the exception you see above.

Two ways to fix this:

1) Dynamically add the UpdatePanel to your page only when you need it,
2) Set the UpdateMode of the panel to Conditional.



Recommended reading:

kick it on DotNetKicks.com
Tuesday, April 03, 2007 12:22:58 PM (Central Standard Time, UTC-06:00)  #    Comments [2] - Trackback
AJAX | ASP.Net | Programming

I'll go into the reason why this happens in a second, but sometimes you'll encounter an exception like this:

"InvalidCastException was unhandled by user code: unable to cast object of type 'ASP.xxxx' to type 'xxxx'". It looks like this:



You might think the way to fix this exception would be by casting to the ASP.home_aspx (in this example) type (which I'll explain to you a minute), but often this does not work either. Why? What's going on?

This is all the result of the dynamic build nature of ASP.Net. What's happening is that types are being automatically generated for you by the ASP.net runtime in some temp directory on your disk. Occasionally this system gets mucked up and you run into typing conflicts.

The way it all works is that ASP.home_aspx (in this example) is the final class that is executed by the ASP.Net runtime when it asks to render out the home.aspx. home_aspx inherits from the class as defined in the .cs/.vb/.aspx files you actually hand-write. ASP.Net inherits from your class so that it can add various other bells and whistles to the class to actually run correctly within the runtime (lots of details here).

...the only thing I can reason that happens when you get a TYPING conflict in this scenario is that the base class the runtime is using for, in this situation, home_aspx is actually a stale object; one that wasn't properly cleaned up by the runtime/Visual Studio. To fix this situation, you generally need to only clean out the temporary asp.net files for this particular site under:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\

Interesting how this looks like a bug in the .Net runtime, but it's actually a bug in the build environments.

Recommended reading:


kick it on DotNetKicks.com
Tuesday, April 03, 2007 12:06:05 PM (Central Standard Time, UTC-06:00)  #    Comments [0] - Trackback
ASP.Net | Programming

Put here for antiquity's sake.

    <connectionStrings>
        <add name="SqlServerDB"
       connectionString="Data Source=SOMECOMPUTER\SQLEXPRESS;Initial Catalog=UserStore;Integrated Security=True"
      providerName="System.Data.SqlClient"/>
    </connectionStrings>

    <membership>
            <providers>
                <clear/>
                <add name="AspNetSqlMembershipProvider"
         type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
          connectionStringName="SqlServerDB"
          enablePasswordRetrieval="false"
          enablePasswordReset="true"
          requiresQuestionAndAnswer="false"
          applicationName="MyRandomWebApplication"
          requiresUniqueEmail="false"
          passwordFormat="Hashed"
          maxInvalidPasswordAttempts="5"
          minRequiredPasswordLength="7"
          minRequiredNonalphanumericCharacters="1"
          passwordAttemptWindow="10"
          passwordStrengthRegularExpression=""/>
            </providers>
        </membership>

Recommended reading:

kick it on DotNetKicks.com
Tuesday, April 03, 2007 10:43:56 AM (Central Standard Time, UTC-06:00)  #    Comments [0] - Trackback
ASP.Net | Programming
 Monday, April 02, 2007

It's really easy; some may not know how to do it though, so I'll write a quick entry on it.

Say you have a GridView, and you want to respond (with server code) to someone clicking an item in the GridView (an image link, text link, etc). First thing you do is setup a handler for the GridView's OnRowCommand event:

<asp:GridView id="GridView_Views" .....
    OnRowCommand="GridView_Views_RowCommand" ....>

You then implement the event handler. You can find the row number for the object that was clicked, and retrieve data that you store in the DataKeys collection for that row this way:

    protected void GridView_Views_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        ....
        Int32 index = Int32.Parse((String)e.CommandArgument);
        String uniqueID = (String)this.GridView_Views.DataKeys[index].Value;
        ....

For more information on the DataKeys property, see here. For more information on the RowCommand event, see here.

Recommended reading:

kick it on DotNetKicks.com
Monday, April 02, 2007 7:33:01 PM (Central Standard Time, UTC-06:00)  #    Comments [0] - Trackback
ASP.Net | Programming

Computers Blogs - Blog Top Sites

Archive
<April 2007>
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345
Blogroll
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2009
Benjamin Rush
Sign In
Statistics
Total Posts: 444
This Year: 0
This Month: 0
This Week: 0
Comments: 128
Themes
Pick a theme:
All Content © 2009, Benjamin Rush
DasBlog theme 'Business' created by Christoph De Baene (delarou)