// Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite oSite = new SPSite(SPContext.Current.Site.ID);
            SPWebCollection collWebsite = oSite.AllWebs;

            for (int i = 0; i < collWebsite.Count; i++)
            {
                using (SPWeb oWebsite = collWebsite[i])
                {
                    try
                    {
                        SPWeb oWeb = oSite.OpenWeb(oWebsite.ID);
                        oWeb.AllowUnsafeUpdates = true;
                        oWeb.Features.Remove(new Guid(FeatureGUID_InternalMasterwithSearchBox));
                        oWeb.AllowUnsafeUpdates = false;
                    }
                    catch (Exception ex)
                    {
                        SPDiagnosticsService diagSvc = SPDiagnosticsService.Local;
                        diagSvc.WriteTrace(0, new SPDiagnosticsCategory("Kapsch GSA Search Box On All Subsites", TraceSeverity.High, EventSeverity.Error),
                                                                TraceSeverity.Monitorable,
                                                                "Writing to the ULS log:  {0}",
                                                                new object[] { ex.Message }); 
                    }
                }
            }
            oSite.Dispose();
            collWebsite = null;
        }
 /// <summary>
 /// Retrieves a TaxonomyValue corresponding to a term label within the default term store in the site collection's reserved group
 /// </summary>
 /// <remarks>
 /// Use other overloads and specify a group name to fetch from farm-global term sets instead of being limited 
 /// to the site collection's associated term group
 /// </remarks>
 /// <param name="site">The current site</param>
 /// <param name="termSetName">The term set name</param>
 /// <param name="termLabel">The default label of the term</param>
 /// <returns>The taxonomy value or null if not found</returns>
 public TaxonomyValue GetTaxonomyValueForLabel(SPSite site, string termSetName, string termLabel)
 {
     using (var timeTracker = this.timeTracker.BeginTimeTrackerScope(TimeTrackerKey))
     {
         return this.decorated.GetTaxonomyValueForLabel(site, termSetName, termLabel);
     }
 }
Пример #3
0
        protected void BindDropDownList()
        {
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                using (var adminSite = new SPSite(CurrentWeb.Site.ID))
                {
                    using (var adminWeb = adminSite.OpenWeb(CurrentWeb.ID))
                    {
                        try
                        {
                            adminWeb.AllowUnsafeUpdates = true;
                            SPList iconLink = Utilities.GetCustomListByUrl(adminWeb, ListsName.InternalName.WebsiteLink);
                            SPQuery query = new SPQuery();
                            query.Query = "<OrderBy><FieldRef Name='Title' Ascending='True' /></OrderBy>";

                            SPListItemCollection items = iconLink.GetItems(query);
                            DataTable dt = items.GetDataTable();
                            if (dt != null && dt.Rows.Count > 0)
                            {
                                lbWebURL.DataSource = dt;
                                lbWebURL.DataTextField = FieldsName.WebsiteLink.InternalName.Title;
                                lbWebURL.DataValueField = FieldsName.WebsiteLink.InternalName.WebURL;
                                lbWebURL.DataBind();
                            }
                            //lbWebURL.Items.Insert(0, new ListItem("--Liên kết website--", string.Empty));
                            lbWebURL.Attributes.Add("onclick", string.Format("RedirectURL('{0}')", lbWebURL.ClientID));
                        }
                        catch (SPException ex)
                        {
                            Utilities.LogToULS(ex);
                        }
                    }
                }
            });
        }
Пример #4
0
        void SaveAsso1()
        {
            ISharePointService sps = ServiceFactory.GetSharePointService(true);

            SPList list = sps.GetList(CAWorkFlowConstants.WorkFlowListName.StoreMaintenanceItems1.ToString());

            foreach (DataRow row in this.DataForm1.Asso1.Rows)
            {
                SPListItem item = list.Items.Add();
                item["WorkflowNumber"] = DataForm1.WorkflowNumber;
                item["Seq"] = row["Seq"];
                item["Reason"] = row["Reason"];
                item["Description"] = row["Description"];
                item["Remark"] = row["Remark"];
                try
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb web = site.OpenWeb(SPContext.Current.Site.RootWeb.ID))
                        {
                            item.Web.AllowUnsafeUpdates = true;
                            item.Update();
                            item.Web.AllowUnsafeUpdates = false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Response.Write("An error occured while updating the items");
                }

                //item.Web.AllowUnsafeUpdates = true;
                //item.Update();
            }
        }
        /// <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, StringDictionary keyValues, out string output)
        {
            output = string.Empty;

            string url = Params["url"].Value.TrimEnd('/');

            using (SPSite site = new SPSite(url))
            {
                using (SPWeb web = site.AllWebs[Utilities.GetServerRelUrlFromFullUrl(url)])
                {

                    foreach (SPLanguage lang in web.RegionalSettings.InstalledLanguages)
                    {
                        foreach (SPWebTemplate template in site.GetWebTemplates((uint)lang.LCID))
                        {
                            output += template.Name + " = " + template.Title + " (" + lang.LCID + ")\r\n";
                        }
                        foreach (SPWebTemplate template in site.GetCustomWebTemplates((uint)lang.LCID))
                        {
                            output += template.Name + " = " + template.Title + " (Custom)(" + lang.LCID + ")\r\n";
                        }
                    }
                }
            }

            return (int)ErrorCodes.NoError;
        }
Пример #6
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            SPListItem item = SPContext.Current.ListItem;
            item["FileName"] = DataForm1.Submit();
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb(SPContext.Current.Site.RootWeb.ID))
                    {
                        item.Web.AllowUnsafeUpdates = true;
                        item.Update();
                        item.Web.AllowUnsafeUpdates = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write("An error occured while updating the items");
            }

            //item.Web.AllowUnsafeUpdates = true;
            //item.Update();
            UpdateRecords();
            base.Back();
        }
Пример #7
0
        public System.Collections.Specialized.StringCollection GetSPChoiceFieldValue(string listName, string fieldName)
        {
            SPContext context = SPContext.Current;
            StringCollection fieldChoices = null;

            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite site = new SPSite(context.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb(context.Web.ID))
                    {
                        SPList list = web.Lists[listName];
                        SPField field = list.Fields[fieldName] as SPField;

                        if (field != null
                            && field.Type == SPFieldType.Choice)
                        {

                            fieldChoices = (field as SPFieldChoice).Choices;
                        }
                    }
                }
            });

            return fieldChoices;
        }
Пример #8
0
 /// <summary>
 /// Copies files from given directory to the SiteConfig list, overwriting existing items.
 /// 
 /// The filenames are split on __ (two underscores) and used to fill columns in the item.
 /// The format is "Location__App__.xml"
 /// 
 /// Contents of file go into the ConfigXML field.
 /// </summary>
 /// <param name="site"></param>
 /// <param name="path">like @"{0}\LAYOUTS\SPTools\SiteConfigs\"</param>
 public void CopySiteConfigItems(SPSite site, string path, string keyForMainFileValue)
 {
     if (site == null) throw new ArgumentNullException("site");
     SPList siteConfig = site.RootWeb.OpenList(Const.SITECONFIG_LIST_TITLE, true);
     List<object> itemResults = siteConfig.ImportFilesAsListItems(path, new[] { "NVR_SiteConfigPackage", "Title" }, keyForMainFileValue);
     log.LogInfo("CopySiteConfigItems\n", itemResults.Select(i => i is SPListItem ? ((SPListItem)i).FormUrlDisplay() : i.ToString()).JoinStrings("\n"));
 }
Пример #9
0
 public static void BindIdentificationType(RadioButtonList rbList, string texto, string valor)
 {
     try
     {
     if (SPContext.Current != null)
     {
       using(Microsoft.SharePoint.SPWeb web = SPContext.Current.Web)
       {
         BLL.IdentificationTypeBLL bll = new CAFAM.WebPortal.BLL.IdentificationTypeBLL(web);
         DataSet ds = bll.GetIdentificationTypeList();
         BindList(rbList, ds, texto, valor);
       }
     }
     else
     {
       using(SPSite site = new SPSite(SP_SITE)){
         using(Microsoft.SharePoint.SPWeb web = site.OpenWeb())
         {
             BLL.IdentificationTypeBLL bll = new CAFAM.WebPortal.BLL.IdentificationTypeBLL(web);
             DataSet ds = bll.GetIdentificationTypeList();
             BindList(rbList, ds, texto, valor);
         }
       }
     }
     }
     catch (Exception ex)
     {
     throw ex;
     }
 }
        /// <summary>
        /// Retrieves a TaxonomyValue corresponding to a term label within the default term store
        /// </summary>
        /// <param name="site">The current site</param>
        /// <param name="termStoreGroupName">The group name</param>
        /// <param name="termSetName">The term set name</param>
        /// <param name="termLabel">The default label of the term</param>
        /// <returns>The taxonomy value or null if not found</returns>
        public TaxonomyValue GetTaxonomyValueForLabel(SPSite site, string termStoreGroupName, string termSetName, string termLabel)
        {
            TaxonomySession session = this.taxManager.GetSiteTaxonomyCache(site, null).TaxonomySession;
            TermStore termStore = session.DefaultSiteCollectionTermStore;

            return GetTaxonomyValueForLabelInternal(termStore, termStoreGroupName, termSetName, termLabel);
        }
Пример #11
0
        static void Main(string[] args)
        {
            using (SPSite site = new SPSite("http://sam2012:33333"))
            {
                using (SPWeb web = site.OpenWeb("/sub"))
                {
                    web.AnonymousPermMask64 |= SPBasePermissions.UseRemoteAPIs;//SPBasePermissions.OpenItems;
                    Console.Write(web.AnonymousPermMask64);
                    Console.Write(web.DoesUserHavePermissions(SPBasePermissions.AddListItems));
                    SPList list = web.Lists["Temp"];
                    bool addItemPerm = list.DoesUserHavePermissions(SPBasePermissions.AddListItems);
                    Console.WriteLine(addItemPerm);
                    Console.WriteLine(list.AnonymousPermMask64);
                    web.Update();
                    Console.ReadKey();
                }
            }

            //byte[] sidBytes = UserPropertiesHelper.ConvertStringSidToSid("S-1-5-21-1343462910-744444023-3288617952-1638");
            //string loginName = PeopleEditor.GetAccountFromSid(sidBytes);
            //Console.WriteLine(loginName);
            //Console.ReadKey();

            //foreach (SPServer server in SPFarm.Local.Servers)
            //{
            //    Console.WriteLine(server.Name + "--" + server.Role);
            //    //Helper.Administration.Server.IsWebFrontEnd(server);
            //}
            //Console.ReadKey();
        }
        internal Employee GetEmployeedetails(string name)
        {
            var empEntity = new Employee();
            using (var site = new SPSite(SPContext.Current.Site.Url))
            {
                using (var web = site.OpenWeb())
                {
                    SPUser user = web.CurrentUser;

                    hdnCurrentUsername.Value = user.Name;

                    SPListItemCollection currentUserDetails = GetListItemCollection(web.Lists[Utilities.EmployeeScreen], "Employee Name", name, "Status", "Active");
                    foreach (SPListItem currentUserDetail in currentUserDetails)
                    {
                        empEntity.EmpId = currentUserDetail[Utilities.EmployeeId].ToString();
                        empEntity.EmployeeType = currentUserDetail[Utilities.EmployeeType].ToString();
                        empEntity.Department = currentUserDetail[Utilities.Department].ToString();
                        empEntity.Desigination = currentUserDetail[Utilities.Designation].ToString();
                        empEntity.DOJ = DateTime.Parse(currentUserDetail[Utilities.DateofJoin].ToString());
                        empEntity.ManagerWithID = currentUserDetail[Utilities.Manager].ToString();
                        var spv = new SPFieldLookupValue(currentUserDetail[Utilities.Manager].ToString());
                        empEntity.Manager = spv.LookupValue;
                    }
                }
            }
            return empEntity;
        }
        /// <summary>
        /// Retrieves a TaxonomyValue corresponding to a term label within a desired term store
        /// </summary>
        /// <param name="site">The current site</param>
        /// <param name="termStoreName">The term store name</param>
        /// <param name="termStoreGroupName">The group name</param>
        /// <param name="termSetName">The term set name</param>
        /// <param name="termLabel">The default label of the term</param>
        /// <returns>The taxonomy value or null if not found</returns>
        public TaxonomyValue GetTaxonomyValueForLabel(SPSite site, string termStoreName, string termStoreGroupName, string termSetName, string termLabel)
        {
            TaxonomySession session = this.taxManager.GetSiteTaxonomyCache(site, termStoreName).TaxonomySession;
            TermStore termStore = session.TermStores[termStoreName];

            return GetTaxonomyValueForLabelInternal(termStore, termStoreGroupName, termSetName, termLabel);
        }
Пример #14
0
        /*SP.GlobalTopMenu*/
        /// <summary>
        /// Builds the xDocument of the specific color and Fiscal Year.
        /// </summary>
        /// <param name="strFiscalYearTitle">Fiscal Year title from the Fiscal Year Custom list.</param>
        /// <param name="strColorTitle">Color title from the Color custom list.</param>
        /// <returns></returns>
        public static XDocument GetXDocument(XMLType eXMLName)
        {
            try
            {
                using (SPSite oSite = new SPSite(SiteRootUrl))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        SPFolder oTargetFolder = oWeb.Folders[XML_LIBRARY];
                        SPFile spFile;

                        if (oWeb.GetFolder(oTargetFolder.Url + "/" + XML_FOLDER).Exists)
                        {
                            if (oWeb.GetFile(oTargetFolder.SubFolders[XML_FOLDER].Url + "/" + eXMLName + ".xml").Exists)
                            {
                                spFile = oTargetFolder.SubFolders[XML_FOLDER].Files[eXMLName + ".xml"];

                                StreamReader sr = new StreamReader(spFile.OpenBinaryStream());

                                return XDocument.Parse(sr.ReadToEnd());
                            }
                        }
                        return emptyXMLFile(eXMLName);
                    }
                }
            }
            catch (Exception ex)
            {
                return emptyXMLFile(eXMLName);
            }
        }
        public SharepointList ExportListToObjects(string siteUrl, string listName)
        {
            var list = new SPSite(siteUrl).OpenWeb().Lists[listName];
            var cols = new List<SharepointList.Column>();

            foreach (SPField field in list.Fields)
            {
                if(field.ReadOnlyField) continue;
                cols.Add(new SharepointList.Column()
                         {
                             Name = field.InternalName,
                             Type = field.FieldValueType
                         });
            }

            var rows = new List<SharepointList.Row>();
            foreach (SPListItem item in list.Items)
            {
                var values = new List<object>();
                foreach (SPField field in list.Fields)
                {
                    if (field.ReadOnlyField) continue;
                    values.Add(item[field.InternalName]);
                }
                rows.Add(new SharepointList.Row() { Values = values});
            }

            return new SharepointList() {Columns = cols, Rows = rows};
        }
 public static void Log(Exception ex, string component)
 {
     try
     {
         SPSecurity.RunWithElevatedPrivileges(delegate
         {
             using (SPSite site = new SPSite(SPContext.Current.Site.RootWeb.Url + "/Admin"))
             {
                 using (SPWeb rootweb = site.OpenWeb())
                 {
                     rootweb.AllowUnsafeUpdates = true;
                     SPList logs = rootweb.Lists.TryGetList("Logs");
                     if (logs != null)
                     {
                         SPListItem item = logs.AddItem();
                         if (ex.Message.Length > 100)
                             item["Message"] = ex.Message.Substring(0, 100);
                         else
                             item["Message"] = ex.Message;
                         if (ex.StackTrace != null)
                             item["StackTrace"] = ex.StackTrace;
                         item["Component"] = component;
                         item.Update();
                         logs.Update();
                     }
                 }
             }
         });
     }
     catch { }
 }
        public void DeployIntranet(SPSite site, Options options)
        {
            // pushing site model
            if (options.DeploySite)
            {
                var siteModel = new IntrSiteModel();

                this.DeploySiteModel(site, siteModel.GetSandboxSolutionsModel());
                this.DeploySiteModel(site, siteModel.GetSiteFeaturesModel());
                this.DeploySiteModel(site, siteModel.GetSiteSecurityModel());
                this.DeploySiteModel(site, siteModel.GetFieldsAndContentTypesModel());
            }

            // pushing root web model
            if (options.DeployRootWeb)
            {
                var rootWebModel = new IntrRootWebModel();

                this.DeployWebModel(site.RootWeb, rootWebModel.GetStyleLibraryModel());
                this.DeployWebModel(site.RootWeb, rootWebModel.GetModel());
            }

            // pushing 'How-tow' sub web
            if (options.DeployHowTosWeb)
            {
                var howTosWebModel = new IntrHowTosWebModel();

                this.DeployWebModel(site.RootWeb, howTosWebModel.GetModel());
            }
        }
Пример #18
0
        private string GetDepartmentOfCurrentUser()
        {
            string output = string.Empty;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPListItemCollection userItems = web.Lists.TryGetList(web.SiteUserInfoList.Title).GetItems();

                            SPListItem userItem = web.Lists.TryGetList(web.SiteUserInfoList.Title).GetItemById(SPContext.Current.Web.CurrentUser.ID);
                            if (userItem != null)
                            {
                                output = userItem["Department"] == null ? string.Empty : userItem["Department"].ToString();
                            }
                        }
                    }
                });
            }
            catch { throw; }

            return output;
        }
        public Scope EnsureSiteScope(SPSite site, string scopeName, string displayGroupName, string searchPagePath)
        {
            // remotescopes class retrieves information via search web service so we run this as the search service account
            RemoteScopes remoteScopes = new RemoteScopes(SPServiceContext.GetContext(site));

            // see if there is an existing scope
            Scope scope = remoteScopes.GetScopesForSite(new Uri(site.Url)).Cast<Scope>().FirstOrDefault(s => s.Name == scopeName);

            // only add if the scope doesn't exist already
            if (scope == null)
            {
                scope = remoteScopes.AllScopes.Create(scopeName, string.Empty, new Uri(site.Url), true, searchPagePath, ScopeCompilationType.AlwaysCompile);
            }

            // see if there is an existing display group
            ScopeDisplayGroup displayGroup = remoteScopes.GetDisplayGroupsForSite(new Uri(site.Url)).Cast<ScopeDisplayGroup>().FirstOrDefault(d => d.Name == displayGroupName);

            // add if the display group doesn't exist
            if (displayGroup == null)
            {
                displayGroup = remoteScopes.AllDisplayGroups.Create(displayGroupName, string.Empty, new Uri(site.Url), true);
            }

            // add scope to display group if not already added
            if (!displayGroup.Contains(scope))
            {
                displayGroup.Add(scope);
                displayGroup.Update();
            }

            // optionally force a scope compilation so this is available immediately
            remoteScopes.StartCompilation();

            return scope;
        }
        /// <summary>
        /// Executes 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, StringDictionary keyValues, out string output)
        {
            output = string.Empty;

            #if !MOSS
            output = NOT_VALID_FOR_FOUNDATION;
            return (int)ErrorCodes.GeneralError;
            #endif

            SPServiceContext context = null;
            if (Params["serviceappname"].UserTypedIn)
            {
                SPSiteSubscriptionIdentifier subId = Utilities.GetSiteSubscriptionId(new Guid(Params["sitesubscriptionid"].Value));
                SPServiceApplication svcApp = Utilities.GetUserProfileServiceApplication(Params["serviceappname"].Value);
                Utilities.GetServiceContext(svcApp, subId);
            }
            else
            {
                using (SPSite site = new SPSite(Params["contextsite"].Value))
                    context = SPServiceContext.GetContext(site);
            }

            Common.Audiences.DeleteAudience.Delete(context,
                   Params["name"].Value,
                   Params["rulesonly"].UserTypedIn);

            return (int)ErrorCodes.NoError;
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow itemRow in this.Gridview1.Rows)
            {
                TextBox txtCount = itemRow.FindControl("txtCounty") as TextBox;
                TextBox txtCountry = itemRow.FindControl("txtCountry") as TextBox;
                TextBox txtDate = itemRow.FindControl("txtDate") as TextBox;

                using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists.TryGetList(Consts.Lists.ScheduleHoliday.ListName);
                        if (list == null) continue;

                        SPListItem itemAdd = list.AddItem();
                        itemAdd[Consts.Lists.ScheduleHoliday.Fields.Title] = txtCount.Text;
                        itemAdd[Consts.Lists.ScheduleHoliday.Fields.Country] = txtCountry.Text;
                        itemAdd[Consts.Lists.ScheduleHoliday.Fields.Holidays] = Convert.ToDateTime(txtDate.Text);
                        itemAdd.Update();
                    }
                }
            }

            SetInitialRow();
        }
