May 20
2010
// Member variables
private static XmlDocument _document;
private static XDocument _xdoc;
private static object _lock = new object();

/// <summary>
/// read xml file "ExtendedSearchService.xml" from resources and return it as XDocument
/// </summary>
public static XDocument XDoc
{
get
{
lock (_lock)
{
if (_xdoc == null)
{
_xdoc = XDocument.Parse(Properties.Resources.ExtendedSearchService);
}
}
return _xdoc;
}
}

/// <summary>
/// helpmethod to convert XDocument to XmlDocument
/// </summary>
/// <param name="xdoc"></param>
/// <returns></returns>
public static XmlDocument ToXmlDocument(XDocument xdoc)
{
var xmlDoc = new XmlDocument();
xmlDoc.Load(xdoc.CreateReader());
return xmlDoc;
}
 
 
Using it:
var test = ToXmlDocument(XDoc);
 
 

Reverse direction:

/// <summary>
/// Converts an XmlDocument to an XDocument.
/// </summary>
/// <param name="xmldoc">The XmlDocument to convert.</param>
/// <returns>The equivalent XDocument.</returns>
public static XDocument ToXDocument(this XmlDocument xmldoc)
{
return XDocument.Load(xmldoc.CreateNavigator().ReadSubtree());
}
=======================================================================
Tags:
Apr 05
2010

Registering a javascript for an aspx page is possible in many ways.
Here is an example to add an eventhandler for an asp.net control using ASP.NET AJAX client life-cycle events.

  • First on the bottom of our javascript code in aspx we have to add handler functions for the load and unload event. The event handlers itself contains the needed js functions:

    Sys.Application.add_load(jsFunction_pageLoad);
    Sys.Application.add_unload(jsFunction_pageUnload);

  • The next step is to add a click handler to our asp.net control, in this case to a radiobutton. Javascript finds the control by getting the controls ClientID. To complete this way the handler will removed when page will be unloaded:

    function jsFunction_pageLoad(source, args)
    {
        if (!args.get_isPartialLoad())
        {
            $addHandler($get('<%= rbtnTest.ClientID %>'),
'click', rbtnTest_click);
         }
    }

    function jsFunction_pageUnload(source, args)
    {
        $removeHandler($get('<%= rbtnTest.ClientID %>'),
'click', rbtnTest_click);
    }

  •  Now we can write the real js function which will execute something when the radiobutton is clicked:

    function rbtnTest_click(evt)
    {
        alert('hello world');
    }

 

Here the complete code:

<script type="text/javascript">
//<![CDATA[

    function jsFunction_pageLoad(source, args)
    {
        if (!args.get_isPartialLoad())
        {
            $addHandler($get('<%= rbtnTest.ClientID %>'), 'click', rbtnTest_click);
         }
    }

    function jsFunction_pageUnload(source, args)
    {
        $removeHandler($get('<%= rbtnTest.ClientID %>'), 'click', rbtnTest_click);
    }

    //event when rbtnTest is clicked
    function rbtnTest_click(evt)
    {
        alert('hello world');
    }


 Sys.Application.add_load(jsFunction_pageLoad);
 Sys.Application.add_unload(jsFunction_pageUnload);

//]]>
</script>

More informations about AJAX client events you can get here.

Tags: Tags:
Feb 26
2010

If a user tries to hit an ASP.NET submit button more than once only the very first request should submit to server.
All other clicks shouldn't make any request. So, for this you need to disable the button when first time click on button and enable it after processed.

Example 1)  in codebehind:
   
   /// <summary>
   /// OnInit stage
   /// </summary>
   /// <param name="e"></param>
   protected override void OnInit(EventArgs e)
   {
        base.OnInit(e);
        btnDataSave.Attributes.Add("onclick", "javascript:" + btnDataSave.ClientID + ".disabled=true;"  + ClientScript.GetPostBackEventReference(btnDataSave, string.Empty));
    }
  
  The method "ClientScript.GetPostBackEventReference" allows you to create the "__doPostBack Script" code which causes a serverside postback. 
  
  
  or example 2) in aspx:
  
            <asp:Button
                ID="btnDataSave"
                runat="server"        
                Text="SAVE"
                OnClientClick='this.disabled=Page_ClientValidate("valgrpData");'
                UseSubmitBehavior="false"
                ToolTip="save data"
                ValidationGroup="valgrpData" />
      
   using this js function:
   
   //check if clientside validation of a single validationgroup is valid
   //returns a boolean value
   function Page_ClientValidate(valGrp)
   {
      Page_InvalidControlToBeFocused = null;
      if (typeof(Page_Validators) == "undefined")
      {
        return true;
      }
      var i;
      for (i = 0; i < Page_Validators.length; i++)
      {
         ValidatorValidate(Page_Validators[i], valGrp, null);
      }
      ValidatorUpdateIsValid();
      ValidationSummaryOnSubmit(valGrp);
      Page_BlockSubmit = !Page_IsValid;
      return Page_IsValid;
   }
      
The button will only be disabled when page validation passed successful.   
   
Problem when using both ways:
In Firefox the disabled button looks the same like an enabled button, in IE it works.
This could irritate the user. Well this is a different behaviour of browsers.
But if necessary there may be more complex ways to solve this problem for example
using different styles or images for the button.

    
Thanxs for Praveen Kumar Battula for his initial idea i found at
http://praveenbattula.blogspot.com/2010/01/disable-button-in-onclick-and-process.html

Tags:
Jan 18
2010

