Exemplo n.º 1
1
        public static void BatchDeleteItems(SPList splTask, SPQuery query,SPWeb web)
        {
            // Set up the variables to be used.
            StringBuilder methodBuilder = new StringBuilder();
            string batch = string.Empty;
            string batchFormat = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                                "<Batch onError=\"Return\">{0}</Batch>";

            string methodFormat = "<Method ID=\"{0}\">" +
                "<SetList Scope=\"Request\">{1}</SetList>" +
                "<SetVar Name=\"ID\">{2}</SetVar>" +
                "<SetVar Name=\"Cmd\">Delete</SetVar>" +
                "</Method>";

            // Get the list containing the items to update.
            //PList list = WorkFlowUtil.GetWorkflowList(listName);

            // Query to get the unprocessed items.

            SPListItemCollection unprocessedItems = splTask.GetItems(query);

            // Build the CAML delete commands.
            foreach (SPListItem item in unprocessedItems)
            {
                methodBuilder.AppendFormat(methodFormat, "1", item.ParentList.ID, item.ID.ToString());
            }

            // Put the pieces together.
            batch = string.Format(batchFormat, methodBuilder.ToString());

            // Process the batch of commands.
            string batchReturn = web.ProcessBatchData(batch.ToString());
        }
Exemplo n.º 2
0
        public void Insert(SPList mediaList, MediaAsset asset, out int id, out string contentTypeId)
        {
            var item = mediaList.Items.Add();
            item["ContentTypeId"] = GetContentTypeId(mediaList, asset.MediaType.ToString());
            item["Title"] = asset.Title;
            item[new Guid(MediaAssetsColumns.TempLocation)] = asset.TempLocation;
            item[new Guid(MediaAssetsColumns.Format)] = asset.Format;
            item[new Guid(MediaAssetsColumns.ProcStatus)] = Enum.GetName(typeof(ProcessingStatus), asset.Status);
            if (!String.IsNullOrEmpty(asset.Location))
            {
                item[new Guid(MediaAssetsColumns.Location)] = asset.Location;
            }
            if (!String.IsNullOrEmpty(asset.Thumbnail))
            {
                item[new Guid(MediaAssetsColumns.Thumbnail)] = asset.Thumbnail;
            }
            if (!String.IsNullOrEmpty(asset.Poster))
            {
                item[new Guid(MediaAssetsColumns.Poster)] = asset.Poster;
            }
            if ((asset.MediaType == MediaType.Audio || asset.MediaType == MediaType.Video) && asset.Duration != TimeSpan.MinValue)
            {
                item[new Guid(MediaAssetsColumns.Length)] = asset.Duration.TotalSeconds;
            }
            item.Update();

            id = item.ID;
            contentTypeId = item.ContentTypeId.ToString();
        }
Exemplo n.º 3
0
        private SPListItem EnsureListItem(SPList list, ListItemDefinition listItemModel)
        {
            // TODO, lazy to query
            // BIG TODO, don't tell me, I know that
            var currentItem = list.Items
                            .OfType<SPListItem>()
                            .FirstOrDefault(i => i.Title == listItemModel.Title);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = currentItem,
                ObjectType = typeof(SPListItem),
                ObjectDefinition = listItemModel,
                ModelHost = list
            });

            if (currentItem == null)
            {
                var newItem = list.AddItem();

                newItem["Title"] = listItemModel.Title;

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioned,
                    Object = newItem,
                    ObjectType = typeof(SPListItem),
                    ObjectDefinition = listItemModel,
                    ModelHost = list
                });

                newItem.Update();

                return newItem;
            }
            else
            {
                currentItem["Title"] = listItemModel.Title;

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioned,
                    Object = currentItem,
                    ObjectType = typeof(SPListItem),
                    ObjectDefinition = listItemModel,
                    ModelHost = list
                });

                currentItem.Update();

                return currentItem;
            }
        }
 public MoveListItemCommand(SPListItem copyItem, SPList targetList, List<string> siteColumnGroups, SPWeb web)
     : base(web)
 {
     _CopyItem = copyItem;
     _SiteColumnGroups = siteColumnGroups;
     _List = targetList;
 }
Exemplo n.º 5
0
        /// <summary>
        /// Sets the lookup to a list.
        /// </summary>
        /// <param name="fieldCollection">The field collection.</param>
        /// <param name="fieldId">The field identifier of the lookup field.</param>
        /// <param name="lookupList">The lookup list.</param>
        /// <exception cref="System.ArgumentNullException">
        /// fieldCollection
        /// or
        /// fieldId
        /// or
        /// lookupList
        /// </exception>
        /// <exception cref="System.ArgumentException">Unable to find the lookup field.;fieldId</exception>
        public void SetLookupToList(SPFieldCollection fieldCollection, Guid fieldId, SPList lookupList)
        {
            if (fieldCollection == null)
            {
                throw new ArgumentNullException("fieldCollection");
            }

            if (fieldId == null)
            {
                throw new ArgumentNullException("fieldId");
            }

            if (lookupList == null)
            {
                throw new ArgumentNullException("lookupList");
            }

            this.logger.Info("Start method 'SetLookupToList' for field id: '{0}'", fieldId);

            // Get the field.
            SPFieldLookup lookupField = this.fieldLocator.GetFieldById(fieldCollection, fieldId) as SPFieldLookup;
            if (lookupField == null)
            {
                throw new ArgumentException("Unable to find the lookup field.", "fieldId");
            }

            // Configure the lookup field.
            this.SetLookupToList(lookupField, lookupList);

            this.logger.Info("End method 'SetLookupToList'.");
        }
Exemplo n.º 6
0
        internal override void CreateField(SPList list)
        {
            if (!list.Fields.ContainsFieldWithStaticName(InternalName))
            {
                list.Fields.Add(InternalName, SPFieldType.Currency, Required);
            }

            var field = (SPFieldCurrency) list.Fields.GetFieldByInternalName(InternalName);
            field.Description = Description;
            field.MinimumValue = MinimumValue;
            field.MaximumValue = MaximumValue;
            field.DisplayFormat = DisplayFormat;
            field.DefaultValue = DefaultValue;
            field.CurrencyLocaleId = CurrencyLocaleId;
            if (EnforceUniqueValues)
            {
                field.Indexed = true;
                field.EnforceUniqueValues = true;
            }
            field.ValidationFormula = ValidationFormula;
            field.ValidationMessage = ValidationMessage;
            field.Title = Name;
            field.AllowDeletion = true;
            field.Update();
        }
        internal SPListItemCollection GetListItemCollection(SPList spList, string keyOne, string valueOne, string keyTwo, string valueTwo,string keyThree, string valueThree)
        {
            // Return list item collection based on the lookup field

            SPField spFieldOne = spList.Fields[keyOne];
            SPField spFieldTwo = spList.Fields[keyTwo];
            SPField spFieldThree = spList.Fields[keyThree];
            var query = new SPQuery
            {
                Query = @"<Where>
                          <And>
                             <And>
                                <Eq>
                                   <FieldRef Name=" + spFieldOne.InternalName + @" />
                                   <Value Type=" + spFieldOne.Type.ToString() + @">" + valueOne + @"</Value>
                                </Eq>
                                <Eq>
                                   <FieldRef Name=" + spFieldTwo.InternalName + @" />
                                   <Value Type=" + spFieldTwo.Type.ToString() + @">" + valueTwo + @"</Value>
                                </Eq>
                             </And>
                             <Eq>
                                <FieldRef Name=" + spFieldThree.InternalName + @" />
                                <Value Type=" + spFieldThree.Type.ToString() + @">" + valueThree + @"</Value>
                             </Eq>
                          </And>
                       </Where>"
            };

            return spList.GetItems(query);
        }
Exemplo n.º 8
0
        public static void AddEventReceivers(SPList list, Type t, string eventData, params SPEventReceiverType[] eventTypes  )
        {
            try
            {
                string assambly = t.Assembly.FullName;
                string className = t.FullName;

                foreach (SPEventReceiverType et in eventTypes)
                {
                    SPEventReceiverDefinition ef = list.EventReceivers.Add();

                    ef.Assembly = assambly ;
                    ef.Class = className ;
                    ef.Type = et ;
                    ef.Data = eventData;
                    ef.Update();
                }

                //list.Update();
            }
            catch
            {
                throw;
            }
        }
Exemplo n.º 9
0
        internal override void CreateField(SPList list)
        {
            if (!list.Fields.ContainsFieldWithStaticName(InternalName))
            {
                list.Fields.Add(InternalName, SPFieldType.Choice, Required);
            }

            var field = (SPFieldChoice) list.Fields.GetFieldByInternalName(InternalName);
            field.Description = Description;

            field.Choices.Clear();

            foreach (var choice in this.Choices)
            {
                field.Choices.Add(choice);
            }
            field.EditFormat = this.EditFormat;
            field.FillInChoice = this.FillInChoice;
            field.DefaultValue = this.DefaultValue;
            if (EnforceUniqueValues)
            {
                field.Indexed = true;
                field.EnforceUniqueValues = true;
            }
            field.ValidationFormula = ValidationFormula;
            field.ValidationMessage = ValidationMessage;
            field.Title = Name;
            field.AllowDeletion = true;
            field.Update();
        }
Exemplo n.º 10
0
        internal override void CreateField(SPList list)
        {
            if (!list.Fields.ContainsFieldWithStaticName(InternalName))
            {
                list.Fields.AddFieldAsXml(string.Format("<Field Type=\"UserMulti\" DisplayName=\"{0}\" List=\"UserInfo\" ShowField=\"ImnName\" Required=\"{1}\" UserSelectionMode=\"{2}\" UserSelectionScope=\"{3}\" Mult=\"TRUE\" Sortable=\"FALSE\" />", InternalName, Required.ToString().ToUpperInvariant(), SelectionMode, SelectionGroup), false, SPAddFieldOptions.Default);
            }

            var field = (SPFieldUser) list.Fields.GetFieldByInternalName(InternalName);
            field.Description = Description;
            field.SelectionMode = SelectionMode;
            field.AllowMultipleValues = AllowMultipleValues;

            if (!string.IsNullOrEmpty(ShowField))
                field.LookupField = ShowField;
            else
                field.LookupField = "ImnName";

            if (SelectionGroup > 0)
            {
                field.SelectionGroup = SelectionGroup;
            }

            if (EnforceUniqueValues)
            {
                field.Indexed = true;
                field.EnforceUniqueValues = true;
            }

            field.Title = Name;
            field.AllowDeletion = true;
            field.Update();
        }
Exemplo n.º 11
0
		// Executes the expression tree that is passed to it. 
		internal static object Execute(SPList list, Expression expression, bool isEnumerable)
		{
			// The expression must represent a query over the data source. 
			if (!IsQueryOverDataSource(expression))
				throw new InvalidProgramException("No query over the data source was specified.");

			var caml = (new CamlTranslator()).Translate(null, expression);

			var query = new SPQuery();

			var viewFieldsXml = caml.Element(Tags.ViewFields);
			var rowLimitXml = caml.Element(Tags.RowLimit);
			var queryXml = caml.Elements()
				.Where(n => n.Name != Tags.ViewFields && n.Name != Tags.RowLimit)
				.ToList();

			query.Query = (new XElement(Tags.Query, queryXml)).Value;
			if (viewFieldsXml != null)
			{
				query.ViewFields = viewFieldsXml.Value;
				query.ViewFieldsOnly = true;
			}
			if (rowLimitXml != null)
			{
				query.RowLimit = (int)rowLimitXml.Value;
			}

			return list.GetItems(query);
		}
        private void AssertSPListHost(SPList targetList, SPGroup securityGroup, SecurityRoleLinkDefinition securityRoleLinkModel)
        {
            var web = targetList.ParentWeb;
            var role = web.RoleDefinitions[securityRoleLinkModel.SecurityRoleName];

            // check if roleAssignment has current  role

            TraceUtils.WithScope(traceScope =>
            {
                traceScope.WriteLine(string.Format("Validate model:[{0}] securableObject:[{1}]", securityRoleLinkModel, targetList));

                traceScope.WithTraceIndent(trace =>
                {
                    // asserting it exists
                    traceScope.WriteLine(string.Format("Validating existance..."));

                    var roleAssignment = targetList
                                            .RoleAssignments
                                            .OfType<SPRoleAssignment>()
                                            .FirstOrDefault(r => r.Member.ID == securityGroup.ID);

                    Assert.IsNotNull(roleAssignment);

                    traceScope.WriteLine(string.Format("Validating role presence..."));
                    roleAssignment.RoleDefinitionBindings.Contains(role);

                    traceScope.WriteLine(string.Format("Role [{0}] exists!", securityRoleLinkModel.SecurityRoleName));
                });
            });
        }
 public static void CheckandAddEntry(SPList configurationList, Guid ProjectGuid, Project Project_Svc)
 {
     try
     {
         // Checking whether the project id is already available.
         var query = new SPQuery
         {
             Query =
                 @"<Where><Eq><FieldRef Name='" + ProjectUIDFieldName + "' /><Value Type='Text'>" + ProjectGuid.ToString() + "</Value></Eq></Where>"
         };
         var ProjectItemCollection = configurationList.GetItems(query);
         if (ProjectItemCollection.Count == 0)
         {
             configurationList.ParentWeb.Site.RootWeb.AllowUnsafeUpdates = true;
             SPListItem item = configurationList.Items.Add();
             //first project name
             item["Title"] = Project_Svc.GetProjectNameFromProjectUid(ProjectGuid, DataStoreEnum.WorkingStore);
             item[GroupFieldName] = DefaultGroupValue;
             item[ProjectUIDFieldName] = ProjectGuid.ToString();
             item.Update();
             configurationList.ParentWeb.Site.RootWeb.Update();
         }
     }
     catch (Exception ex)
     {
         ErrorLog("Error at adding configuration item to the list due to " + ex.Message, EventLogEntryType.Error);
     }
 }
Exemplo n.º 14
0
        internal SPView Apply(SPList list)
        {
            SPView view;
            try
            {
                view = list.Views[Name];
            }
            catch (Exception ex)
            {
                var viewFields = new StringCollection();
                foreach (var viewField in ViewFields)
                {
                    viewFields.Add(GetInternalFieldName(list, viewField));
                }

                var camlQuery = TransformCamlQuery(list, Query);

                view = list.Views.Add(Name, viewFields, camlQuery, RowLimit, true, MakeViewDefault);

                if (!string.IsNullOrEmpty(UserControlPath))
                {
                    var web = list.ParentWeb;
                    WebPartHelper.HideDefaultWebPartOnView(web, view);
                    var containerWebPart = WebPartHelper.GetContainerWebPart(web);
                    containerWebPart.Title = string.Format(CultureInfo.InvariantCulture, "{0} - Custom View", Name);
                    containerWebPart.UserControlPath = UserControlPath;
                    WebPartHelper.AddWebPartToViewPage(web, view, containerWebPart);
                }
            }

            return view;
        }
