Wednesday, July 28, 2010

Filter multiple List Columns & also by specific columns

Add a Content Editor webpart to the page with the following script in the Source Editor:


<script src="http://www.google.com/jsapi"></script>

<script>

google.load("jquery", "1.2.6");google.setOnLoadCallback(function() {

$(document).ready(function(){

jQuery.extend(jQuery.expr[':'], { containsIgnoreCase: "(a.textContent

a.innerText

jQuery(a).text()

'').toLowerCase().indexOf((m[3]

'').toLowerCase())>=0"

});





$("table.ms-listviewtable tr.ms-viewheadertr").each(function()

{
if($("td.ms-vh-group", this).size() > 0){return;}
var tdset = "";var colIndex = 0;
$(this).children("th,td").each(function()

{

//modify the test columns here....
if( ($(this).hasClass("ms-vh-icon")) ||($(this).text()== "col2") || ($(this).text() == "col3") )

{// attachment
tdset += "<td></td>";
}else

{// filterable
tdset += "<td><input type='text' class='vossers-filterfield' filtercolindex='" + colIndex + "' /></td>";
}

colIndex++;
});

var tr = "<tr class='vossers-filterrow'>" + tdset + "</tr>";
$(tr).insertAfter(this);
});



$("input.vossers-filterfield")

.css("border", "1px solid #7f9db9")
.css("width", "100%").css("margin", "2px")
.css("padding", "2px").keyup(function()
{
var inputClosure = this;
if(window.VossersFilterTimeoutHandle)
{
clearTimeout(window.VossersFilterTimeoutHandle);
}

window.VossersFilterTimeoutHandle = setTimeout(function()

{

var filterValues = new Array();

$("input.vossers-filterfield", $(inputClosure).parents("tr:first")).each(function()

{

if($(this).val() != "")

{
filterValues[$(this).attr("filtercolindex")] = $(this).val();
}

});

$(inputClosure).parents("tr.vossers-filterrow").nextAll("tr").each(function()

{

var mismatch = false;


$(this).children("td").each(function(colIndex)
{
if(mismatch) return;

if(filterValues[colIndex])
{
var val = filterValues[colIndex];

// replace double quote character with 2 instances of itself

val = val.replace(/"/g, String.fromCharCode(34) + String.fromCharCode(34));

if($(this).is(":not(:containsIgnoreCase('" + val + "'))"))

{
mismatch = true;

}

}

});


if(mismatch)

{

$(this).hide();

}

else

{

$(this).show();

}

});



}, 250);

});

});


});


</script>

Thanks to http://instantlistfilter.codeplex.com/

Monday, July 12, 2010

Modify form labels, Hide or remove columns in SharePoint form

In the CEWP or on the new item page or on the Display.aspx add the following script

<script type="text/javascript" src="http://YourServer/sites/yourSubsite/JQuery/jquery-1.4.2.min.js"></script>
<script type="text/javascript">

fields = init_fields();

var dateTypeLabel = "<div style='color:red'>Please enter the Date Type. (...custom text added by adressing the formlabel with jQuery!)</div>"
var applicationLabel = "<div style='color:red;font-size:9px;'><i>Please enter the Application Name</i></div>";

//Can change more field labels similarly & all the variables defined are the field Internal names


$(fields['DateType']).find(".ms-formlabel h3").after(dateTypeLabel);
$(fields['ApplicationName']).find(".ms-formlabel h3").after(applicationLabel);
// after appends the content whereas .text() changes the existing field label to new label

//Can also append text to labels on hover

//$(fields['DateType']).find(".ms-formlabel h3").hover(
//   function(){     $(fields['DateType']).find(".ms-formlabel h3").append(dateTypeLabel);  },
//   function(){     $(fields['DateType']).find(".ms-formlabel h3").text("DateType");       }
//)

// Hide the Current user label display ( to show only selected labels )
//$(fields['Current_x0020_User']).find(".ms-formlabel h3").parent().parent().hide();
////$(fields['Current_x0020_User']).find(".ms-formlabel h3").parent().parent().hide();

//Set Status(like color,font...) of  Few or Many columns at a time
var arrCFC = ["Col1", "Col2",  "Col3", "Col8", "Col9", "Col12", "Col13", "Col14"];

           //  All these columns, labels here are turned blue
          jQuery.each(arrCFC, function() {
               $(fields[this]).find(".ms-formlabel h3").parent().parent().css("color","Blue");
               $(fields[this]).find(".ms-formlabel h3").css("color","Blue");
  
             });

function init_fields(){
  var res = {};
  $("td.ms-formbody").each(function(){
      if($(this).html().indexOf('FieldInternalName="')<0) return;
      var start = $(this).html().indexOf('FieldInternalName="')+19;
      var stopp = $(this).html().indexOf('FieldType="')-7;
      var nm = $(this).html().substring(start,stopp);
      res[nm] = this.parentNode;
  });
  return res;
}
</script>

Reference:  http://sharepointjavascript.wordpress.com/2009/10/03/modify-formlabel-in-sharepoint-form/
(By Alexander)

Wednesday, July 7, 2010

Jquery - Adding Tabs with each tab refers to a new page

//Download all the necessary plugins from Jquery UI: http://jqueryui.com/download
<script type="text/javascript" src="Javascript/JQuery/jquery-1.4.2.js"></script>
    <script type="text/javascript" src="Javascript/JQuery/jquery.ui.widget.js"></script>
    <script type="text/javascript" src="Javascript/JQuery/jquery.ui.tabs.js"></script>
    <link type="text/css" href="Javascript/JQuery/jquery-ui-1.8.2.custom.css" rel="stylesheet" >
   
    <style type="text/css" >
    ul.tabs {
    margin: 0;
    padding: 0;
    float: left;
    list-style: none;
    height: 32px; /*--Set height of tabs--*/
    border-bottom: none;
    border-left: 1px solid #999;
    width: 100%;
}
ul.tabs li {
    float: left;
    margin: 0;
    padding: 0;
    height: 31px; /*--Subtract 1px from the height of the unordered list--*/
    line-height: 31px; /*--Vertically aligns the text within the tab--*/
    border: 1px solid #999;
    border-left: none;
    margin-bottom: -1px; /*--Pull the list item down 1px--*/
    overflow: hidden;
    position: relative;
    background: #e0e0e0;
}
ul.tabs li a {
    text-decoration: none;
    color: #000;
    display: block;
    font-size: 1.2em;
    padding: 0 20px;
    border: 1px solid #fff; /*--Gives the bevel look with a 1px white border inside the list item--*/
    outline: none;
}
ul.tabs li a:hover {
    background: #ccc;
}
html ul.tabs li.active, html ul.tabs li.active a:hover  { /*--Makes sure that the active tab does not listen to the hover properties--*/
    background: #fff;
    border-bottom: 1px solid #fff; /*--Makes the active tab look like it's connected with its content--*/
}
   
   
    .tab_container {
   
    border: none;
    overflow: hidden;
    clear: both;
    float: left; width: 100%;
    background: #fff;
}
.tab_content {
    padding: 20px;
    font-size: 1.2em;
}
    </style>
   
   

<ul class="tabs">
    <li><a href="#tab1" onClick="parent.location='/sites/.../..../AllItems.aspx'">Tab 1</a></li>
    <li><a href="#tab2" onClick="parent.location='/.../.../Page2.aspx'">Tab 2</a></li>
    <li><a href="#tab3" onClick="parent.location='/sites/.../.../Page3.aspx'">Tab 3</a></li>
    <li><a href="#tab4" onClick="parent.location='/sites/.../.../Page4.aspx'">Tab 4</a></li>
</ul>

<div class="tab_container">
    <div id="tab1" class="tab_content">
        <!--Content-->
                This is a Colloboration site for Page 1 Team Members. This is the Content in Page 1 &amp; Tab 1
    </div>
    <div id="tab2" class="tab_content">
       <!--Content-->
       This is the Home Page for Page 2. This is the Content in Page 1 &amp;     Tab2
    </div>
</div>








<script type="text/javascript">
$(document).ready(function() {

    //When page loads...
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab & li:eq(1) to show second url
    $(".tab_content:first").show(); //Show first tab content

    //On Click Event
    $("ul.tabs li").click(function() {

        $("ul.tabs li").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content
        var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
        $(activeTab).fadeIn(); //Fade in the active ID content
        return false;
    });
});
</script>

Tuesday, June 29, 2010

Jquery: List Items QuickView

 hoverImg = '/_layouts/images/OPENDB.GIF';
      hoverImgDescription = 'Hover mouse over this image to preview the metadata';
                              // The description text added to the top of the page.
                              // If left blank, no description is added to the top of the page.
      arrOfFieldsToShow = ['Title','Description']; // Leave blank to show all fields. To have only the content and not the label, use this format ['Title|0']
      prependHoverImageTo = ''; // The standard placement is "Title-field" for lists and "Name-field" for document library.
                                  // If used with multi line text with append, insert FieldInternalName of "append-field" here.



function getLoadedFields(){
  var res = {};
  $("#jLoadMe td.ms-formbody").each(function(){
      if($(this).html().indexOf('FieldInternalName="')<0) return;
      var start = $(this).html().indexOf('FieldInternalName="')+19;
      var stopp = $(this).html().indexOf('FieldType="')-7;
      var nm = $(this).html().substring(start,stopp);
      res[nm] = {'label':nm,'html':$(this).html()};
  });
  return res;
}

