/// <summary> /// Update a setting for all language-versions of a module /// </summary> public static void UpdateInstanceSettingForAllLanguages(int instanceId, string key, string value, Log log) { log?.Add($"UpdateInstanceSettingForAllLanguages(iid: {instanceId}, key: {key}, val: {value})"); var moduleController = new ModuleController(); // Find this module in other languages and update contentGroupGuid var originalModule = moduleController.GetModule(instanceId); var languages = LocaleController.Instance.GetLocales(originalModule.PortalID); if (!originalModule.IsDefaultLanguage && originalModule.DefaultLanguageModule != null) { originalModule = originalModule.DefaultLanguageModule; } foreach (var language in languages) { // Find module for given Culture var moduleByCulture = moduleController.GetModuleByCulture(originalModule.ModuleID, originalModule.TabID, originalModule.PortalID, language.Value); // Break if no module found if (moduleByCulture == null) { continue; } if (value == null) { moduleController.DeleteModuleSetting(moduleByCulture.ModuleID, key); } else { moduleController.UpdateModuleSetting(moduleByCulture.ModuleID, key, value); } } }
public async Task when_a_cluster_has_nodes_that_crash_very_often_then_logs_are_still_persisted() { Subject<IEnumerable<Peer>> peerObservable = new Subject<IEnumerable<Peer>>(); var scheduler = new VirtualScheduler(); var cluster = TestNode.CreateCluster(clusterSize: 20, peerObservable: peerObservable, scheduler: scheduler); cluster.Start(); await cluster.WaitForLeader(scheduler); var expectedServerLog = new Log(); var crasher = cluster.ToArray().StartRandomlyCrashing(peerObservable, new Random(), scheduler); var validator = Observable.Interval(TimeSpan.FromSeconds(1), scheduler) .Subscribe(async o => { Validate(cluster); }); Enumerable.Range(1, 100).ForEach(async i => { var leader = cluster.Leader(); if (leader != null) { await leader.AddLog(i.ToString()); expectedServerLog.Add(leader.Term, i.ToString()); } scheduler.AdvanceBy(TimeSpan.FromSeconds(1)); }); await cluster.WaitForLeader(scheduler); cluster.Leader().ServerLog.Entries.ShouldBeEquivalentTo(expectedServerLog.Entries); }
/// <summary> /// F /// </summary> /// <param name="_msg"></param> /// <param name="_info"></param> public void Message(string _msg, FileInfo _info) { //Log Message and File Info Log?.Add(new VMLogInfo(_msg, _info)); //On Message event OnMessage?.Invoke(_msg); }
/// <summary> /// Displays a Message to the Aplicaton /// </summary> public void Message(string _msg, bool _isAddedToLog) { if (_isAddedToLog == true) { Log?.Add(new VMLogInfo(_msg)); } //Run the OnMEssage Event OnMessage?.Invoke(_msg); }
public void Add_given_FormatAndArgs_should_AddItem() { // # Arrange. ILog sut = new Log(); Assert.IsFalse(sut.Logs.Any(), "There should be no log when we start."); // # Act. sut.Add("a{0}c{1}", "b", "d"); // # Assert. Assert.AreEqual("abcd", sut.Logs.Single()); }
public void Add_given_XDocument_should_AddIt() { // # Arrange. ILog sut = new Log(); Assert.IsFalse(sut.Logs.Any(), "There should be no log when we start."); var xml = new XDocument(); // # Act. sut.Add(xml); // # Assert. Assert.AreEqual(1, sut.Logs.Count(), "Right now we don't test the formatting, only the existence of the row."); }
public void Add_given_LogRows_should_AddThem() { // # Arrange. ILog sut = new Log(); Assert.IsFalse(sut.Logs.Any(), "There should be no log when we start."); const string RowOne = "My first row"; const string RowTwo = "My second row"; // # Act. sut.Add(new[] { RowOne, RowTwo }); // # Assert. Assert.AreEqual(2, sut.Logs.Count()); Assert.AreEqual(RowOne, sut.Logs[0]); Assert.AreEqual(RowTwo, sut.Logs[1]); }
public async Task logs_can_be_deterministicly_written_to_a_leader() { var scheduler = Scheduler.Default; var cluster = TestNode.CreateCluster(clusterSize: 2, scheduler: scheduler); cluster.Start(); await cluster.WaitForLeader(); var expectedServerLog = new Log(); Enumerable.Range(1,100).ForEach(async i => { await cluster.Leader().AddLog(i.ToString()); expectedServerLog.Add(cluster.Leader().Term, i.ToString()); }); cluster.Leader().LocalLog.ShouldBeEquivalentTo(expectedServerLog); cluster.Leader().ServerLog.ShouldBeEquivalentTo(expectedServerLog); }
public void TestPartialLog() { Log partialLog = new Log(new[] { new KeyValuePair<string, string>(Log.GuidKey, CombGuid.NewCombGuid().ToString()), new KeyValuePair<string, string>(Log.LevelKey, LoggingLevel.SystemNotification.ToString()), new KeyValuePair<string, string>(Log.ThreadIDKey, "1"), new KeyValuePair<string, string>(Log.ExceptionTypeFullNameKey, "System.Data.SqlException"), new KeyValuePair<string, string>(Log.StoredProcedureKey, "spTest"), new KeyValuePair<string, string>(Log.StoredProcedureLineKey, "2") }); Assert.IsNotNull(partialLog); partialLog.Add(); }
private UploadResult UploadOne(string contentTypeName, Guid guid, string field, string subFolder, bool usePortalRoot) { Log.Add($"upload one a:{App?.AppId}, i:{guid}, field:{field}, subfold:{subFolder}, useRoot:{usePortalRoot}"); // Check if the request contains multipart/form-data. if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } ExplicitlyRecheckEditPermissions(); PrepCore(guid, field, usePortalRoot); // Get the content-type definition var cache = App.Data.Cache; var contentType = cache.GetContentType(contentTypeName); var fieldDef = contentType[field]; // check if this field exists and is actually a file-field or a string (wysiwyg) field if (fieldDef == null || !(fieldDef.Type != "Hyperlink" || fieldDef.Type != "String")) { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, "Requested field '" + field + "' type doesn't allow upload")); } Log.Add($"field type:{fieldDef.Type}"); // check for special extensions try { var folder = EntityBase.Folder(); if (!string.IsNullOrEmpty(subFolder)) { folder = EntityBase.Folder(subFolder, false); } var filesCollection = HttpContext.Current.Request.Files; Log.Add($"folder: {folder}, file⋮{filesCollection.Count}"); if (filesCollection.Count > 0) { var originalFile = filesCollection[0]; #region check content-type extensions... // Check file size and extension if (!IsAllowedDnnExtension(originalFile.FileName)) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } // todo: check metadata of the FieldDef to see if still allowed #endregion if (originalFile.ContentLength > (1024 * MaxFileSizeKb)) { return new UploadResult { Success = false, Error = App.Resources.UploadFileSizeLimitExceeded } } ; // remove forbidden / troubling file name characters var fileName = originalFile.FileName .Replace("%", "per") .Replace("#", "hash"); if (fileName != originalFile.FileName) { Log.Add($"cleaned file name from'{originalFile.FileName}' to '{fileName}'"); } // Make sure the image does not exist yet (change file name) for (int i = 1; FileManager.Instance.FileExists(folder, Path.GetFileName(fileName)); i++) { fileName = Path.GetFileNameWithoutExtension(fileName) + "-" + i + Path.GetExtension(fileName); } // Everything is ok, add file var dnnFile = FileManager.Instance.AddFile(folder, Path.GetFileName(fileName), originalFile.InputStream); return(new UploadResult { Success = true, Error = "", Name = Path.GetFileName(fileName), Id = dnnFile.FileId, Path = dnnFile.RelativePath, Type = EntityBase.TypeName(dnnFile.Extension) }); } Log.Add("upload one complete"); return(new UploadResult { Success = false, Error = "No image was uploaded." }); } catch (Exception e) { return(new UploadResult { Success = false, Error = e.Message }); } #region experiment with asyc - not supported by current version of .net framework //string root = HttpContext.Current.Server.MapPath("~/App_Data"); //var provider = new MultipartFormDataStreamProvider(root); //try //{ // // Read the form data. // // todo: try to get this async if possible! // var task = Request.Content.ReadAsMultipartAsync(provider); // task.Wait(); // //await Request.Content.ReadAsMultipartAsync(provider); // //await TaskEx.Run(async () => await Request.Content.ReadAsMultipartAsync(provider)); // // This illustrates how to get the file names. // foreach (MultipartFileData file in provider.FileData) // { // // Check file size and extension // var extension = Path.GetExtension(file.Headers.ContentDisposition.FileName).ToLower().Replace(".", ""); // if (!allowedExtensions.Contains(extension)) // { // throw new HttpResponseException(HttpStatusCode.Forbidden); // // return new UploadResult { Success = false, Error = App.Resources.UploadExtensionNotAllowed }; // } // // todo: save it // // Trace.WriteLine(file.Headers.ContentDisposition.FileName); // // Trace.WriteLine("Server file path: " + file.LocalFileName); // } // return Request.CreateResponse(HttpStatusCode.OK); //} //catch (System.Exception e) //{ // return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); //} #endregion }
private string cleanImages(string html) { string[] allowedAttributes = UmbracoSettings.ImageAllowedAttributes.ToLower().Split(','); string pattern = @"<img [^>]*>"; MatchCollection tags = Regex.Matches(html + " ", pattern, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); foreach (Match tag in tags) { if (tag.Value.ToLower().IndexOf("umbraco_macro") == -1) { string cleanTag = "<img"; // gather all attributes // TODO: This should be replaced with a general helper method - but for now we'll wanna leave umbraco.dll alone for this patch Hashtable ht = new Hashtable(); MatchCollection m = Regex.Matches(tag.Value.Replace(">", " >"), "(?<attributeName>\\S*)=\"(?<attributeValue>[^\"]*)\"|(?<attributeName>\\S*)=(?<attributeValue>[^\"|\\s]*)\\s", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); foreach (Match attributeSet in m) { ht.Add(attributeSet.Groups["attributeName"].Value.ToString().ToLower(), attributeSet.Groups["attributeValue"].Value.ToString()); } // Build image tag foreach (string attr in allowedAttributes) { if (helper.FindAttribute(ht, attr) != "") { cleanTag += " " + attr + "=\"" + helper.FindAttribute(ht, attr) + "\""; } } // If umbracoResizeImage attribute exists we should resize the image! if (helper.FindAttribute(ht, "umbracoresizeimage") != "") { try { cleanTag += doResize(ht); } catch (Exception err) { cleanTag += " src=\"" + helper.FindAttribute(ht, "src") + "\""; if (helper.FindAttribute(ht, "width") != "") { cleanTag += " width=\"" + helper.FindAttribute(ht, "width") + "\""; cleanTag += " height=\"" + helper.FindAttribute(ht, "height") + "\""; } Log.Add(LogTypes.Error, User.GetUser(0), -1, "Error resizing image in editor: " + err.ToString()); } } else { // Add src, width and height properties cleanTag += " src=\"" + helper.FindAttribute(ht, "src") + "\""; if (helper.FindAttribute(ht, "width") != "") { cleanTag += " width=\"" + helper.FindAttribute(ht, "width") + "\""; cleanTag += " height=\"" + helper.FindAttribute(ht, "height") + "\""; } } if (bool.Parse(GlobalSettings.EditXhtmlMode)) { cleanTag += "/"; } cleanTag += ">"; html = html.Replace(tag.Value, cleanTag); } } return(html); }
public void TestPartialLogMinimum() { var loggers = Log.Loggers.ToArray(); foreach (var logger in loggers) Log.RemoveLogger(logger); Log.SetTrace(); Log.Flush(); Log partialLog = new Log(new[] { new KeyValuePair<string, string>(Log.GuidKey, CombGuid.NewCombGuid().ToString()) }); Assert.IsNotNull(partialLog); partialLog.Add(); }
// Initialize only on the first request public void InitializeApplication(HttpApplication HttpApp) { if (s_InitializedAlready) { return; } lock (s_lock) { if (s_InitializedAlready) { return; } // Perform first-request initialization here ... try { Log.Add(LogTypes.System, User.GetUser(0), -1, "Application started at " + DateTime.Now); if (UmbracoSettings.AutoCleanLogs) { AddTask(LOG_SCRUBBER_TASK_NAME, GetLogScrubbingInterval()); } } catch { } // Check for configured key, checking for currentversion to ensure that a request with // no httpcontext don't set the whole app in configure mode if (GlobalSettings.CurrentVersion != null && !GlobalSettings.Configured) { HttpApp.Application["umbracoNeedConfiguration"] = true; } /* This section is needed on start-up because timer objects * might initialize before these are initialized without a traditional * request, and therefore lacks information on application paths */ /* Initialize SECTION END */ // add current default url HttpApp.Application["umbracoUrl"] = string.Format("{0}:{1}{2}", HttpApp.Context.Request.ServerVariables["SERVER_NAME"], HttpApp.Context.Request.ServerVariables["SERVER_PORT"], IOHelper.ResolveUrl(SystemDirectories.Umbraco)); // Start ping / keepalive timer pingTimer = new Timer(new TimerCallback(keepAliveService.PingUmbraco), HttpApp.Context, 60000, 300000); // Start publishingservice publishingTimer = new Timer(new TimerCallback(publishingService.CheckPublishing), HttpApp.Context, 600000, 60000); //Find Applications and event handlers and hook-up the events //BusinessLogic.Application.RegisterIApplications(); //define the base settings for the dependency loader to use the global path settings //if (!CompositeDependencyHandler.HandlerFileName.StartsWith(GlobalSettings_Path)) // CompositeDependencyHandler.HandlerFileName = GlobalSettings_Path + "/" + CompositeDependencyHandler.HandlerFileName; // init done... s_InitializedAlready = true; } }
public void DeleteVersion(int moduleId, int version) => Log.Add("delete version is not supported");
/// <summary> /// Adds debug information data to information list. /// </summary> /// <param name="info">The information list.</param> /// <param name="complete">If set to <c>true</c> add complete information.</param> private void AddDebugInfoData(Log.InfoList info, bool complete) { if (complete) { info.Add("VehicleId", this.vehicleId); Vehicle vehicle = Singleton<VehicleManager>.instance.m_vehicles.m_buffer[this.vehicleId]; info.Add("LeadingVehicle", vehicle.m_leadingVehicle); info.Add("TrailingVehicle", vehicle.m_trailingVehicle); info.Add("Spawned", vehicle.m_flags & Vehicle.Flags.Spawned); info.Add("Flags", vehicle.m_flags); info.Add("Info", vehicle.Info); if (vehicle.Info != null) { info.Add("IsLargeVehicle", vehicle.Info.m_isLargeVehicle); } } if (this.isStuck || this.isBroken) { info.Add("Problem", this.isStuck ? "Stuck" : null, this.isBroken ? "Broken" : null); } if (this.confusedSinceFrame > 0 || this.confusedSinceTime > 0) { info.Add("Confused", this.ConfusedForSeconds, this.ConfusedForFrames); } if (this.checkFlagSinceFrame > 0 || this.checkFlagSinceTime > 0) { info.Add("Flagged", this.checkFlags, this.CheckFlaggedForSeconds, this.CheckFlaggedForFrames); } }
public static void MakeNew(CMSNode Node, User User, User Translator, Language Language, string Comment, bool IncludeSubpages, bool SendEmail) { // Get translation taskType for obsolete task constructor var taskType = ApplicationContext.Current.Services.TaskService.GetTaskTypeByAlias("toTranslate"); // Create pending task Task t = new Task(new Umbraco.Core.Models.Task(taskType)); t.Comment = Comment; t.Node = Node; t.ParentUser = User; t.User = Translator; t.Save(); // Add log entry Log.Add(LogTypes.SendToTranslate, User, Node.Id, "Translator: " + Translator.Name + ", Language: " + Language.FriendlyName); // send it if (SendEmail) { string serverName = HttpContext.Current.Request.ServerVariables["SERVER_NAME"]; int port = HttpContext.Current.Request.Url.Port; if (port != 80) { serverName += ":" + port.ToString(); } serverName += IOHelper.ResolveUrl(SystemDirectories.Umbraco); // Send mail string[] subjectVars = { serverName, Node.Text }; string[] bodyVars = { Translator.Name, Node.Text, User.Name, serverName, t.Id.ToString(), Language.FriendlyName }; if (User.Email != "" && User.Email.Contains("@") && Translator.Email != "" && Translator.Email.Contains("@")) { // create the mail message MailMessage mail = new MailMessage(User.Email, Translator.Email); // populate the message mail.Subject = ui.Text("translation", "mailSubject", subjectVars, Translator); mail.IsBodyHtml = false; mail.Body = ui.Text("translation", "mailBody", bodyVars, Translator); try { SmtpClient sender = new SmtpClient(); sender.Send(mail); } catch (Exception ex) { LogHelper.Error <Translation>("Error sending translation e-mail", ex); } } else { LogHelper.Warn <Translation>("Could not send translation e-mail because either user or translator lacks e-mail in settings"); } } if (IncludeSubpages) { //store children array here because iterating over an Array property object is very inneficient. var c = Node.Children; foreach (CMSNode n in c) { MakeNew(n, User, Translator, Language, Comment, true, false); } } }
public string Logs() { ThrowIfNotSuperuser(); Log.Add("debug log load"); return(LogHeader("Overview") + LogHistoryOverview()); }
/// <summary> /// Construct an import-friedly, type-controlled value-dictionary to create or update an entity /// </summary> /// <param name="contentType"></param> /// <param name="newContentItem"></param> /// <param name="appId"></param> /// <returns></returns> private Dictionary <string, object> CreateEntityDictionary(string contentType, Dictionary <string, object> newContentItem, int appId) { Log.Add($"create ent dic a#{appId}, type:{contentType}"); // Retrieve content-type definition and check all the fields that this content-type has var cache = (BaseCache)DataSource.GetCache(null, appId); var listOfTypes = cache.GetContentType(contentType); // as ContentType; var attribs = listOfTypes.Attributes; var cleanedNewItem = new Dictionary <string, object>(); foreach (var attrDef in attribs) { // var attrDef = attr.Value;// ats.GetAttribute(attr); var attrName = attrDef.Name; if (!newContentItem.ContainsKey(attrName)) { continue; } var foundValue = newContentItem[attrName]; switch (attrDef.Type.ToLower()) { case "string": case "hyperlink": if (foundValue is string) { cleanedNewItem.Add(attrName, foundValue.ToString()); } else { ThrowValueMappingError(attrDef, foundValue); } break; case "boolean": if (bool.TryParse(foundValue.ToString(), out var bolValue)) { cleanedNewItem.Add(attrName, bolValue); } else { ThrowValueMappingError(attrDef, foundValue); } break; case "datetime": if (DateTime.TryParse(foundValue.ToString(), out var dtm)) { cleanedNewItem.Add(attrName, dtm); } else { ThrowValueMappingError(attrDef, foundValue); } break; case "number": if (decimal.TryParse(foundValue.ToString(), out var dec)) { cleanedNewItem.Add(attrName, dec); } else { ThrowValueMappingError(attrDef, foundValue); } break; case "entity": var relationships = new List <int>(); if (foundValue is IEnumerable foundEnum) // it's a list! { foreach (var item in foundEnum) { relationships.Add(CreateSingleRelationshipItem(item)); } } else // not a list { relationships.Add(CreateSingleRelationshipItem(foundValue)); } cleanedNewItem.Add(attrName, relationships); break; default: throw new Exception("Tried to create attribute '" + attrName + "' but the type is not known: '" + attrDef.Type + "'"); } // todo: maybe one day get default-values and insert them if not supplied by JS } return(cleanedNewItem); }
/// <summary> /// Log in game card-speciality info. /// </summary> /// <param name="info"></param> public void AddSpecialityInfo(string info) { Log.Add(info); }
/// <summary> /// Log speciality damage (Weapon-Triangle) of the card. /// </summary> /// <param name="damage"></param> public void AddWeaponTriangleInfo(decimal damage) { Log.Add($"{CardName} has an effective damage of " + $"{damage.ToString(System.Globalization.CultureInfo.InvariantCulture)} " + "in this battle"); }
public Dictionary <Guid, int> Save(IBlock block, AllInOneDto package, int appId, bool partOfPage) { Log.Add($"save started with a#{appId}, i⋮{package.Items.Count}, partOfPage:{partOfPage}"); var validator = new SaveDataValidator(package, Log); // perform some basic validation checks if (!validator.ContainsOnlyExpectedNodes(out var exp)) { throw exp; } // todo: unsure about this - thought I should check contentblockappid in group-header, because this is where it should be saved! //var contextAppId = appId; //var targetAppId = package.Items.First().Header.Group.ContentBlockAppId; //if (targetAppId != 0) //{ // Log.Add($"detected content-block app to use: {targetAppId}; in context of app {contextAppId}"); // appId = targetAppId; //} var appMan = new AppManager(appId, Log); var appRead = appMan.Read; var ser = new JsonSerializer(appRead.AppState, Log) { // Since we're importing directly into this app, we would prefer local content-types PreferLocalAppTypes = true }; validator.PrepareForEntityChecks(appRead); #region check if it's an update, and do more security checks then - shared with EntitiesController.Save // basic permission checks var permCheck = new Save.SaveSecurity(block, Log) .DoPreSaveSecurityCheck(appId, package.Items); var foundItems = package.Items.Where(i => i.Entity.Id != 0 && i.Entity.Guid != Guid.Empty) .Select(i => i.Entity.Guid != Guid.Empty ? appRead.Entities.Get(i.Entity.Guid) // prefer guid access if available : appRead.Entities.Get(i.Entity.Id) // otherwise id ); if (foundItems.Any(i => i != null) && !permCheck.EnsureAll(GrantSets.UpdateSomething, out var error)) { throw HttpException.PermissionDenied(error); } #endregion var items = package.Items.Select(i => { var ent = ser.Deserialize(i.Entity, false, false) as Entity; var index = package.Items.IndexOf(i); // index is helpful in case of errors if (!validator.EntityIsOk(index, ent, out exp)) { throw exp; } if (!validator.IfUpdateValidateAndCorrectIds(index, ent, out exp)) { throw exp; } ent.IsPublished = package.IsPublished; ent.PlaceDraftInBranch = package.DraftShouldBranch; // new in 11.01 if (i.Header.ListHas()) { // Check if Add was true, and fix if it had already been saved (EntityId != 0) // the entityId is reset by the validator if it turns out to be an update // todo: verify use - maybe it's to set before we save, as maybe afterwards it's always != 0? var add = i.Header.ListAdd(); i.Header.Add = add; if (ent.EntityId > 0 && add) { i.Header.Add = false; } } return(new BundleWithHeader <IEntity> { Header = i.Header, Entity = ent }); }) .ToList(); Log.Add("items to save generated, all data tests passed"); var publishing = new SxcPagePublishing().Init(block, Log); return(publishing.SaveInPagePublishing(appId, items, partOfPage, forceSaveAsDraft => new EditSaveBackend().DoSave(appMan, items, forceSaveAsDraft), permCheck)); }
protected virtual void Application_End(Object sender, EventArgs e) { Log.Add(LogTypes.System, BusinessLogic.User.GetUser(0), -1, "Application shut down at " + DateTime.Now); }
public IEnumerable <Dictionary <string, object> > GetAssignedEntities(int assignmentObjectTypeId, Guid keyGuid, string contentType, [FromUri] string appPath = null) { Log.Add($"get assigned for assigmentType#{assignmentObjectTypeId}, guid:{keyGuid}, type:{contentType}, path:{appPath}"); InitEavAndSerializer(); return(new MetadataController().GetAssignedEntities(assignmentObjectTypeId, "guid", keyGuid.ToString(), contentType)); }
public T Deserialize <T>(string obj) { Log.Add(LogTypes.Debug, 0, "NewsletterStudioContrib: Let's Deserialize" + obj); return(new JavaScriptSerializer().Deserialize <T>(obj)); }
public async Task clusters_remain_in_a_valid_state_throughout_logging() { var scheduler = new VirtualScheduler(); var cluster = TestNode.CreateCluster(clusterSize: 2, scheduler: scheduler); cluster.Start(); await cluster.WaitForLeader(scheduler); var expectedServerLog = new Log(); var validationCounter = 0; Observable.Interval(TimeSpan.FromSeconds(1), scheduler) .Subscribe(async o => { Validate(cluster); validationCounter ++; }); Enumerable.Range(1, 100).ForEach(async i => { await cluster.Leader().AddLog(i.ToString()); expectedServerLog.Add(cluster.Leader().Term, i.ToString()); scheduler.AdvanceBy(TimeSpan.FromSeconds(1)); }); Console.WriteLine("Validation ran {0} times on cluster", validationCounter); }
public string Logs(string key) { ThrowIfNotSuperuser(); Log.Add($"debug log load for {key}"); return(LogHeader(key) + LogHistory(key)); }
public string Serialize(object obj) { Log.Add(LogTypes.Debug, 0, "NewsletterStudioContrib: Let's Serialize" + obj.ToString()); return(new JavaScriptSerializer().Serialize(obj)); }
public async Task logs_can_be_quickly_written_in_parallel_to_a_leader_with_test_scheduler() { var scheduler = new VirtualScheduler(); var cluster = TestNode.CreateCluster(clusterSize: 4, scheduler: scheduler); cluster.Start(); await cluster.WaitForLeader(scheduler); var expectedServerLog = new Log(); Enumerable.Range(1, 100).ForEach( i => { cluster.Leader().AddLog(i.ToString()).Wait(); expectedServerLog.Add(cluster.Leader().Term, i.ToString()); scheduler.AdvanceBy(TimeSpan.FromSeconds(1)); }); cluster.Leader().LocalLog.Entries.Count.Should().Be(101); cluster.Leader().ServerLog.Entries.Count.Should().Be(101); cluster.Followers().ForEach(f => { Enumerable.Range(1, 100).ForEach(i => { var s = i.ToString(); f.LocalLog.Entries.Select(e => e.Log).Should().Contain(s); }); }); }
/// <summary> /// Create a module-content block /// </summary> /// <param name="instanceInfo">the dnn module-info</param> /// <param name="parentLog">a parent-log; can be null but where possible you should wire one up</param> /// <param name="tenant"></param> /// <param name="overrideParams">optional override parameters</param> public ModuleContentBlock(IInstanceInfo instanceInfo, Log parentLog, ITenant tenant, IEnumerable <KeyValuePair <string, string> > overrideParams = null) : base(parentLog, "CB.Mod") { InstanceInfo = instanceInfo ?? throw new Exception("Need valid Instance/ModuleInfo / ModuleConfiguration of runtime"); ParentId = instanceInfo.Id; ContentBlockId = ParentId; // url-params _urlParams = overrideParams ?? DnnWebForms.Helpers.SystemWeb.GetUrlParams(); // Ensure we know what portal the stuff is coming from // PortalSettings is null, when in search mode Tenant = tenant; // important: don't use the SxcInstance.Environment, as it would try to init the Sxc-object before the app is known, causing various side-effects var tempEnv = Factory.Resolve <IEnvironmentFactory>().Environment(parentLog); ZoneId = tempEnv.ZoneMapper.GetZoneId(tenant.Id); // use tenant as reference, as it can be different from instance.TennantId AppId = Factory.Resolve <IMapAppToInstance>().GetAppIdFromInstance(instanceInfo, ZoneId) ?? 0; // fallback/undefined YET Log.Add($"parent#{ParentId}, content-block#{ContentBlockId}, z#{ZoneId}, a#{AppId}"); if (AppId == Settings.DataIsMissingInDb) { _dataIsMissing = true; Log.Add("data is missing, will stop here"); return; } // 2018-09-22 new with auto-init-data SxcInstance = new SxcInstance(this, InstanceInfo, _urlParams, Log); if (AppId != 0) { Log.Add("real app, will load data"); // 2018-09-22 old // try to load the app - if possible //App = new App(Tenant, ZoneId, AppId, parentLog: Log); //Configuration = ConfigurationProvider.GetConfigProviderForModule(InstanceInfo.Id, App, SxcInstance); //// maybe ensure that App.Data is ready //var userMayEdit = SxcInstance.UserMayEdit; //App.InitData(userMayEdit, SxcInstance.Environment.PagePublishing.IsEnabled(InstanceInfo.Id), // Configuration); // 2018-09-22 new with auto-init-data App = new App(Tenant, ZoneId, AppId, ConfigurationProvider.Build(SxcInstance, false), true, Log); ContentGroup = App.ContentGroupManager.GetInstanceContentGroup(instanceInfo.Id, instanceInfo.PageId); if (ContentGroup.DataIsMissing) { _dataIsMissing = true; App = null; return; } SxcInstance.SetTemplateOrOverrideFromUrl(ContentGroup.Template); } }
/// <summary> /// the 'EP' of <see cref="REPL"/> /// </summary> public static object EvalPrint(string line, out Assembly AssemblyProduced) { string lineWithoutWhite = line.TrimStart(new char[] { ' ', '\t', '\r', '\n' }).TrimEnd(new char[] { ' ', '\t', '\r', '\n' }); if (lineWithoutWhite == "restart" || lineWithoutWhite == "restart;") { InteractiveShell.Reset(); InteractiveShell.LastError = null; string runcommands = ParseDBErc(); #if !DEBUG try { #endif eval = new SafeEvaluator(() => Startup(runcommands)); #if !DEBUG } catch (Exception e) { Console.WriteLine( "DBE initialization failed with message '{0}'. Type 'LastError' for details.", e.Message); InteractiveShell.LastError = e; eval = new SafeEvaluator(() => Startup(runcommands)); } #endif AssemblyProduced = null; return(null); } if (eval == null) { Console.Error.WriteLine("C# evaluator not initialized: use 'restart'."); AssemblyProduced = null; return(null); } object result = null; bool result_set; #if !DEBUG try { #endif string ans = eval.Evaluator.Evaluate(line, out result, out result_set); AssemblyProduced = eval.LatestAssembly; if (result_set) { InteractiveShell.ans = result; } if (ans != null) { string lineWoComment = RemoveAllComments(line); if (lineWoComment.IsEmptyOrWhite()) { Console.Error.WriteLine("Incomplete statement - missing closing parentheses?."); } return(null); } if (cmpCont.Report.Errors > 0 || cmpCont.Report.Warnings > 0) { Console.WriteLine("No. of errors|warnings: {0}|{1}.", cmpCont.Report.Errors, cmpCont.Report.Warnings); } if (result_set && result != null) { // t.IsAssignableFrom(typeof(char)) => Beware of strings // (a.k.a. IEnumerable<char>) Type typeArg = result.GetType().GetInterfaces(). Where(i => i.GetBaseName() == "IEnumerable"). Where(i => i.GetGenericArguments().Length == 1). Select(i => i.GetGenericArguments().First()). SingleOrDefault(t => !t.IsAssignableFrom(typeof(Char))); // If type implements IEnumerable<SomeClass>, call // IEnumerableExtensions.Summary<SomeClass> (using // reflection) instead of ToString in order to get some // useful output for the user string resultString; if (typeArg != null) { var summaryMethod = typeof(BoSSS.Foundation.IO.IEnumerableExtensions).GetMethods(). Where(m => m.Name == "Summary"). Single(m => m.GetParameters().Length == 1). MakeGenericMethod(typeArg); resultString = summaryMethod.Invoke(result, new object[] { result }).ToString(); } else { resultString = result.ToString(); } Console.Write(resultString); Log.Add(new Tuple <string, string>(line, resultString)); } InteractiveShell.LastError = null; #if !DEBUG } catch (Exception e) { Console.WriteLine(String.Format( "{0} occurred: {1}. Type 'LastError' for details.", e.GetType(), e.Message)); InteractiveShell.LastError = e; AssemblyProduced = null; } #endif return(result); }
/// <summary> /// Executes start-up commands /// </summary> /// <param name="startupCommands">Optional startup commands.</param> private static Evaluator Startup(string startupCommands) { Evaluator eval = GetEvaluator(); // Assembly References eval.ReferenceAssembly(typeof(System.Data.DataTable).Assembly); // required for session tables eval.ReferenceAssembly(typeof(ilPSP.Environment).Assembly); eval.ReferenceAssembly(typeof(ilPSP.LinSolvers.SimpleSolversInterface).Assembly); eval.ReferenceAssembly(typeof(BatchmodeConnector).Assembly); // Do it this cause connector is not referenced anywhere else, i.e. the assembly will often be missing otherwise eval.ReferenceAssembly(typeof(NUnit.Framework.Assert).Assembly); eval.ReferenceAssembly(typeof(BoSSS.PlotGenerator.PlotApplication).Assembly); eval.ReferenceAssembly(typeof(BoSSS.Platform.Utils.Geom.BoundingBox).Assembly); eval.ReferenceAssembly(typeof(BoSSS.Foundation.Basis).Assembly); eval.ReferenceAssembly(typeof(BoSSS.Foundation.XDG.XDGField).Assembly); eval.ReferenceAssembly(typeof(BoSSS.Foundation.Grid.Classic.Grid1D).Assembly); eval.ReferenceAssembly(typeof(BoSSS.Solution.Application).Assembly); eval.ReferenceAssembly(typeof(BoSSS.Solution.Gnuplot.Gnuplot).Assembly); eval.ReferenceAssembly(typeof(BoSSS.Solution.GridImport.Cgns).Assembly); eval.ReferenceAssembly(typeof(BoSSS.Solution.Statistic.CellLocalization).Assembly); eval.ReferenceAssembly(typeof(BoSSS.Solution.Tecplot.Tecplot).Assembly); eval.ReferenceAssembly(typeof(BoSSS.Solution.ASCIIExport.CurveExportDriver).Assembly); eval.ReferenceAssembly(typeof(BoSSS.Solution.AdvancedSolvers.MultigridOperator).Assembly); eval.ReferenceAssembly(typeof(BoSSS.Solution.XNSECommon.CurvatureAlgorithms).Assembly); eval.ReferenceAssembly(typeof(BoSSS.Solution.XdgTimestepping.LevelSetHandling).Assembly); eval.ReferenceAssembly(typeof(BoSSS.Solution.LevelSetTools.ContinuityProjection).Assembly); eval.ReferenceAssembly(typeof(BoSSSpad.BoSSSpadMain).Assembly); eval.ReferenceAssembly(typeof(Renci.SshNet.SftpClient).Assembly); eval.ReferenceAssembly(typeof(MiniBatchProcessor.Client).Assembly); eval.ReferenceAssembly(typeof(System.Numerics.Complex).Assembly); eval.ReferenceAssembly(typeof(Mono.CSharp.Evaluator).Assembly); eval.ReferenceAssembly(typeof(CNS.Program).Assembly); eval.ReferenceAssembly(typeof(IBM_Solver.IBM_SolverMain).Assembly); eval.ReferenceAssembly(typeof(XNSE_Solver.XNSE_SolverMain).Assembly); eval.ReferenceAssembly(typeof(BoSSS.Application.SipPoisson.SipPoissonMain).Assembly); eval.ReferenceAssembly(typeof(Rheology.Rheology).Assembly); eval.ReferenceAssembly(typeof(FSI_Solver.FSI_SolverMain).Assembly); eval.ReferenceAssembly(typeof(BoSSS.Foundation.SpecFEM.SpecFemField).Assembly); eval.ReferenceAssembly(typeof(BoSSS.Application.XdgPoisson3.XdgPoisson3Main).Assembly); // eval.ReferenceAssembly(typeof(BoSSS.Application.LowMachCombustionNSE.LowMachCombustionNSE).Assembly); // eval.ReferenceAssembly(typeof(NSE_SIMPLE.NSE_SIMPLEMain).Assembly); //eval.ReferenceAssembly(typeof(FSI_Solver.FSI_SolverMain).Assembly); //eval.ReferenceAssembly(typeof(FuelCell.FuelCellMain).Assembly); // Helical shit // eval.ReferenceAssembly(typeof(StokesHelical.HelicalMain).Assembly); // eval.ReferenceAssembly(typeof(PosissonScalar3CylinderCoords.PoissonScalar3CCMain).Assembly); // eval.ReferenceAssembly(typeof(PoissonScalar2CylinderCoords.PoissonScalar2CCMain).Assembly); eval.Compile( "using System;" + Console.Out.NewLine + "using System.Collections.Generic;" + Console.Out.NewLine + "using System.Linq;" + Console.Out.NewLine + "using ilPSP;" + Console.Out.NewLine + "using ilPSP.Utils;" + Console.Out.NewLine + "using BoSSS.Platform;" + Console.Out.NewLine + "using BoSSS.Foundation;" + Console.Out.NewLine + "using BoSSS.Foundation.Grid;" + Console.Out.NewLine + "using BoSSS.Foundation.Grid.Classic;" + Console.Out.NewLine + "using BoSSS.Foundation.IO;" + Console.Out.NewLine + "using BoSSS.Solution;" + Console.Out.NewLine + "using BoSSS.Solution.Control; " + Console.Out.NewLine + "using BoSSS.Solution.GridImport;" + Console.Out.NewLine + "using BoSSS.Solution.Statistic;" + Console.Out.NewLine + "using BoSSS.Solution.Utils;" + Console.Out.NewLine + "using BoSSS.Solution.Gnuplot;" + Console.Out.NewLine + "using BoSSS.Application.BoSSSpad;" + Console.Out.NewLine + "using Renci.SshNet;" + Console.Out.NewLine + "using Mono.CSharp;" ); // Make sure user is asked for password where required DatabaseController.PasswordCallback = PromptPassword; // Load Databases and DBController. Run console using (StringWriter stw = new StringWriter()) { ilPSP.Environment.StdOut.WriterS.Add(stw); ilPSP.Environment.StdErr.WriterS.Add(stw); eval.Run(@" Console.WriteLine(""""); Console.WriteLine("" BoSSSpad C# interpreter""); Console.WriteLine("" _______________________\n""); try { databases = DatabaseController.LoadDatabaseInfosFromXML(); string summary = databases.Summary(); Console.WriteLine(""Databases loaded:""); Console.WriteLine(summary); } catch (Exception e) { Console.WriteLine(); Console.WriteLine( ""{0} occurred with message '{1}' while loading the databases. Type 'LastError' for details."", e.GetType(), e.Message); InteractiveShell.LastError = e; } "); // Run startup commands try { using (StringReader reader = new StringReader(startupCommands)) { string multiline = null; int lineno = 0; for (string line = reader.ReadLine(); line != null; line = reader.ReadLine()) { line = line.TrimEnd(); lineno++; if (line.EndsWith("\\")) { if (multiline == null) { multiline = ""; } multiline += " " + line.Substring(0, line.Length - 1); } else { string completeline; if (multiline == null) { completeline = line; } else { completeline = multiline + " " + line; multiline = null; } try { eval.Run(completeline); } catch (Exception e) { throw new AggregateException( e.GetType().Name + " during the interpretation of DBErc file" + " line " + lineno + "; ", e); } } } } } catch (Exception e) { Console.WriteLine("Running startup commands failed with message '{0}'", e.Message); } eval.Run(@"Console.WriteLine(""\n Console ready for input. Type 'help' for help."");"); // Log results of startup Console.Out.Flush(); Console.Error.Flush(); ilPSP.Environment.StdOut.WriterS.Remove(stw); ilPSP.Environment.StdErr.WriterS.Remove(stw); Log.Add(new Tuple <string, string>("restart", stw.ToString())); return(eval); } }
public async Task logs_can_be_quickly_written_in_parallel_to_a_leader() { var scheduler = Scheduler.Default; var cluster = TestNode.CreateCluster(clusterSize: 4, scheduler: scheduler); cluster.Start(); await cluster.WaitForLeader(); var expectedServerLog = new Log(); var result = Enumerable.Range(1, 100).ParrallelForEach( i => { cluster.Leader().AddLog(i.ToString()).Wait(); expectedServerLog.Add(2, i.ToString()); }); cluster.Leader().LocalLog.Entries.Count.Should().Be(101); cluster.Leader().ServerLog.Entries.Count.Should().Be(101); cluster.Followers().ForEach(f => { Enumerable.Range(1, 100).ForEach(i => { var s = i.ToString(); f.LocalLog.Entries.Select(e => e.Log).Should().Contain(s); }); }); }
/// <summary> /// Handles the Error event of the Application control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void Application_Error(Object sender, EventArgs e) { // return immediately if an error is already been handled, to avoid infinite recursion if ((bool)handlingError) { lock (unhandledErrors) { unhandledErrors.Add(mApp.Server.GetLastError()); } return; } // make sure only one thread at a time can handle an error lock (handlingError) { Debug.Assert(!(bool)handlingError, "Two errors are being handled at the same time."); handlingError = true; // make sure handlingError always gets set to false try { if (GlobalSettings.Configured) { // log the error // zb-00017 #29930 : could have been cleared, though: take care, .GetLastError() may return null Exception ex = mApp.Server.GetLastError(); if (ex != null) { ex = ex.InnerException; } string error; if (mApp.Context.Request != null) { error = string.Format("At {0} (Referred by: {1}): {2}", mApp.Context.Request.RawUrl, mApp.Context.Request.UrlReferrer, ex); } else { error = "No Context available -> " + ex; } // Hide error if getting the user throws an error (e.g. corrupt / blank db) User staticUser = null; try { User.GetCurrent(); } catch { } Log.Add(LogTypes.Error, staticUser, -1, error); Trace.TraceError(error); lock (unhandledErrors) { if (unhandledErrors.Count > 0) { Trace.TraceError("New errors occurred while an error was being handled. The error handler Application_Error possibly raised another error, but was protected against an infinite loop."); } foreach (Exception unhandledError in unhandledErrors) { Trace.TraceError(unhandledError.StackTrace); } } } } finally { // clear unhandled errors lock (unhandledErrors) { unhandledErrors.Clear(); } // flag we're done with the error handling handlingError = false; } } }