Wednesday, December 17, 2014

Counting occurences of Javascript array elements

var arr = [2, 2, 2, 2, 2, 4, 5, 5, 5, 9];

function foo(arr) {
    var a = [], b = [], prev;
   
    arr.sort();
    for ( var i = 0; i < arr.length; i++ ) {
        if ( arr[i] !== prev ) {
            a.push(arr[i]);
            b.push(1);
        } else {
            b[b.length-1]++;
        }
        prev = arr[i];
    }
   
    return [a, b];
}

var result = foo(arr);
document.write('[' + result[0] + ']<br>[' + result[1] + ']')

[2,4,5,9]
[5,1,3,1]

Monday, December 8, 2014

asp.net pie chart hide image or change background color to transparent

1 ) Image 1


2) Image 2
 3) Code

   <asp:Chart ID="Chart1" runat="server" Height="200px" Width="300px" OnClick="Chart1_Click"
                                BackColor="Transparent" PageColor="Transparent">
                                <Titles>
                                    <asp:Title ShadowOffset="3" Name="Items" />
                                </Titles>
                                <Series>
                                    <asp:Series Name="Default" />
                                </Series>
                                <ChartAreas>
                                    <asp:ChartArea Name="ChartArea1" BorderWidth="0" BackColor="Transparent">
                                        <AxisX>
                                            <MajorGrid Enabled="False" />
                                        </AxisX>
                                        <AxisY>
                                            <MajorGrid Enabled="False" />
                                        </AxisY>
                                    </asp:ChartArea>
                                </ChartAreas>
                                <Legends>
                                    <asp:Legend Alignment="Center" Docking="Right" IsDockedInsideChartArea="false" IsTextAutoFit="true"
                                        Name="Default" LegendStyle="Table">
                                    </asp:Legend>
                                </Legends>
                            </asp:Chart>

Wednesday, December 3, 2014

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

In your web.config, make sure these keys exist:

<configuration>
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
    </system.webServer>
</configuration>

Tuesday, December 2, 2014

asp.net dropdown add select option

   if (dsRiskCategories.Tables[0].Rows.Count > 0)
                {
                    DataRow dr = dsRiskCategories.Tables[0].NewRow();
                    dr["CategoryId"] = "0";
                    dr["CategoryName"] = "Select Risk Category";
                    dsRiskCategories.Tables[0].Rows.InsertAt(dr, 0);
                }

                ddlCategory.DataSource = dsRiskCategories;
                ddlCategory.DataTextField = "CategoryName";
                ddlCategory.DataValueField = "CategoryId";
                ddlCategory.DataBind();

Saturday, November 29, 2014

asp.net edit command field with css and image

 <asp:CommandField ButtonType="Image" EditText="Edit" EditImageUrl="~/images/Edit.jpg"
                            HeaderStyle-CssClass="centerText" ItemStyle-CssClass="centerText" ControlStyle-CssClass="editIconSize"
                            HeaderText="Edit" ShowEditButton="True" ShowCancelButton="false" UpdateImageUrl="~/images/save.jpg" />

Thursday, November 27, 2014

Select nth row of a table in sql server

SELECT * FROM (
     SELECT     ROW_NUMBER() OVER (ORDER BY CategoryId) AS RowNo,CategoryId, CategoryName, LessThan, GreaterThan, AdvisorId, CategoryRating
          FROM CategoryMapping
WHERE     (AdvisorId = 1)

 ) AS foo
WHERE RowNo= 2

asp.net gridview get column data from datatable

 for (int i = 0; i < tableQuestion.Rows.Count; i++)
            {
 string answer = tableQuestion.Rows[i]["Sanswer"].ToString();
}

asp.net gridview hide and show linkbutton in template field

ASPX -

 <asp:TemplateField HeaderText="Publish">
                        <ItemTemplate>
                            <asp:Label ID="lblStatus" Text='<%# Eval("Status") %>' runat="server" Visible="false"></asp:Label>
                            <asp:LinkButton ID="linkpublishQues" runat="server" CommandArgument='<%#Eval("QuestionId")%>'
                                CommandName="Publish" OnClientClick="return confirm('Do you want to publish this question?')">Publish</asp:LinkButton>
                            <asp:LinkButton ID="linkunpublishQues" runat="server" CommandArgument='<%#Eval("QuestionId")%>'
                                CommandName="UnPublish" OnClientClick="return confirm('Do you want to unpublish this question?')">UnPublish</asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>


