Search This Blog

Wednesday, 19 June 2013

Highlight a textbox when focused using JavaScript

Refer below code, where we attach an event dynamically at the time of page loads

<script language="javascript" type="text/javascript">
    function fnTXTFocus(varname) {

        var objTXT = document.getElementById(varname)
        objTXT.style.borderColor = "Red";

    }

    function fnTXTLostFocus(varname) {
        var objTXT = document.getElementById(varname)
        objTXT.style.borderColor = "White";
    }

    function fnOnLoad() {
        var t = document.getElementsByTagName('INPUT');
        var i;
        for (i = 0; i < t.length; i++) {
            if (t[i].type == "text") {
                t[i].attachEvent('onfocus', new Function("fnTXTFocus('" + t[i].id + "')"));
                t[i].attachEvent('onblur', new Function("fnTXTLostFocus('" + t[i].id + "')"));
            }
        }
    }
</script>
<body onload="fnOnLoad()">
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    UserName ::
                </td>
                <td>
                    <asp:TextBox ID="txtUN" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Password ::
                </td>
                <td>
                    <asp:TextBox ID="txtPwd" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Confirm Password ::
                </td>
                <td>
                    <asp:TextBox ID="txtCpwd" runat="server"></asp:TextBox>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>

The above JavaScript:

Finds the list of textboxes and stores it in an array.
Attaches the OnFocus and OnBlur events to each textbox in the list.

So now, whenever a textbox gets/loses focus, the assigned function will fire.


You can download a sample from here

SharePoint 2010 download multiple files as zip

SharePoint 2010 does not support multiple files download at a single point. There we have an option called “download a copy”, but it used to download a single file only. We have one more option called “Open with Explorer”, where we can copy & paste multiple files, but it has its own limitation, the main thing is, browser compatibility, Yeah – this option cannot work with most of the browser, other than IE.

So we need to find any alternative way for this. While searching, I found this blog; it’s very simple and easy to use. The user provided explained this feature with source code. To deploy and test, they provided wsp, so we can easily download and test this custom feature. To know more about this custom feature, please visit above link. To download wsp and install in your machine, please go ahead.

  1.   Download wsp from here
  2.   Open SharePoint 2010 Management Shell (Run as Administrator)
  3.   Add the solution
    1. Add-SPSolution “\FilePath\”
  4.  Deploy the solution
    1. Install-SPSolution “Solution Name” –gacdeployment
  5.  Go to your Application site
  6.  Site Actions à Site Settings à Site collection features à DeviantPoint Download Zip Feature and activate this feature


Refer below screenshot for reference


                    7. Now you can see new option called “Download as Zip” in Document Library ribbon.



Reference

http://www.deviantpoint.com/post/2010/05/08/SharePoint-2010-Download-as-Zip-File-Custom-Ribbon-Action.aspx

Download Wsp

https://sites.google.com/site/memysharepoint/home/DeviantPoint.DownloadZip.wsp?attredirects=0&d=1

Download Solution

https://sites.google.com/site/memysharepoint/home/DeviantPoint.DownloadZip.zip?attredirects=0&d=1

Monday, 17 June 2013

Restore deleted Site and Site Collection in SharePoint 2010

Recently one of teammates has deleted Root Site Collection instead of deleting sub site. Then we get “HTTP 404 not found” error.



 So, I referred this blog. It helps me to know the PowerShell script to recover the deleted site collection.

Restore deleted sites
Go to Site Actions à Site Settings à Recycle bin (under Site Collection Administrator)
Change the view to “Deleted from end user Recycle Bin” option


Note: you need to be a site collection administrator in order to be able to access this recycle bin.

Restore deleted site collection

For this process you need to be a farm administrator as the process is performed from the SharePoint 2010 Management Shell on the SharePoint Servers. There are three PowerShell commands to take note of for this operation. They are:

Get-SPDeletedSite – this command gets a list of all deleted Site Collections in your farm.
Restore-SPDeletedSite – this command is used to restore a deleted Site Collection within your farm
Remove-SPDeletedSite  – this command is used to actually clear out any deleted Site Collection you no longer want to keep (think "Empty Recycle Bin").

Please refer below snapshot for an idea.


Reference

Delete a SharePoint group programmatically

To delete a SharePoint group using object model, below is the code snippet in c#.


