public DynamicLayoutFile(DocumentFile activeDocument, LayoutFile layout, Site site) : base(layout.SourceRelativePath) { this.ActiveDocument = activeDocument; this.Layout = layout; this.Site = site; }
public void BeginProcessRequest(Site site) { string sql = ""; int iResult = 0; this.Site = site; oDataIO = new DataIO(); SqlConnection Conn = new SqlConnection(); Conn = oDataIO.GetDBConnection("ProfilesDB"); sqlCmd = new SqlCommand(); sqlCmd.Connection = Conn; site.IsDone = false; _request = WebRequest.Create(site.URL); // Enter log record sql = "insert into FSLogOutgoing(FSID,SiteID,Details,SentDate,QueryString) " + " values ('" + site.FSID.ToString() + "'," + site.SiteID.ToString() + ",0,GetDate()," + cs(site.SearchPhrase) + ")"; sqlCmd.CommandText = sql; sqlCmd.CommandType = System.Data.CommandType.Text; iResult = sqlCmd.ExecuteNonQuery(); if (sqlCmd.Connection.State == System.Data.ConnectionState.Open) sqlCmd.Connection.Close(); _request.BeginGetResponse(new AsyncCallback(EndProcessRequest), site); }
void CheckPerformance(Type serializerType) { var instance = GetInstance(serializerType); var site = new Site { LocalUnits = new[] {"ali1", "ali2", "ali3", "ali4", "ali5"} .Select(CreateLocalUnit) .ToArray() }; var stopwatch = Stopwatch.StartNew(); var count = 1000; count.Times(() => { var transportMessageToSend = instance.Serialize(new Message { Messages = new object[] { site } }); var message = instance.Deserialize(new ReceivedTransportMessage { Body = transportMessageToSend.Body }); var deserializedSite = (Site)message.Messages[0]; deserializedSite.LocalUnits.Length.ShouldBe(site.LocalUnits.Length); }); var totalSeconds = stopwatch.Elapsed.TotalSeconds; var serializerName = serializerType.FullName ?? ""; Console.WriteLine(@"{0} {1} {2} roundtrips took {3:0.0} s - that's {4:0}/s", serializerName, new string('-', serializerName.Length), count, totalSeconds, count/totalSeconds); }
public DynamicRenderDocument(DocumentFile document, LayoutFile layout, Site site) : base(document.SourceRelativePath) { _document = document; _layout = layout; _site = site; }
public DynamicPaginator(DocumentFile activeDocument, Paginator Paginator, Site site) : base(null) { this.ActiveDocument = activeDocument; this.Paginator = Paginator; this.Site = site; }
public IEnumerator KongParse(string s) { var q = ParseQueryString(s); string name = q.Get("kongregate_username"); string id = q.Get("kongregate_user_id"); if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(id) && id != "0") { userId = id; _Loader.vkPassword = id; userName = name; Debug.LogWarning(userId); Debug.LogWarning(userName); if (string.IsNullOrEmpty(_Loader.playerName)) _Loader.playerName = name; site= Site.Kg; ExternalEval(@"kongregateAPI.loadAPI();"); vkLoggedIn = true; var url = "http://www.kongregate.com/api/user_info.json?user_id=" + userId; Debug.LogWarning(url); var w = new WWW(url); yield return w; if (!string.IsNullOrEmpty(w.error)) Debug.LogWarning(w.url + w.error); else { var data = JsonMapper.ToObject(w.text); _Loader.avatarUrl = data["avatar_url"].ToString(); Debug.LogWarning("avatar " + _Loader.avatarUrl); } } }
public IEnumerable<Site.SpellcheckResult> CheckPages(Guid siteId, IEnumerable<Guid> pageIds, Site.SpellcheckConfigurations configurations) { var results = new List<Site.SpellcheckResult>(); foreach (var pageId in pageIds) { var page = _blobs.Get<PageProfile>(new BlobReference(siteId, pageId)); var config = configurations.GetFor(page.Url); if (config == null) continue; var spellchecker = _spellcheckerFactory.CreateFor(config.PrimaryLanguageKey, config.SecondaryLanguageKey); var result = spellchecker.Check(page.Text); if (result.HasData) { results.Add(new Site.SpellcheckResult { PageId = pageId, ConfirmedMisspellings = result.Misspellings, PotentialMisspellings = result.PotentialMisspellings, SiteId = siteId }); } } return results; }
/// <summary> /// Try to authenticate the user with OpenID /// </summary> /// <param name="site"></param> /// <param name="externalId">OpenID identifier or Facebook User Id</param> /// <param name="ipAddress"></param> /// <param name="createPersistentCookie"></param> /// <returns></returns> public User AuthenticateUser(Site site, string externalId, string ipAddress, bool createPersistentCookie) { if (site == null) { const string msg = "FormsAuthenticationService.AuthenticateUser invoked with Site = NULL"; log.Error(msg); throw new ApplicationException(msg); } try { User user = userService.GetUserBySiteAndExternalId(site, externalId); if (user != null) { LogIn(user, ipAddress, createPersistentCookie); } else { log.WarnFormat("Invalid External Identifier: {0} on SiteId = {1}", externalId, site.SiteId.ToString()); } return user; } catch (Exception ex) { log.ErrorFormat("An error occured while logging in External Identifier {0} on SiteId = {1}", externalId, site.SiteId.ToString()); throw new Exception(String.Format("Unable to log in External Identifier '{0}': " + ex.Message, externalId), ex); } }
public void SetFeaturesForSite(Site site) { if (site.Features.Count > 0) { log.WarnFormat("Can't add Features to siteid {0} because it already has {1} features", site.SiteId.ToString(), site.Features.Count.ToString()); throw new ApplicationException("Site already has features!"); } IList<Feature> features = FindAll(); foreach (Feature feature in features) { SiteFeature sf = new SiteFeature() { Site = site, Feature = feature, Enabled = false, StartDate = DateTime.Now.ToUniversalTime(), EndDate = null }; site.Features.Add(sf); } siteService.SaveSite(site); }
/// <summary> /// Get a list of all the tags of a given site /// </summary> /// <param name="site"></param> /// <returns></returns> public IList<Tag> GetAllTagsBySite(Site site) { //string hql = "from Arashi.Core.Domain.Tag t where t.Site = :site order by t.Name asc"; return Session.GetNamedQuery("GetAllTagsBySite") .SetEntity("site", site) .List<Tag>(); }
/// <summary> /// Try to authenticate the user with username & password /// </summary> /// <param name="site"></param> /// <param name="email"></param> /// <param name="password"></param> /// <param name="ipAddress"></param> /// <param name="createPersistentCookie"></param> /// <returns></returns> public User AuthenticateUser(Site site, string email, string password, string ipAddress, bool createPersistentCookie) { string hashedPassword = password.EncryptToSHA2(); if (site == null) { const string msg = "FormsAuthenticationService.AuthenticateUser invoked with Site = NULL"; log.Error(msg); throw new ApplicationException(msg); } try { User user = userService.GetUserByEmailAndPassword(site, email, hashedPassword); if (user != null) { LogIn(user, ipAddress, createPersistentCookie); } else { log.WarnFormat("Invalid username-password combination: {0}:{1} on SiteId = {2}", email, password, site.SiteId.ToString()); } return user; } catch (Exception ex) { log.ErrorFormat("An error occured while logging in user {0} on SiteId = {1}", email, site.SiteId.ToString()); throw new Exception(String.Format("Unable to log in user '{0}': " + ex.Message, email), ex); } }
protected override Site CopySite(string sourceSiteId, string targetSiteName, string targetSiteDescription) { // Resolve source site id into its corresponding site object Site sourceSite = SiteConfiguration.FindExistingSiteByID(sourceSiteId); if (sourceSite == null) throw new Exception("Unable to find site with siteId = " + sourceSiteId); // Make sure target site directory does not already exist string physicalPath = string.Format("{0}\\{1}", AppSettings.AppsPhysicalDir, targetSiteName); if (System.IO.Directory.Exists(physicalPath)) throw new Exception("Site with name '" + targetSiteName + "' is in use already. Please try an alternate name."); // Create a new site Site targetSite = new Site(); targetSite.ID = Guid.NewGuid().ToString("N"); targetSite.IsHostedOnIIS = true; targetSite.Name = targetSiteName; targetSite.Description = targetSiteDescription; targetSite.PhysicalPath = physicalPath; targetSite.Url = string.Format("{0}/{1}", AppSettings.AppsBaseUrl.TrimEnd('/'), targetSiteName.TrimStart('/')); targetSite.ProductVersion = sourceSite.ProductVersion; // Copy files from source site directory to target site directory FaultContract Fault = null; if (!(new ApplicationBuilderHelper()).CopySite(sourceSite.PhysicalPath, targetSite, true, out Fault)) throw new Exception(Fault != null ? Fault.Message : "Unable to copy site"); // Update site database (XML file) SiteConfiguration.AddSite(targetSite); // Return target site object return targetSite; }
public SiteWithConfig() { Site = new Site(); SiteConfig = new SiteConfig(); AppSettings = new Hashtable(); DiagnosticsSettings = new DiagnosticsSettings(); }
private void WriteWebsite(Site websiteObject) { SiteConfig config = WebsitesClient.GetWebsiteConfiguration(websiteObject.Name); var diagnosticSettings = new DiagnosticsSettings(); try { diagnosticSettings = WebsitesClient.GetApplicationDiagnosticsSettings(websiteObject.Name); } catch { // Ignore exception and use default values } WebsiteInstance[] instanceIds; try { instanceIds = WebsitesClient.ListWebsiteInstances(websiteObject.WebSpace, websiteObject.Name); } catch { // TODO: Temporary workaround for issue where slots are not supported with this API (yet). instanceIds = new WebsiteInstance[0]; } WriteObject(new SiteWithConfig(websiteObject, config, diagnosticSettings, instanceIds), false); }
/// <summary> /// Get a ConnectionsPoolsSource given a SiteTable using the factory's default pool source /// </summary> /// <param name="sources">SiteTable</param> /// <returns>ConnectionPoolsSource</returns> public override object getPoolSources(object sources) { if (!(sources is SiteTable)) { throw new ArgumentException("Invalid source. Must supply a SiteTable"); } SiteTable siteTable = (SiteTable)sources; Site[] sites = new Site[siteTable.Sites.Count]; for (int i = 0; i < siteTable.Sites.Count; i++) { sites[i] = (Site)siteTable.Sites.GetByIndex(i); } ConnectionPoolsSource result = new ConnectionPoolsSource(); result.CxnSources = new Dictionary<string, ConnectionPoolSource>(); foreach (Site site in sites) { if (site.Sources == null || site.Sources.Length == 0) { continue; } for (int i = 0; i < site.Sources.Length; i++) { if (String.Equals(site.Sources[i].Protocol, "VISTA", StringComparison.CurrentCultureIgnoreCase) || String.Equals(site.Sources[i].Protocol, "PVISTA", StringComparison.CurrentCultureIgnoreCase)) { result.CxnSources.Add(site.Id, (ConnectionPoolSource)getPoolSource(site.Sources[i])); break; } } } return result; }
protected Page AddToCycleRetry(Request request, Site site) { Page page = new Page(request); object cycleTriedTimesObject = request.GetExtra(Request.CycleTriedTimes); if (cycleTriedTimesObject == null) { // 把自己加到目标Request中(无法控制主线程再加载此Request), 传到主线程后会把TargetRequest加到Pool中 request.Priority = 0; page.AddTargetRequest(request.PutExtra(Request.CycleTriedTimes, 1)); } else { long cycleTriedTimes = (long)cycleTriedTimesObject; cycleTriedTimes++; if (cycleTriedTimes >= site.CycleRetryTimes) { // 超过最大尝试次数, 返回空. return null; } request.Priority = 0; page.AddTargetRequest(request.PutExtra(Request.CycleTriedTimes, cycleTriedTimes)); } page.SetNeedCycleRetry(true); return page; }
public SiteDownloadContext(Site site, DownloadOptions options, IList<PageLevel> downloadedPages, Queue<PageLevel> downloadQueue) { this.Site = site; this.Options = options; this.DownloadedPages = downloadedPages ?? new List<PageLevel>(); this.DownloadQueue = downloadQueue ?? new Queue<PageLevel>(); }
///<summary>Inserts one Site into the database. Returns the new priKey.</summary> internal static long Insert(Site site) { if(DataConnection.DBtype==DatabaseType.Oracle) { site.SiteNum=DbHelper.GetNextOracleKey("site","SiteNum"); int loopcount=0; while(loopcount<100){ try { return Insert(site,true); } catch(Oracle.DataAccess.Client.OracleException ex){ if(ex.Number==1 && ex.Message.ToLower().Contains("unique constraint") && ex.Message.ToLower().Contains("violated")){ site.SiteNum++; loopcount++; } else{ throw ex; } } } throw new ApplicationException("Insert failed. Could not generate primary key."); } else { return Insert(site,false); } }
private static void ConnectToSite() { Console.WriteLine("Please enter the URL to the SharePoint Site"); url = Console.ReadLine(); Console.WriteLine("Please enter the username"); username = Console.ReadLine(); Console.WriteLine("Please enter the password"); SecureString securepassword = getpassword(); clientContext = new ClientContext(url); password = new SecureString(); string charpassword = new NetworkCredential(string.Empty, securepassword).Password; foreach (char c in charpassword.ToCharArray()) password.AppendChar(c); clientContext.Credentials = new SharePointOnlineCredentials(username, password); site = clientContext.Site; clientContext.Load(site); clientContext.ExecuteQuery(); siteRelativeUrl = site.ServerRelativeUrl; clientContext.Load(site.RootWeb); clientContext.ExecuteQuery(); Console.WriteLine(""); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Successfully connected to site at " + site.Url); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Press any key to continue.."); Console.ReadLine(); }
internal override void ExecuteCommand() { Site website = null; InvokeInOperationContext(() => { website = RetryCall(s => Channel.GetSite(s, Name, null)); }); if (website == null) { throw new Exception(string.Format(Resources.InvalidWebsite, Name)); } InvokeInOperationContext(() => { Site websiteUpdate = new Site { Name = Name, HostNames = new [] { Name + General.AzureWebsiteHostNameSuffix }, State = "Stopped" }; RetryCall(s => Channel.UpdateSite(s, website.WebSpace, Name, websiteUpdate)); }); }
public DynamicBookPage(DocumentFile activeDocument, BookPage bookPage, Site site) : base(null) { this.ActiveDocument = activeDocument; this.BookPage = bookPage; this.Site = site; }
/// <summary> /// Récupère une Site à partir d'un identifiant de client /// </summary> /// <param name="Identifiant">Identifant de Site</param> /// <returns>Un Site </returns> public static Site Get(Int32 identifiant) { //Connection ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings["EntretienSPPPConnectionString"]; SqlConnection connection = new SqlConnection(connectionStringSettings.ToString()); //Commande String requete = @"SELECT Identifiant, Libelle, Adresse FROM Site WHERE Identifiant = @Identifiant"; SqlCommand commande = new SqlCommand(requete, connection); //Paramètres commande.Parameters.AddWithValue("Identifiant", identifiant); //Execution connection.Open(); SqlDataReader dataReader = commande.ExecuteReader(); dataReader.Read(); //1 - Création du Site Site site = new Site(); site.Identifiant = dataReader.GetInt32(0); site.Libelle = dataReader.GetString(1); site.Adresse = dataReader.GetString(2); dataReader.Close(); connection.Close(); return site; }
public DynamicDocumentFile(DocumentFile activeDocument, DocumentFile document, Site site) : base(document) { this.ActiveDocument = activeDocument; this.Document = document; this.Site = site; }
/// <summary> /// /// </summary> /// <param name="ctx"></param> /// <param name="site"></param> /// <param name="name"></param> public void AddUserVisitorGroup(ClientContext ctx, Site site, string name) { if(string.IsNullOrWhiteSpace(name)) { //TODO LOG } }
private void DeploySearchConfiguration(object modelHost, Site site, SearchConfigurationDefinition definition) { var context = site.Context; var conf = new SearchConfigurationPortability(context); var owner = new SearchObjectOwner(context, SearchObjectLevel.SPSite); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = conf, ObjectType = typeof(SearchConfigurationPortability), ObjectDefinition = definition, ModelHost = modelHost }); conf.ImportSearchConfiguration(owner, definition.SearchConfiguration); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = conf, ObjectType = typeof(SearchConfigurationPortability), ObjectDefinition = definition, ModelHost = modelHost }); context.ExecuteQueryWithTrace(); }
private string Generate(Site site) { StringBuilder sb = new StringBuilder(); sb.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"); sb.AppendLine("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">"); foreach (var post in site.Posts) { sb.AppendLine("\t<url>"); sb.AppendLine("\t\t<loc>http://zacharysnow.net/" + post.Permalink + "</loc>"); sb.AppendLine("\t</url>"); } foreach (var page in site.Pages) { sb.AppendLine("\t<url>"); sb.AppendLine("\t\t<loc>http://zacharysnow.net/" + page.Permalink + "</loc>"); sb.AppendLine("\t</url>"); } foreach (var page in site.GeneratorPages.Where(x => x.Data.IsRedirect != true)) { sb.AppendLine("\t<url>"); sb.AppendLine("\t\t<loc>http://zacharysnow.net/" + page.Permalink + "</loc>"); sb.AppendLine("\t</url>"); } sb.AppendLine("</urlset>"); sb.AppendLine(); return sb.ToString(); }
void CloneAndSendLocal(TransportMessage messageToDispatch, Site destinationSite) { //todo - do we need to clone? check with Jonathan O messageToDispatch.Headers[Headers.DestinationSites] = destinationSite.Key; MessageSender.Send(messageToDispatch, InputAddress); }
public string Generate(Site site) { StringBuilder sb = new StringBuilder(); DateTime pubDate = (DateTime)site.Content.Select(x => x.LastUpdate).Max(); sb.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"); sb.AppendLine("<rss version=\"2.0\">"); sb.AppendLine("\t<channel>"); sb.AppendLine("\t<title>The Blog of Zachary Snow</title>"); sb.AppendLine("\t<description>The Blog of Zachary Snow</description>"); sb.AppendLine("\t<link>http://www.zacharysnow.net/</link>"); sb.AppendLine("\t<lastBuildDate>" + DateTime.Now.ToString("r") + "</lastBuildDate>"); sb.AppendLine("\t<pubDate>" + pubDate.ToString("r") + "</pubDate>"); sb.AppendLine("\t<ttl>1800</ttl>"); foreach (var post in site.Posts.Take(20)) { sb.AppendLine("\t<item>"); sb.AppendLine("\t\t<title><![CDATA[" + post.Title + "]]></title>"); sb.AppendLine("\t\t<description><![CDATA[" + post.Excerpt + "]]></description>"); sb.AppendLine("\t\t<link>http://www.zacharysnow.net/" + post.Permalink + "</link>"); sb.AppendLine("\t\t<guid>http://www.zacharysnow.net/" + post.Permalink + "</guid>"); sb.AppendLine("\t\t<pubDate>" + post.Date.ToString("r") + "</pubDate>"); sb.AppendLine("\t</item>"); } sb.AppendLine("\t</channel>"); sb.AppendLine("</rss>"); sb.AppendLine(); return sb.ToString(); }
public void Test_AddSubSite_ChildSites() { var sampleSite = new Site("SampleSite"); var cnSubSite = new Site(sampleSite, "cn") { Bindings = new[] { new Binding(){ Domain = "192.168.1.1", SitePath = "cn" } } }; siteProvider.Add(cnSubSite); var childSites = siteProvider.ChildSites(sampleSite); Assert.AreEqual(1, childSites.Count()); var actualSubSite = siteProvider.Get(cnSubSite); Assert.AreEqual("SampleSite~cn", actualSubSite.AbsoluteName); Assert.AreEqual("192.168.1.1", actualSubSite.Bindings[0].Domain); Assert.AreEqual("cn", actualSubSite.Bindings[0].SitePath); siteProvider.Remove(cnSubSite); }
void ApplyRules(IEnumerable<StaticFile> staticFiles, Site site, string outputDirectory) { foreach (StaticFile staticFile in staticFiles) { ApplyRouteRule(staticFile, site, outputDirectory); ApplyCompileRule(staticFile, site); } }
public UndoRedoAction PrepareForPolylineCornerRemoval(IViewerObject affectedEdge, Site site) { var action = new SiteRemoveUndoAction(EditedEdge) { RemovedSite = site, }; action.AddAffectedObject(affectedEdge); return(InsertToListAndSetTheBoxBefore(action)); }
/// <summary> /// </summary> /// <param name="delta">delta of the drag</param> /// <param name="e">the modified edge</param> /// <param name="site"></param> internal static void DragEdgeWithSite(Point delta, GeomEdge e, Site site) { e.RaiseLayoutChangeEvent(delta); site.Point += delta; CreateCurveOnChangedPolyline(e); }
public bool IsContentModelPlugin(Site site, Channel channel) { return(!string.IsNullOrEmpty(channel.TableName)); }
public string GetTableName(Site site, IChannelSummary channel) { return(channel != null?GetTableName(site, channel.TableName) : string.Empty); }
public async Task <string> GetTableNameAsync(Site site, int channelId) { return(GetTableName(site, await GetAsync(channelId))); }
static bool BetweenSites(Site prevSite, Site nextSite, Point point) { double par = Point.ClosestParameterOnLineSegment(point, prevSite.Point, nextSite.Point); return(par > 0.1 && par < 0.9); }
/// <summary> /// prepare for polyline corner insertion /// </summary> /// <param name="affectedObj">edited objects</param> /// <param name="site">the site to insert</param> /// <returns></returns> internal UndoRedoAction PrepareForPolylineCornerInsertion(IViewerObject affectedObj, Site site) { var action = new SiteInsertUndoAction(EditedEdge) { InsertedSite = site, }; action.AddAffectedObject(affectedObj); return(InsertToListAndSetTheBoxBefore(action)); }
public override object[] ExpandIdentifier(string typeName, object[] partialIdentifier) { if (typeName == null) { throw new ArgumentNullException("typeName"); } VfpClientTracing.Tracer.TraceVerbose("VfpObjectIdentifierResolver-ExpandIdentifier-typeName = " + typeName); // Find the type in the data object support model IVsDataObjectType type = null; var objectSupportModel = Site.GetService(typeof(IVsDataObjectSupportModel)) as IVsDataObjectSupportModel; Debug.Assert(objectSupportModel != null); if (objectSupportModel != null && objectSupportModel.Types.ContainsKey(typeName)) { type = objectSupportModel.Types[typeName]; } if (type == null) { throw new ArgumentException("Invalid type " + typeName + "."); } // Create an identifier array of the correct full length var identifier = new object[type.Identifier.Count]; // If the input identifier is not null, copy it to the full // identifier array. If the input identifier's length is less // than the full length we assume the more specific parts are // specified and thus copy into the rightmost portion of the // full identifier array. if (partialIdentifier != null) { if (partialIdentifier.Length > type.Identifier.Count) { throw new ArgumentException("Invalid partial identifier."); } partialIdentifier.CopyTo(identifier, type.Identifier.Count - partialIdentifier.Length); } // Get the data source information service IVsDataSourceInformation sourceInformation = Site.GetService(typeof(IVsDataSourceInformation)) as IVsDataSourceInformation; Debug.Assert(sourceInformation != null); if (sourceInformation == null) { // This should never occur return(identifier); } // Now expand the identifier as required if (type.Identifier.Count > 0) { // Fill in the current database if not specified if (!(identifier[0] is string)) { identifier[0] = sourceInformation[DataSourceInformation.DefaultCatalog] as string; } } if (type.Identifier.Count > 1) { // Fill in the default schema if not specified if (!(identifier[1] is string)) { identifier[1] = sourceInformation[DataSourceInformation.DefaultSchema] as string; } } return(identifier); }
public static List <Collection> GetCollections(List <int> Ids = null) { List <Collection> collections = new List <Collection>(); string selector = DbManager.SelectorBuilder(Ids); SqlConnection con = DbManager.GetConnection(); SqlCommand cmd = con.CreateCommand(); cmd.CommandText = "SELECT [Id],[CaptureDateTime],[Catalogue],[Object],[ObjectTitle]," + "[NumberFrames],[FileFormat],[ColorSpace],[Camera],[Scope],[Site],[Optics]," + "[Photographer],[Resolution],[Comments],[FilePath],[MetadataFilePath] " + "FROM [tblCollections] " + selector; SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { int id = reader.GetInt32(0); DateTime captureDateTime = reader.GetDateTime(1); Catalogue catalogue = CatalogueController.GetCatalogues(new List <int>() { reader.GetInt32(2) })[0]; int objectId = reader.GetInt32(3); string objectTitle = reader.GetString(4); int numberFrames = reader.GetInt32(5); FileFormat fileFormat = FileFormatController.GetFileFormats(new List <int>() { reader.GetInt32(6) })[0]; ColorSpace colorSpace = ColorSpaceController.GetColorSpaces(new List <int>() { reader.GetInt32(7) })[0]; Camera camera = CameraController.GetCameras(new List <int>() { reader.GetInt32(8) })[0]; Scope scope = ScopeController.GetScopes(new List <int>() { reader.GetInt32(9) })[0]; Site site = SiteController.GetSites(new List <int>() { reader.GetInt32(10) })[0]; List <Optic> optics = OpticsController.GetOptics(Utilities.StringToIntList(reader.GetString(11))); Photographer photographer = PhotographerController.GetPhotographers(new List <int>() { reader.GetInt32(12) })[0]; Size resolution = Utilities.StringToResolution(reader.GetString(13)); string comments = reader.GetString(14); string filePath = reader.GetString(15); string metadataFile = reader.GetString(16); collections.Add(new Collection(id, captureDateTime, catalogue, objectId, objectTitle, numberFrames, fileFormat, colorSpace, camera, scope, site, optics, photographer, resolution, comments, filePath, metadataFile)); } con.Close(); return(collections); }
private HttpRequestMessage GenerateHttpRequestMessage(Request request, Site site) { HttpRequestMessage httpRequestMessage = new HttpRequestMessage(request.Method, request.Url); var userAgentHeader = "User-Agent"; httpRequestMessage.Headers.Add(userAgentHeader, site.Headers.ContainsKey(userAgentHeader) ? site.Headers[userAgentHeader] : site.UserAgent); if (!string.IsNullOrEmpty(request.Referer)) { httpRequestMessage.Headers.Add("Referer", request.Referer); } if (!string.IsNullOrEmpty(request.Origin)) { httpRequestMessage.Headers.Add("Origin", request.Origin); } if (!string.IsNullOrEmpty(site.Accept)) { httpRequestMessage.Headers.Add("Accept", site.Accept); } var contentTypeHeader = "Content-Type"; foreach (var header in site.Headers) { if (header.Key.ToLower() == "cookie") { continue; } if (!string.IsNullOrEmpty(header.Key) && !string.IsNullOrEmpty(header.Value) && header.Key != contentTypeHeader && header.Key != userAgentHeader) { httpRequestMessage.Headers.Add(header.Key, header.Value); } } if (httpRequestMessage.Method == HttpMethod.Post) { var data = string.IsNullOrEmpty(site.EncodingName) ? Encoding.UTF8.GetBytes(request.PostBody) : site.Encoding.GetBytes(request.PostBody); httpRequestMessage.Content = new StreamContent(new MemoryStream(data)); if (site.Headers.ContainsKey(contentTypeHeader)) { httpRequestMessage.Content.Headers.Add(contentTypeHeader, site.Headers[contentTypeHeader]); } var xRequestedWithHeader = "X-Requested-With"; if (site.Headers.ContainsKey(xRequestedWithHeader) && site.Headers[xRequestedWithHeader] == "NULL") { httpRequestMessage.Content.Headers.Remove(xRequestedWithHeader); } else { if (!httpRequestMessage.Content.Headers.Contains(xRequestedWithHeader) && !httpRequestMessage.Headers.Contains(xRequestedWithHeader)) { httpRequestMessage.Content.Headers.Add(xRequestedWithHeader, "XMLHttpRequest"); } } } return(httpRequestMessage); }
public ChangeHfState(List <Property> properties, World world) : base(properties, world) { foreach (Property property in properties) { switch (property.Name) { case "state": switch (property.Value) { case "settled": State = HfState.Settled; break; case "wandering": State = HfState.Wandering; break; case "scouting": State = HfState.Scouting; break; case "snatcher": State = HfState.Snatcher; break; case "refugee": State = HfState.Refugee; break; case "thief": State = HfState.Thief; break; case "hunting": State = HfState.Hunting; break; case "visiting": State = HfState.Visiting; break; default: State = HfState.Unknown; property.Known = false; break; } break; case "substate": SubState = Convert.ToInt32(property.Value); break; case "coords": Coordinates = Formatting.ConvertToLocation(property.Value); break; case "hfid": HistoricalFigure = world.GetHistoricalFigure(Convert.ToInt32(property.Value)); break; case "site_id": Site = world.GetSite(Convert.ToInt32(property.Value)); break; case "subregion_id": Region = world.GetRegion(Convert.ToInt32(property.Value)); break; case "feature_layer_id": UndergroundRegion = world.GetUndergroundRegion(Convert.ToInt32(property.Value)); break; case "site": Site = world.GetSite(Convert.ToInt32(property.Value)); break; case "mood": switch (property.Value) { case "macabre": Mood = Mood.Macabre; break; case "secretive": Mood = Mood.Secretive; break; case "insane": Mood = Mood.Insane; break; case "possessed": Mood = Mood.Possessed; break; case "berserk": Mood = Mood.Berserk; break; case "fey": Mood = Mood.Fey; break; case "melancholy": Mood = Mood.Melancholy; break; case "fell": Mood = Mood.Fell; break; case "catatonic": Mood = Mood.Catatonic; break; default: Mood = Mood.Unknown; property.Known = false; break; } break; case "reason": switch (property.Value) { case "failed mood": Reason = ChangeHfStateReason.FailedMood; break; case "gather information": Reason = ChangeHfStateReason.GatherInformation; break; case "be with master": Reason = ChangeHfStateReason.BeWithMaster; break; case "flight": Reason = ChangeHfStateReason.Flight; break; case "scholarship": Reason = ChangeHfStateReason.Scholarship; break; case "on a pilgrimage": Reason = ChangeHfStateReason.Pilgrimage; break; case "lack of sleep": Reason = ChangeHfStateReason.LackOfSleep; break; case "great deal of stress": Reason = ChangeHfStateReason.GreatDealOfStress; break; case "exiled after conviction": Reason = ChangeHfStateReason.ExiledAfterConviction; break; default: if (property.Value != "-1") { property.Known = false; } break; } break; } } if (HistoricalFigure != null) { HistoricalFigure.AddEvent(this); HistoricalFigure.States.Add(new HistoricalFigure.State(State, Year)); HistoricalFigure.State lastState = HistoricalFigure.States.LastOrDefault(); if (lastState != null) { lastState.EndYear = Year; } HistoricalFigure.CurrentState = State; } Site.AddEvent(this); Region.AddEvent(this); UndergroundRegion.AddEvent(this); }
private void Execute([NotNull] Site site) { Debug.ArgumentNotNull(site, nameof(site)); AppHost.Windows.Factory.OpenLogViewer(site); }
public void TestCase_S15_TC01_CreateFile() { string randomFileUrl = SharedTestSuiteHelper.GenerateNonExistFileUrl(this.Site); // Initialize the context using user01 and defaultFileUrl. this.InitializeContext(randomFileUrl, this.UserName01, this.Password01, this.Domain); CellSubRequestType putChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedPutChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), SharedTestSuiteHelper.GenerateRandomFileContent(this.Site)); putChange.SubRequestData.CoalesceSpecified = true; putChange.SubRequestData.Coalesce = true; CellStorageResponse response = Adapter.CellStorageRequest(randomFileUrl, new SubRequestType[] { putChange }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse <CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual <ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "When uploading contents if the protocol server was unable to find the URL for the file specified in the Url attribute,, the server returns success and create a new file using the specified contents in the file URI."); // Query the updated file content. CellSubRequestType queryChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedQueryChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID()); response = Adapter.CellStorageRequest(randomFileUrl, new SubRequestType[] { queryChange }); cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse <CellSubResponseType>(response, 0, 0, this.Site); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R3103 // If queryChange subrequest can download a file from randomFileUrl, then capture MS-FSSHTTP_R3103. Site.CaptureRequirementIfAreEqual <ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "MS-FSSHTTP", 3103, @"[In Cell Subrequest] But for Put Changes subrequest, as described in [MS-FSSHTTPB] section 2.2.2.1.4, [If the protocol server was unable to find the URL for the file specified in the Url attribute] the protocol server creates a new file using the specified Url."); } else { Site.Assert.AreEqual <ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), @"[In Cell Subrequest] But for Put Changes subrequest, as described in [MS-FSSHTTPB] section 2.2.2.1.4, [If the protocol server was unable to find the URL for the file specified in the Url attribute] the protocol server creates a new file using the specified Url."); } this.StatusManager.RecordFileUpload(randomFileUrl); // Re-generate the non-exist file URL again. randomFileUrl = SharedTestSuiteHelper.GenerateNonExistFileUrl(this.Site); this.InitializeContext(randomFileUrl, this.UserName01, this.Password01, this.Domain); putChange.SubRequestData.ExpectNoFileExistsSpecified = true; putChange.SubRequestData.ExpectNoFileExists = true; putChange.SubRequestData.Etag = string.Empty; putChange.SubRequestData.CoalesceSpecified = true; putChange.SubRequestData.Coalesce = true; response = Adapter.CellStorageRequest(randomFileUrl, new SubRequestType[] { putChange }); cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse <CellSubResponseType>(response, 0, 0, this.Site); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R2252 Site.CaptureRequirementIfAreEqual <ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "MS-FSSHTTP", 2252, @"[In Cell Subrequest] In this case[If the ExpectNoFileExists attribute is set to true in a file content upload cell subrequest, the Etag attribute MUST be an empty string], the protocol server MUST NOT cause the cell subrequest to fail with a coherency error if the file does not exist on the server."); } else { Site.Assert.AreEqual <ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), @"[In Cell Subrequest] In this case[If the ExpectNoFileExists attribute is set to true in a file content upload cell subrequest, the Etag attribute MUST be an empty string], the protocol server MUST NOT cause the cell subrequest to fail with a coherency error if the file does not exist on the server."); } this.StatusManager.RecordFileUpload(randomFileUrl); }
protected override void Init() { services = new ServiceCollection() .AddSingleton <IMyService, MyService>() .BuildServiceProvider(); using (var api = CreateApi()) { Piranha.App.Init(api); Piranha.App.Fields.Register <MyFourthField>(); var builder = new PageTypeBuilder(api) .AddType(typeof(MissingPage)) .AddType(typeof(MyBlogPage)) .AddType(typeof(MyPage)) .AddType(typeof(MyCollectionPage)) .AddType(typeof(MyDIPage)); builder.Build(); var site = new Site { Id = SITE_ID, Title = "Default Site", InternalId = "DefaultSite", IsDefault = true }; api.Sites.Save(site); var page1 = MyPage.Create(api); page1.Id = PAGE_1_ID; page1.SiteId = SITE_ID; page1.Title = "My first page"; page1.Ingress = "My first ingress"; page1.Body = "My first body"; page1.Blocks.Add(new Extend.Blocks.TextBlock { Body = "Sollicitudin Aenean" }); page1.Blocks.Add(new Extend.Blocks.TextBlock { Body = "Ipsum Elit" }); api.Pages.Save(page1); var page2 = MyPage.Create(api); page2.Id = PAGE_2_ID; page2.SiteId = SITE_ID; page2.Title = "My second page"; page2.Ingress = "My second ingress"; page2.Body = "My second body"; api.Pages.Save(page2); var page3 = MyPage.Create(api); page3.Id = PAGE_3_ID; page3.SiteId = SITE_ID; page3.Title = "My third page"; page3.Ingress = "My third ingress"; page3.Body = "My third body"; api.Pages.Save(page3); var page4 = MyCollectionPage.Create(api); page4.SiteId = SITE_ID; page4.Title = "My collection page"; page4.SortOrder = 1; page4.Texts.Add(new TextField { Value = "First text" }); page4.Texts.Add(new TextField { Value = "Second text" }); page4.Texts.Add(new TextField { Value = "Third text" }); api.Pages.Save(page4); var page5 = MyBlogPage.Create(api); page5.SiteId = SITE_ID; page5.Title = "Blog Archive"; api.Pages.Save(page5); var page6 = MyDIPage.Create(api); page6.Id = PAGE_DI_ID; page6.SiteId = SITE_ID; page6.Title = "My Injection Page"; api.Pages.Save(page6); var page7 = MyPage.Create(api); page7.Id = PAGE_7_ID; page7.SiteId = SITE_ID; page7.Title = "My base page"; page7.Ingress = "My base ingress"; page7.Body = "My base body"; page7.ParentId = PAGE_1_ID; page7.SortOrder = 1; api.Pages.Save(page7); var page8 = MyPage.Create(api); page8.OriginalPageId = PAGE_7_ID; page8.Id = PAGE_8_ID; page8.SiteId = SITE_ID; page8.Title = "My copied page"; page8.ParentId = PAGE_1_ID; page8.SortOrder = 2; page8.IsHidden = true; page8.Route = "test-route"; api.Pages.Save(page8); } }
public ExportObject(IPathManager pathManager, IDatabaseManager databaseManager, CacheUtils caching, Site site) { _pathManager = pathManager; _databaseManager = databaseManager; _caching = caching; _site = site; }
public override string Print(bool link = true, DwarfObject pov = null) { string eventString = GetYearTime() + HistoricalFigure.ToLink(link, pov, this); if (State == HfState.Visiting) { eventString += " visited "; } else if (State == HfState.Settled) { switch (SubState) { case 45: eventString += " fled to "; break; case 46: case 47: eventString += " moved to study in "; break; default: eventString += " settled in "; break; } } else if (State == HfState.Wandering) { eventString += " began wandering "; } else if (State == HfState.Refugee || State == HfState.Snatcher || State == HfState.Thief) { eventString += " became a " + State.ToString().ToLower() + " in "; } else if (State == HfState.Scouting) { eventString += " began scouting the area around "; } else if (State == HfState.Hunting) { eventString += " began hunting great beasts in "; } else if (Mood != Mood.Unknown) { switch (Mood) { case Mood.Macabre: eventString += " began to skulk and brood in "; break; case Mood.Secretive: eventString += " withdrew from society in "; break; case Mood.Insane: eventString += " became crazed in "; break; case Mood.Possessed: eventString += " was possessed in "; break; case Mood.Berserk: eventString += " went berserk in "; break; case Mood.Fey: eventString += " was taken by a fey mood in "; break; case Mood.Melancholy: eventString += " was striken by melancholy in "; break; case Mood.Fell: eventString += " was taken by a fell mood in "; break; case Mood.Catatonic: eventString += " stopped responding to the outside world in "; break; } } else { eventString += " changed state in "; } if (Site != null) { eventString += Site.ToLink(link, pov, this); } else if (Region != null) { eventString += Region.ToLink(link, pov, this); } else if (UndergroundRegion != null) { eventString += UndergroundRegion.ToLink(link, pov, this); } else { eventString += "the wilds"; } if (Reason != ChangeHfStateReason.Unknown) { switch (Reason) { case ChangeHfStateReason.FailedMood: eventString += " after failing to create an artifact"; break; case ChangeHfStateReason.GatherInformation: eventString += " to gather information"; break; case ChangeHfStateReason.BeWithMaster: eventString += " in order to be with the master"; break; case ChangeHfStateReason.Flight: eventString += " in order to flee"; break; case ChangeHfStateReason.Scholarship: eventString += " in order to pursue scholarship"; break; case ChangeHfStateReason.Pilgrimage: eventString += " on a pilgrimage"; break; case ChangeHfStateReason.LackOfSleep: eventString += " due to lack of sleep"; break; case ChangeHfStateReason.GreatDealOfStress: eventString += " after a great deal of stress"; break; case ChangeHfStateReason.ExiledAfterConviction: eventString += " after being exiled following a criminal conviction"; break; } } eventString += PrintParentCollection(link, pov); eventString += "."; return(eventString); }
private Page HandleResponse(Request request, HttpResponseMessage response, int statusCode, Site site) { string content = GetContent(site, response); if (DecodeContentAsUrl) { #if !NET_CORE content = HttpUtility.UrlDecode(HttpUtility.HtmlDecode(content), string.IsNullOrEmpty(site.EncodingName) ? Encoding.Default : site.Encoding); #else content = WebUtility.UrlDecode(WebUtility.HtmlDecode(content)); #endif } Page page = new Page(request, site.ContentType); page.Content = content; page.Url = request.Url.ToString(); page.StatusCode = statusCode; foreach (var header in response.Headers) { page.Request.PutExtra(header.Key, header.Value); } return page; }
public void TestCase_S15_TC04_UploadContents_ExclusiveLockSuccess() { string randomFileUrl = SharedTestSuiteHelper.GenerateNonExistFileUrl(this.Site); // Initialize the context using user01 and defaultFileUrl. this.InitializeContext(randomFileUrl, this.UserName01, this.Password01, this.Domain); CellSubRequestType putChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedPutChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), SharedTestSuiteHelper.GenerateRandomFileContent(this.Site)); putChange.SubRequestData.CoalesceSpecified = true; putChange.SubRequestData.Coalesce = true; putChange.SubRequestData.ExpectNoFileExistsSpecified = true; putChange.SubRequestData.ExpectNoFileExists = true; putChange.SubRequestData.ExclusiveLockID = SharedTestSuiteHelper.DefaultExclusiveLockID; putChange.SubRequestData.BypassLockID = putChange.SubRequestData.ExclusiveLockID; putChange.SubRequestData.Timeout = "3600"; CellStorageResponse response = Adapter.CellStorageRequest(randomFileUrl, new SubRequestType[] { putChange }); CellSubResponseType cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse <CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual <ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "When the file is locked by exclusive lock and the ByPassLockID is specified by the valid exclusive lock id, the server returns the error code success."); this.StatusManager.RecordExclusiveLock(randomFileUrl, SharedTestSuiteHelper.DefaultExclusiveLockID, this.UserName01, this.Password01, this.Domain); this.StatusManager.RecordFileUpload(randomFileUrl); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // If the server responds with the error code "Success", // when the above steps show that the client has got an exclusive lock and the PutChange subrequest was sent with BypassLockID equal to ExclusiveLockID, // then requirement MS-FSSHTTP_R833 is captured. Site.CaptureRequirementIfAreEqual <ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "MS-FSSHTTP", 833, @"[In CellSubRequestDataOptionalAttributes][BypassLockID] If a client has got an exclusive lock, this value[BypassLockID] MUST be the same as the value of ExclusiveLockID, as specified in section 2.3.1.1."); // If the server responds with "ExclusiveLock" in LockType attribute, the requirement MS-FSSHTTP_R1533 is captured. Site.CaptureRequirementIfAreEqual <string>( "ExclusiveLock", cellSubResponse.SubResponseData.LockType.ToString(), "MS-FSSHTTP", 1533, @"[In CellSubResponseDataType] The LockType attribute MUST be set to ""ExclusiveLock"" in the cell subresponse if the ExclusiveLockID attribute is sent in the cell subrequest and the protocol server is successfully able to take an exclusive lock."); } else { Site.Assert.AreEqual <ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), @"[In CellSubRequestDataOptionalAttributes][BypassLockID] If a client has got an exclusive lock, this value[BypassLockID] MUST be the same as the value of ExclusiveLockID, as specified in section 2.3.1.1."); Site.Assert.AreEqual <string>( "ExclusiveLock", cellSubResponse.SubResponseData.LockType.ToString(), @"[In CellSubResponseDataType] The LockType attribute MUST be set to ""ExclusiveLock"" in the cell subresponse if the ExclusiveLockID attribute is sent in the cell subrequest and the protocol server is successfully able to take an exclusive lock."); } // Update contents without the ByPassLockID and coalesce true. putChange = SharedTestSuiteHelper.CreateCellSubRequestEmbeddedPutChanges(SequenceNumberGenerator.GetCurrentFSSHTTPBSubRequestID(), SharedTestSuiteHelper.GenerateRandomFileContent(this.Site)); putChange.SubRequestData.BypassLockID = null; putChange.SubRequestData.CoalesceSpecified = true; putChange.SubRequestData.Coalesce = true; response = Adapter.CellStorageRequest(randomFileUrl, new SubRequestType[] { putChange }); cellSubResponse = SharedTestSuiteHelper.ExtractSubResponse <CellSubResponseType>(response, 0, 0, this.Site); this.Site.Assert.AreEqual <ErrorCodeType>( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(cellSubResponse.ErrorCode, this.Site), "When the file is locked by exclusive lock and the ByPassLockID is not specified, the server returns the error code success."); }
protected override Page DowloadContent(Request request, ISpider spider) { Site site = spider.Site; try { lock (_locker) { _webDriver = _webDriver ?? WebDriverExtensions.Open(_browser, _option); if (!_isLogined && Login != null) { _isLogined = Login.Handle(_webDriver as RemoteWebDriver); if (!_isLogined) { throw new DownloadException("Login failed. Please check your login codes."); } } } Uri uri = request.Url; //#if NET_CORE // string query = string.IsNullOrEmpty(uri.Query) ? "" : $"?{WebUtility.UrlEncode(uri.Query.Substring(1, uri.Query.Length - 1))}"; //#else // string query = string.IsNullOrEmpty(uri.Query) ? "" : $"?{HttpUtility.UrlPathEncode(uri.Query.Substring(1, uri.Query.Length - 1))}"; //#endif // string realUrl = $"{uri.Scheme}://{uri.DnsSafeHost}{(uri.Port == 80 ? "" : ":" + uri.Port)}{uri.AbsolutePath}{query}"; var domainUrl = $"{uri.Scheme}://{uri.DnsSafeHost}{(uri.Port == 80 ? "" : ":" + uri.Port)}"; var options = _webDriver.Manage(); if (options.Cookies.AllCookies.Count == 0 && spider.Site.Cookies?.PairPart.Count > 0) { _webDriver.Url = domainUrl; options.Cookies.DeleteAllCookies(); if (spider.Site.Cookies != null) { foreach (var c in spider.Site.Cookies.PairPart) { options.Cookies.AddCookie(new Cookie(c.Key, c.Value)); } } } string realUrl = request.Url.ToString(); NetworkCenter.Current.Execute("webdriver-download", () => { _webDriver.Navigate().GoToUrl(realUrl); NavigateCompeleted?.Invoke((RemoteWebDriver)_webDriver); }); Thread.Sleep(_webDriverWaitTime); Page page = new Page(request, site.RemoveOutboundLinks ? site.Domains : null) { Content = _webDriver.PageSource, TargetUrl = _webDriver.Url, Title = _webDriver.Title }; // 结束后要置空, 这个值存到Redis会导置无限循环跑单个任务 //request.PutExtra(Request.CycleTriedTimes, null); return(page); } catch (DownloadException de) { Page page = new Page(request, null) { Exception = de }; if (site.CycleRetryTimes > 0) { page = Spider.AddToCycleRetry(request, site); } Logger.AllLog(spider.Identity, $"下载 {request.Url} 失败: {de.Message}.", NLog.LogLevel.Warn); return(page); } catch (Exception e) { Logger.AllLog(spider.Identity, $"下载 {request.Url} 失败: {e.Message}.", NLog.LogLevel.Warn); Page page = new Page(request, null) { Exception = e }; return(page); } }
public override Page Download(Request request, ISpider spider) { if (spider.Site == null) { return null; } Site site = spider.Site; var acceptStatCodes = site.AcceptStatCode; //Logger.InfoFormat("Downloading page {0}", request.Url); HttpResponseMessage response = null; var proxy = site.GetHttpProxyFromPool(); request.PutExtra(Request.Proxy, proxy); int statusCode = 200; try { if (GeneratePostBody != null) { SingleExecutor.Execute(() => { GeneratePostBody(spider.Site, request); }); } var httpMessage = GenerateHttpRequestMessage(request, site); response = RedialManagerUtils.Execute("downloader-download", (m) => { var message = (HttpRequestMessage)m; return httpClient.SendAsync(message).Result; }, httpMessage); AddRequestCount(); response.EnsureSuccessStatusCode(); if (!site.AcceptStatCode.Contains(response.StatusCode)) { throw new DownloadException($"下载 {request.Url} 失败. Code: {response.StatusCode}"); } statusCode = (int)response.StatusCode; request.PutExtra(Request.StatusCode, statusCode); Page page = HandleResponse(request, response, statusCode, site); // need update page.TargetUrl = request.Url.ToString(); //page.SetRawText(File.ReadAllText(@"C:\Users\Lewis\Desktop\taobao.html")); // 这里只要是遇上登录的, 则在拨号成功之后, 全部抛异常在Spider中加入Scheduler调度 // 因此如果使用多线程遇上多个Warning Custom Validate Failed不需要紧张, 可以考虑用自定义Exception分开 ValidatePage(page, spider); // 结束后要置空, 这个值存到Redis会导致无限循环跑单个任务 request.PutExtra(Request.CycleTriedTimes, null); //#if !NET_CORE // httpWebRequest.ServicePoint.ConnectionLimit = int.MaxValue; //#endif return page; //正常结果在上面已经Return了, 到此处必然是下载失败的值. //throw new SpiderExceptoin("Download failed."); } catch (RedialException) { throw; } catch (Exception e) { Page page = new Page(request, site.ContentType) { Exception = e }; ValidatePage(page, spider); throw; } finally { // 先Close Response, 避免前面语句异常导致没有关闭. try { //ensure the connection is released back to pool //check: //EntityUtils.consume(httpResponse.getEntity()); response?.Dispose(); } catch (Exception e) { var logger = LogUtils.GetLogger(spider); logger.Warn("Close response fail.", e); } } }
public override async Task <Dictionary <Guid, Uri?> > GetCommentsUrlAsync(IContentItem[] entities, Site site) { var types = entities.Select(e => e.GetKey()).Distinct().ToArray(); var ids = entities.Select(e => e.Id).ToArray(); var contentSettings = await DbContext.Set <IPBPublishRecord>() .Where(s => types.Contains(s.Type) && ids.Contains(s.ContentId) && s.SiteIds.Contains(site.Id)) .ToListAsync(); var result = new Dictionary <Guid, Uri?>(); foreach (var entity in entities) { Uri?uri = null; var settings = contentSettings.FirstOrDefault(c => c.Type == entity.GetKey() && c.ContentId == entity.Id); if (settings?.TopicId > 0) { uri = new Uri( $"{_options.Url}topic/{settings.TopicId.ToString()}/?do=getNewComment", UriKind.Absolute); } result.Add(entity.Id, uri); } return(result); }
//private HttpWebRequest GeneratorCookie(HttpWebRequest httpWebRequest, Site site) //{ // StringBuilder builder = new StringBuilder(); // foreach (var cookie in site.AllCookies) // { // builder.Append($"{cookie.Key}={cookie.Value};"); // } // httpWebRequest.Headers.Add("Cookie", builder.ToString()); // return httpWebRequest; //} private HttpRequestMessage GenerateHttpRequestMessage(Request request, Site site) { if (site == null) return null; HttpRequestMessage httpWebRequest = CreateRequestMessage(request); if (!site.Headers.ContainsKey("Content-Type") && (site.Headers.ContainsKey("Content-Type") && site.Headers["Content-Type"] != "NULL")) { httpWebRequest.Headers.Add("ContentType", "application /x-www-form-urlencoded; charset=UTF-8"); } else { //httpWebRequest.Content.Headers.Add("Content-Type", site.Headers["Content-Type"]); } if (site.Headers.ContainsKey("UserAgent")) { httpWebRequest.Headers.Add("UserAgent", site.Headers["UserAgent"]); } else { httpWebRequest.Headers.Add("User-Agent", site.UserAgent ?? "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"); } if (!string.IsNullOrEmpty(request.Referer)) { httpWebRequest.Headers.Add("Referer", request.Referer); } httpWebRequest.Headers.Add("Accept", site.Accept ?? "application/json, text/javascript, */*; q=0.01"); if (!site.Headers.ContainsKey("Accept-Language")) { httpWebRequest.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3"); } if (site.IsUseGzip) { httpWebRequest.Headers.Add("Accept-Encoding", "gzip"); } //httpWebRequest.Timeout = site.Timeout; //httpWebRequest.ReadWriteTimeout = site.Timeout; //httpWebRequest.AllowAutoRedirect = true; // headers if (site.Headers != null) { foreach (var header in site.Headers) { if (!string.IsNullOrEmpty(header.Key) && !string.IsNullOrEmpty(header.Value) && header.Key != "Content-Type" && header.Key != "User-Agent") { httpWebRequest.Headers.Add(header.Key, header.Value); } } } httpWebRequest.Headers.Add("Cookie", site.Cookie); if (httpWebRequest.Method == HttpMethod.Post) { var data = string.IsNullOrEmpty(site.EncodingName) ? Encoding.UTF8.GetBytes(request.PostBody) : site.Encoding.GetBytes(request.PostBody); httpWebRequest.Content = new StreamContent(new MemoryStream(data)); if (site.Headers.ContainsKey("Content-Type")) { httpWebRequest.Content.Headers.Add("Content-Type", site.Headers["Content-Type"]); } } #if !NET_CORE //if (site.HttpProxyPoolEnable) //{ // HttpHost host = site.GetHttpProxyFromPool(); // httpWebRequest.Proxy = new WebProxy(host.Host, host.Port); // request.PutExtra(Request.Proxy, host); //} //else //{ // // 避开Fiddler之类的代理 // httpWebRequest.Proxy = null; //} #else //httpWebRequest.Proxy = null; #endif return httpWebRequest; }
private void AddNewDownedRefugee() { if (pawnList.Count == 0) { Messages.Message($"Select minimum 1 pawn", MessageTypeDefOf.NeutralEvent, false); return; } if (edit) { editSite.parts.Clear(); foreach (var p in parts) { editSite.parts.Add(new SitePart(editSite, p, p.Worker.GenerateDefaultParams(threatsFloat, editSite.Tile, editSite.Faction))); } var pawns = editSite.GetComponent <DownedRefugeeComp>(); pawns.pawn.Clear(); foreach (var p in pawnList) { pawns.pawn.TryAdd(p); } if (!string.IsNullOrEmpty(time) && int.TryParse(time, out int t)) { editSite.GetComponent <TimeoutComp>().StartTimeout(t * 60000); } else { editSite.GetComponent <TimeoutComp>().StartTimeout(-1); } if (selectedFaction != null) { editSite.SetFaction(selectedFaction); } Messages.Message($"Success", MessageTypeDefOf.NeutralEvent, false); return; } if (Find.WorldSelector.selectedTile == -1) { Messages.Message($"Select tile", MessageTypeDefOf.NeutralEvent, false); return; } if (selectedFaction == null) { selectedFaction = Find.FactionManager.AllFactionsListForReading.RandomElement(); } Site site = SiteMaker.MakeSite(parts, Find.WorldSelector.selectedTile, selectedFaction, threatPoints: threatsFloat); site.sitePartsKnown = true; var comp = site.GetComponent <DownedRefugeeComp>(); foreach (var p in pawnList) { comp.pawn.TryAdd(p); } if (!string.IsNullOrEmpty(time) && int.TryParse(time, out int timeInt)) { site.GetComponent <TimeoutComp>().StartTimeout(timeInt * 60000); } Find.WorldObjects.Add(site); }
/// <summary> /// 解析出目标链接 /// </summary> /// <param name="page">页面数据</param> /// <param name="site">站点信息</param> /// <returns>目标链接</returns> protected override IEnumerable <Request> Extract(Page page, Site site) { if (_regionSelectorMapPatterns == null || _regionSelectorMapPatterns.Count == 0) { return(new Request[0]); } List <string> resultUrls = new List <string>(); foreach (var targetUrlExtractor in _regionSelectorMapPatterns) { if (Equals(targetUrlExtractor.Key, Selectors.Default())) { continue; } IEnumerable <string> links = null; if (page.ContentType == ContentType.Html) { links = page.Selectable.SelectList(targetUrlExtractor.Key).Links().GetValues(); } else if (page.ContentType == ContentType.Json) { links = page.Selectable.SelectList(Selectors.Regex(RegexUtil.Url)).Links().GetValues(); } else { } if (links == null) { continue; } // check: 仔细考虑是放在前面, 还是在后面做 formatter, 我倾向于在前面. 对targetUrl做formatter则表示Start Url也应该是要符合这个规则的。 List <string> tmp = new List <string>(); foreach (string link in links) { var newUrl = FormateUrl(link); #if !NETSTANDARD tmp.Add(System.Web.HttpUtility.HtmlDecode(System.Web.HttpUtility.UrlDecode(newUrl))); #else tmp.Add(WebUtility.HtmlDecode(WebUtility.UrlDecode(newUrl))); #endif } links = tmp; if (targetUrlExtractor.Value == null || targetUrlExtractor.Value.Count == 0) { resultUrls.AddRange(links); continue; } foreach (var regex in targetUrlExtractor.Value) { foreach (string link in links) { if (regex.IsMatch(link)) { bool isRequired = true; if (ExcludeTargetUrlPatterns != null) { foreach (var excludeRegex in ExcludeTargetUrlPatterns) { if (excludeRegex.IsMatch(link)) { isRequired = false; break; } } } if (isRequired) { resultUrls.Add(link); } } } } } if (site.DownloadFiles) { var links = (page.Selectable.SelectList(ImageSelector)).GetValues(); if (links != null && links.Count() > 0) { foreach (string link in links) { bool isRequired = true; if (ExcludeTargetUrlPatterns != null) { foreach (var excludeRegex in ExcludeTargetUrlPatterns) { if (excludeRegex.IsMatch(link)) { isRequired = false; break; } } } if (isRequired) { resultUrls.Add(link); } } } } return(resultUrls.Select(t => new Request(t, page.Request.Extras) { Site = site })); }
internal static bool IsSectionLocal(Site site, string path) { return(ManagementUnit.IsSectionLocal(site?.Id, path, AuthorizationSection.SECTION_PATH)); }
internal SPPageContextInfo(Site site, Web web, bool isWebPart) { if (site != null) { if (site.IsPropertyAvailable("SiteServerRelativeUrl")) { this.SiteServerRelativeUrl = site.ServerRelativeUrl; } if (site.IsPropertyAvailable("Url")) { this.SiteAbsoluteUrl = site.Url; } if (site.IsPropertyAvailable("CompatibilityLevel")) { this.LayoutsUrl = Helpers.SPContextHelper.GetLayoutsFolder(site.CompatibilityLevel); } } if (web != null) { if (web.IsPropertyAvailable("ServerRelativeUrl")) { this.WebServerRelativeUrl = web.ServerRelativeUrl; } if (web.IsPropertyAvailable("Url")) { this.WebAbsoluteUrl = web.Url; } if (web.IsPropertyAvailable("Language")) { this.WebLanguage = web.Language; } if (web.IsPropertyAvailable("SiteLogoUrl")) { this.WebLogoUrl = web.SiteLogoUrl; } if (web.IsPropertyAvailable("EffectiveBasePermissions")) { //var permissions = new List<int>(); //foreach (var pk in (PermissionKind[])Enum.GetValues(typeof(PermissionKind))) //{ // if (web.EffectiveBasePermissions.Has(pk) && pk != PermissionKind.EmptyMask) // { // permissions.Add((int)pk); // } //} this.WebPermMasks = new SPPermissionInfo(web.EffectiveBasePermissions); } if (web.IsPropertyAvailable("Title")) { this.WebTitle = web.Title; } if (web.IsPropertyAvailable("UIVersion")) { this.WebUIVersion = web.UIVersion; } User user = web.CurrentUser; if (user.IsPropertyAvailable("Id")) { this.UserId = user.Id; } if (user.IsPropertyAvailable("LoginName")) { this.UserLoginName = user.LoginName; } this.RegionalInfo = new SPRegionalInfo(web.RegionalSettings); } IsWebPart = isWebPart; }
//--------------------------------------------------------------------- ///<summary> /// Calculate the The Resource Dominance of all active NEIGHBORS /// within the User defined NeighborRadius. /// /// The weight of neighbors is dependent upon distance and a /// weighting algorithm: uniform, linear, or gaussian. /// /// Subsampling determined by User defined NeighborSpeedUp. /// Gaussian equation: http://www.anc.ed.ac.uk/~mjo/intro/node7.html ///</summary> //--------------------------------------------------------------------- public static void NeighborResourceDominance(IAgent agent) { PlugIn.ModelCore.UI.WriteLine(" Calculating BDA Neighborhood Resource Dominance."); double totalNeighborWeight = 0.0; double maxNeighborWeight = 0.0; int neighborCnt = 0; int speedUpFraction = (int)agent.NeighborSpeedUp + 1; foreach (ActiveSite site in PlugIn.ModelCore.Landscape) { if (agent.OutbreakZone[site] == Zone.Newzone) { //neighborWeight = 0.0; totalNeighborWeight = 0.0; maxNeighborWeight = 0.0; neighborCnt = 0; if (SiteVars.SiteResourceDom[site] > 0) { List <RelativeLocationWeighted> neighborhood = new List <RelativeLocationWeighted>(); foreach (RelativeLocationWeighted relativeLoc in agent.ResourceNeighbors) { Site neighbor = site.GetNeighbor(relativeLoc.Location); if (neighbor != null && neighbor.IsActive) { neighborhood.Add(relativeLoc); } } neighborhood = PlugIn.ModelCore.shuffle(neighborhood); foreach (RelativeLocationWeighted neighbor in neighborhood) { //Do NOT subsample if there are too few neighbors //i.e., <= subsample size. if (neighborhood.Count <= speedUpFraction || neighborCnt % speedUpFraction == 0) { Site activeSite = site.GetNeighbor(neighbor.Location); //Note: SiteResourceDomMod ranges from 0 - 1. if (SiteVars.SiteResourceDomMod[activeSite] > 0) { totalNeighborWeight += SiteVars.SiteResourceDomMod[activeSite] * neighbor.Weight; maxNeighborWeight += neighbor.Weight; } } neighborCnt++; } if (maxNeighborWeight > 0.0) { SiteVars.NeighborResourceDom[site] = totalNeighborWeight / maxNeighborWeight; } else { SiteVars.NeighborResourceDom[site] = 0.0; } } else { SiteVars.NeighborResourceDom[site] = 0.0; } } } }
private void CreateSiteCollection(SiteCollectionProvisioningJob job) { Console.WriteLine("Creating Site Collection \"{0}\".", job.RelativeUrl); // Define the full Site Collection URL String siteUrl = String.Format("{0}{1}", PnPPartnerPackSettings.InfrastructureSiteUrl.Substring(0, PnPPartnerPackSettings.InfrastructureSiteUrl.IndexOf("sharepoint.com/") + 14), job.RelativeUrl); // Load the template from the source Templates Provider if (!String.IsNullOrEmpty(job.TemplatesProviderTypeName)) { ProvisioningTemplate template = null; var templatesProvider = PnPPartnerPackSettings.TemplatesProviders[job.TemplatesProviderTypeName]; if (templatesProvider != null) { template = templatesProvider.GetProvisioningTemplate(job.ProvisioningTemplateUrl); } if (template != null) { using (var adminContext = PnPPartnerPackContextProvider.GetAppOnlyTenantLevelClientContext()) { adminContext.RequestTimeout = Timeout.Infinite; // Configure the Site Collection properties SiteEntity newSite = new SiteEntity(); newSite.Description = job.Description; newSite.Lcid = (uint)job.Language; newSite.Title = job.SiteTitle; newSite.Url = siteUrl; newSite.SiteOwnerLogin = job.PrimarySiteCollectionAdmin; newSite.StorageMaximumLevel = job.StorageMaximumLevel; newSite.StorageWarningLevel = job.StorageWarningLevel; // Use the BaseSiteTemplate of the template, if any, otherwise // fallback to the pre-configured site template (i.e. STS#0) newSite.Template = !String.IsNullOrEmpty(template.BaseSiteTemplate) ? template.BaseSiteTemplate : PnPPartnerPackSettings.DefaultSiteTemplate; newSite.TimeZoneId = job.TimeZone; newSite.UserCodeMaximumLevel = job.UserCodeMaximumLevel; newSite.UserCodeWarningLevel = job.UserCodeWarningLevel; // Create the Site Collection and wait for its creation (we're asynchronous) var tenant = new Tenant(adminContext); tenant.CreateSiteCollection(newSite, true, true); // TODO: Do we want to empty Recycle Bin? Site site = tenant.GetSiteByUrl(siteUrl); Web web = site.RootWeb; adminContext.Load(site, s => s.Url); adminContext.Load(web, w => w.Url); adminContext.ExecuteQueryRetry(); // Enable Secondary Site Collection Administrator if (!String.IsNullOrEmpty(job.SecondarySiteCollectionAdmin)) { Microsoft.SharePoint.Client.User secondaryOwner = web.EnsureUser(job.SecondarySiteCollectionAdmin); secondaryOwner.IsSiteAdmin = true; secondaryOwner.Update(); web.SiteUsers.AddUser(secondaryOwner); adminContext.ExecuteQueryRetry(); } Console.WriteLine("Site \"{0}\" created.", site.Url); // Check if external sharing has to be enabled if (job.ExternalSharingEnabled) { EnableExternalSharing(tenant, site); // Enable External Sharing Console.WriteLine("Enabled External Sharing for site \"{0}\".", site.Url); } } // Move to the context of the created Site Collection using (ClientContext clientContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext(siteUrl)) { clientContext.RequestTimeout = Timeout.Infinite; Site site = clientContext.Site; Web web = site.RootWeb; clientContext.Load(site, s => s.Url); clientContext.Load(web, w => w.Url); clientContext.ExecuteQueryRetry(); // Check if we need to enable PnP Partner Pack overrides if (job.PartnerPackExtensionsEnabled) { // Enable Responsive Design PnPPartnerPackUtilities.EnablePartnerPackOnSite(site.Url); Console.WriteLine("Enabled PnP Partner Pack Overrides on site \"{0}\".", site.Url); } // Check if the site has to be responsive if (job.ResponsiveDesignEnabled) { // Enable Responsive Design PnPPartnerPackUtilities.EnableResponsiveDesignOnSite(site.Url); Console.WriteLine("Enabled Responsive Design Template to site \"{0}\".", site.Url); } // Apply the Provisioning Template Console.WriteLine("Applying Provisioning Template \"{0}\" to site.", job.ProvisioningTemplateUrl); // We do intentionally remove taxonomies, which are not supported // in the AppOnly Authorization model // For further details, see the PnP Partner Pack documentation ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation(); // Write provisioning steps on console log ptai.MessagesDelegate += delegate(string message, ProvisioningMessageType messageType) { Console.WriteLine("{0} - {1}", messageType, messageType); }; ptai.ProgressDelegate += delegate(string message, int step, int total) { Console.WriteLine("{0:00}/{1:00} - {2}", step, total, message); }; // Exclude handlers not supported in App-Only ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.TermGroups; ptai.HandlersToProcess ^= OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.SearchSettings; // Configure template parameters if (job.TemplateParameters != null) { foreach (var key in job.TemplateParameters.Keys) { if (job.TemplateParameters.ContainsKey(key)) { template.Parameters[key] = job.TemplateParameters[key]; } } } // Fixup Title and Description if (template.WebSettings != null) { template.WebSettings.Title = job.SiteTitle; template.WebSettings.Description = job.Description; } // Apply the template to the target site web.ApplyProvisioningTemplate(template, ptai); // Save the template information in the target site var info = new SiteTemplateInfo() { TemplateProviderType = job.TemplatesProviderTypeName, TemplateUri = job.ProvisioningTemplateUrl, TemplateParameters = template.Parameters, AppliedOn = DateTime.Now, }; var jsonInfo = JsonConvert.SerializeObject(info); web.SetPropertyBagValue(PnPPartnerPackConstants.PropertyBag_TemplateInfo, jsonInfo); // Set site policy template if (!String.IsNullOrEmpty(job.SitePolicy)) { web.ApplySitePolicy(job.SitePolicy); } // Apply Tenant Branding, if requested if (job.ApplyTenantBranding) { var brandingSettings = PnPPartnerPackUtilities.GetTenantBrandingSettings(); using (var repositoryContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext( PnPPartnerPackSettings.InfrastructureSiteUrl)) { var brandingTemplate = BrandingJobHandler.PrepareBrandingTemplate(repositoryContext, brandingSettings); // Fixup Title and Description if (brandingTemplate != null) { if (brandingTemplate.WebSettings != null) { brandingTemplate.WebSettings.Title = job.SiteTitle; brandingTemplate.WebSettings.Description = job.Description; } // TO-DO: Need to handle exception here as there are multiple webs inside this where BrandingJobHandler.ApplyBrandingOnWeb(web, brandingSettings, brandingTemplate); } } } Console.WriteLine("Applyed Provisioning Template \"{0}\" to site.", job.ProvisioningTemplateUrl); } } } }
private Installation CreateSite(InstallConfig install) { var result = new Installation { Success = false, Message = string.Empty }; if (!string.IsNullOrEmpty(install.TenantName) && !string.IsNullOrEmpty(install.Aliases) && !string.IsNullOrEmpty(install.SiteName)) { using (var scope = _serviceScopeFactory.CreateScope()) { // use the SiteState to set the Alias explicitly so the tenant can be resolved var aliases = scope.ServiceProvider.GetRequiredService <IAliasRepository>(); string firstalias = install.Aliases.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)[0]; var alias = aliases.GetAliases().FirstOrDefault(item => item.Name == firstalias); var siteState = scope.ServiceProvider.GetRequiredService <SiteState>(); siteState.Alias = alias; var sites = scope.ServiceProvider.GetRequiredService <ISiteRepository>(); var site = sites.GetSites().FirstOrDefault(item => item.Name == install.SiteName); if (site == null) { var tenants = scope.ServiceProvider.GetRequiredService <ITenantRepository>(); var users = scope.ServiceProvider.GetRequiredService <IUserRepository>(); var roles = scope.ServiceProvider.GetRequiredService <IRoleRepository>(); var userroles = scope.ServiceProvider.GetRequiredService <IUserRoleRepository>(); var folders = scope.ServiceProvider.GetRequiredService <IFolderRepository>(); var log = scope.ServiceProvider.GetRequiredService <ILogManager>(); var identityUserManager = scope.ServiceProvider.GetRequiredService <UserManager <IdentityUser> >(); var tenant = tenants.GetTenants().FirstOrDefault(item => item.Name == install.TenantName); site = new Site { TenantId = tenant.TenantId, Name = install.SiteName, LogoFileId = null, DefaultThemeType = install.DefaultTheme, DefaultLayoutType = install.DefaultLayout, DefaultContainerType = install.DefaultContainer, SiteTemplateType = install.SiteTemplate }; site = sites.AddSite(site); IdentityUser identityUser = identityUserManager.FindByNameAsync(Constants.HostUser).GetAwaiter().GetResult(); if (identityUser == null) { identityUser = new IdentityUser { UserName = Constants.HostUser, Email = install.HostEmail, EmailConfirmed = true }; var create = identityUserManager.CreateAsync(identityUser, install.HostPassword).GetAwaiter().GetResult(); if (create.Succeeded) { var user = new User { SiteId = site.SiteId, Username = Constants.HostUser, Password = install.HostPassword, Email = install.HostEmail, DisplayName = install.HostName, LastIPAddress = "", LastLoginOn = null }; user = users.AddUser(user); var hostRoleId = roles.GetRoles(user.SiteId, true).FirstOrDefault(item => item.Name == Constants.HostRole)?.RoleId ?? 0; var userRole = new UserRole { UserId = user.UserId, RoleId = hostRoleId, EffectiveDate = null, ExpiryDate = null }; userroles.AddUserRole(userRole); // add user folder var folder = folders.GetFolder(user.SiteId, Utilities.PathCombine("Users", "\\")); if (folder != null) { folders.AddFolder(new Folder { SiteId = folder.SiteId, ParentId = folder.FolderId, Name = "My Folder", Path = Utilities.PathCombine(folder.Path, user.UserId.ToString(), "\\"), Order = 1, IsSystem = true, Permissions = new List <Permission> { new Permission(PermissionNames.Browse, user.UserId, true), new Permission(PermissionNames.View, Constants.AllUsersRole, true), new Permission(PermissionNames.Edit, user.UserId, true), }.EncodePermissions(), }); } } } foreach (string aliasname in install.Aliases.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { alias = aliases.GetAliases().FirstOrDefault(item => item.Name == aliasname); alias.SiteId = site.SiteId; aliases.UpdateAlias(alias); } tenant.Version = Constants.Version; tenants.UpdateTenant(tenant); log.Log(site.SiteId, LogLevel.Trace, this, LogFunction.Create, "Site Created {Site}", site); } } } result.Success = true; return(result); }
public static List <Rule> GetRules(Site site, string path) { var section = GetSection(site, path); return(section.Rules.ToList()); }