Exemplo n.º 15
0
        private static void Import_Firma(Microsoft.SharePoint.SPWeb web, SPList list)
        {
            list.Items.Cast<SPListItem>()
                .Where(i => i["colTypRekordu"].ToString() == "Firma")
                .ToList()
                .ForEach(item =>
                {
                    string nazwaSkrocona = item["colNazwaSkrocona"] != null ? item["colNazwaSkrocona"].ToString() : string.Empty;
                    string nazwa = item["colNazwa"] != null ? item["colNazwa"].ToString() : string.Empty;
                    int klientId = tabKlienci.Get_KlientByNazwaSkrocona(web, nazwaSkrocona);

                    if (!string.IsNullOrEmpty(nazwa)
                        && !string.IsNullOrEmpty(nazwaSkrocona)
                        && klientId > 0)
                    {
                        int firmaId = tabKlienci.Get_FirmaByNazwa(web, nazwaSkrocona, nazwa);

                        if (firmaId == 0)
                        {
                            firmaId = tabKlienci.AddNew_Firma_Klient(web, item, klientId);

                            item["selKlient"] = firmaId;
                            item.SystemUpdate();
                        }

                    }
                });
        }
Exemplo n.º 16
0
        public void VerifyModifyTaskList(SPList taskList, string contentType)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(workflowProperties.Item.Web.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList task = web.Lists[workflowProperties.TaskListId];

                        if (taskList.ContentTypesEnabled != true)
                        {
                            workflowProperties.TaskList.ContentTypesEnabled = true;
                        }

                        foreach (SPContentType cp in web.ContentTypes)
                        {
                            if (cp.Name.Equals(contentType))
                            {

                                SPContentType cp1 = task.ContentTypes.Add(cp);
                                task.Update();
                                ContentTypeID = cp1.Id.ToString();
                                break;
                            }
                        }
                    }
                }
            });
        }
Exemplo n.º 17
0
Arquivo: Tools.cs Projeto: fraczo/BR5
        private static void Create_Column(SPList list, string targetColumn)
        {
            SPFieldText f = (SPFieldText)list.Fields.CreateNewField(SPFieldType.Text.ToString(), targetColumn);

            list.Fields.Add(f);
            list.Update();
        }
Exemplo n.º 18
0
        private static void Import_OsobaFizyczna(Microsoft.SharePoint.SPWeb web, SPList list)
        {
            list.Items.Cast<SPListItem>()
                .Where(i => i["colTypRekordu"].ToString() == "Osoba fizyczna")
                .ToList()
                .ForEach(item =>
                {
                    string nazwaSkrocona = item["colNazwaSkrocona"] != null ? item["colNazwaSkrocona"].ToString() : string.Empty;
                    string pesel = item["colPESEL"] != null ? item["colPESEL"].ToString() : string.Empty;
                    int klientId = tabKlienci.Get_KlientByNazwaSkrocona(web, nazwaSkrocona);

                    if (!string.IsNullOrEmpty(pesel)
                        && !string.IsNullOrEmpty(nazwaSkrocona)
                        && klientId > 0)
                    {
                        int osobaId = tabKlienci.Get_OsobaFizycznaByPesel(web, nazwaSkrocona, pesel);

                        if (osobaId == 0)
                        {
                            osobaId = tabKlienci.AddNew_OsobaFizyczna_Klient(web, item, klientId);

                            item["selKlient"] = osobaId;
                            item.SystemUpdate();
                        }
                    }

                });
        }
Exemplo n.º 19
0
        protected void EnsureRequestParamsParsed()
        {
            workflowName = Request.Params["WorkflowName"];

            string strListID = Request.QueryString["List"];
            string strCTID = Request.QueryString["ctype"];

            if (strListID != null)
                list = Web.Lists[new Guid(strListID)];

            if (strCTID != null)
            {
                requestQueryString = "ctype=" + strCTID;

                if (list != null)
                {
                    requestQueryString += "&List=" + strListID;
                    contentType = list.ContentTypes[new SPContentTypeId(strCTID)];
                }
                else
                {
                    contentType = Web.ContentTypes[new SPContentTypeId(strCTID)];
                    useContentTypeTemplate = true;
                }
            }
            else
                requestQueryString = "List=" + strListID;
        }
Exemplo n.º 20
0
        /// <summary>
        /// Generates a SPQuery filter for Taxonomy Term
        /// </summary>
        /// <param name="list">The list over which the query will be done</param>
        /// <param name="taxonomyFieldInternalName">The name of the site column associated with the term set</param>
        /// <param name="terms">List of terms for why we want to match in an OR fashion</param>
        /// <param name="includeDescendants">Whether the Term's child terms should be query hits as well</param>
        /// <returns>The SPQuery filter</returns>
        public string TermFilter(SPList list, string taxonomyFieldInternalName, IList<Term> terms, bool includeDescendants)
        {
            string values = string.Empty;

            foreach (var term in terms)
            {
                try
                {
                    values += this.GetAllWssIdByTerm(list, term, includeDescendants);
                }
                catch (ArgumentException)
                {
                    // ignore the not-found labels
                }
            }

            // Filter over the taxonomy field with the proper SID lookup id to the taxonomy hidden list
            if (!string.IsNullOrEmpty(values))
            {
                var query = string.Format(
                    CultureInfo.InvariantCulture,
                    "<In><FieldRef Name='{0}' LookupId='TRUE'/><Values>{1}</Values></In>",
                    taxonomyFieldInternalName,
                    values);

                return query;
            }

            return string.Empty;
        }
Exemplo n.º 21
0
 public static void AddXsltViewWebPart(SPWeb web, SPList list, string pageUrl, string webPartName, string zoneID,
     int zoneIndex, bool isHidden, string viewTitle)
 {
     using (SPLimitedWebPartManager webPartManager = web.GetLimitedWebPartManager(
             pageUrl, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
     {
         bool isExists = false;
         foreach (System.Web.UI.WebControls.WebParts.WebPart wp in webPartManager.WebParts)
         {
             if (wp.Title.Equals(webPartName))
             {
                 isExists = true;
                 break;
             }
             else
             {
                 isExists = false;
             }
         }
         if (!isExists)
         {
             XsltListViewWebPart webPart = new XsltListViewWebPart();
             webPart.ListId = list.ID;
             webPart.Title = webPartName;
             webPart.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.TitleAndBorder;
             SPView view = list.Views[viewTitle];
             webPart.ViewGuid = view.ID.ToString();
             webPart.XmlDefinition = view.GetViewXml();
             webPartManager.AddWebPart(webPart, zoneID, zoneIndex);
         }
     }
 }
Exemplo n.º 22
0
        //string sTitle, string sAssignedTo)//sTitle, sAssignedTo
        /// <summary>
        /// 检测list里是否存在重复的task记录
        /// </summary>
        /// <param name="splCompletedTasks"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool isUnique(SPList splCompletedTasks,string id)
        {
            SPQuery query = new SPQuery();
            query.Query = string.Format(@"
                                            <Where>
                                                 <Eq>
                                                     <FieldRef Name='TaskID' />
                                                     <Value Type='Text'>{0}</Value>
                                                  </Eq>
                                            </Where>", id);
            //            query.Query = string.Format(@" <Where>
            //                                              <And>
            //                                                 <Eq>
            //                                                    <FieldRef Name='AssignedTo' />
            //                                                    <Value Type='User'>{0}</Value>
            //                                                 </Eq>
            //                                                 <Contains>
            //                                                    <FieldRef Name='Title' />
            //                                                    <Value Type='Text'>{1}</Value>
            //                                                 </Contains>
            //                                              </And>
            //                                           </Where>",sAssignedTo,sTitle);

            int iCount = splCompletedTasks.GetItems(query).Count;
            if (iCount > 0)
            {
                return false;
            }
            else
            {
            return true;
            }
        }
Exemplo n.º 23
0
        private static void CleanList(SPList list)
        {
            if (list == null)
                throw new ArgumentNullException("list");

            SPQuery spQuery = CreateGetAllItemsQuery();

            int batchNumber = 1;

            while (true)
            {
                // get ids of items to be deleted
                SPListItemCollection items = list.GetItems(spQuery);
                if (items.Count <= 0)
                    break;

                string batchDeleteXmlCommand = GetBatchDeleteXmlCommand(list, items);

                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();

                RunDeleteBatch(list, batchDeleteXmlCommand);

                stopwatch.Stop();

                Console.WriteLine(string.Format("Processed batch #{0} of {1} items in {2} second(s)", batchNumber, BatchSize, stopwatch.ElapsedMilliseconds / 1000.0));
                batchNumber++;
            }
        }
        private static SPListItemCollection GetCostsFromMonth(SPList costs, SPListItemCollection delegationsForSelectedMonth)
        {
            StringBuilder delegationIDBuilder = new StringBuilder();
            foreach (SPListItem delegationItem in delegationsForSelectedMonth)
            {
                delegationIDBuilder.AppendFormat("<Value Type='Lookup'>{0}</Value>", delegationItem["ID"]);
            }

            string costsForSelectedDelagationsQueryString = string.Format(
                "<Where>" +
                    "<In>" +
                        "<FieldRef Name='{0}' LookupId='TRUE'/>" +
                            "<Values>" +
                                "{1}" +
                            "</Values>" +
                    "</In>" +
                "</Where>",
                DelegationsFields.Delegation.Name,
                delegationIDBuilder);

            SPQuery costsForSelectedDelegationsQuery = new SPQuery();
            costsForSelectedDelegationsQuery.Query = costsForSelectedDelagationsQueryString;

            SPListItemCollection monthlyCosts = costs.GetItems(costsForSelectedDelegationsQuery);
            return monthlyCosts;
        }
Exemplo n.º 25
0
 public static string GenerateValidImageName(string fileName, SPList pictureLibrary)
 {
     //Check if new image name validates
     int i = 0;
     string temp = fileName;
     string extention = Path.GetExtension(fileName);
     SPQuery query = new SPQuery(pictureLibrary.DefaultView);
     SPListItemCollection imageCollection;
     do
     {
         i++;
         query.ViewFields = "<Where><Eq><FieldRef Name='LinkFilename' /><Value Type='Computed'>" + fileName + "</Value></Eq></Where>";
         imageCollection = pictureLibrary.GetItems(query);
         if (imageCollection.Count > 0)
         {
             fileName = temp;
             string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName) + " " + i;
             fileName = fileNameWithoutExtension + extention;
         }
         else {
             break;
         }
     } while (imageCollection.Count > 0);
     return fileName;
 }
        internal override void CreateField(SPList list)
        {
            if (!list.Fields.ContainsFieldWithStaticName(InternalName))
            {
                list.Fields.Add(InternalName, SPFieldType.Note, Required);
            }
            else
            {
                var oldField = list.Fields.GetFieldByInternalName(InternalName);
                if (!oldField.Type.Equals(SPFieldType.Note))
                {
                    oldField.Type = SPFieldType.Note;
                    oldField.Update();
                }
            }

            var field = (SPFieldMultiLineText) list.Fields.GetFieldByInternalName(InternalName);
            field.Description = this.Description;
            field.NumberOfLines = this.NumberOfLines;
            field.RichText = this.RichText;
            if (this.RichText)
            {
                field.RichTextMode = this.RichTextMode;
            }

            field.AppendOnly = this.AppendOnly;
            field.Title = this.Name;
            field.AllowDeletion = true;
            field.Update();
        }
        private DataTable setColumnsToDisplayName(DataTable dat, SPList list)
        {
            foreach (DataColumn dc in dat.Columns)
            {

                dc.ColumnName = list.Fields.GetFieldByInternalName(dc.ColumnName).Id.ToString();

            }
            foreach (DataColumn dc in dat.Columns)
            {

                string colName = list.Fields[new Guid(dc.ColumnName)].Title;
                if (dat.Columns.Contains(colName))
                {
                    int i = 1;
                    while (dat.Columns.Contains(colName + "_" + i.ToString()))
                    {
                        i++;
                    }
                    colName = colName + "_" + i.ToString();
                }
                dc.ColumnName = colName;

            }

            return dat;
        }
Exemplo n.º 28
0
        internal override void CreateField(SPList list)
        {
            if (!list.Fields.ContainsFieldWithStaticName(InternalName))
            {
                list.Fields.Add(InternalName, SPFieldType.Text, Required);
            }

            var field = (SPFieldText)list.Fields.GetFieldByInternalName(InternalName);
            field.Description = Description;
            field.MaxLength = MaxLength;
            field.DefaultValue = DefaultValue;

            if (EnforceUniqueValues)
            {
                field.Indexed = true;
                field.EnforceUniqueValues = true;
            }
            field.Title = Name;
            //field.ShowInDisplayForm = ShowInDisplayForm;
            //field.ShowInEditForm = ShowInEditForm;
            //field.ShowInNewForm = ShowInNewForm;
            field.ValidationFormula = ValidationFormula;
            field.ValidationMessage = ValidationMessage;
            field.AllowDeletion = true;
            field.Update();
        }
Exemplo n.º 29
0
        /// <summary>
        /// Adds the Feedback.
        /// </summary>
        internal void AddFeedback(SPList feedbackList, string userID, Feedback feedbackInfo)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    //Adds the new Feedback to the current folder.
                    SPFolder currentFolder = feedbackList.Folders[feedbackList.Folders.Count - 1].Folder;
                    ;
                    SPListItem newItem = feedbackList.Items.Add(currentFolder.ServerRelativeUrl, SPFileSystemObjectType.File, null);
                    newItem["Title"] = userID + "_" + DateTime.Now.ToString("MMM-dd-yyyy");
                    newItem["Rating"] = feedbackInfo.Rating;
                    newItem["Reason for Rating"] = feedbackInfo.Reason;
                    newItem["Additional Information"] = feedbackInfo.AdditionalInformation;
                    newItem["Type of Feedback"] = feedbackInfo.TypeofFeedback;
                    newItem["Page Level Comment"] = feedbackInfo.Comment;
                    if(feedbackInfo.TypeofFeedback.ToString() == GENERALFEEDBACK)
                        newItem["Page Name"] = string.Empty;
                    else
                        newItem["Page Name"] = feedbackInfo.PageName;
                    if(feedbackInfo.FileAttached != null)
                    {
                        newItem.Attachments.Add(feedbackInfo.FileName, feedbackInfo.FileAttached);
                    }

                    newItem.Update();
                });
            }
            catch(Exception)
            {
                throw;
            }
        }
Exemplo n.º 30
0
        private void EnsureVersioningControl(SPList list)
        {
            var temp = list.ParentWeb.AllowUnsafeUpdates;

            try
            {
                list.ParentWeb.AllowUnsafeUpdates = true;

                list.EnableVersioning = true;
                list.EnableModeration = true;

                //enable minor versions for documents
                list.EnableMinorVersions = true;

                //set maximum limits for major/minor versions
                list.MajorVersionLimit = 5;
                list.MajorWithMinorVersionsLimit = 5;

                list.Update();
            }
            catch { }
            finally
            {
                list.ParentWeb.AllowUnsafeUpdates = temp;
            }
        }
