public static IEnumerable <string> GetTemporaryPermissions(string[] userLabels)
        {
            List <string[]> allPerms = new List <string[]>();

            foreach (var label in userLabels)
            {
                LogEnvironment.LogDebugEvent($"Collecting extended permissions for {label}.", LogSeverity.Report);
                if (grantTable.TryGetValue(label, out var l))
                {
                    lock (l)
                    {
                        allPerms.Add(l.ToArray());
                    }
                }
            }

            return(allPerms.SelectMany(n => n).Distinct());
        }
Exemple #2
0
        /// <summary>
        /// Creates a non-generic Set-Decorator instance that can be used to manipulate entities of an unknown type in EntityFramewokr Core
        /// </summary>
        /// <param name="context">the target context</param>
        /// <param name="t">the target type</param>
        /// <returns>a DbSet-Decorator that mimics the underlaying DbSet</returns>
        public static IDbSet Set(this DbContext context, Type t)
        {
            Type contextType  = context.GetType();
            bool staticMethod = false;

            LogEnvironment.LogDebugEvent($"Creating Decorator for {t}", LogSeverity.Report);
            var method = MethodHelper.GetCapableMethod(contextType, new[] { t }, "Set", ref staticMethod, new object[] { }, out var _);//contextType.GetMethod("Set`1", Type.EmptyTypes);

            LogEnvironment.LogDebugEvent($"Method that was found: {method}", LogSeverity.Report);
            var set           = method.Invoke(context, new object[0]);
            var decoratorType = typeof(DbSetDecorator <>).MakeGenericType(t);

            LogEnvironment.LogDebugEvent($"Final Decorator Type: {decoratorType}", LogSeverity.Report);
            var constructor = decoratorType.GetConstructor(new [] { method.ReturnType });

            LogEnvironment.LogDebugEvent($"Decorator Constructor: {constructor}", LogSeverity.Report);
            return((IDbSet)constructor.Invoke(new[] { set }));
        }
 /// <summary>
 /// Sets an alerting context value indicated by a name
 /// </summary>
 /// <typeparam name="T">the target type that the object is to be of</typeparam>
 /// <param name="name">the name of the context-variable</param>
 /// <param name="value">the value of the context-variable</param>
 public void SetAlertingContextVariable <T>(string name, T value)
 {
     if (contextValues.ContainsKey(name))
     {
         object tmp = contextValues[name];
         if (tmp is T)
         {
             contextValues[name] = value;
         }
         else
         {
             LogEnvironment.LogDebugEvent(null, $"Suppressed the re-set of the value '{name}' to a new value of a different type.", (int)LogSeverity.Warning, null);
         }
     }
     else
     {
         contextValues.Add(name, value);
     }
 }
        /// <summary>
        /// Runs the specified query and registers the result in the defined targets
        /// </summary>
        /// <param name="query">the query that must added to some targets</param>
        private void RunQuery(QueryDefinition query)
        {
            IDbWrapper db;

            DynamicResult[] data;
            using (mappers[query.Source].AcquireDatabase(false, out db))
            {
                List <IDbDataParameter> parameters = new List <IDbDataParameter>();
                foreach (var param in query.Parameters)
                {
                    string callbackName;
                    if (!(param.ParameterValue is string && (callbackName = ((string)param.ParameterValue)).StartsWith("!!")))
                    {
                        parameters.Add(db.GetParameter(param.ParameterName, param.ParameterValue));
                    }
                    else
                    {
                        parameters.Add(db.GetParameter(param.ParameterName,
                                                       variableCallback.Value(callbackName.Substring(2))));
                    }
                }

                LogEnvironment.LogDebugEvent(null, string.Format("Running Query: {0}", query.Query), (int)LogSeverity.Report, null);
                if (query.QueryType == QueryType.Query)
                {
                    data = db.GetNativeResults(query.Query, null, parameters.ToArray());
                }
                else if (query.QueryType == QueryType.Procedure)
                {
                    var tmpData = db.CallProcedure(query.Query, null, parameters.ToArray());
                    data = tmpData[query.DesiredResultSet];
                }
                else
                {
                    throw new InvalidOperationException("Unsupported Query Type provided!");
                }
            }

            foreach (var target in query.Targets)
            {
                containers[target.TargetName].RegisterData(target.RegisterAs, data);
            }
        }
