internal static void TimerTick(DateTime now) { if (AcquireLock(LockingTimeframe)) { try { Debug.WriteLine("#Notification> ** lock recieved"); _processing = true; TimerTick(now, NotificationFrequency.Immediately); TimerTick(now, NotificationFrequency.Daily); TimerTick(now, NotificationFrequency.Weekly); TimerTick(now, NotificationFrequency.Monthly); } catch (Exception ex) { SnLog.WriteException(ex); } finally { _processing = false; ReleaseLock(); NotificationSender.StartMessageProcessing(); } } else { Debug.WriteLine("#Notification> ** couldn't get lock"); } }
/// <summary> /// Gets the value of the resource for the specified culture and class. /// </summary> /// <param name="className">Name of the category.</param> /// <param name="name">Name of the resource.</param> /// <param name="cultureInfo"></param> /// <returns>The value of the resource, If a match is not possible, a generated resourcekey is returned.</returns> public object GetObject(string className, string name, CultureInfo cultureInfo) { var s = GetObjectInternal(cultureInfo, className, name); if (s == null) { if (!string.IsNullOrEmpty(RepositoryEnvironment.FallbackCulture)) { try { // look for resource value using the fallback culture var enCultureInfo = CultureInfo.GetCultureInfo(RepositoryEnvironment.FallbackCulture); s = GetObjectInternal(enCultureInfo, className, name); } catch (CultureNotFoundException ex) { SnLog.WriteException(ex, string.Format("Invalid fallback culture: {0} ({1}, {2})", RepositoryEnvironment.FallbackCulture, className, name)); } } // no fallback resource, display the class and key instead if (s == null) s = String.Concat(className, cultureInfo.Name, name); } if (!IsResourceEditorAllowed) return s; return GetEditorMarkup(className, name, s as string); }
private bool SendToAllQueues(Message message) { var success = true; for (var i = 0; i < _sendQueues.Count; i++) { // if a sender queue is not available at the moment due to a previous error, don't send the message if (!_sendQueuesAvailable[i]) { continue; } try { _sendQueues[i].Send(message); } catch (MessageQueueException mex) { SnLog.WriteException(mex, EventMessage.Errors.SendError, EventId.Messaging); _sendQueuesAvailable[i] = false; // indicate that the queue is out of order success = false; } catch (Exception ex) { SnLog.WriteException(ex, EventMessage.Errors.SendError, EventId.Messaging); _sendQueuesAvailable[i] = false; // indicate that the queue is out of order success = false; } } return(success); }
/* ============================================================================== Init */ public ClusterChannel(IClusterMessageFormatter formatter, ClusterMemberInfo clusterMemberInfo) { _incomingMessages = new List <ClusterMessage>(); CounterManager.Reset("IncomingMessages"); CounterManager.Reset("TotalMessagesToProcess"); m_formatter = formatter; m_clusterMemberInfo = clusterMemberInfo; // initiate processing threads for (var i = 0; i < Configuration.Messaging.MessageProcessorThreadCount; i++) { try { var thstart = new ParameterizedThreadStart(CheckProcessableMessages); var thread = new Thread(thstart); thread.Name = i.ToString(); thread.Start(); SnTrace.Messaging.Write("ClusterChannel: 'CheckProcessableMessages' thread started. ManagedThreadId: {0}", thread.ManagedThreadId); } catch (Exception ex) { SnLog.WriteException(ex); } } }
protected override void OnInit(EventArgs e) { base.OnInit(e); var genericContent = GetContextNode() as GenericContent; if (genericContent != null) { try { if (NeedValidation) { var cnt = Content.Create(genericContent); if (!cnt.IsValid) { return; } } // take action only if the action name is correct if (!string.IsNullOrEmpty(PortalContext.Current.ActionName) && PortalContext.Current.ActionName.ToLower() == "publish") { genericContent.Publish(); } } catch (Exception ex) { SnLog.WriteException(ex); } } CallDone(); }
protected virtual Node[] GetNavigableNodes() { var depth = Depth > 0 ? (OmitContextNode ? Depth + 1 : Depth) : 3; var enumeratorContext = LoadFullTree ? null : PortalContext.Current.ContextNodePath; if (ContextNode == null) { return(new Node[0]); } try { IEnumerable <Node> nodes = null; if (!string.IsNullOrEmpty(this.QueryFilter)) { nodes = SiteMenuNodeEnumerator.GetNodes(ContextNode.Path, ExecutionHint.None, this.QueryFilter, depth, enumeratorContext, GetContextChildren).ToList(); } else { nodes = SiteMenuNodeEnumerator.GetNodes(ContextNode.Path, ExecutionHint.None, GetQuery(), depth, enumeratorContext, GetContextChildren).ToList(); } return(nodes.Where(node => NodeIsValid(node)).ToArray()); } catch (Exception ex) { SnLog.WriteException(ex); return(new Node[0]); } }
public override void SavePersonalizationState(PersonalizationState state) { // Take care of the unexpected personalization behavior, when User scope is not used, we need to ensure that scope is able to be changed to shared scope. // 1. check web.config authorization section that enterSharedScope is allowed to * users. // 2. misconfigured authorization section leads to data loss due to the personalization data becomes user scope before saving the state if (state.WebPartManager.Personalization.Scope == PersonalizationScope.User) { try { WriteLog("SavePersonalizationState --> Personalization.Scope = PersonalizationScope.User: trying to ToggleScope();"); state.WebPartManager.Personalization.ToggleScope(); } catch (InvalidOperationException exc) // logged { SnLog.WriteException(exc); } catch (ArgumentOutOfRangeException exc) // logged { SnLog.WriteException(exc); } } try { base.SavePersonalizationState(state); } catch (InvalidContentActionException ex) { // not enough permissions to save page state, never mind SnLog.WriteException(ex); } }
protected override void CreateChildControls() { // in quick search mode the portlet redirects to the real // search page without executing any query if (QuickSearchMode) { Controls.Clear(); try { var viewControl = Page.LoadControl(SkinManager.Resolve(Renderer)) as UserControl; if (viewControl != null) { Controls.Add(viewControl); InitializeControls(); } } catch (Exception exc) { SnLog.WriteException(exc); } ChildControlsCreated = true; return; } base.CreateChildControls(); InitializeControls(); }
public bool Authenticate(HttpApplication application, bool basicAuthenticated, bool anonymAuthenticated) { var context = AuthenticationHelper.GetContext(application); //HttpContext.Current; var request = AuthenticationHelper.GetRequest(application); bool headerMark, uriMark; string actionHeader, uri, accessHeadAndPayload; if (IsTokenAuthenticationRequested(request, out headerMark, out uriMark, out actionHeader, out uri, out accessHeadAndPayload)) { if (basicAuthenticated && anonymAuthenticated) { SnLog.WriteException(new UnauthorizedAccessException("Invalid user.")); context.Response.StatusCode = HttpResponseStatusCode.Unauthorized; context.Response.Flush(); if (application?.Context != null) { application.CompleteRequest(); } } else { TokenAuthenticate(basicAuthenticated, headerMark, uriMark, actionHeader, uri, accessHeadAndPayload, context, application); } return(true); } return(false); }
public static void Execute(IndexingActivityBase activity) { using (var op = SnTrace.Index.StartOperation("IAQ: A{0} EXECUTION.", activity.Id)) { IndexingActivityHistory.Start(activity.Id); try { using (new Storage.Security.SystemAccount()) activity.ExecuteIndexingActivityAsync(CancellationToken.None).GetAwaiter().GetResult(); } catch (Exception e) { SnLog.WriteException(e, $"Indexing activity execution error. Activity: #{activity.Id} ({activity.ActivityType})"); SnTrace.Index.WriteError("IAQ: A{0} EXECUTION ERROR: {1}", activity.Id, e); IndexingActivityHistory.Error(activity.Id, e); } finally { DependencyManager.Finish(activity); IndexManager.ActivityFinished(activity.Id); } op.Successful = true; } }
private static void Load() { foreach (var type in TypeResolver.GetTypesByInterface(typeof(IEvaluator))) { try { if (!(type.GetCustomAttributes(typeof(ScriptTagNameAttribute), false).FirstOrDefault() is ScriptTagNameAttribute tagAttribute)) { SnLog.WriteWarning($"Evaluator does not have a ScriptTagNameAttribute: {type.FullName} " + $"(Assembly: {type.Assembly})"); continue; } var fullTagName = GetFullTagName(tagAttribute.TagName); // check if we already have an evaluator for this tag if (Providers.Instance.GetProvider <IEvaluator>(fullTagName) != null) { continue; } var engine = (IEvaluator)Activator.CreateInstance(type); Providers.Instance.SetProvider(fullTagName, engine); SnLog.WriteInformation("Evaluator loaded: " + tagAttribute.TagName + ": " + engine); } catch (Exception ex) { SnLog.WriteException(ex, $"Error loading script evaluator class. {type.AssemblyQualifiedName}"); } } }
private static IEnumerable <string> ReadDependencies(string path) { // read dependencies for .js files only if (!path.ToLower().EndsWith(".js")) { return(new List <string>()); } try { var deps = new List <string>(); using (var str = VirtualPathProvider.OpenFile(path)) using (var r = new StreamReader(str)) { var l = r.ReadLine(); var parsedDependency = ParseDependency(l); while (parsedDependency != null) { deps.Add(parsedDependency); l = r.ReadLine(); parsedDependency = ParseDependency(l); } } return(deps); } catch (Exception e) { SnLog.WriteException(e); } return(null); }
public static string GetAllResourcesForClass(string classname, string rnd) { AssertPermission(PlaceholderPath); var langs = GetCurrentSupportedLanguageNames().OrderBy(x => x); var resourceKeys = new Dictionary <string, KeyValuePair <string, string>[]>(); foreach (var name in SenseNetResourceManager.Current.GetClassKeys(classname).OrderBy(x => x)) { var resources = new Dictionary <string, string>(); foreach (var lang in langs) { try { var cultureInfo = new CultureInfo(lang); var s = SenseNetResourceManager.Current.GetObjectOrNull(classname, name, cultureInfo) as string; resources.Add(lang, s); } catch (Exception ex) { SnLog.WriteException(ex); resources.Add(lang, "ERROR: " + ex.Message); } } resourceKeys.Add(name, resources.ToArray()); } return(JsonConvert.SerializeObject(resourceKeys.ToArray())); }
private static bool InsertLock(double timeframe) { using (var context = new DataHandler()) { var success = false; var notifLock = new Synchronization { LockName = NOTIFICATIONLOCKNAME, Locked = true, ComputerName = Environment.MachineName, LockedUntil = DateTime.UtcNow.AddMinutes(timeframe), LockId = AppDomainId }; try { context.Synchronizations.InsertOnSubmit(notifLock); context.SubmitChanges(); success = true; } catch (Exception ex) { SnLog.WriteException(ex); } return(success); } }
protected override void CreateChildControls() { Controls.Clear(); try { // start with the property that may be filled by the parent control var controlPath = ControlPath; // If the property is empty, try to load the control from under the skin. // If it is not found there, the fallback is the old global path. if (string.IsNullOrEmpty(controlPath) && !SkinManager.TryResolve(SkinControlPath, out controlPath)) controlPath = GlobalControlPath; var viewControl = Page.LoadControl(controlPath) as UserControl; if (viewControl != null) { Controls.Add(viewControl); SetParameters(); } } catch (Exception exc) { SnLog.WriteException(exc); } ChildControlsCreated = true; }
protected override void OnInit(EventArgs e) { base.OnInit(e); var genericContent = GetContextNode() as GenericContent; if (genericContent != null) { try { // take action only if the action name is correct if (!string.IsNullOrEmpty(PortalContext.Current.ActionName) && (PortalContext.Current.ActionName.ToLower() == "undocheckout" || PortalContext.Current.ActionName.ToLower() == "forceundocheckout")) { genericContent.UndoCheckOut(); } } catch (Exception ex) { SnLog.WriteException(ex); } } CallDone(); }
protected override void OnLoad(EventArgs e) { var listDefinition = this.ViewDefinition as Handlers.ListView; if (listDefinition != null) { ViewDataSource.FlattenResults = listDefinition.Flat; ViewDataSource.DefaultOrdering = listDefinition.SortBy; ViewDataSource.GroupBy = listDefinition.GroupBy; try { var listGrid = ViewBody as ListGrid; if (listGrid != null) { var sortInfo = new SortingInfo(listDefinition.SortBy); listGrid.DefaulSortExpression = sortInfo.FullName; listGrid.DefaulSortDirection = sortInfo.Direction; } } catch (Exception ex) { SnLog.WriteException(ex); } } base.OnLoad(e); }
private void PingTimer_Elapsed(object sender, ElapsedEventArgs e) { try { if (!ContentRepository.DistributedApplication.ClusterChannel.AllowMessageProcessing) { return; } RecoverChannels(); var receiverName = ContentRepository.DistributedApplication.ClusterChannel.ReceiverName; _currentResponses = new List <string>(); _pongTimer.Enabled = true; _receiverEnabled = true; // receiving is disabled before sending the first ping message _pongTimer.Start(); var notResponsiveChannels = _channels.Where(c => c.NeedToRecover && !c.Running && c.AlreadyStarted).Select(c => c.Name).ToArray(); if (notResponsiveChannels.Length > 0) { Debug.WriteLine( $"ClusterChannelMonitor> notResponsiveChannels ({receiverName}): {string.Join(", ", notResponsiveChannels)}"); } var pingMessage = new PingMessage(notResponsiveChannels); _actualPingId = pingMessage.Id; pingMessage.SendAsync(CancellationToken.None).GetAwaiter().GetResult(); } catch (Exception ex) { SnLog.WriteException(ex); } }
public static async Task SendChangePasswordMailByEmail(Content content, HttpContext httpContext, string email, string returnUrl = null) { if (string.IsNullOrEmpty(email)) { throw new ArgumentNullException(nameof(email)); } // This method will never throw an exception (except if no email address was provided). // The caller can be a Visitor, so they should not receive any information about // whether the user exists or not and if we know the email or not. // query user in elevated mode using (new SystemAccount()) { var user = Content.All.FirstOrDefault(c => c.TypeIs("User") && (string)c["Email"] == email); if (user == null) { return; } try { await SendChangePasswordMail(user, httpContext, returnUrl).ConfigureAwait(false); } catch (Exception ex) { SnLog.WriteException(ex, $"Error during sending password change email for {email}."); } } }
private void PongTimer_Elapsed(object sender, ElapsedEventArgs e) { try { if (!_receiverEnabled) { return; } _receiverEnabled = false; _pongTimer.Stop(); _pongTimer.Enabled = false; var stoppedChannels = _lastResponses.Except(_currentResponses).ToArray(); var startedChannels = _currentResponses.Except(_lastResponses).ToArray(); if (stoppedChannels.Length > 0) { ChannelStopped(stoppedChannels); } if (startedChannels.Length > 0) { ChannelStarted(startedChannels); } _lastResponses = _currentResponses; } catch (Exception ex) { SnLog.WriteException(ex); } }
private static X509Certificate2 LoadCertificate(StoreLocation storeLocation) { X509Store store = null; try { store = new X509Store(storeLocation); store.Open(OpenFlags.ReadOnly); // note that CompareOrdinal does not work on the Thumbprint property return(store.Certificates.Cast <X509Certificate2>().FirstOrDefault(cert => string.Compare(cert.Thumbprint, Configuration.Cryptography.CertificateThumbprint, StringComparison.InvariantCultureIgnoreCase) == 0)); } catch (Exception ex) { SnLog.WriteException(ex, $"Could not load x509 certificate from store location {storeLocation}."); } finally { if (store != null) { store.Close(); } } return(null); }
//================================================================================= Manage applications public static Application RegisterApplication(RegisterApplicationRequest request) { using (var cn = new SqlConnection(Configuration.ConnectionString)) { SqlCommand cm1 = null; try { cn.Open(); cm1 = cn.CreateCommand(); cm1.CommandText = REGISTERAPPLICATIONSQL; cm1.Connection = cn; cm1.CommandType = CommandType.Text; var appData = JsonConvert.SerializeObject(new { ApplicationUrl = request.ApplicationUrl, TaskFinalizeUrl = request.TaskFinalizeUrl, AuthenticationUrl = request.AuthenticationUrl, AuthorizationUrl = request.AuthorizationUrl }); var resultApp = new Application { AppId = request.AppId, ApplicationUrl = request.ApplicationUrl, AuthenticationUrl = request.AuthenticationUrl, AuthorizationUrl = request.AuthorizationUrl }; cm1.Parameters.Add("@AppId", SqlDbType.NVarChar).Value = request.AppId; cm1.Parameters.Add("@AppData", SqlDbType.NVarChar).Value = appData; using (var reader = cm1.ExecuteReader()) { // there must be only one row reader.Read(); resultApp.RegistrationDate = reader.GetDateTime(reader.GetOrdinal("RegistrationDate")); resultApp.LastUpdateDate = reader.GetDateTime(reader.GetOrdinal("LastUpdateDate")); } return(resultApp); } catch (Exception ex) { SnLog.WriteException(ex, "Error during app registration.", EventId.TaskManagement.General); throw new TaskManagementException("Error during application registration.", request.AppId, ex); } finally { if (cm1 != null) { cm1.Dispose(); } } } }
private void DoRefreshLogic() { if (this.IsRefreshTime) { //lock (locked) if (ReclaimLock(this.Id)) { try { if (this.IsRefreshTime) { RefreshDocument(); } } catch (Exception e) { SnLog.WriteException(e); } finally { ReleaseLock(this.Id); } } } }
protected void ButtonSave_Click(object sender, EventArgs e) { try { ClearEveryoneDeny(); ValidateAcl(); var context = Node.LoadNode(ContextInfo.Path); SnAccessControlList.SetAcl(context, this.Acl); var p = Page as PageBase; if (p != null) { p.Done(false); } } catch (Exception ex) { SnLog.WriteException(ex); // show error PanelError.Visible = true; PanelError.Controls.Add(new LiteralControl(ex.Message)); } }
public virtual void OnTaskFinished(SnTaskResult result) { // the task was executed successfully without an error message if (result.Successful && result.Error == null) { return; } try { if (result.Error != null) { // log the error message and details for admins SnLog.WriteError("Task execution error, see the details below.", EventId.TaskManagement.General, properties: new Dictionary <string, object> { { "TaskType", result.Task.Type }, { "TaskData", result.Task.TaskData }, { "ErrorCode", result.Error.ErrorCode }, { "ErrorType", result.Error.ErrorType }, { "Message", result.Error.Message }, { "Details", result.Error.Details }, { "CallingContext", result.Error.CallingContext } }); } } catch (Exception ex) { SnLog.WriteException(ex); } }
public static void SetCacheControlHeaders(HttpCacheability?httpCacheability = null, DateTime?lastModified = null, TimeSpan?maxAge = null) { var cache = HttpContext.Current.Response.Cache; try { if (httpCacheability.HasValue) { cache.SetCacheability(httpCacheability.Value); } if (lastModified.HasValue) { var t = lastModified.Value; if (t > DateTime.UtcNow) { t = DateTime.UtcNow; } cache.SetLastModified(t); } if (maxAge.HasValue) { // max-age does not appear in response header without this cache.SetMaxAge(maxAge.Value); cache.SetSlidingExpiration(true); } } catch (Exception ex) { SnLog.WriteException(ex, $"Exception in SetCacheControlHeaders. Parameter values: httpCacheability:'{httpCacheability}' lastModified:'{lastModified}' maxAge:'{maxAge}'", EventId.Portal); } }
static BlobStorageBase() { Providers = TypeResolver.GetTypesByInterface(typeof(IBlobProvider)) .Select(t => { try { var instance = (IBlobProvider)Activator.CreateInstance(t); SnTrace.System.Write("BlobProvider found: {0}", t.FullName); return(instance); } catch (MissingMethodException) { // no default constructor: provider must be instantiated manually SnTrace.System.Write("BlobProvider found, but must be configured manually: {0}", t.FullName); } catch (Exception ex) { SnLog.WriteException(ex, $"Error during instantiating {t.FullName}."); } return(null); }) .Where(instance => instance != null) .ToDictionary(x => x.GetType().FullName, x => x); BuiltInProvider = new BuiltInBlobProvider(); }
private bool TryLoadFirstContent() { var result = false; if (string.IsNullOrEmpty(this._contentPath) && !string.IsNullOrEmpty(this.UsedContentTypeName) && _displayMode != GetViewModeName(ViewMode.InlineNew)) { try { var cql = $"+TypeIs:{UsedContentTypeName} +InFolder:{PortalContext.Current.ContextNodeHead.Path} .SORT:Index"; var qresult = ContentQuery.Query(cql, QuerySettings.AdminSettings); var firstNode = qresult.Nodes.FirstOrDefault(); if (firstNode != null) { _contentPath = firstNode.Path; _displayMode = GetViewModeName(ViewMode.Browse); result = true; } } catch (Exception exc) // logged { SnLog.WriteException(exc); } } return(result); }
private void RepairSendQueues() { bool repairHappened = false; for (var i = 0; i < _sendQueues.Count; i++) { if (!_sendQueuesAvailable[i]) { try { _sendQueues[i] = RecoverQueue(_sendQueues[i]); _sendQueuesAvailable[i] = true; // indicate that the queue is up and running repairHappened = true; } catch (Exception ex) { SnLog.WriteException(ex, EventMessage.Errors.RepairError, EventId.Messaging); } } } if (repairHappened) { SnLog.WriteInformation("Send queues have been repaired.", EventId.Messaging); } }
internal static Dictionary <string, Dictionary <Version, PackagingResult> > ExecuteAssemblyPatches( IEnumerable <SnComponentInfo> assemblyComponents, RepositoryStartSettings settings = null) { var results = new Dictionary <string, Dictionary <Version, PackagingResult> >(); foreach (var assemblyComponent in assemblyComponents) { try { var patchResults = ExecuteAssemblyPatches(assemblyComponent, settings); if (patchResults?.Any() ?? false) { results[assemblyComponent.ComponentId] = patchResults; } } catch (Exception ex) { SnLog.WriteException(ex, $"Error during patch execution for component {assemblyComponent.ComponentId}."); } } return(results); }