Пример #22
0
        public string createNewDocumentLibrary(SPSite site, string _web, string docLib)
        {
            //foreach (webs web_ in Enum.GetValues(typeof(webs)))
            //{
            try
            {
                bool webExist = webExists(site, _web);

                if (webExist == true)
                {

                    using (SPWeb web = site.OpenWeb(_web))
                    {
                        SPList list = web.Lists.TryGetList(docLib);
                        if (list == null)
                        {
                            SPListTemplateType tempType = SPListTemplateType.DocumentLibrary;
                            web.Lists.Add(docLib, null, tempType);
                            return docLib;
                        }
                    }
                }
                //}
            }
            catch { }
            return docLib;
        }
        /// <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, StringDictionary keyValues, out string output)
        {
            output = string.Empty;

            string url = Params["url"].Value.TrimEnd('/');
            bool force = Params["force"].UserTypedIn;
            string backupDir = Params["backupdir"].Value;

            SPList list = null;
            if (Utilities.EnsureAspx(url, false, false) && !Params["listname"].UserTypedIn)
                list = Utilities.GetListFromViewUrl(url);
            else if (Params["listname"].UserTypedIn)
            {
                using (SPSite site = new SPSite(url))
                using (SPWeb web = site.OpenWeb())
                {
                    try
                    {
                        list = web.Lists[Params["listname"].Value];
                    }
                    catch (ArgumentException)
                    {
                        throw new SPException("List not found.");
                    }
                }
            }

            if (list == null)
                throw new SPException("List not found.");

            Common.Lists.DeleteList.Delete(force, backupDir, list);

            return (int)ErrorCodes.NoError;
        }
        private SiteMapNode BuildFullMenuStructure(SPWeb currentWeb)
        {
            Clear();

            SiteMapNode root = null;

            SPWeb webSite = SPContext.Current.Site.RootWeb;
            string relativeUrl = webSite.ServerRelativeUrl.ToString();

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPSite currentsite = new SPSite(webSite.Site.Url);
                SPWeb rootweb = currentsite.OpenWeb(relativeUrl);

                root = new SiteMapNode(this, rootweb.ID.ToString(), rootweb.ServerRelativeUrl, rootweb.Title);

                if (rootweb == currentWeb)
                {
                    SiteMapNode root2 = new SiteMapNode(this, "Root", "/", null);
                    AddNode(root2);

                    string cacheKey = rootweb.ID.ToString();
                    AddMenuToCache(cacheKey, root2);
                }

                foreach (SPWeb web in rootweb.Webs)
                {
                    SiteMapNode node = BuildNodeTree(web);
                    AddNode(node, root);
                }
            });

            return root;
        }
Пример #25
0
        private void AddFileInfo(SPItemEventProperties properties)
        {
            try
            {
                var url = properties.WebUrl + "/" + properties.AfterUrl;
                var fileName = properties.AfterUrl;

                using (var site = new SPSite(properties.Web.Site.ID))
                using (var web = site.RootWeb)
                {
                    var list = web.Lists[LogList.ListName];
                    var listItems = list.Items;

                    var item = listItems.Add();
                    item["Title"] = fileName;
                    item["URL"] = url;
                    item.Update();
                }

                ULSLog.LogDebug(String.Format("Added {0} to {1} list", url, LogList.ListName));
            }
            catch (Exception ex)
            {
                ULSLog.LogError(ex);
            }
        }
Пример #26
0
        public static DateTime? GetLastUpdateDate()
        {
            DateTime? maxValue = null;

            try
            {
                SPWeb web;
                if (SPContext.Current != null)
                    web = SPContext.Current.Web;
                else
                    web = new SPSite("http://finweb.contoso.com/sites/PMM").OpenWeb();

                SPList objList = web.Lists.TryGetList(Constants.LIST_NAME_PROJECT_TASKS);

                SPQuery objQuery = new SPQuery();
                objQuery.Query = "<OrderBy><FieldRef Name='ModifiedOn' Ascending='False' /></OrderBy><RowLimit>1</RowLimit>";
                objQuery.Folder = objList.RootFolder;

                // Execute the query against the list
                SPListItemCollection colItems = objList.GetItems(objQuery);

                if (colItems.Count > 0)
                {
                    maxValue = Convert.ToDateTime(colItems[0]["ModifiedOn"]);
                }
            }
            catch (Exception ex)
            {

            }

            return maxValue;
        }
Пример #27
0
        public static SPList GetSpecifiedList(string listName)
        {
            // get fresh SPSite and SPWeb objects so they run in the correct context
            // depending on whether we have elevated privileges to view draft items
            // or not

            //Not sure if caching a good idea here or not...
            //object cacheData = HttpContext.Current.Cache["ListCache" + listName];

            //if (cacheData != null)
            //    return (SPList)cacheData;

            using (SPSite site = new SPSite(SPContext.Current.Site.ID))
            {
                if (listName.StartsWith("/"))
                {
                //    SPList lst=site.RootWeb.Lists[listName.Substring(1)];
                //    HttpContext.Current.Cache.Add("ListCache" + listName, lst, null, DateTime.Now.AddHours(12), System.Web.Caching.Cache.NoSlidingExpiration,
                //System.Web.Caching.CacheItemPriority.Default, null);
                    return site.RootWeb.Lists[listName.Substring(1)];
                }
                else
                {
                    using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                    {
                    //    SPList lst = web.Lists[listName];
                    //    HttpContext.Current.Cache.Add("ListCache" + listName, lst, null, DateTime.Now.AddHours(12), System.Web.Caching.Cache.NoSlidingExpiration,
                    //System.Web.Caching.CacheItemPriority.Default, null);

                        return web.Lists[listName];
                    }
                }
            }
        }
        /// <summary>
        /// Processes the content type.
        /// </summary>
        /// <param name="site">The site.</param>
        /// <param name="contentTypeName">Name of the content type.</param>
        /// <param name="verbose">if set to <c>true</c> [verbose].</param>
        /// <param name="updateFields">if set to <c>true</c> [update fields].</param>
        /// <param name="removeFields">if set to <c>true</c> [remove fields].</param>
        public static void Execute(SPSite site, string contentTypeName, bool updateFields, bool removeFields)
        {
            try
            {
                Logger.Write("Pushing content type changes to lists for '" + contentTypeName + "'");
                // get the site collection specified
                using (SPWeb rootWeb = site.RootWeb)
                {

                    //Get the source site content type
                    SPContentType sourceCT = rootWeb.AvailableContentTypes[contentTypeName];
                    if (sourceCT == null)
                    {
                        throw new ArgumentException("Unable to find Content Type named \"" + contentTypeName + "\"");
                    }
                    Execute(sourceCT, updateFields, removeFields);
                }
                return;
            }
            catch (Exception ex)
            {
                Logger.WriteException(new System.Management.Automation.ErrorRecord(new SPException("Unhandled error occured.", ex), null, System.Management.Automation.ErrorCategory.NotSpecified, null));
                throw;
            }
            finally
            {
                Logger.Write("Finished pushing content type changes to lists for '" + contentTypeName + "'");
            }
        }
        internal static void Guardar(Contacto _contacto)
        {
            String webUrl = "http://sharepointser";

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (var site = new SPSite(webUrl))
                {
                    using (var web = site.OpenWeb())
                    {
                        SPListItemCollection list = web.Lists["Contactos"].Items;

                        SPListItem item = list.Add();
                        item["Title"] = _contacto.Nombre;
                        item["Identificacion"] = _contacto.Identificacion;

                        var allowUnsafeUpdates = web.AllowUnsafeUpdates;
                        web.AllowUnsafeUpdates = true;

                        item.Update();

                        web.AllowUnsafeUpdates = allowUnsafeUpdates;
                    }
                }
            });
        }
