Saturday, December 10, 2011

How to create Sharepoint 2010 Modal Dialog Pop up ( Popup with Faded Background )


Many a times we have a requirement like we need to open a Pop-up with the Faded Background. Sharepoint 2010 has provided us a very simple way to achieve this.
Below is the JavaScript with the help of which we can open a Modal Dailog Pop Up of Sharepoint 2010.
<script type="text/javascript">
     function OpenDialog(URL) {
         var NewPopUp = SP.UI.$create_DialogOptions();
         NewPopUp.url = URL;
         NewPopUp.width = 700;
         NewPopUp.height = 350;
         SP.UI.ModalDialog.showModalDialog(NewPopUp);
     }
 </script>

Call the Javascript on Button click and the modal PopUp will pops up with the Page of Specified URL.
btnOpenPopUp.Attributes.Add("onClick""javascript:OpenDialog(‘/_layouts/MyAppPage/MyPage.aspx’);");

Saturday, November 19, 2011

Management of Master Lists in SharePoint with Choice Filter Lookup column


Almost every SharePoint project needs Lookup column. To create each lookup column we need to create separate list. If a requirement comes where developer needs to use master lists for different data then developer needs to create multiple lists which is resource consuming and maintaining multiple list also extra effort required for developer and administrator also. For this type of requirement I have created Choice Filter Lookup column. User can create one choice column in Master list and filter lookup column based on that choice column.


You can download the Source code from here

Current Scenario




MasterList1

MasterList2

MasterList3

MasterList4


MasterConsumerList New or Edit Form


MasterConsumerList View


Now above screen shot shows the real or actual implementation of requirements which generally SharePoint developers and Administrator follow for creating relationship of multiple caregory and reusability.If user want to add one more lookup column then user needs to create one more list for the lookup. The only problem is with above implementation is that it is creating multiple lists which increase the resource utilization and maintainbilty. Now I have tried to resolve the above implementation by creating Choice Lookup filter column. Please refer below screen shots for same implemetation with Choice Lookup filter
  ConsolidateMasterList and ConsolidateMasterListConsumer shows 2 new list for same implementation mentioned above

Consolidated Master List (with new column Category as Choice column with Values {Master1, Master2, Master3, Master4} for differentiate values or for filter values based on category)

Create Column of Choice Filter lookup column (Choose your filter category from the dropdown)




 List Settings view after adding 4 choice filter lookup column


Consolidated Consumer New or Edit Form

Consolidated Consumer List View 2MasterConsumerList View


Happy Coding !!!!!!!!!

Tuesday, November 8, 2011

Add Custom Property Panel in Custom WebPart like OOB SharePoint Property Panel via Reflection


Sometime we have a requirement to create custom property in WebPart. But the custom Property will add in “Miscellaneous” section or added in blank section if we add property via custom tool part. Now if you want to create panel like OOB Panel “Layout, Appearance etc.” then use below method.
Below class is static class for enabling extension method on ToolPart class. You need to add below class in your solution and add namespace in your toolpart class where you want to use this method
namespace ExtensionMethods
{
    public static class CustomExtensions
    {
        public static Panel GetPropertyPanel(this ToolPart currentToolPart, Table table, String sTitle)
        {
            Panel controlPanel = new Panel();
            controlPanel.ID = "propertyPanelHideDisplay";
            controlPanel.Attributes.Add("id", currentToolPart.ClientID + "_" + controlPanel.ID);
            controlPanel.Controls.Add(table);

            Literal lt = new Literal();
            String sScript = "<script language='javascript'>\n" +
                            " var objDiv = document.getElementById('" + currentToolPart.ClientID + "_" + controlPanel.ID + "');\n" +
                            " objDiv.parentNode.parentNode.parentNode.attributes.removeNamedItem('colspan');\n" +
                            " objDiv.parentNode.parentNode.parentNode.attributes.removeNamedItem('class'); \n" +
                            "</script>";
            lt.Text = sScript;
            controlPanel.Controls.Add(lt);

            Type type = typeof(SPSite);
            Assembly assembly = type.Assembly;

            var bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

            Panel propertyPanel = (Panel)assembly.CreateInstance("Microsoft.SharePoint.WebPartPages.TPPanel", false, bindingFlags, null,
               new object[] { sTitle, controlPanel, true }, null, null);

            return propertyPanel;
        }
  
 }
}

Below is the sample class for ToolPart for adding Panel by using above class

using ExtensionMethods;
namespace CustomNameSpace
{
    class CustomToolpart : ToolPart
    {
        private DropDownList ddlDisplayType;
     
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            CreateControls();
        }

        public override void ApplyChanges()
        {
            EnsureChildControls();
            SendDataToWebPart();
        }