Exemplo n.º 31
0
        /// <summary>
        /// Adds the remove PFE data sync events.
        /// </summary>
        /// <param name="operation">The operation.</param>
        /// <param name="dataElement">The data element.</param>
        private void AddRemovePFEDataSyncEvents(string operation, ref XElement dataElement)
        {
            const string assembly = "WorkEnginePPM, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5";

            var classDict = new Dictionary <EPMLiveLists, string>
            {
                { EPMLiveLists.Departments, "DepartmentSyncEvent" },
                { EPMLiveLists.Holidays, "HolidaySyncEvent" },
                { EPMLiveLists.Roles, "RoleSyncEvent" },
                { EPMLiveLists.WorkHours, "WorkScheduleSyncEvent" },
                { EPMLiveLists.HolidaySchedules, "HolidayScheduleSyncEvent" },
            };

            using (SPSite spSite = new SPSite(Web.Site.ID))
            {
                spSite.AllowUnsafeUpdates = true;

                using (SPWeb spWeb = spSite.OpenWeb(Web.ID))
                {
                    spWeb.AllowUnsafeUpdates = true;

                    foreach (var keyValuePair in classDict)
                    {
                        KeyValuePair <EPMLiveLists, string> listEventInfo = keyValuePair;

                        IEnumerable <Guid> listIds = spWeb.Lists.Cast <SPList>()
                                                     .Where(spList => (int)spList.BaseTemplate == (int)listEventInfo.Key)
                                                     .Select(spList => spList.ID);

                        foreach (Guid listId in listIds)
                        {
                            var spEventReceiverTypes = new[]
                            {
                                SPEventReceiverType.ItemAdding,
                                SPEventReceiverType.ItemUpdating,
                                SPEventReceiverType.ItemDeleting,
                                SPEventReceiverType.ItemAdded
                            };

                            AddEventReceiverElement(operation,
                                                    string.Format("WorkEnginePPM.Events.DataSync.{0}",
                                                                  listEventInfo.Value),
                                                    assembly, spEventReceiverTypes,
                                                    listId, ref dataElement);

                            ConfigureExtIdField(listId, spWeb);
                        }
                    }

                    SPList timeOffList = spWeb.Lists.TryGetList("Time Off");

                    if (timeOffList != null)
                    {
                        var spEventReceiverTypes = new[]
                        {
                            SPEventReceiverType.ItemAdded,
                            SPEventReceiverType.ItemUpdated,
                            SPEventReceiverType.ItemDeleting
                        };

                        Guid listId = timeOffList.ID;

                        AddEventReceiverElement(operation, "WorkEnginePPM.Events.DataSync.TimeOffSyncEvent", assembly,
                                                spEventReceiverTypes, listId, ref dataElement);

                        ConfigureExtIdField(listId, spWeb);
                    }

                    SPList personalItemsList = spWeb.Lists.TryGetList("Non Work");

                    if (personalItemsList != null)
                    {
                        var spEventReceiverTypes = new[]
                        {
                            SPEventReceiverType.ItemAdded,
                            SPEventReceiverType.ItemAdding,
                            SPEventReceiverType.ItemUpdating,
                            SPEventReceiverType.ItemDeleting
                        };

                        Guid listId = personalItemsList.ID;

                        AddEventReceiverElement(operation, "WorkEnginePPM.Events.DataSync.PersonalItemsEvent", assembly,
                                                spEventReceiverTypes, listId, ref dataElement);

                        ConfigureExtIdField(listId, spWeb);
                    }

                    SPList rolesList = spWeb.Lists.TryGetList("Roles");

                    if (rolesList != null)
                    {
                        bool fieldAdded = false;

                        if (!rolesList.Fields.ContainsFieldWithInternalName("RoleId"))
                        {
                            var roleIdField = (SPFieldText)rolesList.Fields.CreateNewField(SPFieldType.Text.ToString(), "RoleId");

                            roleIdField.Hidden = true;

                            rolesList.Fields.Add(roleIdField);

                            fieldAdded = true;
                        }

                        if (!rolesList.Fields.ContainsFieldWithInternalName("CCRName"))
                        {
                            var ccrNameField = (SPFieldText)rolesList.Fields.CreateNewField(SPFieldType.Text.ToString(), "CCRName");

                            rolesList.Fields.Add(ccrNameField);

                            fieldAdded = true;
                        }

                        if (fieldAdded)
                        {
                            rolesList.Update();

                            SPField roleIdField = rolesList.Fields.GetFieldByInternalName("RoleId");
                            roleIdField.Title = "Role ID";
                            roleIdField.Update();

                            SPField ccrNameField = rolesList.Fields.GetFieldByInternalName("CCRName");
                            ccrNameField.Title = "Display Name";
                            ccrNameField.Update();
                        }
                    }

                    spWeb.AllowUnsafeUpdates = false;
                }

                spSite.AllowUnsafeUpdates = false;
            }
        }
Exemplo n.º 32
0
        private void RefreshBoundData()
        {
            //if (SelectedNodePath != "")
            // {
            //   SelectedRecordsType.Text = SelectedNodePath.Replace("Records Types/", "").Replace("/", " / ");

            WBRecordsType recordsType    = null;
            WBTerm        functionalArea = null;
            WBTerm        subjectTag     = null;

            /*
             *  switch (SelectedView)
             *  {
             *      case VIEW_BY_RECORDS_TYPE:
             *          {
             *              recordsType = recordsTypesTaxonomy.GetSelectedRecordsType(SelectedNodePath);
             *             // SelectedRecordsTypeDescription.Text = recordsType.Description;
             *              break;
             *          }
             *
             *      case VIEW_BY_FUNCTION_THEN_TYPE:
             *          {
             *              string[] parts = SelectedNodePath.Split('/');
             *              if (parts.Length < 3) return;
             *
             *              string functionPath = parts[0];
             *              List<String> partsList = new List<String>(parts);
             *              partsList.RemoveAt(0);
             *              string recordsTypePath = String.Join("/", partsList.ToArray());
             *
             *              Term functionalAreaTerm = functionalAreaTaxonomy.GetSelectedTermByPath(functionPath);
             *              if (functionalAreaTerm != null)
             *              {
             *                  functionalArea = new WBTerm(functionalAreaTaxonomy, functionalAreaTerm);
             *              }
             *
             *              recordsType = recordsTypesTaxonomy.GetSelectedRecordsType(recordsTypePath);
             *             // SelectedRecordsTypeDescription.Text = recordsType.Description;
             *              break;
             *          }
             *
             *      case VIEW_BY_SUBJECT:
             *          {
             *              Term subjectTagsTerm = subjectTagsTaxonomy.GetSelectedTermByPath(SelectedNodePath);
             *              if (subjectTagsTerm != null)
             *              {
             *                  subjectTag = new WBTerm(subjectTagsTaxonomy, subjectTagsTerm);
             *                  SelectedRecordsTypeDescription.Text = subjectTag.Description;
             *              }
             *
             *              if (subjectTag == null)
             *              {
             *                  WBLogging.Debug("Did not find subject with path: " + SelectedNodePath);
             *                  return;
             *              }
             *              break;
             *          }
             *
             *
             *      default: return;
             *
             *  }
             */

            WBTeam team = null;

            if (!String.IsNullOrEmpty(webPart.FilterByOwningTeam))
            {
                team = teamsTaxonomy.GetSelectedTeam(webPart.FilterByOwningTeam);
            }

            if (team == null)
            {
                team = WBTeam.GetFromTeamSite(teamsTaxonomy, SPContext.Current.Web);
            }

            if (team == null)
            {
                WBUtils.shouldThrowError("There was no team configured - so we'll jus stop");
                return;
            }


            WBFarm farm = WBFarm.Local;

            using (SPSite site = new SPSite(farm.ProtectedRecordsLibraryUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    WBQuery query = new WBQuery();

                    if (recordsType != null)
                    {
                        WBQueryClause recordsTypeClause = new WBQueryClause(WBColumn.RecordsType, WBQueryClause.Comparators.Equals, recordsType);
                        recordsTypeClause.UseDescendants = true;
                        query.AddClause(recordsTypeClause);
                    }

                    if (functionalArea != null)
                    {
                        WBQueryClause functionalAreaClause = new WBQueryClause(WBColumn.FunctionalArea, WBQueryClause.Comparators.Equals, functionalArea);
                        functionalAreaClause.UseDescendants = true;
                        query.AddClause(functionalAreaClause);
                    }

                    if (subjectTag != null)
                    {
                        WBQueryClause subjectTagClause = new WBQueryClause(WBColumn.SubjectTags, WBQueryClause.Comparators.Equals, subjectTag);
                        subjectTagClause.UseDescendants = false;
                        query.AddClause(subjectTagClause);
                    }

                    if (team != null)
                    {
                        query.AddEqualsFilter(WBColumn.OwningTeam, team);
                    }

                    //if (!String.IsNullOrEmpty(webPart.FilterByProtectiveZone))
                    // {
                    //   query.AddEqualsFilter(WBColumn.ProtectiveZone, webPart.FilterByProtectiveZone);
                    //}


                    query.AddViewColumn(WBColumn.Name);
                    query.AddViewColumn(WBColumn.Title);
                    query.AddViewColumn(WBColumn.TitleOrName);
//                        query.AddViewColumn(WBColumn.FileSize);
                    query.AddViewColumn(WBColumn.FileTypeIcon);
                    //                      query.AddViewColumn(WBColumn.FileType);
                    //                    query.AddViewColumn(WBColumn.DisplayFileSize);
                    query.AddViewColumn(WBColumn.EncodedAbsoluteURL);
                    //                  query.AddViewColumn(WBColumn.FunctionalArea);
                    //                query.AddViewColumn(WBColumn.OwningTeam);
                    query.AddViewColumn(WBColumn.ReferenceDate);
                    query.AddViewColumn(WBColumn.DeclaredRecord);
                    query.AddViewColumn(WBColumn.SeriesTag);
                    //            query.AddViewColumn(WBColumn.ProtectiveZone);

                    if (SelectedView != VIEW_BY_SUBJECT)
                    {
                        query.AddViewColumn(WBColumn.SubjectTags);
                    }
                    else
                    {
                        query.AddViewColumn(WBColumn.RecordsType);
                    }

                    if (sortColumn == null)
                    {
                        sortColumn = WBColumn.DeclaredRecord;
                        ascending  = false;
                    }

                    if (sortColumn != null)
                    {
                        query.OrderBy(sortColumn, ascending);
                    }

                    SPList recordsLibrary = web.GetList(farm.ProtectedRecordsLibraryUrl);     //"Documents"]; //farm.RecordsCenterRecordsLibraryName];

                    DataTable dataTable = recordsLibrary.WBxGetDataTable(site, query);

                    ShowResults.DataSource = dataTable;

                    ShowResults.Columns.Clear();
                    ShowResults.Columns.Add(WBUtils.DynamicIconTemplateField(WBColumn.FileTypeIcon, WBColumn.EncodedAbsoluteURL));
                    ShowResults.Columns.Add(WBUtils.HyperLinkField(WBColumn.TitleOrName, WBColumn.EncodedAbsoluteURL, sortColumn, ascending));
                    // ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.FileType, sortColumn, ascending));
                    //  ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.DisplayFileSize, sortColumn, ascending));
                    //                        ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.FunctionalArea, sortColumn, ascending));
                    ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.ReferenceDate, sortColumn, ascending));
                    //                      ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.ReferenceID, sortColumn, ascending));
                    //ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.SeriesTag, sortColumn, ascending));
                    // ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.OwningTeam, sortColumn, ascending));
                    //  ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.ProtectiveZone, sortColumn, ascending));

                    /*
                     * if (SelectedView != VIEW_BY_SUBJECT)
                     * {
                     *  ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.SubjectTags, sortColumn, ascending));
                     * }
                     * else
                     * {
                     *  ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.RecordsType, sortColumn, ascending));
                     * }
                     */

                    ShowResults.DataBind();
                }
            }

            /*
             * }
             * else
             * {
             *  WBUtils.logMessage("SelectedNodePath was empty");
             * }
             */
        }
Exemplo n.º 33
0
        public List <OrderCaseData> GetListsOld()
        {
            SPDataSource ds = new SPDataSource();

            ds.DataSourceMode  = SPDataSourceMode.List;
            ds.UseInternalName = true;
            ds.Scope           = SPViewScope.Recursive;
            ds.IncludeHidden   = true;

            string queryString;

            //queryString = "<View><ViewFields><FieldRef Name='ID'/><FieldRef Name='Title'/><FieldRef Name='PermMask'/></ViewFields><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>5</Value></Eq></Where></Query></View>";
            //queryString = "<View><ViewFields><FieldRef Name='ID'/><FieldRef Name='Title'/><FieldRef Name='PermMask'/></View>";
            queryString = "<View></View>";

            ds.SelectCommand = queryString;

            Parameter dbParam_ListId = new Parameter("ListID");

            dbParam_ListId.DefaultValue = "DF806E7E-0073-4202-99E3-C4A269E2FA5D";
            ds.SelectParameters.Add(dbParam_ListId);


            SPDataSourceView     dsw;
            List <OrderCaseData> dt = new List <OrderCaseData>();

            dsw = ds.GetView();

            SPList xlist = dsw.List;

            SPViewCollection colViews = xlist.Views;

            foreach (SPView vView in colViews)
            {
            }

            /*
             * SPListItem newFolder = xlist.Items.Add(xlist.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, null);
             * if (newFolder != null)
             * {
             *  newFolder["Title"] = "Min Nye Folder";
             *  newFolder.Update();
             * }
             */
            System.Web.UI.DataSourceSelectArguments args = new System.Web.UI.DataSourceSelectArguments();

            SPDataSourceViewResultItem[] arrResult = (SPDataSourceViewResultItem[])dsw.Select(args);
            foreach (SPDataSourceViewResultItem Result in arrResult)
            {
                SPListItem oListItem = (SPListItem)Result.ResultItem;
                //SPField myField = xitem.Fields[new Guid("{FE7E79DD-DD68-438e-A960-E3686025D44B}")];

                OrderCaseData r = new OrderCaseData();
                foreach (SPField ofield in oListItem.Fields)
                {
                    string tekst;
                    try
                    {
                        tekst = ">" + ofield.Title + "< >" + ofield.InternalName + "<>" + oListItem[ofield.Id] + "<";
                    }
                    catch
                    {
                        //OK
                    }

                    switch (ofield.InternalName)
                    {
                    case "ID":
                        r.ID = (int)oListItem[ofield.Id];
                        break;

                    case "Title":
                        r.Title = (string)oListItem[ofield.Id];
                        break;
                    }
                }
                dt.Add(r);
            }

            return(dt);
        }