Пример #30
0
        static void Main(string[] args)
        {
            using (SPSite site = new SPSite("http://sam2012"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    //Test1(web);
                   // GetAllItemsIncludeFolders(web);
                    Test2(web);
                }

                Console.ReadKey();
            }

            List<string> l = new List<string>(){"1","2","3","4"};
            for (int i = 0; i < 3; i++)
            {
                string s = l.FirstOrDefault(k => k == 1.ToString());
                l.Remove(s);
                string s1 = l.FirstOrDefault(k => k == 2.ToString());
                l.Remove(s1);
            }

            foreach (string v in l)
            {
                Console.WriteLine(v);
            }

            Console.ReadKey();
        }
        public Hashtable SetItemFullPermissionsQoBC(SPUserCodeWorkflowContext context, string id, string sourceList)
        {
            Hashtable results = new Hashtable();

            results["result"] = string.Empty;
            string result = string.Empty;

            try
            {
                using (SPSite site = new SPSite(context.CurrentWebUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        int currentId;
                        if (int.TryParse(id, out currentId))
                        {
                            SPList list = web.Lists[sourceList];
                            if (list != null)
                            {
                                SPListItem item = list.GetItemById(currentId);
                                if (item != null)
                                {
                                    using (DisabledItemEventsScope scope = new DisabledItemEventsScope())
                                    {
                                        if (!item.HasUniqueRoleAssignments)
                                        {
                                            item.BreakRoleInheritance(true);
                                        }
                                        foreach (SPRoleAssignment assignment in item.RoleAssignments)
                                        {
                                            assignment.RoleDefinitionBindings.RemoveAll();
                                            assignment.Update();
                                        }

                                        SPRoleDefinition roleDefinition = web.RoleDefinitions["Full Control"];
                                        GetSPUserObject(item, "Created By", roleDefinition);
                                        SPGroup group = web.Groups["QoBCAdmins"];
                                        if (group != null)
                                        {
                                            AddPermissions(item, group, roleDefinition);
                                        }

                                        //SPRoleDefinition roleDefinitionContribute = web.RoleDefinitions["Contribute"];
                                        SPRoleDefinition roleDefinitionContribute = web.RoleDefinitions.GetByType(SPRoleType.Contributor);  // For Contribute
                                        SPGroup          groupResponders          = web.Groups["QoBCResponders"];
                                        if (groupResponders != null)
                                        {
                                            AddPermissions(item, groupResponders, roleDefinitionContribute);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                results["success"] = true;
            }
            catch (Exception e)
            {
                results            = new Hashtable();
                result            += e.ToString();
                results["success"] = false;
            }
            results["result"] = result;

            return(results);
        }
Пример #32
0
        public static void UpdateColForSortData(string siteUrl)
        {
            if (!string.IsNullOrEmpty(siteUrl))
            {
                string colForSortColName          = "Ordering";
                string approvalStatusColName      = "Approval Status";
                string overtimeManagementListName = "Overtime Management";
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        Console.Write("Processing...");
                        using (SPSite spSite = new SPSite(siteUrl))
                        {
                            using (SPWeb spWeb = spSite.RootWeb)
                            {
                                #region Update data for ColForSort
                                Console.WriteLine();
                                Console.Write("List Name: {0}", overtimeManagementListName);
                                SPList overtimeManagementList = spWeb.Lists.TryGetList(overtimeManagementListName);
                                if (overtimeManagementList != null)
                                {
                                    if (overtimeManagementList.Fields.ContainsField(colForSortColName) == true && overtimeManagementList.Fields.ContainsField(approvalStatusColName) == true)
                                    {
                                        spWeb.AllowUnsafeUpdates = true;

                                        SPListItemCollection itemcollection = overtimeManagementList.Items;
                                        foreach (SPListItem item in itemcollection)
                                        {
                                            string approvalStatusVal = item[approvalStatusColName] + string.Empty;
                                            switch (approvalStatusVal)
                                            {
                                            case "true":
                                                item[colForSortColName] = 7;
                                                break;

                                            case "false":
                                                item[colForSortColName] = 8;
                                                break;

                                            default:
                                                item[colForSortColName] = 0;
                                                break;
                                            }
                                            item.SystemUpdate();
                                        }

                                        spWeb.AllowUnsafeUpdates = false;
                                        Console.Write(" -> Done");
                                    }
                                    else
                                    {
                                        Console.Write(" -> Existed");
                                    }
                                }
                                else
                                {
                                    Console.WriteLine();
                                    Console.Write("Cannot find list: {0}", overtimeManagementListName);
                                }
                                #endregion
                            }
                        }
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine(string.Format("Error: {0}", ex.Message));
                }
                Console.WriteLine();
                Console.Write("Press any key to exit...");
                Console.Read();
            }
            else
            {
                Console.Write("Troll?");
                Console.Read();
            }
        }
Пример #33
0
        public static void AddDelegatedByColToList(string siteUrl)
        {
            if (!string.IsNullOrEmpty(siteUrl))
            {
                string colName  = "DelegatedBy";
                string listName = "Employees";
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        Console.Write("Processing...");
                        using (SPSite spSite = new SPSite(siteUrl))
                        {
                            using (SPWeb spWeb = spSite.RootWeb)
                            {
                                SPList employeePositionList = spWeb.Lists.TryGetList("Employee Position");
                                SPList spList = spWeb.Lists.TryGetList(listName);
                                if (spList != null && employeePositionList != null)
                                {
                                    Console.WriteLine();
                                    Console.Write("List Name: {0}", listName);

                                    spWeb.AllowUnsafeUpdates = true;
                                    if (spList.Fields.ContainsField(colName) == false)
                                    {
                                        spList.Fields.AddFieldAsXml(@"<Field ID='{18a99830-576c-4039-b6aa-e350d5ab8692}' Name='DelegatedBy' DisplayName='DelegatedBy' Type='LookupMulti' List='" + employeePositionList.ID.ToString() + "' ShowField='CommonName' Mult='TRUE' Required='FALSE' Group='Stada Columns'></Field>", false, SPAddFieldOptions.AddToDefaultContentType);
                                        spList.Update();

                                        SPField theField   = spList.Fields[new Guid("{18a99830-576c-4039-b6aa-e350d5ab8692}")];
                                        theField.SchemaXml = @"<Field ID='{18a99830-576c-4039-b6aa-e350d5ab8692}' Name='DelegatedBy' DisplayName='$Resources:RBVHStadaLists,EmployeeInfo_DelegatedBy;' Type='LookupMulti' List='" + employeePositionList.ID.ToString() + "' ShowField='CommonName' Mult='TRUE' Required='FALSE' Group='Stada Columns'></Field>";
                                        theField.Update();

                                        Console.Write(" -> Done");
                                    }
                                    else
                                    {
                                        Console.Write(" -> Existed");
                                    }
                                    spWeb.AllowUnsafeUpdates = false;
                                }
                                else
                                {
                                    Console.WriteLine();
                                    Console.Write("Cannot find list: {0}", listName);
                                }
                            }
                        }
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine(string.Format("Error: {0}", ex.Message));
                }
                Console.WriteLine();
                Console.Write("Press any key to exit...");
                Console.Read();
            }
            else
            {
                Console.Write("Troll?");
                Console.Read();
            }
        }
Пример #34
0
        private void SendEmail()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                        {
                            var opinionList = Utility.GetListFromURL(Constants.OPINION_LIST_URL, web);
                            var enquiryList = Utility.GetListFromURL(Constants.TYPE_OF_ENQUIRY_LIST_URL, web);
                            if (opinionList != null && enquiryList != null)
                            {
                                string emailAddress = GetEmailByEnquiry(web, int.Parse(ddlTypeOfEnquiry.SelectedValue));
                                if (string.IsNullOrEmpty(emailAddress))
                                {
                                    string internalEmail = enquiryList.GetCustomProperty(Constants.CONTACT_INTERNAL_EMAIL_PROPERTY);
                                    if (!string.IsNullOrEmpty(internalEmail))
                                    {
                                        string[] internalEmailArray = internalEmail.Split(',');
                                        foreach (string item in internalEmailArray)
                                        {
                                            SPUser user   = web.EnsureUser(item);
                                            emailAddress += user.Email + ";";
                                        }
                                    }
                                    string externalEmail = enquiryList.GetCustomProperty(Constants.CONTACT_EXTERNAL_EMAIL_PROPERTY);
                                    if (!string.IsNullOrEmpty(externalEmail))
                                    {
                                        emailAddress += externalEmail;
                                    }
                                }

                                string emailTitle = enquiryList.GetCustomProperty(Constants.CONTACT_TITLE_EMAIL_PROPERTY);
                                if (string.IsNullOrEmpty(emailTitle))
                                {
                                    emailTitle = opinionList.Title;
                                }

                                string isAddDate = enquiryList.GetCustomProperty(Constants.CONTACT_ADD_DATE_EMAIL_PROPERTY);
                                if (!string.IsNullOrEmpty(isAddDate) && bool.Parse(isAddDate))
                                {
                                    emailTitle = string.Format("[{0}] - {1}", ddlTypeOfEnquiry.SelectedItem.Text, emailTitle);
                                }

                                //string emailHeader = enquiryList.GetCustomProperty(Constants.CONTACT_HEADER_EMAIL_PROPERTY);

                                string emailBodySetting = enquiryList.GetCustomProperty(Constants.CONTACT_BODY_HTML_EMAIL_PROPERTY);
                                string emailBody        = txtContent.Text.Replace(System.Environment.NewLine, "<br />");

                                if (!string.IsNullOrEmpty(emailBodySetting))
                                {
                                    try
                                    {
                                        emailBody = string.Format(emailBodySetting, emailBody);
                                    }
                                    catch
                                    {
                                        emailBody = txtContent.Text.Replace(System.Environment.NewLine, "<br />");;
                                    }
                                }

                                web.AllowUnsafeUpdates      = true;
                                SPListItem spListItem       = opinionList.Items.Add();
                                spListItem["Title"]         = emailTitle;
                                spListItem["Content"]       = txtContent.Text;
                                spListItem["TypeOfEnquiry"] = ddlTypeOfEnquiry.SelectedValue;
                                spListItem["Author"]        = SPContext.Current.Web.CurrentUser;
                                spListItem["Editor"]        = SPContext.Current.Web.CurrentUser;
                                spListItem.SystemUpdate();
                                web.AllowUnsafeUpdates = false;
                                SPUtility.SendEmail(web, true, false, emailAddress, emailTitle, emailBody);
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                Utility.LogError(ex.Message, AIAPortalFeatures.Infrastructure);
            }
        }
Пример #35
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        internal static string GetWorkspaceCenterGridData(string data, SPWeb oWeb)
        {
            try
            {
                #region Xml Parsing - Parameters

                StringBuilder sbListWorkSpaceCenterDiv = new StringBuilder();
                string        sqlquery = string.Empty;
                DataTable     dtWorkspacecenterData = null;
                DataTable     dtFRFData             = null;
                DataTable     dtRPTWebData          = null;
                var           result = new XDocument();
                #endregion


                using (SPSite spSite = new SPSite(oWeb.Site.ID))
                {
                    using (SPWeb spWeb = spSite.OpenWeb(oWeb.ID))
                    {
                        try
                        {
                            var queryExecutor = new QueryExecutor(spWeb);
                            if (data == "MyFavorite")
                            {
                                sqlquery     = string.Format("select WEB_ID from FRF where [TYPE] = 4 and USER_ID ={0}", SPContext.Current.Web.CurrentUser.ID);
                                dtFRFData    = queryExecutor.ExecuteEpmLiveQuery(sqlquery, new Dictionary <string, object> {
                                });
                                dtRPTWebData = queryExecutor.ExecuteReportingDBStoredProc("spGetWorkspaces",
                                                                                          new Dictionary <string, object>
                                {
                                    { "@SiteId", oWeb.Site.ID },
                                    { "@UserId", spWeb.CurrentUser.ID },
                                    { "@View", "AllItems" }
                                });
                                if (dtRPTWebData != null && dtRPTWebData.Rows.Count > 0)
                                {
                                    dtWorkspacecenterData =
                                        (from rptWebRow in dtRPTWebData.AsEnumerable()
                                         join frfRow in dtFRFData.AsEnumerable()
                                         on rptWebRow["WebId"] equals frfRow["WEB_ID"]
                                         into tempDelete
                                         where tempDelete.Count() > 0
                                         select rptWebRow).CopyToDataTable();
                                }
                            }
                            else
                            {
                                dtWorkspacecenterData = queryExecutor.ExecuteReportingDBStoredProc("spGetWorkspaces",
                                                                                                   new Dictionary <string, object>
                                {
                                    { "@SiteId", oWeb.Site.ID },
                                    { "@UserId", spWeb.CurrentUser.ID },
                                    { "@View", data }
                                });
                            }
                        }
                        catch
                        {
                        }

                        result.Add(new XElement("Grid"));
                        XElement grid = result.Element("Grid");
                        grid.Add(new XElement("Body"));
                        grid.Element("Body").Add(new XElement("B"));
                        XElement body = grid.Element("Body").Element("B");

                        if (dtWorkspacecenterData != null && dtWorkspacecenterData.Rows.Count > 0)
                        {
                            string    sqlGetAllWebs = string.Empty;
                            DataTable dtSPData      = new DataTable();
                            sqlGetAllWebs = "SELECT TimeCreated,LastMetadataChange,SiteId,Id FROM AllWebs";

                            using (SqlConnection sqlConnection = GetSpContentDbSqlConnection(spWeb))
                            {
                                using (var sqlCommand = new SqlCommand(sqlGetAllWebs, sqlConnection))
                                {
                                    SPSecurity.RunWithElevatedPrivileges(sqlConnection.Open);
                                    SqlDataAdapter da = new SqlDataAdapter(sqlCommand);
                                    da.Fill(dtSPData);
                                    sqlConnection.Close();
                                }
                            }

                            for (int i = 0; i < dtWorkspacecenterData.Rows.Count; i++)
                            {
                                if (dtWorkspacecenterData.Rows[i]["HasAccess"].Equals(1))
                                {
                                    var    j     = new XElement("I");
                                    string CDate = string.Empty;
                                    string UDate = string.Empty;
                                    var    dates = (from myRow in dtSPData.AsEnumerable()
                                                    where ((myRow.Field <Guid>("Id") == (Guid)dtWorkspacecenterData.Rows[i]["WebId"]) && (myRow.Field <Guid>("SiteId") == spWeb.Site.ID))
                                                    select new
                                    {
                                        CreatedDate = myRow.Field <DateTime>("TimeCreated"),
                                        ModifiedDate = myRow.Field <DateTime>("LastMetadataChange"),
                                    }).FirstOrDefault();
                                    CDate = dates.CreatedDate.ToShortDateString();
                                    UDate = dates.ModifiedDate.ToShortDateString();
                                    //string WebTitle = Convert.ToString(dtWorkspacecenterData.Rows[i]["WebTitle"]);
                                    //string WebTitle = "<div> <div style='float:left;'>" + Convert.ToString(dtWorkspacecenterData.Rows[i]["WebTitle"] + "</div><div style='float:right;'><ul style='margin: 0px; width: 20px;'><li class='workspacecentercontextmenu'><a data-itemid='20'data-listid= '70045944-8348-4D19-A846-1911DF213FFA' data-webid='" + oWeb.ID + "' data-siteid='" + oWeb.Site.ID + "'></a></li></ul></div> </div>");
                                    string WebTitle    = "<div> <div style='float:left;'><a href='" + Convert.ToString(dtWorkspacecenterData.Rows[i]["WebUrl"]) + "'>" + Convert.ToString(dtWorkspacecenterData.Rows[i]["WebTitle"]) + "</a></div><div style='float:right;'><ul style='margin: 0px; width: 20px;'><li class='workspacecentercontextmenu' id='" + dtWorkspacecenterData.Rows[i]["WebId"] + "'><a data-webid='" + dtWorkspacecenterData.Rows[i]["WebId"] + "' data-siteid='" + oWeb.Site.ID + "'></a></li></ul></div></div>";
                                    string Description = Convert.ToString(dtWorkspacecenterData.Rows[i]["WebDescription"]);
                                    string Members     = Convert.ToString(dtWorkspacecenterData.Rows[i]["Members"]);
                                    string Owner       = Convert.ToString(dtWorkspacecenterData.Rows[i]["SharePointAccountText"]);

                                    j.Add(new XAttribute("WorkSpace", WebTitle));
                                    j.Add(new XAttribute("Description", Description));
                                    j.Add(new XAttribute("Owner", Owner));
                                    j.Add(new XAttribute("CreateDate", CDate));
                                    j.Add(new XAttribute("ModifiedDate", UDate));
                                    j.Add(new XAttribute("Members", Members));

                                    body.Add(j);
                                }
                            }
                        }
                    }
                }
                return(result.ToString());
            }
            catch (APIException ex)
            {
                return(Response.Failure(ex.ExceptionNumber, string.Format("Error: {0}", ex.Message)));
            }
        }
Пример #36
0
        /// <summary>
        /// Returns Html with CID named references and updates email message attachments.
        /// </summary>
        /// <param name="html">Html to parse for images</param>
        /// <param name="emailMessage">Adds Attachments to email messages.</param>
        /// <returns></returns>
        /// <exception cref="ApplicationException"></exception>
        public static string GetHtmlWithEmbeddedImages(string html, EmailMessage emailMessage)
        {
            try
            {
                List <string> imgTags = HtmlHelper.GetImagesInHtml(html);
                if (imgTags == null || !imgTags.Any())
                {
                    return(html);
                }

                List <string> sources = new List <string>();
                foreach (var tag in imgTags)
                {
                    if (string.IsNullOrWhiteSpace(tag))
                    {
                        continue;
                    }
                    var imgSrc = HtmlHelper.GetSrcFromImage(tag);
                    if (string.IsNullOrWhiteSpace(imgSrc) || imgSrc.StartsWith("data:") || imgSrc.StartsWith("cid:"))
                    {
                        continue;
                    }
                    sources.Add(imgSrc);
                }

                sources.RemoveAll(x => string.IsNullOrWhiteSpace(x));

                if (emailMessage?.ImageLibraryUrls?.Any() == true)
                {
                    foreach (var additionalImageLibrary in emailMessage.ImageLibraryUrls)
                    {
                        using (SPSite site = new SPSite(additionalImageLibrary))
                        {
                            using (SPWeb web = site.OpenWeb(additionalImageLibrary))
                            {
                                SPList docs = web.GetList(additionalImageLibrary);
                                if (docs?.Items == null || docs.Items.Count == 0)
                                {
                                    return(html);
                                }
                                foreach (SPListItem item in docs.Items)
                                {
                                    if (item.File == null)
                                    {
                                        continue;
                                    }
                                    SPFile file               = item.File;
                                    var    urlEncodedName     = Uri.EscapeUriString(file.Name).Replace("'", "%27");
                                    var    contentIdCheckName = file.Name.Replace(" ", "%20").Replace("'", "%27");
                                    if (file != null &&
                                        emailMessage.LinkedResources.All(x => contentIdCheckName != x.ContentId) &&
                                        sources.Any(x => Path.GetFileName(x)
                                                    .Equals(file.Name,
                                                            StringComparison.InvariantCultureIgnoreCase) ||
                                                    Path.GetFileName(x)
                                                    .Equals(urlEncodedName,
                                                            StringComparison.InvariantCultureIgnoreCase)))
                                    {
                                        byte[]       filecontents = file.OpenBinary();
                                        MemoryStream ms           = new MemoryStream(filecontents);
                                        string       contentType  = MediaTypeNames.Text.Plain;
                                        if (file.Name.EndsWith("jpg") || file.Name.EndsWith("jpeg"))
                                        {
                                            contentType = MediaTypeNames.Image.Jpeg;
                                        }
                                        else if (file.Name.EndsWith("png"))
                                        {
                                            contentType = "image/png";
                                        }
                                        else if (file.Name.EndsWith("gif"))
                                        {
                                            contentType = MediaTypeNames.Image.Gif;
                                        }
                                        else if (file.Name.EndsWith("pdf"))
                                        {
                                            contentType = MediaTypeNames.Application.Pdf;
                                        }
                                        var imgRes =
                                            new LinkedResource(ms,
                                                               contentType); //Using Linked resource so images do not display as attachments.
                                        imgRes.ContentId = file.Name;
                                        imgRes.ContentId = imgRes.ContentId.Replace(" ", "%20").Replace("'", "%27");
                                        emailMessage.LinkedResources
                                        .Add(imgRes);     //Add Linked Item (to be used as CID reference)
                                    }
                                }
                            }
                        }
                    }
                }

                foreach (var linkedRes in emailMessage.LinkedResources)
                {
                    List <string> modifiedSources = new List <string>();
                    foreach (var source in sources.Where(x => Path.GetFileName(x).Equals(linkedRes.ContentId, StringComparison.InvariantCultureIgnoreCase) ||
                                                         Uri.EscapeUriString(Path.GetFileName(x)).Replace("'", "%27").Equals(linkedRes.ContentId, StringComparison.InvariantCultureIgnoreCase) ||
                                                         Path.GetFileName(x).Equals(Uri.EscapeUriString(linkedRes.ContentId).Replace("'", "%27"), StringComparison.InvariantCultureIgnoreCase)))
                    {
                        if (modifiedSources.Any(x => x == source))
                        {
                            continue;                                              //don't do the same image more than once
                        }
                        html = html.Replace(source, "cid:" + linkedRes.ContentId); //Add CID Reference
                        modifiedSources.Add(source);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException(
                          $"Exception occured in ArkUtility.SPMail processing. Specific error: {ex.Message}. Stack: {ex.StackTrace}", ex);
            }
            return(html);
        }
Пример #37
0
        /// <summary>
        /// Render this control to the output parameter specified.
        /// </summary>
        /// <param name="output"> The HTML writer to write out to </param>
        protected override void Render(HtmlTextWriter output)
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.RootWeb)
                {
                    try
                    {
                        SPListItemCollection collListItems;

                        int           LCID = HttpContext.Current.Request.Url.Segments.Contains("fra/") ? 1036 : 1033;// System.Threading.Thread.CurrentThread.CurrentUICulture.LCID;
                        StringBuilder sb   = new StringBuilder();
                        SPList        list = web.Lists["LACRightHeaderLink"];

                        SPQuery oQuery = new SPQuery();
                        if (LCID == 1036)
                        {
                            oQuery.Query = "<Where><IsNotNull><FieldRef Name='ID'/></IsNotNull></Where>" +
                                           "<OrderBy><FieldRef Name='EnglishOrder' /></OrderBy>";
                        }

                        else
                        {
                            oQuery.Query = "<Where><IsNotNull><FieldRef Name='ID'/></IsNotNull></Where>" +
                                           "<OrderBy><FieldRef Name='FrenchOrder' /></OrderBy>";
                        }

                        collListItems = list.GetItems(oQuery);

                        if (list.Items.Count > 0)
                        {
                            int i = 1;
                            sb.Append("<div class=\"toprightlinks\">");
                            foreach (SPListItem item in collListItems)
                            {
                                if (LCID == 1036)
                                {
                                    sb.Append("&nbsp;&nbsp;<a href=\"" + item["French Url"] + "\">" + item["French Link Text"] + "</a>");
                                }
                                else
                                {
                                    sb.Append("&nbsp;&nbsp;<a href=\"" + item["English Url"] + "\">" + item["English Link Text"] + "</a>");
                                }
                                if (i != list.Items.Count)
                                {
                                    sb.Append("&nbsp;&nbsp|");
                                }
                                i++;
                            }
                            sb.Append("</div>");
                        }

                        output.Write(sb);
                    }
                    catch (Exception ex)
                    {
                        output.Write("oTech.Lac.Intranet.WebControls: HomeLink exception message: " + ex.ToString());
                    }
                }
            }
        }
Пример #38
0
        private void UpdateHitCount(SPWeb currentweb, HttpContext ctx)
        {
            var cDate       = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now);
            var sessionDate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now.AddMinutes(-15));
            int diff        = DateTime.Now.DayOfWeek - DayOfWeek.Monday;

            if (diff < 0)
            {
                diff += 7;
            }
            var startWeekDate    = DateTime.Now.AddDays(-1 * diff).Date;
            var dateToDelete     = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now.AddHours(-1));
            var srartDate        = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now.AddDays(-1 * diff));
            var endDate          = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now.AddDays(7 - diff));
            var firstOfThisMonth = SPUtility.CreateISO8601DateTimeFromSystemDateTime(new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1));
            var lastOfThisMonth  = SPUtility.CreateISO8601DateTimeFromSystemDateTime(new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1));
            var cLoginName       = "Khách (không đăng nhập)";
            var cURL             = ctx.Request.Url.AbsoluteUri.ToString();

            if (currentweb.CurrentUser == null || string.IsNullOrEmpty(currentweb.CurrentUser.LoginName))
            {
                cLoginName = "Khách (không đăng nhập)";
            }
            else
            {
                cLoginName = currentweb.CurrentUser.LoginName;
            }
            var cIP       = ctx.Request.UserHostAddress;
            var cBrowser  = ctx.Request.Browser.Browser;
            var camlQuery = "<Where><And><Eq>" +
                            "<FieldRef Name='" + FieldsName.StatisticsList.InternalName.UserUrl + "' />" +
                            "<Value Type='Text'>" + cURL + "</Value></Eq>" +
                            "<And><Eq><FieldRef Name='" + FieldsName.StatisticsList.InternalName.Title + "' />" +
                            "<Value Type='Text'>" + cLoginName + "</Value></Eq>" +
                            "<And><Geq><FieldRef Name='" + Constants.Created + "' /><Value Type='DateTime' IncludeTimeValue='TRUE'>" + sessionDate + "</Value></Geq>" +
                            "<And><Eq><FieldRef Name='" + FieldsName.StatisticsList.InternalName.UserBrowser + "' /><Value Type='Text'>" + cBrowser +
                            "</Value></Eq><Eq><FieldRef Name='" + FieldsName.StatisticsList.InternalName.UserIP + "' /><Value Type='Text'>" + cIP +
                            "</Value></Eq>" +
                            "</And></And></And></And></Where>";

            var camlQueryNow = "<Where>" +
                               "<Geq><FieldRef Name='" + Constants.Created + "' /><Value Type='DateTime' IncludeTimeValue='TRUE'>" + sessionDate + "</Value></Geq>" +
                               "</Where>";

            var camlQueryDay = "<Where>" +
                               "<Eq><FieldRef Name='" + Constants.Created + "' /><Value Type='DateTime' IncludeTimeValue='FALSE'><Today /></Value></Eq>" +
                               "</Where>";

            var camlQueryYesterday = "<Where>" +
                                     "<Eq><FieldRef Name='" + Constants.Created + "' /><Value Type='DateTime' IncludeTimeValue='FALSE'><Today Offset='1' /></Value></Eq>" +
                                     "</Where>";

            var camlQueryWeek = "<Where><And><Geq>" +
                                "<FieldRef Name='" + Constants.Created + "' /><Value Type='DateTime' IncludeTimeValue='FALSE'><Today Offset='" + diff + "'></Today></Value></Geq>" +
                                "<Leq><FieldRef Name='" + Constants.Created + "' /><Value Type='DateTime' IncludeTimeValue='FALSE'><Today Offset='" + (diff - 7) + "'></Today></Value></Leq>" +
                                "</And></Where>";

            var camlQueryMonth = "<Where><And><Geq>" +
                                 "<FieldRef Name='" + Constants.Created + "' /><Value Type='DateTime' IncludeTimeValue='FALSE'>" + firstOfThisMonth + "</Value></Geq>" +
                                 "<Leq><FieldRef Name='" + Constants.Created + "' /><Value Type='DateTime' IncludeTimeValue='FALSE'>" + lastOfThisMonth + "</Value></Leq>" +
                                 "</And></Where>";

            var camlQueryLastMonth = "<Where><Lt>" +
                                     "<FieldRef Name='" + Constants.Created + "' /><Value Type='DateTime' IncludeTimeValue='FALSE'>" + firstOfThisMonth + "</Value></Lt></Where>";
            var camlQueryToDelete = "<Where>" +
                                    "<Lt><FieldRef Name='" + Constants.Created + "' /><Value Type='DateTime' IncludeTimeValue='TRUE'>" + dateToDelete + "</Value></Lt>" +
                                    "</Where>";

            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                using (var site = new SPSite(currentweb.Site.ID))
                {
                    using (var web = site.OpenWeb(currentweb.ID))
                    {
                        try
                        {
                            SPQuery spQuery = new SPQuery
                            {
                                Query    = camlQuery,
                                RowLimit = 1,
                                //QueryThrottleMode = SPQueryThrottleOption.Override
                            };
                            SPQuery spQueryNow = new SPQuery
                            {
                                Query = camlQueryNow,
                                //QueryThrottleMode = SPQueryThrottleOption.Override
                            };
                            //SPQuery spQueryDay = new SPQuery
                            //{
                            //    Query = camlQueryDay,
                            //    //QueryThrottleMode = SPQueryThrottleOption.Override
                            //};
                            //SPQuery spQueryYesterday = new SPQuery
                            //{
                            //    Query = camlQueryYesterday,
                            //    //QueryThrottleMode = SPQueryThrottleOption.Override
                            //};
                            //SPQuery spQueryWeek = new SPQuery
                            //{
                            //    Query = camlQueryWeek,
                            //    //QueryThrottleMode = SPQueryThrottleOption.Override
                            //};
                            //SPQuery spQueryMonth = new SPQuery
                            //{
                            //    Query = camlQueryMonth,
                            //    //QueryThrottleMode = SPQueryThrottleOption.Override
                            //};
                            //SPQuery spQueryLastMonth = new SPQuery
                            //{
                            //    Query = camlQueryLastMonth,
                            //    //QueryThrottleMode = SPQueryThrottleOption.Override
                            //};
                            SPList list = Utilities.GetCustomListByUrl(web, ListsName.InternalName.StatisticsList);

                            SPList listConfig = Utilities.GetCustomListByUrl(web, "AllConfigVP");

                            var oldNumber            = 0;
                            SPListItem configItem    = null;
                            var dayNumber            = 0;
                            SPListItem dayItem       = null;
                            var yesterdayNumber      = 0;
                            SPListItem yesterdayItem = null;
                            var weekNumber           = 0;
                            SPListItem weekItem      = null;
                            var monthNumber          = 0;
                            SPListItem monthItem     = null;
                            if (listConfig != null)
                            {
                                SPQuery spQueryConfig = new SPQuery
                                {
                                    Query = "<Where>" +
                                            "<Eq><FieldRef Name='Title' /><Value Type='Text'>OldNumber</Value></Eq>" +
                                            "</Where>",
                                    RowLimit = 1
                                };
                                var configItems = listConfig.GetItems(spQueryConfig);
                                if (configItems != null && configItems.Count > 0)
                                {
                                    try
                                    {
                                        oldNumber  = Convert.ToInt32(configItems[0]["Value"]);
                                        configItem = configItems[0];
                                    }
                                    catch (SPException) { }
                                    catch (Exception) {}
                                }

                                yesterdayItem = GetValue(web, listConfig, "YesterdayNumBer", ref yesterdayNumber);
                                dayItem       = GetValue(web, listConfig, "DayNumBer", ref dayNumber);
                                weekItem      = GetValue(web, listConfig, "WeekNumBer", ref weekNumber);
                                monthItem     = GetValue(web, listConfig, "MonthNumBer", ref monthNumber);
                            }

                            HitCountNumber          = oldNumber;
                            tdAll.InnerText         = oldNumber.ToString();
                            DayHitCountNumber       = dayNumber;
                            tdToday.InnerText       = DayHitCountNumber.ToString();
                            YesterdayHitCountNumber = yesterdayNumber;
                            tdYesterday.InnerText   = YesterdayHitCountNumber.ToString();
                            WeekHitCountNumber      = weekNumber;
                            tdThisWeek.InnerText    = WeekHitCountNumber.ToString();
                            MonthHitCountNumber     = monthNumber;
                            tdThisMonth.InnerText   = MonthHitCountNumber.ToString();
                            if (list != null)
                            {
                                SPListItemCollection itemsNow = list.GetItems(spQueryNow);
                                if (itemsNow != null && itemsNow.Count > 0)
                                {
                                    CurrentHitCountNumber = itemsNow.Count;
                                    lblCurrent.Text       = "<span id='spCurrent'>" + CurrentHitCountNumber.ToString() + "</span>";
                                }

                                //SPListItemCollection itemsDay = list.GetItems(spQueryDay);
                                //if (itemsDay != null && itemsDay.Count > 0)
                                //{
                                //    DayHitCountNumber = itemsDay.Count;
                                //    tdToday.InnerText = DayHitCountNumber.ToString();
                                //}

                                //SPListItemCollection itemsYesterday = list.GetItems(spQueryYesterday);
                                //if (itemsYesterday != null && itemsYesterday.Count > 0)
                                //{
                                //    YesterdayHitCountNumber = itemsYesterday.Count;
                                //    tdYesterday.InnerText = YesterdayHitCountNumber.ToString();
                                //}

                                //SPListItemCollection itemsWeek = list.GetItems(spQueryWeek);
                                //if (itemsWeek != null && itemsWeek.Count > 0)
                                //{
                                //    WeekHitCountNumber = itemsWeek.Count;
                                //    tdThisWeek.InnerText = WeekHitCountNumber.ToString();
                                //}
                                //SPListItemCollection itemsMonth = list.GetItems(spQueryMonth);
                                //if (itemsMonth != null && itemsMonth.Count > 0)
                                //{
                                //    MonthHitCountNumber = itemsMonth.Count;
                                //    tdThisMonth.InnerText = MonthHitCountNumber.ToString();
                                //}
                                SPListItemCollection itemsToDelete = list.GetItems(new SPQuery {
                                    Query = camlQueryToDelete
                                });

                                if (itemsToDelete != null && itemsToDelete.Count > 0)
                                {
                                    StringBuilder sbDelete = new StringBuilder();
                                    sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");

                                    string command = "<Method>" +
                                                     "<SetList Scope=\"Request\">" + list.ID + "</SetList>" +
                                                     "<SetVar Name=\"ID\">{0}</SetVar>" +
                                                     "<SetVar Name=\"Cmd\">Delete</SetVar>" +
                                                     "</Method>";

                                    foreach (SPListItem item in itemsToDelete)
                                    {
                                        sbDelete.Append(string.Format(command, item.ID.ToString()));
                                    }
                                    sbDelete.Append("</Batch>");

                                    web.AllowUnsafeUpdates = true;
                                    //Run the Batch command
                                    web.ProcessBatchData(sbDelete.ToString());
                                }
                                if (list.ItemCount <= 4900)
                                {
                                    SPListItemCollection items = list.GetItems(spQuery);
                                    if (items == null || items.Count <= 0)
                                    {
                                        HitCountNumber++;
                                        //dvHitCount.InnerText = HitCountNumber.ToString();
                                        var item = list.AddItem();
                                        item[FieldsName.StatisticsList.InternalName.Title]       = cLoginName;
                                        item[FieldsName.StatisticsList.InternalName.UserUrl]     = cURL;
                                        item[FieldsName.StatisticsList.InternalName.UserIP]      = cIP;
                                        item[FieldsName.StatisticsList.InternalName.UserBrowser] = cBrowser;
                                        web.AllowUnsafeUpdates = true;
                                        item.Update();

                                        configItem["Value"]    = oldNumber + 1;
                                        web.AllowUnsafeUpdates = true;
                                        configItem.SystemUpdate(false);

                                        var dayModified = Convert.ToDateTime(Convert.ToString(dayItem["Modified"]));
                                        if (dayModified.Date < DateTime.Now.Date)
                                        {
                                            dayItem["Value"]       = 1;
                                            web.AllowUnsafeUpdates = true;
                                            dayItem.Update();
                                        }
                                        else
                                        {
                                            dayItem["Value"]       = dayNumber + 1;
                                            web.AllowUnsafeUpdates = true;
                                            dayItem.Update();
                                        }

                                        var weekModified = Convert.ToDateTime(Convert.ToString(weekItem["Modified"]));
                                        if (weekModified.Date < startWeekDate)
                                        {
                                            weekItem["Value"]      = 1;
                                            web.AllowUnsafeUpdates = true;
                                            weekItem.Update();
                                        }
                                        else
                                        {
                                            weekItem["Value"]      = weekNumber + 1;
                                            web.AllowUnsafeUpdates = true;
                                            weekItem.Update();
                                        }

                                        var monthModified = Convert.ToDateTime(Convert.ToString(monthItem["Modified"]));
                                        if (monthModified.Date < (new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1)).Date)
                                        {
                                            monthItem["Value"]     = 1;
                                            web.AllowUnsafeUpdates = true;
                                            monthItem.Update();
                                        }
                                        else
                                        {
                                            monthItem["Value"]     = monthNumber + 1;
                                            web.AllowUnsafeUpdates = true;
                                            monthItem.Update();
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Utilities.LogToULS(ex);
                        }
                    }
                }
            });
        }