Exemple #5
0
        /// <summary>
        /// Processes the importer response
        /// </summary>
        /// <param name="notification">the response of the importer that has accepted the input</param>
        protected override void ProcessResult(TextAcceptanceCallbackParameter notification)
        {
            if (notification.Success)
            {
                StringBuilder bld = builderLocal.Value;
                if (notification.FirstAcceptedCharacter != 0 || notification.AcceptedLength < bld.Length)
                {
                    string text = string.Format(
                        "Possibly incomplete parse! Start-Symbol found at {0}, Length: {1}. Expected Length was: {2}",
                        notification.FirstAcceptedCharacter, notification.AcceptedLength, bld.Length);
                    LogEnvironment.LogDebugEvent(null,
                                                 text,
                                                 (int)LogSeverity.Warning, null);
                    LogParserEvent(notification.SourceData, text, ParserEventSeverity.Warning, notification.Data);
                }

                bld.Clear();
            }
        }
        /// <summary>
        /// Checks whether the given taskProcessor is alive and takes appropriate actions if the processor is corrupted
        /// </summary>
        /// <param name="processor">the processor that is being watched</param>
        protected override void WatchProcessorInstance(ITaskProcessor processor)
        {
            if (DateTime.Now.Subtract(processor.LastActivity).TotalMilliseconds > timeout)
            {
                bool statusFixed = false;
                var  currentTask = processor.Worker.CurrentTask;
                if (UseRestart)
                {
                    try
                    {
                        RestartProcessor(processor, ResetWorker);
                        statusFixed = true;
                    }
                    catch (Exception ex)
                    {
                        LogEnvironment.LogEvent($"Restart of processor has failed: {ex.OutlineException()}", LogSeverity.Error);
                        processor.Zombie();
                    }
                }

                if (!statusFixed && UseKill)
                {
                    try
                    {
                        KillProcessor(processor, ReCreateOnKill);
                        statusFixed = true;
                    }
                    catch (Exception ex)
                    {
                        LogEnvironment.LogEvent($"Kill of processor has failed: {ex.OutlineException()}", LogSeverity.Error);
                        processor.Zombie();
                    }
                }

                HandleFailedTask(currentTask);
                if (!statusFixed)
                {
                    LogEnvironment.LogDebugEvent("Processorstatus could not be fixed. Requesting application-shutdown...", LogSeverity.Error);
                    Critical();
                }
            }
        }
        private static object GetJArrayValue(JArray jay, Type type)
        {
            bool makeArray = false;

            if (type.IsArray)
            {
                type      = type.GetElementType();
                makeArray = true;
            }
            else if (type.IsGenericType)
            {
                type = type.GetGenericArguments()[0];
            }

            var   lit = typeof(List <>).MakeGenericType(type);
            IList li  = (IList)lit.GetConstructor(Type.EmptyTypes).Invoke(null);

            foreach (var item in jay)
            {
                if (item is JObject job)
                {
                    li.Add(GetJObjectValue(job));
                }
                else if (item is JValue jaw)
                {
                    li.Add(jaw.Value);
                }
                else
                {
                    LogEnvironment.LogDebugEvent($"Items is {item.GetType().FullName}", LogSeverity.Warning);
                }
            }

            if (makeArray)
            {
                var arr = Array.CreateInstance(type, li.Count);
                li.CopyTo(arr, 0);
                return(arr);
            }

            return(li);
        }
Exemple #8
0
        /// <summary>
        /// Kills the thread that is used by the processor and starts a new one
        /// </summary>
        /// <param name="processor">the processor on which to stop the worker-thread</param>
        /// <param name="resetWorker">indicates whether to re-set the used worker</param>
        protected void RestartProcessor(ITaskProcessor processor, bool resetWorker)
        {
            LogEnvironment.LogEvent($"Restarting WorkerThread of ParallelTaskProcessor {processor.Parent.Identifier}", LogSeverity.Warning);
            if (!(processor.Worker.CurrentTask?.ExecutingUnsafe ?? false))
            {
                processor.KillThread();
                if (resetWorker)
                {
                    LogEnvironment.LogDebugEvent($"Resetting Worker-Instsance of ParallelTaskProcessor {processor.Parent.Identifier}", LogSeverity.Warning);
                    processor.Worker.Reset();
                }

                processor.StartupThread();
            }
            else
            {
                LogEnvironment.LogDebugEvent($"The WorkerThread of ParallelTaskProcessor {processor.Parent.Identifier} is executing unsafe code. Processor can not be restarted.", LogSeverity.Error);
                throw new InvalidOperationException($"The WorkerThread of ParallelTaskProcessor {processor.Parent.Identifier} is executing unsafe code. Processor can not be restarted.");
            }
        }
