private void InitializeSites()
        {
            if (DynamicSiteSettings.GetSiteCache.Count() > 0 && _sites != null && _dynamicSiteDictionary.Count > 0) return;

            Assert.IsNotNullOrEmpty(_dynamicConfigPath, "No siteConfig specified in DynamicSiteProvider configuration.");
            var collection = new SiteCollection();

            var nodes = Factory.GetConfigNodes(FileUtil.MakePath(_dynamicConfigPath, "defaultsite", '/'));
            Assert.IsFalse((nodes.Count > 1 ? 1 : 0) != 0, "Duplicate Dynamic Default Site Definition.");

            if (nodes.Count == 0) return;

            var defaultSite = ParseDefaultNode(nodes[0]);

            //Create Dictionary
            var siteDictionary = DynamicSiteManager.GetDynamicSitesDictionary(defaultSite);
            
            //Set Site Collection
            foreach (var keyValuePair in siteDictionary)
            {
                collection.Add(keyValuePair.Value);
            }

            ResolveInheritance(collection, siteDictionary);

            _sites = collection;
            _dynamicSiteDictionary = siteDictionary;
        }
예제 #2
0
 public NetSimulationInterface(IBaseService provider, CollectionsModel model)
 {
     this.m_provider = provider;
     this.m_SiteCol = model.SiteColl;
     this.m_CellCol = model.TranceiverColl;
     this.m_CarrierCollection = model.LTECellColl;
 }
예제 #3
0
        public GeoNetEntityAssist(CollectionsModel model)
        {
            this.m_Model = model;
            this.m_SiteCol = model.SiteColl;
            this.m_TranceiverCol = model.TranceiverColl;
            this.m_RepCol = model.RepeaterColl;
            this.m_GeoMsgChange = model.GisINetEntity;
            this.m_antennas = model.Antennas;
            this.m_TpCol = model.TplCellCollection;
            this.m_RNCol = model.RNColl;
            this.m_SiteCol.SiteAddEvent += new EventHandler<NESiteEventArgs>(this.SiteCol_SiteAddEvent);
            this.m_SiteCol.SiteDeleteEvent += new EventHandler<NESiteEventArgs>(this.SiteCol_SiteDeleteEvent);
            this.m_SiteCol.SiteModifyEvent += new EventHandler<NESiteEventArgs>(this.SiteCol_SiteModifyEvent);
            this.m_TranceiverCol.AddEvent += new EventHandler<NETranceiverEventArgs>(this.CellCol_CellAddEvent);
            this.m_TranceiverCol.DeleteEvent += new EventHandler<NETranceiverEventArgs>(this.CellCol_CellDeleteEvent);
            this.m_TranceiverCol.ModifyEvent += new EventHandler<NETranceiverEventArgs>(this.CellCol_CellModifyEvent);
            this.m_RepCol.RepeaterAddEvent += new EventHandler<NERepeaterEventArgs>(this.RepCol_RepeaterAddEvent);
            this.m_RepCol.RepeaterDeleteEvent += new EventHandler<NERepeaterEventArgs>(this.RepCol_RepeaterDeleteEvent);
            this.m_RepCol.RepeaterModifyEvent += new EventHandler<NERepeaterEventArgs>(this.RepCol_RepeaterModifyEvent);
            this.m_antennas.ResponseEvent += new RetrunUserInfoDelegate(this.m_antennas_ResponseEvent);
            this.m_RNCol.RNAddEvent += new EventHandler<NERelayNodeEventArgs>(this.RNCol_AddEvent);
            this.m_RNCol.RNDeleteEvent += new EventHandler<NERelayNodeEventArgs>(this.RNCol_DeleteEvent);
            this.m_RNCol.RNModifyEvent += new EventHandler<NERelayNodeEventArgs>(this.RNCol_ModifyEvent);

        }
예제 #4
0
        private static bool CreateSiteInIIS(SiteCollection sites, SiteDTO dto)
        {
            try
            {
                var site = sites.CreateElement();
                site.Id = dto.SiteId;
                site.SetAttributeValue("name", dto.SiteName);
                sites.Add(site);

                var app = site.Applications.CreateElement();
                app.SetAttributeValue("path", "/");
                app.SetAttributeValue("applicationPool", dto.PoolName);
                site.Applications.Add(app);

                var vdir = app.VirtualDirectories.CreateElement();
                vdir.SetAttributeValue("path", "/");
                vdir.SetAttributeValue("physicalPath", string.Format(@"{0}\{1}", dto.RootDir, dto.SiteName));
                app.VirtualDirectories.Add(vdir);

                var binding = site.Bindings.CreateElement();
                binding.SetAttributeValue("protocol", "http");
                binding.SetAttributeValue("bindingInformation", string.Format(@":{0}:{1}", dto.Port, dto.SiteName));
                site.Bindings.Add(binding);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Create site {0} failed. Reason: {1}", dto.SiteName, ex.Message);
                return false;
            }
            return true;
        }
        private void InitializeSites()
        {
            Database database = Factory.GetDatabase(DatabaseName, false);
            if (database == null)
                return;

            if (_siteDictionary != null && _siteDictionary.Any())
                return;

            lock (_lock)
            {
                if (_siteDictionary != null && _siteDictionary.Any())
                    return;

                var sitesCollection = new SiteCollection();
                var siteDictionary = new SafeDictionary<string, Site>(StringComparer.InvariantCultureIgnoreCase);

                foreach (Item siteItem in GetSiteDeinitionItems(database))
                {
                    Site site = ResolveSite(siteItem);

                    if (site != null)
                    {
                        siteDictionary[site.Name] = site;
                        sitesCollection.Add(site);
                    }
                }

                _sitesCollection = sitesCollection;
                _siteDictionary = siteDictionary;
            }
        }
예제 #6
0
 public SitePropertyFormEditor(CollectionsModel model)
 {
     this.m_UserDefCol = model.UserItemsColl;
     this.m_GeoObserver = model.GeoObserver;
     this.m_SiteCol = model.SiteColl;
     this.m_btslist = model.BtsEquipColl;
     this.m_Model = model;
     this.m_UserDefineTool = new UserDefineTool(model);
 }
예제 #7
0
 public RepeaterValidateTool(CollectionsModel model)
 {
     this.m_RepeaterCollection = model.RepeaterColl;
     this.m_SiteCollection = model.SiteColl;
     this.m_CellCollection = model.TranceiverColl;
     this.m_AtennaCollction = model.Antennas;
     this.m_RepeaterEquipCollection = model.RepeaterEquipCollection;
     this.m_PropList = model.PropagetionColl.GetPropagationModelList();
 }
        public override SiteCollection GetSites()
        {
            InitializeSites();

            var sitesCollection = new SiteCollection();

            sitesCollection.AddRange(_sitesCollection);

            return sitesCollection;
        }
        public SiteCollection GetAllSites([NotNull] IEnumerable orderedList)
        {
            var collection = new SiteCollection();

            foreach (string siteName in orderedList)
            {
                collection.Add(GetSite(siteName));
            }

            return collection;
            
        }
예제 #10
0
        /// <summary>
        /// The get sites.
        /// </summary>
        /// <returns>
        /// The <see cref="SiteCollection"/>.
        /// </returns>
        public override SiteCollection GetSites()
        {
            var list = new SiteCollection();
              foreach (SiteProvider provider in SiteManager.Providers)
              {
            if (provider != this)
            {
              list.AddRange(provider.GetSites() ?? new SiteCollection());
            }
              }

              return list;
        }
        internal Site(ConfigurationElement element, SiteCollection parent)
            : base(element, "site", null, parent, null, null)
        {
            ApplicationDefaults = ChildElements["applicationDefaults"] == null
                ? new ApplicationDefaults(parent.ChildElements["applicationDefaults"], this)
                : new ApplicationDefaults(ChildElements["applicationDefaults"], this);
            Parent = parent;
            if (element == null)
            {
                return;
            }

            foreach (ConfigurationElement node in (ConfigurationElementCollection)element)
            {
                var app = new Application(node, Applications);
                Applications.InternalAdd(app);
            }
        }
