Archive

Archive for October, 2009

Disable submit button from client side

October 30th, 2009 5 comments

It seems very easy to disable ASP .Net submit button, but there are a lot of complications to perform this seemingly small thing. Usually when you disable ASP .Net submit button, it stops further processing. So if you disable button from JavaScript onclick function, it will not do postback. Sometime you want to disable submit button before page postback, for example if you have a file upload form and your code take some time to upload a big file, you might like to disable submit button. There are different solutions to solve this issue.
First solution is you can call the postback from client side JavaScript. For this I will prefer to write the JavaScript code from code behind file. You can attach an attribute like this

submit.Attributes.Add(“onclick”, “this.disabled=true;” + Page.ClientScript.GetPostBackEventReference(submit, “”));

But the problem with this solution is, if you have ASP .Net validation implemented on the controls. Even if it fails validation it fires post back event. In my form I also had ASP .Net validator. So I choose another option.
Solution is very simple, create another button with same text value and keep hidden. On client click of actual submit button hide submit button and show the hidden button. Make sure hidden button should be disabled. You can disable it from JavaScript as well. In this way user will not get idea that it’s a different button and it will also give an effect of disabled button.
Now if you are using ASP .Net validation, you would probably like to disable submit button when page validation is successful. So here is the code you can use.

protected override void OnInit(EventArgs e)
{
Button Submit = (Button)FindTemplateControl(“submit”);
Button Cancel = (Button)FindTemplateControl(“cancel”);
Button HiddenSubmit = (Button)FindTemplateControl(“hiddensubmit”);

string script = “if (!(typeof (ValidatorOnSubmit) == \”function\” && ValidatorOnSubmit() == false))”;
script += “{ “;
script += @”document.getElementById(‘” + Submit.ClientID + “‘).style.display=’none’;”;
script += @”document.getElementById(‘” + HiddenSubmit.ClientID + “‘).style.display=’inline’;”;
script += @”document.getElementById(‘” + HiddenSubmit.ClientID + “‘).disabled=true;”;
script += @”document.getElementById(‘” + Cancel.ClientID + “‘).disabled=true;”;
script += @” } “;
script += @”else “;
script += @”return false;”;

Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), “DisableSubmitButton”, script);
}

Have fun :)

Success message using ASP .Net validators

October 29th, 2009 2 comments

Recently we have implemented a form containing file upload controls. We have used ASP .Net validators to validate fields. In ASP .Net validation you can display error message in Recently we have implemented a form containing file upload controls. We have used ASP .Net validators to validate fields. In ASP .Net validation you can display error message in ValidationSummary control, but you can’t display success message. My case was I had to display a message to users before file upload start. And obviously this message needs to appear after successful page validation and before page do a post back. So in case file upload take some time, user can see a message that file upload processing has been started.
Here how I achieve it. When you use ASP .Net validator in page, your ASP .Net validator generates some JavaScript code in page. If you see the source of html page you can see this function.

function WebForm_OnSubmit()
{
    if (typeof(ValidatorOnSubmit) == “function” && ValidatorOnSubmit() ==false)
        return false;
    return true;
}

Now you need to write some code for on submit function. Create a div in your page and add your message in it. Set the display as  none in style property. Here is the div I used for my file upload form.

<div id=”successmessage” style=”display:none; color:Red>
“Please wait for your confirmation message while we upload your files (for large files this may take a few minutes)”
</div>

Now add this piece of code in cs file.

protected override void OnInit(EventArgs e)
{
    string script = “if (typeof (ValidatorOnSubmit) == \”function\” && ValidatorOnSubmit() == false)”;
    script += @”return false;”;
    script += @”else “;
    script += @”document.getElementById(‘successmessage’).style.display=’block’”;
    Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), “SuccessMessage”, script);
}

That’s all, now when you press submit button, it validates page and display success message if successful. After implementing this code your html page source will be like this

function WebForm_OnSubmit()
{
    if (typeof (ValidatorOnSubmit) == “function” && ValidatorOnSubmit() == false)
        return false;
    else
        document.getElementById(‘successmessage’).style.display=’block’;

    if (typeof(ValidatorOnSubmit) == “function” && ValidatorOnSubmit() == false)
        return false;
    return true;
}

Paging in xsl

October 22nd, 2009 3 comments