Exemple #9
0
        /// <summary>
        /// Enables a client to commit that it recieved the TaskDone event for a specific package
        /// </summary>
        /// <param name="requestingSystem">the identifier of the requesting system</param>
        /// <param name="packageId">the package identifier for that system</param>
        public void CommitTaskDoneRecieved(string requestingSystem, int packageId)
        {
            lock (triggeredEvents)
            {
                LogEnvironment.LogDebugEvent(string.Format(ParallellResources.ParallelServer_CommitTaskDoneRecieved_System__0__confirms_that_TaskDone_of_the_Task__1__was_received_,
                                                           requestingSystem, packageId), LogSeverity.Report);
                var commitedEvent = (from t in triggeredEvents
                                     where
                                     t.Args.Package.RequestingSystem == requestingSystem &&
                                     t.Args.Package.Id == packageId
                                     select t).ToArray();
                if (commitedEvent.Length != 1)
                {
                    LogEnvironment.LogDebugEvent(ParallellResources.ParallelServer_Unable_to_commit_this_event_, LogSeverity.Warning);
                    return;
                }

                triggeredEvents.Remove(commitedEvent[0]);
            }
        }
Exemple #10
0
 /// <summary>
 /// Sets a value for the current record
 /// </summary>
 /// <param name="columnName">the columnName</param>
 /// <param name="value">the value of the column</param>
 protected void SetValueOfColumn(string columnName, object value)
 {
     if (!currentValues.ContainsKey(columnName))
     {
         currentValues.Add(columnName, value);
     }
     else
     {
         if (currentValues[columnName] != null &&
             !currentValues[columnName].Equals(value))
         {
             LogEnvironment.LogDebugEvent(null,
                                          string.Format(
                                              "Overwriting Value of {0}. Old value: {1}, New value: {2}. If this behavior is unexpected, please correct config!",
                                              columnName, currentValues[columnName], value),
                                          (int)LogSeverity.Warning, null);
             currentValues[columnName] = value;
         }
     }
 }
 /// <summary>
 /// Checks for plugins that are currently not loaded
 /// </summary>
 /// <param name="state">ignored</param>
 private void CheckPlugins(object state)
 {
     refresher.Change(Timeout.Infinite, Timeout.Infinite);
     try
     {
         var tmp = LoadPlugins().ToArray();
         LogEnvironment.LogDebugEvent($"{tmp.Length} new PlugIns loaded..", LogSeverity.Report);
     }
     catch (Exception ex)
     {
         LogEnvironment.LogEvent(ex.ToString(), LogSeverity.Error);
     }
     finally
     {
         if (refreshCycle != 0)
         {
             refresher.Change(refreshCycle, refreshCycle);
         }
     }
 }
Exemple #12
0
 /// <summary>
 /// Registers a specific UserInterface - Element on the default Window
 /// </summary>
 /// <param name="userInterface"></param>
 public void RegisterIterface(IUserInterface userInterface)
 {
     LogEnvironment.LogDebugEvent(string.Format("UserInterce is UiTerminator: {0}", userInterface is UiTerminator),
                                  LogSeverity.Report);
     if (!(userInterface is UiTerminator))
     {
         if (subManagers.Count == 0)
         {
             AddUiComponent(userInterface);
         }
         else
         {
             subManagers.Peek().RegisterIterface(userInterface);
         }
     }
     else
     {
         LogEnvironment.LogDebugEvent("Finalizing Layout", LogSeverity.Report);
         subManagers.Pop();
     }
 }
        /// <summary>
        /// Reboots the worker service
        /// </summary>
        protected void RebootService()
        {
            bool success = false;

            while (!success)
            {
                KillService();
                try
                {
                    serviceLink.Start();
                    serviceLink.WaitForStatus(ServiceControllerStatus.Running);
                    success = true;
                }
                catch (Exception ex)
                {
                    LogEnvironment.LogDebugEvent(ex.Message, LogSeverity.Error);
                    serviceLink.Dispose();
                    InitializeService(false);
                }
            }
        }
Exemple #14
0
 /// <summary>
 /// Processes a complete data-block that was transferred through the memory-mapped file
 /// </summary>
 private void ProcessIncoming()
 {
     if (incomingData.Count >= 4)
     {
         incomingData.CopyTo(0, lenBuf, 0, 4);
         var expectedLen = BitConverter.ToInt32(lenBuf, 0) + 4;
         LogEnvironment.LogDebugEvent($"Expected length: {expectedLen}, effective length: {incomingData.Count}", LogSeverity.Report);
         if (incomingData.Count >= expectedLen && expectedLen > 4)
         {
             var s = Encoding.UTF8.GetString(incomingData.Skip(4).Take(expectedLen - 4).ToArray());
             incomingData.RemoveRange(0, expectedLen);
             OnDataReceived(new IncomingDataEventArgs {
                 Data = s
             });
         }
         else if (incomingData.Count >= expectedLen)
         {
             incomingData.RemoveRange(0, expectedLen);
         }
     }
 }