// objSPWeb is SPWeb object
objSPWeb.SiteGroups.Remove(groupName);
(or)
objSPWeb.Groups.Remove(groupName);

objSPWeb.Update();

Thursday, 6 June 2013

Calling postback event from JavaScript


I had a situation to force page post back via JavaScript; this has been for a SharePoint Web Part as there is an issue sometimes with a second post back being disabled. Also found it helpful for when doing a SharePoint dialog callback.

Then I referred this link http://gowrishaan.wordpress.com/2009/05/20/calling-postback-event-from-javascript/, here they gave an idea to fire the postback event from JavaScript. The key is

__doPostBack(“ ”,””);

What does __doPostBack() method do?
It is very clear from the above method definition that the method accepts 2 arguments, eventTarget and eventArgument. These arguments values are in turn populated to hidden fields, __EVENTTARGET and __EVENTARGUMENT.
__EVENTTARGET
This field is populated with the ID of the control that raises the postback in order to identify it by the server.
__EVENTARGUMENT

How to Raise a Postback from JavaScript?
To do this, we need to just call the __doPostBack() function from our javascript code.
Refer below,
<script type="text/javascript">
        function CallServer() {
               __doPostBack('','');
        }
    </script>

When the above function is called, it will raise a postback to server.
Note
Sometimes, when the above code is executed we may get the below error,
Microsoft JScript runtime error: Object expected

As i said earlier, ASP.Net runtime will insert the definition of __doPostBack() automatically only when there is a control that can initiate a postback in the page. In this case, your page might not have a control that can raise the postback. ASP.Net is brilliant enough so that it outputs the __doPostBack() function only if there is a control that can raise postback.
We will move to the next section and understand how we can take care of these scenarios.

Emitting __doPostBack()  postback method manually
The ClientScriptManager class released in .NetFramework has method called GetPostBackEventReference() which can emit the definition of __doPostBack method into our page. Include the below code in your page load,
protected void Page_Load(object sender, EventArgs e)
    {
        ClientScript.GetPostBackEventReference(this, "");
    }

The above code will insert the __doPostBack() method into your webpage.

Raising a Control Event
Sometimes, you may have a scenario where you may need to raise a control’s event from a javascript based on some business logic. For example, if you want to raise a DropDownList Selected Index changed event or a LinkButton click event manually, then you can call __doPostBack() method by passing its ID. Refer the below code.
<script type="text/javascript">
        function CallServer() {
               __doPostBack('lbDoPostBack','');
        }
    </script>

You should pass the UniqueID of the control when you have associated master page in the __doPostBack() method above.
When you call __doPostBack() method without any argument (as in section Raising Postback from Javascript) then it will call only the Page_Load event.

More on __EVENTARGUMENT
As i said earlier, the controls can use this argument to send some additional information to the server.  Read the msdn article here where they have used this argument to know the id of the element that raised the postback when there is a custom control that has more than one postback element.
OR
We can use this argument to identify whether the postback is triggered by the control or by the javascript. In the above example(Refer previous section), i have said that we can raise an event of a page control from javascript based on some business logic. Suppose, if we want to differentiate the postback raised by the control and javascript, we can use the __EventArgument parameter.

<script type="text/javascript">
        function CallServer() {
            __doPostBack('lbDoPostBack', 'JavaScript');
          
        }
    </script>
CodeBehind
 protected void lbDoPostBack_Click(object sender, EventArgs e)
    {
        if(Request["__EVENTARGUMENT"] == "JavaScript")
        {
            Response.Write("Called by Javascript!!");
        }
        else
        {
            Response.Write("Called by LinkButton!!");
        }
    }

The above code will actually throw a security exception like below,
Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

To overcome this error, use the ClientScript.RegisterForEventValidation() method of ClientScriptManager class to say the server that the event originating is trusted.
Refer below,
protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {
        ClientScript.RegisterForEventValidation("lbDoPostBack", "JavaScript");
        base.Render(writer);
    }
Include the above code in your codebehind.

You can download sample .Net Application from here
You can download sample SharePoint Webpart from here

Reference

Wednesday, 5 June 2013

Add, Delete Items in Dropdown List, List Box using JavaScript

In some occasions you may want to add one or more options to dropdown/list box and sometimes remove items from a dropdown/list box. You can use a simple JavaScript code to add/remove options from a dropdown/list box. Following examples describe how to dynamically change items in a dropdown/list box.