        private void SendDataToWebPart()
        {
            EnsureChildControls();
            CustomWebPart customWebPart = (CustomWebPart)this.ParentToolPane.SelectedWebPart;

            // Send the custom text to the Web Part.
            if (ddlDisplayType != null)
            {
                customWebPart.Property = ddlDisplayType.SelectedValue;
            }

           
        }

        public override void SyncChanges()
        {
            base.SyncChanges();
           
        }

        private void SetValues()
        {
            ListItem item = null;
            CustomWebPart customWebPart = (CustomWebPart)this.ParentToolPane.SelectedWebPart;
            if (!string.IsNullOrEmpty(customWebPart.Property))
            {
                item = ddlDisplayType.Items.FindByValue(customWebPart.Property);
                if (item != null)
                {
                    ddlDisplayType.SelectedValue = item.Value;
                }
            }
        
           
        }

        public override void CancelChanges()
        {
            base.CancelChanges();
        }


        protected override void RenderToolPart(System.Web.UI.HtmlTextWriter output)
        {
            base.RenderToolPart(output);
        }


        public void CreateControls()
        {
          
            ddlDisplayType = new DropDownList();

            ddlDisplayType.Items.Add("Property 1");
            ddlDisplayType.Items.Add("Property 2");
            ddlDisplayType.Items.Add("Property 3");

            AddControls();
            SetValues();
          
        }

        private void AddControls()
        {
            Table table = new Table();
            TableRow tr = new TableRow();
            TableCell td = new TableCell();
            Literal ltStatic = new Literal();

            ltStatic.Text = "Custom Property";
            td.Controls.Add(ltStatic);
            tr.Cells.Add(td);
            table.Rows.Add(tr);
           
            tr = new TableRow();
            td = new TableCell();
            td.Controls.Add(ddlDisplayType);
            tr.Cells.Add(td);
            table.Rows.Add(tr);

            String sTitle = "Panel Title";
            this.Controls.Add(this.GetPropertyPanel(table, sTitle));
        }
    }
}


In above class bold line will return Panel and add the Panel in ToolPart Pane. Below is the screen shot for the above implementation


Hope it help !!!!

Monday, October 17, 2011

Display Unsupported Browser Error via OOB control in SharePoint

SharePoint 2010 will support many major browsers including IE7, IE8, FF3.5 and Safari4, but there is one browser that will not be supported by the out of the box SharePoint 2010 experience: Internet Explorer 6



How can we handle this gracefully? Microsoft again comes to the rescue with a SharePoint Control to help.
<SharePoint:WarnOnUnsupportedBrowsers runat="server"/>
If you place this control at the bottom of your master page, IE6 users will be greeted with a message like this:
image


Happy Coding !!!!!

Tuesday, October 11, 2011

SPChangeQuery Class in SharePoint

Gets the changes to the list from the change log as filtered by the specified query.



using (SPSite siteCollection = new SPSite("http://localhost"))
         {
            using (SPWeb webSite = siteCollection.OpenWeb())
            {
               // Get a list.
               SPList list = webSite.Lists[0];

               // Construct a query.
               SPChangeQuery query = new SPChangeQuery(false,  // limit object types
                                                       false); // limit change types

               // Specify the object type. 
               query.Item = true;

               // Specify change types. 
               query.Add = true;
               query.Delete = true;
               query.Update = true;

               SPTimeZone timeZone = webSite.RegionalSettings.TimeZone;
               int total = 0;

               // Loop until we reach the end of the log.
               while (true)
               {
                  SPChangeCollection changes = list.GetChanges(query);

                  total += changes.Count;

                  // Print info about each change to the console.
                  foreach (SPChangeItem change in changes)
                  {
                     // Get the item name.
                     string itemName = String.Empty;
                     SPListItem item = null;
                     try
                     {
                        item = list.GetItemByUniqueId(change.UniqueId);
                        itemName = item.Name;
                     }
                     catch (ArgumentException)
                     {
                        itemName = "Unknown";
                     }

                     Console.WriteLine("\nDate: {0}",
                         timeZone.UTCToLocalTime(change.Time).ToString());
                     Console.WriteLine("Change: {0}", change.ChangeType);
                     Console.WriteLine("Item: {0}", itemName);

                  }

                  // Break out of loop if we have the last batch.
                  if (changes.Count < query.FetchLimit)
                     break;

                  // Otherwise, go get another batch.
                  query.ChangeTokenStart = changes.LastChangeToken;
               }

               Console.WriteLine("\nTotal of {0} changes to {1} list", total, list.Title);
            }
         }
         Console.Write("\nPress ENTER to continue...");
         Console.ReadLine();

Thursday, September 29, 2011

Migrate SharePoint List Data to Document Library without changing the Created and Modified Date


 SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite("http://br-pc-203/"))
                {
                    SPList customList = site.RootWeb.Lists["Custom List"];
                    SPList documentLibrary = site.RootWeb.Lists["Document Library"];
                    SPFolder folder = site.RootWeb.Folders[documentLibrary.Title];
                    SPFileCollection fileCollection = null;
                    foreach (SPListItem ltItem in customList.Items)
                    {
                        if (ltItem.Attachments != null && ltItem.Attachments.Count > 0)
                        {
                            foreach (String sFilename in ltItem.Attachments)
                            {
                                fileCollection = folder.Files;
                                SPListItem docItem = documentLibrary.Items.Add();
                                SPFile attachmentFile =  ltItem.ParentList.ParentWeb.GetFile(ltItem.Attachments.UrlPrefix + sFilename);

                                string destFile = fileCollection.Folder.Url + "/" + attachmentFile.Name;
                                byte[] fileData = attachmentFile.OpenBinary();

                                SPFile addedFile = fileCollection.Add(destFile, fileData, site.RootWeb.CurrentUser, site.RootWeb.CurrentUser, Convert.ToDateTime(ltItem[SPBuiltInFieldId.Created]), Convert.ToDateTime(ltItem[SPBuiltInFieldId.Modified]));
                                SPListItem item = addedFile.Item;
                                item[SPBuiltInFieldId.Created] = Convert.ToDateTime(ltItem[SPBuiltInFieldId.Created]);
                                item[SPBuiltInFieldId.Modified] = Convert.ToDateTime(ltItem[SPBuiltInFieldId.Modified]);
                                addedFile.Item.Update();
                            }
 
                        }
                    }
                }
            });

Sunday, September 18, 2011

OOB Redirect Page for Display and Edit form of ListItem : COPYUTIL.ASPX provided by SharePoint


To navigate to a SharePoint list item or document, when you only got the ID's of the item, the item's container (list or document library) and the item's web? I sure did! For example when you query SharePoint data by making use of the SPSiteDataQuery class; the resulting data table includes all those ID's (and additional properties if you want), but it doesn't include a link back to the item. You could make use of the Object Model to build the link in code, but that is both resource intensive and pretty complex. In that case you have to check out the CopyUtil.aspx page, which is also used by the Content Query Web Part by the way. The CopyUtil.aspx page is an application page to which you can provide a bunch of ID's, as a result the page will redirect you to the corresponding item or document.

You just have to build a URL like this (replace the X's with the actual ID's of course):


http://yoursite/_layouts/CopyUtil.aspx?Use=id&Action=dispform&ItemId=X&ListId=X&WebId=X&SiteId=X

And the CopyUtil.aspx page will do the rest!

Action = "dispform" or Action = "editform"

Saturday, September 17, 2011

List filter with URL values SharePoin


Did you know that you easily can filter your Sharepoint list or library with values in your URL? This means that you can create a “view” without really creating a view. To spice up your GUI you can for instance insert some graphical boxes above your document library view that filters with URL values. Last, but not least, you can use this method to filter the content of all web parts on a page, you are not limited to filter a view in a document library (after all, a view is just a web part on a .aspx page). You can filter on a built-in column, or a column you have created yourself.
Example:
Here I have created a couple of links in the Qiuck Launch. The url for the first link could be:
/Forms/AllItems.aspx?FilterField1=_ModerationStatus&FilterValue1=2
I used a built in column (you will have to use the internal column name) in this example, if you use your own column you just use your columns initial name and the plain value. The filter sign next to the column name shows that you have made a regular filtering of the column. Ofcourse you can filter on multiple values and columns, I guess you can figure that out for yourself:)

How do I know that “2″ equals “pending”? Apply the filter manually and check out the URL, you’ll se both the internal column name and the correct value to filter on.
In other words, adding the following code to your URL makes your URL-filtering day in Sharepoint:
?FilterField1=ColumnName&FilterValue1=ValueToFilterOn

Saturday, September 10, 2011

Reset the Farm Passphrase in SharePoint 2010


Adding a new server to the farm and you can’t remember that new SharePoint 2010 addition called the Farm Passphrase? No problem! You can use PowerShell to reset / change that forgotten farm passphrase. Note that I said reset and not retrieve. There is currently no option to retrieve the existing farm passphrase.
  • Must be a member of the SharePoint_Shell_Access database role on the SharePoint Configuration database. Check Get-SPShellAdmin and Add-SPShellAdmin.
  • Open the SharePoint 2010 Management Shell (Start > All Programs > Microsoft SharePoint 2010 Products > SharePoint 2010 Management Shell)
  • Enter this at the PowerShell prompt:
    • $passphrase = ConvertTo-SecureString -asPlainText -Force
  • Input the new passphrase and hit Enter
  • Enter this at the PowerShell prompt:
    • Set-SPPassPhrase -PassPhrase $passphrase -Confirm
  • You will be asked to confirm the passphrase by re-entering it
  • Re-enter the passphrase and hit Enter
  • You will be asked if you are sure that you want to perform this action, type Y (for Yes) and hit Enter
  • Your farm passphrase has now been reset!