Exemple #15
0
 /// <summary>
 /// Kills the given taskProcessor instance
 /// </summary>
 /// <param name="processor">the processor to kill</param>
 /// <param name="createNew">indicates whether to re-create the processor</param>
 protected void KillProcessor(ITaskProcessor processor, bool createNew)
 {
     LogEnvironment.LogEvent($"Killing a Worker-Thread of ParallelTaskProcessor {processor.Parent.Identifier}. {(!createNew?"Consider restarting the application soon. This action will cause the ParallelTaskProcessor to run with reduced capacity.":"")}", LogSeverity.Warning);
     if (!(processor.Worker.CurrentTask?.ExecutingUnsafe ?? false))
     {
         processor.KillThread();
         processor.Worker.Quit();
         var parent = processor.Parent;
         parent.UnRegisterProcessor(processor);
         if (createNew)
         {
             LogEnvironment.LogDebugEvent($"Creating a new Worker-Thread for ParallelTaskProcessor {processor.Parent.Identifier}", LogSeverity.Warning);
             parent.CreateProcessor(processor.LowestPriority);
         }
     }
     else
     {
         LogEnvironment.LogDebugEvent($"The WorkerThread of ParallelTaskProcessor {processor.Parent.Identifier} is executing unsafe code. Processor can not be killed.", LogSeverity.Error);
         throw new InvalidOperationException($"The WorkerThread of ParallelTaskProcessor {processor.Parent.Identifier} is executing unsafe code. Processor can not be killed.");
     }
 }
        /// <summary>
        /// Stellt die Implementierung für Vorgänge bereit, die Memberwerte festlegen.Von der <see cref="T:System.Dynamic.DynamicObject"/>-Klasse abgeleitete Klassen können diese Methode überschreiben, um dynamisches Verhalten für Vorgänge wie das Festlegen eines Werts für eine Eigenschaft anzugeben.
        /// </summary>
        /// <returns>
        /// true, wenn der Vorgang erfolgreich ist, andernfalls false.Wenn die Methode false zurückgibt, wird das Verhalten vom Laufzeitbinder der Sprache bestimmt.(In den meisten Fällen wird eine sprachspezifische Laufzeitausnahme ausgelöst.)
        /// </returns>
        /// <param name="binder">Stellt Informationen zum Objekt bereit, das den dynamischen Vorgang aufgerufen hat.Die binder.Name-Eigenschaft gibt den Namen des Members an, dem der Wert zugewiesen wird.Für die Anweisung sampleObject.SampleProperty = "Test", in der sampleObject eine von der <see cref="T:System.Dynamic.DynamicObject"/>-Klasse abgeleitete Instanz der Klasse ist, gibt binder.Name z. B. "SampleProperty" zurück.Die binder.IgnoreCase-Eigenschaft gibt an, ob der Membername die Groß-/Kleinschreibung berücksichtigt.</param><param name="value">Der Wert, der auf den Member festgelegt werden soll.Für die sampleObject.SampleProperty = "Test"-Anweisung, in der sampleObject eine von der <see cref="T:System.Dynamic.DynamicObject"/>-Klasse abgeleitete Instanz der Klasse ist, ist <paramref name="value"/> z. B. "Test".</param>
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            try
            {
                if (!events.ContainsKey(binder.Name))
                {
                    client.SetProperty(objectName, binder.Name, emptyIndex, value);
                }
                else
                {
                    SetEvent(binder.Name, (Delegate)value);
                }
            }
            catch (Exception ex)
            {
                LogEnvironment.LogDebugEvent(ex.ToString(), LogSeverity.Error);
                throw;
            }

            return(true);
        }
        /// <summary>
        /// Kills the service with the configured name
        /// </summary>
        private void KillService()
        {
            string query = string.Format(
                "SELECT ProcessId FROM Win32_Service WHERE Name='{0}'",
                serviceName);
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(query);

            foreach (ManagementObject obj in searcher.Get())
            {
                uint    processId = (uint)obj["ProcessId"];
                Process process   = null;
                try
                {
                    process = Process.GetProcessById((int)processId);
                }
                catch (ArgumentException)
                {
                    LogEnvironment.LogDebugEvent(@"the process specified by processId
is no longer running.", LogSeverity.Warning);
                }
                try
                {
                    if (process != null)
                    {
                        process.Kill();
                    }
                }
                catch (Win32Exception)
                {
                    LogEnvironment.LogDebugEvent(@"process is already terminating,
the process is a Win16 exe or the process
could not be terminated.", LogSeverity.Warning);
                }
                catch (InvalidOperationException)
                {
                    LogEnvironment.LogDebugEvent("The process has probably already terminated.", LogSeverity.Warning);
                }
            }
        }
        public void Dispose()
        {
            if (!disposed)
            {
                lock (messageSync)
                {
                    if (openReadWait != null)
                    {
                        var t = openReadWait;
                        openReadWait = null;
                        t.SetCanceled();
                        //Monitor.Wait(messageSync);
                    }
                }

                while (messageQueue.TryDequeue(out var msg))
                {
                    LogEnvironment.LogDebugEvent($"{msg.OperationId} broken", LogSeverity.Warning);
                }
                disposed = true;
            }
        }
        /// <summary>
        /// Stellt die Implementierung für Vorgänge bereit, die Memberwerte abrufen.Von der <see cref="T:System.Dynamic.DynamicObject"/>-Klasse abgeleitete Klassen können diese Methode überschreiben, um dynamisches Verhalten für Vorgänge wie das Abrufen eines Werts für eine Eigenschaft anzugeben.
        /// </summary>
        /// <returns>
        /// true, wenn der Vorgang erfolgreich ist, andernfalls false.Wenn die Methode false zurückgibt, wird das Verhalten vom Laufzeitbinder der Sprache bestimmt.(In den meisten Fällen wird eine Laufzeitausnahme ausgelöst.)
        /// </returns>
        /// <param name="binder">Stellt Informationen zum Objekt bereit, das den dynamischen Vorgang aufgerufen hat.Die binder.Name-Eigenschaft gibt den Namen des Members an, für den der dynamische Vorgang ausgeführt wird.Für die Console.WriteLine(sampleObject.SampleProperty)-Anweisung, in der sampleObject eine von der <see cref="T:System.Dynamic.DynamicObject"/>-Klasse abgeleitete Instanz der Klasse ist, gibt binder.Name z. B. "SampleProperty" zurück.Die binder.IgnoreCase-Eigenschaft gibt an, ob der Membername die Groß-/Kleinschreibung berücksichtigt.</param><param name="result">Das Ergebnis des get-Vorgangs.Wenn die Methode z. B. für eine Eigenschaft aufgerufen wird, können Sie <paramref name="result"/> den Eigenschaftswert zuweisen.</param>
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            try
            {
                if (!events.ContainsKey(binder.Name))
                {
                    result = this[binder.Name];
                }
                else
                {
                    result = GetEvent(binder.Name);
                }
            }
            catch (Exception ex)
            {
                result = null;
                LogEnvironment.LogDebugEvent(ex.ToString(), LogSeverity.Error);
                throw;
            }

            return(true);
        }
Exemple #20
0
        /// <summary>
        /// Runs a single command without returning the result
        /// </summary>
        /// <param name="command">the command to execute</param>
        /// <param name="parameters">the parameters for the command</param>
        public void RunCommand(string command, Dictionary <string, object> parameters)
        {
            using (var pip = runspace.CreatePipeline())
            {
                var cmd       = new Command(command);
                var arguments = (from t in parameters select new CommandParameter(t.Key, t.Value)).ToArray();
                foreach (var commandParameter in arguments)
                {
                    cmd.Parameters.Add(commandParameter);
                }

                pip.Commands.Add(cmd);
                var results = pip.Invoke();
                //var errors = pip.Error.Read();
                if (GetPipeErrors <object>(pip, results, out var x))
                {
                    throw x;
                }

                LogEnvironment.LogDebugEvent(null, $"PS:{command}->{results}", (int)LogSeverity.Report, null);
            }
        }
Exemple #21
0
        /// <summary>
        /// Enables a derived class to take further actions after a process was killed
        /// </summary>
        /// <param name="status">the process-status containing information about the killed process</param>
        protected override void ProcessKilled(ProcessStatus status)
        {
            base.ProcessKilled(status);
            var meta = status.MetaData <WindowsServiceMetaData>();

            if (meta != null)
            {
                if (!meta.RegularShutdown)
                {
                    var service = ServiceController.GetServices(meta.MachineName).First(n => n.ServiceName.Equals(meta.ServiceName, StringComparison.OrdinalIgnoreCase));
                    service.Refresh();
                    if (service.Status != ServiceControllerStatus.Stopped)
                    {
                        LogEnvironment.LogEvent($"The service {meta.ServiceName} is not in the stopped status. waiting another 5 seconds for the Servicemanager to detect the service-crash...", LogSeverity.Warning);
                        service.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 0, 5));
                        service.Refresh();
                    }

                    if (service.Status == ServiceControllerStatus.Stopped)
                    {
                        service.Start();
                        service.WaitForStatus(ServiceControllerStatus.Running);
                    }
                    else
                    {
                        LogEnvironment.LogEvent($"Unable to start Service {meta.ServiceName}. The service has the status {service.Status}", LogSeverity.Error);
                    }
                }
                else
                {
                    LogEnvironment.LogDebugEvent($"The Service {meta.ServiceName} has registered a legit shutdown. No further action required.", LogSeverity.Report);
                }
            }
            else
            {
                LogEnvironment.LogEvent($"The given process ({status.ProcessName}) contains no service-information..", LogSeverity.Warning);
            }
        }
        /// <summary>
        /// parses the constructorparameter string for a LogAdapter
        /// </summary>
        /// <param name="constructor">the constructorparameter string</param>
        /// <param name="formatProvider">a Plugin-instance that is capable for formatting custom strings (i.e. decrypting passwords, or buffering sql-server instance names)</param>
        /// <returns>an object array containing the parsed objects</returns>
        private static PluginParameterElement[] ParseConstructor(string constructor, IStringFormatProvider formatProvider)
        {
            List <PluginParameterElement> ls = new List <PluginParameterElement>();
            List <string> strings            = new List <string>();

            if (constructor != string.Empty)
            {
                constructor = StringRecognizer.Replace(constructor, (m) =>
                {
                    int id  = strings.Count;
                    var tmp = Unescape(m.Groups["string"].Value);
                    if (m.Groups["formatIndicator"].Value == "$" && formatProvider != null)
                    {
                        LogEnvironment.LogDebugEvent($"Resolving {tmp} using {formatProvider}...", LogSeverity.Report);
                        tmp = formatProvider.ProcessLiteral(tmp);
                        LogEnvironment.LogDebugEvent($"Resulted to {tmp}", LogSeverity.Report);
                    }

                    strings.Add(tmp);
                    return(string.Format("#STRING##{0}##", id));
                });
                string[] args = constructor.Split(new[] { "," }, StringSplitOptions.None);
                foreach (string arg in args)
                {
                    if (!arg.StartsWith("#"))
                    {
                        AddConstructorVal(arg.ToUpper()[0], arg.Substring(1), ls);
                    }
                    else
                    {
                        string tmpValue = strings[int.Parse(arg.Substring(9, arg.Length - 11))];
                        AddConstructorVal((!tmpValue.StartsWith("^^")) ? 'S' : 'O', tmpValue, ls);
                    }
                }
            }

            return(ls.ToArray());
        }