.CS -

 Label lblStatus = e.Row.FindControl("lblStatus") as Label;

                if (lblStatus.Text == "Save")
                {
                    LinkButton linkunpublishQues = (LinkButton)e.Row.FindControl("linkunpublishQues");
                    LinkButton linkpublishQues = (LinkButton)e.Row.FindControl("linkpublishQues");
                    linkunpublishQues.Visible = false;
                    linkpublishQues.Visible = true;

                }
                else if (lblStatus.Text == "Publish")
                {
                    LinkButton linkunpublishQues = (LinkButton)e.Row.FindControl("linkunpublishQues");
                    LinkButton linkpublishQues = (LinkButton)e.Row.FindControl("linkpublishQues");
                    linkunpublishQues.Visible = true;
                    linkpublishQues.Visible = false;
                }

asp.net gridview change update button text on commandfield edit button

  <asp:CommandField HeaderText="Edit" ShowEditButton="True"  UpdateText="Save" />

asp.net gridview hide cancel button in commandfield edit button

  <asp:CommandField HeaderText="Edit" ShowEditButton="True" ShowCancelButton="false"
                            />

Sunday, November 23, 2014

asp.net editable nested gridview

asp.net Difference between Convert.ToString() and .ToString()

Convert.ToString() handles null, while ToString() doesn't.

asp.net clear all session

 public void ClearSession()
        {
            HttpContext.Current.Session.Clear();
        }

asp.net remove from session

 public void RemoveFromSession(string key)
        {
            HttpContext.Current.Session.Remove(key);
        }

asp.net update value in session

 public void UpdateInSession(string key, object value)
        {
            HttpContext.Current.Session[key] = value;
        }

asp.net set value in session

   public void SetInSession(string key, object value)
        {
            if (HttpContext.Current == null || HttpContext.Current.Session == null)
            {
                return;
            }
            HttpContext.Current.Session[key] = value;
        }

asp.net get value from session

  public object GetFromSession(string key)
        {
            if (HttpContext.Current == null || HttpContext.Current.Session == null)
            {
                return null;
            }
            return HttpContext.Current.Session[key];
        }

asp.net create separate class for session handling

  //added by shekhar 13/6/2014 To Clear Current Session
        public void ClearSession()
        {
            HttpContext.Current.Session.Clear();
        }
        //End Of Clear Session
        //added by shekhar 13/6/2014 To Remove item in session
        public void RemoveFromSession(string key)
        {
            HttpContext.Current.Session.Remove(key);
        }
        //end Of remove  

        public void SetInSession(string key, object value)
        {
            if (HttpContext.Current == null || HttpContext.Current.Session == null)
            {
                return;
            }
            HttpContext.Current.Session[key] = value;
        }

        public object GetFromSession(string key)
        {
            if (HttpContext.Current == null || HttpContext.Current.Session == null)
            {
                return null;
            }
            return HttpContext.Current.Session[key];
        }

        public void UpdateInSession(string key, object value)
        {
            HttpContext.Current.Session[key] = value;
        }

asp.net convert data from object to string

  string advisorId = Convert.ToString(_webcontext.GetFromSession("AdvisorId"));

asp.net abstract data from dataset

 ds = _categorymappingpresenter.getCategories(advisorId);

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                category_entity.AdvisorId = Convert.ToString(_webcontext.GetFromSession("AdvisorId"));
                category_entity.Action = "U";
                category_entity.CategoryName = ds.Tables[0].Rows[i]["CategoryName"].ToString();
                category_entity.CategoryRating = ds.Tables[0].Rows[i]["Id"].ToString();
                category_entity.CategoryId = Convert.ToInt32(ds.Tables[0].Rows[i]["CategoryId"]);
                category_entity.Result = _categorymappingpresenter.addModifyCategory(category_entity);

            }