function jLoadMe(t,pX,pY,listBaseType) {//load content
if(listBaseType==0){
    var whatToLoad = " #part1";
}else if(listBaseType==1){
    var whatToLoad = " #onetIDListForm";
}
    $("#jLoadMe").load(t + whatToLoad, function() {
        if(arrOfFieldsToShow.length==0){
            $("#jLoadMe").css({'width':'590'});
            $("#jLoadMe h3").css({'font-size':'8pt'});
            $("#jLoadMe .ms-formtoolbar:first").hide();
            $("#jLoadMe table.ms-toolbar").hide();
            $("#jLoadMe .ms-ButtonHeightWidth").hide();
            var contentWidth = '590';
            var contentHeight = $("#jLoadMe").height();
        }else{
            $("#jLoadMe h3").css({'font-size':'8pt'});
            var contentWidth = '400';
            var selectedRow = '';
            $.each(arrOfFieldsToShow,function(idx,item){
                var split = item.split('|');
                var fieldTitle = split[0];
                var showTitle = split[1];
                jLoadMeFields = getLoadedFields();
               
               
                if(showTitle!=0){
                    selectedRow += "<b>" + jLoadMeFields[fieldTitle].label + "</b>" + " - ";
                }
                selectedRow += jLoadMeFields[fieldTitle].html + "</br>";
            });
            selectedRow = "<div style='width:" + contentWidth + "'>" + selectedRow + "</div>";




            //    if(showTitle!=0){
                //    selectedRow += "<div style='font-weight:bold;border-bottom:1px silver solid;'>" + jLoadMeFields[fieldTitle].label + "</div>";
            //    }
            //    selectedRow += "<div style='padding:0 0 5 3;margin-left:5;border-left:1px silver solid'>" + jLoadMeFields[fieldTitle].html + "</div>";
        //    });
        //    selectedRow = "<div style='width:" + contentWidth + "'>" + selectedRow + "</div>";
            $("#jLoadMe").html(selectedRow);
            var contentHeight = $("#jLoadMe").height();
        }
        // Get height and width of current window
        var winHeight = $(window).height();
        var winWidth = $(window).width();
        var winScroll = $(window).scrollTop();
        // Calculate the best position for the popup Y-axis
        if((winHeight - pY) < contentHeight){
            if((pY - winScroll) < contentHeight){
                pY = winScroll + 10
            }else{
                pY = (pY - contentHeight) - 30
            }
        }
        // Calculate the best position for the popup X-axis
        if((winWidth - pX) < contentWidth){
            pX = (pX - contentWidth) - 30;
        }
        // Show popup
        $("#jLoadMe")
            .css({'position':'absolute',
                'left':pX,
                'top':pY,
                'background-color':'f8f8ff',
                'border':'2px silver ridge',
                'padding':3})
            .show().mouseenter(function(){
                $(this).hide();
            });
    });
}

function initjLoadMe() { // Loop trough all elements and add hover function
isAppendField = false;
    $("div[id^='WebPartWPQ']").each(function(){
        var thisListCTX = $(this).find("table[ctxname]:first").attr('ctxname');
        if(thisListCTX!=undefined){
            thisListCTX = eval(thisListCTX);
            var listBaseType = thisListCTX.listBaseType;
            if(listBaseType==0){ // List
                if(prependHoverImageTo!=''){// Apend style field
                    whatToFind = "a[href$='SPBookmark_" + prependHoverImageTo + "']";
                    isAppendField = true;
                }else{
                    var whatToFind = "a[href*='DispForm.aspx'][target='_self']";
                }
            }else if(listBaseType==1){ // Document library
                var whatToFind = "td.ms-vb-title";
            }
        }else if($(this).find("a[href*='DispForm.aspx']").length>0){ // Catch calendar views
            var listBaseType = 0;
            var whatToFind = "a[href*='DispForm.aspx'][target='_self']";
        }

        $(this).find(whatToFind).each(function(){
            if($(this).parent().find(".mouseOverImg").length==0){
                if(listBaseType==0){
                    if(isAppendField){
                        var url = $(this).attr("href");
                        url = url.substring(0,url.indexOf('#'));
                    }else{
                        var url = $(this).attr("href");
                        if(url.indexOf('#')>-1) return;
                    }
                    //$(this).before("<a href='" + url + "'><img class='mouseOverImg' src='" + hoverImg + "' height='8' width='8' border='0'></a>&nbsp;");
                }else if(listBaseType==1){
                    // Get id of item from table id
                    var table = $(this).find('table:first');
                    var tableId = table.attr('id');
                    var url = eval(table.attr('ctxname')).displayFormUrl+"?ID=" + tableId;
                    //$(this).find('a').before("<a href='" + url + "'><img class='mouseOverImg' src='/_layouts/images/OPENDB.GIF' height='8' width='8' border='0'></a>&nbsp;&nbsp;");
                }
                // Hover function
                $(this).parent().hover(function(e){
                    posX = e.pageX + 10;
                    posY = e.pageY + 15;
                    jLoadMe(url,posX,posY,listBaseType)
                },
                function(){
                    $("#jLoadMe").html('').hide();
                });
            }
        });
    });
}

$(document).ready(function() {
    // Add description above ms-bodyareaframe
    //if(hoverImgDescription!=''){
    //    $("#onetidPageTitle").append("<div style='font-size:xx-small;float:right;margin:-12 0 0 0'><img src='" + hoverImg + "' height='8' width='8'>&nbsp;" + hoverImgDescription + "&nbsp;</div>");
    //}
    $(".ms-bodyareaframe").append("<div id='jLoadMe' style='display:none;'></div>");
    window.onerror = handleError; // needed for IE
    initjLoadMe();
});

function handleError() { // fn needed for IE
    return true;
}

// Attaches a call to the function to the "expand grouped elements function" for it to function in grouped listview's
function ExpGroupRenderData(htmlToRender, groupName, isLoaded){
    var tbody=document.getElementById("tbod"+groupName+"_");
    var wrapDiv=document.createElement("DIV");
    wrapDiv.innerHTML="<TABLE><TBODY id=\"tbod"+groupName+"_\" isLoaded=\""+isLoaded+"\">"+htmlToRender+"</TBODY></TABLE>";
    tbody.parentNode.replaceChild(wrapDiv.firstChild.firstChild,tbody);
initjLoadMe();
}

Friday, June 25, 2010

Redirecting a site in Sharepoint to another site

Redirect a SharePoint site by using the Content Editor Web Part

In the Content Editor Webpart and in the Source Editor in any sharepoint page from where the redirect should happend, add the following script:
(1)automatic redirect:
<script language="JavaScript">
alert("This site has been moved to another location, please update existing bookmarks. You will be redirected momentarily.");
window.location.href="http://serverTobeRedirectTo"
</script>
(2)with specific timeframe set:
<script language="JavaScript">

function getgoing()
  {
    top.location="http://serverTobeRedirectTo";
   }

   if (top.frames.length==0)
    {
     alert("This site has been moved to another location, please update existing bookmarks. You will be redirected in 10 Seconds.!");
     setTimeout('getgoing()',10000);
     }
</script>


Links Referred:
http://www.endusersharepoint.com/2010/01/20/redirect-a-sharepoint-site-by-using-the-content-editor-web-part/
http://www.dnzone.com/go?565









Wednesday, June 9, 2010

Jquery - Reading Data from XML or JSON data types

(1) Upload files in document library upload json.json and Topics.xml in the root level site.


(2) JSON.JSON:

{
    topics:{
          topic:[
               'Select Topic',
               '1 - Testing Json!',
               '2 - Analysis Statement',
                 '3 - Another element',
              ]
         }
}


(3) TOPICS.XML:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<Topics>
        <Topic>Select Topic</Topic>
        <Topic>1 - Testing Json!</Topic>
        <Topic>2 - Analysis Statement</Topic>
         <Topic>3 - Another element</Topic>
</Topics>



(4) Jquery would be:


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function()

{

     //Binding Json Data using Jquery
       $.getJSON('http://YourServer/DocumentLibrary/json.json', function(data)
      {

         var numItems = data.topics.topic.length // To Count the number of elements in particular node
        //Iterate through all the elements in that particular node
          for(i=1;i<numItems;i++)
         {
            $("<option value='SELECT'>" + data.topics.topic[i] + "</option>").appendTo("#ddlTopic");
           //Binding it to another dropdown with id ddlTopic
          }
        });



//Binding XML data using Jquery

      $.ajax(
      {

         type:"GET",
         url:"http://YourServer/DocumentLibrary/Topics.xml",
         dataType:"xml",
         success:function(xml){

          $(xml).find('Topic').each(function(){
          var topic = $(this).text();
           //Binding it to another dropdown with id ddTopic

            $("<option value='SELECT'>" + topic + "</option>").appendTo("#ddTopic");
      
              }); // end each() loop
          } // end success
  }); // end ajax()

});//end ready()

</script>

Friday, May 28, 2010

Applying a SharePoint Designer Workflow to multiple Lists

When using SharePoint Designer to create a workflow you are required to bind the workflow to a particular list:

The problem is that you cannot from this interface bind the workflow to other lists. You might be tempted to use the “Save List as Template” option in the List’s settings, and then create a new list based on this template to create a list that uses the workflow. The problem is that the workflow is still bound to the list from which the new list is based, and an error will probably be generated whenever you try to start an instance of the workflow – the steps will try to reference items etc. in the original list. In SharePoint Designer you can expand out the files associated with a workflow:
The “.xoml.wfconfig.xml” file contains information on the list the workflow is bound to using the List’s ID (a GUID): association XMLtag listid = 32bit GUID tasklistid=32bit GUID startmanually="true" The file “.xoml.rules” contains the ‘conditions’ you program for the workflow and the “.xoml” file contains the ‘actions’. The “.aspx” form is displayed when the workflow is started manually. To re-use a workflow in another list: Create a new workflow on the new list. Create at least one step, one condition and one action in this workflow. This ensures that the files shown above are created and they will be replaced by the next operations. From the original workflow open the .xoml file as XML and copy the entire contents to the clipboard. Open the .xoml file for the new workflow and replace the entire contents with the copy from (3). Repeat this operation for the xoml.rules file. Double click the .xoml file for the new workflow to open the workflow in the Workflow Designer and click Check Workflow to verify no errors and then click Finish to ensure the workflow is saved. Also, Once done with all the changes make sure the lookup items doesnt point to existing list. Just double click on it and will point to current list. http://vspug.com/agoodwin/2008/08/11/no-options-to-save-workflows-as-templates-in-sharepoint-designer/

Thursday, April 15, 2010

Delete ContentType from a Library

This is a Console Application. Build it and .exe file is generated. Can move to other environments with running .exe from where it is added. ChangeContentType.exe http://YourBox/ TempLib 1stContentType(Form) NewContentType DestinationLibrary static void Main(string[] args) { try { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(args[0])) //"http://YourBox/")) { using (SPWeb web = site.RootWeb) { //args[1] = TempLib //Create a temporary Library, where we move all the Destination Library list items. web.Lists.Add(args[1], args[1], SPListTemplateType.DocumentLibrary); SPList destLib = web.Lists[args[1]]; SPList list = web.Lists[args[1]]; //"DestinationLib"]; //Move all the list items from "DestinationLib" to "TempLib". int count = list.Items.Count; for (int j = count; j >0; j--) { SPFile file = list.Items[j-1].File; file.MoveTo(web.Url + "/" + args[1]+ "/" + file.Name); } try { //Remove "Form" 1st Content Type. args[2]="Form" SPContentType cTypeToBeRemovedForm = list.ContentTypes[args[2]]; //"1stContentType"]; list.ContentTypes.Delete(cTypeToBeRemovedForm.Id); //Remove "SecondContentType" Content Type. args[3] = SecondContentType SPContentType cTypeToBeRemoved = list.ContentTypes[args[3]]; //"SecondContentType"]; list.ContentTypes.Delete(cTypeToBeRemoved.Id); //Add "NewContentType" Content Type from the web. SPContentType cTypeToBeAdded = web.ContentTypes[args[3]]; //"ContentTypefromweb"; list.ContentTypes.Add(cTypeToBeAdded); list.Update(); } catch (Exception ex) { Console.WriteLine(ex.Message); } //Move all the list items from "TempLib" to "DestinationLib". // args[4]= DestinationLib int tempCount = destLib.Items.Count; for (int j = count; j > 0; j--) { SPFile file = destLib.Items[j-1].File; file.MoveTo(web.Url + "/" + args[4] + "/" + file.Name); } web.Lists[args[1]].Delete(); } } }); } catch (Exception e) { Console.WriteLine("Exception Message - " + e.Message + "\nInner Exception - " + e.InnerException + "\nStack Trace - " + e.StackTrace); } }

Monday, March 22, 2010

Code Snippets

Get list Items: /// Gets a collection of list items that match the query from the specified list, regardless of the permissions of the current user /// The server-relative path to the list /// The CAML query that has to be run against the list /// An SPListItemCollection object that represents the resulting list items public static SPListItemCollection GetSecuredListItems(string ListServerRelativePath, string CamlQuery) { if (string.IsNullOrEmpty(ListServerRelativePath)) throw new ArgumentNullException("The server-relative path to the list is required for this function"); SPListItemCollection results = null; string listAbsoluteURL = SPContext.Current.Site.MakeFullUrl(ListServerRelativePath); SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(listAbsoluteURL)) { using (SPWeb web = site.OpenWeb()) { SPList list = web.GetList(ListServerRelativePath); SPQuery query = new SPQuery(); query.Query = CamlQuery; results = list.GetItems(query); } } }); return results; } Update List Item: /// Updates a single item for a single field on a list, even if the current user doesn't have the access /// The server-relative path to the list /// The internal ID of the item to be updated /// The display name of the field to be updated /// The new value that has to be applied for the field /// The SPListItem object that contains the list item that was updated public static SPListItem UpdateSecuredListItem(string ListServerRelativePath, string ID, string FieldName, string Value) { if (string.IsNullOrEmpty(ListServerRelativePath)) throw new ArgumentNullException("The server-relative path to the list is required for this function"); int id; if (!int.TryParse(ID, out id)) throw new ArgumentException("The ID specified is not valid (ID = " + ID + ")."); SPListItem result = null; string listAbsoluteURL = SPContext.Current.Site.MakeFullUrl(ListServerRelativePath); SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(listAbsoluteURL)) { using (SPWeb web = site.OpenWeb()) { web.AllowUnsafeUpdates = true; SPList list = web.GetList(ListServerRelativePath); SPField field = list.Fields[FieldName]; if (field == null) throw new ArgumentException("The FieldName specified (" + FieldName + ") is not valid for the List (" + list.Title + ")."); result = list.GetItemById(id); if (result != null) result[FieldName] = Value; else throw new ArgumentException("There is no listitem with the specified ID (ID = " + ID + ")."); result.Update(); web.AllowUnsafeUpdates = false; } } }); return result; } Delete List Permissions namespace DeleteListPermissions { class Program { static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("\n\n Invocation: DeleteListPermissions "); return; } //Get SPWeb object SPSite Site = new SPSite(args[0]); //e.g., "http://myserver/mysite" SPWeb Web = Site.OpenWeb(); //Get SPListItem SPList List = Web.Lists[args[1]]; //e.g., "Announcements" Console.WriteLine("\n\nList " + args[1] + " found-- Starting Permission Deletion"); //Check for permission inheritance, and break if necessary if (!List.HasUniqueRoleAssignments) { List.BreakRoleInheritance(false); //pass true to copy role assignments from parent, false to start from scratch } List.Update(); Console.WriteLine("Done...."); } } }

Wednesday, March 17, 2010

STSADM Commands

Retract Solution: stsadm -o retractsolution -n YourWSP.wsp Remove Solution: stsadm -o deletesolution -n YourWSP.wsp Add Solution: stsadm -o addsolution -f YourWSP.wsp Deploy Solution: stsadm -o deploysolution -n YourWSP.wsp -allowgacdeployment -immediate at the End do: stsadm -o execadmsvcjobs iisreset pause

Monday, March 15, 2010

TimerJob, Feature Receiver, Feature and Batch Files to Install Timer Job

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

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace PubFormLibraryTimer {
public class FormLibraryTimerJob : SPJobDefinition
{
private const string Event_Source = "FormLibraryTimerJob";

 public FormLibraryTimerJob () : base() { }
  public FormLibraryTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType) : base (jobName, service, server, targetType) { }
public FormLibraryTimerJob(string jobName, SPWebApplication webApplication) : base (jobName, webApplication, null, SPJobLockType.ContentDatabase)
{ this.Title = jobName; }
public override void Execute(Guid targetInstanceId)
{
            DateTime fromTime = DateTime.Now.AddMinutes(-5);
DateTime toTime = DateTime.Now;
SPWebApplication webApplication = this.Parent as SPWebApplication;
SPContentDatabase contentDb = webApplication.ContentDatabases[targetInstanceId];
SPList formsLibraryList = contentDb.Sites[0].RootWeb.Lists["YourFormLibrary"];
            SPQuery oQuery = new SPQuery();
            oQuery.Query = "" + toTime + "" + "" + fromTime + "";
SPListItemCollection collListItems = formsLibraryList.GetItems(oQuery);
this.LogEventMessage(collListItems.Count);
}

  private void LogEventMessage(int count)
{
if (!EventLog.SourceExists(Event_Source))
{ EventLog.CreateEventSource(Event_Source, "Application"); }
EventLog.WriteEntry(Event_Source, "Your Form Library Modified Forms Count In Last 5 mins - " + count.ToString(), EventLogEntryType.Information);
}
}
}






Feature Receiver:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace YourFormLibraryTimer
{

public class FormsLibraryTimerJobFeatureReceiver : SPFeatureReceiver
{
private const string LOGGER_JOB_NAME = "FormLibraryTimerJob"; public override void FeatureInstalled (SPFeatureReceiverProperties properties) { } public override void FeatureUninstalling (SPFeatureReceiverProperties properties) { } public override void FeatureActivated (SPFeatureReceiverProperties properties) { SPSite site = properties.Feature.Parent as SPSite; foreach (SPJobDefinition job in site.WebApplication.JobDefinitions) { if (job.Name == LOGGER_JOB_NAME) job.Delete(); } FormLibraryTimerJob loggerJob = new FormLibraryTimerJob(LOGGER_JOB_NAME, site.WebApplication); SPMinuteSchedule schedule = new SPMinuteSchedule(); schedule.BeginSecond = 0; schedule.EndSecond = 59; schedule.Interval = 5; loggerJob.Schedule = schedule; loggerJob.Update(); } public override void FeatureDeactivating (SPFeatureReceiverProperties properties) { SPSite site = properties.Feature.Parent as SPSite; foreach (SPJobDefinition job in site.WebApplication.JobDefinitions) { if (job.Name == LOGGER_JOB_NAME) job.Delete(); } } } } Feature: ?xml version="1.0" encoding="utf-8" ? Feature Id="{DD1D417C-746B-4793-BA4E-A95F156E1E30}" Title="Form Library Timer Job" Description="Installs Form Library Timer Job" Version="1.0.0.0" Scope="Site" ReceiverAssembly="YourFormLibraryTimer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=68d32dec24dfb1a9"ReceiverClass="YourFormLibraryTimer.FormsLibraryTimerJobFeatureReceiver" xmlns="http://schemas.microsoft.com/sharepoint/" / Installing Timer Job in Batch Files: @SET TEMPLATEDIR="c:\program files\common files\microsoft shared\web server extensions\12\Template" @SET STSADM="c:\program files\common files\microsoft shared\web server extensions\12\bin\stsadm" @SET GACUTIL="C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\gacutil.exe" Echo Installing PubFormLibraryTimer.dll in GAC %GACUTIL% -if bin\debug\YourFormLibraryTimer.dll Echo Copying files to TEMPLATE directory xcopy /e /y TEMPLATE\* %TEMPLATEDIR% %STSADM% -o installfeature -filename FormLibraryTimerJob\feature.xml -force %STSADM% -o activatefeature -filename FormLibraryTimerJob\feature.xml -force -url http://localhost:91IISRESET

Thursday, March 4, 2010

Adding Columns to a List Programatically