Code: (aspx)

<asp:DropDownList ID="DropDownList1" runat="server" Width="182px">
<asp:ListItem Value="1" Text="Approve"></asp:ListItem>
<asp:ListItem Value="2" Text="Accept"></asp:ListItem>
<asp:ListItem Value="3" Text="Test1"></asp:ListItem>
<asp:ListItem Value="4" Text="Test2"></asp:ListItem>
</asp:DropDownList>

<input type="button" value="Remove selected item" onclick="JavaScript: DeleteItem();" />
<input type="text" id="ddlText" name="ddlText" />
<input type="text" id="ddlValue" name="ddlValue" />
<input type="button" value="Add item" onclick="JavaScript: AddItem();" />
<input type="hidden" id="ddlElements" name="ddlElements" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button(Postback)" />

<script type="text/javascript">
   function DeleteItem() {
var dropDownListRef = document.getElementById('<%= DropDownList1.ClientID %>');
       var optionsList = '';
if (dropDownListRef.value.length > 0) {
   var itemIndex = dropDownListRef.selectedIndex;
          if (itemIndex >= 0)
             dropDownListRef.remove(itemIndex);
       }
       else {
          alert('Please select an item');
          dropDownListRef.focus();
          dropDownListRef.select();
       }
       for (var i = 0; i < dropDownListRef.options.length; i++) {
          var optionText = dropDownListRef.options[i].text;
          var optionValue = dropDownListRef.options[i].value;

          if (optionsList.length > 0)
              optionsList += ';';
          optionsList += optionText;
          optionsList += ';';
          optionsList += optionValue;
       }
       document.getElementById('<%= ddlElements.ClientID %>').value = optionsList;
   }


   function AddItem() {
       var dropDownListRef = document.getElementById('<%= DropDownList1.ClientID %>');
       var ddlTextRef = document.getElementById('ddlText');
       var ddlValueRef = document.getElementById('ddlValue');
       var optionsList = '';

       if (ddlTextRef.value != "" && ddlValueRef.value != "") {
           if (!isOptionAlreadyExist(document.getElementById('<%= DropDownList1.ClientID %>'), ddlValueRef.value)) {
               var option1 = document.createElement("option");
               option1.text = ddlTextRef.value;
               option1.value = ddlValueRef.value;
               dropDownListRef.options.add(option1);
           }
           else {
               alert("Value " + ddlTextRef.value + " already exists");
           }
       }
       else
           alert('Please enter values');
       for (var i = 0; i < dropDownListRef.options.length; i++) {
           var optionText = dropDownListRef.options[i].text;
           var optionValue = dropDownListRef.options[i].value;
           if (optionsList.length > 0)
               optionsList += ';';
           optionsList += optionText;
           optionsList += ';';
           optionsList += optionValue;
       }
       document.getElementById('<%= ddlElements.ClientID %>').value = optionsList;

   }
   function isOptionAlreadyExist(listBox, value) {
       var exists = false;
       for (var x = 0; x < listBox.options.length; x++) {
           if (listBox.options[x].value == value || listBox.options[x].text == value) {
               exists = true;
               break;
           }
       }
       return exists;
   }


</script>

In Code behind Page_Load, add following code..

Client-side changes to a Drop Down List/List Box are not persisted server-side, so any changes made will be lost if a Post Back occurs. Added server-side persistence to code.

if (IsPostBack)
            {
                DropDownList1.Items.Clear();
                string[] DropDownListArray = ddlElements.Value.Trim().Split(';');

                for (int i = 0; i < DropDownListArray.Length; i = i + 2)
                {
                    string itemText = DropDownListArray[i];
                    string itemValue = DropDownListArray[i + 1];
                    DropDownList1.Items.Add(new ListItem(itemText, itemValue));
                }

            }

            string optionsList = string.Empty;
            for (int i = 0; i < DropDownList1.Items.Count; i++)
            {
                string optionText = DropDownList1.Items[i].Text;
                string optionValue = DropDownList1.Items[i].Value;

                if (optionsList.Length > 0)

                    optionsList += ";";
                optionsList += optionText;
                optionsList += ';';
                optionsList += optionValue;
            }

            ddlElements.Value = optionsList;

You can download a sample web Application from here.

Reference: