Thursday, June 4, 2015

Checkbox in tree view



ASPX

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="WebApplication4tree._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
   
    <script type="text/javascript">
        function OnTreeClick(evt) {
            var src = window.event != window.undefined ? window.event.srcElement : evt.target;
            var isChkBoxClick = (src.tagName.toLowerCase() == "input" && src.type == "checkbox");
            if (isChkBoxClick) {
                if (src.checked == true) {
                    var nodeText = getNextSibling(src).innerText || getNextSibling(src).innerHTML;

                    var nodeValue = GetNodeValue(getNextSibling(src));
                    var btn = document.getElementById('<%=LinkButton1.ClientID%>');
                    btn.click();
//                    var dopost = document.getElementById("label")
//                    __doPostBack('LinkButton1', '')
                    __doPostBack('__Page', 'MyCustomArgument');
                    document.getElementById("label").innerHTML += nodeText + ",";
                }
                else {
                    var nodeText = getNextSibling(src).innerText || getNextSibling(src).innerHTML;
                    var nodeValue = GetNodeValue(getNextSibling(src));
                    var val = document.getElementById("label").innerHTML;
                    document.getElementById("label").innerHTML = val.replace(nodeText + ",", "");
                }
                var parentTable = GetParentByTagName("table", src);
                var nxtSibling = parentTable.nextSibling;
                //check if nxt sibling is not null & is an element node
                if (nxtSibling && nxtSibling.nodeType == 1) {
                    //if node has children  
                    if (nxtSibling.tagName.toLowerCase() == "div") {
                        //check or uncheck children at all levels
                        CheckUncheckChildren(parentTable.nextSibling, src.checked);
                    }
                }
                //check or uncheck parents at all levels
                CheckUncheckParents(src, src.checked);
            }
        }
        function CheckUncheckChildren(childContainer, check) {
            var childChkBoxes = childContainer.getElementsByTagName("input");
            var childChkBoxCount = childChkBoxes.length;
            for (var i = 0; i < childChkBoxCount; i++) {
                childChkBoxes[i].checked = check;
            }
        }

        function CheckUncheckParents(srcChild, check) {
            var parentDiv = GetParentByTagName("div", srcChild);
            var parentNodeTable = parentDiv.previousSibling;
            if (parentNodeTable) {
                var checkUncheckSwitch;
                //checkbox checked
                if (check) {
                    var isAllSiblingsChecked = AreAllSiblingsChecked(srcChild);
                    if (isAllSiblingsChecked)
                        checkUncheckSwitch = true;
                    else
                        return; //do not need to check parent if any(one or more) child not checked
                }
                else //checkbox unchecked
                {
                    checkUncheckSwitch = false;
                }
                var inpElemsInParentTable = parentNodeTable.getElementsByTagName("input");
                if (inpElemsInParentTable.length > 0) {
                    var parentNodeChkBox = inpElemsInParentTable[0];
                    parentNodeChkBox.checked = checkUncheckSwitch;
                    //do the same recursively
                    CheckUncheckParents(parentNodeChkBox, checkUncheckSwitch);
                }
            }
        }

        function AreAllSiblingsChecked(chkBox) {
            var parentDiv = GetParentByTagName("div", chkBox);
            var childCount = parentDiv.childNodes.length;
            for (var i = 0; i < childCount; i++) {
                if (parentDiv.childNodes[i].nodeType == 1) {
                    //check if the child node is an element node
                    if (parentDiv.childNodes[i].tagName.toLowerCase() == "table") {
                        var prevChkBox = parentDiv.childNodes[i].getElementsByTagName("input")[0];
                        //if any of sibling nodes are not checked, return false
                        if (!prevChkBox.checked) {
                            return false;
                        }
                    }
                }
            }
            return true;
        }
        //utility function to get the container of an element by tagname
        function GetParentByTagName(parentTagName, childElementObj) {
            var parent = childElementObj.parentNode;
            while (parent.tagName.toLowerCase() != parentTagName.toLowerCase()) {
                parent = parent.parentNode;
            }
            return parent;
        }

        function getNextSibling(element) {
            var n = element;
            do n = n.nextSibling;
            while (n && n.nodeType != 1);
            return n;
        }
        //returns NodeValue
        function GetNodeValue(node) {
            var nodeValue = "";
            var nodePath = node.href.substring(node.href.indexOf(",") + 2, node.href.length - 2);
            var nodeValues = nodePath.split("\\");
            if (nodeValues.length > 1)
                nodeValue = nodeValues[nodeValues.length - 1];
            else
                nodeValue = nodeValues[0].substr(1);
            return nodeValue;
        }
</script>

    <asp:TreeView ID="TreeView1" runat="server"

         onselectednodechanged="TreeView1_SelectedNodeChanged"
        ontreenodecheckchanged="TreeView1_TreeNodeCheckChanged" ShowCheckBoxes="Leaf" OnClick="OnTreeClick(event)"  >
       
    </asp:TreeView>

    <asp:LinkButton ID="LinkButton1"  runat="server" style="display:none;" >LinkButton</asp:LinkButton>
</asp:Content>