Exemplo n.º 34
0
 private folder AddFolder(SPList list)
 {
     return(AddFolder(list.RootFolder, list.RoleAssignments, true));
 }
Exemplo n.º 35
0
 private static string GetInternalFieldName(SPList list, string fieldName)
 {
     return(list.Fields[fieldName].InternalName);
 }
        private void iInstallListsWorkflows(SPList list, XmlNode ndList, int ParentMessageId, bool added)
        {
            var ndWorkflows = ndList.SelectSingleNode("Workflows");

            if (ndWorkflows != null)
            {
                if (bVerifyOnly)
                {
                    ParentMessageId = addMessage(0, "Checking Workflows", string.Empty, ParentMessageId);
                }
                else
                {
                    ParentMessageId = addMessage(0, "Updating Workflows", string.Empty, ParentMessageId);
                }

                var ndParent = ndList.ParentNode;

                foreach (XmlNode ndWorkflow in ndWorkflows.SelectNodes("Workflow"))
                {
                    var sName = ApplicationInstallerHelpers.getAttribute(ndWorkflow, "Name");

                    var sDisplayName = ApplicationInstallerHelpers.getAttribute(ndWorkflow, "DisplayName");
                    if (sDisplayName == string.Empty)
                    {
                        sDisplayName = sName;
                    }

                    if (sName != string.Empty)
                    {
                        try
                        {
                            var sTaskList = ApplicationInstallerHelpers.getAttribute(ndWorkflow, "TaskList");
                            if (sTaskList == string.Empty)
                            {
                                sTaskList = "Workflow Tasks";
                            }

                            var sHistoryList = ApplicationInstallerHelpers.getAttribute(ndWorkflow, "HistoryList");
                            if (sHistoryList == string.Empty)
                            {
                                sHistoryList = "Workflow History";
                            }

                            var bOverwrite = false;
                            bool.TryParse(ApplicationInstallerHelpers.getAttribute(ndWorkflow, "Overwrite"), out bOverwrite);

                            var oTaskList    = oWeb.Lists.TryGetList(sTaskList);
                            var oHistoryList = oWeb.Lists.TryGetList(sHistoryList);

                            if (oTaskList != null || (IsListInstalledWithApplication(sTaskList) && bVerifyOnly))
                            {
                                if (oHistoryList != null || (IsListInstalledWithApplication(sHistoryList) && bVerifyOnly))
                                {
                                    if (bVerifyOnly)
                                    {
                                        var found = false;
                                        if (list != null)
                                        {
                                            foreach (SPWorkflowAssociation association in list.WorkflowAssociations)
                                            {
                                                if (association.BaseTemplate.Name == sName)
                                                {
                                                    found = true;
                                                    break;
                                                }
                                            }
                                        }
                                        if (found && !bOverwrite)
                                        {
                                            addMessage(ErrorLevels.Error, sName, "Workflow found and cannot overwrite", ParentMessageId);
                                        }
                                        else if (found)
                                        {
                                            addMessage(ErrorLevels.Upgrade, sName, "Workflow found and will upgrade", ParentMessageId);
                                        }
                                        else
                                        {
                                            addMessage(ErrorLevels.NoError, sName, string.Empty, ParentMessageId);
                                        }
                                    }
                                    else
                                    {
                                        SPWorkflowAssociation association = null;

                                        var found = false;

                                        foreach (SPWorkflowAssociation oassociation in list.WorkflowAssociations)
                                        {
                                            if (oassociation.BaseTemplate.Name == sName)
                                            {
                                                association = oassociation;
                                                found       = true;
                                                break;
                                            }
                                        }

                                        if (found && bOverwrite)
                                        {
                                            found = false;
                                            list.WorkflowAssociations.Remove(association);

                                            iInstallListsWorkflowsInstall(list, sName, sDisplayName, oTaskList, oHistoryList, ndWorkflow);

                                            addMessage(ErrorLevels.Upgrade, sName, "Workflow found and was upgraded", ParentMessageId);
                                        }
                                        else if (found)
                                        {
                                            addMessage(ErrorLevels.Error, sName, "Workflow found and could not overwrite", ParentMessageId);
                                        }
                                        else
                                        {
                                            iInstallListsWorkflowsInstall(list, sName, sDisplayName, oTaskList, oHistoryList, ndWorkflow);

                                            addMessage(ErrorLevels.NoError, sName, string.Empty, ParentMessageId);
                                        }
                                    }
                                }
                                else
                                {
                                    addMessage(ErrorLevels.Error, sName, "Workflow history list (" + sHistoryList + ") does not exist",
                                               ParentMessageId);
                                }
                            }
                            else
                            {
                                addMessage(ErrorLevels.Error, sName, "Workflow task list (" + sTaskList + ") does not exist", ParentMessageId);
                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.WriteLine(ex.ToString());
                            addMessage(ErrorLevels.Error, sName, "Error: " + ex.Message, ParentMessageId);
                        }
                    }
                }
            }
        }
        private void iInstallListsWorkflowsInstall(SPList oList, string sName, string sDisplayName, SPList oTaskList, SPList oHistoryList,
                                                   XmlNode ndWorkflow)
        {
            SPWorkflowAssociation assocation = null;

            var bAllowManual = false;

            bool.TryParse(ApplicationInstallerHelpers.getAttribute(ndWorkflow, "AllowManual"), out bAllowManual);

            var bStartOnCreate = false;

            bool.TryParse(ApplicationInstallerHelpers.getAttribute(ndWorkflow, "StartOnCreate"), out bStartOnCreate);

            var bStartOnChange = false;

            bool.TryParse(ApplicationInstallerHelpers.getAttribute(ndWorkflow, "StartOnChange"), out bStartOnChange);


            foreach (SPWorkflowTemplate template in oWeb.WorkflowTemplates)
            {
                if (template.Name == sName)
                {
                    assocation = SPWorkflowAssociation.CreateListAssociation(template, sDisplayName, oTaskList, oHistoryList);
                    break;
                }
            }
            if (assocation != null)
            {
                assocation.AllowManual     = bAllowManual;
                assocation.AutoStartChange = bStartOnChange;
                assocation.AutoStartCreate = bStartOnCreate;
                oList.WorkflowAssociations.Add(assocation);
            }
        }
        private void iInstallListsItems(SPList list, XmlNode ndList, int ParentMessageId, bool added)
        {
            var ndItems = ndList.SelectSingleNode("Items");

            if (ndItems != null)
            {
                if (bVerifyOnly)
                {
                    ParentMessageId = addMessage(0, "Checking Items", string.Empty, ParentMessageId);
                }
                else
                {
                    ParentMessageId = addMessage(0, "Installing Items", string.Empty, ParentMessageId);
                }

                foreach (XmlNode ndItem in ndItems.SelectNodes("Item"))
                {
                    oWeb.AllowUnsafeUpdates = true;

                    var sTitle = string.Empty;
                    try
                    {
                        sTitle = ndItem.SelectSingleNode("Field[@Name='Title']").InnerText;
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine(ex.ToString());
                    }
                    if (sTitle == string.Empty)
                    {
                        try
                        {
                            sTitle = ndItem.FirstChild.InnerText;
                        }
                        catch (Exception ex)
                        {
                            Trace.WriteLine(ex.ToString());
                        }
                    }

                    if (sTitle != string.Empty)
                    {
                        if (bVerifyOnly)
                        {
                            addMessage(0, sTitle, string.Empty, ParentMessageId);
                        }
                        else
                        {
                            try
                            {
                                var li = list.Items.Add();

                                foreach (XmlNode ndField in ndItem.SelectNodes("Field"))
                                {
                                    li[ndField.Attributes["Name"].Value] = ndField.InnerText;
                                }

                                li.Update();

                                addMessage(0, sTitle, string.Empty, ParentMessageId);
                            }
                            catch (Exception ex)
                            {
                                Trace.WriteLine(ex.ToString());
                                addMessage(ErrorLevels.Error, sTitle, "Error: " + ex.Message, ParentMessageId);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 39
0
        public TableRow CreateEditableTableRow(SPSite site, SPWeb web, SPList library, int index, String details, List <String> refreshedDocumentsDetailsList)
        {
            TableRow row = new TableRow();

            row.ID       = MakeControlID(index, "row");
            row.CssClass = "wbf-edit-action-row";

            //WBLogging.Debug("Just starting with details: " + details);

            string[] parts = details.Split('|');

            string zone     = parts[0];
            string recordID = parts[1];

            //WBLogging.Debug("Here");


            SPListItem recordItem = WBFWebPartsUtils.GetRecord(site, web, library, zone, recordID);

            if (recordItem == null)
            {
                return(row);
            }

            // OK so we're actually going to refresh the details with the values from the record:
            details = String.Format("{0}|{1}|{2}|{3}",
                                    zone, recordID, "Ignore", recordItem.Name.WBxTrim().Replace(";", "-").Replace("|", "-")
                                    );

            refreshedDocumentsDetailsList.Add(details);

            String displayName = recordItem.WBxGetAsString(WBColumn.Title);

            if (String.IsNullOrEmpty(displayName))
            {
                displayName = recordItem.WBxGetAsString(WBColumn.Name);
            }

            string extension = Path.GetExtension(recordItem.Name).Replace(".", "").ToUpper();

            //WBLogging.Debug("And Here");


            Image image = new Image();

            image.ImageUrl = WBUtils.DocumentIcon16(recordItem.Name);
            image.Width    = Unit.Pixel(16);
            image.Height   = Unit.Pixel(16);
            row.WBxAddInTableCell(image);


            Label label = new Label();

            label.Text = recordItem.WBxGetAsString(WBColumn.Title);
            row.WBxAddInTableCell(label);

            label      = new Label();
            label.Text = recordItem.WBxGetAsString(WBColumn.Name);
            row.WBxAddInTableCell(label);


            Label extensionLabel = new Label();

            extensionLabel.Text = extension;
            row.WBxAddInTableCell(extensionLabel);

            //WBLogging.Debug("As far as Here");


            Button upButton = (Button)row.WBxAddWithIDInTableCell(new Button(), MakeControlID(index, "UpButton"));

            upButton.Text            = "/\\";
            upButton.CommandName     = "Up";
            upButton.CommandArgument = index.ToString();
            upButton.Command        += new CommandEventHandler(upButton_OnClick);

            Button downButton = (Button)row.WBxAddWithIDInTableCell(new Button(), MakeControlID(index, "DownButton"));

            downButton.Text            = "\\/";
            downButton.CommandName     = "Down";
            downButton.CommandArgument = index.ToString();
            downButton.Command        += new CommandEventHandler(downButton_OnClick);


            Button replaceButton = (Button)row.WBxAddWithIDInTableCell(new Button(), MakeControlID(index, "ReplaceButton"));

            replaceButton.Text          = "Replace";
            replaceButton.OnClientClick = "WorkBoxFramework_pickADocument(" + index + "); return false;";

            Button removeButton = (Button)row.WBxAddWithIDInTableCell(new Button(), MakeControlID(index, "RemoveButton"));

            removeButton.Text          = "Remove";
            removeButton.OnClientClick = "WBF_DeleteRow(" + index + ",\"" + recordItem.Name + "\"); return false;";

            HiddenField documentDetails = (HiddenField)row.WBxAddWithIDInTableCell(new HiddenField(), MakeControlID(index, "DocumentDetails"));

            //WBLogging.Debug("Really Here");


            if (!IsPostBack)
            {
                documentDetails.Value = details;
            }

            return(row);
        }
Exemplo n.º 40
0
        public static string QueueItemMessageXml(string data, SPWeb oWeb)
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(data);
            int    templateid      = int.Parse(doc.FirstChild.Attributes["TemplateID"].Value);
            bool   hideFromUser    = false;
            bool   doNotEmail      = false;
            bool   unMarkRead      = true;
            bool   forceNewEntry   = false;
            string listName        = "";
            string listId          = "";
            string itemid          = "";
            string webid           = "";
            string sExternalColumn = "";

            try
            {
                listName = doc.FirstChild.Attributes["ListName"].Value;
            }
            catch { }
            try
            {
                listId = doc.FirstChild.Attributes["ListID"].Value;
            }
            catch { }
            try
            {
                itemid = doc.FirstChild.Attributes["ItemID"].Value;
            }
            catch { }
            try
            {
                webid = doc.FirstChild.Attributes["WebID"].Value;
            }
            catch { }

            try
            {
                hideFromUser = bool.Parse(doc.FirstChild.Attributes["HideFromUser"].Value);
            }
            catch { }
            try
            {
                doNotEmail = bool.Parse(doc.FirstChild.Attributes["DoNotEmail"].Value);
            }
            catch { }
            try
            {
                unMarkRead = bool.Parse(doc.FirstChild.Attributes["UnMarkRead"].Value);
            }
            catch { }
            try
            {
                forceNewEntry = bool.Parse(doc.FirstChild.Attributes["ForceNewEntry"].Value);
            }
            catch { }

            Hashtable hshParams = new Hashtable();

            XmlNode nd = doc.FirstChild.SelectSingleNode("Params");

            foreach (XmlNode ndParam in nd.SelectNodes("Param"))
            {
                hshParams.Add(ndParam.Attributes["Name"].Value, ndParam.InnerText);
            }

            ArrayList ArrNew = new ArrayList();
            ArrayList ArrDel = new ArrayList();

            try
            {
                ArrNew = new ArrayList(doc.FirstChild.Attributes["NewUsers"].Value.Split(','));
            }
            catch { }
            try
            {
                ArrDel = new ArrayList(doc.FirstChild.Attributes["RemoveUsers"].Value.Split(','));
            }
            catch { }
            try
            {
                sExternalColumn = doc.FirstChild.Attributes["ExternalColumn"].Value;
            }
            catch { }

            if (sExternalColumn != "")
            {
                DataTable dtResources = API.APITeam.GetResourcePool("<Get><Columns>" + sExternalColumn + "</Columns></Get>", oWeb);

                ArrayList ArrNewTemp = new ArrayList();

                foreach (string s in ArrNew)
                {
                    DataRow[] dr = dtResources.Select(sExternalColumn + " ='" + s + "'");
                    if (dr.Length > 0)
                    {
                        ArrNewTemp.Add(dr[0]["SPID"].ToString());
                    }
                }

                ArrNew = ArrNewTemp;
            }

            string ret = Response.Failure(30010, "Error: No Item Id specificied");

            if (itemid != "" && (listId != "" || listName != ""))
            {
                SPSecurity.RunWithElevatedPrivileges(delegate() {
                    SPList oList = null;
                    try
                    {
                        using (SPSite site = new SPSite(oWeb.Site.ID))
                        {
                            if (webid != "")
                            {
                                using (SPWeb tWeb = site.OpenWeb(new Guid(webid)))
                                {
                                    if (listId != "")
                                    {
                                        oList = tWeb.Lists[new Guid(listId)];
                                    }
                                    else
                                    {
                                        oList = tWeb.Lists.TryGetList(listName);
                                    }

                                    if (oList != null)
                                    {
                                        SPListItem li = oList.GetItemById(int.Parse(itemid));

                                        API.APIEmail.QueueItemMessage(templateid, hideFromUser, hshParams, (string[])ArrNew.ToArray(typeof(string)), (string[])ArrDel.ToArray(typeof(string)), doNotEmail, unMarkRead, li, oWeb.CurrentUser, forceNewEntry);

                                        ret = Response.Success("Success");
                                    }
                                }
                            }
                            else
                            {
                                using (SPWeb web = site.OpenWeb(oWeb.ID))
                                {
                                    if (listId != "")
                                    {
                                        oList = web.Lists[new Guid(listId)];
                                    }
                                    else
                                    {
                                        oList = web.Lists.TryGetList(listName);
                                    }

                                    if (oList != null)
                                    {
                                        SPListItem li = oList.GetItemById(int.Parse(itemid));

                                        API.APIEmail.QueueItemMessage(templateid, hideFromUser, hshParams, (string[])ArrNew.ToArray(typeof(string)), (string[])ArrDel.ToArray(typeof(string)), doNotEmail, unMarkRead, li, oWeb.CurrentUser, forceNewEntry);

                                        ret = Response.Success("Success");
                                    }
                                }
                            }
                        }
                    }
                    catch { }
                });

                return(ret);
            }
            else
            {
                API.APIEmail.QueueItemMessage(templateid, hideFromUser, hshParams, (string[])ArrNew.ToArray(typeof(string)), (string[])ArrDel.ToArray(typeof(string)), doNotEmail, unMarkRead, oWeb, oWeb.CurrentUser, forceNewEntry);

                return(Response.Success("Success"));
            }

            return(Response.Failure(30010, "Error: No Item Id specificied"));
        }
Exemplo n.º 41
0
        protected void OnSubmit(object sender, EventArgs e)
        {
            // ModifiedBySolvion
            // bhi - 09.01.2012
            // Reset message labels
            //lblMessage.Text =
            lblAnswerMessage.Text = lblEmailMessage.Text = lblPasswordMessage.Text = lblQuestionMessage.Text = "";
            // EndModifiedBySolvion

            bool _showRoles = (new MembershipSettings(SPContext.Current.Web)).EnableRoles;

            // check to see if username already in use
            MembershipUser user = Utils.BaseMembershipProvider().GetUser(txtEmail.Text, false);

            if (user == null)
            {
                try
                {
                    // get site reference
                    string provider = Utils.GetMembershipProvider(this.Site);

                    // create FBA database user
                    MembershipCreateStatus createStatus;

                    if (Utils.BaseMembershipProvider().RequiresQuestionAndAnswer)
                    {
                        user = Utils.BaseMembershipProvider().CreateUser(txtEmail.Text, txtPassword.Text, txtEmail.Text, txtQuestion.Text, txtAnswer.Text, isActive.Checked, null, out createStatus);
                    }
                    else
                    {
                        user = Utils.BaseMembershipProvider().CreateUser(txtEmail.Text, txtPassword.Text, txtEmail.Text, null, null, isActive.Checked, null, out createStatus);
                    }

                    if (createStatus != MembershipCreateStatus.Success)
                    {
                        SetErrorMessage(createStatus);
                        return;
                    }

                    if (user == null)
                    {
                        lblEmailMessage.Text = LocalizedString.GetGlobalString("FBAPackWebPages", "UnknownError");
                        return;
                    }

                    bool groupAdded = false;

                    if (_showRoles)
                    {
                        for (int i = 0; i < rolesList.Items.Count; i++)
                        {
                            if (rolesList.Items[i].Selected)
                            {
                                Utils.BaseRoleProvider().AddUsersToRoles(new string[] { user.UserName }, new string[] { rolesList.Items[i].Value });
                            }
                        }

                        // add user to SharePoint whether a role was selected or not
                        AddUserToSite(Utils.EncodeUsername(user.UserName), user.Email, txtFullName.Text);
                    }
                    else
                    {
                        // add user to each group that was selected
                        for (int i = 0; i < groupList.Items.Count; i++)
                        {
                            if (groupList.Items[i].Selected)
                            {
                                // add user to group
                                SPGroup group = this.Web.SiteGroups[groupList.Items[i].Value];
                                group.AddUser(
                                    Utils.EncodeUsername(user.UserName),
                                    user.Email,
                                    txtFullName.Text,
                                    "");

                                // update
                                group.Update();
                                groupAdded = true;
                            }
                        }

                        // if no group selected, add to site with no permissions
                        if (!groupAdded)
                        {
                            AddUserToSite(Utils.EncodeUsername(user.UserName), user.Email, txtFullName.Text);
                        }
                    }

                    SPSite site = SPContext.Current.Site;
                    SPWeb  web  = site.RootWeb;
                    SPList list = web.SiteUserInfoList;

                    SPUser     SPuser   = web.AllUsers.GetByEmail(txtEmail.Text);
                    SPListItem userItem = null;
                    try
                    {
                        userItem = list.GetItemById(SPuser.ID);
                    }
                    catch (Exception ex)
                    {
                        Utils.LogError(ex);
                    }

                    if (userItem != null)
                    {
                        userItem["CMIT Location"]        = txtCMITLocation.Text;
                        userItem["CMITTitle"]            = txtTitle.Text;
                        userItem["Telephone Number"]     = txtTelephoneNumber.Text;
                        userItem["Date of provisioning"] = txtDatofProvisionaing.SelectedDate;
                        userItem.Update();
                    }

                    // Email User
                    if ((emailUser.Checked == true))
                    {
                        if ((!string.IsNullOrEmpty(txtEmailSubject.Text)) && (!string.IsNullOrEmpty(txtEmailBody.Text)))
                        {
                            var emailBody = txtEmailBody.Text + Environment.NewLine + "Use your email as user name :" + txtEmail.Text + " and password as :" + txtPassword.Text + Environment.NewLine + "We recommand you to change your password when you login for first time.";
                            Email.SendEmail(this.Web, user.Email, txtEmailSubject.Text, emailBody);
                        }
                    }

                    SPUtility.Redirect("FBA/Management/UsersDisp.aspx", SPRedirectFlags.RelativeToLayoutsPage | SPRedirectFlags.UseSource, this.Context);
                }
                catch (Exception ex)
                {
                    Utils.LogError(ex, true);
                }
            }
            else
            {
                lblEmailMessage.Text = LocalizedString.GetGlobalString("FBAPackWebPages", "DuplicateUserName");;
            }
        }
Exemplo n.º 42
0
        /*
         * protected void ViewSelector_OnSelectedIndexChanged(object sender, EventArgs e)
         * {
         *  SelectedViewTitle.Text = "Browse " + webPart.RecordsLibraryView; // ViewSelector.SelectedValue;
         *  // SelectedView = ViewSelector.SelectedValue;
         *
         *  SelectedNodePath = "";
         *
         *  RefreshBrowsableTreeView();
         *  RefreshBoundData();
         *
         * }
         *
         * protected void FilterByProtectiveZone_OnSelectedIndexChanged(object sender, EventArgs e)
         * {
         *  ProtectiveZoneFilter = FilterByProtectiveZone.SelectedValue;
         *
         *  RefreshBoundData();
         * }
         */



        private void RefreshBoundData()
        {
            if (SelectedNodePath != "")
            {
                SelectedRecordsType.Text = SelectedNodePath.Replace("Records Types/", "").Replace("/", " / ");

                WBRecordsType recordsType    = null;
                WBTerm        functionalArea = null;
                WBTerm        subjectTag     = null;

                switch (SelectedView)
                {
                case VIEW_BY_RECORDS_TYPE:
                {
                    recordsType = recordsTypesTaxonomy.GetSelectedRecordsType(SelectedNodePath);
                    SelectedRecordsTypeDescription.Text = recordsType.Description;
                    break;
                }

                case VIEW_BY_FUNCTION_THEN_TYPE:
                {
                    string[] parts = SelectedNodePath.Split('/');
                    if (parts.Length < 3)
                    {
                        break;
                    }

                    string        functionPath = parts[0];
                    List <String> partsList    = new List <String>(parts);
                    partsList.RemoveAt(0);
                    string recordsTypePath = String.Join("/", partsList.ToArray());

                    Term functionalAreaTerm = functionalAreaTaxonomy.GetSelectedTermByPath(functionPath);
                    if (functionalAreaTerm != null)
                    {
                        functionalArea = new WBTerm(functionalAreaTaxonomy, functionalAreaTerm);
                    }

                    recordsType = recordsTypesTaxonomy.GetSelectedRecordsType(recordsTypePath);
                    SelectedRecordsTypeDescription.Text = recordsType.Description;
                    break;
                }

                case VIEW_BY_SUBJECT:
                {
                    Term subjectTagsTerm = subjectTagsTaxonomy.GetSelectedTermByPath(SelectedNodePath);
                    if (subjectTagsTerm != null)
                    {
                        subjectTag = new WBTerm(subjectTagsTaxonomy, subjectTagsTerm);
                        SelectedRecordsTypeDescription.Text = subjectTag.Description;
                    }

                    if (subjectTag == null)
                    {
                        WBLogging.Generic.Verbose("Did not find subject with path: " + SelectedNodePath);
                        return;
                    }
                    break;
                }


                default: return;
                }

                String recordsLibraryURL = WBFWebPartsUtils.GetRecordsLibraryURL(SPContext.Current.Site);

                using (SPSite site = new SPSite(recordsLibraryURL))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        WBQuery query = new WBQuery();

                        if (recordsType == null && functionalArea == null)
                        {
                            query.LogicallyCannotHaveResults = true;
                        }
                        else
                        {
                            if (SelectedView == VIEW_BY_FUNCTION_THEN_TYPE)
                            {
                                query.FilterByFolderPath = WBUtils.PrepareFilenameForPublicWeb(SelectedNodePath);
                            }
                            else
                            {
                                if (recordsType != null)
                                {
                                    WBQueryClause recordsTypeClause = new WBQueryClause(WBColumn.RecordsType, WBQueryClause.Comparators.Equals, recordsType);
                                    recordsTypeClause.UseDescendants = true;
                                    query.AddClause(recordsTypeClause);
                                }

                                if (functionalArea != null)
                                {
                                    WBQueryClause functionalAreaClause = new WBQueryClause(WBColumn.FunctionalArea, WBQueryClause.Comparators.Equals, functionalArea);
                                    functionalAreaClause.UseDescendants = true;
                                    query.AddClause(functionalAreaClause);
                                }
                            }

                            //query.AddClause(new WBQueryClause(WBColumn.ContentType, WBQueryClause.Comparators.Equals, WorkBox.WORK_BOX_RECORD_CONTENT_TYPE));

                            if (subjectTag != null)
                            {
                                WBQueryClause subjectTagClause = new WBQueryClause(WBColumn.SubjectTags, WBQueryClause.Comparators.Equals, subjectTag);
                                subjectTagClause.UseDescendants = false;
                                query.AddClause(subjectTagClause);
                            }

                            string protectiveZoneFilter = "Public"; // Request.QueryString["ProtectiveZone"];
                            if (protectiveZoneFilter != null && protectiveZoneFilter != "")
                            {
                                query.AddEqualsFilter(WBColumn.ProtectiveZone, protectiveZoneFilter);
                            }
                        }


                        query.AddViewColumn(WBColumn.Name);
                        query.AddViewColumn(WBColumn.Title);
                        query.AddViewColumn(WBColumn.FileSize);
                        query.AddViewColumn(WBColumn.FileTypeIcon);
                        query.AddViewColumn(WBColumn.FileType);
                        query.AddViewColumn(WBColumn.TitleOrName);
                        query.AddViewColumn(WBColumn.DisplayFileSize);
                        query.AddViewColumn(WBColumn.EncodedAbsoluteURL);
                        //query.AddViewColumn(WBColumn.FunctionalArea);
                        //query.AddViewColumn(WBColumn.OwningTeam);
                        query.AddViewColumn(WBColumn.ReferenceDate);
                        query.AddViewColumn(WBColumn.DeclaredRecord);
                        //query.AddViewColumn(WBColumn.ReferenceID);
                        //query.AddViewColumn(WBColumn.SeriesTag);
                        //query.AddViewColumn(WBColumn.ProtectiveZone);

                        if (SelectedView != VIEW_BY_SUBJECT)
                        {
                            query.AddViewColumn(WBColumn.SubjectTags);
                        }
                        else
                        {
                            query.AddViewColumn(WBColumn.RecordsType);
                        }


                        if (sortColumn != null)
                        {
                            query.OrderBy(sortColumn, ascending);
                        }


                        SPList recordsLibrary = web.GetList(recordsLibraryURL); //"Documents"]; //farm.RecordsCenterRecordsLibraryName];

                        DataTable dataTable = recordsLibrary.WBxGetDataTable(site, query);

                        ShowResults.DataSource = dataTable;

                        ShowResults.Columns.Clear();
                        ShowResults.Columns.Add(WBUtils.DynamicIconTemplateField(WBColumn.FileTypeIcon, WBColumn.EncodedAbsoluteURL));
                        ShowResults.Columns.Add(WBUtils.HyperLinkField(WBColumn.TitleOrName, WBColumn.EncodedAbsoluteURL, sortColumn, ascending));
//                        ShowResults.Columns.Add(WBUtils.HyperLinkField(WBColumn.Name, WBColumn.EncodedAbsoluteURL, sortColumn, ascending));
                        //ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.FunctionalArea, sortColumn, ascending));
                        //ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.OwningTeam, sortColumn, ascending));
                        ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.FileType, sortColumn, ascending));
                        ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.DisplayFileSize, sortColumn, ascending));
                        ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.ReferenceDate, sortColumn, ascending));
                        //ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.DeclaredRecord, sortColumn, ascending));
                        //ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.ReferenceID, sortColumn, ascending));
                        //ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.SeriesTag, sortColumn, ascending));
                        //ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.ProtectiveZone, sortColumn, ascending));

                        /*
                         * if (SelectedView != VIEW_BY_SUBJECT)
                         * {
                         *  ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.SubjectTags, sortColumn, ascending));
                         * }
                         * else
                         * {
                         *  ShowResults.Columns.Add(WBUtils.BoundField(WBColumn.RecordsType, sortColumn, ascending));
                         * }
                         */


                        ShowResults.DataBind();
                    }
                }
            }
            else
            {
                WBUtils.logMessage("SelectedNodePath was empty");
            }
        }
        /// <summary>
        /// Runs the specified command.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <param name="keyValues">The key values.</param>
        /// <param name="output">The output.</param>
        /// <returns></returns>
        public override int Execute(string command, System.Collections.Specialized.StringDictionary keyValues, out string output)
        {
            output         = string.Empty;
            Logger.Verbose = true;


            string url         = Params["url"].Value;
            bool   force       = false; // Params["force"].UserTypedIn;
            string scope       = Params["scope"].Value.ToLowerInvariant();
            bool   haltOnError = Params["haltonerror"].UserTypedIn;

            switch (scope)
            {
            case "file":
                using (SPSite site = new SPSite(url))
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPFile file = web.GetFile(url);
                        if (file == null)
                        {
                            throw new FileNotFoundException(string.Format("File '{0}' not found.", url), url);
                        }

                        Common.Pages.ReGhostFile.Reghost(site, web, file, force, haltOnError);
                    }
                break;

            case "list":
                using (SPSite site = new SPSite(url))
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = Utilities.GetListFromViewUrl(web, url);
                        Common.Pages.ReGhostFile.ReghostFilesInList(site, web, list, force, haltOnError);
                    }
                break;

            case "web":
                bool recurseWebs = Params["recursewebs"].UserTypedIn;
                using (SPSite site = new SPSite(url))
                    using (SPWeb web = site.AllWebs[Utilities.GetServerRelUrlFromFullUrl(url)])
                    {
                        Common.Pages.ReGhostFile.ReghostFilesInWeb(site, web, recurseWebs, force, haltOnError);
                    }
                break;

            case "site":
                using (SPSite site = new SPSite(url))
                {
                    Common.Pages.ReGhostFile.ReghostFilesInSite(site, force, haltOnError);
                }
                break;

            case "webapplication":
                SPWebApplication webApp = SPWebApplication.Lookup(new Uri(url));
                Logger.Write("Progress: Analyzing files in web application '{0}'.", url);

                foreach (SPSite site in webApp.Sites)
                {
                    try
                    {
                        Common.Pages.ReGhostFile.ReghostFilesInSite(site, force, haltOnError);
                    }
                    finally
                    {
                        site.Dispose();
                    }
                }
                break;
            }
            return((int)ErrorCodes.NoError);
        }
