Showing posts with label WSS. Show all posts
Showing posts with label WSS. Show all posts

Install log4net in SharePoint 2007

Posted On // Leave a Comment

Step 1 Download the latest version of log4net library
Step 2 Add log4net reference to your project
Step 3 Add log4net assembly to GAC
Step 4 Select your SharePoint web application. E.g.
C:\inetpub\wwwroot\wss\VirtualDirectories\88
Choose one of following steps (Step 5, Step 6):
Step 5 Add below line in your AssemblyInfo.cs file.
 
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "C:\\inetpub\\wwwroot\\wss\\VirtualDirectories\\88\\web.config", Watch = true)]
 
Step 6 Modify your SharePoint web application’s global.asax
 
C:\inetpub\wwwroot\wss\VirtualDirectories\88\global.asax
 
<%@ Assembly Name="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" %>
<%@ Import Namespace="log4net" %>
<%@ Import Namespace="log4net.Config" %>
<%@ Import Namespace="System.IO" %>

<script language="C#" runat="server">
void Application_Start(object sender, EventArgs e)
    {   
    //string currentFolder = HttpContext.Current.Request.PhysicalApplicationPath;//Context.Request.PhysicalApplicationPath;
    //log4net.Config.XmlConfigurator.Configure(new FileInfo(currentFolder + "web.config"));
    log4net.Config.XmlConfigurator.Configure(new FileInfo("C:\\inetpub\\wwwroot\\wss\\VirtualDirectories\\88\\web.config"));     
    }
</script>
 
Step 7 Add below sections in your SharePoint web application’s web.config
 
C:\inetpub\wwwroot\wss\VirtualDirectories\88\web.config
 
<configSections>
  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  …
</configSections>
…
<log4net debug="true">
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="[set your file path log here]" />
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="10" />
    <maximumFileSize value="10MB" />
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
    </layout>
  </appender>
  <root>
    <level value="ALL" />
    <appender-ref ref="RollingLogFileAppender" />
  </root>
</log4net>
</configuration>

Snippet code using log4net in SharePoint Webpart
 