code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication4tree
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           
            if (!IsPostBack)
            {
                TreeView1.Nodes.Add(new TreeNode("Fruits", "Fruits"));

                TreeView1.Nodes[0].ChildNodes.Add(new TreeNode("Mango", "Mango"));
                TreeView1.Nodes[0].ChildNodes.Add(new TreeNode("Apple", "Apple"));
                TreeView1.Nodes[0].ChildNodes.Add(new TreeNode("Pineapple", "Pineapple"));
                TreeView1.Nodes[0].ChildNodes.Add(new TreeNode("Orange", "Orange"));
                TreeView1.Nodes[0].ChildNodes.Add(new TreeNode("Grapes", "Grapes"));

                TreeView1.Nodes.Add(new TreeNode("Vegetables", "Vegetables"));
                TreeView1.Nodes[1].ChildNodes.Add(new TreeNode("Carrot", "Carrot"));
                TreeView1.Nodes[1].ChildNodes.Add(new TreeNode("Cauliflower", "Cauliflower"));
                TreeView1.Nodes[1].ChildNodes.Add(new TreeNode("Potato", "Potato"));
                TreeView1.Nodes[1].ChildNodes.Add(new TreeNode("Tomato", "Tomato"));
                TreeView1.Nodes[1].ChildNodes.Add(new TreeNode("Onion", "Onion"));
            }
        }

        protected void TreeView1_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
        {

        }

    }
}

Wednesday, May 6, 2015

Hide col in List edit and new form






Please use the following PowerShell Script to hide the column from New and Edit forms.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$web = Get-SPWeb "http://sp2013" # Site where your list exists
$list = $web.Lists.TryGetList("EmergencyContacts") #list name
if($list)
{
    $field = $list.Fields["Phone"] #internal field name
    $field.ShowInNewForm = $false
    $field.ShowInEditForm = $false
    $field.Update()
}
Alternate option is to customize the New and Edit form using SharePoint Designer.  Remove the columns tag.  In my suggestion best to use the PowerShell script to hide the columns for New and Edit form.  If you want to enable later, please change the script to true, it will be shown without any effor.
Please mark it answered, if your problem resolved or helpful.


$web = Get-SPWeb webUrl
$list = $web.Lists.TryGetList("Listname")
if($list)
{
    $field = $list.Fields["FieldName"]
    $field.ShowInNewForm = $false
    $field.Update()
}


<script type="text/javascript">
$(document).ready(function() {
    $('nobr:contains("Completion time")').closest('tr').hide();
    $('nobr:contains("Score")').closest('tr').hide();
});

-------------------
</script> 

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('select[title=ColumnName]').val('ValueYouWant');
$("nobr:contains('ColumnName')").parent('h3').parent('td').parent('tr').hide();
});
</script> 


 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('select[title=ColumnName]').val('ValueYouWant');
$("nobr:contains('ColumnName')").parent('h3').parent('td').parent('tr').hide();
});
</script>


-----------------------
http://www.sharepointdiary.com/2012/12/hide-columns-in-newform-editform-dispforms.html

Using SharePoint Manager Tool to Hide SharePoint List Form Fields:
My favorite utility, SharePoint Manager is not just a Object Explorer but supports changing configurations also. So we can use SharePoint Manager to change the specific fields properties. Just download the SharePoint Manager, navigate to the field all the way through Web Applications, Site Collections, Sites, Lists. Set the "ShowInDisplayForm" or whatever required and save the changes.


PowerShell Script to Hide SharePoint List Columns:
SharePoint fields can be hidden programmatically. Why not PowerShell? Lets use PowerShell to set the field properties.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#Get the Web
$SPWeb = Get-SPWeb "http://sharepoint.crescent.com"
#Get the List
$SPList = $SPWeb.Lists["Project Matrics"]
#Get the Field
$SPField = $SPList.Fields["Parent Project"] 

#Hide from NewForm & EditForm
$SPField.ShowInEditForm = $true
$SPField.ShowInNewForm  = $false

$SPField.Update()
$SPWeb.Dispose()

Same code goes in MOSS 2007 also, with slight change to hide list field in SharePoint 2007:
 [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

  $SPSite = New-Object Microsoft.SharePoint.SPSite("http://sharepoint.crescent.com")
  $SPWeb = $SPSite.OpenWeb()

  $SPList = $SPWeb.Lists["Project Matrics"]

  $SPField = $SPList.Fields["Parent Project"]
  $SPField.ShowInNewForm = $False
  $SPField.ShowInEditForm = $False
  $SPField.Update()

  $SPSite.Dispose()

Object Model C# Code to hide fields on a form:
       using (SPSite oSPSite = new SPSite("http://sharepoint.crescent.com"))
            {
                using (SPWeb oSPWeb = oSPSite.OpenWeb())
                {
                     //Get List & Field
                    SPList oSPList = oSPWeb.Lists["Project Metrics"];
                    SPField oSPField = oSPList.Fields["Parent Project"];

                    oSPField.ShowInEditForm = true;
                    oSPField.ShowInNewForm  = true;

                    oSPField.Update();

                }
            }

 Before hide column from SharePoint list: Parent Project

Using JavaScript to Hide Form Fields:
Just edit the List form page by appending ?toolpaneview=2 at the end. Add a CEWP to the page, place this JavaScript code: (Its not written by me, BTW!)
<script language="javascript" type="text/javascript">
_spBodyOnLoadFunctionNames.push("HideColumns");

function GetControl(FieldName) 
{
   var arr = document.getElementsByTagName("!");

   for (var i=0;i < arr.length; i++ )
   {
      if (arr[i].innerHTML.indexOf(FieldName) > 0) {
          return arr[i];     
      }
   }
}

function HideColumns()
{
   var control = GetControl("Parent Project");
   control.parentNode.parentNode.style.display="none";
}
</script>



 

Sunday, April 19, 2015

Parallel Programing



December 3, 2012

Asynchronous Programming in .Net: Async and Await for Beginners

Introduction

There are several ways of doing asynchronous programming in .Net.  Visual Studio 2012 introduces a new approach using the ‘await’ and ‘async’ keywords.  These tell the compiler to construct task continuations in quite an unusual way.
I found them quite difficult to understand using the Microsoft documentation, which annoyingly keeps saying how easy they are.
This series of articles is intended to give a quick recap of some previous approaches to asynchronous programming to give us some context, and then to give a quick and hopefully easy introduction to the new keywords

Example

By far the easiest way to get to grips with the new keywords is by seeing an example.  For this initially I am going to use a very basic example: you click a button on a screen, it runs a long-running method, and displays the results of the method on the screen.
Since this article is about asynchronous programming we will want the long-running method to run asynchronously on a background thread.  This means we need to marshal the results back on to the user interface thread to display them.
In the real world the method could be running a report, or calling a web service.  Here we will just use the method below, which sleeps to simulate the long-running process:
        private string LongRunningMethod(string message)
        {
            Thread.Sleep(2000);
            return "Hello " + message;
        }
The method will be called asynchronously from a button click method, with the results assigned to the content of a label.

Coding the Example with Previous Asynchronous C# Approaches

There are at least five standard ways of coding the example above in .Net currently.  This has got so confusing that Microsoft have started giving the various patterns acronyms, such as the ‘EAP‘ and the ‘APM‘.   I’m not going to talk about those as they are effectively deprecated.  However it’s worth having a quick look at how to do our example using some of the other approaches.

Coding the Example by Starting our Own Thread

This simple example is fairly easy to code by just explicitly starting a new thread and then using Invoke or BeginInvoke to get the results back onto the UI thread.  This should be familiar to you:
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            new Thread(() => { 
                string result = LongRunningMethod("World");
                Dispatcher.BeginInvoke((Action)(() => Label1.Content = result)); 
            }).Start();
            Label1.Content = "Working...";
        }