Exemplo n.º 44
0
        private void GetItemNav(string lstName)
        {
            if (ItemID == 0)
            {
                itemNav.InnerHtml = "无法获取当前项目数据";
            }
            else
            {
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate() //模拟管理员权限执行,让匿名用户也可以查看此Web部件
                    {
                        string siteUrl = SPContext.Current.Site.Url;
                        using (SPSite mySite = new SPSite(siteUrl))
                        {
                            using (SPWeb myWeb = SPContext.Current.Web)
                            {
                                SPList mylist = myWeb.Lists.TryGetList(lstName);
                                if (mylist != null)
                                {
                                    string queryStr        = "";
                                    SPListItem currentItem = mylist.GetItemById(ItemID);
                                    if (currentItem != null)
                                    {
                                        string flag = "0";
                                        if (currentItem["Flag"] != null)
                                        {
                                            flag = currentItem["Flag"].ToString();;
                                        }
                                        string isOnly   = webpartObj.OnlyAudit;//是否只显示待审记录
                                        string showYear = webpartObj.ByYear;
                                        if (string.IsNullOrEmpty(showYear))
                                        {
                                            showYear = DateTime.Now.Year.ToString();
                                        }
                                        if (isOnly == "是")   //只显示未审
                                        {
                                            if (flag != "1") //当前未审
                                            {
                                                queryStr += "<Where><And><Eq><FieldRef Name='Year'/><Value Type='Text'>" + showYear + "</Value></Eq><Eq><FieldRef Name='Flag'/><Value Type='Number'>0</Value></Eq></And></Where>";
                                            }
                                            else//当前已审,不参与导航
                                            {
                                                itemNav.Visible = false;
                                                return;
                                            }
                                        }
                                        else
                                        {
                                            queryStr += "<Where><Eq><FieldRef Name='Year'/><Value Type='Text'>" + showYear + "</Value></Eq></Where>";
                                        }

                                        string myurl             = mylist.DefaultDisplayFormUrl + "?ID=";
                                        SPQuery qry              = new SPQuery();
                                        SPFieldCollection fields = mylist.Fields;
                                        queryStr += GenQuery(fields);
                                        if (queryStr == null)
                                        {
                                            itemNav.InnerHtml = "设置项中的某个字段名设置错误";
                                        }
                                        else
                                        {
                                            qry.Query = queryStr;
                                            SPListItemCollection myItems = mylist.GetItems(qry);//获取sharepoint列表集合
                                            if (myItems.Count > 0)
                                            {
                                                List <SPListItem> listItems = myItems.Cast <SPListItem>().ToList();          //将SharePoint列表数据集合转化为普通列表集合
                                                SPListItem myItem           = listItems.FirstOrDefault(p => p.ID == ItemID); //查询指定ID的列表项
                                                int index  = listItems.IndexOf(myItem);                                      //获取指定列表项的索引
                                                int rCount = myItems.Count;                                                  //获取列表的计数
                                                if (rCount >= 2)                                                             //多余两条显示导航
                                                {
                                                    if (index == 0)
                                                    {
                                                        //itemindex = myItems[rCount - 1]["ID"].ToString() + ";" + myItems[rCount - 1]["Title"].ToString() + ";"  + myItems[i+1]["ID"].ToString() + ";" + myItems[i+1]["Title"].ToString();
                                                        itemNav.InnerHtml = "<ul><li>当前已是第一条</li><li>&nbsp;&nbsp;共计 <b>" + rCount + "</b> 条</li><li>▽下一条:<a href='" + myurl + myItems[index + 1]["ID"].ToString() + "'>" + GetSubString(myItems[index + 1]["Title"].ToString(), 50) + "</a></li></ul>";
                                                    }
                                                    else if (index == rCount - 1)
                                                    {
                                                        //itemindex = myItems[i - 1]["ID"].ToString() + ";" + myItems[i - 1]["Title"].ToString() + ";" + myItems[0]["ID"].ToString() + ";" + myItems[0]["Title"].ToString();
                                                        itemNav.InnerHtml = "<ul><li>△上一条:<a href='" + myurl + myItems[index - 1]["ID"].ToString() + "'>" + GetSubString(myItems[index - 1]["Title"].ToString(), 50) + "</a></li><li>&nbsp;&nbsp;共计 <b>" + rCount + "</b> 条</li><li>当前已是最后一条</li></ul>";
                                                    }
                                                    else
                                                    {
                                                        //itemindex = myItems[i - 1]["ID"].ToString() + ";" + myItems[i-1]["Title"].ToString()+";"+ myItems[i + 1]["ID"].ToString() + ";" + myItems[i+1]["Title"].ToString();
                                                        itemNav.InnerHtml = "<ul><li>△上一条:<a href='" + myurl + myItems[index - 1]["ID"].ToString() + "'>" + GetSubString(myItems[index - 1]["Title"].ToString(), 50) + "</a></li><li>&nbsp;&nbsp;当前第 <b>" + (index + 1).ToString() + "</b> 条,共计 <b>" + rCount + "</b> 条</li><li>▽下一条:<a href='" + myurl + myItems[index + 1]["ID"].ToString() + "'>" + GetSubString(myItems[index + 1]["Title"].ToString(), 50) + "</a></li></ul>";
                                                    }
                                                }
                                                else
                                                {
                                                    itemNav.Visible = false;//不够两条,无须导航
                                                }
                                            }
                                            else
                                            {
                                                itemNav.Visible = false;//没有数据
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    itemNav.Visible = false;//列表不存在
                                }
                            }
                        }
                    });
                }
                catch (System.Exception ex)
                {
                    itemNav.InnerHtml = ex.ToString();
                }
            }
        }
Exemplo n.º 45
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPList list = web.Lists.TryGetList(ListName);
                            if (list != null)
                            {
                                SPListItem NewItem = list.Items.Add();
                                {
                                    #region Save to SP

                                    web.AllowUnsafeUpdates = true;

                                    NewItem["ClientID"] = cid;
                                    NewItem["_x0627__x0644__x0625__x0633__x06"] = txtArabicFullName.Text;
                                    NewItem["EIDCardNumber"] = txtIDNumber.Text;
                                    NewItem["Phone"]         = txtPhone.Text;
                                    NewItem["_x0646__x0648__x0639__x0020__x06"] = ddlAidType.SelectedItem.Text;
                                    NewItem["_x062a__x0641__x0627__x0635__x06"] = txtAidRequestDetails.Text;
                                    NewItem["_x062a__x0627__x0631__x064a__x06"] = dtcDueDate.SelectedDate;

                                    NewItem["_x0642__x064a__x0645__x0629__x00"] = txtRequiredAmount.Text;
                                    NewItem["NewColumn1"] = ddlAidRequestStatus.SelectedItem.Text;
                                    NewItem["_x0645__x062f__x0629__x0020__x06"] = txtResidencyYears.Text;
                                    NewItem["_x062a__x0648__x0635__x064a__x06"] = txtPanelOpinion.Text;
                                    NewItem["_x0645__x0628__x0644__x063a__x00"] = txtApprovedAmount.Text;

                                    //================================== New Fields ============================================
                                    NewItem["Nationality"]      = txtNationality.Text;
                                    NewItem["MaritalStatus"]    = txtMaritalStatus.Text;
                                    NewItem["Age"]              = txtAge.Text;
                                    NewItem["FamilySize"]       = txtFamilySize.Text;
                                    NewItem["Job"]              = txtJob.Text;
                                    NewItem["HomeAddress"]      = txtHomeAddress.Text;
                                    NewItem["HomePhone"]        = txtHomePhone.Text;
                                    NewItem["NoOfStudyingSons"] = txtNoOfStudyingSons.Text;
                                    NewItem["Income"]           = txtIncome.Text;
                                    NewItem["HouseType"]        = ddlHouseType.SelectedItem.Text;

                                    NewItem["Rent"]           = txtRent.Text;
                                    NewItem["Bills"]          = txtBills.Text;
                                    NewItem["Banks"]          = txtBanks.Text;
                                    NewItem["LivingExpenses"] = txtLivingExpenses.Text;
                                    NewItem["EduExpenses"]    = txtEduExpenses.Text;
                                    NewItem["OtherExpenses"]  = txtOtherExpenses.Text;

                                    NewItem["IsPreviousZayedAid"]     = ddlIsPreviousZayedAid.SelectedItem.Text;
                                    NewItem["PreviousZayedAidYear"]   = txtPreviousZayedAidYear.Text;
                                    NewItem["PreviousZayedAidAmount"] = txtPreviousZayedAidAmount.Text;

                                    NewItem["IsPreviousOtherOrgAid"] = ddlIsPreviousOtherOrgAid.SelectedItem.Text;
                                    NewItem["OtherOrgAidName"]       = txtOtherOrgAidName.Text;
                                    NewItem["OtherOrgAidAmount"]     = txtOtherOrgAidAmount.Text;

                                    NewItem["ChequeOrgName"] = txtChequeOrgName.Text;
                                    //============================= Medical Aid Request Fields ============================================

                                    NewItem["IllnessDesc"] = txtIllnessDesc.Text;
                                    NewItem["Hospital"]    = txtHospital.Text;
                                    NewItem["MedCost"]     = txtMedCost.Text;

                                    //===============================================================================================
                                    if (FileUpload1.HasFile)
                                    {
                                        NewItem.Attachments.Add(FileUpload1.FileName, FileUpload1.FileBytes);
                                    }

                                    NewItem.Update();// means "Update Changes" , used for both Insert and Update. If ID is empty , it Inserts , otherwise if ID has value , it Updates
                                    web.AllowUnsafeUpdates = false;

                                    #endregion Save to SP

                                    if (NewItem.ID != 0)
                                    {
                                        lblSuccess.Visible   = true;
                                        lblSuccess.Text      = "تم تسجيل الطلب بنجاح.   ";
                                        lblSuccess.BackColor = ColorTranslator.FromHtml("#d0ffc6");

                                        if (ddlAidRequestStatus.SelectedItem.Text.Trim() == "للعرض على المستشار الطبي")
                                        {
                                            string Request_Details_URL = SPContext.Current.Web.Url + "/Lists/" + ListName + "/Item/displayifs.aspx?ID=" + NewItem.ID.ToString();
                                            string Request_Number      = NewItem.ID.ToString();
                                            string Med_Email           = get_Med_Email();
                                            Send_Email_To_Medical_Consultant(Request_Details_URL, Request_Number, Med_Email);
                                        }

                                        Prepare_Printing(NewItem.ID.ToString());
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    lblSuccess.Visible   = true;
                    lblSuccess.Text      = "حدث الخطأ التالى اثناء محاولة إضافة الطلب : " + ex.Message;
                    lblSuccess.BackColor = ColorTranslator.FromHtml("#ffbfbf");
                }
            });
        }