WatiN - developed in C# - brings to you an easy way to automate your tests with Internet Explorer and FireFox using .Net.
Often WatiN is used to click through the UI of your web application.
In this case it is important to use a sure method to find controls in a page.

A really simple way to find a control for example is:

ie.Link(Find.ById("ctl03_lnkbtnConfirmStartingProcess")).Click();

or

var link = ie.Link("ctl03_repCustomers_ctl00_repProducts_ctl00_lnkSlideDownStatistics");

 

Below there are two examples how to find controls in a page using regular expression. In my opinion this is more comfortable to use.

Example 1 - Find a dropdownlist in a testpage and check dropdown values:

//some other code...
ie.GoTo(
string.Format("{0}{1}", baseURL, "testpage.html"
));
var
selectStatusNames = new[] { "all", "online", "offline", "scheduled" };
var statusOpts = ie.SelectList(FindWithRegEx("ddlState")).Options;
for (var i = 0; i < selectStatusNames.Length; i++)
{
    if (String.Equals(statusOpts[i].InnerHtml, selectStatusNames[i])) continue;
    var msg = "Search in articles: selectbox 'Status': option #" + i + " must be " + selectStatusNames[i];
    trace(msg);
    Assert.Fail(msg);
}

 

Example 2 - Find a hyperlink in a testpage and click it:

//some other code...
ie.GoTo(string.Format("{0}{1}", baseURL, "testpage.html"));
var lnkSubmit = ie.Link(FindWithRegEx("lnkbtnSubmitPage"));
Assert.IsTrue(lnkChangePassword.Exists, "cannot find linkbutton to submit page");
lnkChangePassword.Click();

 

helpmethods:

/// <summary>helpmethod to find a control in a page using regular expressions</summary>
/// <param name="idCtrl">part of control ID as string</param>
/// <returns>control ID as string</returns>
public static Regex FindWithRegEx(string idCtrl)
{
    return new Regex(".*" + idCtrl + "$");
}

/// <summary>helpmethod to trace and debug output to console</summary>
/// <param name="msg">debug message
</param>
/// </summary>
/// <param name="msg">message as string</param>
public
static void trace(String msg)
{
    Console.WriteLine(msg);
}

Tags: Tags:
Sep 22
2009

Here a simple example to get a commaseparated list of cities to show them in the UI.
The result could be "New York, Madrid, Rome and Munich".

/// <summary>
/// commaseparated string of location cities
/// </summary>
        public string LocationsCitiesAsString
        {
            get
            {
                string strVacLocations = null;

                //put all vacancyLocations commaseparated to a string:
                foreach (var location in Vacancy.Locations)
                {
                     strVacLocations += location.City + ", ";
                }

                //if existing delete comma and whitespace at the end of string:
                if (strVacLocations.EndsWith(", "))
                {
                    strVacLocations = strVacLocations.Remove(strVacLocations.Length - 2, 2);
                }

                //replace last ", " with " and":
                int lastSpace = strVacLocations.LastIndexOf(", ");
                if (lastSpace > 0)
                {
                    strVacLocations = strVacLocations.Remove(lastSpace, 2).Insert(lastSpace, " and ");
                }

                return strVacLocations;
            }
        }

Tags: Tags:
Jul 09
2009

Sometimes it is necessary to read an HTML File, to replace some sections and to response the achievment. A good way to to this is using regular expressions.

For example:

Read the HTML file:
string strHTMLBefore = ReadHTML(@"c:\example.html");

Execute regEx operations:
string strHTMLAfter = ExecuteRegExOperations(strHTMLBefore);

Print string to a literal:
litHTMLAfterReplace.Text = strHTMLAfter;

 

C#:

        /// <summary>
        /// reads an html file from filesystem and returns ist
        /// </summary>
        /// <param name="filePath">path to file on disk</param>
        /// <returns>file content</returns>
        private string ReadHTML(string filePath)
        {
            bool bExists = File.Exists(filePath);
            string fileOriginal = null;

            if (bExists)
            {
                StreamReader objStreamReader = new StreamReader(filePath, Encoding.Default);
                fileOriginal = objStreamReader.ReadToEnd();
                objStreamReader.Close();
            }
            else
            {
                lblMessage.Visible = true;
                lblMessage.Text = "file not found";
            }
            return fileOriginal;
        }

 

         /// <summary>
        /// executes RegEx operations
        /// </summary>
        /// <param name="strHTMLBefore">input string</param>
        /// <returns>output string</returns>
        private string ExecuteRegExOperations(string strHTMLBefore)
        {
            string strBeforeRegEx = strHTMLBefore;
            string strAfterRegEx = null;

            //vacancyTitle:
            string patternExample  = "(<!--###JS24Begin:Name_Title###-->)(([\\r,\\n]|.)*?)(<!--###JS24End:Name_Title###-->)";
            Regex myRegex = new Regex(patternExample);
            strAfterRegEx = myRegex.Replace(strBeforeRegEx, "string to be inserted");

            return strAfterRegEx;
        }

 

example.html:

<td width="40%" style="padding: 5px; border: 1px solid #666666">
        <!--###JS24Begin:Name_Title###-->this text will be replaced by regex<!--###JS24End:Name_Title###-->
</td>

 

It works fine. But a malfunction must be described. If the regex does not find the "Begin" tag in aspx code, for example a mistake in writing, the program does not stop and the text will not be replaced.
That may be ok. But if the regex does not find the "end" tag the program will be lead to an endless loop and your cpu willl work up to 100% :-)
Until now I didn't found a way to avoid this. Do you have an idea?

Tags: