only My site

Thursday, August 30, 2012

Add a file to a Document Library and update metadata properties in a single method

Basically the steps are as follows:
  • Add the file through the document library
  • Get a reference to the same document library as an SPList
  • get the SPListItem you just added using the newFile.ListItemAllFields.ID
  • Set the metatdata properties
  • Call SPListItem.Update()
  • Check the file in (IMPORTANT TO DO THIS LAST AFTER YOU’VE SET ALL THE FIELDS OTHERWISE YOU’LL GET AN ERROR TRYING TO SET THE LIST ITEM PROPERTIES SAYING THAT THE FILE IS NOT CHEKED OUT)
private void AddFileToDocumentLibrary(string documentLibraryUrl, string filename, byte[] file_bytes, string itemTitleText)
     {
         SPSecurity.RunWithElevatedPrivileges(delegate()
         {
             using (SPSite site = new SPSite(documentLibraryUrl))
             {
                 using (SPWeb web = site.OpenWeb())
                 {
                     web.AllowUnsafeUpdates = true;
                     SPDocumentLibrary documentLibrary = (SPDocumentLibrary)web.Lists["MyDocumentLibraryName"];
                     SPFileCollection files = documentLibrary.RootFolder.Files;
                     SPFile newFile = files.Add(documentLibrary.RootFolder.Url + "/" + filename, file_bytes, true);

                     SPList documentLibraryAsList = web.Lists["MyDocumentLibraryName"];
                     SPListItem itemJustAdded = documentLibraryAsList.GetItemById(newFile.ListItemAllFields.ID);
                     //amend with your document-derived custom Content Type
                     SPContentType documentContentType = documentLibraryAsList.ContentTypes["Document"];
                     itemJustAdded["ContentTypeId"] = documentContentType.Id;
                     itemJustAdded["Title"] = itemTitleText;
                     //set other propeerties here..
                     itemJustAdded.Update();
                     newFile.CheckIn("New", SPCheckinType.OverwriteCheckIn);
                     web.AllowUnsafeUpdates = false;
                 }
             }
         });
     }

Friday, August 24, 2012

Sharepoint : ResourcePoints for Sandbox solutions

To restrict the resources that your sandboxed solutions consume, you define resource points. Resource points correspond to specific levels of resource usage that you can define for up to 15 system resources that you want to monitor. Each of these resource measures accumulates points based on a single sandboxed solution's use of that resource, and those points are aggregated toward a quota that has been set for the whole site collection. If the number of accrued resource points exceeds the quota set for the site collection, all sandboxed solutions in the site collection are stopped. For a list of the individual resource measures and the minimum threshold, absolute limit, and resources per point for each resource, see Resource Usage Limits on Sandboxed Solutions in SharePoint 2010 (http://go.microsoft.com/fwlink/p/?LinkId=217149).

Quotas are managed through the SharePoint Central Administration Web site as a single number that controls the aggregate total of the resource points allowed per day for all sandboxed solutions in a site collection. For more information about quotas, see Sandboxed solutions overview (SharePoint Server 2010). For information about how to set the maximum resource quota for a site collection, see Change the storage limits for a site collection in Manage site collection storage limits (SharePoint Server 2010).

You can fine-tune the resource point distribution by using Windows PowerShell, as described in this article. When these Windows PowerShell commands are added to a script, you can configure the individual resource point distribution within the sandboxed solution quota for a site collection. For more information about quotas and resource points, see Sandboxed solutions overview (SharePoint Server 2010).

For full article click 

Tekerik RADTreeView - Tips

1. Clone()
There is a clone() method for node object. This is very useful to reuse a hierarchical tree structure node in different Telerik tree view controls. We cannot add a node to multiple tree view control without cloning a copy of the node.

Example : 

RadTreeNode objNewNode = new RadTreeNode();
objNewNode  = objOldTreeNode.Clone(); 

TreeViewOld.Nodes.Add( objOldNode);
TreeViewNew.Nodes.Add( objNewNode);

2. LoadXMLString()
We can load the tree view with nodes using the XML string value. The XML should be well structured and hierarchical order.

objNewTree.LoadXmlString(strXml);

SharePoint : Add Event receiver to List programmatically

We may sometimes have need to create Event recivers as a DLL and use it for a particular List. Creating eveint receiver is out of scope of this page and it is easy and please click this link to know more about event receiver

using (SPSite site = new SPSite("http://localhost"))
{
        using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["Shared Documents"];
                    SPEventReceiverDefinition def = list.EventReceivers.Add();
                    def.Assembly = "ERDefinition, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=704f58d28567dc00";                    def.Class = "ERDefinition.ItemEvents";
                    def.Name = "ItemAdded Event";
                    def.Type = SPEventReceiverType.ItemAdded;
                    def.SequenceNumber = 1000;
                    def.Synchronization = SPEventReceiverSynchronization.Synchronous;
                    def.Update();
                }
}

Alternative way is as follows

using (SPSite site = new SPSite("http://localhost"))
{
        using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["Shared Documents"];
                    string strAssembly="ERDefinition, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=704f58d28567dc00"; 
                    string strClass = "ERDefinition.ItemEvents";
                    web.AllowUnsafeUpdates = true;
                    list.EventReceivers.Add(SPEventReceiverType.ItemAdded, strAssembly, strClass );
                    list.Update();
                    web.AllowUnsafeUpdates = false;
                }
}

Some notes about Event reciver base class

We need to use "SPItemEventReceiver" base class to create event receiver for list items. we need to overwrite the methods from the base class such as ItemAdded, ItemUpdated etc.

The other event reciver base classes are
the base class have 2 methods this.EnableEventFiring() and this.DisableEventFiring() which will help us to stop nested event receiver calls. The following example prevents the nested call of the ItemUpdated method call.

public override void ItemUpdated(SPItemEventProperties properties)

{
    this.DisableEventFiring();
        SPListItem item = properties.ListItem;
    item[
"Title"] = properties.ListItem["Title"].ToString() + " - Item Updated";    item.Update();

        this.DisableEventFiring();
}

RadAsyncUpload - RadAsyncUpload does not have permission to write files in the TemporaryFolder

Today I deployed a aspx page (with telerik:RadAsyncUpload) control in a new environment and come up with the following error

Error :

"RadAsyncUpload does not have permission to write files in the TemporaryFolder. In Medium Trust scenarios, the TemporaryFolder should be a subfolder of the Application Path.   at Telerik.Web.UI.RadAsyncUpload.TestTemporaryFolderPermissions() "

Cause :

The logged in user don't have Write permission for the temporary folder.

Resolution :

The resolution for the issue is need to give Authenticated_Users account write permission for the TemporaryFolder. The temporary folder is by default located in ApplicationRootPath.com80\App_Data\RadUploadTemp. You may also give everyone account also, but it is not advisable.

In addition we can also specify a custom path for the TemporaryFolder. The following is the code for the same

<telerik:RadAsyncUpload TemporaryFolder="c:\windows\temp"

Again we need to give the appropriate permissions to the "c:\windows\temp" folder as mentioned above.

Monday, August 20, 2012

SharePoint : EnsureUser & Add user to a Group


The ensureuser method adds the
string loginName = "Domain\User_Alias";
string grpName = "Group1";
//EnsureUser - Checks whether the specified logon name belongs to a valid user of the website, and if the logon name does not already exist, adds it to the website.
SPUser user = SPContext.Current.Web.EnsureUser(loginName);

SPGroup group = SPContext.Current.Web.Groups[grpName];
//Add the user to the Group
group.AddUser(user);
group.Update();

SharePoint Tools/Tips - Must use


SPDisposeCheck.exe

SPDisposeCheck is a tool that helps developers and administrators check custom SharePoint solutions that use the SharePoint Object Model helping measure against known Microsoft dispose best practices. This tool may not show all memory leaks in your code and may produce false positives which need further review by subject matter experts.

SPMetal.exe

A Command-line tool to generate entity class declarations for your Microsoft SharePoint Foundation solutions.

Wca.exe

The workflow communication activity command-line utility is used to generate code files for the strictly-bound HandleExternalEventActivity activity and CallExternalMethodActivity activity derived classes from an input assembly that contains one or more ExternalDataExchangeService interfaces.

WinDbg.exe 

To debug a Windows service. To debug a Windows service, you can attach the WinDbg debugger to the process that hosts the service after the service starts, or you can configure the service to start with the WinDbg debugger attached so that you can troubleshoot service-startup-related problems. This article describes both these methods. More Infor on http://support.microsoft.com/kb/824344

Wfc.exe

The workflow command-line compiler is used to compile both workflows and activities. It takes workflow markup (.xoml) and C# or Visual Basic source files, validates the workflows or activities, and generates assemblies or executables. Running wfc.exe with the /? argument provides a full list of options.

Trace.axd

You need to ensure that you can view the trace history in the Trace.axd file.

Web.Config : In the <system.web> element, add the following line of code:
<trace enabled="true" localOnly="true" pageOutput="false" />

Connectable Webpartshttp://msdn.microsoft.com/en-us/library/ms469765.aspx

SPPropertyBag

It is to add properties to a web (subsite). Properties is the SPPropertyBag object with the metadata for the website.
SPContext.Current.Web.Properties

SPWorkflowEventReceiver

The SPWorkflowEventReceiver class handles workflow events throughout the lifetime of a workflow.

Starting: Occurs when a workflow is starting
Started: Occurs when a workflow is started
Postponed: Occurs when a workflow is postponed
Completed: Occurs when a workflow is completed

SPContext.Current.FormContext

Page layour codebehind - You create a custom page layout that contains code-behind.You need to identify whether the page is in Edit mode or in Display mode.What should you use? The answer is

SPContext.Current.FormContext

Possible values for SPContext.Current.FormContext.FormMode property are Display, Edit, Invalid, and New

Sunday, August 19, 2012

SPWebConfigModifications - Add/Remove web.config settings

one way to modify web.config settings is to use the SPWebConfigModificationclass of the Microsoft.SharePoint.Administration namespace, which allows you to dynamically register entities. These modifications are persisted in the configuration database where they function as a kind of virtual web.config that effectively serves as the final layer of the .config file stack for the SharePoint Foundation web application. The changes become effective when the SPWebService.ApplyWebConfigModifications method is called
 
Holds modifications that are made to the web.config.

Use the WebConfigModifications property of the SPWebApplication or SPWebService class to get the collection of web.config modifications either in the Web application or in all Web applications within the Web service. To apply modifications that you define through the SPWebConfigModification class to the web.config files in the server farm, call the ApplyWebConfigModifications method on the current content Web service object, as follows:SPWebService.ContentService.ApplyWebConfigModifications

The following example adds a safe control entry to the safe controls section in web.config throughout the server farm.

Add Settings

SPWebService myService = SPWebService.ContentService;

SPWebConfigModification myModification = new SPWebConfigModification();
myModification.Path = "configuration/SharePoint/SafeControls";
myModification.Name = "SafeControl[@Assembly='MyCustomAssembly'][@Namespace='MyCustomNamespace'][@TypeName='*'][@Safe='True']";
myModification.Sequence = 0;
myModification.Owner = WebConfigModificationFeatureReceiver.OwnerId;
myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
myModification.Value = "<SafeControl Assembly='MyCustomAssembly' Namespace='MyCustomNamespace' TypeName='*' Safe='True' />";

myService.WebConfigModifications.Add(myModification);
myService.Update(); 
myService.ApplyWebConfigModifications();
 Remove Settings sample
SPWebConfigModification configModFound = null;
SPWebApplication webApplication = SPWebApplication.Lookup(new Uri("http://localhost/"));
Collection<SPWebConfigModification> modsCollection = webApplication.WebConfigModifications;

// Find the most recent modification of a specified owner
int modsCount1 = modsCollection.Count;
for (int i = modsCount1 - 1; i > -1; i--)
{
    if (modsCollection[i].Owner == "User Name")
    {
        configModFound = modsCollection[i];
    }
}

// Remove it and save the change to the configuration database  
modsCollection.Remove(configModFound);
webApplication.Update();

// Reapply all the configuration modifications
webApplication.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications(); 

Sharepoint : FormDigest Control and SPUtility.ValidateFormDigest()

<SharePoint:FormDigest runat="server"/>
This control inserts the security validation key within the form of an .aspx page

<form id="Form1" method="post" runat="server">
   <SharePoint:FormDigest runat="server"/>
   <asp:Button id="Button1" style="Z-INDEX: 101; LEFT: 282px; POSITION: absolute;
      TOP: 282px" runat="server" Text="Button"></asp:Button>
</form>

SPUtility.ValidateFormDigest()
Validates the form digest control that is used in the current request.

Remark
If the method that is passed to the RunWithElevatedPrivileges method includes a write operation, either of theSPUtility.ValidateFormDigest() or SPWeb.ValidateFormDigest() methods should be called before a call is made toRunWithElevatedPrivileges.
 

SharePoint : Hide Left Navigation Panel

The default master page of SharePoint will display the navigation panel (basically a DIV element) on the left hand side of the page. Often, we may not require those panel if we go for a custom UI rather than using a standard SharePoint type pages.

There are two ways

1. If you want to hide permanently in all the pages, then edit the Master Page and add the below style. This will override the style and hide the panel

<style>.ms-navframe{ display:none; }</style>

2. Insert a content editor web part and add the above style code in it, before publishing the page, make sure you set the chrome type to 'None' (this will hide the Title of the web part in the page)

Thursday, August 16, 2012

SQL Deployment using BAT file

SET username=USER_NAME
SET password=PASSWORD
SET dbname=DBNAME
SET servername=SERVER_NAME

sqlcmd -U %username%  -P %password%   -S %servername%  -d %dbname%  -i RequiredScript.sql   -o  SQLFILENAMEWITHPATH.txt

pause