We start a new thread and hand it the code we want to run.  This calls the long-running method and then uses Dispatcher.BeginInvoke to call back onto the user interface thread with the result and update our label.
Note that immediately after we start the new thread we set the content of our label to ‘Working…’.  This is to show that the button click method continues immediately on the user interface thread after the new thread is started.
The result is that when we click the button our label says ‘Working…’ almost immediately, and then shows ‘Hello World’ when the long-running method returns.  The user interface will remain responsive whilst the long-running thread is running.

Coding the Example Using the Task Parallel Library (TPL)

More instructive is to revisit how we would do this with tasks using the Task Parallel Library.  We would typically use a task continuation as below.
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            Task.Run<string>(() => LongRunningMethod("World"))
                .ContinueWith(ant => Label2.Content = ant.Result, 
                              TaskScheduler.FromCurrentSynchronizationContext());
            Label2.Content = "Working...";
        }
Here we’ve started a task on a background thread using Task.Run.  This is a new construct in .Net 4.5.  However, it is nothing more complicated than Task.Factory.StartNew with preset parameters.  The parameters are the ones you usually want to use.  In particular Task.Run uses the default Task Scheduler and so avoids one of the hidden problems with StartNew.
The task calls the long-running method, and does so on a threadpool thread.  When it is done a continuation runs using ContinueWith.  We want this to run on the user interface thread so it can update our label.  So we specify that it should use the task scheduler in the current synchronization context, which is the user interface thread when the task is set up.
Again we update the label after the task call to show that it returns immediately.  If we run this we’ll see a ‘Working…’ message and then ‘Hello World’ when the long-running method returns.

Coding the Example Using Async and Await

Code

Below is the full code for the async/await implementation of the example above.  We will go through this in detail.
       private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            CallLongRunningMethod();
            Label3.Content = "Working...";        
        }

        private async void CallLongRunningMethod()
        {
            string result = await LongRunningMethodAsync("World");
            Label3.Content = result;
        }

        private Task<string> LongRunningMethodAsync(string message)
        {
            return Task.Run<string>(() => LongRunningMethod(message));
        }

        private string LongRunningMethod(string message)
        {
            Thread.Sleep(2000);
            return "Hello " + message;
        }

Asynchronous Methods

The first thing to realize about the async and await keywords is that by themselves they never start a thread.  They are a way of controlling continuations, not a way of starting asynchronous code.
As a result the usual pattern is to create an asynchronous method that can be used with async/await, or to use an asynchronous method that is already in the framework.  For these purposes a number of new asynchronous methods have been added to the framework.
To be useful to async/await the asynchronous method has to return a task.  The asynchronous method has to start the task it returns as well, something that maybe isn’t so obvious.
So in our example we need to make our synchronous long-running method into an asynchronous method.  The method will start a task to run the long-running method and return it.  The usual approach is to wrap the method in a new method.   It is usual to give the method the same name but append ‘Async’.  Below is the code to do this for the method in our example:
        private Task<string> LongRunningMethodAsync(string message)
        {
            return Task.Run<string>(() => LongRunningMethod(message));
        }
Note that we could use this method directly in our example without async/await.  We could call it and use ‘ContinueWith’ on the return value to effect our continuation in exactly the same way as in the Task Parallel Library code above.  This is true of the new async methods in the framework as well.

Async/Await and Method Scope

Async and await are a smart way of controlling continuations through method scope.  They are used as a pair in a method as shown below:
        private async void CallLongRunningMethod()
        {
            string result = await LongRunningMethodAsync("World");
            Label3.Content = result;
        }
Here async is simply used to tell the compiler that this is an asynchronous method that will have an await in it.  It’s the await itself that’s interesting.
The first line in the method calls LongRunningMethodAsync, clearly.  Remember that LongRunningMethodAsync is returning a long-running task that is running on another thread.  LongRunningMethodAsync starts the task and then returns reasonably quickly.
The await keyword ensures that the remainder of the method does not execute until the long-running task is complete.  It sets up a continuation for the remainder of the method. Once the long-running method is complete the label content will update: note that this happens on the same thread that CallLongRunningMethod is already running on, in this case the user interface thread.
However, the await keyword does not block the thread completely.  Instead control is returned to the calling method on the same thread.  That is, the method that called CallLongRunningMethod will execute at the point after the call was made.
The code that calls LongRunningMethod is below:
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            CallLongRunningMethod();
            Label3.Content = "Working...";        
        }