Add Columns / Fields Programmatically to a SharePoint List You can think of a SharePoint List somewhat similar to a table present within a Database. As tables consist of different columns, a SharePoint List also comprises of different columns / fields and these fields can indeed have different attributes associated to it (like "Required field check", "Max Length", "Display Formats", etc). We can use SharePoint API to create these fields and associate the corresponding attributes programmatically within an existing List. Provided below is a code snippet in C#.Net describing the same. using (SPSite oSPsite = new SPSite("http://Web-URL")) { oSPsite.AllowUnsafeUpdates = true; using (SPWeb oSPWeb = oSPsite.OpenWeb()) { oSPWeb.AllowUnsafeUpdates = true; /* get the SPList object by list name*/ SPList lst = oSPWeb.Lists["EmpList"]; /* create a Numeric field for EmpID */ SPFieldNumber fldEmpID = (SPFieldNumber)lst.Fields.CreateNewField( SPFieldType.Number.ToString(), "EmpID"); fldEmpID.Required = true; fldEmpID.DisplayFormat = SPNumberFormatTypes.NoDecimal; /* create a Text field for Name */ SPFieldText fldName = (SPFieldText)lst.Fields.CreateNewField( SPFieldType.Text.ToString(), "Name"); fldName.Required = true; fldName.MaxLength = 50; /* create a Date field for Dob*/ SPFieldDateTime fldDob = (SPFieldDateTime)lst.Fields.CreateNewField( SPFieldType.DateTime.ToString(), "Dob"); fldDob.DisplayFormat = SPDateTimeFieldFormatType.DateOnly; /* create a Currency field for Salary */ SPFieldCurrency fldSal = (SPFieldCurrency)lst.Fields.CreateNewField( SPFieldType.Currency.ToString(), "Salary"); fldSal.Currency = SPCurrencyFieldFormats.UnitedStates; fldSal.DisplayFormat = SPNumberFormatTypes.TwoDecimals; /* add the new fields to the list */ lst.Fields.Add(fldEmpID); lst.Fields.Add(fldName); lst.Fields.Add(fldDob); lst.Fields.Add(fldSal); /* finally update list */ lst.Update(); oSPWeb.AllowUnsafeUpdates = false; } oSPsite.AllowUnsafeUpdates = false; } Adding Hyperlink Column to a SharePoint List Example 1: Set the url field of a link Use the SPFieldUrlValue class to create an object that holds the url to link to, and the title to display: SPList list = web.Lists["Links"]; SPListItem newLink = list.Items.Add(); SPFieldUrlValue value = new SPFieldUrlValue(); value.Description = "Click Me"; value.Url = "http://www.microsoft.com/sharepoint"; newLink["URLColumn"] = value; //URLColumn that we have added on the list newLink.Update(); Example 2: Get the url field of a link Use the SPFieldUrlValue class to create an object that gets the url and description: SPList list = web.Lists["Links"]; SPListItem existingLink = list.Items[0]; SPFieldUrlValue value = new SPFieldUrlValue(existingLink["URL"].ToString()); string linkTitle = value.Description; string linkURL = value.Url; Example 3: Add Choice Column to a List or Document Library programatically Considering lstCustomList is your list object and you have set AllowUnsafeUpdate() to true for the web object. We are adding two choices in the choice column. First we will add choice column itself to the list and then we will add the choices in that column and update the field. The main point to taken in to consideration is that it is SPFieldChoice not the SPField. lstCustomList.Fields.Add("ABC", SPFieldType.Choice, false); lstCustomList.Update(); SPFieldChoice objChoiceCol = (SPFieldChoice)lstCustomList.Fields["ABC"]; string[] strdata = new string[2]; strdata[0] = "Open"; strdata[1] = "Close"; objChoiceCol.Choices.Add(strdata[0]); objChoiceCol.Choices.Add(strdata[1]); objChoiceCol.Update(); lstCustomList.Update();

Wednesday, March 3, 2010

Return Items from a List