asp.net for loop on dataset

 ds = _categorymappingpresenter.getCategories(advisorId);

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                category_entity.AdvisorId = Convert.ToString(_webcontext.GetFromSession("AdvisorId"));
                category_entity.Action = "U";
                category_entity.CategoryName = ds.Tables[0].Rows[i]["CategoryName"].ToString();
                category_entity.CategoryRating = ds.Tables[0].Rows[i]["Id"].ToString();
                category_entity.CategoryId = Convert.ToInt32(ds.Tables[0].Rows[i]["CategoryId"]);
                category_entity.Result = _categorymappingpresenter.addModifyCategory(category_entity);

            }

asp.net find Textbox text from gridview row

  category_entity.CategoryName = ((TextBox)GridView1.Rows[e.RowIndex]
                               .FindControl("txtCategoryName")).Text;

asp.net find label text from gridview row

  category_entity.CategoryId = Convert.ToInt32(((Label)GridView1.Rows[e.RowIndex]
                               .FindControl("lblCategoryId")).Text);

Tuesday, October 28, 2014

SharePoint App Deployment error : 'Failed to install app for SharePoint' There was a problem with activating the app web definition

It is because SharePoint is trying to activate your app as a standard SharePoint feature, when its really an App.
In the features folder of the SharePoint project, there will be a Feature named Feature1.
Open Feature1 and ensure it's contained in the "Items in the solution" list and not in the "Items in the feature" list.
After that you should be able to deploy.

Friday, October 10, 2014

Exporting and Importing SharePoint Designer 2010 List Workflow

Exporting and importing of the List Workflow to and from another list or site is actually a non-supported feature. However, there is a "workaround" to achieve this.
  1. In SharePoint Designer 2010, click on your completed List Workflow.
  2. Click on "Save" and "Publish" for the completed List Workflow.
  3. Next, click on "Export to Visio". Save the file as CompletedWorkflow.vwi or any preferred name.
  4. Then create a new "similar" list on the current site or on a new site collection. There is no way to import the exported visio into this new list.
  5. In SharePoint Designer 2010, click on this new list and then click on "List Workflow" to create a new workflow for this new list.
  6. Please make sure that you do not add any workflow steps!
  7. Click on "Save" and "Publish" for this empty List Workflow.
  8. Then, click on "Export to Visio" and save this as EmptyWorkflow.vwi or any preferred name.
  9. Rename both the vwi files by adding ".zip" extension. The files should be CompletedWorkflow.vwi.zip and EmptyWorkflow.vwi.zip.
  10. The objective is to replace the "workflow.xoml.wfconfig.xml" file from the EmptyWorkflow.vwi.zip into the CompletedWorkflow.vwi.zip.
  11. It is likely that you cannot replace it directly. Copy the file out to the desktop and then copy the file into the other zipped folder.
  12. Remove the ".zip" extension from the CompletedWorkflow.vwi.
  13. With this, we have a working importable visio List Workflow.
  14. Back in the SharePoint Designer 2010, close all the workflow tabs.
  15. Click on the "Import from Visio" and select the CompletedWorkflow.vwi.
  16. You have successfully exported and imported the List Workflow!

Thursday, August 21, 2014

Get Item count in array using jquery

   GetItemCountInArray: function (myArr, item) {

        num = 0;
        for (i = 0; i <= myArr.length; i++) {
            if (myArr[i] == item)
                num++;
        }
        return num;

    }

Wednesday, August 20, 2014

get unique values from array jquery

   GetUnique: function (inputArray) {
        var outputArray = [];
        for (var i = 0; i < inputArray.length; i++) {
            if ((jQuery.inArray(inputArray[i], outputArray)) == -1) {
                outputArray.push(inputArray[i]);
            }
        }
        return outputArray;
    }

Find length (size) of an array in jquery

var itemArr = new Array();

 alert(itemArr.length);

Delete Item From Custom list By caml query sharepoint 2013

   deleteDataFromListByQuery: function (customListName, query, columns) {

        var scriptbase = hostUrl + "/_layouts/15/";
        $.getScript(scriptbase + 'SP.Runtime.js',
        function () {
            $.getScript(scriptbase + 'SP.js',
           function () {
               $.getScript(scriptbase + 'SP.RequestExecutor.js', deleteItem);
           });
        });

        function deleteItem() {

            var context;
            var factory;
            var appContextSite;
            var mylist;
            context = new SP.ClientContext(appweburl);
            factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
            context.set_webRequestExecutorFactory(factory);
            appContextSite = new SP.AppContextSite(context, hostUrl);
            this.web = appContextSite.get_web();
            mylist = this.web.get_lists().getByTitle(customListName);//Custom List Name
            var camlQuery = new SP.CamlQuery();
            camlQuery.set_viewXml(query);
            var collListItem = mylist.getItems(camlQuery);
            context.load(mylist);
            context.load(collListItem);

            context.executeQueryAsync(

                function () {


                    var listItemEnumerator = collListItem.getEnumerator();
                    var counter = 0;
                    var itemArr = new Array();
                    var id;
                    while (listItemEnumerator.moveNext()) {

                        var listItem = listItemEnumerator.get_current();

                        //itemArr[counter] = listItem.get_item("ID");

                        //counter++;
                        id = listItem.get_item('ID');

                        var spItem = mylist.getItemById(id);

                        spItem.deleteObject();


                    }

                    //        for (var id in itemArr) {

                    //            var spItem = mylist.getItemById(itemArr[id]);

                    //            spItem.deleteObject();

                    //        }


                    context.executeQueryAsync(

                function () {

                    alert('success');


                },
            function () {
                error();
            });



                },
            function () {
                error();
            });
        }

    }

Delete Item from custom list in sharepoint 2013 using Caml query and JSOM

1) function deleteItem(id) {

    //REST.Common.deleteDataFromParentList(customlist.TravelRequestlist, id);
    var department = 52;
    var customListName = 'TMS_AirBooking';//Custom List Name
    var query = '<View><Query><Where><Eq><FieldRef Name=\'Travel_Req_No\'/>' +
'<Value Type=\'Number\'>' + department + '</Value></Eq></Where></Query><RowLimit>10</RowLimit></View>';
    var columns = ['Travel_Req_No'];



    deleteDataFromChildList(customListName, query, columns);
    // alert(id + ',' + 'TravelRequests');
}


2) deleteDataFromChildList: function (customListName, query, columns) {

        var scriptbase = hostUrl + "/_layouts/15/";
        $.getScript(scriptbase + 'SP.Runtime.js',
        function () {
            $.getScript(scriptbase + 'SP.js',
           function () {
               $.getScript(scriptbase + 'SP.RequestExecutor.js', deleteItem);
           });
        });
     
        function deleteItem() {

            var context;
            var factory;
            var appContextSite;
            var mylist;
            context = new SP.ClientContext(appweburl);
            factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
            context.set_webRequestExecutorFactory(factory);
            appContextSite = new SP.AppContextSite(context, hostUrl);
            this.web = appContextSite.get_web();
            mylist = this.web.get_lists().getByTitle(customListName);//Custom List Name
            var camlQuery = new SP.CamlQuery();
            camlQuery.set_viewXml(query);
            var collListItem = mylist.getItems(camlQuery);
            context.load(mylist);
            context.load(collListItem);

            context.executeQueryAsync(

                function () {


                    var listItemEnumerator = collListItem.getEnumerator();
                    var counter = 0;
                    var itemArr = new Array();

                    while (listItemEnumerator.moveNext()) {

                        var listItem = listItemEnumerator.get_current();

                        itemArr[counter] = listItem.get_item("ID");

                        counter++;

                    }

                    for (var id in itemArr) {

                        var spItem = mylist.getItemById(itemArr[id]);

                        spItem.deleteObject();

                    }


                    context.executeQueryAsync(

                function () {

                    alert('success');


                },
            function () {
                error();
            });

                },
            function () {
                error();
            });
        }

    }

Wednesday, August 13, 2014

Popup in sharepoint 2013 with ModalDialog

openDialog: function (id) {
       
        SP.UI.ModalDialog.showModalDialog({
            url: "Edit.aspx?ID=" + id + "&SPHostUrl=" + hostUrl + "&SPAppWebUrl=" + appweburl + "",
            title: "Edit",
            allowMaximize: false,
            showClose: true,
            width: 400,
            height: 200
        });
       
    }

Tuesday, August 12, 2014

set textbox value in jquery

$("#s1").val("Glenn Quagmire");

get data row from custom list in sharepoint 2013