So the end result of this is exactly the same as before.  When the button is clicked the label has content ‘Working…’ almost immediately, and then shows ‘Hello World’ when the long-running task completes.

Return Type

One other thing to note is that LongRunningMethodAsync returns a Task<string>, that is, a Task that returns a string.  However the line below assigns the result of the task to the string variable called ‘result’, not the task itself.
string result = await LongRunningMethodAsync("World");
The await keyword ‘unwraps’ the task.  We could have attempted to access the Result property of the task (string result = LongRunningMethodAsync(“World”).Result.  This would have worked but would have simply blocked the user interface thread until the method completed, which is not what we’re trying to do.
I’ll discuss this further below.

Recap

To recap, the button click calls CallLongRunningMethod, which in turn calls LongRunningMethodAsync, which sets up and runs our long-running task.  When the task is set up (not when it’s completed) control returns to CallLongRunningMethod, where the await keyword passes control back to the button click method.
So almost immediately the label content will be set to “Working…”, and the button click method will exit, leaving the user interface responsive.
When the task is complete the remainder of CallLongRunningMethod executes as a continuation on the user interface thread, and sets the label to “Hello World”.

Async and Await are a Pair

Async and await are always a pair: you can’t use await in a method unless the method is marked async, and if you mark a method async without await in it then you get a compiler warning.  You can of course have multiple awaits in one method as long as it is marked async.

Aside: Using Anonymous Methods with Async/Await

If you compare the code for the Task Parallel Library (TPL) example with the async/await example you’ll see that we’ve had to introduce two new methods for async/await: for this simple example the TPL code is shorter and arguably easier to understand.  However, it is possible to shorten the async/await code using anonymous methods, as below. This shows how we can use anonymous method syntax with async/await, although I think this code is borderline incomprehensible:
        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            new Action(async () =>
            {
                string result = await Task.Run<string>(() => LongRunningMethod("World"));
                Label4.Content = result;
            }).Invoke();
            Label4.Content = "Working...";
        }

Using the Call Stack to Control Continuations

Overview of Return Values from Methods Marked as Async

There’s one other fundamental aspect of async/await that we have not yet looked at.  In the example above our method marked with the async keyword did not return anything.  However, we can make all our async methods return values wrapped in a task, which means they in turn can be awaited on further up the call stack.  In general this is considered good practice: it means we can control the flow of our continuations more easily.
The compiler makes it easy for us to return a value wrapped in a task from an async method.  In a method marked async the ‘return’ statement works differently from usual.  The compiler doesn’t simply return the value passed with the statement, but instead wraps it in a task and returns that instead.

Example of Return Values from Methods Marked as Async

Again this is easiest to see with our example.  Our method marked as async was CallLongRunningMethod, and this can be altered to return the string result to the calling method as below:
        private async Task<string> CallLongRunningMethodReturn()
        {
            string result = await LongRunningMethodAsync("World");
            return result;
        }
We are returning a string (‘return result’), but the method signature shows the return type as Task<string>.  Personally I think this is a little confusing, but as discussed it means the calling method can await on this method.  Now we can change the calling method as below:
        private async void Button_Click_5(object sender, RoutedEventArgs e)
        {
            Label5.Content = "Working...";
            string result = await CallLongRunningMethodReturn();
            Label5.Content = result;
        }
We can await the method lower down the call stack because it now returns a task we can await on.  What this means in practice is that the code sets up the task and sets it running and then we can await the results from the task when it is complete anywhere in the call stack.  This gives us a lot of flexibility as methods at various points in the stack can carry on executing until they need the results of the call.
As discussed above when we await on a method returning type Task<string> we can just assign the result to a string as shown.  This is clearly related to the ability to just return a string from the method: these are syntactic conveniences to avoid the programmer having to deal directly with the tasks in async/await.
Note that we have to mark our method as ‘async’ in the method signature (‘private async void Button_Click_5′) because it now has an await in it, and they always go together.

What the Code Does

The code above has exactly the same result as the other examples: the label shows ‘Working…’ until the long-running method returns when it shows ‘Hello World’.  When the button is clicked it sets up the task to run the long-running method and then awaits its completion both in CallLongRunningMethodReturn and Button_Click_5.  There is one slight difference in that the click event is awaiting: previously it exited.  However, if you run the examples you’ll see that the user interface remains responsive whilst the task is running.

What’s The Point?

If you’ve followed all the examples so far you may be wondering what the point is of the new keywords.  For this simple example the Task Parallel Library syntax is shorter, cleaner and probably easier to understand than the async/await syntax.  At first sight async/await are a little confusing.
The answer is that for basic examples async/await don’t seem to me to be adding a lot of value, but as soon as you try to do more complex continuations they come into their own.  For example it’s possible to set up multiple tasks in a loop and write very simple code to deal with what happens when they complete, something that is tricky with tasks.  I suggest you look at the examples in the Microsoft documentation which do show the power of the new keywords.

Code

The full code for these examples is available to download.

Conclusion

This article has only covered the basics of the async/await keywords, although I think it’s addressed all the things that were confusing me when trying to learn about them from the Microsoft documentation.  There are some obvious things it hasn’t covered such as cancelling tasks, exception handling, unwrapping tasks (and why you might need to do that) and how to deal with the reentrancy problems that arise.  All of these are covered reasonably well in the documentation.
Personally I think async and await are far from intuitive: the compiler is performing some magic of a kind we don’t usually see in C#.  The result is that we are yielding control in the middle of a method to the calling method until some other task is complete.  Of course we can do similar things with regular task continuations, but the syntax makes regular continuations look slightly less magical.
However, async/await are a powerful way of controlling multithreaded code once you understand what they are doing.  They can make fairly complex threading look simple.
About these ads