[Guid("857bb65a-fd9c-4294-9ddf-7f090d777267")]
    public class log4netWebPartTest : Microsoft.SharePoint.WebPartPages.WebPart
    {
        #region log4net
        private static readonly ILog _log = LogManager.GetLogger(typeof(log4netWebPartTest).Name);
        #endregion

        private bool _error = false;
        private string _myProperty = null;


        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("My Property Group")]
        [WebDisplayName("MyProperty")]
        [WebDescription("Meaningless Property")]
        public string MyProperty
        {
            get
            {
                if (_myProperty == null)
                {
                    _myProperty = "Hello SharePoint";
                }
                return _myProperty;
            }
            set { _myProperty = value; }
        }


        public log4netWebPartTest()
        {
            this.ExportMode = WebPartExportMode.All;
        }

        /// <summary>
        /// Create all your controls here for rendering.
        /// Try to avoid using the RenderWebPart() method.
        /// </summary>
        protected override void CreateChildControls()
        {
            if (!_error)
            {
                try
                {

                    base.CreateChildControls();

                    // Your code here...
                    this.Controls.Add(new LiteralControl(this.MyProperty));
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        /// <summary>
        /// Ensures that the CreateChildControls() is called before events.
        /// Use CreateChildControls() to create your controls.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            if (!_error)
            {
                try
                {
                    base.OnLoad(e);
                    this.EnsureChildControls();

                    try
                    {                       
                        File.ReadAllBytes(@"fileDoesNotExist.txt");
                    }
                    catch (FileNotFoundException ex)
                    {
                        if (_log.IsErrorEnabled)
                        {
                            _log.Error("OnLoad error: " + ex.Message);
                        }

                    }
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        /// <summary>
        /// Clear all child controls and add an error message for display.
        /// </summary>
        /// <param name="ex"></param>
        private void HandleException(Exception ex)
        {
            this._error = true;
            this.Controls.Clear();
            this.Controls.Add(new LiteralControl(ex.Message));
        }
    }



















[Read more]

Add workflow association to specific list in SharePoint 207

Posted On // 2 comments
Here is my snippet code how to create a workflow association that can then be added to a list.
/// <summary>
        /// Add workflow association to specific list
        /// </summary>
        /// <param name="siteId">Site collection object</param>
        /// <param name="webId">SharePoint website object</param>
        /// <param name="strWorkflowAssociateToListTitle">List title of SPList object will be associated workflow</param>
        /// <param name="workflowName">The name of the desired workflow association.</param>
        /// <param name="workflowId">Workflow template based on template ID</param>
        /// <param name="workflowHistoryListTitle">List title of Workflow History list</param>
        /// <param name="taskListTitle">List title of Task List</param>
        /// <param name="autoStartWorkflowCreate">A Boolean that represents whether the workflow starts 
        /// automatically when a new item is created.</param>
        public static void AssociateWorklowToList(Guid siteId, Guid webId, string strWorkflowAssociateToListTitle, string workflowName,
                 Guid workflowId, string workflowHistoryListTitle, string taskListTitle, bool autoStartWorkflowCreate)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite siteCollection = new SPSite(siteId))
                {
                    siteCollection.AllowUnsafeUpdates = true;
                    using (SPWeb site = siteCollection.OpenWeb(webId))
                    {
                        bool allowUnsafeUpdates = false;
 
                        allowUnsafeUpdates = site.AllowUnsafeUpdates;
                        site.AllowUnsafeUpdates = true;
 
                        SPListCollection lists = site.Lists;
                        ////a workflow association that can then be added to a this list.
                        SPList workflowAssociateToList = lists[strWorkflowAssociateToListTitle];
                        ////workflow history list
                        SPList workflowHistoryList = lists[workflowHistoryListTitle];
                        ////task list
                        SPList taskList = lists[taskListTitle];
 
                        SPWorkflowAssociation 
                                existingAssociation = workflowAssociateToList.WorkflowAssociations
                                        .GetAssociationByName(workflowName, 
                                                System.Globalization.CultureInfo.CurrentCulture);
                        if (existingAssociation == null)
                        {
                            SPWorkflowManager workflowManager = siteCollection.WorkflowManager;
                            SPWorkflowTemplateCollection templates = workflowManager.GetWorkflowTemplatesByCategory(site, null);
                            SPWorkflowTemplate template = templates.GetTemplateByBaseID(workflowId);
                            SPWorkflowAssociation association = SPWorkflowAssociation.CreateListAssociation(template, workflowName, taskList, workflowHistoryList);
 
                            ////the key solution
                            site.Update();
 
                            association.AllowManual = true;
                            association.AutoStartCreate = false;
 
                            workflowAssociateToList.AddWorkflowAssociation(association);
                            workflowAssociateToList.Update();
                            association.Enabled = true;
                        }
 
                        site.AllowUnsafeUpdates = allowUnsafeUpdates;
                    }
                }
            });
 
        }
[Read more]

Update SPListItem in workflow SharePoint

Posted On // Leave a Comment

Problem:

In workflow SharePoint context
SPListItem itemAssociateWithWorkflow =  this.workflowProperties.Item;
itemAssociateWithWorkflow["Your field name"] = "your value";
itemAssociateWithWorkflow.Update();
After update successfully, that item will be modified by “System Account” that means field Modified By has value System Account

Solve:

SPUser currentUser = GetCurrentUserInWorkflow(this.workflowProperties);
////impersonate real current user
using (SPSite site = new SPSite(this.workflowProperties.Web.Site.ID, currentUser.UserToken))
{
    using (SPWeb webCurrentUser = site.OpenWeb(this.workflowProperties.Web.ID))
    {
     SPListItem itemCurrentUser = webCurrentUser.Lists  [this.workflowProperties.ListId].GetItemById(this.workflowProperties.ItemId);
        itemCurrentUser["your field name"] = "your value";
        itemCurrentUser.Update();
    }
}
[Read more]

How to get currently logged-in user in workflow

Posted On // Leave a Comment
        /// <summary>
        /// Get current user in workflow sharepoint context
        /// </summary>
        /// <param name="workflowProperties"></param>
        /// <returns></returns>
        public static SPUser GetCurrentUserInWorkflow(Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties workflowProperties)
        {
            string ModifiedbyUserName = Convert.ToString(workflowProperties.Item.GetFormattedValue("Modified By"));
            string[] strChar = { "ID=" };
 
            string[] strChars = ModifiedbyUserName.Split(strChar, StringSplitOptions.None);
 
            Int32 iUserID = Convert.ToInt32(strChars[1].Substring(0, strChars[1].IndexOf("\"")));
 
            SPUserCollection usersInSite = workflowProperties.Web.SiteUsers;
            int countUsers = usersInSite.Count;
            for (int iCnt = 0; iCnt <= countUsers - 1; iCnt++)
            {
                if (usersInSite[iCnt].ID == iUserID)
                {
                    return workflowProperties.Web.SiteUsers[iCnt];
                }
            }
            return null;
        }
Refer from http://www.sharepointkings.com/2008/08/how-to-get-currently-logged-in-user-in.html
[Read more]

Screenshot Pemission in Sharepoint 2007

Posted On // Leave a Comment
Maybe these screenshot could make you easy understand permission in Sharpoint 2007
Figure - 01: Permission level
permission Sharepoint
Figure - 01
Figure – 02: Built-in permission Sharepoint
built-in permission Sharepoint
Figure - 02
[Read more]

Microsoft.SharePoint.SPFieldUserValueCollection is not marked as serializable

Posted On // Leave a Comment

Problem:
Develop on SharePoint Workflow
Unexpected    System.Workflow.Runtime.Hosting.PersistenceException: Type 'Microsoft.SharePoint.SPFieldUserValueCollection' in Assembly 'Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' is not marked as serializable.
Snippet code causes error:
public sealed partial class YourWorkflow : SharePointSequentialWorkflowActivity
    {
        SPFieldUserValueCollection _reviewers;
Resolve:
Check fields in your custom activity or workflow, if it has field type Microsoft.SharePoint.SPFieldUserValueCollection, just remove it or use it as variable method.
[Read more]

HRESULT 0x80040E14 When Calling SPListItem.Update

Posted On // Leave a Comment
Problem:
This is snippet code causes error HRESULT 0x80040E14 when calling SPListItem.Update method
SPList docApprovalList = _web.Lists[List.DocumentApprovalList];
SPListItem itemUpdate = docApprovalList.GetItemById(documentApprovalListObj.Id);
//itemUpdate[SPBuiltInFieldId._Identifier] = documentApprovalListObj.Id;
itemUpdate["ID"] = documentApprovalListObj.Id;
itemUpdate["Status"] = documentApprovalListObj.Status;
itemUpdate.Update();
documentApprovalListObj is my business object which has an attribute Id is a SharePoint List Field ID {1d22ea11-1e32-424e-89ab-9fedbadb6ce1}
Solve:
DO NOT change or re-assign value of field ID of list item
[Read more]

How to create a User field that can contain more than one value

Posted On // Leave a Comment
<Field ID="{44DB06B2-DC96-4dd7-AA6A-1A82AE906179}"
         Type="UserMulti"
         Name="Groups"
         DisplayName="Groups"
         ShowInEditForm="FALSE"
         Mult = "TRUE"
         Group="MyGruoup"/>
There are 2 notes:
  • Type="UserMulti"
  • Mult = "TRUE" - Upper TRUE!
[Read more]