// Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPContext.Current.Web.AllowUnsafeUpdates = true;

                SPAdministrationWebApplication caWebApp = SPAdministrationWebApplication.Local;
                //Delete any existing jobs
                string jobName = "Check License";
                foreach (SPJobDefinition job in caWebApp.JobDefinitions)
                {
                    if (job.Name.ToUpper().Equals(jobName.ToUpper()))
                    {
                        job.Delete();
                    }
                }

                //Schedule new job
                SPMonthlySchedule schedule4 = new SPMonthlySchedule();
                schedule4.BeginDay  = 1;
                schedule4.EndDay    = 1;
                schedule4.BeginHour = 2;
                schedule4.EndHour   = 6;
                LicenseChecker newJob4 = new LicenseChecker(jobName, caWebApp);
                newJob4.Schedule = schedule4;
                newJob4.Update();
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
            }
        }
コード例 #2
0
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPAdministrationWebApplication centralWeb = SPAdministrationWebApplication.Local;
            SPSite caSite = centralWeb.Sites[0];
            SPWeb  caWeb  = caSite.RootWeb;


            Guid featureID2010 = new Guid("61b45a0f-5a98-4353-aec3-9ff6791468c3");
            Guid featureID2007 = new Guid("5c87f143-910f-4bde-a0c0-a474f8813880");

            if (SPFarm.Local.BuildVersion >= new Version("14.0.0.0"))
            {
                if (caWeb.Features[featureID2010] == null)
                {
                    caWeb.Features.Add(featureID2010);
                }
                // SP2010 mode
            }
            else
            {
                // SP2007 mode
                if (caWeb.Features[featureID2007] == null)
                {
                    caWeb.Features.Add(featureID2007);
                }
            }
        }
コード例 #3
0
        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


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

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            SPAdministrationWebApplication adminWebApp = SPAdministrationWebApplication.Local;

            using (SPSite siteCollection = new SPSite(adminWebApp.Sites[0].Url))
            {
                using (SPWeb site = siteCollection.OpenWeb())
                {
                    SPList list = site.Lists.TryGetList("Nauplius.ADLDS.UserProfiles - GlobalSettings");
                    if (list != null)
                    {
                        try
                        {
                            list.Delete();
                        }
                        catch (Exception)
                        { }
                    }

                    SPList list2 = site.Lists.TryGetList("Nauplius.ADLDS.UserProfiles - WebAppSettings");
                    if (list2 != null)
                    {
                        try
                        {
                            list2.Delete();
                        }
                        catch (Exception)
                        { }
                    }
                }
            }
        }
        private static WebTemplateInfo[] GetWebTemplates(ISharePointCommandContext context)
        {
            context.Logger.WriteLine(Resources.WebTemplateSharePointCommands_TryingToRetrieveAvailableWebTemplates, LogCategory.Status);

            List <WebTemplateInfo> webTemplateInfos = new List <WebTemplateInfo>();

            try
            {
                SPSite caSite  = null;
                SPWeb  rootWeb = null;

                if (context.Site == null)
                {
                    //Do this as from item templates the site is always null
                    SPAdministrationWebApplication caWebApp = SPAdministrationWebApplication.Local;
                    caSite  = caWebApp.Sites[0];
                    rootWeb = caSite.RootWeb;
                }
                else
                {
                    caSite  = context.Site;
                    rootWeb = context.Web;
                }

                SPWebTemplateCollection webTemplates = caSite.GetWebTemplates((uint)rootWeb.Locale.LCID);

                foreach (SPWebTemplate item in webTemplates)
                {
                    //Check the temaplate is a site defintion and has a display category
                    if (!String.IsNullOrEmpty(item.DisplayCategory) && !item.IsCustomTemplate)
                    {
                        WebTemplateInfo info = new WebTemplateInfo();

                        info.Id               = item.ID;
                        info.ImageUrl         = item.ImageUrl;
                        info.Name             = item.Name;
                        info.Description      = item.Description;
                        info.DisplayCategory  = item.DisplayCategory;
                        info.IsCustomTemplate = item.IsCustomTemplate;
                        info.IsHidden         = item.IsHidden;
                        info.IsRootWebOnly    = item.IsRootWebOnly;
                        info.IsSubWebOnly     = item.IsSubWebOnly;
                        info.Lcid             = item.Lcid;
                        info.Title            = item.Title;
                        info.SetupPath        = typeof(SPWebTemplate).InvokeMember("SetupPath", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetProperty, null, item, null) as string;

                        webTemplateInfos.Add(info);
                    }
                }
            }
            catch (Exception ex)
            {
                context.Logger.WriteLine(String.Format(Resources.WebTemplateSharePointCommands_RetrievingException,
                                                       ex.Message,
                                                       Environment.NewLine,
                                                       ex.StackTrace), LogCategory.Error);
            }

            return(webTemplateInfos.ToArray());
        }