Exemplo n.º 46
0
        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="web">The web.</param>
        /// <param name="docLibName">Name of the document library.</param>
        /// <param name="fUpload">The fupload.</param>
        /// <param name="viewStateName">Name of the view state.</param>
        /// <param name="gv">The GridView.</param>
        /// <param name="type">The type.</param>
        private void AddWorkFile(SPWeb web, string docLibName, FileUpload fUpload, String viewStateName, GridView gv, int type)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite elevatedsiteColl = new SPSite(MySite.ID))
                    {
                        using (SPWeb elevatedSite = elevatedsiteColl.OpenWeb(MyWeb.ID))
                        {
                            string urlStr = elevatedSite.Url;
                            elevatedSite.AllowUnsafeUpdates = true;
                            SPList list = elevatedSite.Lists.TryGetList(docLibName);
                            //如果没有文档库,生成文档库
                            if (list == null)
                            {
                                list   = ProjectDll.DAL.ProjectFileDAL.CreateList(docLibName);
                                urlStr = urlStr + "\\" + docLibName;
                            }
                            var docLib = (SPDocumentLibrary)list;
                            if (fUpload.HasFile)
                            {
                                //数据库

                                //判断是否存在
                                if (JudgeSize(fUpload.PostedFile.ContentLength))//判断文件大小是否超出限制
                                {
                                    ProjectDll.DAL.Common.ShowMessage(this.Page, this.GetType(), "超出上传文档大小限制!");
                                }
                                else
                                {
                                    string fname = type.ToString().PadLeft(2, '0') + DateTime.Now.Year + ddlSubjectC.SelectedValue.PadLeft(4, '0') + "-" + ProjectDll.BLL.User.GetAccount() + "-" + Path.GetFileName(fUpload.PostedFile.FileName);
                                    Stream stm   = fUpload.PostedFile.InputStream;
                                    int iLength  = (int)stm.Length;
                                    if (iLength > 0)
                                    {
                                        SPFolder rootFolder = docLib.RootFolder;
                                        Byte[] filecontent  = new byte[iLength];
                                        stm.Read(filecontent, 0, iLength);
                                        try
                                        {
                                            SPFile f;
                                            //如果在文档库中有,删除文档库中同名文档后,上传文档
                                            bool isDocHave = false;

                                            isDocHave = ProjectDll.DAL.ProjectFileDAL.JudgeIsExistInDocLib(docLib, fname, type);
                                            proj_ProjectFile isDBHave = ProjectDll.DAL.ProjectFileDAL.JudgeIsExistInDb(fname, currentUserId);
                                            //判断文档库
                                            if (isDocHave)
                                            {
                                                ProjectDll.DAL.Common.ShowMessage(this.Page, this.GetType(), "请注意,该文件已存在,上传后自动覆盖已有文件!");
                                                DelList(fname, type.ToString());
                                                f = rootFolder.Files.Add(fname, filecontent, true);
                                            }
                                            else
                                            {
                                                f = rootFolder.Files.Add(fname, filecontent, true);
                                            }
                                            urlStr += "\\" + fname;

                                            ////判断数据库
                                            //if (isDBHave)
                                            //{
                                            //    //如果数据库中有,更新数据库
                                            //}
                                            //else
                                            //{
                                            //    //如果没有插入数据库

                                            //    //数据库

                                            //}
                                        }
                                        catch (Exception ex)
                                        {
                                            ProjectDll.DAL.Common.Alert(ex.ToString());
                                        }
                                        finally
                                        {
                                            stm.Close();
                                        }
                                    }
                                }
                            }
                            elevatedSite.AllowUnsafeUpdates = false;
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                ProjectDll.DAL.Common.Alert(ex.ToString());
                // DAL.Common.ShowMessage(this.Page, this.GetType(), "出错了,请报告给管理员!");
            }
            finally
            {
            }
            //BindGridView((DataTable)ViewState[viewStateName], gv);
        }