You might have seen a lot of paging options using xml and xsl. In such options you need to pass some parameters from xml and then you do the paging on it. I have implemented such pagings before. But this time it’s a simple example of creating all the paging from xsl.

Recenetly I was using a third party dll to generate xml, my task was to implement paging on returned xml without doing any change in server side code. So here is the solution.

 

<xsl:stylesheet version=1.0 xmlns:xsl=http://www.w3.org/1999/XSL/Transform>

 

      <xsl:output method=html indent=yes omit-xml-declaration=yes />

 

  <!– Define some primary variables–>

  <xsl:param name=qs-p />

  <xsl:variable name=newsCount select=count(rows/row) />

  <xsl:variable name=pageMaxLimit select=10 />

 

  <xsl:template match=/>

    <!– This page constant has been defined just to make some calculation for starting

    number and end number, we will asume constant value as 0 if there is no page variable

    value in query string–>

    <xsl:variable name=page_constant>

      <xsl:choose>

        <xsl:when test=$qs-p = ”>

          <xsl:value-of select=0/>

        </xsl:when>

        <xsl:otherwise>

          <xsl:value-of select=$qs-p – 1/>

        </xsl:otherwise>

      </xsl:choose>

    </xsl:variable>

   

    <xsl:apply-templates select=/rows/row >

      <!– Calculate the records start number and end number, later we will mactch

      records position for starting number and end number to display records for current page–>

      <xsl:with-param name=start_no select=($page_constant * 10 ) + 1 />

      <xsl:with-param name=end_no select=($page_constant * 10 ) + 10 />

    </xsl:apply-templates>

 

    <xsl:if test=$newsCount &gt; 10>

      <xsl:call-template name=paging />

    </xsl:if>

  </xsl:template>

 

  <xsl:template match=row>

    <xsl:param name=start_no />

    <xsl:param name=end_no />

    <!– Display the records for the current page number by making a check on their position –>

    <xsl:if test=position() &gt;= ($start_no) and position() &lt;= ($end_no)>

      <p>

        <a href=/{substring-after(FileRef/text(), ‘#’)} class=bold>

          <xsl:value-of select=Title/>

        </a>

        <br/>

        <xsl:value-of select=Intro/>

      </p>

    </xsl:if>

  </xsl:template>

 

  <xsl:template name=paging>

    <br></br>

    <xsl:variable name=pageCount select=floor($newsCount div 10) + ($newsCount mod 10 != 0) />

    <!–Call the template to create page numbered links,

    send loop iterator ‘i’, page count ‘count’ and current page ‘pageNo’ as parameters.–>

    <xsl:call-template name=page_links>

      <xsl:with-param name=i select=1 />       

      <xsl:with-param name=count select=$pageCount />     

      <xsl:with-param name=pageNo select=$qs-p />

    </xsl:call-template>

  </xsl:template>

  <!–Loop to create page numbers.–>

  <xsl:template name=page_links>

    <xsl:param name=i      />

    <xsl:param name=count  />

    <xsl:param name=pageNo />

   

    <xsl:if test=$i &lt;= $count>

      <xsl:variable name=page_no>

        <xsl:value-of select=$i – 1 />

      </xsl:variable>

      <a href=?p={$i} style=padding-right:2px;>

        <xsl:choose>

          <xsl:when test=$i = $pageNo or $pageNo = ”>

            <strong>

              <xsl:value-of select=$i />

            </strong>

          </xsl:when>

          <xsl:otherwise>

            <xsl:value-of select=$i />

          </xsl:otherwise>

        </xsl:choose>

      </a>

      <xsl:text xml:space=preserve> </xsl:text>

    </xsl:if>

    <xsl:if test=$i &lt;= $count>

      <xsl:call-template name=page_links>

        <xsl:with-param name=i>

          <xsl:value-of select=$i + 1/>

        </xsl:with-param>

        <xsl:with-param name=count>

          <xsl:value-of select=$count/>

        </xsl:with-param>

        <xsl:with-param name=pageNo>

          <xsl:value-of select=$pageNo/>

        </xsl:with-param>

 

      </xsl:call-template>

    </xsl:if>

  </xsl:template> 

</xsl:stylesheet>

Categories: XSLT Tags: , ,

Maintain scroll position in postbacks

October 15th, 2009 9 comments

It’s a very small thing but some time you want to maintain the scroll position after postback. I recently had the same requirement. We have a control in the depth of the page and we have to maintain the position of the scroll after the postback. Thanks to .Net developers, it’s very simple now. You can set the page property like this

MaintainScrollPositionOnPostback=”true” in aspx page directive or

Page.MaintainScrollPositionOnPostback = true;  in c# code for page_load

I hope you enjoy this easiness of .Net.

Implementing CAPTCHA in SharePoint sites

October 7th, 2009 36 comments

What is CAPTCHA

A CAPTCHA is a program that can generate and grade tests that humans can pass but automated programs cannot. For example, humans can read distorted text as the one shown below, but automated programs can’t.

 recaptcha-example

The term CAPTCHA (for Completely Automated Turing Test to Tell Computers and Humans Apart) was coined in 2000. CAPTCHA is very useful in current applications. Below are some of the applications of CAPTCHA.

  • Preventing Comment Spam in Blogs
  • Protecting Website Registration
  • Online Polls
  • Preventing Dictionary Attacks
  • Search Engine Bots
  • Worms and Spam

There are different types of CAPTCHA programs available on the internet, but all of them are not the same in their usability and implementation. Here are some examples.

 image_captcha_example_thumbnail

     captcha_with_features

 broken-captchas

 

 

 

 

 

When you start your search to implement CAPTCHA program in your site, you should consider a following items.

  • CAPTCHA should be compatible with your existing implementation. CAPTCHA programs are available for PHP, ASP .Net, Perl, Java and many other environments. Like for SharePoint I choose ASP .Net CAPTCHA.
  • It shouldn’t be very simple. Because if it generates a very simple image, using the same font and style, there is a huge chance that automated image processing programs can read it. Then it’s useless. It should be complex enough for smart hackers.
  • The scripts used to create CAPTCHA program should be secured and the system shouldn’t have loop holes for hackers. Common examples of insecurities in this respect include: (1) Systems that pass the answer to the CAPTCHA in plain text as part of the web form. (2) Systems where a solution to the same CAPTCHA can be used multiple times (this makes the CAPTCHA vulnerable to so-called “replay attacks”).
  • There are a lot of text based CAPTCHA programs in the market, like mathematical questions. These are very easy calculations for automated scripts and break easily.
  • One very important thing CAPTCHA should be accessible.  There should be support for impaired users to access it. There are CAPTCHA programs in the market with audio support.

After considering all the above mentioned factors I have selected reCAPTCHA. It has support for ASP .Net, complex to break, provides secure implementation, accessible and major thing it is free to use for any website. You can even change the look and feel of reCAPTCHA control.

Implementation in SharePoint

In order to use reCAPTCHA in your web site you need to get a new key from reCAPTCHA website (http://www.recaptcha.net). For this you need to signup to the site and then you can get a key against your domain name. Your reCAPTCHA key will be valid for the specified domain and all sub-domains. If you like to use reCAPTCHA for other domains, you need to get more keys or you can select global key to use cross domain.

You can download the reCAPTCHA dll from this link http://recaptcha.net/plugins/aspnet/ , this dll is for ASP .Net implementations. The latest version available is 1.0.3.0. Now you can deploy reCAPTCHA to local bin for the web site or in GAC as well.

In order to deploy it in GAC, you need to do some more steps. You need strongly named dll for GAC. In this case you already have a dll and it is not strongly named. But there is nothing serious worries you can change it into a strongly named dll. Here are some simple steps.

  • Get the MSIL from the dll
    • Open visual studio command prompt and enter the following command
    • ildasm Recaptcha.dll /out: Recaptcha.il
    • Rename the original dll file
      • Use this command
      • Rename Recaptcha.dll Recaptcha_org.dll
      • Create a snk (key) file
        • Sn –k Recaptcha.snk
        • Create strongly named dll from MSIL and key files
          • ilasm Recaptcha.il /dll /key= Recaptcha.snk

That’s all, now your file is ready to deploy in GAC. Deploy it in GAC. You can use below ‘gacutil’ command or simply drag and drop to assembly folder (usually the path is C:\windows\assembly).

  • Gacutil –l “path to dll”

Now you need to add the reCAPTCHA control to safe control list in web.config. This entry will be like this

<SafeControl Assembly=Recaptcha, Version=1.0.3.0, Culture=neutral, PublicKeyToken=9c9a3ef27e62a14a Namespace=Recaptcha TypeName=* Safe=True />

Add the reCAPTCHA control on the page, where you want to use it.

<%@ Register Tagprefix=Recaptcha Namespace=Recaptcha Assembly=Recaptcha, Version=1.0.3.0, Culture=neutral, PublicKeyToken=9c9a3ef27e62a14a %>

Finally insert the reCAPTCHA control under the form tag.

<Recaptcha:RecaptchaControl
ID=idAntiBotReCAPTCHA runat=server Theme=clean
PublicKey=CAPTCHA-Public-Key
PrivateKey=CAPTCHA-Private-Key/>

This is how it will look like in SharePoint page.

 recaptcha-in-form

 

Reference links.

http://www.captcha.net/

http://recaptcha.net/

http://code.google.com/p/recaptcha/downloads/list

 

Cheers

Categories: MOSS Tags: ,

Using SharePoint site Navigation to a non-SharePoint website

October 5th, 2009 Comments off

It was a very interesting task we had from one client. We had developed a publishing internet site for the same client. This client has a non SharePoint site, somehow this non SharePoint site has a relation with SharePoint site and client wanted to provide an option to navigate to other site from publishing SharePoint site. The interesting thing was client wanted to have the same look and feel for other site as of SharePoint site, specially client wanted to have the same left navigation. So when users navigate from SharePoint site to non SharePoint site they don’t get the feeling that now they are on a different website.

We have tried to think in different ways to implement this option. But there was no straight forward way to use the SharePoint navigation in a non SharePoint site. After giving it some thought we suggested something pretty simple, which looked difficult in initial talks.

We have created a web service, which interact with SharePoint. This web service actually makes a request to the same page from SharePoint website, from where we have to use the left navigation. Then it grab the whole html and use xpath to extract the div with navigation part. It just return this extracted html as xml.
Now we call this web service from the non SharePoint website and fill the left part with returned div from web method used in web service. It seems pretty simple 
We used the same technique to change the whole look and feel for the non SharePoint site to match the SharePoint site. And it worked great.

Here is the piece of code from web service.

[WebMethod(Description = "pageType should be one of pre-defined page type.")]

public XmlDocument GetLeftNavigation(string pageType)

{

  XmlDocument oDoc = new XmlDocument();

  oDoc.LoadXml(“<rows/>”);

  string html = “”;

  if (ConfigurationManager.AppSettings[pageType] != null)

  {

    string url = ConfigurationManager.AppSettings[pageType];

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

    request.Method = “GET”;

    request.Credentials = CredentialCache.DefaultCredentials;

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

 

    try

    {

      if (response.StatusCode == HttpStatusCode.OK)

      {

        // get the response stream.

        Stream responseStream = response.GetResponseStream();

        // use a stream reader that understands UTF8

        StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);

        try

        {

          html = reader.ReadToEnd();

          html = html.Substring(html.IndexOf(“<div id=\”nav-y\”>”));

          html = html.Remove(html.IndexOf(“</li></ul></div>”) + 16);

          oDoc.LoadXml(html);

          if (oDoc.GetElementsByTagName(“a”).Count > 0)

          {

            string siteUrl = ConfigurationManager.AppSettings["webpath"];

            foreach (XmlNode oNode in oDoc.GetElementsByTagName(“a”))

            {

              string href = oNode.Attributes["href"].Value;

              href = siteUrl + href.Substring(1);

              oNode.Attributes["href"].Value = href;

            }

          }

        }

        catch (Exception ex) { }

        finally

        {

          // close the reader

          reader.Close();

        }

      }

    }

    finally

    {

      response.Close();

    }

  }

  return oDoc;

}

Hope you will like it.

Cheers

Categories: MOSS Tags: , ,

Recall message in Outlook 2007

October 1st, 2009 1 comment

Recall message is an amazing option in outlook. Sometime we click on send and then realized that we had missed something or had some mistake in message. In a few steps you can recall your message, isn’t it amazing and useful.

  •  Double click the sent message and open in new window.
  • Select Other Actions from Actions tab
  • Now choose Recall this message
    • Select Delete unread copies of this message.
      (Note: the recipient needs to have Outlook opened for the message to be deleted)
    • To replace the message:
    • Select Delete unread copies and replace with a new message, click OK, and type your new message.
    • To be notified about the success of the recall or replacement:
    • Check the Tell me if recall succeeds or fails for each recipient check box.
  • Click OK

Cheers

Categories: General Tags: ,