コード例 #5
0
        private void AttributeMapping()
        {
            SPAdministrationWebApplication adminWebApp = SPAdministrationWebApplication.Local;

            using (SPSite siteCollection = new SPSite(adminWebApp.Sites[0].Url))
            {
                using (SPWeb site = siteCollection.OpenWeb())
                {
                    SPList list = site.Lists.TryGetList("Nauplius.ADLDS.UserProfiles - GlobalSettings");
                    if (list != null)
                    {
                        if (list.ItemCount >= 1)
                        {
                            foreach (SPListItem item in list.Items)
                            {
                                if (item["GlobalDefault"].ToString() == "GlobalDefaultValues")
                                {
                                    DepartmentAttrib    = item["Department"].ToString();
                                    FirstNameAttrib     = item["FirstName"].ToString();
                                    LastNameAttrib      = item["LastName"].ToString();
                                    OfficeAttrib        = item["Office"].ToString();
                                    PreferredNameAttrib = item["PreferredName"].ToString();
                                    UserTitleAttrib     = item["UserTitle"].ToString();
                                    WebSiteAttrib       = item["WebSite"].ToString();
                                    WorkEmailAttrib     = item["WorkEmail"].ToString();
                                    WorkPhoneAttrib     = item["WorkPhone"].ToString();
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #6
0
        public static SPListItem GetClaimProvider(SPWebApplication webApp, SPUrlZone zone)
        {
            SPAdministrationWebApplication adminWebApp = SPAdministrationWebApplication.Local;

            using (SPSite siteCollection = new SPSite(adminWebApp.Sites[0].Url))
            {
                using (SPWeb site = siteCollection.OpenWeb())
                {
                    SPList list = site.Lists.TryGetList("Nauplius.ADLDS.FBA - WebApplicationSettings");
                    if (list != null)
                    {
                        if (list.ItemCount >= 1)
                        {
                            foreach (SPListItem item in list.Items)
                            {
                                if (item["WebApplicationUrl"].ToString() == webApp.GetResponseUri(zone).AbsoluteUri)
                                {
                                    return(item);
                                }
                            }
                        }
                    }
                }
            }
            return(null);
        }
コード例 #7
0
        public static void RemoveAllAdminModifications(SPAdministrationWebApplication adminWebApp, List <string> names)
        {
            var modifications = new List <SPWebConfigModification>();

            foreach (SPWebConfigModification modification in adminWebApp.WebConfigModifications)
            {
                if (modification.Owner == ModificationOwner)
                {
                    modifications.Add(modification);
                }
            }

            foreach (SPWebConfigModification modification in modifications)
            {
                foreach (string name in names)
                {
                    if (modification.Name == name)
                    {
                        adminWebApp.WebConfigModifications.Remove(modification);
                    }
                }
            }

            adminWebApp.Update();
        }
コード例 #8
0
        public static SPWebApplicationCollection GetAllWebApps()
        {
            // all the content WebApplications
            SPWebApplicationCollection     webapps      = SPWebService.ContentService.WebApplications;
            SPAdministrationWebApplication centralAdmin = SPAdministrationWebApplication.Local;

            webapps.Add(centralAdmin);
            return(webapps);
        }
コード例 #9
0
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPFarm local = SPFarm.Local;

            var services = from s in local.Services
                           where s.Name == "SPTimerV4"
                           select s;

            var service = services.First();

            foreach (SPJobDefinition job in service.JobDefinitions)
            {
                if (job.Name == tJobName)
                {
                    job.Delete();
                }
            }

            var newTimerJob = new STSSyncMonitor(tJobName, service);

            newTimerJob.IsDisabled = true;
            newTimerJob.Schedule   = new SPYearlySchedule();
            newTimerJob.Update();

            //build the Master XML Fragment
            SPAdministrationWebApplication adminWebApp = SPAdministrationWebApplication.Local;

            using (var siteCollection = new SPSite(adminWebApp.Sites[0].Url))
            {
                using (var site = siteCollection.OpenWeb())
                {
                    SPList list = site.Lists.TryGetList("Nauplius.ADLDS.FBA - StsFarm");
                    if (list == null)
                    {
                        return;
                    }
                    if (list.ItemCount == 0)
                    {
                        var path   = SPUtility.GetGenericSetupPath(@"WebServices\SecurityToken\web.config");
                        var config = new XmlDocument();
                        config.Load(path);

                        XmlNode systemwebChild =
                            config.SelectSingleNode("configuration/system.web");

                        if (systemwebChild != null)
                        {
                            SPListItem item = list.Items.Add();
                            item["StsConfig"]    = "MasterXmlFragment";
                            item["XMLStsConfig"] = systemwebChild.OuterXml;
                            item.Update();
                        }
                    }
                }
            }
        }
コード例 #10
0
        /// <summary>
        /// Runs the specified command.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <param name="keyValues">The key values.</param>
        /// <param name="output">The output.</param>
        /// <returns></returns>
        public override int Execute(string command, System.Collections.Specialized.StringDictionary keyValues,
                                    out string output)
        {
            output = string.Empty;

            Uri uri = new Uri(Params["url"].Value);

            SPWebApplicationBuilder builder = GetWebAppBuilder(uri);

            SPWebApplication app = builder.Create();

            SPAdministrationWebApplication local = SPAdministrationWebApplication.Local;

            // Set the TimeZone of the Application
            if (Params["timezone"].UserTypedIn)
            {
                app.DefaultTimeZone = ushort.Parse(Params["timezone"].Value);
            }

            app.Update();
            app.ProvisionGlobally();

            // Execute pending timer jobs before moving on.
            Common.TimerJobs.ExecAdmSvcJobs.Execute(false, true);
            // Recreate the web application object to avoid update conflicts.
            app = SPWebApplication.Lookup(uri);

            // Upload the newly created WebApplication to the List 'Web Application List' in Central Administration:
            SPWebService.AdministrationService.WebApplications.Add(app);

            if (!Params["donotcreatesite"].UserTypedIn)
            {
                uint   nLCID       = uint.Parse(Params["lcid"].Value);
                string webTemplate = Params["sitetemplate"].Value;
                string ownerLogin  = Params["ownerlogin"].Value;
                ownerLogin = Utilities.TryGetNT4StyleAccountName(ownerLogin, app);
                string ownerName  = Params["ownername"].Value;
                string ownerEmail = Params["owneremail"].Value;

                app.Sites.Add(uri.AbsolutePath, null, null, nLCID, webTemplate, ownerLogin, ownerName, ownerEmail, null, null, null);
            }


            Console.WriteLine(SPResource.GetString("PendingRestartInExtendWebFarm", new object[0]));
            Console.WriteLine();

            if (!Params["donotcreatesite"].UserTypedIn)
            {
                Console.WriteLine(SPResource.GetString("AccessSiteAt", new object[] { uri.ToString() }));
            }
            Console.WriteLine();

            return((int)ErrorCodes.NoError);
        }
コード例 #11
0
        /// <summary>
        /// TODO: Add comment
        /// </summary>
        /// <param name="sender">Sender of the event</param>
        /// <param name="e">Arguments of the event</param>
        private void BtnOk_Click(object sender, EventArgs e)
        {
            this.TxtInput.Text = "Ok clicked";
            SPAdministrationWebApplication caWebApp = SPAdministrationWebApplication.Local;
            //Delete any existing jobs
            string jobName = "Check License";

            foreach (SPJobDefinition job in caWebApp.JobDefinitions)
            {
                if (job.Name.ToUpper().Equals(jobName.ToUpper()))
                {
                    job.RunNow();
                }
            }
        }
コード例 #12
0
        public ArtDevBCS(string ModelName)
        {
            this.ModelName = ModelName;
            // Get the Catalog for the SharePoint site
            BdcService service = SPFarm.Local.Services.GetValue <BdcService>(String.Empty);
            SPAdministrationWebApplication centralWeb = SPAdministrationWebApplication.Local;
            SPSite           AdminSite = new SPSite(centralWeb.Sites.FirstOrDefault <SPSite>().Url);
            SPServiceContext context   = SPServiceContext.GetContext(AdminSite);

            this.catalog =
                service.GetAdministrationMetadataCatalog(context);

            this.catalog.GetModels(ModelName)?.ToList().ForEach(m => m.Delete());
            // Create a new Model
            // NOTE: Assume that the "ModelName" Model
            // does not already exist.
            this.Model = Model.Create(ModelName, true, catalog);
        }
コード例 #13
0
        protected override void OnInit(EventArgs e)
        {
            SPAdministrationWebApplication centralAdmin = SPAdministrationWebApplication.Local;
            SPWebApplication currentApp = SPContext.Current.Site.WebApplication;

            if (currentApp.Id != centralAdmin.Id)
            {
                // Wrong web app, redirect.
                string url = centralAdmin.Sites[0].Url;
                if (url == "/")
                {
                    url = "";
                }
                string source = HttpContext.Current.Request.Url.AbsoluteUri;
                targetWebURL = HttpUtility.UrlEncode(source);
                url         += "/_layouts/SPSIN/Store/";
                installerURL = url;

                url          += "StoreFront.aspx?SourceURL=";
                installerURL += "install.aspx?SourceURL=";

                Uri referrer = HttpContext.Current.Request.UrlReferrer;
                if (referrer != null)
                {
                    url          += referrer.ToString();
                    installerURL += referrer.ToString();
                }
                else
                {
                    url          += HttpUtility.UrlEncode(source);
                    installerURL += HttpUtility.UrlEncode(source);
                }
                //Response.Redirect(url, true);
            }


            if (Page.IsPostBack)
            {
                SPUtility.ValidateFormDigest();
            }
            //            stores = SPSINStoreUtilities.LoadPackageRepositories(SPContext.Current.Web);
            base.OnInit(e);
        }
        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPContext.Current.Web.AllowUnsafeUpdates = true;
                SPAdministrationWebApplication caWebApp = SPAdministrationWebApplication.Local;
                //Delete any existing jobs
                string jobName = "Check License";
                foreach (SPJobDefinition job in caWebApp.JobDefinitions)
                {
                    if (job.Name.ToUpper().Equals(jobName.ToUpper()))
                    {
                        job.Delete();
                    }
                }
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
            }
        }
コード例 #15
0
ファイル: SecureStoreAccess.cs プロジェクト: johnsonpace/home
        private static SPSite GetCentralAdminSite()
        {
            SPAdministrationWebApplication adminWebApp = SPAdministrationWebApplication.Local;

            if (adminWebApp == null)
            {
                throw new InvalidProgramException("Unable to get the admin web app");
            }

            SPSite adminSite    = null;
            Uri    adminSiteUri = adminWebApp.GetResponseUri(SPUrlZone.Default);

            if (adminSiteUri != null)
            {
                adminSite = adminWebApp.Sites[adminSiteUri.AbsoluteUri];
            }
            else
            {
                throw new InvalidProgramException("Unable to get Central Admin Site.");
            }

            return(adminSite);
        }
コード例 #16
0
        private static void ModifyAdminWebConfig(SPAdministrationWebApplication adminWebApp, string modificationName, string modificationPath,
                                                 string modificationValue, SPWebConfigModification.SPWebConfigModificationType modificationType)
        {
            SPWebConfigModification modification = new SPWebConfigModification(modificationName, modificationPath);

            modification.Value    = modificationValue;
            modification.Sequence = 0;
            modification.Type     = modificationType;
            modification.Owner    = ModificationOwner;

            try
            {
                adminWebApp.WebConfigModifications.Add(modification);
                adminWebApp.Update();
            }
            catch (Exception ex)
            {
                EventLog eventLog = new EventLog();
                eventLog.Source = ModificationOwner;
                eventLog.WriteEntry(ex.Message);
                throw ex;
            }
        }
コード例 #17
0
        private void sendEmail(string sUserEmail, string sFromEmail, string sSubject, string sUserDisplayName)
        {
            string sMailSvr = "";

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPAdministrationWebApplication spWebAdmin = Microsoft.SharePoint.Administration.SPAdministrationWebApplication.Local;
                    sMailSvr = spWebAdmin.OutboundMailServiceInstance.Server.Name;

                    using (var mailMsg = new MailMessage())
                    {
                        mailMsg.From = new MailAddress(sFromEmail);
                        mailMsg.To.Add(new MailAddress(sUserEmail));
                        mailMsg.Subject      = sSubject;
                        mailMsg.Body         = createMsgBody(sUserDisplayName);
                        mailMsg.IsBodyHtml   = true;
                        mailMsg.BodyEncoding = Encoding.UTF8;
                        mailMsg.Priority     = MailPriority.Normal;

                        using (var smtpClient = new SmtpClient
                        {
                            Host = sMailSvr
                        })
                        {
                            smtpClient.Send(mailMsg);
                        }
                    }
                });
            }
            catch (Exception exc)
            {
                logException("NotificationListsJob.sendEmail", exc.Message, " Email address: " + sUserEmail + " Mail Server: " + sMailSvr);
            }
        }
コード例 #18
0
        public override void Execute(Guid targetInstanceId)
        {
            Logging.LogMessage(900, Logging.LogCategories.TimerJob, TraceSeverity.Medium, "Entering " + tJobName, new object[] { null });

            SPAdministrationWebApplication adminWebApp = SPAdministrationWebApplication.Local;

            using (SPSite siteCollection = new SPSite(adminWebApp.Sites[0].Url))
            {
                using (SPWeb site = siteCollection.OpenWeb())
                {
                    SPList list = site.Lists.TryGetList("Nauplius.ADLDS.UserProfiles - GlobalSettings");
                    if (list != null)
                    {
                        if (list.ItemCount >= 1)
                        {
                            foreach (SPListItem item in list.Items)
                            {
                                if (item["GlobalDefault"].ToString() == "GlobalDefaultValues")
                                {
                                    ClaimsIdentifier    = item["ClaimsIdentifier"].ToString();
                                    LDAPFilter          = item["LDAPFilter"].ToString();
                                    DeleteProfiles      = (bool)item["DeleteProfiles"];
                                    DepartmentAttrib    = item["Department"].ToString();
                                    FirstNameAttrib     = item["FirstName"].ToString();
                                    LastNameAttrib      = item["LastName"].ToString();
                                    OfficeAttrib        = item["Office"].ToString();
                                    PreferredNameAttrib = item["PreferredName"].ToString();
                                    UserTitleAttrib     = item["UserTitle"].ToString();
                                    WebSiteAttrib       = item["WebSite"].ToString();
                                    WorkEmailAttrib     = item["WorkEmail"].ToString();
                                    WorkPhoneAttrib     = item["WorkPhone"].ToString();
                                }
                            }
                        }
                    }

                    SPList list2 = site.Lists.TryGetList("Nauplius.ADLDS.FBA - WebApplicationSettings");
                    if (list2 != null)
                    {
                        if (list2.ItemCount >= 1)
                        {
                            foreach (SPListItem item in list2.Items)
                            {
                                WebApplication        = SPWebApplication.Lookup(new Uri(item["WebApplicationUrl"].ToString()));
                                ServerName            = item["ADLDSServer"].ToString();
                                PortNumber            = Convert.ToInt32(item["ADLDSPort"].ToString());
                                DistinguishedNameRoot = item["ADLDSUserContainer"].ToString();
                                UseSSL         = (bool)item["ADLDSUseSSL"];
                                LoginAttribute = item["ADLDSLoginAttrib"].ToString();
                                var            zone = GetZone(item);
                                DirectoryEntry de   = DirEntry(ServerName, PortNumber, DistinguishedNameRoot);

                                if (de != null)
                                {
                                    SearchResultCollection results = ResultCollection(de);

                                    Create(results, LoginAttribute, WebApplication, ServerName, PortNumber, zone);

                                    if (DeleteProfiles)
                                    {
                                        Delete(results, LoginAttribute, WebApplication, ServerName, PortNumber, zone);
                                    }
                                }
                            }

                            Logging.LogMessage(901, Logging.LogCategories.TimerJob, TraceSeverity.Medium, "Exiting " + tJobName, new object[] { null });
                        }
                    }
                }
            }
        }
コード例 #19
0
        public SPLicense.LicenseFile.SPLicenseFile GetLicense(Type type, object instance, bool allowExceptions)
        {
            try
            {
                TestLicense   test    = new TestLicense();
                SPLicenseFile license = test.Create(type, instance, allowExceptions);
                string        key     = new Guid("7F3A08D4-7308-4142-A1DF-DF705136D0A8").ToString();

                SPAdministrationWebApplication centralWebApp = SPAdministrationWebApplication.Local;
                SPSite lowSite = centralWebApp.Sites[0];

                SPUserToken oSysToken = GetSysToken(lowSite.ID);
                using (SPSite centralSite = new SPSite(lowSite.ID, oSysToken))
                {
                    centralSite.AllowUnsafeUpdates = true;


                    using (SPWeb centralWeb = centralSite.OpenWeb())
                    {
                        bool     availableList = true;
                        SPFile   licenseFile   = null;
                        SPFolder licenseFolder = null;

                        centralWeb.AllowUnsafeUpdates = true;
                        try
                        {
                            SPList            LicenseList    = centralWeb.Lists["Hemrika License Files"];
                            SPDocumentLibrary LicenseLibrary = (SPDocumentLibrary)LicenseList;
                            licenseFolder = centralWeb.Folders["Hemrika License Files"];


                            /*
                             * if (!Farmbag.Contains("Hemrika_Encryption_Key"))
                             * {
                             *  Farmbag["Hemrika_Encryption_Key"] = new Guid("7F3A08D4-7308-4142-A1DF-DF705136D0A8").ToString();
                             * }
                             *
                             * encrypt = Farmbag["Hemrika_Encryption_Key"];
                             */

                            SPQuery oQuery = new SPQuery();
                            oQuery.Query = string.Format("<Where><Contains><FieldRef Name=\"FileLeafRef\" /><Value Type=\"File\">" + type.Assembly.FullName + "</Value></Contains></Where><OrderBy><FieldRef Name=\"FileLeafRef\" /></OrderBy>");
                            SPListItemCollection colListItems = LicenseLibrary.GetItems(oQuery);

                            foreach (SPListItem licenseItem in colListItems)
                            {
                                licenseFile = licenseItem.File;
                                break;
                            }
                        }
                        catch (Exception)
                        {
                            availableList = false;
                        }

                        MemoryStream lic = null; //= new MemoryStream();
                        XmlDocument  xml = new XmlDocument();

                        if (licenseFile == null)
                        {
                            lic = new MemoryStream();
                            xml.LoadXml(license.ToXmlString());

                            SPLicenseFile.SaveFile(license, lic, false, String.Empty, false);

                            if (availableList && licenseFolder != null)
                            {
                                licenseFile = licenseFolder.Files.Add(type.Assembly.FullName + ".lic", lic, true);

                                licenseFile.Update();
                                licenseFile.Item.Update();
                            }
                        }

                        if (lic != null)
                        {
                            lic.Close();
                            //lic.Dispose();
                        }

                        if (licenseFile != null)
                        {
                            //byte[] bytes = licenseFile.OpenBinary();
                            //lic = new MemoryStream();
                            //lic.Read(bytes, 0, bytes.Length);

                            license = SPLicenseFile.LoadFile(licenseFile.OpenBinaryStream(), type, false, String.Empty);// true, key);
                        }

                        /*
                         * if (lic != null)
                         * {
                         *  lic.Close();
                         *  //lic.Dispose();
                         * }
                         */
                        centralWeb.AllowUnsafeUpdates = false;
                    }
                    centralSite.AllowUnsafeUpdates = false;
                }

                return(license);
            }
            catch (Exception ex)
            {
                throw new LicenseException(type, instance, ex.Message, ex);
            }
        }
コード例 #20
0
        public override SPHealthCheckStatus Check()
        {
            if (!SPFarm.Joined)
            {
                throw new InvalidOperationException();
            }

            SPAdministrationWebApplication adminWebApp = SPAdministrationWebApplication.Local;

            try
            {
                var lists = new Lists
                {
                    Url         = adminWebApp.Sites[0].Url + "/_vti_bin/Lists.asmx",
                    Credentials = CredentialCache.DefaultNetworkCredentials
                };

                var        document   = new XmlDocument();
                XmlElement query      = document.CreateElement("Query");
                XmlElement viewFields = document.CreateElement("ViewFields");

                query.InnerXml =
                    "<Query><Where><And><BeginsWith><FieldRef Name='Title'></FieldRef><Value Type='Text'>MasterXmlFragment</Value></BeginsWith><IsNotNull><FieldRef Name='Title'></FieldRef></IsNotNull></And></Where></Query>";
                viewFields.InnerXml = "<FieldRef Name='XMLStsConfig' />";

                var listItem = lists.GetListItems(_listName, null, query, viewFields, _rowLimit, null, null);

                foreach (XmlNode node in listItem)
                {
                    if (node.Name == "rs:data")
                    {
                        for (int i = 0; i < node.ChildNodes.Count; i++)
                        {
                            if (node.ChildNodes[i].Name == "z:row")
                            {
                                MasterXmlFragment.LoadXml(node.ChildNodes[i].Attributes["ows_XMLStsConfig"].Value);

                                if (MasterXmlFragment == null)
                                {
                                    Logging.LogMessage(902, Logging.LogCategories.Health, TraceSeverity.Verbose,
                                                       "AD LDS/ADAM Forms Based Authentication not configured.",
                                                       new object[] { null });
                                    return(SPHealthCheckStatus.Passed);
                                }

                                string path   = SPUtility.GetGenericSetupPath(@"WebServices\SecurityToken\web.config");
                                var    config = new XmlDocument();
                                config.Load(path);

                                XmlNode xmlNode = config.SelectSingleNode("configuration/system.web");

                                if (xmlNode != null && MasterXmlFragment.OuterXml != xmlNode.OuterXml)
                                {
                                    Logging.LogMessage(901, Logging.LogCategories.Health, TraceSeverity.Unexpected,
                                                       "SharePoint Server {0} does not match master Security Token Service configuration.",
                                                       new object[] { SPServer.Local.DisplayName });
                                    return(SPHealthCheckStatus.Failed);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                Logging.LogMessage(903, Logging.LogCategories.Health,
                                   TraceSeverity.Unexpected,
                                   "Error calling Lists SOAP service {0}.",
                                   new object[] { SPServer.Local.DisplayName });
                return(SPHealthCheckStatus.Failed);
            }

            return(SPHealthCheckStatus.Passed);
        }
コード例 #21
0
        protected override void CreateChildControls()
        {
            // Show only to farm administrators?

            SPContext currentContext = SPContext.Current;

            if (currentContext != null)
            {
                try
                {
                    bool storeActivated = false;

                    // If in central admin, or elsewhere outside web, check for target web SP SIN Store activation
                    HttpRequest Request = HttpContext.Current.Request;

                    if (Request["SourceURL"] != null && !string.IsNullOrEmpty(Request["SourceURL"]))
                    {
                        using (SPSite site = new SPSite(Request["SourceURL"]))
                        {
                            using (SPWeb targetWeb = site.OpenWeb())
                            {
                                if (targetWeb.Features[new Guid("7e39c867-dcb9-456e-8017-a117d845ed03")] != null)
                                {
                                    storeActivated = true;
                                }
                            }
                        }
                    }
                    else if (currentContext.Web.Features[new Guid("7e39c867-dcb9-456e-8017-a117d845ed03")] != null)
                    {
                        storeActivated = true;
                    }
                    // SP SIN Store activated, show link
                    SPAdministrationWebApplication centralAdmin = SPAdministrationWebApplication.Local;

                    string url = centralAdmin.Sites[0].Url;
                    if (url == "/")
                    {
                        url = "";
                    }

                    HyperLink link = new HyperLink();

                    link.Text        = "SP SIN App Store";
                    link.NavigateUrl = url + "/_layouts/SPSIN/Store/StoreFront.aspx";
                    link.Enabled     = false;

                    if (storeActivated)
                    {
                        string source = HttpContext.Current.Request.Url.AbsoluteUri;
                        link.NavigateUrl += "?SourceURL=" + HttpUtility.UrlEncode(source);
                        link.Enabled      = true;
                    }
                    Controls.Add(link);

                    if (!storeActivated)
                    {
                        Controls.Add(new LiteralControl("<br />"));
                        Label inactivateLabel = new Label();
                        inactivateLabel.Text        = "SP SIN Store feature not activated. Activate from Site Settings->Site Features to enable link";
                        inactivateLabel.ForeColor   = Color.DarkGray;
                        inactivateLabel.Font.Italic = true;
                        Controls.Add(inactivateLabel);
                    }
                }
                catch
                {
                }
            }

            if (HttpContext.Current != null)
            {
                HttpRequest Request = HttpContext.Current.Request;
                if (Request["SourceURL"] != null && !string.IsNullOrEmpty(Request["SourceURL"]))
                {
                    string source = HttpUtility.UrlDecode(Request["SourceURL"]);
                    Controls.Add(new LiteralControl("<br />\n"));
                    HyperLink link = new HyperLink();
                    link.Text        = "Back";
                    link.NavigateUrl = source;
                    Controls.Add(link);
                }
            }
        }
コード例 #22
0
        private static void iSendEmail(int templateid, bool hidefrom, Guid siteid, Guid webid, SPUser curUser, SPUser eUser, Hashtable additionalParams)
        {
            try
            {
                if (eUser.Email != "")
                {
                    try
                    {
                        using (SPSite site = new SPSite(siteid))
                        {
                            try
                            {
                                using (SPWeb web = site.OpenWeb(webid))
                                {
                                    try
                                    {
                                        string body    = "";
                                        string subject = "";

                                        SqlConnection cn = new SqlConnection(CoreFunctions.getConnectionString(site.WebApplication.Id));
                                        cn.Open();

                                        GetCoreInformation(cn, templateid, out body, out subject, web, curUser);


                                        cn.Close();

                                        foreach (string s in additionalParams.Keys)
                                        {
                                            body    = body.Replace("{" + s + "}", additionalParams[s].ToString());
                                            subject = subject.Replace("{" + s + "}", additionalParams[s].ToString());
                                        }

                                        SPAdministrationWebApplication spWebAdmin = Microsoft.SharePoint.Administration.SPAdministrationWebApplication.Local;
                                        string sMailSvr = spWebAdmin.OutboundMailServiceInstance.Server.Address;

                                        System.Net.Mail.MailMessage mailMsg = new MailMessage();
                                        if (hidefrom)
                                        {
                                            mailMsg.From = new MailAddress(spWebAdmin.OutboundMailSenderAddress);
                                        }
                                        else
                                        {
                                            if (curUser.Email == "")
                                            {
                                                mailMsg.From = new MailAddress(spWebAdmin.OutboundMailSenderAddress, curUser.Name);
                                            }
                                            else
                                            {
                                                mailMsg.From = new MailAddress(curUser.Email, curUser.Name);
                                            }
                                        }

                                        body = body.Replace("{ToUser_Name}", eUser.Name);
                                        body = body.Replace("{ToUser_Email}", eUser.Email);
                                        body = body.Replace("{ToUser_Username}", CoreFunctions.GetJustUsername(eUser.LoginName));

                                        subject = subject.Replace("{ToUser_Name}", eUser.Name);
                                        subject = subject.Replace("{ToUser_Email}", eUser.Email);
                                        subject = subject.Replace("{ToUser_Username}", CoreFunctions.GetJustUsername(eUser.LoginName));

                                        mailMsg.To.Add(new MailAddress(eUser.Email));
                                        mailMsg.Subject    = subject;
                                        mailMsg.Body       = body;
                                        mailMsg.IsBodyHtml = true;

                                        SmtpClient smtpClient = new SmtpClient();

                                        smtpClient.Host = sMailSvr;

                                        smtpClient.Send(mailMsg);
                                    }
                                    catch (Exception Exception) { throw new Exception(Exception.Message); }
                                }
                            }
                            catch (Exception Exception) { throw new Exception(Exception.Message); }
                        }
                    }
                    catch (Exception Exception) { throw new Exception(Exception.Message); }
                }
            }
            catch (Exception Exception) { throw new Exception(Exception.Message); }
        }
コード例 #23
0
        protected void OK_Click(object sender, EventArgs e)
        {
            try
            {
                SPContext.Current.Web.AllowUnsafeUpdates = true;
                SPAdministrationWebApplication caWebApp = SPAdministrationWebApplication.Local;
                AppData.Local.Entries[AppData.SELECTED_INDEX] = lstSchedule.SelectedIndex.ToString();
                AppData.Local.Update();

                //Delete any existing jobs
                string jobName = "SiteMap Ping";
                foreach (SPJobDefinition job in caWebApp.JobDefinitions)
                {
                    if (job.Name.ToUpper().Equals(jobName.ToUpper()))
                    {
                        job.Delete();
                    }
                }

                //Schedule new job
                switch (lstSchedule.SelectedIndex)
                {
                case 1:    //Immediate
                    SPOneTimeSchedule schedule1 = new SPOneTimeSchedule(DateTime.Now);
                    Worker            newJob1   = new Worker(jobName, caWebApp);
                    newJob1.Schedule = schedule1;
                    newJob1.Update();
                    break;

                case 2:    //Daily
                    SPDailySchedule schedule2 = new SPDailySchedule();
                    schedule2.BeginHour = 2;
                    schedule2.EndHour   = 6;
                    Worker newJob2 = new Worker(jobName, caWebApp);
                    newJob2.Schedule = schedule2;
                    newJob2.Update();
                    break;

                case 3:    //Weekly
                    SPWeeklySchedule schedule3 = new SPWeeklySchedule();
                    schedule3.BeginDayOfWeek = DayOfWeek.Saturday;
                    schedule3.EndDayOfWeek   = DayOfWeek.Saturday;
                    schedule3.BeginHour      = 2;
                    schedule3.EndHour        = 6;
                    Worker newJob3 = new Worker(jobName, caWebApp);
                    newJob3.Schedule = schedule3;
                    newJob3.Update();
                    break;

                case 4:    //Monthly
                    SPMonthlySchedule schedule4 = new SPMonthlySchedule();
                    schedule4.BeginDay  = 1;
                    schedule4.EndDay    = 1;
                    schedule4.BeginHour = 2;
                    schedule4.EndHour   = 6;
                    Worker newJob4 = new Worker(jobName, caWebApp);
                    newJob4.Schedule = schedule4;
                    newJob4.Update();
                    break;
                }


                SPUtility.Redirect(caWebApp.Sites[0].Url, SPRedirectFlags.Default, HttpContext.Current);
            }
            catch (Exception x)
            {
                lblMessages.Text = x.Message;
            }
        }
コード例 #24
0
        /// <summary> Returns an instance of the SharePoint Central Administration web service.</summary>
        internal static SPWebService GetAdminWebService()
        {
            SPAdministrationWebApplication adminWebApp = SPAdministrationWebApplication.Local;

            return((SPWebService)adminWebApp.Parent);
        }
コード例 #25
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string strAction = Request["action"];
            string period    = Request["period"];

            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Expires = -1;

            data = "";

            string fEmail = SPContext.Current.Web.CurrentUser.Email;

            SPSite site = SPContext.Current.Site;
            //using ()
            {
                //using ()
                SPWeb web = SPContext.Current.Web;
                {
                    try
                    {
                        SqlConnection cn = null;
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            cn = new SqlConnection(EPMLiveCore.CoreFunctions.getConnectionString(site.WebApplication.Id));
                            cn.Open();

                            string requestedUser = Page.Request["duser"];

                            if (requestedUser != null && requestedUser != "")
                            {
                                if (SharedFunctions.canUserImpersonate(username, requestedUser, SPContext.Current.Site.RootWeb, out resName))
                                {
                                    username = requestedUser;
                                }
                                else
                                {
                                    impFailed = true;
                                }
                            }
                            bool.TryParse(EPMLiveCore.CoreFunctions.getConfigSetting(SPContext.Current.Site.RootWeb, "EPMLiveTSLiveHours"), out liveHours);
                        });
                        if (impFailed)
                        {
                            data = "Error: Impersonation Failed";
                        }
                        else
                        {
                            if (cn != null)
                            {
                                SqlCommand cmd;

                                int           iperiod;
                                SqlDataReader dr;

                                switch (strAction)
                                {
                                case "deleteTS":
                                    if (web.CurrentUser.IsSiteAdmin)
                                    {
                                        string[] tsuids = Request["ts_uids"].Split(',');
                                        foreach (string tsuidData in tsuids)
                                        {
                                            cmd = new SqlCommand("DELETE FROM TSTIMESHEET where ts_uid=@ts_uid", cn);
                                            cmd.Parameters.AddWithValue("@ts_uid", tsuidData);
                                            cmd.ExecuteNonQuery();
                                        }
                                        data = "Success";
                                    }
                                    else
                                    {
                                        data = "Error: Access Denied";
                                    }
                                    break;

                                case "closePeriod":
                                    cmd = new SqlCommand("update tsperiod set locked=1 where period_id=@periodid and site_id=@siteid", cn);
                                    cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID);
                                    cmd.Parameters.AddWithValue("@periodid", period);
                                    cmd.ExecuteNonQuery();
                                    data = period;
                                    break;

                                case "openPeriod":
                                    cmd = new SqlCommand("update tsperiod set locked=0 where period_id=@periodid and site_id=@siteid", cn);
                                    cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID);
                                    cmd.Parameters.AddWithValue("@periodid", period);
                                    cmd.ExecuteNonQuery();
                                    data = period;
                                    break;

                                case "submitTime":
                                    cmd = new SqlCommand("update TSTIMESHEET set submitted=1,approval_status=0,lastmodifiedbyu=@u,lastmodifiedbyn=@n where ts_uid=@ts_uid", cn);
                                    cmd.Parameters.AddWithValue("@ts_uid", Request["ts_uid"]);
                                    cmd.Parameters.AddWithValue("@u", SPContext.Current.Web.CurrentUser.LoginName);
                                    cmd.Parameters.AddWithValue("@n", SPContext.Current.Web.CurrentUser.Name);
                                    cmd.ExecuteNonQuery();
                                    SPSecurity.RunWithElevatedPrivileges(delegate()
                                    {
                                        SPWeb tweb = SPContext.Current.Web;
                                        {
                                            SharedFunctions.processResources(cn, Request["ts_uid"], tweb, username);
                                        }
                                    });

                                    if (EPMLiveCore.CoreFunctions.getConfigSetting(SPContext.Current.Site.RootWeb, "EPMLiveTSDisableApprovals").ToLower() == "true")
                                    {
                                        approve(Request["ts_uid"], SPContext.Current.Web, Request["Period"]);
                                    }
                                    else
                                    {
                                        string actualWork = "";
                                        //SPSecurity.RunWithElevatedPrivileges(delegate()
                                        //{
                                        //    actualWork = EPMLiveCore.CoreFunctions.getConfigSetting(SPContext.Current.Site.RootWeb, "EPMLiveTSActualWork");
                                        //});
                                        //if (actualWork != "")
                                        //{
                                        if (!liveHours)
                                        {
                                            data = SharedFunctions.processActualWork(cn, Request["ts_uid"], site, false, true);
                                        }
                                        //}
                                    }

                                    if (data == "")
                                    {
                                        data = "Success";
                                    }

                                    cmd = new SqlCommand("select ts_item_uid,web_uid,list_uid,item_id,project from TSITEM where TS_UID=@ts_uid", cn);
                                    cmd.Parameters.AddWithValue("@ts_uid", Request["ts_uid"]);
                                    DataSet        ds = new DataSet();
                                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                                    da.Fill(ds);

                                    SPList pList    = null;
                                    SPWeb  iWeb     = null;
                                    SPList iList    = null;
                                    Guid   webGuid  = Guid.Empty;
                                    Guid   listGuid = Guid.Empty;

                                    foreach (DataRow dataRow in ds.Tables[0].Rows)
                                    {
                                        try
                                        {
                                            Guid wGuid = new Guid(dataRow["WEB_UID"].ToString());
                                            Guid lGuid = new Guid(dataRow["LIST_UID"].ToString());

                                            if (webGuid != wGuid)
                                            {
                                                if (iWeb != null)
                                                {
                                                    iWeb.Close();
                                                    iWeb = site.OpenWeb(wGuid);
                                                }
                                                else
                                                {
                                                    iWeb = site.OpenWeb(wGuid);
                                                }
                                                webGuid = iWeb.ID;
                                            }
                                            if (listGuid != lGuid)
                                            {
                                                iList = iWeb.Lists[lGuid];
                                                try
                                                {
                                                    pList = SharedFunctions.getProjectCenterList(iList);
                                                }
                                                catch { }
                                                listGuid = iList.ID;
                                            }
                                            SPListItem li = iList.GetItemById(int.Parse(dataRow["ITEM_ID"].ToString()));
                                            SharedFunctions.processMeta(iWeb, iList, li, new Guid(dataRow["ts_item_uid"].ToString()), dataRow["project"].ToString(), cn, pList);
                                        }
                                        catch { }
                                    }
                                    break;

                                case "unsubmitTime":
                                    cmd = new SqlCommand("update TSTIMESHEET set submitted=0,approval_status=0,lastmodifiedbyu=@u,lastmodifiedbyn=@n where ts_uid=@ts_uid", cn);
                                    cmd.Parameters.AddWithValue("@ts_uid", Request["ts_uid"]);
                                    cmd.Parameters.AddWithValue("@u", SPContext.Current.Web.CurrentUser.LoginName);
                                    cmd.Parameters.AddWithValue("@n", SPContext.Current.Web.CurrentUser.Name);
                                    cmd.ExecuteNonQuery();
                                    if (EPMLiveCore.CoreFunctions.getConfigSetting(SPContext.Current.Site.RootWeb, "EPMLiveTSDisableApprovals").ToLower() == "true" && !liveHours)
                                    {
                                        data = SharedFunctions.processActualWork(cn, Request["ts_uid"], site, true, true);
                                    }
                                    if (data == "")
                                    {
                                        data = "Success";
                                    }
                                    break;

                                case "deletePeriod":
                                    cmd = new SqlCommand("delete from tsperiod where period_id=@periodid and site_id=@siteid", cn);
                                    cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID);
                                    cmd.Parameters.AddWithValue("@periodid", period);
                                    cmd.ExecuteNonQuery();
                                    data = "Success";
                                    break;

                                case "addPeriod":
                                    cmd = new SqlCommand("select top 1 period_id from tsperiod where site_id=@siteid order by period_id desc", cn);
                                    cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID);
                                    dr      = cmd.ExecuteReader();
                                    iperiod = 1;
                                    if (dr.Read())
                                    {
                                        iperiod = dr.GetInt32(0) + 1;
                                    }
                                    dr.Close();

                                    cmd = new SqlCommand("insert into tsperiod (period_start,period_end,period_id,site_id) values (@periodstart,@periodend,@period_id,@siteid)", cn);
                                    cmd.Parameters.AddWithValue("@periodstart", Request["start"]);
                                    cmd.Parameters.AddWithValue("@periodend", Request["end"]);
                                    cmd.Parameters.AddWithValue("@period_id", iperiod);
                                    cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID);
                                    cmd.ExecuteNonQuery();
                                    data = "Success";
                                    break;

                                case "addPeriods":
                                    var periods    = JsonConvert.DeserializeObject <List <Dictionary <string, string> > >(Request[JsonDataParameter]);
                                    var createdIds = CreatePeriods(cn, periods);
                                    data = string.Format("Success,{0},{1}", strAction, string.Join(",", createdIds));
                                    break;

                                case "addType":
                                    cmd = new SqlCommand("select top 1 tstype_id from tstype where site_uid=@siteid order by tstype_id desc", cn);
                                    cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID);
                                    dr      = cmd.ExecuteReader();
                                    iperiod = 1;
                                    if (dr.Read())
                                    {
                                        iperiod = dr.GetInt32(0) + 1;
                                    }
                                    dr.Close();

                                    cmd = new SqlCommand("insert into tstype (tstype_id,tstype_name,site_uid) values (@tstype_id,@tstype_name,@siteid)", cn);
                                    cmd.Parameters.AddWithValue("@tstype_name", Request["typename"]);
                                    cmd.Parameters.AddWithValue("@tstype_id", iperiod);
                                    cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID);
                                    cmd.ExecuteNonQuery();
                                    data = "Success";
                                    break;

                                case "editType":
                                    cmd = new SqlCommand("update tstype set tstype_name = @tstype_name where tstype_id=@tstype_id and site_uid=@siteid", cn);
                                    cmd.Parameters.AddWithValue("@tstype_name", Request["typename"]);
                                    cmd.Parameters.AddWithValue("@tstype_id", Request["typeid"]);
                                    cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID);
                                    cmd.ExecuteNonQuery();
                                    data = "Success";
                                    break;

                                case "approveTS":
                                {
                                    approve(Request["ts_uids"].ToString(), SPContext.Current.Web, Request["Period"]);

                                    if (data == "")
                                    {
                                        data = "Success";
                                    }
                                }
                                break;

                                case "rejectTS":
                                {
                                    string[] tsuids = Request["ts_uids"].Split(',');
                                    foreach (string tsuidData in tsuids)
                                    {
                                        string[] tsuid = tsuidData.Split('|');
                                        cmd = new SqlCommand("update TSTIMESHEET set approval_status=2,approval_notes=@notes where ts_uid=@ts_uid", cn);
                                        cmd.Parameters.AddWithValue("@ts_uid", tsuid[0]);
                                        cmd.Parameters.AddWithValue("@notes", tsuid[1]);
                                        cmd.ExecuteNonQuery();

                                        data += SharedFunctions.processActualWork(cn, tsuid[0], site, true, true);
                                    }

                                    if (data == "")
                                    {
                                        data = "Success";
                                    }
                                }
                                break;

                                case "unlockTS":
                                {
                                    string[] tsuids = Request["ts_uids"].Split(',');
                                    foreach (string tsuidData in tsuids)
                                    {
                                        string[] tsuid = tsuidData.Split('|');
                                        cmd = new SqlCommand("update TSTIMESHEET set approval_status=0 where ts_uid=@ts_uid", cn);
                                        cmd.Parameters.AddWithValue("@ts_uid", tsuid[0]);
                                        cmd.ExecuteNonQuery();
                                    }
                                    data = "Success";
                                }
                                break;

                                case "rejectEmail":
                                {
                                    string[] tsuids = Request["ts_uids"].Split(',');
                                    foreach (string tsuid in tsuids)
                                    {
                                        cmd = new SqlCommand("select username,approval_notes,period_start,period_end from vwTSApprovalNotes where ts_uid=@ts_uid", cn);
                                        cmd.Parameters.AddWithValue("@ts_uid", tsuid);
                                        dr = cmd.ExecuteReader();
                                        if (dr.Read())
                                        {
                                            string username = dr.GetString(0);
                                            string notes    = dr.GetString(1);
                                            try
                                            {
                                                SPUser user = web.AllUsers[username];
                                                if (user.Email != "")
                                                {
                                                    System.Net.Mail.MailMessage mailMsg = new MailMessage();
                                                    mailMsg.From = new MailAddress(fEmail);
                                                    mailMsg.To.Add(new MailAddress(user.Email));
                                                    mailMsg.Subject      = web.Title + " Timesheet approval notice";
                                                    mailMsg.Body         = "Your timesheet for period (" + dr.GetDateTime(2).ToShortDateString() + " - " + dr.GetDateTime(3).ToShortDateString() + ") has been rejected:<br>" + notes;
                                                    mailMsg.IsBodyHtml   = true;
                                                    mailMsg.BodyEncoding = System.Text.Encoding.UTF8;
                                                    mailMsg.Priority     = MailPriority.Normal;

                                                    // Configure the mail server
                                                    SmtpClient smtpClient = new SmtpClient();
                                                    SPAdministrationWebApplication spWebAdmin = Microsoft.SharePoint.Administration.SPAdministrationWebApplication.Local;
                                                    string sMailSvr = spWebAdmin.OutboundMailServiceInstance.Server.Name;
                                                    smtpClient.Host = sMailSvr;
                                                    smtpClient.Send(mailMsg);
                                                }
                                            }
                                            catch { }
                                        }
                                        dr.Close();
                                    }
                                }
                                    data = "Success";
                                    break;

                                case "autoadd":
                                    //string flagfield = "";
                                    string lists = "";
                                    SPSecurity.RunWithElevatedPrivileges(delegate()
                                    {
                                        using (SPSite uSite = SPContext.Current.Site)
                                        {
                                            //flagfield = EPMLiveCore.CoreFunctions.getConfigSetting(uSite.RootWeb, "EPMLiveTSFlag");
                                            lists = EPMLiveCore.CoreFunctions.getConfigSetting(uSite.RootWeb, "EPMLiveTSLists");
                                        }
                                    });
                                    autoAdd(cn, Request["ts_uid"], web, lists);
                                    data = "Success";
                                    break;

                                case "approvePM":
                                {
                                    string[] tsitemuids = Request["tsitemuids"].Split(',');

                                    foreach (string tsitemuid in tsitemuids)
                                    {
                                        //string[] tsuid = tsuidData.Split('|');
                                        cmd = new SqlCommand("update tsitem set approval_status=1 where ts_item_uid=@tsitemuid", cn);
                                        cmd.Parameters.AddWithValue("@tsitemuid", tsitemuid);
                                        cmd.ExecuteNonQuery();
                                    }
                                    data = "Success";
                                }
                                break;

                                case "rejectPM":
                                {
                                    string[] tsitemuids = Request["tsitemuids"].Split(',');

                                    foreach (string tsitemuid in tsitemuids)
                                    {
                                        //string[] tsuid = tsuidData.Split('|');
                                        cmd = new SqlCommand("update tsitem set approval_status=2 where ts_item_uid=@tsitemuid", cn);
                                        cmd.Parameters.AddWithValue("@tsitemuid", tsitemuid);
                                        cmd.ExecuteNonQuery();
                                    }
                                }
                                    data = "Success";
                                    break;

                                default:
                                    data = "Error: Invalid Command";
                                    break;
                                }
                                ;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        data = "Error: " + ex.Message;
                    }
                }
            }
        }