Exemple #23
0
        /// <summary>
        /// Runs a Powershell command with the given arguments
        /// </summary>
        /// <typeparam name="T">the exepected result-type of the command</typeparam>
        /// <param name="command">the command to run</param>
        /// <param name="arguments">the run-arguments</param>
        /// <returns>the result converted to the given type</returns>
        public T RunCommand <T>(string command, Dictionary <string, object> arguments)
        {
            using (var pip = runspace.CreatePipeline())
            {
                var cmd        = new Command(command);
                var parameters = (from t in arguments select new CommandParameter(t.Key, t.Value)).ToArray();
                foreach (var commandParameter in parameters)
                {
                    cmd.Parameters.Add(commandParameter);
                }

                pip.Commands.Add(cmd);
                var results = pip.Invoke();
                LogEnvironment.LogDebugEvent(null, $"Received {results.Count} results.", (int)LogSeverity.Report, null);
                LogEnvironment.LogDebugEvent(null, $"Output from Powershell-Command: {pip.Output.ReadToEnd()}", (int)LogSeverity.Report, null);
                if (GetPipeErrors <T>(pip, results, out var x))
                {
                    throw x;
                }

                return(TryGetList <T>(results).FirstOrDefault());
            }
        }
        /// <summary>
        /// Creates a Parameter on the Service
        /// </summary>
        /// <param name="sessionId">the id of the current session</param>
        /// <param name="name">the desired name of the parameter</param>
        /// <param name="value">the value of the parameter</param>
        /// <param name="typeName">the typename of structured types</param>
        /// <returns>a Parameter that represents the desired value</returns>
        public IDbDataParameter CreateParameter(long sessionId, string name, object value, string typeName)
        {
            LogEnvironment.LogDebugEvent(null, "Entering CreateParameter", (int)LogSeverity.Report, null);
            LogEnvironment.LogDebugEvent(null, "Looking up session", (int)LogSeverity.Report, null);
            ConnectionHandle conn = GetSession(sessionId);

            LogEnvironment.LogDebugEvent(null, string.Format("session==null:{0}", conn == null), (int)LogSeverity.Report, null);
            long objectId = NextObjectId();

            LogEnvironment.LogDebugEvent(null, string.Format("ObjectId: {0}", objectId), (int)LogSeverity.Report, null);
            IDbDataParameter param = conn.Connection.GetParameter(name, value, typeName);

            LogEnvironment.LogDebugEvent(null, string.Format("Param.Name: {0}", param.ParameterName), (int)LogSeverity.Report, null);
            lock (parameters)
            {
                LogEnvironment.LogDebugEvent(null, "Addin Parameter", (int)LogSeverity.Report, null);
                parameters.Add(objectId, param);
                LogEnvironment.LogDebugEvent(null, "Ok", (int)LogSeverity.Report, null);
            }

            LogEnvironment.LogDebugEvent(null, "About to return!", (int)LogSeverity.Report, null);
            return(new RemoteDataParameter(param, objectId));
        }