(1)The following example returns all the items for a specified Events list. It assumes the existence of a text box that can be used to type the name of an Events list. SPWeb mySite = SPContext.Current.Web; SPListItemCollection listItems = mySite.Lists[TextBox1.Text].Items; for (int i=0;i"); } (2)You can also use one of the GetItems methods of the SPList class to return a subset of items from a list. The following example returns only Title column values where the Stock column value surpasses 100. SPWeb mySite = SPContext.Current.Web; SPList list = mySite.Lists["Books"]; SPQuery query = new SPQuery(); query.Query = "100"; SPListItemCollection myItems = list.GetItems(query); foreach (SPListItem item in myItems) { Response.Write(SPEncode.HtmlEncode(item["Title"].ToString()) + " "); } (3)Cross-List Queries You can perform cross-list queries to query more efficiently for data across multiple Web sites. The following example uses the SPSiteDataQuery class to define a query, and then uses the GetSiteData method to return items where the Status column equals "Completed". SPWeb webSite = SPContext.Current.Web; SPSiteDataQuery query = new SPSiteDataQuery(); query.Lists = ""; query.Query = "" + "Completed"; System.Data.DataTable items = webSite.GetSiteData(query); foreach (System.Data.DataRow item in items) { Response.Write(SPEncode.HtmlEncode(item["Title"].ToString()) + " "); }

Wednesday, February 24, 2010

What's New in Infopath 2010

Link Referred: http://blogs.msdn.com/infopath/archive/2009/07/15/what-s-new-in-infopath-2010.aspx Microsoft InfoPath 2010 makes it easier than ever to design electronic forms. InfoPath now includes the Office Fluent UI and allows the creation of powerful, interactive forms, without having to write any code. With a few clicks, Office users can customize SharePoint list forms, add custom layouts and rules to validate the data, and take them offline in SharePoint Workspace. IT professionals can create custom forms for document workflows and Office Business Applications that include managed code, digital signatures and that connect to line of business data. In InfoPath 2010, we’ve made some big investments to make it much easier to build rich forms-based applications on top of the SharePoint Server 2010 platform. Quickly Design Forms with Easy-to-Use Tools New features to help you quickly and easily create forms include our new Fluent UI, pre-built layout sections, out-of-the-box rules, improved rules management, and varied styles. The New tab in the Designer Backstage presents you with the available form templates that you can choose from. Most templates start you off with a default layout table. Stay tuned for more details on our new and improved form design features! Layout your Forms Using Pre-built Page and Section Layouts Laying out your form and making it look more attractive is now easier than ever. Insert one of our pre-built page layouts to give your form structure. Then, insert some section layouts into the page layout to start building your form. Page and Section Layouts in InfoPath Designer:
New and Improved Controls We’ve added some new controls and narrowed the feature gap between client and browser forms, ensuring a more consistent form filling experience for all our users.
New controls in InfoPath 2010 include: Picture buttons – Instead of the default gray button, use any image as a button in your form. Hyperlink capabilities –Allow users to insert their own hyperlinks when filling out forms. Date and time picker – Allow users to insert dates and times in their forms Person/Group pickers – Updated! This is now a first class control and is included by default in the Controls gallery. Signature Line (Editor Only) – Allow users to digitally sign a form Controls and functionality that are now supported in browser forms include: Bulleted, numbered, and plain lists, multiple selection list boxes, Combo boxes, Choice group and sections, and Filtering functionality. Add Rules to your Forms With our new out-of-the-box rules (or quick rules) and improved rules management UI, you can easily add rules to validate data, format your form, or perform other actions with just a couple of clicks, and without any code. Quick Rules in InfoPath Designer: Publish Forms Quickly Our new “quick” publish functionality allows you to publish forms in a single click (no more clicking through the Publishing Wizard every time you want to make an update to your forms!) Create Forms for SharePoint Lists Using InfoPath, you can now extend and enhance the forms used for creating, editing and viewing items in a SharePoint list. In a browser, simply navigate to a SharePoint list, and on the SharePoint Ribbon under List Tools, choose the Customize Form option. This will automatically generate a form which looks very similar to the default out-of-the-box SharePoint list form. You can then customize and enhance this form by modifying the layout, creating additional views or pages, and adding rules to validate your data, show or hide sections of the form or set a fields value (to name just a few of the options). Example of Customized SharePoint List Form: Stay tuned for more details on SharePoint List Customization! We recommend using a form associated with a SharePoint list when possible. This provides the most straightforward design and form management experience. However, there are more complex scenarios where using a form associated with a form library is preferred e.g. if your form has a complex schema or if you need to add code to your form. Create SharePoint Applications With InfoPath 2010, SharePoint Server 2010, and SharePoint Designer 2010, you can easily create powerful team, departmental or enterprise applications on top of SharePoint Server. Form-based applications: InfoPath forms can be integrated with components such as workflow, reporting, and custom Web pages to create rich form-based applications. Document Workflows: InfoPath can be used to design custom workflow initiation and task forms that drive document management processes. Business Connectivity Services: Integrating with BCS, it is straightforward to design InfoPath forms that create, read, update, and delete business data from a back-end system. Stay tuned for more details on creating SharePoint applications! Create Mashups using the InfoPath Form Web Part Now, without writing a single line of code, you can host your InfoPath browser forms in Web pages by simply adding the InfoPath Form Web Part to a Web Part page. You can also connect it to other Web Parts on the page to send or receive data. Stay tuned for more details on the InfoPath Form Web Part! Build Forms with Code Using Visual Studio Tools for Applications, you can add managed code to your forms. Stay tuned for more details on programming with InfoPath! InfoPath Editor The InfoPath 2010 Editor Fluent user interface provides a much improved, simpler user experience for filling out forms. Form opened in InfoPath 2010 Editor: SharePoint Workspace InfoPath 2010 is the forms technology used by SharePoint Workspace 2010 for creating and filling out forms. InfoPath Forms Services Administration and Management We have invested in many improvements to make it easier to manage your InfoPath Forms Services as a component of Microsoft SharePoint Server 2010.

Tuesday, February 23, 2010

Batch Files to Retract, Deploy WSPs

All-Retr-Depl-Sol @Echo on @Echo Installing all solutions @Echo. @Echo. for %%i in (*.wsp) do call Retr-Depl-Sol %%i for %%i in (*.wsp) do call Feature-Deac-Act %%~ni Retr-Depl-Sol @Echo on @Echo Retracting Solution %1 stsadm -o retractsolution -name %1 -immediate stsadm -o execadmsvcjobs @Echo Deleting Solution %1 stsadm -o deletesolution -name %1 @Echo Adding Solution %1 stsadm -o addsolution -filename %1 @Echo Deploying Solution %1 stsadm -o deploysolution -name %1 -immediate -allowgac -force stsadm -o execadmsvcjobs stsadm -o execadmsvcjobs Feature-Deac-Act @echo On stsadm -o deactivatefeature -filename %1\feature.xml -url http://Server/ -force stsadm -o activatefeature -filename %1\feature.xml -url http://Server/ -force iisreset popd