コード例 #26
0
        public override SPHealthRepairStatus Repair()
        {
            Logging.LogMessage(903, Logging.LogCategories.Health, TraceSeverity.Verbose,
                               "Starting Security Token Service configuration repair.", new object[] { null });

            SPAdministrationWebApplication adminWebApp = SPAdministrationWebApplication.Local;

            try
            {
                var lists = new Lists
                {
                    Url         = adminWebApp.Sites[0].Url + "/_vti_bin/Lists.asmx",
                    Credentials = CredentialCache.DefaultNetworkCredentials
                };

                var        document   = new XmlDocument();
                XmlElement query      = document.CreateElement("Query");
                XmlElement viewFields = document.CreateElement("ViewFields");

                query.InnerXml =
                    "<Query><Where><And><BeginsWith><FieldRef Name='Title'></FieldRef><Value Type='Text'>MasterXmlFragment</Value></BeginsWith><IsNotNull><FieldRef Name='Title'></FieldRef></IsNotNull></And></Where></Query>";
                viewFields.InnerXml = "<FieldRef Name='XMLStsConfig' />";

                var listItem = lists.GetListItems(_listName, null, query, viewFields, _rowLimit, null, null);

                foreach (XmlNode node in listItem)
                {
                    if (node.Name == "rs:data")
                    {
                        for (int i = 0; i < node.ChildNodes.Count; i++)
                        {
                            if (node.ChildNodes[i].Name == "z:row")
                            {
                                MasterXmlFragment.LoadXml(node.ChildNodes[i].Attributes["ows_XMLStsConfig"].Value);

                                if (MasterXmlFragment == null)
                                {
                                    Logging.LogMessage(902, Logging.LogCategories.Health, TraceSeverity.Verbose,
                                                       "AD LDS/ADAM Forms Based Authentication not configured.",
                                                       new object[] { null });
                                }
                                else
                                {
                                    string path   = SPUtility.GetGenericSetupPath(@"WebServices\SecurityToken\web.config");
                                    var    config = new XmlDocument();
                                    config.Load(path);

                                    XmlNode systemwebChild =
                                        config.SelectSingleNode("configuration/system.web");

                                    if (systemwebChild != null)
                                    {
                                        if (systemwebChild.ParentNode != null)
                                        {
                                            systemwebChild.ParentNode.RemoveChild(systemwebChild);
                                        }
                                        try
                                        {
                                            config.Save(path);
                                        }
                                        catch (Exception)
                                        {
                                            Logging.LogMessage(902, Logging.LogCategories.Health,
                                                               TraceSeverity.Verbose,
                                                               "Failed to save removal of child node to Security Token Service web.config on {0}.",
                                                               new object[] { SPServer.Local.DisplayName });
                                            return(SPHealthRepairStatus.Failed);
                                        }
                                    }

                                    XmlNode importNode =
                                        config.ImportNode(MasterXmlFragment.SelectSingleNode("system.web"), true);
                                    if (config.DocumentElement != null)
                                    {
                                        config.DocumentElement.AppendChild(importNode);
                                    }

                                    try
                                    {
                                        config.Save(path);
                                    }
                                    catch (Exception)
                                    {
                                        Logging.LogMessage(902, Logging.LogCategories.Health,
                                                           TraceSeverity.Verbose,
                                                           "Failed to save updates to Security Token Service web.config on {0}.",
                                                           new object[] { SPServer.Local.DisplayName });
                                        return(SPHealthRepairStatus.Failed);
                                    }
                                }
                            }
                        }
                    }
                }
                return(SPHealthRepairStatus.Succeeded);
            }
            catch (Exception)
            {
                Logging.LogMessage(903, Logging.LogCategories.Health,
                                   TraceSeverity.Unexpected,
                                   "Error calling Lists SOAP service {0}.",
                                   new object[] { SPServer.Local.DisplayName });
            }
            return(SPHealthRepairStatus.Succeeded);
        }