Exemplo n.º 47
0
        protected void SyncFieldRecursive(SPWeb webTo, string sListName)
        {
            try
            {
                sResults += sLeftPadding + "Website: " + webTo.Name + "<br>";
                SPList oToList = null;
                try
                {
                    oToList = webTo.Lists[sListName] as SPList;
                }
                catch
                {
                    if (chkCreateNewList.Checked)
                    {
                        webTo.Lists.Add(sListName, oFromList.Description, oFromList.BaseTemplate);
                        webTo.Update();
                        oToList = webTo.Lists[sListName] as SPList;
                    }
                }

                if (oToList != null)
                {
                    string sFldName = "";

                    // Select the checkboxes from the GridView control
                    for (int i = 0; i < GvFields.Rows.Count; i++)
                    {
                        GridViewRow row           = GvFields.Rows[i];
                        bool        isSyncChecked = ((CheckBox)row.FindControl("chkSync")).Checked;
                        if (isSyncChecked)
                        {
                            bool isSealChecked = ((CheckBox)row.FindControl("chkSeal")).Checked;

                            sFldName = GvFields.DataKeys[i]["InternalName"].ToString();

                            fldFromField = oFromList.Fields.GetFieldByInternalName(sFldName);
                            SPField fldToTest = null;
                            try
                            {
                                fldToTest = oToList.Fields.GetFieldByInternalName(sFldName);
                                if (fldFromField.Type == fldToTest.Type)
                                {
                                    Boolean bIsUpdatable;
                                    if (!fldToTest.Sealed)
                                    {
                                        bIsUpdatable = true;
                                    }
                                    else if (fldToTest.Sealed & fldToTest.Type.ToString() != "User")
                                    {
                                        fldToTest.Sealed = false;
                                        bIsUpdatable     = true;
                                    }
                                    else
                                    {
                                        bIsUpdatable = false;
                                    }

                                    if (bIsUpdatable)
                                    {
                                        fldToTest.SchemaXml    = fldFromField.SchemaXml.Replace(oFromList.ID.ToString(), oToList.ID.ToString());
                                        fldToTest.DefaultValue = fldFromField.DefaultValue;
                                        if (fldFromField.Type == SPFieldType.Lookup)
                                        {
                                            string sTopListId = getFieldSchemaAttribValue(fldFromField.SchemaXml, "List");
                                            string sSubListId = "";
                                            try
                                            {
                                                sSubListId = webTo.Lists[oFromWeb.Lists[new Guid(sTopListId)].Title].ID.ToString();
                                            }
                                            catch { }
                                            fldToTest.SchemaXml = fldFromField.SchemaXml.Replace(sTopListId, "{" + sSubListId + "}");
                                        }

                                        fldToTest.Update();

                                        if (fldToTest.Type.ToString() != "User" && fldToTest.InternalName != "Title")
                                        {
                                            fldToTest.Sealed = isSealChecked;
                                        }
                                    }
                                    else
                                    {
                                        sResults += sLeftPadding + " Failed: the field " + sFldName + " of type '" + fldToTest.Type.ToString() + "' already exists in list " + oToList.Title + "<br>";
                                    }
                                }
                                else
                                {
                                    sResults += sLeftPadding + " - Failed: the field '" + sFldName + "' already exists in list " + oToList.Title + ".<br>";
                                    sResults += sLeftPadding + "           This field is of a different type (" + fldToTest.Type.ToString() + ") than <br>";
                                    sResults += sLeftPadding + "           the field being copied, which is of type " + fldFromField.Type.ToString() + ".<br>";
                                }
                            }
                            catch (Exception exc)
                            {
                                if ((fldToTest == null || fldToTest.InternalName != "Title") & exc.GetType().FullName == "System.ArgumentException")
                                {
                                    oToList.Fields.Add(fldFromField);
                                    //webTo.Update();
                                    SPField fldNewField = oToList.Fields.GetFieldByInternalName(sFldName);
                                    fldNewField.SchemaXml = fldFromField.SchemaXml.Replace(oFromList.ID.ToString(), oToList.ID.ToString());
                                    if (fldFromField.Type == SPFieldType.Lookup)
                                    {
                                        string sTopListId = getFieldSchemaAttribValue(fldFromField.SchemaXml, "List");
                                        string sSubListId = "";
                                        try
                                        {
                                            sSubListId = webTo.Lists[oFromWeb.Lists[new Guid(sTopListId)].Title].ID.ToString();
                                        }
                                        catch {}
                                        fldNewField.SchemaXml = fldFromField.SchemaXml.Replace(sTopListId, "{" + sSubListId + "}");
                                    }
                                    //fldNewField.Update();
                                    fldNewField.Sealed = isSealChecked;
                                    webTo.Update();
                                    //sResults += sLeftPadding + " - field " + sFldName + " added to list " + oToList.Title + "\r";
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                sResults += sLeftPadding + " - Error: " + exc.Message;
            }

            sLeftPadding += "   ";

            foreach (SPWeb w in webTo.Webs)
            {
                try
                {
                    SyncFieldRecursive(w, sListName);
                }
                catch { }
                w.Close();
                w.Dispose();
            }

            sLeftPadding = sLeftPadding.Substring(1, sLeftPadding.Length - 3);
        }
Exemplo n.º 48
0
        /// <summary>
        /// Redistribuye (prorratea) los costos definidos al envio
        /// para cada ítem pedido asociado
        /// </summary>
        /// <param name="itemEnvio"></param>
        private void RedistribuirCostosEnvio(SPListItem itemEnvio)
        {
            SPList listaParametros   = itemEnvio.Web.Lists[LISTA_PARAMETROS];
            SPList listaFacturas     = itemEnvio.Web.Lists[LISTA_FACTURAS];
            SPList listaAlmacen      = itemEnvio.Web.Lists[LISTA_ALMACEN];
            SPList listaItemsPedidos = itemEnvio.Web.Lists[LISTA_ITEMS_PEDIDOS];

            bool prorrateoConArancel = true;

            #region Obtener el tipo de prorrateo
            SPQuery consultaParam = new SPQuery();
            consultaParam.Query = "<Where><Eq><FieldRef Name='Title' />" +
                                  "<Value Type='Text'>" + PARAMETRO_TITULO + "</Value></Eq></Where>";
            SPListItemCollection itemsParametros = listaParametros.GetItems(consultaParam);

            if (itemsParametros.Count != 0 &&
                itemsParametros[0]["Valor parámetro"].ToString() == PARAMETRO_VALOR)
            {
                prorrateoConArancel = false;
            }
            #endregion

            #region Distribuir (prorratear) costos
            double totalEnvio         = 0;
            double costoFletes        = 0;
            double costoAranceles     = 0;
            double costoAduana        = 0;
            double costoTransportador = 0;
            double costoOtros         = 0;

            totalEnvio = this.ObtenerTotalDelEnvio(itemEnvio);
            if (itemEnvio["Costo fletes"] != null)
            {
                costoFletes = double.Parse(itemEnvio["Costo fletes"].ToString());
            }
            if (itemEnvio["Costo aranceles"] != null)
            {
                costoAranceles = double.Parse(itemEnvio["Costo aranceles"].ToString());
            }
            if (itemEnvio["Costo aduana"] != null)
            {
                costoAduana = double.Parse(itemEnvio["Costo aduana"].ToString());
            }
            if (itemEnvio["Costo transportador"] != null)
            {
                costoTransportador = double.Parse(itemEnvio["Costo transportador"].ToString());
            }
            if (itemEnvio["Costo otros"] != null)
            {
                costoOtros = double.Parse(itemEnvio["Costo otros"].ToString());
            }

            SPFieldLookupValueCollection almacenesAsociados =
                (SPFieldLookupValueCollection)itemEnvio["Almacenes asociados"];

            foreach (SPFieldLookupValue almacenAsociado in almacenesAsociados)
            {
                SPListItem elAlmacen =
                    listaAlmacen.GetItemByIdSelectedFields(almacenAsociado.LookupId,
                                                           "Facturas_x0020_asociadas");
                SPFieldLookupValueCollection facturasAsociadas =
                    (SPFieldLookupValueCollection)elAlmacen["Facturas asociadas"];

                foreach (SPFieldLookupValue facturaAsociada in facturasAsociadas)
                {
                    SPListItem laFactura =
                        listaFacturas.GetItemByIdSelectedFields(facturaAsociada.LookupId,
                                                                "_x00cd_tems_x0020_asociados");
                    SPFieldLookupValueCollection itemsAsociados =
                        (SPFieldLookupValueCollection)laFactura["Ítems asociados"];

                    foreach (SPFieldLookupValue itemAsociado in itemsAsociados)
                    {
                        SPListItem itemPedido = listaItemsPedidos.GetItemByIdSelectedFields(
                            itemAsociado.LookupId, "Costo_x0020_fletes", "Costo_x0020_aranceles",
                            "Costo_x0020_aduana", "Costo_x0020_transportador", "Costo_x0020_otros",
                            "Precio_x0020_extendido", "Item_x0020_asociado");
                        double precioItem =
                            double.Parse(SubcadenaDespues(itemPedido["Precio extendido"]).Replace('.', ','));
                        double porcentajeArancel = this.ObtenerPorcentajeArancel(itemPedido);

                        if (prorrateoConArancel)
                        {//TODO Prorrateo con aranceles, verificar el calculo
                            itemPedido["Costo fletes"] =
                                this.AplicarProrrateoConArancelFletes(precioItem, totalEnvio, costoFletes);
                            itemPedido["Costo aranceles"] =
                                this.AplicarProrrateoConArancelAranceles(precioItem, totalEnvio, costoFletes, porcentajeArancel);
                            itemPedido["Costo aduana"] =
                                this.AplicarProrrateoConArancelAduana(precioItem, totalEnvio, costoAduana, costoFletes);
                            itemPedido["Costo transportador"] =
                                this.AplicarProrrateoConArancelTransp(precioItem, totalEnvio, costoTransportador, costoFletes);
                            itemPedido["Costo otros"] =
                                this.AplicarProrrateoConArancelOtros(precioItem, totalEnvio, costoOtros, costoFletes);
                        }
                        else
                        {//Prorrateo sin aranceles
                            itemPedido["Costo fletes"] =
                                this.AplicarProrrateoSinArancel(precioItem, totalEnvio, costoFletes);
                            itemPedido["Costo aranceles"] =
                                this.AplicarProrrateoSinArancel(precioItem, totalEnvio, costoAranceles);
                            itemPedido["Costo aduana"] =
                                this.AplicarProrrateoSinArancel(precioItem, totalEnvio, costoAduana);
                            itemPedido["Costo transportador"] =
                                this.AplicarProrrateoSinArancel(precioItem, totalEnvio, costoTransportador);
                            itemPedido["Costo otros"] =
                                this.AplicarProrrateoSinArancel(precioItem, totalEnvio, costoOtros);
                        }

                        using (DisabledItemEventsScope scope = new DisabledItemEventsScope())
                        {
                            try
                            {
                                itemPedido.Web.AllowUnsafeUpdates = true;
                                itemPedido.Update();
                            }
                            finally
                            {
                                itemPedido.Web.AllowUnsafeUpdates = false;
                            }
                        }
                    }
                }
            }
            #endregion
        }
Exemplo n.º 49
0
 public static RoleAssociation AddRole(this SPList list, string name)
 {
     return(new RoleAssociation(list.ParentWeb, list.RoleAssignments, name));
 }
Exemplo n.º 50
0
        private string renderSecondLevelLink(SPList aList, SPListItem aItem, string aLevel, string aLang, string selected)
        {
            string returnString    = string.Empty;
            string currentNavClass = string.Empty;

            //Ensure that this is a second level link by checking number of dots in Level value. Must be 1
            string      level        = aItem["Level"].ToString();
            List <char> list         = level.ToList <char>();
            int         numberOfDots = list.Count <char>(c => c == '.');

            if (numberOfDots == 1)
            {
                string urlLink = string.Empty;
                string title   = string.Empty;

                title   = Convert.ToString(aItem["Title"]);
                urlLink = Convert.ToString(aItem["UrlLink"]);

                if (selected == urlLink)
                {
                    currentNavClass = " class=\"nav-current\"";
                }
                else
                {
                    currentNavClass = string.Empty;
                }

                returnString = "<ul>" +
                               "<li><a href=\"" + urlLink + "\"" + currentNavClass + ">" + title + "</a>";

                //Check if this level has any sub levels
                List <SPListItem> thirdLevelCollItem = (from SPListItem li in aList.Items
                                                        where Convert.ToString(li["Level"]).StartsWith(level)
                                                        orderby li["SortOrder"]
                                                        select li).ToList <SPListItem>();



                // render the second level heading
                if (thirdLevelCollItem.Count > 1)
                {
                    // start our child UL
                    returnString += "<ul>";

                    // render any children
                    foreach (SPItem item in thirdLevelCollItem)
                    {
                        string      thirdLevel = item["Level"].ToString();
                        List <char> thirdList  = thirdLevel.ToList <char>();
                        numberOfDots = thirdList.Count <char>(c => c == '.');
                        urlLink      = Convert.ToString(item["UrlLink"]);
                        if (urlLink.ToLower().Contains(selected.ToLower()))
                        {
                            currentNavClass = " class=\"nav-current\"";
                        }
                        else
                        {
                            currentNavClass = string.Empty;
                        }


                        if (numberOfDots == 2)
                        {
                            title         = Convert.ToString(item["Title"]);
                            returnString += "<li><a href=\"" + urlLink + "\"" + currentNavClass + ">" + title + "</a></li>";
                        }
                    }

                    // close off the list
                    returnString += "</ul>";
                }

                // close off the heading
                returnString += "</li></ul>";
            }

            return(returnString);
        }
Exemplo n.º 51
0
        protected override void Render(HtmlTextWriter writer)
        {
            string currentNavClass = string.Empty;
            string selectedNav     = string.Empty;

            try
            {
                // setup the outer wrappers
                string htmlOutput = string.Empty;

                // figure out our language of the current label
                if (SPContext.Current.ListItem != null && PublishingPage.IsPublishingPage(SPContext.Current.ListItem))
                {
                    PublishingPage publishingPage = PublishingPage.GetPublishingPage(SPContext.Current.ListItem);
                    string         langWeb        = string.Empty;
                    if (publishingPage.PublishingWeb.Label != null)
                    {
                        langWeb = (publishingPage.PublishingWeb.Label.Title.Substring(0, 2).ToLower() == "en") ? "eng" : "fra";
                    }
                    else
                    {
                        langWeb = "eng";
                    }

                    currentNavClass = "class=\"nav-current\"";
                    selectedNav     = SPContext.Current.ListItemServerRelativeUrl;

                    SPList            WETLeftNavigation = null;
                    List <SPListItem> firstLevelCollItem;

                    try
                    {
                        WETLeftNavigation = SPContext.Current.Web.Lists["WETLeftNavigation"];

                        firstLevelCollItem = (from SPListItem li in WETLeftNavigation.Items
                                              where Convert.ToString(li["Level"]).IndexOf(".") == -1
                                              orderby li["SortOrder"]
                                              select li).ToList <SPListItem>();

                        foreach (SPListItem oItem_1 in firstLevelCollItem)
                        {
                            //Ensure that this is a first level link by checking number of dots in Level value. Must be 0
                            string      level        = oItem_1["Level"].ToString();
                            List <char> list         = level.ToList <char>();
                            int         numberOfDots = list.Count <char>(c => c == '.');

                            if ((numberOfDots == 0))
                            {
                                //renderfirstlevelLink
                                htmlOutput += renderTopLevelLink(WETLeftNavigation, oItem_1, level, langWeb, selectedNav);
                            }
                        }
                    }
                    finally
                    {
                    }
                    htmlOutput += "<br /><br /><br />";
                    writer.Write(htmlOutput);
                }
                else
                {
                    //Nik20121026 - Handles the case where the site's template is a collaboration one;
                    string langWeb = string.Empty;
                    string cultISO = "";
                    if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("/eng/"))
                    {
                        cultISO = "en";
                    }
                    else
                    {
                        cultISO = "fr";
                    }

                    langWeb = (cultISO == "en") ? "eng" : "fra";

                    currentNavClass = "class=\"nav-current\"";
                    selectedNav     = SPContext.Current.ListItemServerRelativeUrl;

                    SPList            WETLeftNavigation = null;
                    List <SPListItem> firstLevelCollItem;

                    try
                    {
                        WETLeftNavigation = SPContext.Current.Web.Lists["WETLeftNavigation"];

                        firstLevelCollItem = (from SPListItem li in WETLeftNavigation.Items
                                              where Convert.ToString(li["Level"]).IndexOf(".") == -1
                                              orderby li["SortOrder"]
                                              select li).ToList <SPListItem>();

                        foreach (SPListItem oItem_1 in firstLevelCollItem)
                        {
                            //Ensure that this is a first level link by checking number of dots in Level value. Must be 0
                            string      level        = oItem_1["Level"].ToString();
                            List <char> list         = level.ToList <char>();
                            int         numberOfDots = list.Count <char>(c => c == '.');

                            if ((numberOfDots == 0))
                            {
                                //renderfirstlevelLink
                                htmlOutput += renderTopLevelLink(WETLeftNavigation, oItem_1, level, langWeb, selectedNav);
                            }
                        }
                    }
                    finally
                    {
                    }

                    writer.Write(htmlOutput);
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex.Message + " " + ex.StackTrace);
            }
        }
Exemplo n.º 52
0
 public SPListEntity(SPList list)
 {
     _underlyingObject = list;
 }
        static void Main(string[] args)
        {
            SPSite sitio = null;
            SPWeb  web   = null;

            string urlSitio;
            string nombreLista;
            int    idInicio;

            try
            {
                #region Toma de datos
                Console.WriteLine("Este programa permite iniciar una determinada " +
                                  "lista con un valor ID definido.");
                Console.WriteLine();

                Console.Write("Ingrese la URL del sitio: ");
                urlSitio = Console.ReadLine();

                Console.Write("Ingrese el nombre de la lista: ");
                nombreLista = Console.ReadLine();

                Console.Write("Ingrese el ID de inicio: ");
                idInicio = Convert.ToInt16(Console.ReadLine());
                #endregion

                #region Consulta SP
                sitio = new SPSite(urlSitio);
                web   = sitio.OpenWeb();

                SPList lista = web.Lists[nombreLista];
                SPListItemCollection itemsAntes = lista.Items;

                if (itemsAntes.Count == 0)
                {
                    #region Crear items
                    for (int i = 1; i < idInicio; i++)
                    {
                        SPListItem item = itemsAntes.Add();
                        item["Title"] = "Item " + i;
                        item.Update();
                    }
                    #endregion

                    #region Eliminar items
                    SPListItemCollection itemsDespues = lista.Items;
                    StringBuilder        batchString  = new StringBuilder();
                    batchString.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
                    foreach (SPListItem item in itemsDespues)
                    {
                        batchString.Append("<Method>");
                        batchString.Append("<SetList Scope=\"Request\">" + Convert.ToString(item.ParentList.ID) + "</SetList>");
                        batchString.Append("<SetVar Name=\"ID\">" + Convert.ToString(item.ID) + "</SetVar>");
                        batchString.Append("<SetVar Name=\"Cmd\">Delete</SetVar>");
                        batchString.Append("</Method>");
                    }
                    batchString.Append("</Batch>");
                    web.ProcessBatchData(batchString.ToString());

                    // Eliminar papelera
                    sitio.RecycleBin.DeleteAll();

                    Console.WriteLine("Proceso completado exitosamente.");
                    #endregion
                }
                else
                {
                    Console.WriteLine("Este proceso solo puede ser aplicado " +
                                      "a una lista que no contenga items.");
                }
                #endregion
            }
            catch (Exception ex)
            {
                Console.WriteLine("Se produjo un error vuelva a intentarlo.");
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (web != null)
                {
                    web.Dispose();
                }
                if (sitio != null)
                {
                    sitio.Dispose();
                }
            }
        }
Exemplo n.º 54
0
 public SPListCacheDependency(SPList list, double interval)
     : this(list) { }
Exemplo n.º 55
0
 public static SPListChangeMonitor GetMonitor(SPList list)
 {
     return(GetMonitors <SPListChangeMonitor>(list.ParentWeb.Site.ID).FirstOrDefault(v => v.listId == list.ID) ?? new SPListChangeMonitor(list));
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            string listName = "Service Desk Status";
            int    licdtmp  = System.Threading.Thread.CurrentThread.CurrentUICulture.LCID;

            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    try
                    {
                        int           LCID = (HttpContext.Current.Request.Url.ToString().Contains("fra/") ? 1036 : 1033);
                        StringBuilder sb   = new StringBuilder();
                        SPList        list = web.Lists.TryGetList(listName);



                        Literal1.Text = sb.ToString();

                        /*TableRow headerRow = new TableRow();
                         * TableCell headerCell = new TableCell();
                         *
                         * headerCell.BackColor = System.Drawing.Color.Black;
                         * headerCell.ForeColor = System.Drawing.Color.White;
                         * headerCell.Text = (LCID == 1036 ? "<h3>État du système</h3>" : " <h3> System Status</h3>");
                         * headerRow.BackColor = System.Drawing.Color.Black;
                         * headerRow.ForeColor = System.Drawing.Color.White;
                         * headerRow.Cells.Add(headerCell);
                         * Table1.Rows.Add(headerRow);
                         * Dont need to do this just changing the Title so Pascal doesnot have to modify it from GUI
                         * */

                        string wptitle;
                        string html;



                        string Fieldname = (LCID == 1036 ? "Status-FR" : "Status");
                        if (LCID == 1036)
                        {
                            this.Title = "État du système";
                            wptitle    = "État du système";
                        }
                        else
                        {
                            this.Title = "System Status";
                            wptitle    = "System Status";
                        }
                        //SPList geturl = web.Lists.[listName];
                        String strUrlbase = web.Url + "/" + list.RootFolder.Url;
                        int    i          = 0;
                        //only write html if there is something to write
                        html = "";
                        if (list.ItemCount > 0)
                        {
                            html = "<div id=\"SystemStatustitle\" class=\"SystemStatusTitleRow\" runat=\"server\"><h3 runat=\"server\" id=\"SystemStatush3\" class=\"background-accent margin-bottom-medium\" style=\"width:100% !important; vertical-align:middle;\">" + wptitle + "</h3></div>";
                        }
                        //html = html + "<br /> <br />";
                        foreach (SPListItem item in list.Items)
                        {
                            if (i < 3)
                            {
                                String strUrl     = strUrlbase + "/DispForm.aspx?ID=" + item.ID;
                                String tableField = " " +
                                                    "<a href=\"" + strUrl + "\"" + " class =\"taglink\" >" + item[Fieldname].ToString() + "</a> ";
                                //SystemStatusGrid.InnerText = "<div> " + tableField + " </div>" ;

                                html = html + "<div class=\"SystemStatusGrid\" id=\"SystemStatusGrid\" runat=\"server\" >";
                                html = html + tableField.ToString();
                                html = html + "</div>";

                                i++;
                            }
                        }
                        Literal1.Text = html.ToString();
                    }
                    catch (Exception ex)
                    {
                        Literal1.Text = ex.ToString();
                    }
                }
            }
        }
Exemplo n.º 57
0
        private void buildColumns(SPWeb web)
        {
            try
            {
                dt.Columns.Add("Period");
                dt.Columns.Add("Value");
                dt.Columns.Add("Capacity");
                dt.Columns.Add("ValueType");

                dt.Columns.Add("Site Name");
                dt.Columns.Add("Project");

                SPList  list  = web.Lists["EPMLiveOutlineCodes"];
                SPQuery query = new SPQuery();
                query.Query = "<Where><Eq><FieldRef Name=\"OutlineCodeType\"/><Value Type=\"Text\">Project</Value></Eq></Where>";
                foreach (SPListItem li in list.GetItems(query))
                {
                    dt.Columns.Add(li["DisplayName"].ToString());
                    arrProjectOC.Add(li.Title);
                }
                query       = new SPQuery();
                query.Query = "<Where><Eq><FieldRef Name=\"OutlineCodeType\"/><Value Type=\"Text\">Task</Value></Eq></Where>";
                dt.Columns.Add("Task");
                foreach (SPListItem li in list.GetItems(query))
                {
                    dt.Columns.Add(li["DisplayName"].ToString());
                    arrTaskOC.Add(li.Title);
                }

                dt.Columns.Add("Resource");

                list = web.Lists[CoreFunctions.getConfigSetting(web, "EPMLiveResourcePool")];

                foreach (SPField f in list.Fields)
                {
                    if (!f.Hidden && !f.ReadOnlyField && f.Type != SPFieldType.Attachments && f.InternalName != "Title" && f.InternalName != "SharePointAccount")
                    {
                        arrResOC.Add(f.InternalName);
                        dt.Columns.Add(f.Title);
                        dt.Columns.Add(f.Title + " Capacity");
                        buildResourceCap(list, f.InternalName);
                    }
                }

                list = web.Lists["EPMLivePeriods"];



                foreach (SPListItem li in list.Items)
                {
                    //dt.Columns.Add(li.Title);
                    PeriodItem pi = new PeriodItem();
                    pi.name     = li.Title.Replace(" ", "_x0020_");
                    pi.start    = li["StartDate"].ToString();
                    pi.finish   = li["EndDate"].ToString();
                    pi.capacity = li["Capacity"].ToString();
                    arrPeriods.Add(pi);
                }
            }
            catch { }
        }
Exemplo n.º 58
0
        private void processData(SPWeb web, SPWeb resWeb)
        {
            if (CoreFunctions.getConfigSetting(web, "EPMLiveResourceURL").ToLower() != resWeb.ServerRelativeUrl.ToLower())
            {
                return;
            }

            try
            {
                SPList list = web.Lists["EPMLiveTimePhased"];

                SPQuery query = new SPQuery();
                query.Query = "<Where><Eq><FieldRef Name='TimePhasedType'/><Value Type='Number'>1</Value></Eq></Where>";

                foreach (SPListItem li in list.GetItems(query))
                {
                    object[] arrDtRow  = new object[dt.Columns.Count];
                    string   project   = li.Title;
                    string   task      = li["Task"].ToString();
                    string   wbs       = li["WBS"].ToString();
                    string   resource  = li["Resource"].ToString();
                    string   valuetype = li["ValueType"].ToString();

                    arrDtRow[4] = web.Title;

                    processProjectInfo(web, ref arrDtRow, project);
                    processTaskInfo(web, ref arrDtRow, project, task, wbs);
                    processResourceInfo(resWeb, ref arrDtRow, resource);

                    arrDtRow[3] = valuetype;

                    processPeriods(li, ref arrDtRow);

                    dt.Rows.Add(arrDtRow);
                }
            }
            catch (Exception ex)
            {
                logError(ex.Message + ex.StackTrace);
            }
            try
            {
                if (Request["rollup"] != null && Request["rollup"].ToString() == "true")
                {
                    foreach (SPWeb w in web.Webs)
                    {
                        try
                        {
                            processData(w, resWeb);
                        }
                        catch (Exception ex) { LoggingService.WriteTrace(Area.EPMLiveCore, Categories.EPMLiveCore.Others, TraceSeverity.Medium, ex.ToString()); }
                        finally { if (w != null)
                                  {
                                      w.Dispose();
                                  }
                        }
                    }
                }
            }
            catch (Exception ex) { LoggingService.WriteTrace(Area.EPMLiveCore, Categories.EPMLiveCore.Others, TraceSeverity.Medium, ex.ToString()); }
        }
Exemplo n.º 59
0
 private void buildResourceCap(SPList list, string field)
 {
     BuildResourceCap(list, field, lstResourceCap);
 }
Exemplo n.º 60
0
 public FieldDefinition <TParentDefinition> AsMultiLookupTo(SPList specificTargetList)
 {
     return(AsMultiLookupTo(specificTargetList, "Title"));
 }