Exemple #25
0
        /// <summary>
        /// Wraps the given IndexFile and all provided files into a wrapper file
        /// </summary>
        /// <param name="map">the FileMap used to map the files from FileSystem to the archive file</param>
        /// <param name="wrappedName">the name of the taret wrapper-file</param>
        /// <param name="password">the password that is used for encryption</param>
        public void WrapFiles(FileMap map, string wrappedName, string password)
        {
            using (FileStream fst = new FileStream(wrappedName, FileMode.Create, FileAccess.ReadWrite))
            {
                using (ZipOutputStream zos = new ZipOutputStream(fst))
                {
                    if (password != null)
                    {
                        zos.Password = password;
                    }

                    zos.SetLevel(compressionLevel);
                    ZipEntryFactory fac = new ZipEntryFactory {
                        IsUnicodeText = true
                    };
                    LogEnvironment.LogDebugEvent(null, (from t in map
                                                        select
                                                        WriteEntry(t,
                                                                   fac.MakeFileEntry(t.LocationInFileSystem, t.ArchiveFileName, true),
                                                                   zos, password != null ? 256 : 0)).Count().ToString(), (int)LogSeverity.Report, null);
                }
            }
        }
        /// <summary>
        /// Reads a formattable resource and deserializes it to an object using a json-deserializer
        /// </summary>
        /// <typeparam name="T">the target-type</typeparam>
        /// <param name="localizer">the localizer instance</param>
        /// <param name="name">the name of the resource</param>
        /// <param name="arguments">string-format arguments. If the type implements IFormattableLocalizationObject, the resource does not have to be formatted to be used with string-format</param>
        /// <returns>an instance of the requested type.</returns>
        public static T FromJson <T>(this IStringLocalizer localizer, string name, params object[] arguments) where T : class, new()
        {
            var isformattable = typeof(IFormattableLocalizationObject).IsAssignableFrom(typeof(T));
            var raw           = !isformattable ? localizer[name, arguments] : localizer[name];

            try
            {
                T retVal = JsonHelper.FromJsonString <T>(raw);
                if (isformattable && retVal is IFormattableLocalizationObject flo)
                {
                    flo.FormatProperties(arguments);
                }

                return(retVal);
            }
            catch (Exception ex)
            {
                LogEnvironment.LogDebugEvent($"Error translating value to object: {ex.Message}", LogSeverity.Error);
            }



            return(new T());
        }