コード例 #27
0
        public static void sendEmail(int templateID, Hashtable additionalParams, List <String> emailTo, string emailFrom, SPWeb oWeb, bool hideFrom, SPUser currentUser = null)
        {
            string body    = "";
            string subject = "";

            //Guid siteid = SPContext.Current.Site.ID;
            //Guid webid = SPContext.Current.Web.ID;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SqlConnection cn = new SqlConnection(CoreFunctions.getConnectionString(oWeb.Site.WebApplication.Id)))
                {
                    cn.Open();

                    GetCoreInformation(cn, templateID, out body, out subject, oWeb, currentUser == null ? oWeb.CurrentUser:currentUser);

                    foreach (string s in additionalParams.Keys)
                    {
                        body    = Regex.Replace(body, "{" + s + "}", additionalParams[s].ToString(), RegexOptions.IgnoreCase);
                        subject = Regex.Replace(subject, "{" + s + "}", additionalParams[s].ToString(), RegexOptions.IgnoreCase);
                    }

                    SPAdministrationWebApplication spWebAdmin = Microsoft.SharePoint.Administration.SPAdministrationWebApplication.Local;
                    string sMailSvr = spWebAdmin.OutboundMailServiceInstance?.Server.Address;

                    if (string.IsNullOrEmpty(sMailSvr))
                    {
                        return;
                    }

                    using (MailMessage mailMsg = new MailMessage())
                    {
                        if (hideFrom)
                        {
                            mailMsg.From = new MailAddress(spWebAdmin.OutboundMailSenderAddress);
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(emailFrom))
                            {
                                mailMsg.From = new MailAddress(spWebAdmin.OutboundMailSenderAddress, oWeb.CurrentUser.Name);
                            }
                            else
                            {
                                mailMsg.From = new MailAddress(oWeb.CurrentUser.Email, oWeb.CurrentUser.Name);
                            }
                        }

                        emailTo.ForEach(i => mailMsg.To.Add(i));
                        mailMsg.Subject    = subject;
                        mailMsg.Body       = body;
                        mailMsg.IsBodyHtml = true;

                        using (SmtpClient smtpClient = new SmtpClient())
                        {
                            smtpClient.Host = sMailSvr;
                            smtpClient.Send(mailMsg);
                        }
                    }
                }
            });
        }