getDataRowFromCustomListUsingId: function (customListName, id) {

        var scriptbase = hostUrl + "/_layouts/15/";
        $.getScript(scriptbase + 'SP.Runtime.js',
        function () {
            $.getScript(scriptbase + 'SP.js',
           function () {
               $.getScript(scriptbase + 'SP.RequestExecutor.js', getDataById);
           });
        });

        //Read Data From Custom List - Host Web
        function getDataById() {

            var context;
            var factory;
            var appContextSite;
            var mylist;
            var targetListItem;
            context = new SP.ClientContext(appweburl);
            factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
            context.set_webRequestExecutorFactory(factory);
            appContextSite = new SP.AppContextSite(context, hostUrl);
            this.web = appContextSite.get_web();
            mylist = this.web.get_lists().getByTitle(customListName);//Custom List Name          
            targetListItem = mylist.getItemById(id);
            context.load(targetListItem);
            context.executeQueryAsync(

                function () {

                    editsuccess(targetListItem);

                },
                function () {
                    error();
                });
        }
    }

check undefined variable in jquery

var id = decodeURIComponent(getQueryStringParameter("ID"));

    alert(id);
    if (id != 'undefined') {
        alert('success');
    }
    else {
        alert('fail');
    }

Monday, August 11, 2014

Get Peoplepicker content using JSOM in sharepoint 2013

var html = $("#ctl00_PlaceHolderMain_docReviewerUser_upLevelDiv"); params['DocReviewerLoginName'] = $("#divEntityData", html).attr("key");

Sunday, August 10, 2014

Caml query example with Person or Group (By Name) sharepoint 2013

1) Person or Group (By Name)
2) Value Type - Text
<Query>
<Where>
<Eq>

<FieldRef Name=\'Title\'/>'

      '<Value Type=\'Text\'>Shekhar</Value>

</Eq>
</Where>
</Query>

Caml query example withMultiple Lines of Text sharepoint 2013

1) Multiple Lines of Text
2) Value Type - Text
<Query>
<Where>
<Contains>

<FieldRef Name=\'Title\'/>'

      '<Value Type=\'Text\'>Shekhar</Value>

</Contains>
</Where>
</Query>

Caml query example with Single line of text sharepoint 2013

1) Single line of text

Value Type - Text

<Query>
<Where>
<Eq>
<FieldRef Name=\'Title\'/>'
      '<Value Type=\'Text\'>Shekhar</Value>
</Eq>
</Where>

</Query>

Caml Query Operators Sharepoint 2013

Operators
Some list of operators used in SPQuery

  1. Eq--Equals
  2. Neq--Not equal
  3. Gt--Greater than
  4. Geq--Greater than or equal
  5. Lt--Lower than
  6. Leq--Lower than
  7. IsNull--Is null
  8. BeginsWith--Begins with
  9. Contains--Contains

Thursday, August 7, 2014

return in javascript function

<!DOCTYPE html>
<html>
<body>



<p id="demo"></p>

<script>
function myFunction(a, b) {
    return a * b;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>

</body>
</html>
This example calls a function which performs a calculation, and returns the result:12

Wednesday, August 6, 2014

Jquery DatePicker example 2

<html lang="en">
<head>
<style >
div.ui-datepicker{
 font-size:11px;
}
</style>
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
  <script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>

  <script>

  $(function() {
    $( "#fromdatepicker" ).datepicker();
    $( "#todatepicker" ).datepicker();
  });
$(function() {
$("#btnFilter").click(function() {
 var startDate = $("#fromdatepicker").datepicker("getDate");
 startDate  =  startDate.getFullYear()+"-"+(startDate.getMonth()+1)+"-"+startDate.getDate();

 var endDate = $("#todatepicker").datepicker("getDate");
 endDate  =  endDate.getFullYear()+"-"+(endDate.getMonth()+1)+"-"+endDate.getDate();

 alert(startDate +"-"+ endDate);
});
});
  </script>
</head>
<body>

<p>
From Date: <input type="text" id="fromdatepicker" style="font-size:11px"  />
To Date: <input type="text" id="todatepicker" style="font-size:11px"  /> &nbsp;&nbsp;&nbsp;
<input type="button" id="btnFilter" value="Generate Report">
</p>


</body>
</html>
jQuery UI Datepicker - Default functionality From Date: To Date:    

Datepicker example Jquery

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</head>
<body>
<p>Date: <input type="text" id="datepicker"></p>
</body>
</html>
jQuery UI Datepicker - Default functionality Date: