Showing posts with label sharepoint. Show all posts
Showing posts with label sharepoint. Show all posts

Thursday, January 6, 2011

Issues With Programmatically Attaching Multiple Files To A List Item

Recently one of my team member was facing issue while adding multiple files to a list item programmatically. The issue was, about 10% files added programmatically were corrupt while uploading. So whenever the user tries to download the file, they were getting "HTTP 500 Internal Server". Below is the piece of code he was using;

HttpFileCollection uploads = HttpContext.Current.Request.Files;


for (int i = 0; i < uploads.Count; i++)

{


HttpPostedFile upload = uploads[i];


if (upload.ContentLength == 0)


continue;


Stream inputStream = upload.InputStream;


byte[] buffer = new byte[inputStream.Length];


inputStream.Read(buffer, 0, (int)inputStream.Length);


inputStream.Close();


eItem.Attachments.Add(upload.FileName, buffer);


}


eItem.Update();
 
On analysing we found out that, the issue was with Attachments.Add method. It was causing some corruptions in the bytes uploaded. So we tried with Attachments.AddNow..
Bingo!!! It started to work without any issues.
 
The only difference between "Attachments.Add" and "Attachments.AddNow" was, "Attachments.AddNow"; it will create new version whenever you attach.
Also, "Attachments.AddNow" internally calls the "Update" method of the List Item. Though its very weird, it is solving the problem of bytes corruption while uploading multiple attachments to the list item.

Monday, December 13, 2010

Forbidden 403 error while accessing workitems in TFS2010 sharepoint site Dashboard

Sometimes you may experience the "Forbidden 403" error in TFS2010 when you try to access the workitems from Dashboard in Sharepoint site.

Here is the solution for that;
1) Login to the TFS Application server
2) Locate the directory "C:\inetpub\wwwroot\bin"
3) Give Write permission for the users of TFS

Bingo, now you should be able to access workitems from Dashboard.

Friday, December 4, 2009

Settings for using WSPBuilder with MSBuild or TFS Team Build

1) Install the latest WSPBuilder
2) Upload the WSPTools folder to TFS source control
3) Update the "Post Build" event with the one shown below. [Update the path to WSPBuilder.exe accordingly]
IF ("$(OutDir)")==("bin\Debug\") GOTO LocalBuild
 

:TfsBuild
MD "$(TargetDir)bin\Debug\"
COPY "$(TargetDir)*.dll" "$(TargetDir)bin\Debug\"
"D:\TFS Build Location\AAS Web Transform\AAS.DevelopmentBuild\AAS Demo\Sources\Tools\WSPTools\WSPBuilderExtensions\WSPBuilder.exe" -SolutionPath "$(TargetDir)" - OutputPath "$(TargetDir)"
RENAME "$(TargetDir)Debug.wsp" "$(ProjectName).wsp"
RMDIR "$(TargetDir)bin" /S /Q
RMDIR "$(TargetDir)12" /S /Q
GOTO Finish


:LocalBuild
$(TargetDir)..\..\..\..\..\..\Tools\WSPTools\WSPBuilderExtensions\WspBuilder.exe -SolutionPath "$(ProjectDir)" -OutputPath "$(TargetDir)"

:Finish

Collecting Data from web parts and submitting to back end using C#

There can be scenarios, wherein you may have to collect data from various web parts in a page and submit to back end. One solution will be to use Connected Web parts feature. Or the sample code below also will help to achieve this;


1) Define one base class
public abstract class IBaseForm : WebPart
    {

    }



2) Implement this class in all the web parts whose data need to be collected
public class InputForm2 : IBaseForm
    {
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            TextBox t1 = new TextBox();
            t1.ID = "LastName";
            t1.Text = "Last Name";
            this.Controls.Add(t1);
        }
    }



3) This is the piece of code which will collect the data from all the web parts which implement the base class
public class SubmitButton : WebPart
    {
        TextBox t1 = new TextBox();
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            Button b1 = new Button();
            b1.ID = "submitData";
            b1.Text = "Submit Data";
            b1.Click += new EventHandler(b1_Click);
            this.Controls.Add(b1);

            t1.ID = "result";
            this.Controls.Add(t1);
        }

        void b1_Click(object sender, EventArgs e)
        {
            t1.Text = string.Empty;
            System.Web.UI.ControlCollection colls = this.Parent.Controls;
            IEnumerable bf= colls.OfType();
            foreach (IBaseForm f in bf)
            {
                t1.Text = t1.Text + GetValue(f);
            }
        }

        string GetValue(IBaseForm f)
        {
            string res = string.Empty;
            TextBox t = default(TextBox);

            foreach (System.Web.UI.Control c in f.Controls)
            {
                if (c.GetType().Equals(typeof(TextBox)))
                    t = c as TextBox;
                break;
            }
            res = t.Text;
            return res;
        }
    }

Thursday, October 22, 2009

Creating Custom List from List Template through feature in sharepoint

Elements.xml file:


<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="KM" Url="_catalogs/lt" RootWebOnly="TRUE">
    <File Url="Knowledge Management.stp" Type="GhostableInLibrary" >
      <Property Name="Name" Value="Knowledge Management"/>
      <Property Name="Title" Value="Knowledge Management"/>
    </File>
    <File Url="Team Details.stp" Type="GhostableInLibrary" >
      <Property Name="Name" Value="Team Details"/>
      <Property Name="Title" Value="Team Details"/>
    </File>
    <File Url="Team Leave.stp" Type="GhostableInLibrary" >
      <Property Name="Name" Value="Team Leave"/>
      <Property Name="Title" Value="Team Leave"/>
    </File>
    <File Url="Training Plan.stp" Type="GhostableInLibrary" >
      <Property Name="Name" Value="Training Plan"/>
      <Property Name="Title" Value="Training Plan"/>
    </File>
  </Module>
</Elements>



Feature Activation code:


 public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            //System.Diagnostics.Debugger.Launch();
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(properties.Feature.Definition.RootDirectory + "/ListInstance.xml");
            XmlElement xmlElement = xmlDocument.DocumentElement;
            XmlNodeList node = xmlElement.ChildNodes;
            using (SPWeb web = (SPWeb)properties.Feature.Parent)
                {
                    //SPWeb web = site.OpenWeb();
                    foreach (XmlNode node1 in node)
                    {
                        SPListTemplate template;
                        SPListTemplateCollection templateList = web.Site.GetCustomListTemplates(web);
                        if (templateList != null && templateList.Count > 0)
                        {
                            template = templateList[node1.Attributes[0].Value];
                        }
                        else
                        {
                            throw new Exception(string.Format("No custom lists found for {0}", web));
                        }

                        if (template != null)
                        {
                            web.Lists.Add(node1.Attributes[0].Value, node1.Attributes[0].Value, template);
                            //web.Lists.Add("Teams TSL", "Teams TSL", template);
                            //web.Lists.Add("Teams Toezicht", "Teams Toezicht", template);
                            web.Update();
                            SPList list=web.Lists[node1.Attributes[0].Value];
                            list.OnQuickLaunch=true;
                            list.Update();
                        }
                        else
                        {
                            throw new Exception("No template to add");
                        }
                    }
                }
           
            //throw new NotImplementedException();
        }

Tuesday, October 6, 2009

Elements.xml file for creating folders inside document library

Below is the sample elements.xml file content for creating folders inside document library through features


<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/"><Module Path ="Client Supplies" Url ="Requirement/Client Supplies" />
<Module Path ="Functional Requirements" Url ="Requirement/Functional Requirements" />

</Elements>


Please note that, like this any level of nested folder structure can be created. (Url = "Docs/FirstLevel/SecondLevel/ThirdLevel"

Solution for "Cannot complete action. Try again later" error while activating ListInstance in sharepoint

Each ListInstance in ListInstance.xml file must contain "FeatureId="00bfea71-e717-4e80-aa17-d0c71b360101"" to avoid this error. 
Basically, your <ListInstance> node should look like as shown below;


    <ListInstance
           Title="Requirement Management"
           Description="Requirement Management"
           Id="A26D9F72-5F3B-477d-8E43-CB20698BC669"
           TemplateType="101"
FeatureId="00bfea71-e717-4e80-aa17-d0c71b360101"
OnQuickLaunch="true"
           Url="Requirement">
    </ListInstance>



The feature ID listed above is the FeatureID of the a normal (OOTB) sharepoint feature. This is required to find the TemplateType 101; which is a default doclib.

Wednesday, September 23, 2009

Simple Modal Popup using Javascript which works in sharepoint and ASP.NET

Here is the code for simple modal popup using Javascript which works in sharepoint as well as ASP.NET



<div id='modal' style='position: absolute; top: 0px; left: 0px; display: none; z-index: 9;
    background-color: #383838; filter: alpha(opacity=60);'>
</div>
<div id='chart' style='position: absolute; top: 100px; left: 180px; display: none;
    z-index: 10;'>
    <asp:Button ID="btnYes" runat ="server" Text ="Yes" OnClick ="btnYes_Click" />
    <button onclick="javascript:document.getElementById('modal').style.display='none';document.getElementById('chart').style.display='none';">
        CANCEL</button>
    <br />
    <br />
</div>
<a href='#'  onclick="javascript:document.getElementById('modal').style.width = document.body.clientWidth + 'px';document.getElementById('modal').style.height = document.body.clientHeight + 'px';document.getElementById('modal').style.display='block';document.getElementById('chart').style.display='block';">
<asp:Label ID="lblClick" runat ="server" Text ="Click Me"></asp:Label>
</a>


To get this code working properly in ASP.NET remove the following code in .aspx pages
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Saturday, September 19, 2009

Accessing Active Directory information from Sharepoint

To access the information in AD like username, first name, last name, given name, CN, Role etc... from sharepoint; the following are some of the options

  • Access the Active Directory directly from the Portal
  • Create a WCF Service running under privileged user which will access the Active Directory and return the required information
  • Create Shared Service provider and use “Profile Import” technique in the sharepoint
Option 1:
This option may not be the good one since every user to the sharepoint need to have access to the corresponding Active Directory. This might not work out in case of using Windows Authentication in the sharepoint.


Option 2: (Using WCF Service)

A WCF Service can be created and make it to run under the highly privileged user who have access to Active Directory. From Portal we can make a WCF call to get the Active Directory information. The service will pull the user information from Active Directory and return back to the portal.
Pros
  •  Unlike profile import approach, the information about the user is always up-to-date since we are directly fetching the information from Active Directory.
Cons 
  • One WCF Service has to be setup to access Active Directory. Involves a little bit effort to create & deploy the WCF Service.
  •  Whenever a user logs-in a web service call has to be made to fetch the Active Directory information. This might affect the performance of the portal a little
Option 3:(Profile Import)

MOSS has the built-in technology for access the Active Directory called “Profile Import shared service”.
To use this,

  • Shared Services has to be created
  • Under “User Profiles and Properties”, “Import Connection” has to configured to the Active Directory
  • Using “Configure Profile Import” either incremental or full import has to be configured using the privileged user id and password
  • Property mappings have to be created for the information required from Active Directory
  • Then sharepoint will import all the profiles from Active Directory and store them in its SQL configuration database
  • From Portal using Elevated Privilege we will have to use “UserProfileManager” and access the user profiles.
Pros

  • The Active Directory information will be imported and stored in the configuration database of the sharepoint portal. Also, the profile information will be set in the User Context info of the logged-in user. Hence, accessing the Profile Information will have better performance than accessing the WCF Service.
  • “Profile Import” technique is in-built in sharepoint and does not involve any coding. Simple configuration settings in the “Sharepoint Central Administration” will suffice
Cons
  • The Profile Import from Active Directory will happen through schedule jobs. Hence there is a chance that the latest updated information of the user in Active Directory might not reflect immediately in the User Profile

Thursday, September 17, 2009

Refresh Parent page while closing the modal popup in sharepoint

In sharepoint, to refresh the parent page on closing the popup just add this piece of code after calling the window.showModalDialog "window.location.href=window.location.href"