コード例 #28
0
        protected void btnSend_Click(object sender, EventArgs e)
        {
            strSent = "";

            string emails = hdnEmails.Value;
            string names  = hdnNames.Value;

            SPWeb web = SPContext.Current.Web;

            {
                string fromEmail = web.CurrentUser.Email;
                if (fromEmail == "")
                {
                    fromEmail = "*****@*****.**";
                }

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    // Mail server objects
                    SmtpClient smtpClient = new SmtpClient();
                    SPAdministrationWebApplication spWebAdmin = Microsoft.SharePoint.Administration.SPAdministrationWebApplication.Local;

                    string[] semails = emails.Split(',');
                    string[] snames  = names.Split(',');

                    string body = txtBody.Text + "<br><br>Go To Site: <a href=\"" + web.Url + "\">" + web.Title + "</a>";

                    if (spWebAdmin.OutboundMailServiceInstance != null)
                    {
                        for (int i = 0; i < semails.Length; i++)
                        {
                            if (semails[i] != "")
                            {
                                try
                                {
                                    System.Net.Mail.MailMessage mailMsg = new MailMessage();
                                    mailMsg.From = new MailAddress(spWebAdmin.OutboundMailSenderAddress, web.CurrentUser.Name);
                                    mailMsg.To.Add(new MailAddress(semails[i]));
                                    mailMsg.Subject      = txtSubject.Text;
                                    mailMsg.Body         = body;
                                    mailMsg.IsBodyHtml   = true;
                                    mailMsg.BodyEncoding = System.Text.Encoding.UTF8;
                                    mailMsg.Priority     = MailPriority.Normal;

                                    //Email Sent process.
                                    string sMailSvr = spWebAdmin.OutboundMailServiceInstance.Server.Name;
                                    smtpClient.Host = sMailSvr;
                                    smtpClient.Send(mailMsg);
                                    strSent += snames[i] + " (" + semails[i] + ")...Success<br>";
                                }
                                catch (Exception ex)
                                {
                                    strSent += "<font color=\"red\">" + snames[i] + " (" + semails[i] + ")...Failed: " + ex.Message + "</font><br>";
                                }
                            }
                        }
                    }
                    else
                    {
                        strSent = "<font color=\"red\"> Email Failure: Outbound Email service is not configured on this server, please contact your System Administrator. </font><br>";
                    }
                });
            }

            pnlMain.Visible = false;
            pnlSent.Visible = true;
        }