Пример #39
0
        private void CreateWorkItem(SPWebEventProperties properties)
        {
            Guid   siteId = properties.SiteId;
            Guid   webId  = properties.WebId;
            string url    = properties.ServerRelativeUrl;

            if (url.StartsWith("/"))
            {
                url = url.Remove(0, 1);
            }

            bool disabled = false;
            WebSiteControllerPrincipalType principalType = WebSiteControllerPrincipalType.None;
            bool   appliesToSSL = true;
            int    sequence     = 1;
            String pricipal     = string.Empty;

            StringBuilder builder = new StringBuilder();

            builder.Append(url + ";");
            builder.Append(disabled.ToString() + ";");
            builder.Append(appliesToSSL.ToString() + ";");
            builder.Append(sequence.ToString() + ";");
            builder.Append(principalType.ToString() + ";");
            builder.Append(pricipal + ";");
            builder.Append("#");

            builder.Append(String.Format("{0}:{1};", "OriginalUrl", url + "/default.aspx"));

            string full = builder.ToString();

            Guid itemGuid = new Guid("386577D9-0777-4AD3-A90A-C240D8B0A49E");
            int  item     = -1;

            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                using (SPSite site = new SPSite(siteId))
                {
                    site.AddWorkItem(
                        Guid.NewGuid(),
                        DateTime.Now.ToUniversalTime(),
                        WebSiteControllerRuleWorkItem.WorkItemTypeId,
                        webId,
                        siteId,
                        item,
                        true,
                        itemGuid,
                        Guid.Empty,
                        site.SystemAccount.ID,
                        null,
                        builder.ToString(),
                        Guid.Empty
                        );
                }
            });

            SPJobDefinitionCollection jobs = properties.Web.Site.WebApplication.JobDefinitions;
            int _seconds = 0;

            foreach (SPJobDefinition job in jobs)
            {
                if (job.Name == WebSiteControllerRuleWorkItem.WorkItemJobDisplayName)
                {
                    DateTime next = job.Schedule.NextOccurrence(job.LastRunTime);
                    _seconds = next.Millisecond;
                    break;
                }
            }

            //System.Threading.Thread.Sleep(_seconds);
        }
        protected virtual bool SetSPTrustInCurrentContext(Uri context)
        {
            var webApp = SPWebApplication.Lookup(context);

            if (webApp == null)
            {
                return(false);
            }

            SPSite site = null;

            try
            {
                site = new SPSite(context.AbsoluteUri);
            }
            catch (Exception)
            {
                // The root site doesn't exist
                this.associatedSPTrustedLoginProvider = Utils.GetSPTrustAssociatedWithCP(ProviderInternalName);

                if (this.associatedSPTrustedLoginProvider != null &&
                    this.associatedSPTrustedLoginProvider.IdentityClaimTypeInformation != null)
                {
                    this.identifierClaimType = this.associatedSPTrustedLoginProvider.IdentityClaimTypeInformation.InputClaimType;
                }

                return(this.associatedSPTrustedLoginProvider != null);
            }

            if (site == null)
            {
                return(false);
            }

            SPUrlZone     currentZone = site.Zone;
            SPIisSettings iisSettings = webApp.GetIisSettingsWithFallback(currentZone);

            site.Dispose();

            if (!iisSettings.UseTrustedClaimsAuthenticationProvider)
            {
                return(false);
            }

            // Get the list of authentication providers associated with the zone
            foreach (SPAuthenticationProvider prov in iisSettings.ClaimsAuthenticationProviders)
            {
                if (prov.GetType() == typeof(Microsoft.SharePoint.Administration.SPTrustedAuthenticationProvider))
                {
                    // Check if the current SPTrustedAuthenticationProvider is associated with the claim provider
                    if (prov.ClaimProviderName == ProviderInternalName)
                    {
                        this.associatedSPTrustedLoginProvider = Utils.GetSPTrustAssociatedWithCP(ProviderInternalName);

                        if (this.associatedSPTrustedLoginProvider != null &&
                            this.associatedSPTrustedLoginProvider.IdentityClaimTypeInformation != null)
                        {
                            this.identifierClaimType = this.associatedSPTrustedLoginProvider.IdentityClaimTypeInformation.InputClaimType;
                        }

                        return(this.associatedSPTrustedLoginProvider != null);
                    }
                }
            }

            return(false);
        }
        protected string GetCurrentSearchConfiguration(SPSite site)
        {
            var owner = new SearchObjectOwner(SearchObjectLevel.SPSite, site.RootWeb);

            return(new SearchConfigurationPortability(site).ExportSearchConfiguration(owner));
        }
Пример #42
0
        private void InsertRowIntoPublisherCheck(Guid projectGuid)
        {
            // prepare command string
            string insertString = @"INSERT INTO [PUBLISHERCHECK] 
                ([projectguid]
                           ,[webguid]                           
                           ,[checkbit]
                           ,[weburl])
                     VALUES
                           (@projectguid,
                            @webguid,  
                            @checkbit,                        
                            @weburl)";

            SPSecurity.RunWithElevatedPrivileges(
                delegate()
            {
                // Get Site ID
                SPSite site = null;
                Guid siteID;
                try
                {
                    site   = new SPSite(ViewState["siteURL"].ToString());
                    siteID = site.ID;
                }
                finally
                {
                    if (site != null)
                    {
                        site.Close();
                    }
                }

                // Instantiate the connection
                SqlConnection conn = new SqlConnection(EPMLiveCore.CoreFunctions.getConnectionString(SPContext.Current.Site.WebApplication.Id));

                try
                {
                    // Open the connection
                    conn.Open();

                    // Instantiate a new command with a query and connection
                    SqlCommand cmd = new SqlCommand(insertString, conn);

                    // Add Parameters
                    cmd.Parameters.Add("@projectguid", SqlDbType.UniqueIdentifier, 16);
                    cmd.Parameters.Add("@webguid", SqlDbType.UniqueIdentifier, 16);
                    cmd.Parameters.Add("@weburl", SqlDbType.VarChar, 255);
                    cmd.Parameters.Add("@checkbit", SqlDbType.Bit, 1);

                    // Set Parameter values
                    cmd.Parameters["@projectguid"].Value = projectGuid;
                    cmd.Parameters["@webguid"].Value     = siteID;
                    cmd.Parameters["@weburl"].Value      = SPContext.Current.Web.Url;
                    cmd.Parameters["@checkbit"].Value    = false;

                    // Call ExecuteNonQuery to send command
                    cmd.ExecuteNonQuery();
                }
                finally
                {
                    // Close the connection
                    if (conn != null)
                    {
                        conn.Close();
                    }
                }
            });
        }