class Program
    {
        delegate int someDel(int x);
        static void Main(string[] args)
        {

            Func<int, int> func = new Func<int, int>(testfunc);

            Console.WriteLine("before invoke");
            IAsyncResult asy = func.BeginInvoke(10, null, null);


            while (!asy.IsCompleted)
            {
               
            }
            if (asy.IsCompleted==true)
            {
                int res = func.EndInvoke(asy);
            }
            Console.WriteLine("back to main");


            Console.ReadLine();


            //someDel sd = SquareNumber;

            //Console.WriteLine("before invoke");
            //IAsyncResult asy = sd.BeginInvoke(10, null, null);

            //Console.WriteLine("back to main");

            //int res = sd.EndInvoke(asy);
            //Console.ReadLine();

            //DateTime t1 = DateTime.Now;
            //PrintPrimaryNumbers();
            //var ts1 = DateTime.Now.Subtract(t1);
            //Console.WriteLine("Finished Sync and started Async");
            //var t2 = DateTime.Now;
            //PrintPrimaryNumbersAsync();
            //var ts2 = DateTime.Now.Subtract(t2);

            //Console.WriteLine(string.Format("It took {0} for the sync call and {1} for the Async one", ts1, ts2));
            //Console.WriteLine("Any Key to terminate!!");
            //Console.ReadLine();
        }

        private static int testfunc(int a)
        {
            Console.WriteLine("square invoked new func");
            Thread.Sleep(20000);
            return a * a;
        }

      

        private static int SquareNumber(int a)
        {
            Console.WriteLine("square invoked");
            Thread.Sleep(20000000);
            return a * a;
        } 

Rate this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace Concurrency
{
    class Program
    {
        static void Main(string[] args)
        {

            DateTime t1 = DateTime.Now;
            PrintPrimaryNumbers();
            var ts1 = DateTime.Now.Subtract(t1);
            Console.WriteLine("Finished Sync and started Async");
            var t2 = DateTime.Now;
            PrintPrimaryNumbersAsync();
            var ts2 = DateTime.Now.Subtract(t2);

            Console.WriteLine(string.Format("It took {0} for the sync call and {1} for the Async one", ts1, ts2));
            Console.WriteLine("Any Key to terminate!!");
            Console.ReadLine();
        }

        public async Task DoWork()
        {
            int res = await Task.FromResult<int>(GetSum(4, 5));
        }

        private int GetSum(int a, int b)
        {
            return a + b;
        }
        private static async void PrintPrimaryNumbersAsync()
        {
            for (int i = 0; i < 10; i++)
            {
                var result = await Task.Run(() => getPrimes(i + 1, i * 10));
                //var result = await getPrimes(i + 1, i * 10);
                result.ToList().ForEach(x => Console.WriteLine(string.Format("This is generated async {0}", x)));
            }
        }
        private static void PrintPrimaryNumbers()
        {
            for (int i = 0; i < 10; i++)
                getPrimes(i + 1, i * 10)
                    .ToList().
                    ForEach(x => Console.WriteLine(string.Format("This is generated sync {0}", x)));
        }
        public static int getPrimeCount(int min, int count)
        {
            return ParallelEnumerable.Range(min, count).Count(n=>
                Enumerable.Range(2,(int)Math.Sqrt(n)-1).All(i=>
                n%i>0));
        }
        public static IEnumerable<int> getPrimes(int min, int count)
        {
            return Enumerable.Range(min, count).Where
              (n => Enumerable.Range(2, (int)Math.Sqrt(n) - 1).All(i =>
                n % i > 0));
        }
        public static Task<IEnumerable<int>> getPrimesAsync(int min, int count)
        {
             return Task.Run (()=> Enumerable.Range(min, count).Where
              (n => Enumerable.Range(2, (int)Math.Sqrt(n) - 1).All(i =>
                n % i > 0)));
        }

    }
}

---------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class _Default : Page
    {
        protected async void Page_Load(object sender, EventArgs e)
        {

            string name = "prabakarn";
            string finalValue1 = string.Empty;
            string finalValue2 = string.Empty;
           
            finalValue1 = await Task.Run(() => GetName(name));
            //finalValue2 = await Task.Run(() => GetName(name));
            RegisterAsyncTask(new PageAsyncTask(async () =>
                finalValue2 = await Task.Run(() => GetName(name))
            ));
            ExecuteRegisteredAsyncTasks();
            Response.Write(finalValue1);
            Response.Write(finalValue2);


            //var result = await getPrimes(i + 1, i * 10);
            //result.ToList().ForEach(x => Console.WriteLine(string.Format("This is generated async {0}", x)));
           
            //var client = new WebClient();
            //var content = await client.DownloadStringTaskAsync("http://www.google.com");
            //Response.Write(content);
            //

           
            //RegisterAsyncTask(new PageAsyncTask(async () =>
            //{
            //    var client = new WebClient();
            //    var content = await client.DownloadStringTaskAsync("http://www.google.com");
            //    Response.Write(content);
            //    Response.Write(name);
            //}));

            //RegisterAsyncTask(new PageAsyncTask(async () =>
            //{
            //    var client = new WebClient();
            //    var content = await client.DownloadStringTaskAsync("http://www.yahoo.com");
            //    Response.Write(content);
            //    Response.Write(name);
            //}));

           
        }

        public void Page_Loadtest()
        {
            var Client = new WebClient();
            var clientcontacts = Client.DownloadString("api/contacts");
            var clienttemperature = Client.DownloadString("api/temperature");
            var clientlocation = Client.DownloadString("api/location");


            //var contacts = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Contact>>(clientcontacts);
            //var location = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(clientlocation);
            //var temperature = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(clienttemperature);

            //listcontacts.DataSource = contacts;
            //listcontacts.DataBind();
            //Temparature.Text = temperature;
            //Location.Text = location;
        }
        private string GetName(string name)
        {
            for (int i = 0; i < 10; i++);
            Response.Write(name);
            return "hello";
        }

        //private async Task GetGizmosSvcAsync(string name)
        //{
        //    var client = new WebClient();
        //    var content = await client.DownloadStringTaskAsync("http://www.google.com");
        //    Response.Write(content);
        //}
    }
}

----------------

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" Async="true" %>

Sunday, March 8, 2015

Retrive List Data using paging



SharePoint List Pagination using SPListItemCollectionPosition


http://sharepoint.infoyen.com/2012/03/06/sharepoint-list-pagination-using-splistitemcollectionposition/

Description
This article will show you how to apply paging with sorting on search grid which gets data from sharepoint list by using SPQuery and SPListItemCollectionPosition.
Requirement:-
I have search page which is divided in 2 part; Search filter criteria and other is display result in grid. This page query to sharepoint list using object model and display result.
By thinking of performance; you will never try to get all results from sharepoint list. You have to query page by page. I mean query sharepoint list only for 10 page (page size=10) and display data.
Here I am giving detail about how to query for 10 page and get data. Then display pagination.
Precisely my page will do below things:-
1. Put caml query (only for page size which is set to 10 in my example) on sharepoint list
2. Filter on folder basis
3. Apply sorting
4. Display paging on search result page.
My hunt On Google:-
I have search on google lots but no where I find proper solution which handle sorting, paging with filter using caml query and folder query.
But still I like msdn and below 2 blogs from where I got basic understanding
http://www.directsharepoint.com/2011/03/step-by-step-guide-to-implement-paging.html
http://blogs.msdn.com/b/colbyafrica/archive/2009/02/19/learning-sharepoint-part-vi-list-pagination.aspx
The Code 
Below are 2 classes SearchDocuments and SearchPaging.
SearchDocuments: This class is code behind file my user control which manage search.
SearchPaging: This class set property for search results and search paging.

Hi Sai,

I have already mentioned the steps in article. However see below a quick glance:-

1. Create a user control, place your all filters and place grid there to see results.
2. In code behind file; write your logic to get items from sharepoint list.
3. Then bind into your grid.
4. Now the issue is paging. Now you can use my article :)

A) Use my logic to create prev and next link button link.
B) Use my logic to bind your filters
C) Use my logic to create paging info string which is constructed using PreviousPageString or nextPageString.
D) Use my method “GetAllSearch” to get document from sharepoint list.

Note: My blogs are not complete copy paste to get solution. You need to take logic and may be few functions which you can merge into your code to mitigate your business needs.
public partial class SearchDocuments : System.Web.UI.UserControl
{
public string Next
{
get { return ViewState["Next"] == null ? string.Empty : (string)ViewState["Next"]; }
set { ViewState["Next"] = value; }
}
public string Previous
{
get { return ViewState["Previous"] == null ? string.Empty : (string)ViewState["Previous"]; }
set { ViewState["Previous"] = value; }
}
// store column name for order by query
private string DataSortExpression
{
get { return ViewState["DataSortExpression"] == null ?
Constant.SearchResultColumnDocumentName : (string)ViewState["DataSortExpression"]; }
set { ViewState["DataSortExpression"] = value; }
}
// store direction; Acending or decending for order by query
private SortDirection DataSortDirection
{
get { return ViewState["DataSortDirection"] == null ?
SortDirection.Ascending : (SortDirection)ViewState["DataSortDirection"]; }
set { ViewState["DataSortDirection"] = value; }
}

/// <summary>
/// This function get call on search button and prev or next link
/// this manage paging and grid results.
/// </summary>
private void BindListData(Dictionary<string, string> searchFilters,
string pagingInfo, int currentPageNumber)
{
try
{
ViewState["CurrentPage"] = currentPageNumber.ToString();
uint rowCount = 10; //Page Size

// below 2 string format are good if you have orderby in your caml query.
string nextPageString = "Paged=TRUE&p_FSObjType=0&p_{0}={1}&p_ID={2}";
string PreviousPageString = "Paged=TRUE&p_FSObjType=0&PagedPrev=TRUE&p_{0}={1}&p_ID={2}";
/*
 below 2 string format are good if you dont have orderby in your caml query.
 string nextPageString = "Paged=TRUE&p_{0}={1}&p_ID={2}";
 string PreviousPageString = "Paged=TRUE&PagedPrev=TRUE&p_{0}={1}&p_ID={2}";
*/
int pageOrderNumber = ((currentPageNumber - 1) * Convert.ToInt32(rowCount)) + 1;
string orderBy = string.Empty;
// set order by query.
// By default DataSortExpression value is ID. but on click of sorting it change column value
if (DataSortDirection == SortDirection.Ascending)
orderBy = @"<OrderBy><FieldRef Name='" +
DataSortExpression + "' Ascending='True' /></OrderBy>";
else
orderBy = @"<OrderBy><FieldRef Name='" +
DataSortExpression + "' Ascending='False' /></OrderBy>";

// it generate caml query based on my search filters
// you can write you own logic to build caml query
string query = GetQuery(searchFilters);
query = string.Concat(query, orderBy); // add order by in query
// get folder name from you search filter criteria
string folderName = searchFilters.TryGetValue("FolderName", out folderName);

// pass paging info, query row limit in below function
// this function will return object of my custom class which hold datatable object and paging info
// Once current function ends; You will find detail about GetAllSearch function in this blog
SearchPaging searchData = GetAllSearch(query, pagingInfo, rowCount, pageOrderNumber, folderName);

if (searchData != null && searchData.SearchItems != null)
{
SPListItemCollectionPosition itemPosition = searchData.ItemCollPosition;
// ctlGrid is a object of my SPGridView
ctlGrid.DataSource = searchData.SearchItems;
ctlGrid.DataBind();
this.ResultPanel_Search.Visible = true;

//now we need to identify if this is a call from next or first
if (null != itemPosition)
{
  nextPageString =
  string.Format(nextPageString, DataSortExpression,
archData.LastItem[DataSortExpression], searchData.LastItem.ID);
}
else
{
nextPageString = string.Empty;
}

if (currentPageNumber > 1)
{
 PreviousPageString =
 string.Format(PreviousPageString, DataSortExpression,
searchData.FirstItem[DataSortExpression], searchData.FirstItem.ID);
}
else
{
PreviousPageString = string.Empty;
}

if (string.IsNullOrEmpty(nextPageString))
{
LinkButtonNext.Visible = false;
}
else
{
LinkButtonNext.Visible = true;
}

if (string.IsNullOrEmpty(PreviousPageString))
{
LinkButtonPrevious.Visible = false;
}
else
{
LinkButtonPrevious.Visible = true;
}

ViewState["Previous"] = PreviousPageString;
ViewState["Next"] = nextPageString;

string pageNumber = string.Empty;

if (currentPageNumber == 1)
pageNumber = Convert.ToString(((currentPageNumber - 1) * Convert.ToInt32(rowCount)) + 1);
else
pageNumber = Convert.ToString((currentPageNumber));

lblPaging.Text = "Page - " + pageNumber;

ctlContainerUpdatePanel.Update();

}
else
{
ctlContainerUpdatePanel.Update();
this.ResultPanel_Search.Visible = false;
this.ErrorMessageLabel.Text = "No records found";
}
}
catch (Exception ex)
{
// manage exception
}
}

/// <summary>
/// This function query to sharepoint list and return SearchPaging class object
/// which holde results and paging info
/// </summary>
private SearchPaging GetAllSearch(string queryXML, string pagingInfo, uint rowCount,
int pageOrderNumber, string folderName)
{
SPQuery query = new SPQuery();
query.Query = queryXML;
query.RowLimit = rowCount;
if (!string.IsNullOrEmpty(pagingInfo))
{
SPListItemCollectionPosition position = new SPListItemCollectionPosition(pagingInfo);
query.ListItemCollectionPosition = position;
}

query.ViewFields = string.Concat(
"<FieldRef Name='ID' />",
  "<FieldRef Name='Title' />");

// assign folder name
if (!String.IsNullOrEmpty(folderName))
{
SPFolder searchFolder = list.RootFolder.SubFolders[folderName];
query.Folder = searchFolder;
query.ViewAttributes = "Scope="Recursive"";
}

SPListItemCollection itemColl = list.GetItems(query);

// SearchPaging is my custom class which have some get set.
// i have copied code of this class in bottom for your reference

SearchPaging searchPaging = new SearchPaging(itemColl.GetDataTable()); // set result datatable
searchPaging.ItemCollPosition = itemColl.ListItemCollectionPosition; // set position object
searchPaging.FirstItem = itemColl[0]; // set first item of page
searchPaging.LastItem = itemColl[itemColl.Count - 1]; // set last item of page

return searchPaging;
}

protected void linkBtn_Search_Click(object sender, EventArgs e)
{
try
{
ViewState["Next"] = string.Empty;
ViewState["Previous"] = string.Empty;
ViewState["DataSortExpression"] = Constant.SearchResultColumnDocumentName;
// get filters and store into Dictionary object
// i store actual internal column value as key, so that i can use in my caml query
Dictionary<string, string> searchFilters = GetSearchData();
if (searchFilters.Count > 0)
{
BindListData(searchFilters, ViewState["Next"] as string, 1);
}
}
catch(Exception ex)
{
// manage exception
}
}

protected void LinkButtonPrevious_Click(object sender, EventArgs e)
{
Dictionary<string, string> searchFilters = GetSearchData();
if (searchFilters.Count > 0)
BindListData(searchFilters, ViewState["Previous"] as string, Convert.ToInt32(ViewState["CurrentPage"]) - 1);
}

protected void LinkButtonNext_Click(object sender, EventArgs e)
{
Dictionary<string, string> searchFilters = GetSearchData();
if (searchFilters.Count > 0)
BindListData(searchFilters, ViewState["Next"] as string, Convert.ToInt32(ViewState["CurrentPage"]) + 1);
}    

}

public partial class SearchPaging
{
public SPListItemCollectionPosition ItemCollPosition { get; set; }
public SPListItem FirstItem { get; set; }
public SPListItem LastItem { get; set; }
private DataTable searchItems;
public int SearchResultCount { get; set; }
public DataTable SearchItems
{
get{return searchItems;}
}

public SearchPaging() { }

public SearchPaging(DataTable SearchItems)
{
searchItems = SearchItems;
}
}

-----------------------------------------

PagingInfo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI;
using System.Text.RegularExpressions;

namespace SPListItemCollectionPositionExample
{
    public static class PagingInfo
    {
        public static void SavePageInfo(StateBag viewState, string pagingInfo)
        {
            viewState["PagingInfo"] = pagingInfo;
        }

        public static SPListItemCollectionPosition GetNextPagePosition(StateBag viewState)
        {
            string pagingInfo = string.Empty;

            if (viewState["PagingInfo"] != null)
                pagingInfo = viewState["PagingInfo"].ToString();

            return new SPListItemCollectionPosition(pagingInfo);
        }

        /// <summary>
        /// Returns the Previous Page information (not accurage when items are deleted in between / ID sequencing problem)
        /// </summary>
        /// <param name="viewState"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static SPListItemCollectionPosition GetPrevPagePosition(StateBag viewState, int pageSize)
        {
            string pagingInfo = string.Empty;

            if (viewState["PagingInfo"] != null)
            {
                pagingInfo = viewState["PagingInfo"].ToString();

                if (!string.IsNullOrEmpty(pagingInfo))
                {
                    string pIDKeyValue = new Regex("p_ID=(?'p_ID'\\d+)").Match(pagingInfo).Value;
                    string pIDValue = pIDKeyValue.Replace("p_ID=", string.Empty);
                    if (!string.IsNullOrEmpty(pIDValue))
                    {
                        int value = int.Parse(pIDValue);

                        value -= (pageSize * 2);
                        if (value < 1)
                            pagingInfo = string.Empty;
                        else
                            pagingInfo = pagingInfo.Replace(pIDKeyValue, "p_ID=" + value.ToString());
                    }
                }
            }

            return new SPListItemCollectionPosition(pagingInfo);
        }
    }
}


--------------
VisualWebPart1UserControl

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %> 
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="VisualWebPart1UserControl.ascx.cs" Inherits="SPListItemCollectionPositionExample.VisualWebPart1.VisualWebPart1UserControl" %>
<style type="text/css">
    .style1
    {
        width: 100%;
    }
</style>

<table class="style1">
    <tr>
        <td>
            <asp:Button ID="CreateDataButton" runat="server" 
                onclick="CreateDataButton_Click" Text="Create Data" Width="175px" />
            <asp:Label ID="Label1" runat="server" 
                Text="Create a Contact List of 1000 Items"></asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;</td>
    </tr>
    <tr>
        <td>
            <asp:Button ID="ShowDataButton" runat="server" Text="Show Data" 
                onclick="ShowDataButton_Click" />
            <asp:Button ID="NextPageButton" runat="server" Text="Next Page" 
                onclick="NextPageButton_Click" />
        </td>
    </tr>
    <tr>
        <td>
            <asp:GridView ID="GridView1" runat="server">
            </asp:GridView>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;</td>
    </tr>
</table>
----------------

VisualWebPart1UserControl.ascx.cs

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;

namespace SPListItemCollectionPositionExample.VisualWebPart1
{
    public partial class VisualWebPart1UserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void CreateDataButton_Click(object sender, EventArgs e)
        {
            using (SPWeb web = SPContext.Current.Web)
            {
                string listName = "Contacts 1000";
                SPList list = null;

                // Create Lists
                try
                {
                    list = web.Lists[listName];
                }
                catch
                {
                    web.Lists.Add(listName, "A Contact List of 1000 items", SPListTemplateType.Contacts);
                    list = web.Lists[listName];

                    // Create Data
                    for (int i = 1; i <= 1000; i++)
                    {
                        SPListItem item = list.Items.Add();
                        item["First Name"] = "First Name " + i.ToString();
                        item["Last Name"] = "Last Name " + i.ToString();

                        item.Update();
                    }
                }
            }
        }

        protected void ShowDataButton_Click(object sender, EventArgs e)
        {
            SPQuery query = new SPQuery();
            query.RowLimit = 10;
            query.ViewFields = "<FieldRef Name=\"Title\" />" +  /* Title is LastName column */
                            "<FieldRef Name=\"FirstName\" Nullable=\"TRUE\" Type=\"Text\"/>";
            string listName = "Contacts 1000";
            SPList list = SPContext.Current.Web.Lists[listName];

            SPListItemCollection collection = list.GetItems(query);

            PagingInfo.SavePageInfo(ViewState, collection.ListItemCollectionPosition.PagingInfo);

            GridView1.DataSource = collection.GetDataTable();
            GridView1.DataBind();
        }

        protected void NextPageButton_Click(object sender, EventArgs e)
        {
            SPQuery query = new SPQuery();
            query.RowLimit = 10;
            query.ViewFields = "<FieldRef Name=\"Title\" />" +  /* Title is LastName column */
                            "<FieldRef Name=\"FirstName\" Nullable=\"TRUE\" Type=\"Text\"/>";
            string listName = "Contacts 1000";
            SPList list = SPContext.Current.Web.Lists[listName];

            /* New */
            query.ListItemCollectionPosition = PagingInfo.GetNextPagePosition(ViewState);

            SPListItemCollection collection = list.GetItems(query);

            PagingInfo.SavePageInfo(ViewState, collection.ListItemCollectionPosition.PagingInfo);

            GridView1.DataSource = collection.GetDataTable();
            GridView1.DataBind();
        }

        protected void PrevPageButton_Click(object sender, EventArgs e)
        {
            SPQuery query = new SPQuery();
            query.RowLimit = 10;
            query.ViewFields = "<FieldRef Name=\"Title\" />" +  /* Title is LastName column */
                            "<FieldRef Name=\"FirstName\" Nullable=\"TRUE\" Type=\"Text\"/>";
            string listName = "Contacts 1000";
            SPList list = SPContext.Current.Web.Lists[listName];

            /* New */
            query.ListItemCollectionPosition = PagingInfo.GetPrevPagePosition(ViewState, 10);

            SPListItemCollection collection = list.GetItems(query);

            PagingInfo.SavePageInfo(ViewState, collection.ListItemCollectionPosition.PagingInfo);

            GridView1.DataSource = collection.GetDataTable();
            GridView1.DataBind();
        }
    }
}