<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>.NET FOLLOWER</title>
	<atom:link href="http://dotnetfollower.com/wordpress/feed/" rel="self" type="application/rss+xml" />
	<link>http://dotnetfollower.com/wordpress</link>
	<description>Scenes from programmer&#039;s life</description>
	<lastBuildDate>Sun, 16 Jun 2013 02:31:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.3</generator>
		<item>
		<title>SharePoint: Simple Event Logger</title>
		<link>http://dotnetfollower.com/wordpress/2013/06/sharepoint-simple-event-logger/</link>
		<comments>http://dotnetfollower.com/wordpress/2013/06/sharepoint-simple-event-logger/#comments</comments>
		<pubDate>Tue, 04 Jun 2013 03:31:05 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Administration]]></category>
		<category><![CDATA[Event Logging]]></category>
		<category><![CDATA[Share Point]]></category>
		<category><![CDATA[SharePoint 2010]]></category>

		<guid isPermaLink="false">http://dotnetfollower.com/wordpress/?p=1452</guid>
		<description><![CDATA[&#160;&#160;&#160;&#160;Errors, warnings and info messages in all my SharePoint applications are being logged to the Application Event Log. For that I use a simple class tritely named EventLogger and listed later in this post. As for the moment, a couple of words about the EventLogger are stated below. If necessary, the EventLogger registers a source [...]]]></description>
			<content:encoded><![CDATA[<p style='text-align:justify'>&nbsp;&nbsp;&nbsp;&nbsp;Errors, warnings and info messages in all my <b>SharePoint</b> applications are being logged to the <b>Application Event Log</b>. For that I use a simple class tritely named <b>EventLogger</b> and listed later in this post. As for the moment, a couple of words about the <b>EventLogger</b> are stated below.</p>
<p style='text-align:justify'>If necessary, the <b>EventLogger</b> registers a source in the <b>Application Event Log</b> once any its method is called for the first time (see the <b>static constructor</b>). The event logging uses the information stored in the <b>Eventlog registry key</b>. So, when dealing with the <b>Application Event Log</b>, we have to be ready to get exception about a lack of rights to read from or write to the <b>registry</b>. Because of that, the <b>EventLogger</b> initially tries adding a new source under the current user account and then, in case of failure, repeats the same under the <b>application pool account</b> (<b>SPSecurity.RunWithElevatedPrivileges</b>) that is supposed to have all suitable permissions.</p>
<p style='text-align:justify'>Due to the same reason, whenever a user different from the <b>application pool account</b> writes anything to the log, he will likely get an exception which is reporting that the current user doesn&#8217;t have write access. To guard users from that, we as administrators have to do some manual work, namely, to add the <b>CustomSD</b> value to the <b>[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application] registry key</b> how it&#8217;s described in the article <a href="http://dotnetfollower.com/wordpress/2012/04/sharepoint-cannot-open-log-for-source-you-may-not-have-write-access/" title="Cannot open log for source. You may not have write access">SharePoint: Cannot open log for source. You may not have write access</a>. If a <b>SharePoint</b> application supports <b>anonymous access</b>, use <b>WD</b> (all users) instead of <b>AU</b> (authenticated users). Also it&#8217;s very important to understand that the appropriate <b>CustomSD</b> <u>must be added on all machines of a <b>SharePoint</b> farm</u>. An alternative way is to wrap the writing to the log in <b>SPSecurity.RunWithElevatedPrivileges</b>. Remember, however, that the <b>SPSecurity.RunWithElevatedPrivileges</b> is quite resource-consuming and excessive for such frequent operation as event logging. So, use the <b>SPSecurity.RunWithElevatedPrivileges</b> as an extreme measure and only when the previous approach with <b>CustomSD</b> didn&#8217;t help for some reasons.</p>
<p style='text-align:justify'>Another feature of the <b>EventLogger</b> is that, as a backup plan, it writes to the <b>SharePoint Trace Log</b> through the <b><a href="http://msdn.microsoft.com/en-us/library/ff512738.aspx">Unified Logging Service</a></b> (see the <b>WriteToHiveLog</b> method). In other words, if the <b>EventLogger</b> doesn&#8217;t manage to write a message to the <b>Application Event Log</b>, it tries appending the message to the <b>ULS Log</b> stored in the file system and accessible, for example, through the <b><a href="http://ulsviewer.codeplex.com">ULS Viewer</a></b>.</p>
<p style='text-align:justify'>Logging an error or warning based on the passed exception, the <b>EventLogger</b> forms the final text, using the exception&#8217;s message along with the message of the inner exception (if any) and stack trace.</p>
<p style='text-align:justify'>Below is a combined example that demonstrates how to use the <b>EventLogger</b> to log errors, warnings and info.</p>
<pre class="brush: csharp; title: ;">
using dotNetFollower;
...

EventLogger.WriteInfo(&quot;How to use the EventLogger&quot;);

EventLogger.WriteError(&quot;Sorry, couldn't perform this operation!&quot;);
// OR
EventLogger.WriteWarning(&quot;Sorry, couldn't perform this operation!&quot;);

try
{
	// the next line throws an exception
	SPList spList = SPContext.Current.Web.Lists[&quot;Not existing list&quot;];
}
catch (Exception ex)
{
	EventLogger.WriteError(ex);
	// OR
	EventLogger.WriteWarning(ex);
}
</pre>
<p style='text-align:justify'>Below is depicted what those records look like in the <b>Windows Event Viewer</b>:<br />
<img src="http://dotnetfollower.com/wordpress/wordpress-content/uploads/2013/06/EventLoggerRecords.png" alt="EventLogger Records" title="EventLogger Records" width="478" height="453" class="aligncenter size-full wp-image-1453" />
</p>
<p style='text-align:justify'>Ok, it&#8217;s about time for the <b>EventLogger</b> listing:</p>
<pre class="brush: csharp; title: ;">
using System;
using System.Diagnostics;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace dotNetFollower
{
    public static class EventLogger
    {
        private const string SOURCE = &quot;dotNetFollower&quot;; // put here your own source name

        /// &lt;summary&gt;
        /// Writes an error message
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;errorText&quot;&gt;Error message&lt;/param&gt;
        public static void WriteError(string errorText)
        {
            WriteWithinTryCatch(errorText, EventLogEntryType.Error);
        }
        /// &lt;summary&gt;
        /// Writes an error message
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;ex&quot;&gt;Exception&lt;/param&gt;
        public static void WriteError(Exception ex)
        {
            WriteWithinTryCatch(GetExceptionFormatted(ex), EventLogEntryType.Error);
        }
        /// &lt;summary&gt;
        /// Writes a warning message
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;text&quot;&gt;Warning message&lt;/param&gt;
        public static void WriteWarning(string text)
        {
            WriteWithinTryCatch(string.Format(&quot;Warning: {0}&quot;, text), EventLogEntryType.Warning);
        }
        /// &lt;summary&gt;
        /// Writes a warning message
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;ex&quot;&gt;Exception&lt;/param&gt;
        public static void WriteWarning(Exception ex)
        {
            WriteWithinTryCatch(GetExceptionFormatted(ex), EventLogEntryType.Warning);
        }
        /// &lt;summary&gt;
        /// Writes an info message
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;text&quot;&gt;Info message&lt;/param&gt;
        public static void WriteInfo(string text)
        {
            WriteWithinTryCatch(string.Format(&quot;Information: {0}&quot;, text), EventLogEntryType.Information);
        }

        /// &lt;summary&gt;
        /// Creates the appropriate source in Event Logs, if necessary
        /// &lt;/summary&gt;
        public static void EnsureLogSourceExist()
        {
            if (!EventLog.SourceExists(SOURCE))
                EventLog.CreateEventSource(SOURCE, &quot;Application&quot;);
        }

        /// &lt;summary&gt;
        /// Returns an error message based on a passed exception. Includes an inner exception (if any) and stack trace
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;ex&quot;&gt;Exception&lt;/param&gt;
        /// &lt;returns&gt;Formed error message&lt;/returns&gt;
        public static string GetExceptionFormatted(Exception ex)
        {
            return string.Format(&quot;Error: {0} (Inner Exception: {1})\t\nDetails: {2}&quot;,
                ex.Message,
                ex.InnerException != null ? ex.InnerException.Message : string.Empty,
                ex.StackTrace);
        }

        static EventLogger()
        {
            bool error = false;

            Action action = delegate
                {
                    try
                    {
                        // register source in Event Logs
                        EnsureLogSourceExist();
                    }
                    catch
                    {
                        error = true;
                    }
                };

            // try under current user
            action();

            if(error)
                // try under application pool account
                SPSecurity.RunWithElevatedPrivileges(() =&gt; action());
        }

        private static void WriteWithinTryCatch(string message, EventLogEntryType type)
        {
            try
            {
                // To allow users (authenticated only or all of them) writing to Event Log,
                // follow the steps described in the article
                // http://dotnetfollower.com/wordpress/2012/04/sharepoint-cannot-open-log-for-source-you-may-not-have-write-access/

                // If it doesn't help for some reason, uncomment the line with SPSecurity.RunWithElevatedPrivileges and
                // comment the other one. Note, however, that the use of SPSecurity.RunWithElevatedPrivileges is
                // resource-consuming and looks excessive for such frequent operation as event logging.

                //SPSecurity.RunWithElevatedPrivileges(() =&gt; EventLog.WriteEntry(SOURCE, message, type));
                EventLog.WriteEntry(SOURCE, message, type);
            }
            catch
            {
                WriteToHiveLog(message, type);
            }
        }

        private static void WriteToHiveLog(string message, EventLogEntryType type)
        {
            EventSeverity eventSeverity = type == EventLogEntryType.Error ? EventSeverity.Error :
                (type == EventLogEntryType.Warning ? EventSeverity.Warning : EventSeverity.Information);

            var category = new SPDiagnosticsCategory(SOURCE, TraceSeverity.Unexpected, eventSeverity);

            SPDiagnosticsService.Local.WriteTrace(0, category, TraceSeverity.Unexpected, message, null);
        }
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://dotnetfollower.com/wordpress/2013/06/sharepoint-simple-event-logger/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SharePoint: What is a People Picker? Part 1 &#8211; PeopleEditor</title>
		<link>http://dotnetfollower.com/wordpress/2013/04/sharepoint-what-is-people-picker-part-1-peopleeditor/</link>
		<comments>http://dotnetfollower.com/wordpress/2013/04/sharepoint-what-is-people-picker-part-1-peopleeditor/#comments</comments>
		<pubDate>Tue, 30 Apr 2013 15:51:09 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[People Picker]]></category>
		<category><![CDATA[Share Point]]></category>
		<category><![CDATA[SharePoint 2010]]></category>

		<guid isPermaLink="false">http://dotnetfollower.com/wordpress/?p=1345</guid>
		<description><![CDATA[In fact, there is no control with the name PeoplePicker in SharePoint, it&#8217;s a common name of the group of elements: a few controls, one aspx-page and a couple of JavaScript files. These elements are closely connected with each other, use each other and all together allow searching and picking out users and groups available [...]]]></description>
			<content:encoded><![CDATA[<p style='text-align:justify'>In fact, there is no control with the name <b>PeoplePicker</b> in <b>SharePoint</b>, it&#8217;s a common name of the group of elements: a few controls, one <b>aspx</b>-page and a couple of <b>JavaScript</b> files. These elements are closely connected with each other, use each other and all together allow searching and picking out users and groups available in <b>SharePoint</b> and/or <b>Active Directory</b>.</p>
<p style='text-align:justify'>Let&#8217;s take a closer look at each element of the <b>People Picker</b>.</p>
<p><a name="peopleEditor" id="peopleEditor"></a><br />
<h4>PeopleEditor</h4>
<p style='text-align:justify'><b><a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webcontrols.peopleeditor_members.aspx">PeopleEditor</a></b> is a visual control providing an entry point to deal with <b>People Picker</b>. So, to leverage the <b>People Picker</b> functionality we need just to add the <b>PeopleEditor</b> control to our <b>aspx</b>-page as follows:</p>
<pre class="brush: xml; title: ;">
&lt;%@ Register TagPrefix=&quot;wssawc&quot; Namespace=&quot;Microsoft.SharePoint.WebControls&quot;
 Assembly=&quot;Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c&quot; %&gt;
...
&lt;wssawc:PeopleEditor id=&quot;peoplePicker&quot; runat=&quot;server&quot; SelectionSet=&quot;User,SecGroup,DL&quot;
  MultiSelect=&quot;true&quot; Height=&quot;20px&quot; Width=&quot;200px&quot; /&gt;
...
 </pre>
<p style='text-align:justify'>Below is a class diagram demonstrating the ancestors of the <b>PeopleEditor</b> and supported interfaces:</p>
<p><img src="http://dotnetfollower.com/wordpress/wordpress-content/uploads/2013/04/PeoplePickerClassDiagram.png" alt="PeoplePicker Class Diagram" title="PeoplePicker Class Diagram" width="429" height="739" class="aligncenter size-full wp-image-1412" /></p>
<p style='text-align:justify'>The <b>PeopleEditor</b> usually consists of a composite Edit Box and two buttons: <b>Check Names</b> and <b>Browse</b>.</p>
<p><img src="http://dotnetfollower.com/wordpress/wordpress-content/uploads/2013/04/PeopleEditor.png" alt="PeopleEditor Parts" title="PeopleEditor Parts" width="502" height="259" class="aligncenter size-full wp-image-1352" /></p>
<p style='text-align:justify'>The <b>Hml</b> markup generated by the <b>PeopleEditor</b> is listed below. The listing is a relatively large bunch of the <b>Html</b>-tags but helps figure out what <b>DOM</b> elements are involved in and where in the markup they are located. The <b>Html</b> comments, indents and formatting are added for clarity.</p>
<div id="PeopleEditorHtmlMarkup">
<h3><a href="#">Click to open the PeopleEditor&#8217;s Html markup</a></h3>
<div>
<pre class="brush: xml; title: ;">
&lt;span id=&quot;ctl00_PlaceHolderMain_ctl00_ctl01_userPicker&quot; editoroldvalue=&quot;&quot;
  removetext=&quot;Remove&quot; value=&quot;&quot; nomatchestext=&quot;&amp;lt;No Matching Names&amp;gt;&quot;
  moreitemstext=&quot;More Names...&quot; prefercontenteditablediv=&quot;true&quot;
  showdatavalidationerrorborder=&quot;false&quot; eeaftercallbackclientscript=&quot;&quot;
  invalidate=&quot;false&quot; allowtypein=&quot;true&quot; showentitydisplaytextintextbox=&quot;0&quot;&gt;

 &lt;!-- [Begin] Hidden inputs of the composite Edit Box --&gt;
 &lt;input type=&quot;hidden&quot; value=&quot;&quot;
  name=&quot;ctl00$PlaceHolderMain$ctl00$ctl01$userPicker$hiddenSpanData&quot;
  id=&quot;ctl00_PlaceHolderMain_ctl00_ctl01_userPicker_hiddenSpanData&quot;&gt;
 &lt;input type=&quot;hidden&quot; value=&quot;&amp;lt;Entities /&amp;gt;&quot;
  name=&quot;ctl00$PlaceHolderMain$ctl00$ctl01$userPicker$OriginalEntities&quot;
  id=&quot;ctl00_PlaceHolderMain_ctl00_ctl01_userPicker_OriginalEntities&quot;&gt;
 &lt;input type=&quot;hidden&quot;
  name=&quot;ctl00$PlaceHolderMain$ctl00$ctl01$userPicker$HiddenEntityKey&quot;
  id=&quot;ctl00_PlaceHolderMain_ctl00_ctl01_userPicker_HiddenEntityKey&quot;&gt;
 &lt;input type=&quot;hidden&quot;
  name=&quot;ctl00$PlaceHolderMain$ctl00$ctl01$userPicker$HiddenEntityDisplayText&quot;
  id=&quot;ctl00_PlaceHolderMain_ctl00_ctl01_userPicker_HiddenEntityDisplayText&quot;&gt;
 &lt;!-- [End] Hidden inputs of the composite Edit Box --&gt;

 &lt;table id=&quot;ctl00_PlaceHolderMain_ctl00_ctl01_userPicker_OuterTable&quot; class=&quot;ms-usereditor&quot; cellspacing=&quot;0&quot; cellpadding=&quot;0&quot; border=&quot;0&quot; style=&quot;border-collapse:collapse;&quot;&gt;
  &lt;tr&gt;
   &lt;td valign=&quot;top&quot;&gt;
    &lt;table cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; border=&quot;0&quot; style=&quot;width:100%;table-layout:fixed;&quot;&gt;
     &lt;tr&gt;
      &lt;td id=&quot;ctl00_PlaceHolderMain_ctl00_ctl01_userPicker_containerCell&quot;&gt;

 &lt;!-- [Begin] Visible up level div of the composite Edit Box --&gt;
 &lt;div id=&quot;ctl00_PlaceHolderMain_ctl00_ctl01_userPicker_upLevelDiv&quot; tabindex=&quot;0&quot;
   onfocus=&quot;StoreOldValue('ctl00_PlaceHolderMain_ctl00_ctl01_userPicker');
            saveOldEntities('ctl00_PlaceHolderMain_ctl00_ctl01_userPicker');&quot;
   onclick=&quot;onClickRw(true, true,event,'ctl00_PlaceHolderMain_ctl00_ctl01_userPicker');&quot;
   onchange=&quot;updateControlValue('ctl00_PlaceHolderMain_ctl00_ctl01_userPicker');&quot;
   onpaste=&quot;dopaste('ctl00_PlaceHolderMain_ctl00_ctl01_userPicker',event);&quot;
   autopostback=&quot;0&quot; rows=&quot;3&quot;
   ondragstart=&quot;canEvt(event);&quot;
   onkeyup=&quot;return onKeyUpRw('ctl00_PlaceHolderMain_ctl00_ctl01_userPicker');&quot;
   oncopy=&quot;docopy('ctl00_PlaceHolderMain_ctl00_ctl01_userPicker',event);&quot;
   onblur=&quot;
    if(typeof(ExternalCustomControlCallback)=='function'){
     if(ShouldCallCustomCallBack('ctl00_PlaceHolderMain_ctl00_ctl01_userPicker',event)){
      if(!ValidatePickerControl('ctl00_PlaceHolderMain_ctl00_ctl01_userPicker')){
        ShowValidationError();
        return false;
      }
      else
        ExternalCustomControlCallback('ctl00_PlaceHolderMain_ctl00_ctl01_userPicker');
     }
    }&quot;
   title=&quot;People Picker&quot;
   onkeydown=&quot;return onKeyDownRw('ctl00_PlaceHolderMain_ctl00_ctl01_userPicker', 3, true, event);&quot;
   aria-multiline=&quot;true&quot; contenteditable=&quot;true&quot; aria-haspopup=&quot;true&quot; class=&quot;ms-inputuserfield&quot;
   style=&quot;word-wrap: break-word; overflow-x: hidden; background-color: window; color: windowtext; overflow-y: auto; height: 48px;&quot;
   prefercontenteditablediv=&quot;true&quot; name=&quot;upLevelDiv&quot; role=&quot;textbox&quot;&gt;
 &lt;/div&gt;
 &lt;!-- [End] Visible up level div of the composite Edit Box --&gt;

 &lt;!-- [Begin] Usually invisible down level textarea of the composite Edit Box --&gt;
 &lt;textarea rows=&quot;3&quot; cols=&quot;20&quot; style=&quot;width:100%;display: none;position: absolute; &quot;
  name=&quot;ctl00$PlaceHolderMain$ctl00$ctl01$userPicker$downlevelTextBox&quot;
  id=&quot;ctl00_PlaceHolderMain_ctl00_ctl01_userPicker_downlevelTextBox&quot;
  class=&quot;ms-inputuserfield&quot; autopostback=&quot;0&quot;
  onkeyup=&quot;return onKeyUpRw('ctl00_PlaceHolderMain_ctl00_ctl01_userPicker');&quot;
  title=&quot;People Picker&quot;
  onfocus=&quot;StoreOldValue('ctl00_PlaceHolderMain_ctl00_ctl01_userPicker');
           saveOldEntities('ctl00_PlaceHolderMain_ctl00_ctl01_userPicker');&quot;
  onblur=&quot;
   if(typeof(ExternalCustomControlCallback)=='function'){
    if(ShouldCallCustomCallBack('ctl00_PlaceHolderMain_ctl00_ctl01_userPicker',event)){
     if(!ValidatePickerControl('ctl00_PlaceHolderMain_ctl00_ctl01_userPicker')){
       ShowValidationError();
       return false;
     }
     else
       ExternalCustomControlCallback('ctl00_PlaceHolderMain_ctl00_ctl01_userPicker');
    }
   }&quot;
  onkeydown=&quot;return onKeyDownRw('ctl00_PlaceHolderMain_ctl00_ctl01_userPicker', 3, true, event);&quot;
  renderascontenteditablediv=&quot;true&quot;
  onchange=&quot;updateControlValue('ctl00_PlaceHolderMain_ctl00_ctl01_userPicker');&quot;&gt;
 &lt;/textarea&gt;
 &lt;!-- [End] Usually invisible down level textarea of the composite Edit Box --&gt;

      &lt;/td&gt;
     &lt;/tr&gt;
    &lt;/table&gt;
   &lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
   &lt;td&gt;
    &lt;span id=&quot;ctl00_PlaceHolderMain_ctl00_ctl01_userPicker_errorLabel&quot; class=&quot;ms-error&quot;&gt;&lt;/span&gt;
   &lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr style=&quot;padding-top:2;&quot;&gt;
   &lt;td&gt;
    &lt;table cellspacing=&quot;0&quot; cellpadding=&quot;0&quot; border=&quot;0&quot; style=&quot;width:100%;border-collapse:collapse;&quot;&gt;
     &lt;tr&gt;
      &lt;td valign=&quot;top&quot; style=&quot;width:88%;&quot;&gt;
       &lt;span style=&quot;font-size:8pt;&quot;&gt;&lt;/span&gt;
      &lt;/td&gt;
      &lt;td valign=&quot;top&quot; nowrap=&quot;true&quot; style=&quot;padding-left:5px;padding-right:5px;&quot;&gt;

 &lt;!-- [Begin] Check Names Button --&gt;
 &lt;a id=&quot;ctl00_PlaceHolderMain_ctl00_ctl01_userPicker_checkNames&quot;
  title=&quot;Check Names&quot;
  href=&quot;javascript:&quot;
  onclick=&quot;
    if(!ValidatePickerControl('ctl00_PlaceHolderMain_ctl00_ctl01_userPicker')){
      ShowValidationError();
      return false;
    }
    var arg=getUplevel('ctl00_PlaceHolderMain_ctl00_ctl01_userPicker');
    var ctx='ctl00_PlaceHolderMain_ctl00_ctl01_userPicker';
    EntityEditorSetWaitCursor(ctx);
    WebForm_DoCallback('ctl00$PlaceHolderMain$ctl00$ctl01$userPicker',arg,
           EntityEditorHandleCheckNameResult,
           ctx,EntityEditorHandleCheckNameError,true);
    return false;&quot;&gt;
  &lt;img title=&quot;Check Names&quot; src=&quot;/_layouts/images/checknames.png&quot; alt=&quot;Check Names&quot; style=&quot;border-width:0px;&quot;&gt;
 &lt;/a&gt;&amp;nbsp;
 &lt;!-- [End] Check Names Button --&gt;

 &lt;!-- [Begin] Browse Button --&gt;
 &lt;a id=&quot;ctl00_PlaceHolderMain_ctl00_ctl01_userPicker_browse&quot;
  title=&quot;Browse&quot; href=&quot;javascript:&quot;
  onclick=&quot;__Dialog__ctl00_PlaceHolderMain_ctl00_ctl01_userPicker();
          return false;&quot;&gt;
  &lt;img title=&quot;Browse&quot; src=&quot;/_layouts/images/addressbook.gif&quot; alt=&quot;Browse&quot; style=&quot;border-width:0px;&quot;&gt;
 &lt;/a&gt;
 &lt;!-- [End] Browse Button --&gt;

      &lt;/td&gt;
     &lt;/tr&gt;
    &lt;/table&gt;
   &lt;/td&gt;
  &lt;/tr&gt;
 &lt;/table&gt;
&lt;/span&gt;
</pre>
</div>
</div>
<p><script>
        $(function () {
            $("#PeopleEditorHtmlMarkup").accordion({
                collapsible: true,
                autoHeight: false,
                active: 2
            });            
        });
</script></p>
<p style='text-align:justify'><i>*Note that this markup corresponds to the empty <b>PeopleEditor</b> when nothing is typed in.</i></p>
<p style='text-align:justify'>The <b>PeopleEditor</b> (like other classes derived from <b>EntityEditor</b>) uses functions defined in the <b>entityeditor.js</b> that located at <b>14\TEMPLATE\LAYOUTS</b>.</p>
<p><a name="compositeEditBox" id="compositeEditBox"></a><br />
<h5 style="color: rgb(0, 136, 0);">Composite Edit Box</h5>
<p style='text-align:justify'>The composite Edit Box performs the following two functions:</p>
<ul>
<li>displays the already selected users and groups (I call them &#8220;resolved accounts&#8221;);</li>
<li>allows typing names (or part of them) of users and groups (I call them &#8220;unresolved accounts&#8221;).</li>
</ul>
<p style='text-align:justify'>All names (resolved and unresolved) should be delimited by the so-called <b>Entity Separator</b>. Usually it&#8217;s a semicolon (&#8220;<b>;</b>&#8220;). So, typing two or more names we need to separate them from each other to let the validation know what entries should be resolved.</p>
<p style='text-align:justify'>Being aggregative, the Edit Box usually comprises a few <b>hidden inputs</b>, one invisible <b>textarea</b> and one visible <b>div</b> element (see the <b>PeopleEditor</b>&#8216;s <b>Html</b> markup above). The <b>div</b> element, so-called <b>upLevelDiv</b>, displays everything we see in the Edit Box and allows typing by handling key pressing. And, of course, there are a lot of <b>JavaScript</b> defined in the <b>entityeditor.js</b> and intended to apply all that rich functionality to the simple <b>div</b>. Besides the <b>upLevelDiv</b> another quite important element of the Edit Box is one of the <b>hidden inputs</b> namely the so-called <b>hiddenSpanData</b>. The <b>value</b> attribute of the <b>hiddenSpanData</b> at any moment contains the copy of the content (<b>innerHtml</b>) of the <b>upLevelDiv</b>. Whenever the content of the <b>upLevelDiv</b> is changed those changes are reflected in the <b>hiddenSpanData</b> by calling the <b>copyUplevelToHidden</b> function defined in the <b>entityeditor.js</b>. As you know, the content of <b>div</b> elements is never sent when submitting data to the server. That&#8217;s why we need the <b>hiddenSpanData</b>, which is an <b>input</b> (though invisible) and, therefore, takes part in <b>form submitting</b>. So, everything we typed in or selected in the <b>upLevelDiv</b> will be sent to the server by the <b>hiddenSpanData</b>. Also note that the <b>hiddenSpanData</b> keeps the copy of the <b>upLevelDiv</b>&#8216;s inner <b>Html</b> as is, NO transformation is applied. That means that the very <b>Html</b> used to visualize the &#8220;resolved accounts&#8221; in the <b>upLevelDiv</b> is going to be posted to the server. That requires the server side to parse the <b>Html</b> (usually bunch of <b>SPAN</b> and <b>DIV</b> tags) to extract the entries. I have no idea why the <b>Microsoft</b> uses such a complex and excess format to pass the entries, but that&#8217;s a fact. Later in the article we&#8217;ll see<a href="#htmlDataSentToServer"> an example of such <b>Html</b>-formatted entries</a> sent to the server.</p>
<p style='text-align:justify'>The usually invisible so-called <b>downlevelTextBox textarea</b> is used when browser doesn&#8217;t support <b>content editable div</b>. So, in case of legacy browser the <b>downlevelTextBox</b> gets visible while the <b>upLevelDiv</b> disappears. All changes of the text inside the <b>downlevelTextBox</b> are being reflected in the <b>hiddenSpanData</b> as well. Note that since <b>textarea</b> doesn&#8217;t support <b>Html</b> formatting inside, the typed entries are being sent to the server as a plain text.</p>
<p style='text-align:justify'>The <b>hidden input</b> so-called <b>OriginalEntities</b> is aimed to keep the users and groups (&#8220;resolved accounts&#8221;) that were selected formerly. For example, if we are opening a list item to edit and the page contains the <b>PeopleEditor</b> bound to a field of the &#8220;<b>Person or Group</b>&#8221; type, the current value of the field will be persisted into the <b>OriginalEntities</b>. When data is submitted back to the server the original entities allow tracking whether the set of users and groups has been changed. Unlike the <b>hiddenSpanData</b>, the <b>OriginalEntities input</b> keeps the &#8220;resolved accounts&#8221; as a pure <b>Xml</b> string. The following two methods are used on the server side to serialize entities to and deserialize from the <b>Xml</b> stored in the <b>OriginalEntities</b>: <b>PickerEntity.ConvertEntitiesToXmlData</b> and <b>PickerEntity.ParseEntitiesFromXml</b> respectively. Below in the article we&#8217;ll see <a href="#xmlClientCallbackResult">an example of such <b>Xml</b>-formatted entries</a> as the same format is used to return the result of the validation process.</p>
<p style='text-align:justify'>Two more <b>hidden inputs</b>, <b>HiddenEntityKey</b> and <b>HiddenEntityDisplayText</b>, make sense only if the <b>MultiSelect</b> property of the <b>PeopleEditor</b> is set to <b>false</b> (that&#8217;s true for other controls derived from the <b>EntityEditor</b> unless that behavior is overridden somehow). The <b>inputs</b> keep respectively the <b>Key</b> (ID) and <b>DisplayText</b> (readable alias) of the first and only resolved entity. Both look quite useless for the <b>PeopleEditor</b>, but you can learn the way they are employed for picking out a <b>BDC entity</b> through the <b><a href="http://dotnetfollower.com/wordpress/2012/02/sharepoint-enhanced-itempicker/" title="Enhanced ItemPicker">Enhanced ItemPicker</a></b>.</p>
<p><a name="checkNamesButton" id="checkNamesButton"></a><br />
<h5 style="color: rgb(0, 136, 0);">Check Names button</h5>
<p style='text-align:justify'>The <b>Check Names</b> button validates/resolves the typed names. If the typed names match real accounts, such accounts are displayed in the Edit Box as the resolved ones. If no matches are found or some typed name matches multiple accounts, the name becomes clickable, and clicking on it displays the drop-down menu that looks like the one depicted below:</p>
<p><img src="http://dotnetfollower.com/wordpress/wordpress-content/uploads/2013/04/MultipleAccountsMatched.png" alt="Multiple Accounts Matched" title="Multiple Accounts Matched" width="572" height="150" class="aligncenter size-full wp-image-1387" /></p>
<p style='text-align:justify'>The menu allows choosing an entity that, in user&#8217;s opinion, best conforms to the typed name. Clicking <b>Remove</b> in the menu deletes the typed name. While <b>More Names&#8230;</b> does the same what the <b>Browse</b> button does (<a href="#browseButton">described below</a>).</p>
<p style='text-align:justify'>The <b>PeopleEditor</b> implements the <b>ICallbackEventHandler</b> interface and therefore supports <b><a href="http://msdn.microsoft.com/en-us/library/ms178208.aspx">Client Callbacks</a></b>. Clicking <b>Check Names</b> button ends up with sending an async request to the page that hosts the <b>PeopleEditor</b>. When on the server side the page and all its controls have been re-created the instance of the <b>PeopleEditor</b> handles the request by parsing input, validating/resolving entries and sending the result back to the browser, then on the client side the Edit Box&#8217;s content is updated. What is the input sent to the server? It&#8217;s an inner <b>Html</b> of the <b>upLevelDiv</b> (or text of the <b>downlevelTextBox textarea</b> in case of a legacy browser). The <b>GetInnerHTMLOrTextOfUpLevelDiv</b> function from the <b>entityeditor.js</b> is responsible for getting the current input. So, in case of the <b>Client Callback</b> the <b>Html</b>-like data is taken directly from the <b>upLevelDiv</b>/<b>downlevelTextBox</b>, while in case of the usual <b>Form Submit</b> the data of the same format is posted by the <b>hiddenSpanData</b>.</p>
<p style='text-align:justify'>Ok, let&#8217;s take a look at possible inputs (<b>__CALLBACKPARAM</b> in the request) that come into the <b>ICallbackEventHandler.RaiseCallbackEvent</b> method of the <b>PeopleEditor</b>. For example, in case the &#8220;<b>jira; student</b>&#8221; is typed in the Edit Box, the input will be the same &#8211; &#8220;<b>jira; student</b>&#8220;. If, however, the Edit Box contains one or more of the &#8220;resolved accounts&#8221;, the input becomes much trickier. For example, the string &#8220;<b><u>JIRA</u>; jir</b>&#8221; transforms to the following (indents and formatting are added for clarity):</p>
<p><a name="htmlDataSentToServer" id="htmlDataSentToServer"></a></p>
<pre class="brush: xml; title: ;">
&amp;nbsp;
&lt;SPAN id=spanHQ\jira class=ms-entity-resolved
   onmouseover=this.contentEditable=false;
   title=HQ\jira tabIndex=-1
   onmouseout=this.contentEditable=true;
   contentEditable=true isContentType=&quot;true&quot;&gt;

  &lt;DIV id=divEntityData description=&quot;HQ\jira&quot;
     isresolved=&quot;True&quot; displaytext=&quot;JIRA&quot; key=&quot;HQ\jira&quot; style=&quot;DISPLAY: none&quot;&gt;

    &lt;DIV data='&lt;ArrayOfDictionaryEntry xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot;&gt;
                      &lt;DictionaryEntry&gt;
                        &lt;Key xsi:type=&quot;xsd:string&quot;&gt;AccountName&lt;/Key&gt;
                        &lt;Value xsi:type=&quot;xsd:string&quot;&gt;HQ\jira&lt;/Value&gt;
                      &lt;/DictionaryEntry&gt;
                      &lt;DictionaryEntry&gt;
                        &lt;Key xsi:type=&quot;xsd:string&quot;&gt;Email&lt;/Key&gt;
                        &lt;Value xsi:type=&quot;xsd:string&quot;&gt;jira@someservername.com&lt;/Value&gt;
                      &lt;/DictionaryEntry&gt;
                      &lt;DictionaryEntry&gt;
                        &lt;Key xsi:type=&quot;xsd:string&quot;&gt;PrincipalType&lt;/Key&gt;
                        &lt;Value xsi:type=&quot;xsd:string&quot;&gt;User&lt;/Value&gt;
                      &lt;/DictionaryEntry&gt;&lt;/ArrayOfDictionaryEntry&gt;'&gt;
    &lt;/DIV&gt;

  &lt;/DIV&gt;
  &lt;SPAN id=content tabIndex=-1 contentEditable=true
     oncontextmenu='onContextMenuSpnRw(event,&quot;ctl00_PlaceHolderMain_ctl00_ctl01_userPicker&quot;);'
     onmousedown=onMouseDownRw(event);&gt;
		JIRA
  &lt;/SPAN&gt;

&lt;/SPAN&gt;; jir&amp;nbsp;;
</pre>
<p style='text-align:justify'>So, this listing demonstrates three things at once: the inner <b>html</b> of the <b>upLevelDiv</b>, the data stored in the <b>hiddenSpanData</b> and the data sent during the <b>Client Callback</b>. The <b>EntityEditor.ParseSpanData</b> is called on the server side to parse the input like that, while the <b>ConvertEntityToSpan</b> function from the <b>entityeditor.js</b> is used on the client side to turn the <b>Client Callback</b> result into such <b>Html</b>-like string.</p>
<p style='text-align:justify'>To get the picture of how the <b>PeopleEditor</b> processes the input, see the code along with my comments that are listed below. The code is borrowed from the <b>EntityEditor</b> class (the ancestor of the <b>PeopleEditor</b>).</p>
<pre class="brush: csharp; title: ;">
// eventArgument is an input similar to the ones shown above
private string InvokeCallbackEvent(string eventArgument)
{
	// ensure that all child controls of the PeopleEditor are re-created
    this.EnsureChildControls();
	// remove all &quot;&amp;nbsp;&quot;, i.e. Html spaces
    string spans = StrEatUpNbsp(eventArgument);
	// parse input, extract entries, convert them to instances of PickerEntity
    // and then add to the Entities collection
    this.ParseSpanData(spans);
	// go through the collection and try resolving the entities
    this.Validate();
	// serialize the entities into the output xml string
    return this.GenerateCallbackData(this.Entities, false);
}
</pre>
<p style='text-align:justify'>During the validation process itself the following methods are used ultimately: <b>SPUtility.ResolvePrincipal</b> or <b>SPUtility.ResolveWindowsPrincipal</b>,  or, in case of the <b>claims-based authentication</b>, <b>SPClaimProviderOperations.Resolve</b>. If a name can&#8217;t be resolved, the process will make an attempt to find suitable accounts by calling such methods as <b>SPUtility.SearchWindowsPrincipals</b> or <b>SPUtility.SearchPrincipals</b>. As regards the <b>claims-based authentication</b>, the <b>SPClaimProviderOperations.Resolve</b> itself is able to return suitable accounts if the only one couldn&#8217;t be found.</p>
<p style='text-align:justify'>Ok, let&#8217;s take a look at what kind of result is returned to the browser in case the &#8220;<b>jira</b>&#8221; entity has been resolved while the &#8220;<b>jir</b>&#8221; has multiple matches:</p>
<p><a name="xmlClientCallbackResult" id="xmlClientCallbackResult"></a></p>
<div id="CheckNamesClientCallbackXmlResult">
<h3><a href="#">Click to open the Client Callback&#8217;s XML result</a></h3>
<div>
<pre class="brush: xml; title: ;">
&lt;Entities Append=&quot;False&quot; DoEncodeErrorMessage=&quot;True&quot; Separator=&quot;;&quot; MaxHeight=&quot;3&quot;
    Error=&quot;No exact match was found. Click the item(s) that did not resolve for more options.&quot;&gt;

  &lt;Entity Key=&quot;HQ\jira&quot; DisplayText=&quot;JIRA&quot; IsResolved=&quot;True&quot; Description=&quot;HQ\jira&quot;&gt;
    &lt;ExtraData&gt;
      &lt;ArrayOfDictionaryEntry xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot;&gt;
        &lt;DictionaryEntry&gt;
          &lt;Key xsi:type=&quot;xsd:string&quot;&gt;AccountName&lt;/Key&gt;
          &lt;Value xsi:type=&quot;xsd:string&quot;&gt;HQ\jira&lt;/Value&gt;
        &lt;/DictionaryEntry&gt;
        &lt;DictionaryEntry&gt;
          &lt;Key xsi:type=&quot;xsd:string&quot;&gt;Email&lt;/Key&gt;
          &lt;Value xsi:type=&quot;xsd:string&quot;&gt;jira@someservername.com&lt;/Value&gt;
        &lt;/DictionaryEntry&gt;
        &lt;DictionaryEntry&gt;
          &lt;Key xsi:type=&quot;xsd:string&quot;&gt;PrincipalType&lt;/Key&gt;
          &lt;Value xsi:type=&quot;xsd:string&quot;&gt;User&lt;/Value&gt;
        &lt;/DictionaryEntry&gt;
      &lt;/ArrayOfDictionaryEntry&gt;
    &lt;/ExtraData&gt;
    &lt;MultipleMatches /&gt;
  &lt;/Entity&gt;

  &lt;Entity Key=&quot;jir&quot; DisplayText=&quot;jir&quot; IsResolved=&quot;False&quot; Description=&quot;Multiple entries matched, please click to resolve.&quot;&gt;
    &lt;MultipleMatches&gt;
      &lt;Entity Key=&quot;HQ\jira-users&quot; DisplayText=&quot;HQ\jira-users&quot; IsResolved=&quot;True&quot; Description=&quot;HQ\jira-users&quot;&gt;
        &lt;ExtraData&gt;
          &lt;ArrayOfDictionaryEntry xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot;&gt;
            &lt;DictionaryEntry&gt;
              &lt;Key xsi:type=&quot;xsd:string&quot;&gt;AccountName&lt;/Key&gt;
              &lt;Value xsi:type=&quot;xsd:string&quot;&gt;HQ\jira-users&lt;/Value&gt;
            &lt;/DictionaryEntry&gt;
            &lt;DictionaryEntry&gt;
              &lt;Key xsi:type=&quot;xsd:string&quot;&gt;PrincipalType&lt;/Key&gt;
              &lt;Value xsi:type=&quot;xsd:string&quot;&gt;SecurityGroup&lt;/Value&gt;
            &lt;/DictionaryEntry&gt;
          &lt;/ArrayOfDictionaryEntry&gt;
        &lt;/ExtraData&gt;
      &lt;/Entity&gt;
      &lt;Entity Key=&quot;HQ\locadmin&quot; DisplayText=&quot;Jira Admin Local&quot; IsResolved=&quot;True&quot; Description=&quot;HQ\locadmin&quot;&gt;
        &lt;ExtraData&gt;
          &lt;ArrayOfDictionaryEntry xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot;&gt;
            &lt;DictionaryEntry&gt;
              &lt;Key xsi:type=&quot;xsd:string&quot;&gt;AccountName&lt;/Key&gt;
              &lt;Value xsi:type=&quot;xsd:string&quot;&gt;HQ\locadmin&lt;/Value&gt;
            &lt;/DictionaryEntry&gt;
            &lt;DictionaryEntry&gt;
              &lt;Key xsi:type=&quot;xsd:string&quot;&gt;PrincipalType&lt;/Key&gt;
              &lt;Value xsi:type=&quot;xsd:string&quot;&gt;User&lt;/Value&gt;
            &lt;/DictionaryEntry&gt;
          &lt;/ArrayOfDictionaryEntry&gt;
        &lt;/ExtraData&gt;
      &lt;/Entity&gt;
      &lt;Entity Key=&quot;HQ\jira&quot; DisplayText=&quot;JIRA&quot; IsResolved=&quot;True&quot; Description=&quot;HQ\jira&quot;&gt;
        &lt;ExtraData&gt;
          &lt;ArrayOfDictionaryEntry xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot;&gt;
            &lt;DictionaryEntry&gt;
              &lt;Key xsi:type=&quot;xsd:string&quot;&gt;AccountName&lt;/Key&gt;
              &lt;Value xsi:type=&quot;xsd:string&quot;&gt;HQ\jira&lt;/Value&gt;
            &lt;/DictionaryEntry&gt;
            &lt;DictionaryEntry&gt;
              &lt;Key xsi:type=&quot;xsd:string&quot;&gt;Email&lt;/Key&gt;
              &lt;Value xsi:type=&quot;xsd:string&quot;&gt;jira@someservername.com&lt;/Value&gt;
            &lt;/DictionaryEntry&gt;
            &lt;DictionaryEntry&gt;
              &lt;Key xsi:type=&quot;xsd:string&quot;&gt;PrincipalType&lt;/Key&gt;
              &lt;Value xsi:type=&quot;xsd:string&quot;&gt;User&lt;/Value&gt;
            &lt;/DictionaryEntry&gt;
          &lt;/ArrayOfDictionaryEntry&gt;
        &lt;/ExtraData&gt;
      &lt;/Entity&gt;
    &lt;/MultipleMatches&gt;
  &lt;/Entity&gt;

&lt;/Entities&gt;
</pre>
</div>
</div>
<p><script>
        $(function () {
            $("#CheckNamesClientCallbackXmlResult").accordion({
                collapsible: true,
                autoHeight: false,
                active: 2
            });            
        });
</script></p>
<p style='text-align:justify'>So, the server response is a <b>Xml</b>-based string where each resolved or unresolved name is presented by an <b>Entity</b>-node. The <b>IsResolved</b> attribute indicates if the name is resolved, i.e. whether the name matches a real user or group. Each <b>Entity</b> may contain the nested ones wrapped into <b>MultipleMatches</b>-tag in case the name matches multiple accounts. Those nested <b>Entities</b> will be enumerated in the drop-down menu when clicking the unresolved name.</p>
<p style='text-align:justify'>Note that the <b>OriginalEntities</b> input contains the data in the same format.</p>
<p><a name="browseButton" id="browseButton"></a><br />
<h5 style="color: rgb(0, 136, 0);">Browse button</h5>
<p style='text-align:justify'>The <b>Browse</b> button opens the <b>search dialog</b> namely the dialog containing the <b>picker.aspx</b> page. Note that the static method <b>PickerDialog.PickerActivateScript</b> is called to get the appropriate <b>JavaScript</b> opening/activating the <b>search dialog</b>. The <b>PickerDialog.PickerActivateScript</b>, in turn, uses another static method <b>PickerDialog.GetPickerDialogPage</b> that constructs the url to the <b>picker.aspx</b> including all needed query string parameters. The <b>PickerDialog</b> is an ancestor of the <b>PeoplePickerDialog</b> class that along with the <b>picker.aspx</b> will be described in another article.</p>
]]></content:encoded>
			<wfw:commentRss>http://dotnetfollower.com/wordpress/2013/04/sharepoint-what-is-people-picker-part-1-peopleeditor/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Knockout.js: HtmlNoScript binding</title>
		<link>http://dotnetfollower.com/wordpress/2013/02/knockout-js-htmlnoscript-binding/</link>
		<comments>http://dotnetfollower.com/wordpress/2013/02/knockout-js-htmlnoscript-binding/#comments</comments>
		<pubDate>Thu, 14 Feb 2013 16:19:07 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Knockout.js]]></category>
		<category><![CDATA[Regex]]></category>

		<guid isPermaLink="false">http://dotnetfollower.com/wordpress/?p=1334</guid>
		<description><![CDATA[&#160;&#160;&#160;&#160;The Knockout.js is one of the most popular and fast-developing libraries that bring the MVVM pattern into the world of JavaScript development. Knockout.js allows to declaratively bind UI (Document Object Model elements) to an underlying data model. One of the built-in bindings is the html-binding allowing to display an arbitrary Html provided by an associated [...]]]></description>
			<content:encoded><![CDATA[<p style='text-align:justify'>&nbsp;&nbsp;&nbsp;&nbsp;The <b><a href="http://knockoutjs.com/">Knockout.js</a></b> is one of the most popular and fast-developing libraries that bring the <b>MVVM</b> pattern into the world of <b>JavaScript</b> development. <b>Knockout.js</b> allows to declaratively bind <b>UI</b> (<b>Document Object Model</b> elements) to an underlying <b>data model</b>. One of the built-in bindings is the <b>html-binding</b> allowing to display an arbitrary <b>Html</b> provided by an associated property/field of the <b>data model</b>. The typical use of this <b>binding</b> may look like this:</p>
<pre class="brush: xml; title: ;">
&lt;div data-bind=&quot;html: comment&quot; /&gt;
</pre>
<p>where the <b>comment</b> property may be specified as shown in the following <b>data model</b>:</p>
<pre class="brush: jscript; title: ;">
...
// include the knockout library
&lt;script src=&quot;js/knockout/knockout-2.2.0.debug.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
...
$(function () {
	// define a data model
	var viewModel = function () {
        var self = this;
		self.comment = ko.observable(&quot;some html comment &lt;span&gt;Hello&lt;script type='text/javascript'&gt;alert('Hello!');&lt;\/script&gt;&lt;/span&gt;&quot;);
		...
	}
	...
	// create instance of the data model
	var viewModelInstance = new viewModel();
	// bind the instance to UI (since that moment all of the declarative bindings have worked off and the data are displayed)
	ko.applyBindings(viewModelInstance);
});
</pre>
</p>
<p style='text-align:justify'>Applying a value to a <b>DOM</b> element, the <b>html-binding</b> exploits the <b>jQuery</b>&#8216;s <b>html()</b> method, of course, if <b>jQuery</b> is available on the page; otherwise <b>knockout.js</b> relies on its own logic that ends up with call of the <b>DOM</b>&#8216;s <b><a href="http://www.w3schools.com/dom/met_element_appendchild.asp">appendChild</a></b> function. In both cases if the <b>html</b> being applied contains inclusions of <b>JavaScripts</b>, the <b>scripts</b> execute once the <b>html</b> has been added to the <b>DOM</b>. Preventing all unwanted <b>scripts</b> from running is the best practice when displaying random <b>htmls</b> on the page. Using the approach described in my post <b><a href="http://dotnetfollower.com/wordpress/2013/02/javascript-how-to-prevent-execution-of-javascript-within-a-html-being-added-to-the-dom/" title="Prevent scripts from running">How to prevent execution of JavaScript within a html being added to the DOM</a></b> we are able to develop our own <b>knockout binding</b> disabling the <b>scripts</b>. It could look like the following: </p>
<pre class="brush: jscript; title: ;">
 ko.bindingHandlers.htmlNoScripts = {
    init: function () {
        // Prevent binding on the dynamically-injected HTML
        return { 'controlsDescendantBindings': true };
    },
    update: function (element, valueAccessor, allBindingsAccessor) {
        // First get the latest data that we're bound to
        var value = valueAccessor();
        // Next, whether or not the supplied model property is observable, get its current value
        var valueUnwrapped = ko.utils.unwrapObservable(value);
		// disable scripts
        var disarmedHtml = valueUnwrapped.replace(/&lt;script(?=(\s|&gt;))/i, '&lt;script type=&quot;text/xml&quot; ');
        ko.utils.setHtml(element, disarmedHtml);
    }
};
 </pre>
</p>
<p style='text-align:justify'>An alternative way to prevent <b>scripts</b> from running is to use the <b>innerHTML</b> property of a <b>DOM</b> element as follows: </p>
<pre class="brush: jscript; title: ;">
 var html = &quot;&lt;script type='text/javascript'&gt;alert('Hello!');&lt;\/script&gt;&quot;;
 var newSpan = document.createElement('span');
 newSpan.innerHTML = str;
 document.getElementById('content').appendChild(newSpan);
 </pre>
</p>
<p style='text-align:justify'>Some people, however, report that this doesn&#8217;t work in <b>Internet Explorer 7</b> for unknown reasons. So, let&#8217;s combine these two methods in one to minimize the risk of unwanted <b>scripts</b> running. My tests show the combined approach successfully prevent <b>JavaScript</b> from being executed in all popular browsers. Even in the worst case, at least one of the methods works off. The resultant <b>knockout binding</b> may look like the following:</p>
<pre class="brush: jscript; title: ;">
ko.bindingHandlers.htmlNoScripts = {
    init: function () {
        // Prevent binding on the dynamically-injected HTML
        return { 'controlsDescendantBindings': true };
    },
    update: function (element, valueAccessor, allBindingsAccessor) {
        // First get the latest data that we're bound to
        var value = valueAccessor();
        // Next, whether or not the supplied model property is observable, get its current value
        var valueUnwrapped = ko.utils.unwrapObservable(value);
        // disable scripts
        var disarmedHtml = valueUnwrapped.replace(/&lt;script(?=(\s|&gt;))/i, '&lt;script type=&quot;text/xml&quot; ');
        // create a wrapping element
        var newSpan = document.createElement('span');
        // safely set internal html of the wrapping element
        newSpan.innerHTML = disarmedHtml;
        // clear the associated node from the previous content
        ko.utils.emptyDomNode(element);
        // add the sanitized html to the DOM
        element.appendChild(newSpan);
    }
};
</pre>
</p>
<p style='text-align:justify'>This <b>htmlNoScripts binding</b> can be used as follows:</p>
<pre class="brush: xml; title: ;">
&lt;div data-bind=&quot;htmlNoScripts: comment&quot; /&gt;
</pre>
</p>
<h5>Related posts:</h5>
<ul>
<li><a href="http://dotnetfollower.com/wordpress/2013/02/javascript-how-to-prevent-execution-of-javascript-within-a-html-being-added-to-the-dom/" title="How to prevent execution of JavaScript within a html being added to the DOM">JavaScript: How to prevent execution of JavaScript within a html being added to the DOM</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://dotnetfollower.com/wordpress/2013/02/knockout-js-htmlnoscript-binding/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JavaScript: How to prevent execution of JavaScript within a html being added to the DOM</title>
		<link>http://dotnetfollower.com/wordpress/2013/02/javascript-how-to-prevent-execution-of-javascript-within-a-html-being-added-to-the-dom/</link>
		<comments>http://dotnetfollower.com/wordpress/2013/02/javascript-how-to-prevent-execution-of-javascript-within-a-html-being-added-to-the-dom/#comments</comments>
		<pubDate>Wed, 06 Feb 2013 03:37:20 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Regex]]></category>

		<guid isPermaLink="false">http://dotnetfollower.com/wordpress/?p=1315</guid>
		<description><![CDATA[&#160;&#160;&#160;&#160;Getting pieces of html from an external web service, I display them &#8220;as is&#8221; on a page. To insert the htmls into the document I use handy jQuery methods: append() and html(). The only problem is the htmls contain inclusions of JavaScript that is executed whenever I add the htmls to the DOM (Document Object [...]]]></description>
			<content:encoded><![CDATA[<p style='text-align:justify'>&nbsp;&nbsp;&nbsp;&nbsp;Getting pieces of <b>html</b> from an external web service, I display them &#8220;as is&#8221; on a page. To insert the <b>html</b>s into the document I use handy <b>jQuery</b> methods: <b>append()</b> and <b>html()</b>. The only problem is the <b>html</b>s contain inclusions of <b>JavaScript</b> that is executed whenever I add the <b>html</b>s to the <b>DOM</b> (<b>Document Object Model</b>). Having looked for an acceptable solution to prevent untrusted <b>script</b>s from running I found out that almost all solutions come to removing <b>script</b>-tags from <b>html</b> using the <b>Regular Expressions</b>. I tried a couple of <b>regexes</b>, and they really worked. However, every time I could find such a combination of <b>script</b>-tag, <b>JavaScript</b> inside it and wrapping <b>html</b> when the <b>regexes</b> either didn&#8217;t recognize a <b>script</b> block or cut out more than it was needed. And I don&#8217;t even mention that parsing an arbitrary <b>HTML</b> with the <b>Regular Expressions</b> is <a href="http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454">a bad idea in all respects</a> <img src='http://dotnetfollower.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . Trying to find another solution, I recalled that if we replace the <b>type=&#8221;text/javascript&#8221;</b> of a <b>script</b>-tag with the <b>type=&#8221;text/xml&#8221;</b>, the <b>JavaScript</b> inside will not execute. This is quite known fact, and a few <b>JavaScript</b> libraries use this behavior for their purposes. However, two things impeded me to implement the direct replacing of one <b>type</b> with another: the <b>type=&#8221;text/javascript&#8221;</b> sub-string may encounter outside the <b>&lt;script&gt;</b>, somewhere in the content (like in this article <img src='http://dotnetfollower.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  ); the <b>script</b>-tag may be without the <b>type</b> attribute at all, and, in this case, the code inside will be run as if the <b>type=&#8221;text/javascript&#8221;</b> is specified. Taking into account these conditions, I developed a few tricky <b>regexes</b>, that seemed to be fairly complicated and not reliable enough though. After all, this led me to a thought to examine what happens if the <b>script</b>-tag has two <b>type</b> attributes. Something like this:</p>
<pre class="brush: jscript; title: ;">
&lt;script type=&quot;text/xml&quot; type=&quot;text/javascript&quot;&gt;
    alert('Hello!');
&lt;/script&gt;
</pre>
</p>
<p style='text-align:justify'>All browsers I tested this in didn&#8217;t execute <b>JavaScript</b>. On the contrary, if I change the <b>type</b> attributes over, the <b>script</b> is executed. Only the first <b>type</b> attribute seems to be efficient. So, my resultant solution is based on the following assumptions:</p>
<ul>
<li><b>JavaScript</b> inside the <b>&lt;script type=&#8221;text/xml&#8221;&gt;</b> doesn&#8217;t execute;</li>
<li><b>JavaScript</b> inside the <b>&lt;script type=&#8221;text/xml&#8221; type=&#8221;text/javascript&#8221;&gt;</b> doesn&#8217;t execute as well because only the first <b>type</b> is considered;</li>
</ul>
<p style='text-align:justify'>So, below is a very simple <b>JavaScript</b> function, which prevents <b>script</b>s from running and seems to avoid most of drawbacks:</p>
<pre class="brush: jscript; title: ;">
function preventJS(html) {
    return html.replace(/&lt;script(?=(\s|&gt;))/i, '&lt;script type=&quot;text/xml&quot; ');
}
</pre>
</p>
<p style='text-align:justify'>The solution still relies on the <b>Regular Expressions</b>, but the <b>regex</b> itself is quite simple and unambiguous. The <b>script</b>-tags are preserved in the <b>html</b>, so you can treat them later in a manner you want.</p>
<p style='text-align:justify'>Below is an example of use</p>
<pre class="brush: xml; title: ;">
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Prevent scripts from running&lt;/title&gt;
    &lt;script src=&quot;jquery-1.8.3.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div id=&quot;content&quot;&gt;&lt;/div&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
      $(function () {
        var html1 = &quot;&lt;span&gt;Hello 1&lt;script type='text/javascript'&gt;alert('Hello 1!');&lt;\/script&gt;&lt;/span&gt;&quot;
        var html2 = &quot;&lt;span&gt;Hello 2 &amp;lt;script&amp;gt; alert('Hi') &amp;lt;/script&amp;gt; &lt;script   type='text/javascript'&gt;alert('Hello 2!');&lt;\/script&gt;&lt;/span&gt;&quot;;
        var html3 = &quot;&lt;script src=\&quot;someJs.js\&quot; type='text/javascript'&gt;&lt;\/script&gt;&quot;;
        var html4 = &quot;&lt;script&gt;alert('Hello 4!');&lt;\/script&gt;&quot;;
        var html5 = &quot;&lt;scriptsomeAttr &gt;alert('Hello 5!');&quot;;

        $(&quot;#content&quot;).html(preventJS(html1));
        $(&quot;#content&quot;).append(preventJS(html2));
        $(&quot;#content&quot;).append(preventJS(html3));
        $(&quot;#content&quot;).append(preventJS(html4));
        $(&quot;#content&quot;).append(preventJS(html5));
      });

      function preventJS(html) {
        return html.replace(/&lt;script(?=(\s|&gt;))/i, '&lt;script type=&quot;text/xml&quot; ');
      }
    &lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>
</p>
<p style='text-align:justify'>I tested this solution in <b>Google Chrome v. 24.0.1312.56</b>, <b>FireFox v. 18.0.1</b> and <b>Internet Explorer 9 v.9.0.8112.16421</b>, and it works as directed. However, I still have doubts whether it&#8217;s applicable for all browsers and their versions. So, if you have tested it, please don&#8217;t hesitate to post a comment here with the result, browser&#8217;s name and version you use.</p>
<p style='text-align:justify'>For test purposes you can download a <b>html</b> page and a couple of <b>js</b>-files <b><a href="http://dotnetfollower.com/wordpress/Downloads/Prevent_scripts.zip" title="Prevent scripts from running">here</a></b>. If the preventing works correctly, having opened the page in a browser, you shouldn&#8217;t get any alerts.</p>
<h5>Related posts:</h5>
<ul>
<li><a href="http://dotnetfollower.com/wordpress/2013/02/knockout-js-htmlnoscript-binding/" title="Knockout.js: HtmlNoScript binding">Knockout.js: HtmlNoScript binding</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://dotnetfollower.com/wordpress/2013/02/javascript-how-to-prevent-execution-of-javascript-within-a-html-being-added-to-the-dom/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C#: How to set or get value of a private or internal property through the Reflection</title>
		<link>http://dotnetfollower.com/wordpress/2012/12/c-how-to-set-or-get-value-of-a-private-or-internal-property-through-the-reflection/</link>
		<comments>http://dotnetfollower.com/wordpress/2012/12/c-how-to-set-or-get-value-of-a-private-or-internal-property-through-the-reflection/#comments</comments>
		<pubDate>Mon, 17 Dec 2012 06:17:24 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">http://dotnetfollower.com/wordpress/?p=1304</guid>
		<description><![CDATA[&#160;&#160;&#160;&#160;Quite often in my practice I need to interact with hidden (internal and private) properties of an object. It easily can be done through the Reflection API. The only complication may arise here it&#8217;s when a private property is defined in one of the base classes. In this case we have to iterate through the [...]]]></description>
			<content:encoded><![CDATA[<p style='text-align:justify'>&nbsp;&nbsp;&nbsp;&nbsp;Quite often in my practice I need to interact with hidden (<b>internal</b> and <b>private</b>) properties of an object. It easily can be done through the <b>Reflection API</b>. The only complication may arise here it&#8217;s when a <b>private</b> property is defined in one of the base classes. In this case we have to iterate through the object&#8217;s class hierarchy, looking for the property. So, trying to simplify getting and setting values of object&#8217;s <b>private</b> and <b>internal</b> properties, I&#8217;ve implemented a couple of the methods-<b>extensions</b> listed below. The <b>GetPropertyValue</b> method returns value of a <b>private</b> or <b>internal</b> property, and the <b>SetPropertyValue</b>, in turn, sets value to a <b>private</b> or <b>internal</b> property.</p>
<pre class="brush: csharp; title: ;">
public static class ReflectionHelper
{
 private static PropertyInfo GetPropertyInfo(Type type, string propertyName)
 {
   PropertyInfo propInfo = null;
   do
   {
     propInfo = type.GetProperty(propertyName,
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
     type = type.BaseType;
   }
   while (propInfo == null &amp;&amp; type != null);
   return propInfo;
 }

 public static object GetPropertyValue(this object obj, string propertyName)
 {
   if (obj == null)
     throw new ArgumentNullException(&quot;obj&quot;);
   Type objType = obj.GetType();
   PropertyInfo propInfo = GetPropertyInfo(objType, propertyName);
   if (propInfo == null)
     throw new ArgumentOutOfRangeException(&quot;propertyName&quot;,
       string.Format(&quot;Couldn't find property {0} in type {1}&quot;, propertyName, objType.FullName));
   return propInfo.GetValue(obj, null);
 }

 public static void SetPropertyValue(this object obj, string propertyName, object val)
 {
    if (obj == null)
      throw new ArgumentNullException(&quot;obj&quot;);
    Type objType = obj.GetType();
    PropertyInfo propInfo = GetPropertyInfo(objType, propertyName);
    if (propInfo == null)
      throw new ArgumentOutOfRangeException(&quot;propertyName&quot;,
        string.Format(&quot;Couldn't find property {0} in type {1}&quot;, propertyName, objType.FullName));
    propInfo.SetValue(obj, val, null);
 }
}
</pre>
<p style='text-align:justify'>Below is how to use the methods. Let&#8217;s assume we have the following hierarchy of classes:</p>
<pre class="brush: csharp; title: ;">
class SomeBase
{
    private bool IsLimited { get; set; }

    public SomeBase()
    {
        IsLimited = false;
    }
}

class SomeClass : SomeBase
{
    private  string Str { get; set; }
    internal int    Int { get; set; }

    public SomeClass()
    {
        Str = &quot;initial value&quot;;
        Int = 0;
    }
}
</pre>
<p style='text-align:justify'>So, we need to get and set hidden properties&#8217; values from within a project (library) different to the one where the <b>SomeBase</b> and <b>SomeClass</b> are located. A possible code may look like the following:</p>
<pre class="brush: csharp; title: ;">
SomeClass someObj = new SomeClass();

// the Str and Int properties will be found on the first step of iteration,
// so, the base class won't be analyzed
string currentStrValue = (string)someObj.GetPropertyValue(&quot;Str&quot;);
int    currentIntValue = (int)someObj.GetPropertyValue(&quot;Int&quot;);

// the IsLimited propertiy will be found on the second step of iteration,
// so, the base class will be analyzed as well
bool currentBoolValue = (bool)someObj.GetPropertyValue(&quot;IsLimited&quot;);

// the Str and Int properties will be found on the first step of iteration,
// so, the base class won't be analyzed
someObj.SetPropertyValue(&quot;Str&quot;, &quot;brand new value&quot;);
someObj.SetPropertyValue(&quot;Int&quot;, -1);

// the IsLimited propertiy will be found on the second step of iteration,
// so, the base class will be analyzed as well
someObj.SetPropertyValue(&quot;IsLimited&quot;, true);
</pre>
]]></content:encoded>
			<wfw:commentRss>http://dotnetfollower.com/wordpress/2012/12/c-how-to-set-or-get-value-of-a-private-or-internal-property-through-the-reflection/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>jQuery: Plugins to handle long click and taphold events</title>
		<link>http://dotnetfollower.com/wordpress/2012/12/jquery-plugins-to-handle-long-click-and-taphold-events/</link>
		<comments>http://dotnetfollower.com/wordpress/2012/12/jquery-plugins-to-handle-long-click-and-taphold-events/#comments</comments>
		<pubDate>Mon, 03 Dec 2012 18:19:19 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[iPad]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://dotnetfollower.com/wordpress/?p=1286</guid>
		<description><![CDATA[jQuery plugin to catch a long click event Below is a simple jQuery plugin to catch a long click or long press: (function ($) { $.fn.longClick = function (callback, timeout) { // bind to element's mousedown event to track the longclick's beginning $(this).mousedown(function (event) { // save the initial event object var initialEvent = event; [...]]]></description>
			<content:encoded><![CDATA[<p><a name="longclickHandling" id="longclickHandling"></a><br />
<h4>jQuery plugin to catch a long click event</h4>
<p style='text-align:justify'>Below is a simple <b>jQuery plugin</b> to catch a <b>long click</b> or <b>long press</b>:</p>
<pre class="brush: jscript; title: ;">
(function ($) {
  $.fn.longClick = function (callback, timeout) {
   // bind to element's mousedown event to track the longclick's beginning
   $(this).mousedown(function (event) {
    // save the initial event object
    var initialEvent = event;
    // set the delay after which the callback will be called
    var timer = window.setTimeout(function () { callback(initialEvent); }, timeout);
    // bind to global mouseup event for clearance
    $(document).mouseup(function () {
      // clear timer
      window.clearTimeout(timer);
      // unbind from global mouseup event
      $(document).unbind(&quot;mouseup&quot;);
      return true;
      // use 'return false;' if you need to prevent default handler and
      // stop event bubbling
    });
     return true;
     // use 'return false;' if you need to prevent default handler and
     // stop event bubbling
   });
  };
})(jQuery);

...
// using
(function ($) {
  $(&quot;#someDiv&quot;).longClick(function (e) {
              alert($(e.target).attr(&quot;id&quot;) + &quot; was clicked&quot;); },
              1500);
})(jQuery);
</pre>
<p style='text-align:justify'>The <b>plugin</b> accepts a <b>callback</b> function that will be called once a <b>long click</b> event occurred and a <b>timeout</b> in milliseconds saying how long user should keep button pressed to produce the <b>long click</b>.</p>
<p><a name="tapholdHandling" id="tapholdHandling"></a><br />
<h4>jQuery plugin to catch a taphold event</h4>
<p style='text-align:justify'>The same <b>long click</b> for <b>iPad</b> is usually called <b>taphold</b> and can be implemented as follows:</p>
<pre class="brush: jscript; title: ;">
(function ($) {
  $.fn.taphold = function (callback, timeout) {
   // bind to element's touchstart event to track the taphold's beginning
   $(this).bind(&quot;touchstart&quot;, function (event) {
    // save the initial event object
    var initialEvent = event;
    // set the delay after which the callback will be called
    var timer = window.setTimeout(function () { callback(initialEvent); }, timeout);
    // bind to global touchend and touchcancel events for clearance
    $(document).bind(&quot;touchend touchcancel&quot;, function () {
      // clear timer
      window.clearTimeout(timer);
      // unbind from touchend and touchcancel events
      $(document).unbind(&quot;touchend touchcancel&quot;);
      return true;
      // use 'return false;' if you need to prevent default handler and
      // stop event bubbling
    });
    return true;
    // use 'return false;' if you need to prevent default handler and
    // stop event bubbling
   });
  };
})(jQuery);

...
// using
(function ($) {
  $(&quot;#someDiv&quot;).taphold(function () {
               alert($(e.target).attr(&quot;id&quot;) + &quot; was tapholded&quot;); },
               1500);
})(jQuery);
</pre>
<p style='text-align:justify'>The only difference from the previous <b>plugin</b> is that touchable device&#8217;s events are used.</p>
<p><a name="clickTapholdHandling" id="clickTapholdHandling"></a><br />
<h4>Combined jQuery plugin to catch both long click and taphold events</h4>
<p style='text-align:justify'>Two shown above <b>plugins</b> can be quite easily combined in one. The new <b>plugin</b> checks if the current device is an <b>iPad</b> and, if so, deals with such <b>iPad</b> events as <b>touchstart</b>, <b>touchend</b> and <b>touchcancel</b>; otherwise, it uses traditional <b>mousedown</b> and <b>mouseup</b>.</p>
<pre class="brush: jscript; title: ;">
(function ($) {
 $.fn.longclick = function (callback, timeout) {
   var isIPad = $.isIPad();

   var startEvents = isIPad ? &quot;touchstart&quot; :           &quot;mousedown&quot;;
   var endEvents   = isIPad ? &quot;touchend touchcancel&quot; : &quot;mouseup&quot;;

   $(this).bind(startEvents, function (event) {
    // save the initial event object
    var initialEvent = event;
    // set delay after which the callback will be called
    var timer = window.setTimeout(function () { callback(initialEvent); }, timeout);
    // bind to global event(s) for clearance
    $(document).bind(endEvents, function () {
        // clear timer
        window.clearTimeout(timer);
        // reset global event handlers
        $(document).unbind(endEvents);
        return true;
        // use 'return false;' if you need to prevent default handler and
        // stop event bubbling
    });
    return true;
    // use 'return false;' if you need to prevent default handler and
    // stop event bubbling
   });
 };
})(jQuery);

...
// using
(function ($) {
    $(&quot;#someDiv&quot;).longclick(function () {
             alert($(e.target).attr(&quot;id&quot;) + &quot; was clicked&quot;); },
             1500);
})(jQuery);
</pre>
<p style='text-align:justify'>Note that the <b>isIPad plugin</b> was described in the post &#8211; <a href="http://dotnetfollower.com/wordpress/2012/11/jquery-plugins-to-detect-ipad-and-iphone-devices/" title="Detect iPad and iPhone devices">jQuery: Plugins to detect iPad and iPhone devices</a>.</p>
<h5>Related posts:</h5>
<ul>
<li><a href="http://dotnetfollower.com/wordpress/2012/11/jquery-plugins-to-detect-ipad-and-iphone-devices/" title="Plugins to detect iPad and iPhone devices">jQuery: Plugins to detect iPad and iPhone devices</a></li>
<li><a href="http://dotnetfollower.com/wordpress/2012/11/jquery-isnullorempty-plugin-for-jquery/" title="IsNullOrEmpty plugin for jQuery">jQuery: IsNullOrEmpty plugin for jQuery</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://dotnetfollower.com/wordpress/2012/12/jquery-plugins-to-handle-long-click-and-taphold-events/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery: Plugins to detect iPad and iPhone devices</title>
		<link>http://dotnetfollower.com/wordpress/2012/11/jquery-plugins-to-detect-ipad-and-iphone-devices/</link>
		<comments>http://dotnetfollower.com/wordpress/2012/11/jquery-plugins-to-detect-ipad-and-iphone-devices/#comments</comments>
		<pubDate>Fri, 30 Nov 2012 19:04:54 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[iPad]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://dotnetfollower.com/wordpress/?p=1277</guid>
		<description><![CDATA[jQuery plugin for iPad detection Below is a simple jQuery plugin to detect whether a page is opened in an iPad: (function ($) { $.isIPad = function () { return (typeof navigator != &#34;undefined&#34; &#38;&#38; navigator &#38;&#38; navigator.userAgent &#38;&#38; navigator.userAgent.match(/iPad/i) != null); }; })(jQuery); ... // using $(function(){ if($.isIPad()) alert('Hello, iPad'); }); jQuery plugin for [...]]]></description>
			<content:encoded><![CDATA[<p><a name="iPadDetection" id="iPadDetection"></a><br />
<h4>jQuery plugin for iPad detection</h4>
<p style='text-align:justify'>Below is a simple <b>jQuery plugin</b> to detect whether a page is opened in an <b>iPad</b>:</p>
<pre class="brush: jscript; title: ;">
(function ($) {
    $.isIPad = function () {
        return (typeof navigator != &quot;undefined&quot; &amp;&amp;
               navigator &amp;&amp; navigator.userAgent &amp;&amp;
               navigator.userAgent.match(/iPad/i) != null);
    };
})(jQuery);

...
// using
$(function(){
    if($.isIPad())
        alert('Hello, iPad');
});
</pre>
<p><a name="iPhoneDetection" id="iPhoneDetection"></a><br />
<h4>jQuery plugin for iPhone detection</h4>
<p style='text-align:justify'>The next <b>plugin</b> allows to detect an <b>iPhone</b>:</p>
<pre class="brush: jscript; title: ;">
(function ($) {
    $.isIPhone = function () {
        if(!$.isIPad())
            return (typeof navigator != &quot;undefined&quot; &amp;&amp;
               navigator &amp;&amp; navigator.userAgent &amp;&amp;
               (navigator.userAgent.match(/iPhone/i) != null ||
                navigator.userAgent.match(/iPod/i) != null));
        return false;
    };
})(jQuery);

...
// using
$(function(){
    if($.isIPhone())
        alert('Hello, iPhone');
});
</pre>
<p style='text-align:justify'>Note, initially I check if the device is an <b>iPad</b> and only then try to identify it as an <b>iPhone</b>. I do so because people reports that some <b>iPad</b> browsers/applications use substring <b>&#8216;iPhone&#8217;</b> in their <b>userAgents</b> along with the expected <b>&#8216;iPad&#8217;</b>. For example, such behavior was noticed in <b>Facebook UIWebView</b>.</p>
<p><a name="appleDetection" id="appleDetection"></a><br />
<h4>jQuery plugin for Apple mobile device detection</h4>
<p style='text-align:justify'>To detect any <b>Apple</b> mobile devices (<b>iPad</b>, <b>iPhone</b> or <b>iPod</b>) you can use the following <b>jQuery plugin</b>:</p>
<pre class="brush: jscript; title: ;">
(function ($) {
    $.isAppleMobile = function () {
        return (typeof navigator != &quot;undefined&quot; &amp;&amp;
               navigator &amp;&amp; navigator.userAgent &amp;&amp;
               navigator.userAgent.match(/(iPad|iPhone|iPod)/i) != null);
    };
})(jQuery);

...
// using
$(function(){
    if($.isAppleMobile())
        alert('Hello, Apple device');
});
</pre>
<h5>Related posts:</h5>
<ul>
<li><a href="http://dotnetfollower.com/wordpress/2012/12/jquery-plugins-to-handle-long-click-and-taphold-events/" title="Plugins to handle long click and taphold events">jQuery: Plugins to handle long click and taphold events</a></li>
<li><a href="http://dotnetfollower.com/wordpress/2012/11/jquery-isnullorempty-plugin-for-jquery/" title="IsNullOrEmpty plugin for jQuery">jQuery: IsNullOrEmpty plugin for jQuery</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://dotnetfollower.com/wordpress/2012/11/jquery-plugins-to-detect-ipad-and-iphone-devices/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript: How to determine whether a variable has a valid value</title>
		<link>http://dotnetfollower.com/wordpress/2012/11/javascript-how-to-determine-whether-a-variable-has-a-valid-value/</link>
		<comments>http://dotnetfollower.com/wordpress/2012/11/javascript-how-to-determine-whether-a-variable-has-a-valid-value/#comments</comments>
		<pubDate>Thu, 29 Nov 2012 20:17:12 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://dotnetfollower.com/wordpress/?p=1265</guid>
		<description><![CDATA[&#160;&#160;&#160;&#160;A good way to examine whether a variable (or object&#8217;s field) has a valid value looks like the following: if( variable /* obj.field */ ) { } This statement allows to check if the value is null (explicit assignment of null to variable happened) or undefined (variable wasn&#8217;t initialized). To be more precise it returns [...]]]></description>
			<content:encoded><![CDATA[<p style='text-align:justify'>&nbsp;&nbsp;&nbsp;&nbsp;A good way to examine whether a variable (or object&#8217;s field) has a valid value looks like the following:</p>
<pre class="brush: jscript; title: ;">
if( variable /* obj.field */ ) {
}
</pre>
<p style='text-align:justify'>This statement allows to check if the value is <b>null</b> (explicit assignment of <b>null</b> to variable happened) or undefined (variable wasn&#8217;t initialized). To be more precise it returns <b>true</b> when the variable is not</p>
<ul>
<li>null</li>
<li>undefined</li>
<li>NaN</li>
<li>empty string (&#8220;&#8221;)</li>
<li>0</li>
<li>false</li>
</ul>
<p style='text-align:justify'>Mostly, such validity check is more than enough for further safe treating with the variable. However, we&#8217;ll get the &#8220;<b>&#8216;variable&#8217; is undefined error</b>&#8221; if the variable is undeclared. In this case we have to perform the following check in advance:</p>
<pre class="brush: jscript; title: ;">
if(typeof variable !== 'undefined') {
}
</pre>
<p style='text-align:justify'>Of course, if you are pretty sure that the variable exists (is declared), you can omit the <b>typeof</b> check. But if you deal with something going from an external library or source, I recommend having it. So, gathering all together, we obtain the following code:</p>
<pre class="brush: jscript; title: ;">
if(typeof variable !== 'undefined' &amp;&amp; variable) {
}
</pre>
<p style='text-align:justify'>In some forums, people from time to time suggest to wrap such check into a function. Let&#8217;s assume we have such function:</p>
<pre class="brush: jscript; title: ;">
function isValid(obj) {
  return typeof obj !== 'undefined' &amp;&amp; obj;
}
</pre>
<p style='text-align:justify'>However, it doesn&#8217;t make sense at all as you can&#8217;t call the function, passing an undeclared variable, in any case. The mentioned above error is thrown whenever you try addressing to the unknown variable:</p>
<pre class="brush: jscript; title: ;">
if(isValid(varibale)) // throw &quot;'variable' is undefined error&quot;,
                      // if the variable doesn't exist
  ...
</pre>
<p style='text-align:justify'>Thus, in case of undeclared variable, we have to have inline <b>typeof</b> check. In all other cases, it&#8217;s enough to have simple <b>if(variable)</b>. So, using variables and objects likely declared outside of my code, I examine them like in the sample below:</p>
<pre class="brush: jscript; title: ;">
if(typeof navigator != &quot;undefined&quot; &amp;&amp; navigator &amp;&amp; navigator.userAgent)
     alert(navigator.userAgent);
</pre>
]]></content:encoded>
			<wfw:commentRss>http://dotnetfollower.com/wordpress/2012/11/javascript-how-to-determine-whether-a-variable-has-a-valid-value/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery: IsNullOrEmpty plugin for jQuery</title>
		<link>http://dotnetfollower.com/wordpress/2012/11/jquery-isnullorempty-plugin-for-jquery/</link>
		<comments>http://dotnetfollower.com/wordpress/2012/11/jquery-isnullorempty-plugin-for-jquery/#comments</comments>
		<pubDate>Wed, 21 Nov 2012 02:44:11 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://dotnetfollower.com/wordpress/?p=1261</guid>
		<description><![CDATA[&#160;&#160;&#160;&#160;I was a bit disappointed when couldn&#8217;t find in jQuery library a method similar to String.IsNullOrEmpty from C#. So, below is a simple jQuery plugin to examine whether the passed string is empty or null. (function ($) { $.isNullOrEmpty = function (str) { return !str &#124;&#124; $.trim(str) === &#34;&#34;; // the trim method is provided [...]]]></description>
			<content:encoded><![CDATA[<p style='text-align:justify'>&nbsp;&nbsp;&nbsp;&nbsp;I was a bit disappointed when couldn&#8217;t find in <b>jQuery</b> library a method similar to <b>String.IsNullOrEmpty</b> from <b>C#</b>. So, below is a simple <b>jQuery plugin</b> to examine whether the passed string is empty or null.</p>
<pre class="brush: jscript; title: ;">
(function ($) {
    $.isNullOrEmpty = function (str) {
        return !str || $.trim(str) === &quot;&quot;; // the trim method is provided by jQuery
    };
})(jQuery);
</pre>
<p style='text-align:justify'>Some samples of use</p>
<pre class="brush: jscript; title: ;">
var res = $.isNullOrEmpty(''); // true
res = $.isNullOrEmpty(&quot;bla-bla-bla&quot;); // false
res = $.isNullOrEmpty(null); // true
res = $.isNullOrEmpty(); // true
</pre>
<h5>Related posts:</h5>
<ul>
<li><a href="http://dotnetfollower.com/wordpress/2012/12/jquery-plugins-to-handle-long-click-and-taphold-events/" title="Plugins to handle long click and taphold events">jQuery: Plugins to handle long click and taphold events</a></li>
<li><a href="http://dotnetfollower.com/wordpress/2012/11/jquery-plugins-to-detect-ipad-and-iphone-devices/" title="Plugins to detect iPad and iPhone devices">jQuery: Plugins to detect iPad and iPhone devices</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://dotnetfollower.com/wordpress/2012/11/jquery-isnullorempty-plugin-for-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SharePoint: Issue with calling an asmx web service in SharePoint 2010 through jQuery</title>
		<link>http://dotnetfollower.com/wordpress/2012/11/sharepoint-issue-with-calling-an-asmx-web-service-in-sharepoint-2010-through-jquery/</link>
		<comments>http://dotnetfollower.com/wordpress/2012/11/sharepoint-issue-with-calling-an-asmx-web-service-in-sharepoint-2010-through-jquery/#comments</comments>
		<pubDate>Tue, 20 Nov 2012 19:05:50 +0000</pubDate>
		<dc:creator>Admin</dc:creator>
				<category><![CDATA[Administration]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[SharePoint 2010]]></category>

		<guid isPermaLink="false">http://dotnetfollower.com/wordpress/?p=1246</guid>
		<description><![CDATA[&#160;&#160;&#160;&#160;After migration a SharePoint 2007 application to SharePoint 2010 my jQuery scripts communicating with asmx web services stopped working. The error I got was a 500 Internal Server Error. The scripts looks as follows: $.ajax({ type: &#34;POST&#34;, url: &#34;http://someserver/someapp/_layouts/Services/Products.asmx/GetProductByCountry&#34;, data: JSON.stringify({ countryCode: &#34;USA&#34; }), dataType: &#34;json&#34;, contentType: 'application/json; charset=utf-8', context: this, success: function (data) { [...]]]></description>
			<content:encoded><![CDATA[<p style='text-align:justify'>&nbsp;&nbsp;&nbsp;&nbsp;After migration a <b>SharePoint 2007</b> application to <b>SharePoint 2010</b> my <b>jQuery</b> scripts communicating with <b>asmx web services</b> stopped working. The error I got was a <b>500 Internal Server Error</b>. The scripts looks as follows:</p>
<pre class="brush: jscript; title: ;">
$.ajax({
  type: &quot;POST&quot;,
  url:  &quot;http://someserver/someapp/_layouts/Services/Products.asmx/GetProductByCountry&quot;,

  data:        JSON.stringify({ countryCode: &quot;USA&quot; }),
  dataType:    &quot;json&quot;,
  contentType: 'application/json; charset=utf-8',
  context:     this,

  success: function (data) {
		     alert(data.d);
           },
  error:   function (XMLHttpRequest, textStatus, errorThrown) {
		     alert(textStatus);
           }
});
</pre>
<p><i>Note: The <b>JSON</b> object mentioned in the script is defined in the <b>json2.js</b> available at <a href="http://www.json.org">http://www.json.org</a>.</i></p>
<p style='text-align:justify'>This issue can be solved by adding an appropriate <b>&lt;webServices&gt;</b> section to the <b>SharePoint</b> application&#8217;s <b>web.config</b> (in my case it&#8217;s located at <b>C:\inetpub\wwwroot\wss\VirtualDirectories\80</b>). So, find the global <b>&lt;system.web&gt;</b> section in your <b>web.config</b> and make changes so that the result would look like the following:</p>
<pre class="brush: xml; title: ;">
&lt;system.web&gt;
  &lt;webServices&gt;
    &lt;protocols&gt;
      &lt;add name=&quot;HttpGet&quot; /&gt;
      &lt;add name=&quot;HttpPost&quot; /&gt;
    &lt;/protocols&gt;
  &lt;/webServices&gt;
...
&lt;/system.web&gt;
</pre>
<p style='text-align:justify'>However, from the security point of view such solution is not ideal as it allows external access through the <b>HTTP-GET</b> and <b>HTTP-POST</b> messaging protocols to all your <b>XML web services</b>. So, it&#8217;s better to specify the access protocols for each <b>web service</b> separately, not affecting other ones. The <b>&lt;location&gt;</b> element added to the root <b>&lt;configuration&gt;</b> element provides us with this capability. The sample below defines the protocols for accessing the <b>web service</b> reachable by the specified path:</p>
<pre class="brush: xml; title: ;">
&lt;configuration&gt;
...
  &lt;location path=&quot;_layouts/Services/Products.asmx&quot;&gt;
    &lt;system.web&gt;
      &lt;webServices&gt;
        &lt;protocols&gt;
          &lt;add name=&quot;HttpGet&quot;/&gt;
          &lt;add name=&quot;HttpPost&quot;/&gt;
        &lt;/protocols&gt;
      &lt;/webServices&gt;
    &lt;/system.web&gt;
  &lt;/location&gt;
...
&lt;/configuration&gt;
</pre>
<p style='text-align:justify'>Note that the <b>_layouts</b> virtual directory is available as a subfolder of every <b>SharePoint</b> Web site. So if you want to limit the use of the <b>web service</b> by only one <b>SharePoint</b> Web site, specify the path like <b>someapp/_layouts/Services/Products.asmx</b>.</p>
<p style='text-align:justify'>PS <a href="http://msmvps.com/blogs/windsor/archive/2011/11/04/walkthrough-creating-a-custom-asp-net-asmx-web-service-in-sharepoint-2010.aspx">Here</a> is a good article about how to create a custom <b>web service</b> in <b>SharePoint 2010</b>.</p>
]]></content:encoded>
			<wfw:commentRss>http://dotnetfollower.com/wordpress/2012/11/sharepoint-issue-with-calling-an-asmx-web-service-in-sharepoint-2010-through-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