예제 #12
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            foreach (var ch in ApplicationCollection.InvalidApplicationPathCharacters())
            {
                if (txtAlias.Text.Contains(ch.ToString(CultureInfo.InvariantCulture)))
                {
                    MessageBox.Show("The application path cannot contain the following characters: \\, ?, ;, :, @, &, =, +, $, ,, |, \", <, >, *.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
            }

            foreach (var ch in SiteCollection.InvalidSiteNameCharactersJexus())
            {
                if (txtAlias.Text.Contains(ch.ToString(CultureInfo.InvariantCulture)))
                {
                    MessageBox.Show("The site name cannot contain the following characters: ' '.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
            }

            if (!_application.Server.Verify(txtPhysicalPath.Text))
            {
                MessageBox.Show("The specified directory does not exist on the server.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (VirtualDirectory == null)
            {
                // TODO: fix this
                VirtualDirectory = new VirtualDirectory(null, _application.VirtualDirectories)
                {
                    Path = "/" + txtAlias.Text
                };
                VirtualDirectory.PhysicalPath = txtPhysicalPath.Text;
                VirtualDirectory.Parent.Add(VirtualDirectory);
            }
            else
            {
                VirtualDirectory.PhysicalPath = txtPhysicalPath.Text;
            }

            DialogResult = DialogResult.OK;
        }
예제 #13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="siteName"></param>
        /// <param name="binding"></param>
        /// <returns></returns>
        public static bool AddSiteBinding(string siteName, string ipAddress, string tcpPort, string hostHeader, string protocol, string remoteServer = "localhost")
        {
            try
            {
                if (string.IsNullOrEmpty(siteName))
                {
                    throw new ArgumentNullException("siteName", "AddSiteBinding: siteName is null or empty.");
                }
                //get the server manager instance
                using (ServerManager mgr = ServerManager.OpenRemote(remoteServer))
                {
                    SiteCollection sites = mgr.Sites;
                    Site           site  = mgr.Sites[siteName];
                    if (site != null)
                    {
                        string bind = ipAddress + ":" + tcpPort + ":" + hostHeader;
                        //check the binding exists or not
                        foreach (Binding b in site.Bindings)
                        {
                            if (b.Protocol == protocol && b.BindingInformation == bind)
                            {
                                throw new Exception("A binding with the same ip, port and host header already exists.");
                            }
                        }
                        Binding newBinding = site.Bindings.CreateElement();
                        newBinding.Protocol           = protocol;
                        newBinding.BindingInformation = bind;

                        site.Bindings.Add(newBinding);
                        mgr.CommitChanges();
                        return(true);
                    }
                    else
                    {
                        throw new Exception("Site: " + siteName + " does not exist.");
                    }
                }
            }
            catch// (Exception ex)
            {
                throw;
            }
        }
예제 #14
0
        static void Main(string[] args)
        {
            ServerManager  mgr   = new ServerManager();
            SiteCollection sites = mgr.Sites;

            if (!VerifyIISVersion())
            {
                Console.WriteLine("This utility requires at least IIS version 7.");
                return;
            }


            foreach (Site site in sites)
            {
                Console.WriteLine($"Found site \"{site.Name}\".");
            }

            Console.WriteLine("Hello World!");
        }
        public void DeleteSite(string siteName)
        {
            try
            {
                using (ServerManager serverManager = GetServerManager())
                {
                    TestUtility.LogTrace(String.Format("#################### Deleting Site {0} ####################", siteName));

                    SiteCollection sites = serverManager.Sites;
                    sites.Remove(sites[siteName]);

                    serverManager.CommitChanges();
                }
            }
            catch (Exception ex)
            {
                TestUtility.LogInformation(String.Format("#################### Delete site {0} failed. Reason: {1} ####################", siteName, ex.Message));
            }
        }
예제 #16
0
        public static void TestServerManager()
        {
            ServerManager server = new ServerManager();

            SiteCollection sites = server.Sites;

            foreach (Site site in sites)
            {
                ApplicationDefaults defaults = site.ApplicationDefaults;

                //get the name of the ApplicationPool under which the Site runs
                string appPoolName = defaults.ApplicationPoolName;

                ConfigurationAttributeCollection attributes = defaults.Attributes;
                foreach (ConfigurationAttribute configAttribute in attributes)
                {
                    //put code here to work with each ConfigurationAttribute
                }

                ConfigurationAttributeCollection attributesCollection = site.Attributes;
                foreach (ConfigurationAttribute attribute in attributesCollection)
                {
                    //put code here to work with each ConfigurationAttribute
                }

                //Get the Binding objects for this Site
                BindingCollection bindings = site.Bindings;
                foreach (Microsoft.Web.Administration.Binding binding in bindings)
                {
                    //put code here to work with each Binding
                }

                //retrieve the State of the Site
                ObjectState siteState = site.State;

                //Get the list of all Applications for this Site
                ApplicationCollection applications = site.Applications;
                foreach (Microsoft.Web.Administration.Application application in applications)
                {
                    //put code here to work with each Application
                }
            }
        }
예제 #17
0
        /// <summary>
        /// Checks if a website exists on the webserver
        /// </summary>
        /// <param name="strWebsitename">name of the website as a string</param>
        /// <returns></returns>
        public bool IsWebsiteExists(string strWebsitename)
        {
            Boolean        flagset        = false;
            SiteCollection sitecollection = ServerMngr.Sites;

            foreach (Site site in sitecollection)
            {
                if (site.Name == strWebsitename.ToString())
                {
                    flagset = true;
                    break;
                }
                else
                {
                    flagset = false;
                }
            }
            return(flagset);
        }
예제 #18
0
        private static bool IsWebsiteExists(string strWebsitename)
        {
            Boolean        flagset        = false;
            SiteCollection sitecollection = serverMgr.Sites;

            //checks to see if the site name given already exists
            foreach (Site site in sitecollection)
            {
                if (site.Name == strWebsitename.ToString())
                {
                    flagset = true;
                    break;
                }
                else
                {
                    flagset = false;
                }
            }
            return(flagset);
        }
예제 #19
0
        public NewSiteDialog(IServiceProvider serviceProvider, SiteCollection collection)
            : base(serviceProvider)
        {
            InitializeComponent();
            cbType.SelectedIndex = 0;
            _collection          = collection;
            if (collection.Parent == null)
            {
                throw new InvalidOperationException("null server for site collection");
            }

            btnBrowse.Visible = collection.Parent.IsLocalhost;
            txtPool.Text      = collection.Parent.ApplicationDefaults.ApplicationPoolName;
            btnChoose.Enabled = collection.Parent.Mode != WorkingMode.Jexus;
            txtHost.Text      = collection.Parent.Mode == WorkingMode.IisExpress ? "localhost" : string.Empty;
            DialogHelper.LoadAddresses(cbAddress);
            if (!collection.Parent.SupportsSni)
            {
                cbSniRequired.Enabled = false;
            }
        }
예제 #20
0
 protected override void ExecuteCmdlet()
 {
     try
     {
         var results      = SiteCollection.TeamifySiteAsync(ClientContext);
         var returnedBool = results.GetAwaiter().GetResult();
         WriteObject(returnedBool);
     }
     catch (Exception)
     {
         try
         {
             var groupId = ClientContext.Site.EnsureProperty(s => s.GroupId);
             Microsoft365GroupsUtility.CreateTeamAsync(HttpClient, AccessToken, groupId).GetAwaiter().GetResult();
         }
         catch
         {
             throw;
         }
     }
 }
예제 #21
0
        private void listView1_AfterLabelEdit(object sender, LabelEditEventArgs e)
        {
            if (string.IsNullOrEmpty(e.Label))
            {
                e.CancelEdit = true;
                return;
            }

            var service = (IManagementUIService)GetService(typeof(IManagementUIService));

            Debug.Assert(service != null, "service != null");
            foreach (var ch in SiteCollection.InvalidSiteNameCharacters())
            {
                if (e.Label.Contains(ch))
                {
                    service.ShowMessage(
                        "The site name cannot contain the following characters: '\\, /, ?, ;, :, @, &, =, +, $, ,, |, \", <, >'.",
                        "Sites", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    e.CancelEdit = true;
                    return;
                }
            }

            foreach (var ch in SiteCollection.InvalidSiteNameCharactersJexus())
            {
                if (e.Label.Contains(ch) || e.Label.StartsWith("~"))
                {
                    service.ShowMessage("The site name cannot contain the following characters: '~,  '.", "Sites",
                                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    e.CancelEdit = true;
                    return;
                }
            }

            var site = (Site)listView1.Items[e.Item].Tag;

            site.Name = e.Label;
            _form.UpdateSiteNode(site);
            site.Server.CommitChanges();
        }
예제 #22
0
        public void CreateSite()
        {
            if (server.Sites != null && server.Sites.Count > 0)
            {
                SiteCollection sc = server.Sites;

                //we will first check to make sure that the site isn't already there
                if (server.Sites.FirstOrDefault(s => s.Name == "Default Web Site") == null)
                {
                    //we will just pick an arbitrary location for the site
                    string path = @source;

                    //we must specify the Binding information
                    string ip       = "*";
                    string port     = "81";
                    string hostName = "*";

                    string bindingInfo = string.Format(@"{0}:{1}:{2}", ip, port, hostName);

                    //add the new Site to the Sites collection
                    Site site = server.Sites.Add("Default Web Site", "http", bindingInfo, path);

                    //set the ApplicationPool for the new Site
                    site.ApplicationDefaults.ApplicationPoolName = myAppPool.Name;

                    //save the new Site!
                    server.CommitChanges();
                }
            }
            if (server.Sites.FirstOrDefault(s => s.Name == "Default Web Site") != null)
            {
                Site defaultSite = server.Sites["Default Web Site"];
                if (defaultSite.Applications.FirstOrDefault(a => a.Path == "/website") == null)
                {
                    defaultSite.Applications.Add("/website", @source);
                    server.CommitChanges();
                }
            }
        }
예제 #23
0
        public async Task <string> CreateCommunicationSiteAsync(CommunicationSiteRequest request)
        {
            using var context = new ClientContext(AppConfigurations.SpoUrlAdmin)
                  {
                      Credentials = new SharePointOnlineCredentials(
                          AppConfigurations.SpoUserAdmin,
                          AppConfigurations.PasswordSecure)
                  };

            var communicationSite = new CommunicationSiteCollectionCreationInformation
            {
                Title               = request.Title,
                Url                 = $"{AppConfigurations.SpoUrl}/sites/{request.Alias}",
                Description         = request.Description,
                Lcid                = (uint)request.Language,
                ShareByEmailEnabled = true,
            };

            await SiteCollection.CreateAsync(context, communicationSite, noWait : true);

            return(communicationSite.Url);
        }
예제 #24
0
        public async Task <string> CreateSiteCollectionAsync(SiteCollectionRequest request)
        {
            var accessToken = await tokenManager.GetAccessTokenSPOAsync(spoSetting.SiteUrlAdmin);

            var accessTokenSecure = accessToken.ToSecureString();

            using var authManager = new AuthenticationManager(accessTokenSecure);
            using var context     = authManager.GetContext(spoSetting.SiteUrlAdmin);

            var site = new TeamNoGroupSiteCollectionCreationInformation
            {
                Owner = spoSetting.UserName,
                Title = request.Title,
                Url   = $"{spoSetting.SiteUrl.RemoveLastSlash()}/sites/{request.Alias}",
                Lcid  = 1033,
                ShareByEmailEnabled = true,
            };

            await SiteCollection.CreateAsync(context, site, noWait : true);

            return(site.Url);
        }
예제 #25
0
        private bool SiteExists(string siteName)
        {
            Boolean        flag           = false;
            ServerManager  iisManager     = new ServerManager();
            SiteCollection siteCollection = iisManager.Sites;

            foreach (Site site in siteCollection)
            {
                if (site.Name == siteName.ToString())
                {
                    flag = true;
                    if (chkDeleteSiteIfExists.Checked)
                    {
                        if (site.ApplicationDefaults.ApplicationPoolName == siteName + "_nvQuickSite")
                        {
                            ApplicationPoolCollection appPools = iisManager.ApplicationPools;
                            foreach (ApplicationPool appPool in appPools)
                            {
                                if (appPool.Name == siteName + "_nvQuickSite")
                                {
                                    iisManager.ApplicationPools.Remove(appPool);
                                    break;
                                }
                            }
                        }
                        iisManager.Sites.Remove(site);
                        iisManager.CommitChanges();
                        flag = false;
                        break;
                    }
                    break;
                }
                else
                {
                    flag = false;
                }
            }
            return(flag);
        }
예제 #26
0
    public IisSiteApplicationList()
    {
        ServerManager  iisManager = new ServerManager();
        SiteCollection sites      = iisManager.Sites;

        foreach (Site iisSite in sites)
        {
            foreach (Application iisApp in iisSite.Applications)
            {
                IisSiteApplication app = new IisSiteApplication
                {
                    SiteId              = iisSite.Id,
                    SiteName            = iisSite.Name,
                    AppName             = iisApp.ToString(),
                    ApplicationPoolName = iisApp.ApplicationPoolName,
                    Directories         =
                        String.Join(";", iisApp.VirtualDirectories.Select(a => a.PhysicalPath).ToArray())
                };
                Add(app);
            }
        }
    }
예제 #27
0
        private void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            var site = (Site)e.Node.Tag;

            if (string.IsNullOrEmpty(e.Label))
            {
                e.CancelEdit = true;
                return;
            }

            foreach (var ch in SiteCollection.InvalidSiteNameCharacters())
            {
                if (e.Label.Contains(ch))
                {
                    UIService.ShowMessage("The site name cannot contain the following characters: '\\, /, ?, ;, :, @, &, =, +, $, ,, |, \", <, >'.", "Sites", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    e.CancelEdit = true;
                    return;
                }
            }

            foreach (var ch in SiteCollection.InvalidSiteNameCharactersJexus())
            {
                if (e.Label.Contains(ch) || e.Label.StartsWith("~"))
                {
                    UIService.ShowMessage("The site name cannot contain the following characters: '~,  '.", "Sites", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    e.CancelEdit = true;
                    return;
                }
            }

            // TODO: is this required by Jexus?
            // await site.RemoveApplicationsAsync();
            site.Name = e.Label;
            site.Server.CommitChanges();

            treeView1.SelectedNode = null;
            treeView1.SelectedNode = e.Node;
        }
        public void AddBindingToSite(string siteName, string Ip, int Port, string host)
        {
            string bindingInfo = "";

            if (Ip == null)
            {
                Ip = "*";
            }
            bindingInfo += Ip;
            bindingInfo += ":";
            bindingInfo += Port;
            bindingInfo += ":";
            if (host != null)
            {
                bindingInfo += host;
            }

            TestUtility.LogInformation(String.Format("#################### Adding Binding {0} to Site {1} ####################", bindingInfo, siteName));

            try
            {
                using (ServerManager serverManager = GetServerManager())
                {
                    SiteCollection sites = serverManager.Sites;
                    Binding        b     = sites[siteName].Bindings.CreateElement();
                    b.SetAttributeValue("protocol", "http");
                    b.SetAttributeValue("bindingInformation", bindingInfo);

                    sites[siteName].Bindings.Add(b);

                    serverManager.CommitChanges();
                }
            }
            catch (Exception ex)
            {
                TestUtility.LogInformation(String.Format("#################### Adding Binding {0} to Site {1} failed. Reason: {2} ####################", bindingInfo, siteName, ex.Message));
            }
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            var configuration     = new ConfigurationSettings();
            var storageService    = new StorageService(configuration, log);
            var tokenCacheService = new TokenCacheService(configuration, storageService);
            var tokenManager      = new TokenManager(configuration, tokenCacheService, log);
            var scopes            = new string[] {
                $"api://{configuration["ClientId"]}/access_as_user"
            };

            var siteCollection = new SiteCollection()
            {
                Url                  = $"https://{configuration["SharePointTenantPrefix"]}.sharepoint.com/sites/rztest123",
                Owner                = $"{configuration["Username"]}",
                Title                = "Test123",
                Template             = "STS#0",
                StorageMaximumLevel  = 100,
                UserCodeMaximumLevel = 300
            };

            var uri = await tokenManager.GetAuthUriAsync(scopes);

            //var authCode = await tokenRetriever.GetAuthCodeByMsalUriAsync(uri);
            var authenticationHeaderValue = req.Headers.Authorization;
            var authResult = await tokenManager.GetAccessTokenFromCodeAsync(authenticationHeaderValue.Parameter, scopes);

            var sharepointManager = new SharePointManager(configuration, tokenManager, authResult.AccessToken);
            var results           = await sharepointManager.CreateSiteCollectionAsync(siteCollection);

            var httpContent = new StringContent(JsonConvert.SerializeObject(results));

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = httpContent,
            });
        }
예제 #30
0
        static void CreateAppPoolAndSite(string siteName, string appPoolName, string path, string port, string ip, string domain)
        {
            using (var sm = new ServerManager())
            {
                var invalidChars = SiteCollection.InvalidSiteNameCharacters();
                if (siteName.IndexOfAny(invalidChars) > -1)
                {
                    throw new Exception(String.Format("Invalid Site Name: {0}", siteName));
                }

                var bindingInfo = String.Format("{0}:{1}:{2}", ip, port, domain);
                var site        = sm.Sites.Add(siteName, "http", bindingInfo, path);
                site.ServerAutoStart = true;

                var appPool = sm.ApplicationPools.Add(appPoolName);
                appPool.ManagedRuntimeVersion = "v4.0";
                appPool.ManagedPipelineMode   = ManagedPipelineMode.Integrated;

                site.ApplicationDefaults.ApplicationPoolName = appPoolName;

                sm.CommitChanges();
            }
        }
예제 #31
0
        /// <summary>
        /// 关闭IIS网站
        /// </summary>
        private Site CloseProjectSite(out string siteName)
        {
            int userIdIndex   = txtConnectString.Text.IndexOf("User ID=");
            int passWordIndex = txtConnectString.Text.IndexOf(";Password=");

            siteName = txtConnectString.Text.Substring(userIdIndex + 8, passWordIndex - userIdIndex - 8); //数据库的实例名就是网站的名称
            ServerManager  serverMgr      = new ServerManager();
            SiteCollection siteCollection = serverMgr.Sites;                                              //获取IIS里面的所有网站
            Site           returnSite     = null;

            foreach (Site site in siteCollection)
            {
                Console.WriteLine(site.Name);
                if (site.Name == siteName)
                {
                    site.ServerAutoStart = false;//必须加这一句,否则Stop无效
                    site.Stop();
                    returnSite = site;
                    break;
                }
            }
            return(returnSite);
        }
        public async Task AddSiteCollection()
        {
            // Arrange
            var configuration     = Substitute.For <IConfiguration>();
            var log               = Substitute.For <ILogger>();
            var tokenRetriever    = new TokenRetriever(configuration);
            var tokenCacheService = Substitute.For <ITokenCacheService>();

            var tokenManager = new TokenManager(configuration, tokenCacheService, log);
            var scopes       = new string[] {
                $"api://{configuration["ClientId"]}/access_as_user"
            };

            var siteCollection = new SiteCollection()
            {
                Url                  = $"https://{configuration["SharePointTenantPrefix"]}.sharepoint.com/sites/rztest123",
                Owner                = $"{configuration["Username"]}",
                Title                = "Test123",
                Template             = "STS#0",
                StorageMaximumLevel  = 100,
                UserCodeMaximumLevel = 300
            };

            // Act
            var uri = await tokenManager.GetAuthUriAsync(scopes);

            var authCode = await tokenRetriever.GetAuthCodeByMsalUriAsync(uri);

            var authResult = await tokenManager.GetAccessTokenFromCodeAsync(authCode, scopes);

            //var sharepointManager = new SharePointManager(configuration, tokenManager, authResult.AccessToken);
            //var result = await sharepointManager.CreateSiteCollectionAsync(siteCollection);

            //// Assert
            //Assert.NotNull(result);
            //Assert.False(result.HasError);
        }
        public List <IISSiteModel> GetIISSite()

        {
            List <IISSiteModel> iisSiteList = new List <IISSiteModel>();

            ServerManager serverMgr = new ServerManager();

            SiteCollection sitecollection = serverMgr.Sites;

            foreach (var site in sitecollection)
            {
                var BindingInfo = "";
                if (site.Bindings.Count() > 0)
                {
                    var index = 0;
                    foreach (var Site in site.Bindings)
                    {
                        BindingInfo += Site.Protocol + "://" + site.Bindings[index].Host + " | ";
                        index++;
                    }
                    ;
                }
                IISSiteModel issObject = new IISSiteModel()
                {
                    SiteName = site.Name,
                    State    = "1",
                    Bindings = BindingInfo,
                    SiteID   = site.Id
                };

                iisSiteList.Add(issObject);
            }



            return(iisSiteList);
        }
예제 #34
0
        static bool CreateSitesInIIS(SiteCollection sites, string sitePrefix, int siteId, string dirRoot)
        {
            string siteName = sitePrefix + siteId;
            // site gets set to Poolname using the following format. Example: 'Site_POOL10'
            string poolName = POOLPREFIX + sitePrefix + siteId;

            try
            {
                Site site = sites.CreateElement();
                site.Id = siteId;
                site.SetAttributeValue("name", siteName);
                sites.Add(site);

                Application app = site.Applications.CreateElement();
                app.SetAttributeValue("path", "/");
                app.SetAttributeValue("applicationPool", poolName);
                site.Applications.Add(app);

                VirtualDirectory vdir = app.VirtualDirectories.CreateElement();
                vdir.SetAttributeValue("path", "/");
                vdir.SetAttributeValue("physicalPath", dirRoot + @"\" + siteName);

                app.VirtualDirectories.Add(vdir);

                Binding b = site.Bindings.CreateElement();
                b.SetAttributeValue("protocol", "http");
                b.SetAttributeValue("bindingInformation", ":80:" + siteName);
                site.Bindings.Add(b);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Create site {0} failed. Reason: {1}", siteName, ex.Message);
                return(false);
            }

            return(true);
        }
예제 #35
0
        public List <PlayerAggregate> Process(SiteCollection siteCollection)
        {
            var players = new List <Player>();

            foreach (var fantasySite in siteCollection.FantasySites)
            {
                fantasySite.PageHtml = this.htmlLoader.GetHtml(fantasySite.PageUrl);
                var parser = new PageParser.Parser(fantasySite);
                parser.Parse();
                players.AddRange(fantasySite.Players);
            }

            return((from p in players
                    group p by p.Name
                    into g
                    select new PlayerAggregate
            {
                Name = g.Key,
                Rank = (decimal)g.Sum(x => x.Rank) / (decimal)g.Count(),
                Position = g.Select(x => x.Position).Distinct().FirstOrDefault()
            })
                   .OrderBy(p => p.Rank)
                   .ToList());
        }
예제 #36
0
        public async Task <bool> UpdateSiteCollectionDetailsAsync(SiteCollection model)
        {
            Ensure.Argument.NotNull(model);

            var tempModel = await _db.SiteCollections.FirstOrDefaultAsync(x => x.Id == model.Id);

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

            tempModel.Name = model.Name;

            try
            {
                await _db.SaveChangesAsync();

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
예제 #37
0
파일: SiteInfo.cs 프로젝트: xingfudaiyan/OA
 /// <summary>
 /// 批量装载
 /// </summary>
 internal static void LoadFromDALPatch(List< SiteInfo> pList, SiteCollection pCollection)
 {
     foreach (Site site in pCollection)
     {
         SiteInfo siteInfo = new SiteInfo();
         LoadFromDAL(siteInfo, site );
         pList.Add(siteInfo);
     }
 }
예제 #38
0
 /// <summary>
 /// Retrieve all Freedb servers from the main server site
 /// </summary>
 /// <param name="sites">SiteCollection that is populated with the site information</param>
 /// <returns>Response Code</returns>
 public string GetSites(out SiteCollection sites)
 {
     return(GetSites(Site.PROTOCOLS.ALL, out sites));
 }
 private void ResolveInheritance(SiteCollection sites, List<KeyValuePair<string, Site>> siteDictionary)
 {
     foreach (var site in sites.Where(site => !string.IsNullOrEmpty(site.Properties["inherits"])))
     {
         AddInheritedProperties(site, siteDictionary);
     }
 }
예제 #40
0
 private void InvalidateExternalSitesCollections(object sender, EventArgs e)
 {
     this._ConnectedSites = null;
 }
예제 #41
0
 public IISData(Version IisVersion,  SiteCollection sites)
 {
     this.IisVersion = IisVersion;
     this.sites = sites;
 }
예제 #42
0
        private void RemoveApplications(SiteCollection iisSites, string siteName)
        {
            var adminSite = iisSites[AzureRoleEnvironment.RoleWebsiteName()];

            var applicationsToRemove = from app in adminSite.Applications
                                       where app.Path.EndsWith("/test/" + siteName, StringComparison.OrdinalIgnoreCase) ||
                                       app.Path.EndsWith("/cdn/" + siteName, StringComparison.OrdinalIgnoreCase)
                                       select app;

            _logger.InfoFormat("IISManager.Removing Test and CDN applications for site '{0}'", siteName);

            foreach (var app in applicationsToRemove.ToArray())
            {
                adminSite.Applications.Remove(app);
            }
        }
        private void Initialize()
        {
            if (this.Initialized)
            {
                return;
            }

            this.Initialized = true;
            PreInitialize();
            var machineConfig = Helper.IsRunningOnMono()
                ? "/Library/Frameworks/Mono.framework/Versions/Current/etc/mono/4.5/machine.config"
                : Path.Combine(
                                    Environment.GetFolderPath(Environment.SpecialFolder.Windows),
                                    "Microsoft.NET",
                                    IntPtr.Size == 2 ? "Framework" : "Framework64",
                                    "v4.0.30319",
                                    "config",
                                    "machine.config");
            var machine =
                new Configuration(
                    new FileContext(
                        this,
                        machineConfig,
                        null,
                        null,
                        false,
                        true,
                        true));
            var webConfig = Helper.IsRunningOnMono()
                ? "/Library/Frameworks/Mono.framework/Versions/Current/etc/mono/4.5/web.config"
                : Path.Combine(
                                Environment.GetFolderPath(Environment.SpecialFolder.Windows),
                                "Microsoft.NET",
                                IntPtr.Size == 2 ? "Framework" : "Framework64",
                                "v4.0.30319",
                                "config",
                                "web.config");
            var web =
                new Configuration(
                    new FileContext(
                        this,
                        webConfig,
                        machine.FileContext,
                        null,
                        false,
                        true,
                        true));

            _applicationHost =
                new Configuration(
                new FileContext(this, this.FileName, web.FileContext, null, true, false, this.ReadOnly));

            this.LoadCache();

            var poolSection = _applicationHost.GetSection("system.applicationHost/applicationPools");
            _applicationPoolDefaults =
                new ApplicationPoolDefaults(poolSection.GetChildElement("applicationPoolDefaults"), poolSection);
            this.ApplicationPoolCollection = new ApplicationPoolCollection(poolSection, this);
            var siteSection = _applicationHost.GetSection("system.applicationHost/sites");
            _siteDefaults = new SiteDefaults(siteSection.GetChildElement("siteDefaults"), siteSection);
            _applicationDefaults = new ApplicationDefaults(
                siteSection.GetChildElement("applicationDefaults"),
                siteSection);
            _virtualDirectoryDefaults =
                new VirtualDirectoryDefaults(siteSection.GetChildElement("virtualDirectoryDefaults"), siteSection);
            this.SiteCollection = new SiteCollection(siteSection, this);

            PostInitialize();
        }
예제 #44
0
 public Enterprise(string name)
 {
     this.name = name;
     Site = new SiteCollection(this);
 }
예제 #45
0
 public SiteValidateTool(SiteCollection siteColl, GeoInfoObserver geoInfo)
 {
     this.m_SiteCollection = siteColl;
     this.m_GeoInfo = geoInfo;
 }
예제 #46
0
        public NewSiteDialog(IServiceProvider serviceProvider, SiteCollection collection)
            : base(serviceProvider)
        {
            InitializeComponent();
            cbType.SelectedIndex = 0;
            if (collection == null)
            {
                throw new InvalidOperationException("null collection");
            }

            if (collection.Parent == null)
            {
                throw new InvalidOperationException("null server for site collection");
            }

            btnBrowse.Visible = collection.Parent.IsLocalhost;
            txtPool.Text      = collection.Parent.ApplicationDefaults.ApplicationPoolName;
            btnChoose.Enabled = collection.Parent.Mode != WorkingMode.Jexus;
            txtHost.Text      = collection.Parent.Mode == WorkingMode.IisExpress ? "localhost" : string.Empty;
            DialogHelper.LoadAddresses(cbAddress);
            if (!collection.Parent.SupportsSni)
            {
                cbSniRequired.Enabled = false;
            }

            var container = new CompositeDisposable();

            FormClosed += (sender, args) => container.Dispose();

            container.Add(
                Observable.FromEventPattern <EventArgs>(cbType, "SelectedIndexChanged")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                txtPort.Text            = cbType.Text == "http" ? "80" : "443";
                txtCertificates.Visible = cbType.SelectedIndex == 1;
                cbSniRequired.Visible   = cbType.SelectedIndex == 1;
                cbCertificates.Visible  = cbType.SelectedIndex == 1;
                btnSelect.Visible       = cbType.SelectedIndex == 1;
                btnView.Visible         = cbType.SelectedIndex == 1;
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnBrowse, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                DialogHelper.ShowBrowseDialog(txtPath);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                foreach (var ch in SiteCollection.InvalidSiteNameCharacters())
                {
                    if (txtName.Text.Contains(ch))
                    {
                        MessageBox.Show("The site name cannot contain the following characters: '\\, /, ?, ;, :, @, &, =, +, $, ,, |, \", <, >'.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }

                foreach (var ch in SiteCollection.InvalidSiteNameCharactersJexus())
                {
                    if (txtName.Text.Contains(ch) || txtName.Text.StartsWith("~"))
                    {
                        MessageBox.Show("The site name cannot contain the following characters: '~,  '.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }

                if (!collection.Parent.Verify(txtPath.Text))
                {
                    MessageBox.Show("The specified directory does not exist on the server.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                if (!IPEndPointIsValid(out IPAddress address, out int port))
                {
                    return;
                }

                var invalid = "\"/\\[]:|<>+=;,?*$%#@{}^`".ToCharArray();
                foreach (var ch in invalid)
                {
                    if (txtHost.Text.Contains(ch))
                    {
                        MessageBox.Show("The specified host name is incorrect. The host name must use a valid host name format and cannot contain the following characters: \"/\\[]:|<>+=;,?*$%#@{}^`. Example: www.contoso.com.", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                }

                if (collection.Parent.Mode == WorkingMode.IisExpress)
                {
                    if (txtHost.Text != "localhost")
                    {
                        MessageBox.Show(
                            "The specific host name is not recommended for IIS Express. The host name should be localhost.",
                            Text,
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Warning);
                    }
                }

                long largestId = 0;
                foreach (Site site in collection)
                {
                    if (site.Id > largestId)
                    {
                        largestId = site.Id;
                    }
                }

                largestId++;

                NewSite = new Site(collection)
                {
                    Name = txtName.Text, Id = largestId
                };
                var host    = txtHost.Text.DisplayToHost();
                var info    = cbType.Text == "https" ? (CertificateInfo)cbCertificates.SelectedItem : null;
                var binding = new Binding(
                    cbType.Text,
                    string.Format("{0}:{1}:{2}", address.AddressToDisplay(), port, host.HostToDisplay()),
                    info?.Certificate.GetCertHash() ?? new byte[0],
                    info?.Store,
                    cbSniRequired.Checked ? SslFlags.Sni : SslFlags.None,
                    NewSite.Bindings);
                if (collection.FindDuplicate(binding, null, null) != false)
                {
                    var result = MessageBox.Show(string.Format("The binding '{0}' is assigned to another site. If you assign the same binding to this site, you will only be able to start one of the sites. Are you sure that you want to add this duplicate binding?", binding), Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result != DialogResult.Yes)
                    {
                        collection.Remove(NewSite);
                        return;
                    }
                }

                if (collection.Parent.Mode == WorkingMode.IisExpress)
                {
                    var result = binding.FixCertificateMapping(info?.Certificate);
                    if (!string.IsNullOrEmpty(result))
                    {
                        collection.Remove(NewSite);
                        MessageBox.Show(string.Format("The binding '{0}' is invalid: {1}", binding, result), Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

                var app  = NewSite.Applications.Add(Application.RootPath, txtPath.Text);
                app.Name = string.Empty;
                app.ApplicationPoolName = txtPool.Text;
                NewSite.Bindings.Add(binding);
                DialogResult = DialogResult.OK;
            }));

            var certificatesSelected = Observable.FromEventPattern <EventArgs>(cbCertificates, "SelectedIndexChanged");

            container.Add(
                certificatesSelected
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                btnView.Enabled = cbCertificates.SelectedIndex > 0;
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(txtName, "TextChanged")
                .Merge(Observable.FromEventPattern <EventArgs>(txtPath, "TextChanged"))
                .Merge(Observable.FromEventPattern <EventArgs>(txtPort, "TextChanged"))
                .Merge(Observable.FromEventPattern <EventArgs>(cbAddress, "TextChanged"))
                .Merge(certificatesSelected)
                .Sample(TimeSpan.FromSeconds(1))
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                if (Helper.IsRunningOnMono())
                {
                    return;
                }

                var toElevate = IPEndPointIsValid(out IPAddress address, out int port, false) ? BindingUtility.Verify(cbType.Text, cbAddress.Text, txtPort.Text, cbCertificates.SelectedItem as CertificateInfo) : false;
                btnOK.Enabled = toElevate != null && !string.IsNullOrWhiteSpace(txtName.Text) &&
                                !string.IsNullOrWhiteSpace(txtPath.Text);
                if (!toElevate.HasValue || !toElevate.Value)
                {
                    NativeMethods.RemoveShieldFromButton(btnOK);
                }
                else
                {
                    NativeMethods.TryAddShieldToButton(btnOK);
                }
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnView, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                var info = (CertificateInfo)cbCertificates.SelectedItem;
                DialogHelper.DisplayCertificate(info.Certificate, this.Handle);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnChoose, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                var dialog = new SelectPoolDialog(txtPool.Text, collection.Parent);
                if (dialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                txtPool.Text = dialog.Selected.Name;
            }));
        }
예제 #47
0
 public SiteValidator(CollectionsModel model)
 {
     this.m_Model = model;
     this.m_SiteColl = model.SiteColl;
     this.m_UserDesc = new UserDefineDesc(model.UserItemsColl.SiteExtDefList, new List<ExtDefKeyValue>());
 }
예제 #48
0
파일: SiteInfo.cs 프로젝트: xingfudaiyan/OA
        /// <summary>
        /// 获得分页列表,无论是否是缓存实体都从数据库直接拿取数据
        /// </summary>
        /// <param name="pPageIndex">页数</param>
        /// <param name="pPageSize">每页列表</param>
        /// <param name="pOrderBy">排序</param>
        /// <param name="pSortExpression">排序字段</param>
        /// <param name="pRecordCount">列表行数</param>
        /// <returns>数据分页</returns>
        public static List<SiteInfo> GetPagedList(int pPageIndex,int pPageSize,SortDirection pOrderBy,string pSortExpression,out int pRecordCount)
        {
            if(pPageIndex<=1)
            pPageIndex=1;
            List< SiteInfo> list = new List< SiteInfo>();

            Query q = Site .CreateQuery();
            q.PageIndex = pPageIndex;
            q.PageSize = pPageSize;
            q.ORDER_BY(pSortExpression,pOrderBy.ToString());
            SiteCollection  collection=new  SiteCollection();
             	collection.LoadAndCloseReader(q.ExecuteReader());

            foreach (Site  site  in collection)
            {
                SiteInfo siteInfo = new SiteInfo();
                LoadFromDAL(siteInfo,   site);
                list.Add(siteInfo);
            }
            pRecordCount=q.GetRecordCount();

            return list;
        }
예제 #49
0
파일: SiteInfo.cs 프로젝트: xingfudaiyan/OA
 /// <summary>
 /// 获得数据列表
 /// </summary>
 /// <returns></returns>
 public static List<SiteInfo> GetList()
 {
     string cacheKey = GetCacheKey();
     //本实体已经注册成缓存实体,并且缓存存在的时候,直接从缓存取
     if (CachedEntityCommander.IsTypeRegistered(typeof(SiteInfo)) && CachedEntityCommander.GetCache(cacheKey) != null)
     {
         return CachedEntityCommander.GetCache(cacheKey) as List< SiteInfo>;
     }
     else
     {
         List< SiteInfo>  list =new List< SiteInfo>();
         SiteCollection  collection=new  SiteCollection();
         Query qry = new Query(Site.Schema);
         collection.LoadAndCloseReader(qry.ExecuteReader());
         foreach(Site site in collection)
         {
             SiteInfo siteInfo= new SiteInfo();
             LoadFromDAL(siteInfo,site);
             list.Add(siteInfo);
         }
       	//生成缓存
         if (CachedEntityCommander.IsTypeRegistered(typeof(SiteInfo)))
         {
             CachedEntityCommander.SetCache(cacheKey, list);
         }
         return list;
     }
 }
예제 #50
0
        private void CertWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            // expirations currently does not work correctly
            try
            {
                using (ServerManager manager = new ServerManager())
                {
                    SiteCollection siteCollection = manager.Sites;
                    List <string>  sites          = new List <string>();
                    //List<string> expirations = new List<string>();
                    foreach (Site site in siteCollection)
                    {
                        if (site.State != ObjectState.Started)
                        {
                            continue;
                        }

                        EventLog.WriteEntry(Source, $"Getting https bindings for {site.Name} (ID: {site.Id})", EventLogEntryType.Information);
                        List <string>           bindingNames = new List <string>();
                        List <X509Certificate2> certHashes   = new List <X509Certificate2>();
                        foreach (Binding binding in site.Bindings)
                        {
                            bindingNames.Add(binding.Host);
                            if (binding.Protocol == "https" && binding.CertificateHash != null && binding.CertificateHash.Length > 0)
                            {
                                var store = new X509Store("Web Hosting", StoreLocation.LocalMachine);
                                store.Open(OpenFlags.ReadOnly);
                                var storeCerts = store.Certificates.Find(X509FindType.FindByThumbprint, binding.CertificateHash.ToHex(), false);
                                EventLog.WriteEntry(Source, $"storeCerts in Web Hosting for {binding.Host} = {storeCerts.Count}", EventLogEntryType.Information);
                                if (storeCerts.Count > 0)
                                {
                                    certHashes.Add(storeCerts[0]);
                                }
                                else
                                {
                                    store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                                    store.Open(OpenFlags.ReadOnly);
                                    storeCerts = store.Certificates.Find(X509FindType.FindByThumbprint, binding.CertificateHash.ToHex(), false);
                                    EventLog.WriteEntry(Source, $"storeCerts in My for {binding.Host} = {storeCerts.Count}", EventLogEntryType.Information);
                                    if (storeCerts.Count > 0)
                                    {
                                        certHashes.Add(storeCerts[0]);
                                    }
                                    //else
                                    //{
                                    //    expirations.Add(site.Name + " (no certificates in store for " + binding.Host + ", Thumbprint: " + binding.CertificateHash.ToHex() + ")");
                                    //}
                                }
                            }
                            else if (binding.Protocol == "https" && (binding.CertificateHash == null || binding.CertificateHash.Length == 0))
                            {
                                sites.Add(site.Name + " (no certificate detected on https binding for " + binding.Host + ")");
                            }
                        }
                        foreach (var cert in certHashes)
                        {
                            //EventLog.WriteEntry(Source, $"var cert.NotAfter = {cert.NotAfter}\nvar DateTime.Now = {DateTime.Now}\nvar TotalDays = {(cert.NotAfter - DateTime.Now).TotalDays}", EventLogEntryType.Information);
                            //if ((cert.NotAfter - DateTime.Now).TotalDays < 30)
                            //{
                            //    if (!expirations.Contains(site.Name))
                            //        expirations.Add(site.Name);
                            //}
                            var names = ParseSujectAlternativeNames(cert);
                            if (!bindingNames.Any(x => cert.FriendlyName.Contains(x) || cert.FriendlyName.Contains("*." + x) || names.Contains(x) || names.Contains(_parser.Get(x).RegistrableDomain)))
                            {
                                sites.Add(site.Name);
                                break;
                            }
                        }
                    }
                    SendCertNotification(sites);
                    //SendExpirationNotification(expirations);
                }
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(Source, $"{ex.Message}\n\n{ex.StackTrace}", EventLogEntryType.Error);
            }
        }
 public void Clear()
 {
     _siteDictionary = null;
     _sitesCollection = null;
 }
예제 #52
0
        private void run()
        {
            try
            {
                //int step = 0;
                DataRow row = dt.NewRow();
                //https://stackoverflow.com/questions/4593412/list-all-websites-in-iis-c-sharp
                var            iisManager = new ServerManager();
                SiteCollection sites      = iisManager.Sites;
                //_form.my.file_put_contents(_form.my.pwd() + "\\log\\iislog.txt", "");
                List <string> field_same_arr = new List <string>();
                foreach (Microsoft.Web.Administration.Site site in sites)
                {
                    row = dt.NewRow();
                    //_form.my.file_put_contents(_form.my.pwd() + "\\log\\iislog.txt", sites[i]., true);
                    row["iis_site_id"]   = site.Id;
                    row["iis_site_name"] = site.Name;
                    //row["iis_site_name"] = site.Applications["/"].ApplicationPoolName;
                    row["iis_Path"]         = site.Applications["/"].Path;
                    row["iis_PhysicalPath"] = site.Applications["/"].VirtualDirectories["/"].PhysicalPath;
                    row["iis_PhysicalPath"] = row["iis_PhysicalPath"].ToString().Replace("%SystemDrive%", _form.my.getenv("SystemDrive"));
                    //row["iis_Path"] = row["iis_Path"].ToString().Replace("/", "\\");
                    row["iis_IsWebconfigEncrypt"] = "檔案不存在";
                    row["iis_customErrors"]       = "檔案不存在";
                    row["iis_sessionTimeout"]     = "檔案不存在";
                    row["iis_mimeMap"]            = "檔案不存在";
                    row["iis_defaultDocument"]    = "檔案不存在";
                    string webconfig = row["iis_PhysicalPath"] + "\\web.config";
                    if (_form.my.is_file(webconfig))
                    {
                        string data = _form.my.b2s(_form.my.file_get_contents(webconfig));
                        var    m    = _form.my.explode("\n", data);
                        if (_form.my.is_istring_like(data, "EncryptedKey"))
                        {
                            row["iis_IsWebconfigEncrypt"] = "Y";
                        }
                        else
                        {
                            row["iis_IsWebconfigEncrypt"] = "N";
                        }
                        if (_form.my.is_istring_like(data, "customErrors"))
                        {
                            row["iis_customErrors"] = "Y";
                        }
                        else
                        {
                            row["iis_customErrors"] = "N";
                        }
                        if (!_form.my.is_istring_like(data, "sessionState"))
                        {
                            row["iis_sessionTimeout"] = "未設定";
                        }
                        else
                        {
                            row["iis_sessionTimeout"] = "未設定";
                            XmlDocument doc = new XmlDocument();
                            doc.Load(webconfig);
                            if (doc != null)
                            {
                                if (doc.GetElementsByTagName("sessionState").Count != 0)
                                {
                                    if (doc.GetElementsByTagName("sessionState")[0].Attributes["timeout"] != null)
                                    {
                                        row["iis_sessionTimeout"] = doc.GetElementsByTagName("sessionState")[0].Attributes["timeout"].Value;
                                    }
                                }
                            }
                        }
                        if (!_form.my.is_istring_like(data, "mimeMap"))
                        {
                            row["iis_mimeMap"] = "未設定";
                        }
                        else
                        {
                            row["iis_mimeMap"] = "未設定";
                            XmlDocument doc = new XmlDocument();
                            doc.Load(webconfig);
                            if (doc != null)
                            {
                                List <string> mimeMapArr = new List <string>();
                                for (int i = 0; i < doc.GetElementsByTagName("mimeMap").Count; i++)
                                {
                                    string d = doc.GetElementsByTagName("mimeMap")[i].Attributes["fileExtension"].Value + "|" + doc.GetElementsByTagName("mimeMap")[i].Attributes["mimeType"].Value;
                                    mimeMapArr.Add(d);
                                }
                                row["iis_mimeMap"] = _form.my.implode("|||", mimeMapArr);
                            }
                        }
                        if (!_form.my.is_istring_like(data, "defaultDocument"))
                        {
                            row["iis_defaultDocument"] = "未設定";
                        }
                        else
                        {
                            row["iis_defaultDocument"] = "未設定";
                            XmlDocument doc = new XmlDocument();
                            doc.Load(webconfig);
                            if (doc != null)
                            {
                                XmlNodeList   f  = doc.SelectNodes("configuration/system.webServer/defaultDocument/files/add");
                                List <string> mm = new List <string>();
                                for (int i = 0; i < f.Count; i++)
                                {
                                    XmlElement element = (XmlElement)f[i];
                                    //XmlAttribute attribute = element.GetAttributeNode("value")
                                    XmlAttributeCollection attributes = element.Attributes;
                                    foreach (XmlAttribute item in attributes)
                                    {
                                        if (item.Name == "value")
                                        {
                                            mm.Add(item.Value);
                                        }
                                    }
                                }
                                row["iis_defaultDocument"] = _form.my.implode("|||", mm);
                            }
                        }
                    }
                    string check_same_concat = row["iis_site_name"].ToString() + row["iis_PhysicalPath"].ToString() + row["iis_Path"].ToString();
                    //如果 name、PhysicalPath、Path 相同,就跳過
                    if (!_form.my.in_array(check_same_concat, field_same_arr))
                    {
                        field_same_arr.Add(check_same_concat);
                        dt.Rows.Add(row);
                    }
                    foreach (Microsoft.Web.Administration.Application app in iisManager.Sites[site.Name].Applications)
                    {
                        row = dt.NewRow();
                        row["iis_site_id"]             = site.Id;
                        row["iis_ApplicationPoolName"] = app.ApplicationPoolName;
                        row["iis_site_name"]           = site.Name;
                        row["iis_Path"] = app.Path;
                        if (row["iis_Path"] == null)
                        {
                            continue;
                        }
                        row["iis_PhysicalPath"] = site.Applications[row["iis_Path"].ToString()].VirtualDirectories["/"].PhysicalPath;
                        row["iis_PhysicalPath"] = row["iis_PhysicalPath"].ToString().Replace("%SystemDrive%", Environment.GetEnvironmentVariable("SystemDrive"));

                        //if (row["iis_PhysicalPath"].ToString().Substring(row["iis_PhysicalPath"].ToString().Length - 1, 1) == "\\")
                        //{
                        //    row["iis_PhysicalPath"] = row["iis_PhysicalPath"].ToString().Substring(0, row["iis_PhysicalPath"].ToString().Length - 1);
                        //}

                        webconfig = row["iis_PhysicalPath"] + "\\web.config";
                        row["iis_IsWebconfigEncrypt"] = "檔案不存在";
                        row["iis_customErrors"]       = "檔案不存在";
                        row["iis_sessionTimeout"]     = "檔案不存在";
                        row["iis_mimeMap"]            = "檔案不存在";
                        row["iis_defaultDocument"]    = "檔案不存在";
                        if (_form.my.is_file(webconfig))
                        {
                            string data = _form.my.b2s(_form.my.file_get_contents(webconfig));
                            data = data.Replace("\r", "");
                            var m = _form.my.explode("\n", data);
                            if (_form.my.is_istring_like(data, "EncryptedKey"))
                            {
                                row["iis_IsWebconfigEncrypt"] = "Y";
                            }
                            else
                            {
                                row["iis_IsWebconfigEncrypt"] = "N";
                            }
                            if (_form.my.is_istring_like(data, "customErrors"))
                            {
                                row["iis_customErrors"] = "Y";
                            }
                            else
                            {
                                row["iis_customErrors"] = "N";
                            }
                            if (!_form.my.is_istring_like(data, "sessionState"))
                            {
                                row["iis_sessionTimeout"] = "未設定";
                            }
                            else
                            {
                                row["iis_sessionTimeout"] = "未設定";
                                XmlDocument doc = new XmlDocument();
                                doc.Load(webconfig);
                                if (doc != null)
                                {
                                    if (doc.GetElementsByTagName("sessionState").Count != 0)
                                    {
                                        if (doc.GetElementsByTagName("sessionState")[0].Attributes["timeout"] != null)
                                        {
                                            row["iis_sessionTimeout"] = doc.GetElementsByTagName("sessionState")[0].Attributes["timeout"].Value;
                                        }
                                    }
                                    //row["iis_sessionTimeout"] = (doc.GetElementsByTagName("sessionState") != null) ?
                                    //(doc.GetElementsByTagName("sessionState")[0].Attributes["timeout"] == null) ? row["iis_sessionTimeout"] : doc.GetElementsByTagName("sessionState")[0].Attributes["timeout"].ToString() :
                                    //row["iis_sessionTimeout"];
                                }

                                /*
                                 * for (int i = 0, max_i = m.Count(); i < max_i; i++)
                                 * {
                                 *  if (_form.my.is_istring_like(m[i], "<sessionState"))
                                 *  {
                                 *      row["iis_sessionTimeout"] = _form.my.get_between(m[i], "timeout=\"", "\"");
                                 *      break;
                                 *  }
                                 * }
                                 */
                            }
                            if (!_form.my.is_istring_like(data, "mimeMap"))
                            {
                                row["iis_mimeMap"] = "未設定";
                            }
                            else
                            {
                                row["iis_mimeMap"] = "未設定";
                                XmlDocument doc = new XmlDocument();
                                doc.Load(webconfig);
                                if (doc != null)
                                {
                                    List <string> mimeMapArr = new List <string>();
                                    for (int i = 0; i < doc.GetElementsByTagName("mimeMap").Count; i++)
                                    {
                                        string d = doc.GetElementsByTagName("mimeMap")[i].Attributes["fileExtension"].Value + "|" + doc.GetElementsByTagName("mimeMap")[i].Attributes["mimeType"].Value;
                                        mimeMapArr.Add(d);
                                    }
                                    row["iis_mimeMap"] = _form.my.implode("|||", mimeMapArr);
                                }
                            }
                            if (!_form.my.is_istring_like(data, "defaultDocument"))
                            {
                                row["iis_defaultDocument"] = "未設定";
                            }
                            else
                            {
                                row["iis_defaultDocument"] = "未設定";
                                XmlDocument doc = new XmlDocument();
                                doc.Load(webconfig);
                                if (doc != null)
                                {
                                    XmlNodeList   f  = doc.SelectNodes("configuration/system.webServer/defaultDocument/files/add");
                                    List <string> mm = new List <string>();
                                    for (int i = 0; i < f.Count; i++)
                                    {
                                        XmlElement element = (XmlElement)f[i];
                                        //XmlAttribute attribute = element.GetAttributeNode("value")
                                        XmlAttributeCollection attributes = element.Attributes;
                                        foreach (XmlAttribute item in attributes)
                                        {
                                            if (item.Name == "value")
                                            {
                                                mm.Add(item.Value);
                                            }
                                        }
                                    }
                                    row["iis_defaultDocument"] = _form.my.implode("|||", mm);
                                }
                            }
                        }

                        //如果 site_name、PhysicalPath、Path 相同,就跳過
                        check_same_concat = row["iis_site_name"].ToString() + row["iis_PhysicalPath"].ToString() + row["iis_Path"].ToString();
                        if (!_form.my.in_array(check_same_concat, field_same_arr))
                        {
                            field_same_arr.Add(check_same_concat);
                            dt.Rows.Add(row);
                        }
                    }
                }
                //

                _form.updateDGVUI(_form.iis_grid, dt);
                //_form.my.file_put_contents(_form.my.pwd() + "\\log\\iislog.txt", _form.my.json_encode(dt));
                _form.setStatusBar("就緒", 0);
                is_running = false;
            }
            catch (Exception ex)
            {
                //_form.logError("IIS Error...:\r\n" + ex.Message + "\r\n" + ex.StackTrace);
                is_running = false;
            }
        }
        private static void RemoveApplications(SiteCollection iisSites, string siteName)
        {
            var adminSite = iisSites[roleWebSiteName];

            var applicationsToRemove = from app in adminSite.Applications
                                             where app.Path.EndsWith("/test/" + siteName, StringComparison.OrdinalIgnoreCase) ||
                                             app.Path.EndsWith("/cdn/" + siteName, StringComparison.OrdinalIgnoreCase)
                                             select app;

            TraceHelper.TraceInformation("IISManager.Removing Test and CDN applications for site '{0}'", siteName);

            foreach (var app in applicationsToRemove.ToArray())
            {
                adminSite.Applications.Remove(app);
            }
        }
예제 #54
0
        /// <summary>
        /// Get the Freedb sites
        /// </summary>
        /// <param name="protocol"></param>
        /// <param name="sites">SiteCollection that is populated with the site information</param>
        /// <returns>Response Code</returns>
        ///
        public string GetSites(string protocol, out SiteCollection sites)
        {
            if (protocol != Site.PROTOCOLS.CDDBP && protocol != Site.PROTOCOLS.HTTP)
            {
                protocol = Site.PROTOCOLS.ALL;
            }

            StringCollection coll;

            try
            {
                coll = Call(Commands.CMD_SITES, m_mainSite.GetUrl());
            }

            catch (Exception ex)
            {
                Debug.WriteLine("Error retrieving Sites." + ex.Message);
                Exception newEx = new Exception("FreedbHelper.GetSites: Error retrieving Sites.", ex);
                throw newEx;
            }

            sites = null;

            // check if results came back
            if (coll.Count < 0)
            {
                string    msg = "No results returned from sites request.";
                Exception ex  = new Exception(msg, null);
                throw ex;
            }

            string code = GetCode(coll[0]);

            if (code == ResponseCodes.CODE_INVALID)
            {
                string    msg = "Unable to process results Sites Request. Returned Data: " + coll[0];
                Exception ex  = new Exception(msg, null);
                throw ex;
            }

            switch (code)
            {
            case ResponseCodes.CODE_500:
                return(ResponseCodes.CODE_500);

            case ResponseCodes.CODE_401:
                return(ResponseCodes.CODE_401);

            case ResponseCodes.CODE_210:
            {
                coll.RemoveAt(0);
                sites = new SiteCollection();
                foreach (String line in coll)
                {
                    Debug.WriteLine("line: " + line);
                    Site site = new Site(line);
                    if (protocol == Site.PROTOCOLS.ALL)
                    {
                        sites.Add(new Site(line));
                    }
                    else if (site.Protocol == protocol)
                    {
                        sites.Add(new Site(line));
                    }
                }

                return(ResponseCodes.CODE_210);
            }

            default:
                return(ResponseCodes.CODE_500);
            }
        }
 internal Site(SiteCollection parent)
     : this(null, parent)
 { }