Пример #43
0
        static void Main(string[] args)
        {
            if (args?.Length != 2)
            {
                throw new ArgumentException(
                          $"Usage: {typeof (Program).Namespace}.exe c:\\somewhere\\MasterPageFullPath.master http://sharepoiont/site/url");
            }

            //if (!File.Exists(args[0]))
            //{
            //    throw new FileNotFoundException("Master Page not found", args[0]);
            //}

            List <string> fileNames = new List <string>();

            try
            {
                var dirPath = Path.GetDirectoryName(args[0]);
                if (!Directory.Exists(dirPath))
                {
                    throw new DirectoryNotFoundException(dirPath);
                }

                var filter     = Path.GetFileName(args[0]);
                var filesInDir = Directory.GetFiles(dirPath, filter);
                if (filesInDir?.Length == 0)
                {
                    throw new FileNotFoundException($"Master Page not found: {args[0]}");
                }
                fileNames.AddRange(filesInDir);
            }
            catch (Exception)
            {
                throw;
            }

            if (fileNames?.Count > 0)
            {
                try
                {
                    string siteUrl = args[1];
                    using (SPSite s = new SPSite(siteUrl))
                    {
                        using (SPWeb w = s.OpenWeb(s.RootWeb.ID))
                        {
                            SPList mpCatalog = w.GetCatalog(SPListTemplateType.MasterPageCatalog);

                            SPFolder fld = mpCatalog.RootFolder;

                            Uri uri = new Uri(siteUrl);
                            if (uri.AbsolutePath != w.ServerRelativeUrl)
                            {
                                fld = w.GetFolder(uri.AbsolutePath);
                            }

                            if (fld.Exists)
                            {
                                foreach (var fileName in fileNames)
                                {
                                    string fname = Path.GetFileName(fileName);

                                    byte[] allBytes = File.ReadAllBytes(fileName);
                                    var    spPath   = $"{fld.ServerRelativeUrl}/{fname}";
                                    Console.WriteLine($"Uploading {fname} into {spPath}");
                                    SPFile spFile = w.GetFile(spPath);
                                    if (!spFile.Exists)
                                    {
                                        throw new SPException("Upload file manually first time");
                                    }
                                    spFile.CheckOut();
                                    spFile.SaveBinary(allBytes);
                                    spFile.CheckIn("Automatically updated", SPCheckinType.MajorCheckIn);
                                    spFile.Publish("Automatically published");
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
Пример #44
0
        private void SetupDisplayTemplateControls(List <MultipleImageUploadFieldValue> selectedValues)
        {
            string strLibraryName    = this.ParentField.LibraryName;
            string strUniqueFolderID = this.ParentField.UniqueFolderGuid;
            bool   editMode          = (this.ControlMode == SPControlMode.Edit);
            bool   newMode           = (this.ControlMode == SPControlMode.New);

            try
            {
                using (SPSite SiteCollection = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb site = SiteCollection.OpenWeb())
                    {
                        SPList   targetList = site.Lists.TryGetList(strLibraryName);
                        SPFolder RootFolder = targetList.RootFolder;
                        SPFolder subfolder  = null;
                        try
                        {
                            subfolder = RootFolder.SubFolders[strUniqueFolderID];
                            if (subfolder != null)
                            {
                                SPFileCollection files = subfolder.Files;
                                int      idIndex       = 1;
                                TableRow valueRow      = new TableRow();
                                TableImage.Rows.Add(valueRow);
                                int cellcount = 1;
                                foreach (SPFile file in files)
                                {
                                    var formattedValue = file.ServerRelativeUrl.ToLower().ToString();
                                    var selectedValue  = selectedValues.FirstOrDefault(val => val.URL.ToLower() == formattedValue) ?? new MultipleImageUploadFieldValue();

                                    if (!string.IsNullOrEmpty(selectedValue.URL))
                                    {
                                        if (cellcount == 4)
                                        {
                                            cellcount = 1;
                                            valueRow  = new TableRow();
                                            TableImage.Rows.Add(valueRow);
                                        }
                                        if (cellcount <= 3)
                                        {
                                            TableCell imageCell = new TableCell();
                                            imageCell.Width           = new Unit(15, UnitType.Percentage);
                                            imageCell.VerticalAlign   = VerticalAlign.Top;
                                            imageCell.HorizontalAlign = HorizontalAlign.Left;
                                            valueRow.Cells.Add(imageCell);

                                            // Creating the people editor and populating with the selected field
                                            Image image = new Image();
                                            image.ID       = "img" + file.UniqueId;
                                            image.ImageUrl = file.ServerRelativeUrl;
                                            image.Width    = new Unit(100, UnitType.Pixel);
                                            image.Height   = new Unit(100, UnitType.Pixel);
                                            imageCell.Controls.Add(image);

                                            HtmlGenericControl divImageName = new HtmlGenericControl();
                                            divImageName.InnerText = file.Name.ToString();
                                            imageCell.Controls.Add(divImageName);

                                            tableControlsList.Add(formattedValue, new ControlSet
                                            {
                                                Image = image,
                                                div   = divImageName
                                            });
                                            cellcount++;
                                        }
                                        idIndex++;
                                    }
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #45
0
 private void MigrateOneDocumentToWorkBox(WBMigrationMapping mapping, SPSite controlSite, SPWeb controlWeb, SPList controlList, SPView controlView, SPListItem migrationItem)
 {
     throw new NotImplementedException();
 }
Пример #46
0
        public static void SaveToSP(string strEmpDisplayName, string Active_Set_Goals_Year, DataTable tblObjectives, string login_name_to_convert_to_SPUser)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPSite oSite             = new SPSite(SPContext.Current.Web.Url);
                SPWeb spWeb              = oSite.OpenWeb();
                spWeb.AllowUnsafeUpdates = true;
                SPList spList            = spWeb.GetList(SPUrlUtility.CombineUrl(spWeb.ServerRelativeUrl, "lists/" + "Objectives")); //SPList oList = oWeb.GetList("/Lists/Objectives");

                #region Remove any previous objectives of same Emp and same year

                SPQuery qry = new SPQuery();
                qry.Query   =
                    @"   <Where>
                                          <And>
                                             <Eq>
                                                <FieldRef Name='Emp' />
                                                <Value Type='User'>" + strEmpDisplayName + @"</Value>
                                             </Eq>
                                             <Eq>
                                                <FieldRef Name='ObjYear' />
                                                <Value Type='Text'>" + Active_Set_Goals_Year + @"</Value>
                                             </Eq>
                                          </And>
                                       </Where>";
                qry.ViewFieldsOnly             = true;
                qry.ViewFields                 = @"<FieldRef Name='ID' /><FieldRef Name='ObjName' /><FieldRef Name='Status' /><FieldRef Name='Emp' />
                                                       <FieldRef Name='ObjQ' /><FieldRef Name='ObjYear' /><FieldRef Name='ObjType' /><FieldRef Name='ObjWeight' />";
                SPListItemCollection listItems = spList.GetItems(qry);

                foreach (SPListItem item in listItems)
                {
                    spList.GetItemById(item.ID).Delete();
                }

                #endregion Remove any previous objectives of same Emp and same year

                #region Add the new (or updated) objectives

                if (tblObjectives != null)
                {
                    foreach (DataRow row in tblObjectives.Rows)
                    {
                        SPListItem oListItem       = spList.AddItem();
                        oListItem["ObjName"]       = row["ObjName"].ToString();
                        oListItem["Status"]        = WF_States.Objectives_set_by_Emp.ToString();
                        oListItem["Emp"]           = SPContext.Current.Web.EnsureUser(login_name_to_convert_to_SPUser);
                        oListItem["ObjWeight"]     = row["ObjWeight"].ToString();
                        oListItem["ObjQ"]          = row["ObjQ"].ToString();
                        oListItem["ObjYear"]       = Active_Set_Goals_Year;
                        oListItem["StrDirID"]      = int.Parse(row["StrDirID"].ToString());
                        oListItem["PrimaryGoalID"] = int.Parse(row["PrimaryGoalID"].ToString());
                        oListItem["EmpHierLvl"]    = row["EmpHierLvl"].ToString();

                        oListItem.Update();
                    }
                }
                else
                {
                }

                #endregion Add the new (or updated) objectives

                spWeb.AllowUnsafeUpdates = false;
            });
        }
Пример #47
0
        static void Main(string[] args)
        {
            string       site;
            StreamWriter SW;

            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Enter the Web Application URL:");
                    site = Console.ReadLine();
                }
                else
                {
                    site = args[0];
                }

                SPSite           tmpRoot     = new SPSite(site);
                SPSiteCollection tmpRootColl = tmpRoot.WebApplication.Sites;

                //objects for the CSV file generation
                SW = File.AppendText("c:\\VersioningReport.csv");

                //Write the CSV Header
                SW.WriteLine("Site Name, Library, File Name, File URL, Last Modified, No. of Versions, Latest Version Size -KB,Total Versions Size - MB");

                //Enumerate through each site collection
                foreach (SPSite tmpSite in tmpRootColl)
                {
                    //Enumerate through each sub-site
                    foreach (SPWeb tmpWeb in tmpSite.AllWebs)
                    {
                        //Enumerate through each List
                        foreach (SPList tmpList in tmpWeb.Lists)
                        {
                            //Get only Document Libraries & Exclude specific libraries
                            if (tmpList.BaseType == SPBaseType.DocumentLibrary & tmpList.Title != "Workflows" & tmpList.Title != "Master Page Gallery" & tmpList.Title != "Style Library" & tmpList.Title != "Pages")
                            {
                                foreach (SPListItem tmpSPListItem in tmpList.Items)
                                {
                                    if (tmpSPListItem.Versions.Count > 5)
                                    {
                                        SPListItemVersionCollection tmpVerisionCollection = tmpSPListItem.Versions;

                                        //Get the versioning details
                                        foreach (SPListItemVersion tmpVersion in tmpVerisionCollection)
                                        {
                                            int    versionID       = tmpVersion.VersionId;
                                            string strVersionLabel = tmpVersion.VersionLabel;
                                        }

                                        //Get the versioning Size details
                                        double versionSize = 0;
                                        SPFile tmpFile     = tmpWeb.GetFile(tmpWeb.Url + "/" + tmpSPListItem.File.Url);

                                        foreach (SPFileVersion tmpSPFileVersion in tmpFile.Versions)
                                        {
                                            versionSize = versionSize + tmpSPFileVersion.Size;
                                        }
                                        //Convert to MB
                                        versionSize = Math.Round(((versionSize / 1024) / 1024), 2);

                                        string siteName;
                                        if (tmpWeb.IsRootWeb)
                                        {
                                            siteName = tmpWeb.Title + " - Root";
                                        }
                                        else
                                        {
                                            siteName = tmpSite.RootWeb.Title + " - " + tmpWeb.Title;
                                        }

                                        //Log the data to a CSV file where versioning size > 0MB!
                                        if (versionSize > 0)
                                        {
                                            SW.WriteLine(siteName + "," + tmpList.Title + "," + tmpSPListItem.Name + "," + tmpWeb.Url + "/" + tmpSPListItem.Url + "," + tmpSPListItem["Modified"].ToString() + "," + tmpSPListItem.Versions.Count + "," + (tmpSPListItem.File.Length / 1024) + "," + versionSize);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                //Close the CSV file object
                SW.Close();

                //Dispose of the Root Site Object
                tmpRoot.Dispose();

                //Just to pause
                Console.WriteLine(@"Versioning Report Generated Successfull at c:\VersioningReport.csv. Press ""Enter"" key to Exit");
                Console.ReadLine();
            }

            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("Get Versioning Report", ex.Message);
            }
        }
Пример #48
0
        private void MigrateOneDocumentToLibrary(
            WBMigrationMapping mapping,
            SPSite sourceSite,
            SPWeb sourceWeb,
            SPDocumentLibrary sourceLibrary,
            SPSite destinationSite,
            SPWeb destinationWeb,
            SPFolder destinationRootFolder,
            SPSite controlSite,
            SPWeb controlWeb,
            SPList controlList,
            SPView controlView,
            SPListItem migrationItem)
        {
            WBFarm farm = WBFarm.Local;

            //foreach (SPField field in migrationItem.Fields)
            //{
            //    WBLogging.Migration.Verbose("Field InternalName: " + field.InternalName + "  Field Title: " + field.Title +  " item[field.Title] : " + migrationItem[field.Title]);
            //}

            String sourceFilePath = migrationItem.WBxGetAsString(WBColumn.SourceFilePath);
            String mappingPath    = WBUtils.NormalisePath(migrationItem.WBxGetAsString(WBColumn.MappingPath));

            WBLogging.Migration.Verbose("Trying to migrate file      : " + sourceFilePath);
            WBLogging.Migration.Verbose("Migrating with mapping path : " + mappingPath);

            WBMappedPath mappedPath = mapping[mappingPath];

            SPListItem controlItem = migrationItem;
            SPListItem mappingItem = null;
            SPListItem subjectItem = null;

            String documentumSourceID = "";

            if (MigrationSourceSystem == MIGRATION_SOURCE__DOCUMENTUM_WEB_DOCUMENTS)
            {
                documentumSourceID = controlItem.WBxGetAsString(WBColumn.SourceID);

                if (!String.IsNullOrEmpty(documentumSourceID))
                {
                    mappingItem = WBUtils.FindItemByColumn(controlSite, MigrationMappingList, WBColumn.SourceID, documentumSourceID);

                    subjectItem = WBUtils.FindItemByColumn(controlSite, MigrationSubjectsList, WBColumn.SourceID, documentumSourceID);
                }
            }



            if (mappedPath.InErrorStatus)
            {
                WBLogging.Migration.HighLevel("WBMigrationTimerJob.MigrateOneDocumentToLibrary(): There was an error with the mapped path: " + mappedPath.ErrorStatusMessage);
                return;
            }

            // OK so let's first get the various WBTerms from the mapped path so that if these
            // fail they fail before we copy the document!

            WBRecordsType                   recordsType    = null;
            WBTermCollection <WBTerm>       functionalArea = null;
            WBTermCollection <WBSubjectTag> subjectTags    = null;

            if (MigrationSourceSystem == MIGRATION_SOURCE__DOCUMENTUM_WEB_DOCUMENTS)
            {
                string recordsTypePath = controlItem.WBxGetAsString(WBColumn.RecordsTypePath);
                if (String.IsNullOrEmpty(recordsTypePath) && mappingItem != null)
                {
                    recordsTypePath = mappingItem.WBxGetAsString(WBColumn.RecordsTypePath);
                }

                Term rterm = mapping.RecordsTypesTaxonomy.GetSelectedTermByPath(recordsTypePath);
                if (rterm != null)
                {
                    recordsType = new WBRecordsType(mapping.RecordsTypesTaxonomy, rterm);
                }


                string functionalAreaPath = controlItem.WBxGetAsString(WBColumn.FunctionalAreaPath);
                if (String.IsNullOrEmpty(functionalAreaPath) && mappingItem != null)
                {
                    functionalAreaPath = mappingItem.WBxGetAsString(WBColumn.FunctionalAreaPath);
                }

                if (!String.IsNullOrEmpty(functionalAreaPath))
                {
                    string[] paths = functionalAreaPath.Split(';');

                    List <WBTerm> fterms = new List <WBTerm>();

                    foreach (string path in paths)
                    {
                        WBLogging.Migration.Verbose("Trying to get a Functional Area by path with: " + path);

                        Term fterm = mapping.FunctionalAreasTaxonomy.GetOrCreateSelectedTermByPath(path);
                        if (fterm != null)
                        {
                            fterms.Add(new WBTerm(mapping.FunctionalAreasTaxonomy, fterm));
                        }
                        else
                        {
                            WBLogging.Debug("Coundn't find the functional area with path: " + path);
                        }
                    }

                    if (fterms.Count > 0)
                    {
                        functionalArea = new WBTermCollection <WBTerm>(mapping.FunctionalAreasTaxonomy, fterms);
                    }
                }


                string subjectTagsPaths = controlItem.WBxGetAsString(WBColumn.SubjectTagsPaths);
                if (String.IsNullOrEmpty(subjectTagsPaths) && mappingItem != null)
                {
                    subjectTagsPaths = mappingItem.WBxGetAsString(WBColumn.SubjectTagsPaths);
                }

                if (!String.IsNullOrEmpty(subjectTagsPaths))
                {
                    List <WBSubjectTag> sterms = new List <WBSubjectTag>();


                    // Note that it is not necessarily an error for the subject tags to be empty.
                    if (!String.IsNullOrEmpty(subjectTagsPaths) && subjectTagsPaths != "/")
                    {
                        string[] paths = subjectTagsPaths.Split(';');

                        foreach (string path in paths)
                        {
                            WBLogging.Migration.Verbose("Trying to get a Subject Tag by path with: " + path);

                            if (path != "/")
                            {
                                Term sterm = mapping.SubjectTagsTaxonomy.GetOrCreateSelectedTermByPath(path);
                                if (sterm != null)
                                {
                                    sterms.Add(new WBSubjectTag(mapping.SubjectTagsTaxonomy, sterm));
                                }
                                else
                                {
                                    WBLogging.Debug("Coundn't find the subject tag with path: " + path);
                                }
                            }
                        }
                    }

                    subjectTags = new WBTermCollection <WBSubjectTag>(mapping.SubjectTagsTaxonomy, sterms);
                }
            }
            else
            {
                recordsType    = mappedPath.RecordsType;
                functionalArea = mappedPath.FunctionalArea;
                subjectTags    = mappedPath.SubjectTags;
            }



            if (MigrationSubjectsList != null && MigrationSourceSystem == MIGRATION_SOURCE__HFI_INTRANET_DOCUMENTS)
            {
                //foreach (SPField field in migrationItem.Fields)
                //{
                //   WBLogging.Debug("Found field: " + field.Title + " field inner name: " + field.InternalName);
                //}

                subjectTags = AddAdditionalSubjectTags(controlSite, subjectTags, migrationItem.WBxGetAsString(WBColumn.SourceID));
            }


            if (recordsType == null)
            {
                MigrationError(migrationItem, "The records type for this item could not be found. Looked for: " + mappedPath.RecordsTypePath);
                return;
            }

            if (functionalArea == null || functionalArea.Count == 0)
            {
                MigrationError(migrationItem, "The functional area for this item could not be found. Looked for: " + mappedPath.FunctionalAreaPath);
                return;
            }

            // OK so we can start building up our information about the document we are going to declare:
            WBDocument document = new WBDocument();

            document.RecordsType    = recordsType;
            document.FunctionalArea = functionalArea;
            document.SubjectTags    = subjectTags;

            document[WBColumn.SourceFilePath] = sourceFilePath;

            string sourceSystem = migrationItem.WBxGetAsString(WBColumn.SourceSystem);

            if (String.IsNullOrEmpty(sourceSystem))
            {
                sourceSystem = farm.MigrationSourceSystem;
            }
            if (String.IsNullOrEmpty(sourceSystem))
            {
                sourceSystem = farm.MigrationControlListUrl;
            }
            document[WBColumn.SourceSystem] = sourceSystem;

            String sourceID = migrationItem.WBxGetAsString(WBColumn.SourceID);

            if (String.IsNullOrEmpty(sourceID) && MigrationSourceSystem != MIGRATION_SOURCE__DOCUMENTUM_WEB_DOCUMENTS)
            {
                sourceID = sourceFilePath;
            }
            document[WBColumn.SourceID] = sourceID;

            SPFile     sourceFile = null;
            SPListItem sourceItem = null;

            if (MigrationSourceSystem == MIGRATION_SOURCE__DOCUMENTUM_WEB_DOCUMENTS)
            {
                if (String.IsNullOrEmpty(sourceID))
                {
                    sourceItem = sourceWeb.GetListItem(sourceFilePath);
                    document[WBColumn.SourceID]     = sourceFilePath;
                    document[WBColumn.SourceSystem] = "Initial SharePoint Web Docs";
                }
                else
                {
                    sourceItem = WBUtils.FindItemByColumn(sourceSite, (SPList)sourceLibrary, WBColumn.Source_ID, sourceID);
                }

                if (sourceItem == null)
                {
                    MigrationError(migrationItem, "Could not find the doc with source id = " + sourceFilePath);
                    return;
                }
                sourceFile = sourceItem.File;
            }



            if (migrationItem.WBxIsNotBlank(WBColumn.ReferenceDateString))
            {
                document.ReferenceDate = WBUtils.ParseDate(migrationItem.WBxGetAsString(WBColumn.ReferenceDateString));
            }

            if (migrationItem.WBxIsNotBlank(WBColumn.ModifiedDateString))
            {
                document.Modified = WBUtils.ParseDate(migrationItem.WBxGetAsString(WBColumn.ModifiedDateString));
            }
            else
            {
                if (mappingItem != null)
                {
                    if (mappingItem.WBxIsNotBlank(WBColumn.ModifiedDateString))
                    {
                        document.Modified = WBUtils.ParseDate(mappingItem.WBxGetAsString(WBColumn.ModifiedDateString));
                    }
                }
                else if (subjectItem != null)
                {
                    if (subjectItem.WBxIsNotBlank(WBColumn.ModifiedDateString))
                    {
                        document.Modified = WBUtils.ParseDate(subjectItem.WBxGetAsString(WBColumn.ModifiedDateString));
                    }
                }
                else if (sourceItem != null)
                {
                    if (sourceItem.WBxHasValue(WBColumn.Modified))
                    {
                        document.Modified = (DateTime)sourceItem["Modified"];
                    }
                }
            }

            if (migrationItem.WBxIsNotBlank(WBColumn.DeclaredDateString))
            {
                document.DeclaredRecord = WBUtils.ParseDate(migrationItem.WBxGetAsString(WBColumn.DeclaredDateString));
            }

            if (migrationItem.WBxIsNotBlank(WBColumn.ScanDateString))
            {
                document.ScanDate = WBUtils.ParseDate(migrationItem.WBxGetAsString(WBColumn.ScanDateString));
            }


            if (migrationItem.WBxIsNotBlank(WBColumn.OwningTeamPath) || !String.IsNullOrEmpty(mappedPath.OwningTeamPath))
            {
                WBTaxonomy teamsTaxonomy = mapping.TeamsTaxonomy;

                string owningTeamPath = migrationItem.WBxGetAsString(WBColumn.OwningTeamPath);
                if (owningTeamPath == "")
                {
                    owningTeamPath = mappedPath.OwningTeamPath;
                }
                WBTeam foundTeam = teamsTaxonomy.GetSelectedTeam(WBUtils.NormalisePath(owningTeamPath));

                if (foundTeam != null)
                {
                    WBLogging.Migration.Verbose("Found the owning team: " + foundTeam.Name);
                    document.OwningTeam = foundTeam;
                }
                else
                {
                    MigrationError(migrationItem, "Could not find the owning team at: " + owningTeamPath);
                    return;
                }
            }

            if (migrationItem.WBxIsNotBlank(WBColumn.Title))
            {
                document[WBColumn.Title] = migrationItem.WBxGetAsString(WBColumn.Title);
            }


            if (MigrationSourceSystem == MIGRATION_SOURCE__HFI_INTRANET_DOCUMENTS)
            {
                document.Modified = File.GetLastWriteTime(sourceFilePath);
                WBLogging.Debug("Found the last modified date to be: " + document.Modified);
            }

            // We'll set the reference date for these imported files based on their existing declared date or modified date if it exists.
            if (!document.HasReferenceDate)
            {
                if (document.HasDeclaredRecord)
                {
                    document.ReferenceDate = document.DeclaredRecord;
                }
                else if (document.HasScanDate)
                {
                    document.ReferenceDate = document.ScanDate;
                }
                else if (document.HasModified)
                {
                    document.ReferenceDate = document.Modified;
                }
            }

            if (migrationItem.WBxHasValue(WBColumn.ReferenceID))
            {
                document.ReferenceID = migrationItem.WBxGetAsString(WBColumn.ReferenceID);
            }


            string protectiveZone = migrationItem.WBxGetAsString(WBColumn.ProtectiveZone);

            if (String.IsNullOrEmpty(protectiveZone))
            {
                protectiveZone = mappedPath.ProtectiveZone;
                if (String.IsNullOrEmpty(protectiveZone))
                {
                    protectiveZone = WBRecordsType.PROTECTIVE_ZONE__PROTECTED;
                }
            }
            document[WBColumn.ProtectiveZone] = protectiveZone;

            string liveOrArchived = migrationItem.WBxGetAsString(WBColumn.LiveOrArchived);

            if (String.IsNullOrEmpty(liveOrArchived))
            {
                liveOrArchived = mappedPath.LiveOrArchived;
                if (String.IsNullOrEmpty(liveOrArchived))
                {
                    liveOrArchived = WBColumn.LIVE_OR_ARCHIVED__LIVE;
                }
            }
            document[WBColumn.LiveOrArchived] = liveOrArchived;

            bool downloadFromWebSite = false;

            if (MigrationSourceSystem == MIGRATION_SOURCE__ALFRESCO_RECORDS)
            {
                downloadFromWebSite = true;
            }


            String originalFileName = migrationItem.WBxGetAsString(WBColumn.OriginalFilename).Trim();

            if (String.IsNullOrEmpty(originalFileName))
            {
                originalFileName = Path.GetFileName(sourceFilePath);
            }
            if (MigrationSourceSystem == MIGRATION_SOURCE__DOCUMENTUM_WEB_DOCUMENTS)
            {
                originalFileName = sourceFile.Name;
            }
            if (downloadFromWebSite)
            {
                originalFileName = HttpUtility.UrlDecode(originalFileName);
            }

            document.OriginalFilename = originalFileName;

            //String extension = Path.GetExtension(filename);


            WBItemMessages metadataErrors = recordsType.CheckMetadataIsOK(document);

            if (metadataErrors.Count > 0)
            {
                string message = "There were problems with the prepared metadata. ";
                foreach (WBColumn column in metadataErrors.Keys)
                {
                    message += "Error for column: " + column.DisplayName + " message: " + metadataErrors[column] + "  ";
                }
                MigrationError(migrationItem, message);
                return;
            }

            Stream fileStream = null;

            if (downloadFromWebSite)
            {
                WebClient webClient = new WebClient();

                if (!String.IsNullOrEmpty(farm.MigrationUserName) && !String.IsNullOrEmpty(farm.MigrationPassword))
                {
                    webClient.Credentials = new NetworkCredential(farm.MigrationUserName, farm.MigrationPassword);
                }

                string tempFile = @"C:\Temp\tmp.bin";
                if (farm.FarmInstance == WBFarm.FARM_INSTANCE__PROTECTED_INTERNAL_FARM)
                {
                    tempFile = @"E:\Temp\tmp.bin";
                }

                webClient.DownloadFile(sourceFilePath, tempFile);
                WBLogging.Migration.Verbose("Downloaded to local tmp file using webClient.DownloadFile() successfully");

                fileStream = File.OpenRead(tempFile);
                WBLogging.Migration.Verbose("Opened local tmp file using File.OpenRead() successfully");
            }
            else if (MigrationSourceSystem == MIGRATION_SOURCE__DOCUMENTUM_WEB_DOCUMENTS)
            {
                fileStream = sourceFile.OpenBinaryStream();
                WBLogging.Migration.Verbose("Opened using sourceFile.OpenBinaryStream() successfully");
            }
            else
            {
                fileStream = File.OpenRead(sourceFilePath);
                WBLogging.Migration.Verbose("Opened using File.OpenRead() successfully");
            }

            SPListItem uploadedItem = null;

            try
            {
                uploadedItem = recordsType.PublishDocument(destinationWeb, destinationRootFolder, document, fileStream);
            }
            finally
            {
                fileStream.Close();
                fileStream.Dispose();
            }

            if (uploadedItem == null)
            {
                MigrationError(migrationItem, "There was a problem in the call to recordsType.PublishDocument() as the uploaded item is null.");
                return;
            }

            migrationItem.WBxSet(WBColumn.DateMigrated, DateTime.Now);
            migrationItem.WBxSet(WBColumn.MigratedToUrl, uploadedItem.WBxGet(WBColumn.EncodedAbsoluteURL));
            migrationItem.WBxSet(WBColumn.RecordID, uploadedItem.WBxGet(WBColumn.RecordID));
            migrationItem.WBxSet(WBColumn.MigrationStatus, WBColumn.MIGRATION_STATUS__DONE);

            migrationItem.Update();
        }
Пример #49
0
        //创建任务时创建文档对象,如果文档对象不为空,则不创建
        public void WriteDocument(SPItemEventProperties properties)
        {
            if (properties.ListItem["Document"] != null)
            {
                return;
            }
            string taskDocName = "项目文档";
            SPUser lgUser      = properties.Web.CurrentUser;

            //StreamWriter w = new StreamWriter("c:\\lg.txt");
            try
            {
                SPSite            site    = properties.Site;
                SPWeb             web     = properties.Web;
                SPDocumentLibrary library = web.Lists[taskDocName] as SPDocumentLibrary;
                string            docType = "Word文档.docx";
                if (properties.ListItem["DocType"] != null)
                {
                    docType = properties.ListItem["DocType"].ToString();
                }
                string fileType            = docType.Substring(docType.LastIndexOf("."));
                string templatePath        = "";
                string documentName        = properties.ListItem.Title;                   // +".xlsx";//".docx" ;
                string libraryRelativePath = library.RootFolder.ServerRelativeUrl;
                string libraryPath         = site.MakeFullUrl(libraryRelativePath);       //带网站集的url
                string documentPath        = libraryPath + "/" + documentName + fileType; //创建的文档名称
                templatePath = libraryPath + "/Forms/" + docType;                         // +fileType;// web.Url + "/" + library.DocumentTemplateUrl;
                SPFile file = web.GetFile(templatePath);
                #region  fileNotNull
                if (file != null)
                {
                    try
                    {
                        web.AllowUnsafeUpdates = true;
                        Stream readStream   = file.OpenBinaryStream(); //file is SPFile type文件不存在会报错
                        SPFile uploadedFile = null;                    // web.GetFile(documentPath);//
                        #region   文件
                        try
                        {
                            uploadedFile = web.Files.Add(documentPath, readStream, false);

                            uploadedFile.Item["Title"] = documentName;
                            uploadedFile.Item.Update();

                            uploadedFile.CheckIn("", SPCheckinType.MajorCheckIn);
                            uploadedFile.Update();
                        }
                        catch (Exception ex)//文档存在,原来的任务无链接则继续执行或者是原来的地址不统一,则不更改返回
                        {
                            //w.WriteLine(ex.ToString());
                            if (properties.ListItem["Document"] == null || !properties.ListItem["Document"].ToString().Contains(documentName + fileType))
                            {
                                uploadedFile = web.GetFile(documentPath);
                            }
                            else
                            {
                                //w.Close();
                                //w.Dispose();
                                return;
                            }
                        }
                        #endregion
                        //更新作务主表文档对象字段
                        SPFieldUrlValue urlValue = new SPFieldUrlValue();
                        urlValue.Description            = documentName;
                        urlValue.Url                    = documentPath;
                        this.EventFiringEnabled         = false;//否则会死循环
                        properties.ListItem["Document"] = urlValue;
                        properties.ListItem.Update();
                        this.EventFiringEnabled = true;
                        web.AllowUnsafeUpdates  = false;
                    }
                    catch (Exception ex)//源文件不存在或目标文档已经存在,会报错
                    {
                        //w.WriteLine(ex.ToString());
                        web.AllowUnsafeUpdates = false;
                    }
                }
                #endregion
                //    }
                //}
            }
            catch (Exception ex)
            {
                //w.WriteLine(ex.ToString());
            }
            //});
            //w.Close();
            //w.Dispose();
        }
Пример #50
0
        private void RunOneMigrationCycle()
        {
            WBFarm farm = WBFarm.Local;

            WBMigrationMapping mapping = new WBMigrationMapping(farm.MigrationMappingListUrl, farm.MigrationMappingListView);

            using (SPSite controlSite = new SPSite(farm.MigrationControlListUrl))
                using (SPWeb controlWeb = controlSite.OpenWeb())
                {
                    SPList controlList = controlWeb.GetList(farm.MigrationControlListUrl);
                    SPView controlView = null;
                    SPListItemCollection migrationItems = null;

                    MigrationMappingList = controlWeb.GetList(farm.MigrationMappingListUrl);

                    if (!String.IsNullOrEmpty(farm.MigrationSubjectsListUrl))
                    {
                        MigrationSubjectsList = controlWeb.GetList(farm.MigrationSubjectsListUrl);
                    }

                    if (String.IsNullOrEmpty(farm.MigrationControlListView))
                    {
                        migrationItems = controlList.Items;
                    }
                    else
                    {
                        controlView    = controlList.Views[farm.MigrationControlListView];
                        migrationItems = controlList.GetItems(controlView);
                    }

                    int total = migrationItems.Count;

                    int itemsPerCycle = Convert.ToInt32(farm.MigrationItemsPerCycle);
                    if (itemsPerCycle <= 0)
                    {
                        itemsPerCycle = total;
                    }

                    int count = 0;

                    // Now let's get the additional subjects list if it is defined:



                    /*
                     *
                     *   Now opening the SPSite and SPWeb objects that can be re-used for each migrated item (where appropriate).
                     *
                     */

                    SPSite   destinationSite       = null;
                    SPWeb    destinationWeb        = null;
                    SPFolder destinationRootFolder = null;

                    SPSite            sourceSite    = null;
                    SPWeb             sourceWeb     = null;
                    SPDocumentLibrary sourceLibrary = null;

                    switch (farm.MigrationType)
                    {
                    case WBFarm.MIGRATION_TYPE__MIGRATE_IZZI_PAGES:
                    {
                        // nothing at the moment
                        break;
                    }

                    case WBFarm.MIGRATION_TYPE__MIGRATE_DOCUMENTS_TO_LIBRARY:
                    {
                        destinationSite       = new SPSite(farm.ProtectedRecordsLibraryUrl);
                        destinationWeb        = destinationSite.OpenWeb();
                        destinationRootFolder = destinationWeb.GetFolder(farm.ProtectedRecordsLibraryUrl);

                        mapping.ConnectToSite(destinationSite);


                        if (MigrationSourceSystem == MIGRATION_SOURCE__DOCUMENTUM_WEB_DOCUMENTS)
                        {
                            if (farm.FarmInstance == WBFarm.FARM_INSTANCE__DEVELOPMENT_FARM)
                            {
                                sourceSite    = new SPSite("http://sharepointhub/records");
                                sourceWeb     = sourceSite.OpenWeb();
                                sourceLibrary = sourceWeb.Lists["Source Library"] as SPDocumentLibrary;
                            }
                            else
                            {
                                sourceSite    = new SPSite("http://stagingweb/publicrecords");
                                sourceWeb     = sourceSite.OpenWeb();
                                sourceLibrary = sourceWeb.Lists["Documents"] as SPDocumentLibrary;

                                foreach (SPField field in sourceLibrary.Fields)
                                {
                                    WBLogging.Generic.Verbose("Field found: " + field.Title + " internal: " + field.InternalName + " type: " + field.Type.ToString());
                                }
                            }
                        }



                        break;
                    }

                    case WBFarm.MIGRATION_TYPE__MIGRATE_DOCUMENTS_TO_WORK_BOXES:
                    {
                        // nothing at the moment
                        break;
                    }
                    }

                    try
                    {
                        foreach (SPListItem migrationItem in migrationItems)
                        {
                            count++;
                            if (count > itemsPerCycle)
                            {
                                break;
                            }

                            string progressString = String.Format("Migrating item {0} of {1} in a cycle of {2} items using control list: {3}", count, total, itemsPerCycle, farm.MigrationControlListUrl);

                            try
                            {
                                switch (farm.MigrationType)
                                {
                                case WBFarm.MIGRATION_TYPE__MIGRATE_IZZI_PAGES:
                                {
                                    WBLogging.Migration.HighLevel("WBMigrationTimerJob.RunOneMigrationCycle(): Start izzi Page Migration Cycle. " + progressString);

                                    MigrateOneWebPage(mapping, controlSite, controlWeb, controlList, controlView, migrationItem);

                                    WBLogging.Migration.HighLevel("WBMigrationTimerJob.RunOneMigrationCycle(): End izzi Page Migration Cycle.");
                                    break;
                                }

                                case WBFarm.MIGRATION_TYPE__MIGRATE_DOCUMENTS_TO_LIBRARY:
                                {
                                    WBLogging.Migration.HighLevel("WBMigrationTimerJob.RunOneMigrationCycle(): Start Documents To Library Migration Cycle. " + progressString);

                                    if (migrationItem.WBxGetAsString(WBColumn.FileOrFolder) == WBColumn.FILE_OR_FOLDER__FOLDER)
                                    {
                                        AddSubFilesAndFolders(mapping,
                                                              controlSite, controlWeb, controlList, controlView,
                                                              migrationItem);
                                    }
                                    else
                                    {
                                        MigrateOneDocumentToLibrary(mapping,
                                                                    sourceSite, sourceWeb, sourceLibrary,
                                                                    destinationSite, destinationWeb, destinationRootFolder,
                                                                    controlSite, controlWeb, controlList, controlView,
                                                                    migrationItem);
                                    }


                                    WBLogging.Migration.HighLevel("WBMigrationTimerJob.RunOneMigrationCycle(): End Documents To Library Migration Cycle.");
                                    break;
                                }

                                case WBFarm.MIGRATION_TYPE__MIGRATE_DOCUMENTS_TO_WORK_BOXES:
                                {
                                    WBLogging.Migration.HighLevel("WBMigrationTimerJob.RunOneMigrationCycle(): Start Documents To Work Boxes Migration Cycle. " + progressString);

                                    MigrateOneDocumentToWorkBox(mapping, controlSite, controlWeb, controlList, controlView, migrationItem);

                                    WBLogging.Migration.HighLevel("WBMigrationTimerJob.RunOneMigrationCycle(): End Documents To Work Boxes Migration Cycle.");
                                    break;
                                }

                                default:
                                {
                                    WBLogging.Migration.HighLevel("WBMigrationTimerJob.RunOneMigrationCycle(): No migration setup to run - doing nothing.");
                                    break;
                                }
                                }
                            }
                            catch (Exception itemLevelException)
                            {
                                string messageSoFar = migrationItem.WBxGetAsString(WBColumn.MigrationMessage);

                                migrationItem.WBxSet(WBColumn.MigrationStatus, WBColumn.MIGRATION_STATUS__ERROR);
                                migrationItem.WBxSet(WBColumn.MigrationMessage, messageSoFar + "Exception Thrown: " + itemLevelException.Message);
                                migrationItem.Update();

                                WBLogging.Migration.Unexpected("An item level exception has occurred:");
                                WBLogging.Migration.Unexpected(itemLevelException);
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        WBLogging.Migration.Unexpected(exception);
                    }
                    finally
                    {
                        if (destinationWeb != null)
                        {
                            destinationWeb.Dispose();
                        }
                        if (destinationSite != null)
                        {
                            destinationSite.Dispose();
                        }

                        if (sourceWeb != null)
                        {
                            sourceWeb.Dispose();
                        }
                        if (sourceSite != null)
                        {
                            sourceSite.Dispose();
                        }
                    }
                }
        }
Пример #51
0
        private void loadEnterpriseFields()
        {
            Guid siteGuid = SPContext.Current.Site.ID;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = SPContext.Current.Site)
                {
                    try
                    {
                        WebSvcCustomFields.CustomFields cf = new WebSvcCustomFields.CustomFields();
                        cf.Url = SPContext.Current.Site.Url + "/_vti_bin/PSI/customfields.asmx";
                        cf.UseDefaultCredentials = true;

                        WebSvcCustomFields.CustomFieldDataSet dsF = cf.ReadCustomFieldsByEntity(new Guid(PSLibrary.EntityCollection.Entities.TaskEntity.UniqueId));

                        ddlAssignedToField.Items.Add(new ListItem("[Not Specified]", ""));
                        ddlTimesheet.Items.Add(new ListItem("[Select Field]", ""));
                        ddlTimesheetHours.Items.Add(new ListItem("[Select Field]", ""));

                        foreach (DataRow dr in dsF.Tables[0].Select("MD_PROP_TYPE_ENUM = 21"))
                        {
                            ListItem li = new ListItem(dr["MD_PROP_NAME"].ToString(), dr["MD_PROP_UID"].ToString());
                            ddlAssignedToField.Items.Add(li);
                        }

                        foreach (DataRow dr in dsF.Tables[0].Select("MD_PROP_TYPE_ENUM = 15"))
                        {
                            ListItem li = new ListItem(dr["MD_PROP_NAME"].ToString(), dr["MD_PROP_ID"].ToString());
                            ddlTimesheetHours.Items.Add(li);
                        }

                        foreach (DataRow dr in dsF.Tables[0].Select("MD_PROP_TYPE_ENUM = 17"))
                        {
                            ListItem li = new ListItem(dr["MD_PROP_NAME"].ToString(), dr["MD_PROP_UID"].ToString());
                            ddlTimesheet.Items.Add(li);
                        }

                        ddlTimesheetHours.Items.Add(new ListItem("Actual Work", "251658250"));

                        using (var connection = new SqlConnection(CoreFunctions.getConnectionString(site.WebApplication.Id)))
                        {
                            connection.Open();

                            using (var command = new SqlCommand("SELECT config_value FROM ECONFIG where config_name='AssignedToField'", connection))
                                using (var reader = command.ExecuteReader())
                                {
                                    if (reader.Read())
                                    {
                                        ddlAssignedToField.SelectedValue = reader.GetString(0);
                                    }
                                }

                            using (var command = new SqlCommand("SELECT config_value FROM ECONFIG where config_name='TimesheetField'", connection))
                                using (var reader = command.ExecuteReader())
                                {
                                    if (reader.Read())
                                    {
                                        ddlTimesheet.SelectedValue = reader.GetString(0);
                                    }
                                }

                            using (var command = new SqlCommand("SELECT config_value FROM ECONFIG where config_name='TimesheetHoursField'", connection))
                                using (var reader = command.ExecuteReader())
                                {
                                    if (reader.Read())
                                    {
                                        ddlTimesheetHours.SelectedValue = reader.GetString(0);
                                    }
                                }

                            using (var command = new SqlCommand("SELECT config_value FROM ECONFIG where config_name='LockSynch'", connection))
                                using (var reader = command.ExecuteReader())
                                {
                                    if (reader.Read())
                                    {
                                        chkLockSynch.Checked = bool.Parse(reader.GetString(0));
                                    }
                                }

                            using (var command = new SqlCommand("SELECT config_value FROM ECONFIG where config_name='ForceWS'", connection))
                                using (var reader = command.ExecuteReader())
                                {
                                    if (reader.Read())
                                    {
                                        chkForceWS.Checked = bool.Parse(reader.GetString(0));
                                    }
                                }

                            using (var command = new SqlCommand("SELECT config_value FROM ECONFIG where config_name='ValidTemplates'", connection))
                                using (var reader = command.ExecuteReader())
                                {
                                    if (reader.Read())
                                    {
                                        loadTemplates(reader.GetString(0));
                                    }
                                    else
                                    {
                                        loadTemplates(string.Empty);
                                    }
                                }

                            using (var command = new SqlCommand("SELECT config_value FROM ECONFIG where config_name='CrossSite'", connection))
                                using (var reader = command.ExecuteReader())
                                {
                                    if (reader.Read())
                                    {
                                        chkCrossSite.Checked = bool.Parse(reader.GetString(0));
                                    }
                                }

                            using (var command = new SqlCommand("SELECT config_value FROM ECONFIG where config_name='DefaultURL'", connection))
                                using (var reader = command.ExecuteReader())
                                {
                                    if (reader.Read())
                                    {
                                        txtDefaultURL.Text = reader.GetString(0);
                                    }
                                }

                            using (var command = new SqlCommand("SELECT config_value FROM ECONFIG where config_name='ConnectedURLs'", connection))
                                using (var reader = command.ExecuteReader())
                                {
                                    if (reader.Read())
                                    {
                                        txtUrls.Text = reader.GetString(0);
                                    }
                                }
                        }

                        lblError.Visible = false;

                        WebSvcEvents.Events events = new EPMLiveEnterprise.WebSvcEvents.Events();
                        events.Url = SPContext.Current.Site.Url + "/_vti_bin/psi/events.asmx";
                        events.UseDefaultCredentials = true;

                        WebSvcEvents.EventHandlersDataSet ds = events.ReadEventHandlerAssociations();

                        if (ds.EventHandlers.Select("EventId = 53 and name = 'EPMLivePublisher'").Length <= 0)
                        {
                            lblProjectPublished.Text = "Not Installed";
                        }
                        else
                        {
                            lblProjectPublished.Text = "Installed";
                        }

                        if (ds.EventHandlers.Select("EventId = 133 and name = 'EPMLiveStatusing'").Length <= 0)
                        {
                            lblStatusingApplied.Text = "Not Installed";
                        }
                        else
                        {
                            lblStatusingApplied.Text = "Installed";
                        }

                        if (ds.EventHandlers.Select("EventId = 95 and name = 'EPMLiveResUpdated'").Length <= 0)
                        {
                            lblResUpdated.Text = "Not Installed";
                        }
                        else
                        {
                            lblResUpdated.Text = "Installed";
                        }

                        if (ds.EventHandlers.Select("EventId = 89 and name = 'EPMLiveResCreated'").Length <= 0)
                        {
                            lblResCreated.Text = "Not Installed";
                        }
                        else
                        {
                            lblResCreated.Text = "Installed";
                        }

                        if (ds.EventHandlers.Select("EventId = 92 and name = 'EPMLiveResDeleting'").Length <= 0)
                        {
                            lblResDeleted.Text = "Not Installed";
                        }
                        else
                        {
                            lblResDeleted.Text = "Installed";
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex.Message.Contains("401"))
                        {
                            lblError.Text    = "Error: 401 Unauthorized<br>This usually means the service account that is current running your SharePoint Application Pool does not have access to the Project Server Site.";
                            lblError.Visible = true;
                        }
                        else
                        {
                            Response.Write("Error: " + ex.Message + "<br>Current User: " + HttpContext.Current.User.Identity.Name);
                        }
                    }
                }
            });
        }
Пример #52
0
        private void WriteDocument11(SPItemEventProperties properties)
        {
            string            taskDocName    = "项目文档";
            SPSite            siteCollection = properties.Site;
            SPWeb             subWeb         = properties.Web;
            SPDocumentLibrary library        = subWeb.Lists[taskDocName] as SPDocumentLibrary;
            string            docType        = properties.ListItem["DocType"].ToString();
            string            temType        = "";
            string            fileType       = "";

            if (docType == "Word文档")
            {
                temType = ".dotx"; fileType = ".docx";
            }
            else if (docType == "PPT演示文稿")
            {
                temType = ".potx"; fileType = ".pptx";
            }
            else if (docType == "Excel工作簿")
            {
                temType = ".xltx"; fileType = ".xlsx";
            }

            foreach (SPContentType cType in library.ContentTypes)
            {
                if (cType.DocumentTemplateUrl.EndsWith(temType))
                {
                    library.DocumentTemplateUrl = cType.DocumentTemplateUrl;
                    break;
                }
            }
            string documentName        = properties.ListItem.Title;// +".xlsx";//".docx" ;
            string libraryRelativePath = library.RootFolder.ServerRelativeUrl;
            string libraryPath         = siteCollection.MakeFullUrl(libraryRelativePath);
            string documentPath        = libraryPath + "/" + documentName + fileType;

            Stream       documentStream = new MemoryStream();
            StreamWriter writer         = new StreamWriter(documentStream);

            writer.Write("");
            writer.Flush();

            Hashtable docProperties = new Hashtable();

            docProperties["vti_title"] = documentName;
            //docProperties["Color"] = "Green";

            try
            {
                subWeb.Files.Add(documentPath, documentStream, docProperties, false);
                SPFieldUrlValue urlValue = new SPFieldUrlValue();
                urlValue.Description = documentName;
                urlValue.Url         = documentPath;

                properties.ListItem["Document"] = urlValue;
                properties.ListItem.Update();
                ////Response.Redirect(libraryPath);
            }
            catch//文档已经存在,会报错
            {
            }
        }
        public void RemoveTemplate(string sTemplate)
        {
            SPWeb web = null;

            try
            {
                using (SPSite site = SPContext.Current.Site)
                {
                    web = site.AllWebs[sTemplate];
                }
            }
            catch (Exception ex)
            {
            }

            if (web != null)
            {
                string sWebId = web.ID.ToString();
                using (SPWeb rootWeb = SPContext.Current.Site.RootWeb)
                {
                    if (rootWeb.Properties.ContainsKey("EPMLiveSiteTemplateIDs"))
                    {
                        string sIDs = rootWeb.Properties["EPMLiveSiteTemplateIDs"];
                        rootWeb.AllowUnsafeUpdates = true;

                        if (sIDs.Contains(sWebId))
                        {
                            int iPipeLocation = sIDs.IndexOf("|" + sWebId);
                            if (iPipeLocation > 0 && iPipeLocation < (sIDs.Length - (sWebId.Length))) // has more
                            {
                                sIDs = sIDs.Replace("|" + sWebId, "");
                            }
                            else
                            {
                                sIDs = "";
                            }
                            rootWeb.Properties["EPMLiveSiteTemplateIDs"] = sIDs;
                            rootWeb.Properties.Update();

                            //SPFeature oFT = null;
                            //try
                            //{
                            //    oFT = web.Features[new Guid("dfb82bdd-a86c-4314-a0f2-654526c7814e")];
                            //}
                            //catch { }
                            //if (oFT == null)
                            //{
                            //    try
                            //    {
                            //        web.Features.Remove(new Guid("dfb82bdd-a86c-4314-a0f2-654526c7814e"));
                            //    }
                            //    catch { }
                            //}
                        }

                        LogHelper logHlpr = new LogHelper();
                        logHlpr.Action = "synchtemplate";
                        logHlpr.Source = web.ServerRelativeUrl;
                        string sLastResults = logHlpr.DeleteLastResult();

                        rootWeb.Properties.Update();
                        rootWeb.AllowUnsafeUpdates = false;
                    }
                }
                if (web.Properties.ContainsKey("EPMLiveTemplateID"))
                {
                    web.AllowUnsafeUpdates = true;
                    web.Properties.Remove("EPMLiveTemplateID");
                    web.Properties.Update();
                    web.AllowUnsafeUpdates = false;
                }

                web.Close();
                web.Dispose();
            }
        }
Пример #54
0
        //创建任务时创建文档对象,如果文档对象不为空,则不创建,Routine部分不进行处理
        //2019-1-19日更新,项目文档中去年项目,不用判断
        public void WriteDocumentNew(SPItemEventProperties properties)
        {
            if (!properties.List.Fields.ContainsFieldWithStaticName("TaskDoc") || properties.ListItem["TaskDoc"] != null)//条件判断
            {
                return;
            }
            int           level       = 0;
            List <string> account     = new List <string>();;
            string        projectName = GetRootType(properties.ListItemId, properties.List, ref level, ref account);

            //if (taskType == "Routine"  ||level==1 )//Routine/用户/类别/规则文档,项目顶级不处理&& level < 4
            //    return;
            web = properties.Web;
            string taskDocLibName = projectName + "任务文档"; // 二级任务所对应的文档库
            string blogName       = projectName + "项目任务"; //三级及以上对应的博客

            try
            {
                SPSite          site         = properties.Site;
                SPWeb           web          = properties.Web;
                string          documentName = properties.ListItem.Title;//.Replace(properties.UserDisplayName,"") ;// 去掉用户的显示名称
                SPFieldUrlValue urlValue     = new SPFieldUrlValue();
                web.AllowUnsafeUpdates = true;
                if (level < 2)
                {
                    SPDocumentLibrary library             = web.Lists[taskDocLibName] as SPDocumentLibrary;
                    string            docType             = "Word文档.docx";
                    string            templatePath        = "";
                    string            fileName            = documentName + docType.Substring(docType.IndexOf("."));
                    string            libraryRelativePath = library.RootFolder.ServerRelativeUrl;
                    string            libraryPath         = site.MakeFullUrl(libraryRelativePath); //带网站集的url
                    string            documentPath        = libraryPath + "/" + fileName;          //创建的文档名称
                    templatePath = libraryPath + "/Forms/" + docType;                              // +fileType;// web.Url + "/" + library.DocumentTemplateUrl;
                    SPFile file = web.GetFile(templatePath);                                       //获取模板文件
                    #region  fileNotNull
                    if (file != null)
                    {
                        try
                        {
                            //更新作务主表文档对象字段
                            Stream readStream   = file.OpenBinaryStream(); //file is SPFile type文件不存在会报错
                            SPFile uploadedFile = null;                    // web.GetFile(documentPath);//
                            #region   文件
                            try
                            {
                                uploadedFile = web.Files.Add(documentPath, readStream, false);
                                uploadedFile.Item["Title"] = documentName;
                                uploadedFile.Item.Update();
                                uploadedFile.CheckIn("", SPCheckinType.MajorCheckIn);
                                uploadedFile.Update();
                            }
                            catch (Exception ex)//文档存在,原来的任务无链接则继续执行或者是原来的地址不统一,则不更改返回
                            {
                                uploadedFile = web.GetFile(documentPath);
                            }
                            urlValue             = new SPFieldUrlValue();
                            urlValue.Description = uploadedFile.Title;
                            urlValue.Url         = library.DefaultViewUrl;// documentPath;
                            #endregion
                        }
                        catch (Exception ex)//源文件不存在或目标文档已经存在,会报错
                        {
                            web.AllowUnsafeUpdates = false;
                        }
                    }
                    #endregion
                }
                else//三级以上直接打开编辑
                {
                    int   blogCateID = 0;
                    SPWeb blogWeb    = GetBlogWeb(web, blogName);//列表名为任务文章 或Posts
                    if (blogWeb == null)
                    {
                        return;
                    }
                    string cateListName = "类别"; //类别网站
                    SPList cateList     = blogWeb.Lists.TryGetList(cateListName);
                    if (level == 2)             //按类别打开博客
                    {
                        blogCateID           = GetBlogCategoryID(cateList, documentName);
                        urlValue             = new SPFieldUrlValue();
                        urlValue.Description = documentName;
                        string itemUrl = cateList.DefaultViewUrl.Replace("AllCategories.aspx", "Category.aspx");//由显示改为编辑
                        urlValue.Url = itemUrl + "?CategoryId=" + blogCateID;
                    }
                    else
                    {
                        SPList blogList = blogWeb.Lists.TryGetList(blogName.Replace(projectName, ""));

                        if (blogList == null)
                        {
                            blogList = blogWeb.Lists.TryGetList("Posts");
                        }

                        SPQuery qry = new SPQuery();
                        qry.Query = @"<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + documentName + "</Value></Eq></Where>";
                        SPListItemCollection items = blogList.GetItems(qry);
                        SPListItem           item;
                        if (items.Count > 0)
                        {
                            item = items[0];
                        }
                        else
                        {
                            item                  = blogList.AddItem();
                            item["Title"]         = documentName;
                            item["PublishedDate"] = DateTime.Now;
                            string category = account[1];//当前任务的上级任务
                            blogCateID = GetBlogCategoryID(cateList, category);
                            if (blogCateID > 0)
                            {
                                SPFieldLookupValue cateValue = new SPFieldLookupValue();
                                cateValue.LookupId   = items[0].ID;
                                item["PostCategory"] = cateValue;
                            }
                            item.Update();
                        }

                        urlValue             = new SPFieldUrlValue();
                        urlValue.Description = documentName;
                        string itemUrl = blogList.DefaultViewUrl.Replace("AllPosts.aspx", "EditPost.aspx");//由显示改为编辑
                        urlValue.Url = itemUrl + "?ID=" + item.ID;
                    }
                }
                if (urlValue == null)
                {
                    return;
                }
                this.EventFiringEnabled        = false;//否则会死循环
                properties.ListItem["TaskDoc"] = urlValue;
                properties.ListItem.Update();
                this.EventFiringEnabled = true;
                web.AllowUnsafeUpdates  = false;
            }
            catch (Exception ex)
            {
                //w.WriteLine(ex.ToString());
            }
        }
        private void loadListGrid(string sLists, SPSite site)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("ListName");
            dt.Columns.Add("EditLink");
            dt.Columns.Add("SyncOptions");
            dt.Columns.Add("DeleteLink");
            dt.Columns.Add("SyncLink");
            dt.Columns.Add("LastSync");
            dt.Columns.Add("Status");
            dt.Columns.Add("Results");
            dt.Columns.Add("ListGuid");
            dt.Columns.Add("Percent");

            int cntFields = 0;

            string[] arrLists = sLists.Split(chrPipeSeparator, StringSplitOptions.RemoveEmptyEntries);

            SqlConnection cn = new SqlConnection();

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                cn.ConnectionString = EPMLiveCore.CoreFunctions.getConnectionString(site.WebApplication.Id);
                cn.Open();
            });

            foreach (string sListID in arrLists)
            {
                string sListName        = "";
                string sListGuid        = "";
                string sListEditPageURL = "";
                try
                {
                    SPList lst = currWeb.Lists[new Guid(sListID)];
                    sListName = lst.Title;
                    sListGuid = lst.ID.ToString();
                }
                catch { }
                if (sListGuid.Length != 0)
                {
                    sListEditPageURL = currWeb.Url + "/_layouts/ListEdit.aspx?List={" + sListGuid + "}&Source=" + currWeb.Url + "/_layouts/epmlive/templates.aspx";


                    string sSiteGuid = "";
                    sSiteGuid = currWeb.Site.ID.ToString();
                    string sServerRelativeUrl = currWeb.ServerRelativeUrl;
                    //if (currWeb.ServerRelativeUrl.Trim() == "/")
                    //{
                    //    sServerRelativeUrl = "";
                    //}
                    //else
                    //{
                    //    sServerRelativeUrl = currWeb.ServerRelativeUrl;
                    //}


                    SqlCommand cmd = new SqlCommand();
                    cmd.CommandText = "Select timerjobuid,runtime,percentComplete,status,dtfinished,result From vwQueueTimerLog Where listguid=@listguid and jobtype=4";
                    cmd.Parameters.AddWithValue("@listguid", sListGuid);
                    cmd.Connection = cn;
                    SqlDataReader rdr;
                    rdr = cmd.ExecuteReader();

                    string sImg       = "";
                    string sLogTime   = "";
                    string sLogResult = "";
                    string percent    = "0";

                    if (rdr.Read())
                    {
                        if (!rdr.IsDBNull(3))
                        {
                            if (rdr.GetInt32(3) == 0)
                            {
                                sLogResult = "Queued";
                            }
                            else if (rdr.GetInt32(3) == 1)
                            {
                                sLogResult = "Processing";
                                percent    = rdr.GetInt32(2).ToString("##0");
                            }
                            else if (!rdr.IsDBNull(5))
                            {
                                sLogResult = rdr.GetString(5);
                                if (sLogResult == "No Errors")
                                {
                                    sImg = "<img src=\"/_layouts/images/green.gif\" alt=\"\" >";
                                }
                                else
                                {
                                    sImg = "<img src=\"/_layouts/images/yellow.gif\" alt=\"\" >";
                                }
                            }
                            else
                            {
                                sLogResult = "No Results";
                            }
                        }

                        if (!rdr.IsDBNull(4))
                        {
                            sLogTime = rdr.GetDateTime(4).ToString();
                        }
                    }

                    rdr.Close();

                    dt.Rows.Add(new string[] { sListName, sListEditPageURL, "", "", "", sLogTime, sImg, sLogResult, sListGuid, percent });
                    cntFields++;



                    ////bool processing = false;



                    ////if (rdr.Read())
                    ////{
                    ////    if (rdr.GetInt32(0) == 0)
                    ////    {
                    ////        processing = true;
                    ////        sLogResult = "Queued";
                    ////    }
                    ////    else if (rdr.GetInt32(0) == 1)
                    ////    {
                    ////        processing = true;
                    ////        sLogResult = "Processing";
                    ////    }
                    ////    percent = rdr.GetInt32(1).ToString("##0");
                    ////    if (!rdr.IsDBNull(2))
                    ////    {
                    ////        sLogTime = rdr.GetDateTime(2).ToString();
                    ////    }
                    ////}
                    ////rdr.Close();

                    ////if (!processing)
                    ////{
                    ////    cmd = new SqlCommand();
                    ////    cmd.CommandText = "Select result From epmlive_log Where listguid=@listguid and log_type=4";
                    ////    cmd.Parameters.AddWithValue("@listguid", sListGuid);
                    ////    cmd.Connection = cn;
                    ////    rdr = cmd.ExecuteReader();
                    ////    if (rdr.Read())
                    ////    {
                    ////        sLogResult = rdr.GetString(0);
                    ////        if (sLogResult.Contains("No Errors"))
                    ////        {
                    ////            sImg = "<img src=\"/_layouts/images/green.gif\" alt=\"\" >";
                    ////        }
                    ////        else
                    ////        {
                    ////            sImg = "<img src=\"/_layouts/images/yellow.gif\" alt=\"\" >";
                    ////        }
                    ////    }
                    ////    rdr.Close();
                    ////}



                    /*
                     * if (rdr.Read())
                     * {
                     *  sLogResult = rdr.GetString(0);
                     *  sLogTime = rdr.GetDateTime(1).ToLocalTime().ToString();
                     *  if(!rdr.IsDBNull(2))
                     *      percent = rdr.GetDouble(2).ToString("##0");
                     * }
                     * rdr.Close();
                     *
                     * //if (sLastResults.Length > 0 && sLastResults.IndexOf("Log time:") > 0)
                     * //{
                     * //    sLogResult = sLastResults.Substring(0, sLastResults.IndexOf("Log time:") - 2);
                     * //    sLogTime = sLastResults.Substring(sLastResults.IndexOf("Log time:") + 10);
                     * DateTime dtLogTime;
                     * if (DateTime.TryParse(sLogTime, out dtLogTime))
                     * {
                     *  if (sMaxListSyncDate == "")
                     *  {
                     *      sMaxListSyncDate = dtLogTime.ToString();
                     *  }
                     *  else
                     *  {
                     *      DateTime dtMaxListSyncDate;
                     *      if (DateTime.TryParse(sLogTime, out dtLogTime) && DateTime.TryParse(sMaxListSyncDate, out dtMaxListSyncDate))
                     *      {
                     *          if (dtLogTime.CompareTo(dtMaxListSyncDate) > 0)
                     *          {
                     *              sMaxListSyncDate = dtLogTime.ToShortDateString() + " " + dtLogTime.ToLongTimeString();
                     *          }
                     *      }
                     *  }
                     * }
                     * //}
                     *
                     *
                     *
                     * if (sLogResult.Contains("Success") || sLogResult == "" || sLogResult.Contains("Processing"))
                     * {
                     *  sImg = "<img src=\"/_layouts/images/green.gif\" alt=\"\" >";
                     * }
                     * else
                     * {
                     *  sImg = "<img src=\"/_layouts/images/yellow.gif\" alt=\"\" >";
                     * }
                     */

                    DateTime dtLogTime;
                    if (DateTime.TryParse(sLogTime, out dtLogTime))
                    {
                        if (sMaxListSyncDate == "")
                        {
                            sMaxListSyncDate = dtLogTime.ToString();
                        }
                        else
                        {
                            DateTime dtMaxListSyncDate;
                            if (DateTime.TryParse(sLogTime, out dtLogTime) && DateTime.TryParse(sMaxListSyncDate, out dtMaxListSyncDate))
                            {
                                if (dtLogTime.CompareTo(dtMaxListSyncDate) > 0)
                                {
                                    sMaxListSyncDate = dtLogTime.ToShortDateString() + " " + dtLogTime.ToLongTimeString();
                                }
                            }
                        }
                    }
                }
            }


            cn.Close();

            //if (cntFields > 0) gvLists.PageSize = cntFields;
            gvLists.DataSource = dt;
            gvLists.DataBind();
        }
        public void ProcessRequest(HttpContext context)
        {
            //Debugger.Break();

            try
            {
                Parameters prms = new Parameters();

                TextReader tr         = new StreamReader(context.Request.InputStream);
                string     input      = tr.ReadToEnd();
                string[]   parameters = input.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

                tr.Close();
                context.Request.InputStream.Close();

                foreach (string s in parameters)
                {
                    string[] itms = s.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries);
                    if (itms.Length == 2)
                    {
                        string key   = itms[0].Trim(new char[] { '\r', '\n', '|' }).ToLower();
                        string value = itms[1].Trim(new char[] { '\r', '\n', '|' });
                        switch (key)
                        {
                        case "reflist":
                            prms.RefList = value;
                            break;

                        case "refsrcfield":
                            prms.RefSrcField = value;
                            break;

                        case "refdstfield":
                            prms.RefDstField = value;
                            break;

                        case "srctype":
                            prms.SrcType = value;
                            break;

                        case "dsttype":
                            prms.DstType = value;
                            break;

                        case "selection":
                            string[] selpart1 = value.Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries);
                            foreach (string selpart1i in selpart1)
                            {
                                string[] selpart2 = selpart1i.Split(new string[] { "%%" }, StringSplitOptions.RemoveEmptyEntries);
                                if (selpart2.Length == 2)
                                {
                                    prms.Selection.Add(new Selection(selpart2[0], selpart2[1]));
                                }
                                ;
                            }
                            ;
                            break;

                        case "dstselection":
                            string[] selpart3 = value.Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries);
                            foreach (string selpart3i in selpart3)
                            {
                                string[] selpart4 = selpart3i.Split(new string[] { "%%" }, StringSplitOptions.RemoveEmptyEntries);
                                if (selpart4.Length == 2)
                                {
                                    prms.DstSelection.Add(new Selection(selpart4[0], selpart4[1]));
                                }
                                ;
                            }
                            ;
                            break;
                        }
                    }
                    ;
                }
                ;

                if (prms.IsValid())
                {
                    if (SPContext.Current != null)
                    {
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            //Debugger.Break();

                            using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                            {
                                using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                                {
                                    SPList reflist = web.GetList(web.ServerRelativeUrl + (prms.RefList.StartsWith("/") ? "" : "/") + prms.RefList);
                                    if (reflist != null)
                                    {
                                        if (reflist.Fields.ContainsField(prms.RefDstField))
                                        {
                                            if (reflist.Fields.ContainsField(prms.RefSrcField))
                                            {
                                                List <string> ret    = new List <string>();
                                                List <string> selret = new List <string>();

                                                switch (prms.DstType)
                                                {
                                                case "0":
                                                    ret.Add(@"<option value=""0"">(none)</option>");
                                                    break;

                                                case "1":
                                                    ret.Add("(none)|0");
                                                    break;
                                                }
                                                ;

                                                SPQuery q = new SPQuery();

                                                if (prms.Selection.Count == 1)
                                                {
                                                    q.Query = "<Where><Eq><FieldRef Name=\"" + prms.RefSrcField + "\"/><Value Type=\"Lookup\">" + prms.Selection[0].Key + "</Value></Eq></Where>";
                                                }
                                                else
                                                {
                                                    string qq = "<Where><Or>";
                                                    foreach (Selection sel in prms.Selection)
                                                    {
                                                        qq += "<Eq><FieldRef Name=\"" + prms.RefSrcField + "\"/><Value Type=\"Lookup\">" + sel.Key + "</Value></Eq>";
                                                    }
                                                    qq     += "</Or></Where>";
                                                    q.Query = qq;
                                                };

                                                SPListItemCollection lic = reflist.GetItems(q);

                                                foreach (SPListItem li in lic)
                                                {
                                                    string val   = "";
                                                    string valID = "0";
                                                    if (!li.Fields.GetField(prms.RefDstField).TypeAsString.Equals("lookup", StringComparison.InvariantCultureIgnoreCase))
                                                    {
                                                        string valTmp = (string)li[prms.RefDstField];
                                                        if (valTmp.Contains(";#"))
                                                        {
                                                            string[] fl = ((string)li[prms.RefDstField]).Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                                                            val         = fl[1];
                                                        }
                                                        else
                                                        {
                                                            val = valTmp;
                                                        };
                                                        valID = li.ID.ToString();
                                                    }
                                                    else
                                                    {
                                                        string[] fl = ((string)li[prms.RefDstField]).Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                                                        val         = fl[1];
                                                        valID       = fl[0];
                                                    }

                                                    bool isSelected = false;
                                                    foreach (Selection sel in prms.DstSelection)
                                                    {
                                                        if (string.Compare(sel.Key, val, true) == 0)
                                                        {
                                                            isSelected = true;
                                                        }
                                                    }

                                                    switch (prms.DstType)
                                                    {
                                                    case "0":
                                                        ret.Add(string.Format(@"<option value=""{0}""{2}>{1}</option>", valID, val, (isSelected ? @" selected=""selected""" : "")));
                                                        break;

                                                    case "1":
                                                        ret.Add(string.Format(@"{0}|{1}", val, valID));
                                                        if (isSelected)
                                                        {
                                                            selret.Add(val);
                                                        }
                                                        break;
                                                    }
                                                    ;
                                                }
                                                ;

                                                TextWriter tw = new StreamWriter(context.Response.OutputStream);
                                                switch (prms.DstType)
                                                {
                                                case "0":
                                                    tw.Write(string.Join("\r\n", ret.ToArray()));
                                                    break;

                                                case "1":
                                                    tw.Write(string.Join("|", ret.ToArray()));
                                                    if (selret.Count > 0)
                                                    {
                                                        tw.Write("\n");
                                                        tw.Write(string.Join("|", selret.ToArray()));
                                                    }
                                                    break;
                                                }
                                                ;

                                                tw.Flush();
                                                tw.Close();
                                                context.Response.OutputStream.Close();
                                                return;
                                            }
                                            else
                                            {
                                                throw new Exception("Reference source field \"" + prms.RefSrcField + "\" not found.");
                                            }
                                        }
                                        else
                                        {
                                            throw new Exception("Reference destination field \"" + prms.RefDstField + "\" not found.");
                                        };
                                    }
                                    else
                                    {
                                        throw new Exception("Reference list \"" + prms.RefList + "\" not found.");
                                    }
                                };
                            };
                        });
                    }
                    else
                    {
                        throw new Exception("No valid SPContext!");
                    }
                }
                else
                {
                    throw new Exception("Parameters not valid");
                };
            }
            catch (Exception ex)
            {
                TextWriter tw = new StreamWriter(context.Response.OutputStream);
                tw.WriteLine("ERROR");
                tw.WriteLine(ex.Message);
                tw.Flush();
                tw.Close();
                context.Response.OutputStream.Close();
            }
        }
Пример #57
0
 /// <summary>
 /// Ensure the creation of a site-collection-specific lifetime scope (or reuse an existing one).
 /// Don't dispose this instance, as it is meant to live as long as the root app container.
 /// </summary>
 /// <param name="site">The current site collection</param>
 /// <returns>The current site-collection-specific lifetime scope</returns>
 public ILifetimeScope EnsureSiteScope(SPSite site)
 {
     return(this.EnsureSiteScopeInternal(site));
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            EPMLiveCore.Act act = new EPMLiveCore.Act(SPContext.Current.Web);

            int activation = act.CheckFeatureLicense(EPMLiveCore.ActFeature.WebParts);

            if (activation != 0)
            {
                pnlMain.Visible = false;
                pnlAct.Visible  = true;
                lblAct.Text     = act.translateStatus(activation);
                return;
            }

            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            try
            {
                string sLists = "";
                using (currWeb = SPContext.Current.Web)
                {
                    if (currWeb.CurrentUser.IsSiteAdmin)
                    {
                        sSiteUrl = (currWeb.ServerRelativeUrl == "/") ? "" : currWeb.ServerRelativeUrl;
                        siteid   = currWeb.Site.ID.ToString();
                        webid    = currWeb.ID.ToString();
                        //if (!IsPostBack)
                        {
                            SPSecurity.RunWithElevatedPrivileges(delegate()
                            {
                                if (currWeb.Properties.ContainsKey("EPMLiveSynchLists"))
                                {
                                    sLists = currWeb.Properties["EPMLiveSynchLists"];
                                }
                            });

                            ddlLists.Items.Clear();
                            foreach (SPList lst in currWeb.Lists)
                            {
                                if (!lst.Hidden)
                                {
                                    ListItem li = new ListItem(lst.Title, lst.ID.ToString());
                                    if (!sLists.Contains(lst.ID.ToString()))
                                    {
                                        ddlLists.Items.Add(li);
                                    }
                                }
                            }

                            SPList liTemplate = currWeb.Lists.TryGetList("Template Gallery");
                            if (liTemplate != null)
                            {
                                pnlTemplates.Visible = false;
                            }

                            if (Request["TrnxType"] != null && Request["TrnxType"].ToString() == "clear")
                            {
                                // clear Template ID property
                                currWeb.AllowUnsafeUpdates = true;

                                currWeb.Properties["EPMLiveTemplateID"] = ""; // clear
                                currWeb.Properties.Update();

                                currWeb.AllowUnsafeUpdates = false;

                                Response.Redirect(currWeb.Url + "/_layouts/epmlive/setsitetemplate.aspx");
                            }
                            else if (Request["TrnxType"] != null && Request["TrnxType"].ToString() == "set")
                            {
                                if (Request["TemplateID"] != null && Request["TemplateID"].ToString().Trim() != "")
                                {
                                    // update Template ID property
                                    currWeb.AllowUnsafeUpdates = true;

                                    currWeb.Properties["EPMLiveTemplateID"] = Request["TemplateID"].ToString(); // overwrite with new ID
                                    currWeb.Properties.Update();

                                    currWeb.AllowUnsafeUpdates = false;

                                    Response.Redirect(currWeb.Url + "/_layouts/epmlive/setsitetemplate.aspx");
                                }
                            }
                            else if (Request["TrnxType"] != null && Request["TrnxType"].ToString() == "add")
                            {
                                if (Request["List"] != null && Request["List"].ToString().Trim().Length != 0)
                                {
                                    AddList(Request["List"].ToString());
                                    Response.Redirect(currWeb.Url + "/_layouts/epmlive/templates.aspx");
                                }
                                else if (Request["TemplateID"] != null && Request["TemplateID"].ToString().Trim() != "")
                                {
                                    using (SPSite site = SPContext.Current.Site)
                                    {
                                        // add Template ID property
                                        Guid webGUID = new Guid(Request["TemplateID"].ToString());
                                        using (SPWeb oSelectedWeb = site.AllWebs[webGUID])
                                        {
                                            if (currWeb.ID != oSelectedWeb.ID)
                                            {
                                                oSelectedWeb.AllowUnsafeUpdates = true;

                                                string sGUID = System.Guid.NewGuid().ToString();
                                                if (!oSelectedWeb.Properties.ContainsKey("EPMLiveTemplateID"))
                                                {
                                                    oSelectedWeb.Properties.Add("EPMLiveTemplateID", sGUID);
                                                }
                                                else
                                                {
                                                    oSelectedWeb.Properties["EPMLiveTemplateID"] = sGUID;
                                                }
                                                oSelectedWeb.Properties.Update();

                                                using (SPWeb rootWeb = site.RootWeb)
                                                {
                                                    AddAsSynchedTemplate(rootWeb, Request["TemplateID"].ToString());
                                                }

                                                //SPFeature oFT = null;
                                                //try
                                                //{
                                                //    oFT = oSelectedWeb.Features[new Guid("dfb82bdd-a86c-4314-a0f2-654526c7814e")];
                                                //}
                                                //catch { }
                                                //if (oFT == null)
                                                //{
                                                //    try
                                                //    {
                                                //        oSelectedWeb.Features.Add(new Guid("dfb82bdd-a86c-4314-a0f2-654526c7814e"));
                                                //    }
                                                //    catch { }
                                                //}

                                                oSelectedWeb.AllowUnsafeUpdates = false;
                                            }
                                        }
                                    }

                                    Response.Redirect(currWeb.Url + "/_layouts/epmlive/templates.aspx");
                                }
                            }
                            else if (Request["TrnxType"] != null && Request["TrnxType"].ToString() == "delete")
                            {
                                if (Request["List"] != null && Request["List"].ToString().Trim() != "")
                                {
                                    SPSecurity.RunWithElevatedPrivileges(delegate()
                                    {
                                        DeleteList("|" + Request["List"].ToString());
                                    });
                                }
                                else if (Request["Template"] != null && Request["Template"].ToString().Trim() != "")
                                {
                                    SPSecurity.RunWithElevatedPrivileges(delegate()
                                    {
                                        RemoveTemplate(Request["Template"].ToString());
                                    });
                                }
                                Response.Redirect(currWeb.Url + "/_layouts/epmlive/templates.aspx");
                            }
                        }
                    }
                    else
                    {
                        Response.Redirect(currWeb.Url + "/_layouts/AccessDenied.aspx");
                    }

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        loadListGrid(sLists, currWeb.Site);
                        loadTemplateListBox();
                    });
                }
            }
            catch (Exception ex)
            {
                Response.Write("Error: " + ex.Message);
            }
        }
Пример #59
0
 private void BtnInstall_Click_1(object sender, EventArgs e)
 {
     try
     {
         if (MyConfiguration.DeploymentLevel != MyUtilities.DeploymentLevel.None)
         {
             this.Cursor = Cursors.WaitCursor;
             if (TxtUrl.Text.Trim() == "")
             {
                 this.Cursor = Cursors.Default;
                 MyUtilities.ShowDialog("Enter Site Url and then Press OK.", RadMessageIcon.Error);
                 TxtUrl.Focus();
                 return;
             }
             using (SPSite Site = new SPSite(TxtUrl.Text.Trim()))
             {
                 if (MyConfiguration.DeploymentLevel == MyUtilities.DeploymentLevel.Workspace)
                 {
                     CmbWeb.Items.Clear();
                     RadComboBoxItem item1 = new RadComboBoxItem();
                     item1.Text = "Root Web";
                     CmbWeb.Items.Add(item1);
                     foreach (SPWeb Web in Site.AllWebs)
                     {
                         if (!Web.IsRootWeb)
                         {
                             RadComboBoxItem item = new RadComboBoxItem();
                             item.Text  = Web.Title;
                             item.Value = Web.ID.ToString();
                             CmbWeb.Items.Add(item);
                         }
                     }
                     if (CmbWeb.Items.Count > 0)
                     {
                         CmbWeb.SelectedIndex = 0;
                     }
                     PnlConfiguration.Visible  = false;
                     PnlInstaller.Visible      = false;
                     PnlConfiguration2.Visible = true;
                     this.Height = PnlConfiguration2.Height + 25;
                     Application.DoEvents();
                     this.Cursor = Cursors.Default;
                 }
                 else
                 {
                     PnlConfiguration.Visible  = false;
                     PnlConfiguration2.Visible = false;
                     PnlInstaller.Visible      = true;
                     this.Height = PnlInstaller.Height + 25;
                     Application.DoEvents();
                     MyUtilities.UpdateStatus("Connecting to SharePoint Site ....", LblStatus);
                     MyConfiguration.StartInstallation(Site, Site.OpenWeb(), LblStatus);
                 }
             }
         }
         else
         {
             PnlConfiguration.Visible  = false;
             PnlConfiguration2.Visible = false;
             PnlInstaller.Visible      = true;
             this.Height = PnlInstaller.Height + 25;
             Application.DoEvents();
             MyUtilities.UpdateStatus("Initializing ...", LblStatus);
             MyConfiguration.StartInstallation(null, null, LblStatus);
         }
     }
     catch (Exception ex)
     {
         this.Cursor = Cursors.Default;
         MyUtilities.ShowDialog(ex.Message, RadMessageIcon.Error);
     }
 }
Пример #60
0
        /// <summary>
        /// Get catalog's items. All items when parameter is 0.
        /// </summary>
        /// <param name="itemId">ID of the especific item.</param>
        /// <param name="order">Order type of the results.</param>
        /// <returns></returns>
        internal static List <CatalogItem> GetCatalog(int itemId, string orderBy, bool isAscending)
        {
            List <CatalogItem> catalog = new List <CatalogItem>();

            #region SharePoint query
            SPListItemCollection queriedCatalog = null;
            SPListItem           queriedItem    = null;

            using (SPSite sps = new SPSite(SPContext.Current.Web.Url))
                using (SPWeb spw = sps.OpenWeb())
                {
                    if (itemId == 0)
                    {
                        string ascending = isAscending ? "" : "Ascending='FALSE'";

                        SPQuery query = new SPQuery();
                        query.Query = string.Format(
                            "<OrderBy><FieldRef Name='{0}' {1} /></OrderBy>" +
                            "<Where><Eq><FieldRef Name='_ModerationStatus' /><Value Type='ModStat'>0</Value></Eq></Where>",
                            orderBy, ascending);

                        queriedCatalog = spw.Lists[LIST_CATALOG].GetItems(query);
                    }
                    else
                    {
                        queriedItem = spw.Lists[LIST_CATALOG].GetItemById(itemId);
                    }
                }
            #endregion

            if (queriedItem != null)
            {
                int      id            = queriedItem.ID;
                string   title         = queriedItem.Title;
                string   description   = queriedItem["Descripci_x00f3_n"].ToString();
                string   image         = FormatedUrl(queriedItem["Imagen_x0020_referencia"].ToString());
                int      points        = Convert.ToInt32(queriedItem["Puntos"]);
                bool     isNew         = Convert.ToBoolean(queriedItem["Nuevo"]);
                string[] categoryArray = StringArrayTwo(queriedItem["Categor_x00ed_a0"]);
                int      categoryId    = Convert.ToInt32(categoryArray[0]);
                string   category      = categoryArray[1];
                string   brand         = queriedItem["Marca"].ToString();
                string   region        = queriedItem["Sucursal"].ToString();

                catalog.Add(new CatalogItem(id, title, description, image, points, isNew, category, categoryId, brand, region, "catalog"));
            }
            else
            {
                foreach (SPListItem item in queriedCatalog)
                {
                    int      id            = item.ID;
                    string   title         = item.Title;
                    string   description   = item["Descripci_x00f3_n"].ToString();
                    string   image         = FormatedUrl(item["Imagen_x0020_referencia"].ToString());
                    int      points        = Convert.ToInt32(item["Puntos"]);
                    bool     isNew         = Convert.ToBoolean(item["Nuevo"]);
                    string[] categoryArray = StringArrayTwo(item["Categor_x00ed_a0"]);
                    int      categoryId    = Convert.ToInt32(categoryArray[0]);
                    string   category      = categoryArray[1];
                    string   brand         = item["Marca"].ToString();
                    string   region        = item["Sucursal"].ToString();

                    catalog.Add(new CatalogItem(id, title, description, image, points, isNew, category, categoryId, brand, region, "catalog"));
                }
            }

            return(catalog);
        }