Exemple #27
0
        /// <summary>
        /// Adds the instruction to the list of schedule-instructions and sets the remarks if requested
        /// </summary>
        /// <param name="instruction">the instruction that is used for this schedule-request</param>
        /// <param name="setRemarks">indicates whether to use the default-remarks</param>
        protected override void AddInstruction(string instruction, bool setRemarks)
        {
            bool setBaseRemarks = setRemarks;

            if (parent != null)
            {
                if (!string.IsNullOrEmpty(instruction))
                {
                    TimeTable tmp = parent.GetTimeTable(instruction);
                    DateTime? nx  = tmp.GetNextExecutionTime(LastExecution);
                    if (nx != null &&
                        (NextExecution == null || nx.Value < NextExecution.Value || NextExecution.Value == DateTime.MinValue))
                    {
                        LogEnvironment.LogDebugEvent(string.Format("Next Execution: {0:dd.MM.yyyy HH:mm:ss}", nx.Value),
                                                     LogSeverity.Report);
                        //LogEnvironment.LogEvent(new StackTrace().ToString(), LogSeverity.Report);
                        NextExecution = nx.Value;
                        if (setRemarks)
                        {
                            Remarks        = string.Format("Next Execution: {0:dd.MM.yyyy HH:mm:ss}", NextExecution);
                            setBaseRemarks = false;
                        }
                    }
                }
                else
                {
                    LogEnvironment.LogEvent($"Ignored empty Scheduler instruction...", LogSeverity.Warning);
                }

                base.AddInstruction(instruction, setBaseRemarks);
            }
            else
            {
                deferredInstructions.Add(instruction);
            }
        }
Exemple #28
0
        /// <summary>
        /// Monitors the active connections and disposeds abandoned ones
        /// </summary>
        /// <param name="state">unused argument</param>
        private void MonitorConnections(object state)
        {
            timer.Change(Timeout.Infinite, Timeout.Infinite);
            Thread.CurrentThread.Name = state.ToString();
            try
            {
                List <DatabaseContainer> abandonedConnections = new List <DatabaseContainer>();
                DateTime now = DateTime.Now;
                lock (connections)
                {
                    LogEnvironment.LogDebugEvent(null, string.Format("Current Connectioncount: {0}", connections.Count), (int)LogSeverity.Report, "DataAccess");
                    foreach (DatabaseContainer item in connections)
                    {
                        if (!item.InUse &&
                            now.Subtract(item.LastUsage).TotalMinutes > AbandonTimeoutMinutes)
                        {
                            abandonedConnections.Add(item);
                        }
                    }

                    foreach (DatabaseContainer item in abandonedConnections)
                    {
                        item.Database.Dispose();
                        item.Disposed = true;
                        connections.Remove(item);
                        LogEnvironment.LogDebugEvent(null, DataAccessResources.ParallelAbandonMessage, (int)LogSeverity.Report, "DataAccess");
                    }

                    LogEnvironment.LogDebugEvent(null, string.Format("New Connectioncount: {0}", connections.Count), (int)LogSeverity.Report, "DataAccess");
                }
            }
            finally
            {
                timer.Change(600000, 600000);
            }
        }
Exemple #29
0
        /// <summary>
        /// Tests the received message and returns it, if its the expected type or throws an exception otherwise
        /// </summary>
        /// <typeparam name="TExpectedType">the expected incoming type</typeparam>
        /// <param name="message">the received message</param>
        /// <returns>the parsed message</returns>
        private async Task <TExpectedType> TestMessage <TExpectedType>(Task <string> msgFunc) where TExpectedType : class
        {
            object tmp     = null;
            string message = null;

            try
            {
                message = await msgFunc;
                tmp     = JsonHelper.FromJsonStringStrongTyped <object>(message, true);
                var ret = tmp as TExpectedType;
                if (tmp != null && ret != null)
                {
                    return(ret);
                }
            }
            catch (Exception exx)
            {
                LogEnvironment.LogDebugEvent(null, $"Error processing message: {exx.OutlineException()}",
                                             (int)LogSeverity.Error, "ITVComponents.IPC.MS.MessageClient");
                tmp = exx;
            }

            if (tmp is SerializedException ex)
            {
                CheckConnected(ex);
                throw new InterProcessException("Server-Operation failed!", ex);
            }

            if (tmp is Exception inex)
            {
                CheckConnected(inex);
                throw new InterProcessException("Server-Operation failed!", inex);
            }

            throw new InterProcessException($"Unexpected Response: {message}", null);
        }
Exemple #30
0
        /// <summary>
        /// Writes data into the memory-mapped file and blocks until the data was processed by the server or a timeout occurs
        /// </summary>
        /// <param name="data">the data to transmit to the target-endpoint</param>
        /// <param name="cancellationToken">the cancellation token to control the inner async method executions</param>
        public async Task WriteAsync(string data, CancellationToken cancellationToken)
        {
            mux.WaitOne();
            LogEnvironment.LogDebugEvent("Starting Write...", LogSeverity.Report);
            try
            {
                var tmp = Encoding.UTF8.GetBytes(data);
                var len = tmp.Length;
                tmp = BitConverter.GetBytes(len).Concat(tmp).ToArray();
                var id = 0;
                var ln = 0;
                while (id < tmp.Length && !cancellationToken.IsCancellationRequested)
                {
                    ln = tmp.Length - id > bufferSize - sizeof(int) ? bufferSize - sizeof(int) : tmp.Length - id;
                    cmux.WaitOne();
                    try
                    {
                        var dat = BitConverter.GetBytes(ln).Concat(tmp.Skip(id).Take(ln)).ToArray();
                        mvs.Seek(0, SeekOrigin.Begin);
                        await mvs.WriteAsync(dat, 0, dat.Length, cancellationToken);

                        int ok       = -1;
                        int attempts = 0;
                        while (ok != 0 && !cancellationToken.IsCancellationRequested)
                        {
                            cmux.WaitOne();
                            mvs.Seek(0, SeekOrigin.Begin);
                            await mvs.ReadAsync(lenBuf, 0, 4, cancellationToken);

                            ok = BitConverter.ToInt32(lenBuf, 0);
                            if (ok != 0)
                            {
                                attempts++;
                                if (attempts == 15)
                                {
                                    forEverClosed.WaitOne(600);
                                }
                                else
                                {
                                    forEverClosed.WaitOne(20);
                                }

                                if (attempts > 30)
                                {
                                    mvs.Seek(0, SeekOrigin.Begin);
                                    await mvs.WriteAsync(zero, 0, 4, cancellationToken);

                                    throw new CommunicationException("Nobody listening!");
                                }
                            }
                        }
                    }
                    finally
                    {
                        cmux.Pulse();
                    }

                    id += ln;
                }
            }
            finally
            {
                LogEnvironment.LogDebugEvent("Write done.", LogSeverity.Report);
                mux.Pulse();
            }
        }