public static TInterface Resolve <TInterface>()
            where TInterface : class
        {
            var type = typeof(TInterface);
            var id   = GetTypeId(type);

            lock (internals)
            {
                object   obj;
                IFactory factory;
                if (services.ContainsKey(id) && (obj = services[id]) != null)
                {
                    return((TInterface)services[id]);
                }
                else if (factories.ContainsKey(id) && (factory = factories[id]) != null)
                {
                    var instance = factory.Create();
                    if (!(factory is FactoryFactoryService))
                    {
                        services[id] = instance;
                    }
                    TraceEx.Info("ApplicationServices", "Created instance of " + (instance != null ? instance.ToString() : id.ToString()));
                    return((TInterface)instance);
                }
            }

            return(null);
        }
        private async Task <BuildContentOutput> DoBuildContentForBuildRequestAsync(BuildRequest buildRequest)
        {
            Message message = buildRequest.SharedObject.GetValue <Message>(Constants.BuildMessage);

            // add message priority into AmbientContext
            SetMessagePriorityInAmbientContext(message);

            TraceEx.TraceInformation(
                string.Format(
                    "Build content for request Action: {0}, EntityIdentifier: {1}, Message: {2}",
                    buildRequest.ActionName,
                    buildRequest.EntityIdentifier,
                    Utility.ToJsonString(message)));

            string pipelineName = BuildActionMapper.GetPipelineName(buildRequest.ActionName);

            if (string.IsNullOrEmpty(pipelineName))
            {
                string errorMessage = LogMessage.FormatMessage(LogCode.PipelineForActionNotFound, buildRequest.ActionName);
                TraceEx.TraceError(errorMessage);
                throw new ArgumentException(errorMessage);
            }

            BuildEngine  engine;
            BuildContext context;

            using (new PerformanceScopeWrapper(
                       "Setup Context",
                       PerformanceCategory.Pipeline))
            {
                string reportPipelineName = GetReportPipelineName(buildRequest.ActionName, message.MessageType);
                engine  = BuildEngineFactory.CreateEngineByPipelineName(reportPipelineName);
                context = engine.Context;

                context.XmlContext.AddVariable(Constants.ContextData.PipelineName, pipelineName);
                await SetupContextAsync(context, buildRequest);

                context.SetSharedObject(Constants.ContextData.PipelineStartTime, DateTime.UtcNow);
            }

            PipelineResult result = PipelineResult.Break;

            using (new PerformanceScopeWrapper(
                       string.Format("Setup Pipeline: {0}", buildRequest.ActionName),
                       PerformanceCategory.Pipeline))
            {
                engine.Pipeline.Setup(context);
            }

            XmlDocument document = new XmlDocument();

            result = await engine.Pipeline.ApplyAsync(document, context);

            return(new BuildContentOutput
            {
                BuildContentResult = result == PipelineResult.NeedRerun ? BuildContentResult.NeedRerun : BuildContentResult.Succeeded,
                Outputs = context.Outputs
            });
        }
Ejemplo n.º 3
0
        public static async Task <bool> CompleteTaskWithinTimeOutAsync(Task task, int timeoutInSeconds, string taskDescription, Func <Exception> exceptionGeneratorOnTimeout)
        {
            Guard.ArgumentNotNull(task, nameof(task));
            Guard.ArgumentNotNull(exceptionGeneratorOnTimeout, nameof(exceptionGeneratorOnTimeout));

            if (timeoutInSeconds <= 0 || await RunTaskWithTimeoutAsync(task, TimeSpan.FromSeconds(timeoutInSeconds), taskDescription))
            {
                await task;
                return(true);
            }

            TraceEx.TraceError($"{taskDescription} timeout in {timeoutInSeconds} seconds.");
            throw exceptionGeneratorOnTimeout();
        }
Ejemplo n.º 4
0
        public static async void RunTaskSilentlyNoWait(Task task, [CallerMemberName] string taskDescription = null)
        {
            Guard.ArgumentNotNull(task, nameof(task));

            try
            {
                await task;
                TraceEx.TraceInformation($"{taskDescription} succeeded.");
            }
            catch (Exception ex)
            {
                TraceEx.TraceError($"{taskDescription} failed: {ex}");
            }
        }
 private EngineExecutor()
 {
     try
     {
         // environment variable to be used in the pipeline transform component
         Environment.SetEnvironmentVariable(Constants.BuildSetupFilePath, CommonServiceConfiguration.BuildSetupFilesUrl);
         Environment.SetEnvironmentVariable(Constants.ExecutableDir, CommonServiceConfiguration.ExecutableDir);
     }
     catch (Exception e)
     {
         TraceEx.TraceError(LogMessage.FormatMessage(LogCode.EngineExecutorInitError, e.Message));
         throw;
     }
 }
Ejemplo n.º 6
0
        public static void ForceDeleteFile(string filePath)
        {
            Guard.ArgumentNotNullOrEmpty(filePath, nameof(filePath));

            try
            {
                File.SetAttributes(filePath, FileAttributes.Normal);
                File.Delete(filePath);
            }
            catch (Exception ex)
            {
                TraceEx.TraceWarning($"Delete File {filePath} failed.", ex);
            }
        }
 public static Task Run(Action function)
 {
     return(Task.Run(() =>
     {
         try
         {
             function();
         }
         catch (Exception ex)
         {
             TraceEx.TraceException(ex);
             //Dispatch your MessageBox etc.
         }
     }));
 }
        /// <summary>
        /// Unregisters a service with from specified interface type.
        /// </summary>
        /// <typeparam name="TInterface">The type of the interface.</typeparam>
        public static void Unregister <TInterface>()
            where TInterface : class
        {
            var type = typeof(TInterface);
            var id   = type.GUID;

            lock (internals)
            {
                if (services.ContainsKey(id))
                {
                    services.Remove(id);
                    TraceEx.Info("ApplicationServices", "Removed instance for " + type.Name);
                }
            }
        }
        /// <summary>
        /// Drops the instance of a service registered with the TInterface type (does not call <see cref="IDisposable.Dispose"/>).
        /// Does not unregister the factory (the object will be recreated if resolved).
        /// </summary>
        public static void DropInstance <TInterface>()
            where TInterface : class
        {
            var type = typeof(TInterface);
            var id   = GetTypeId(type);

            lock (internals)
            {
                if (services.ContainsKey(id))
                {
                    var instance = services[id];
                    services[id] = null;
                    TraceEx.Info("ApplicationServices", "Removed instance of " + (instance != null ? instance.ToString() : id.ToString()));
                }
            }
        }
        /// <summary>
        /// Registers a service with a specified interface type.
        /// The service is automatically instanciated on the first call to it using the default constructor.
        /// </summary>
        /// <typeparam name="TInterface">The resolving type (interface).</typeparam>
        /// <typeparam name="TImplementation">The type of the implementation.</typeparam>
        /// <exception cref="ArgumentException">If service or factory already exists</exception>
        public static void Register <TInterface, TImplementation>()
            where TInterface : class
            where TImplementation : class, TInterface, new()
        {
            var type     = typeof(TInterface);
            var implType = typeof(TImplementation);
            var id       = GetTypeId(type);

            lock (internals)
            {
                ThrowIfRegisteredOrInstanciated(type, id);

                factories.Add(id, new LazyEmptyService(implType));
                TraceEx.Info("ApplicationServices", "Registered factory for " + type.Name);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 根据指定的 XML 和 SQL 名称获取参数的Mapping 配置信息。
        /// </summary>
        /// <param name="xmlFileName"></param>
        /// <param name="sqlName"></param>
        /// <returns></returns>
        public MB.Orm.Mapping.QueryParameterMappings GetSqlQueryParamMappings(string xmlFileName, string sqlName)
        {
            System.Xml.XmlNode sqlNode = getSqlNode(xmlFileName, sqlName);
            if (sqlNode == null || sqlNode.ChildNodes.Count == 0)
            {
                TraceEx.Write("在XML 文件:" + xmlFileName + " 中获取相应SQL 语句:" + sqlName + "出错,请检查资源文件或者对应SQL 语句是否存在!");
                return(null);
            }
            MB.Orm.Mapping.QueryParameterMappings mappings = null;
            foreach (System.Xml.XmlNode paramMappingNode in sqlNode.ChildNodes)
            {
                if (paramMappingNode.NodeType != System.Xml.XmlNodeType.Element)
                {
                    continue;
                }
                if (string.Compare(paramMappingNode.Name, XML_PARAM_MAPPINGS, true) != 0)
                {
                    continue;
                }

                mappings = new QueryParameterMappings();
                if (paramMappingNode.Attributes["DefaultTableAlias"] != null)
                {
                    mappings.DefaultTableAlias = paramMappingNode.Attributes["DefaultTableAlias"].Value;
                }

                foreach (System.Xml.XmlNode node in paramMappingNode.ChildNodes)
                {
                    if (node.NodeType != System.Xml.XmlNodeType.Element)
                    {
                        continue;
                    }
                    if (string.Compare(node.Name, "Mapping", true) != 0)
                    {
                        continue;
                    }
                    if (node.Attributes["Name"] == null || node.Attributes["DbFieldName"] == null)
                    {
                        throw new MB.Util.APPException(string.Format("XML配置文件{0},配置QueryParamMappings 是可能没有配置 Name 或者 DbFieldName!", xmlFileName));
                    }

                    mappings.Add(new QueryParameterMappingInfo(node.Attributes["Name"].Value, node.Attributes["DbFieldName"].Value));
                }
                break;
            }
            return(mappings);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 获取指定的SQL 字符窜。
        /// </summary>
        /// <param name="xmlFileName"></param>
        /// <param name="sqlName"></param>
        /// <returns></returns>
        public MB.Orm.DbSql.SqlString[]  GetSqlString(string xmlFileName, string sqlName)
        {
            // string xmlFileFullName = XML_FILE_PATH + xmlFileName + ".xml";
            //统一在方法 getSqlNode 进行判断
            //if (!System.IO.File.Exists(xmlFileFullName))
            //    throw new MB.Util.APPException(string.Format("XML配置文件{0},不存在!", xmlFileFullName), MB.Util.APPMessageType.SysErrInfo);

            System.Xml.XmlNode sqlNode = getSqlNode(xmlFileName, sqlName);
            if (sqlNode == null || sqlNode.ChildNodes.Count == 0)
            {
                TraceEx.Write("在XML 文件:" + xmlFileName + " 中获取相应SQL 语句:" + sqlName + "出错,请检查资源文件或者对应SQL 语句是否存在!");
                return(null);
            }
            List <MB.Orm.DbSql.SqlString> sqlStrings = new List <SqlString>();

            foreach (System.Xml.XmlNode sqlStringNode in sqlNode.ChildNodes)
            {
                if (sqlStringNode.NodeType != System.Xml.XmlNodeType.Element)
                {
                    continue;
                }
                if (string.Compare(sqlStringNode.Name, XML_SQL_STRING_NAME, true) != 0)
                {
                    continue;
                }

                string str = string.Empty;
                foreach (System.Xml.XmlNode node in sqlStringNode.ChildNodes)
                {
                    if (node.NodeType != System.Xml.XmlNodeType.Element)
                    {
                        continue;
                    }
                    if (string.Compare(node.Name, XML_SQL_STRING_TEXT_NAME, true) != 0)
                    {
                        continue;
                    }
                    TraceEx.Write("成功发现SQL 语句:" + sqlName);
                    str = formatSqlString(node.InnerText.Trim());
                    break;
                }
                List <SqlParamInfo>    pars   = getSqlParams(sqlStringNode);
                MB.Orm.DbSql.SqlString sqlStr = new MB.Orm.DbSql.SqlString(str, pars);
                sqlStrings.Add(sqlStr);
            }
            return(sqlStrings.ToArray());
        }
Ejemplo n.º 13
0
        // The same behavior as "RunTaskSilentlyNoWait".
        // but it is bad because it returns Task,
        // and the caller has chance to wait "RunTaskSilentlyNoWaitBad" to complete.
        public static async Task RunTaskSilentlyNoWaitBad(Task task, string taskDescription = null)
        {
            Guard.ArgumentNotNull(task, nameof(task));

            try
            {
                Console.WriteLine(task.Status + ": RunTaskSilentlyNoWait1");
                await task;
                Console.WriteLine(task.Status + " : RunTaskSilentlyNoWait1");
            }
            catch (Exception ex)
            {
                TraceEx.TraceError(taskDescription != null
                    ? $"{taskDescription} failed: {ex}"
                    : $"Running task failed: {ex}");
            }
        }
        /// <summary>
        /// Registers a service with a specified interface type.
        /// The service is automatically instanciated on ALL call to it.
        /// </summary>
        /// <typeparam name="TInterface">The resolving type (interface).</typeparam>
        /// <param name="factory">The factory for the instantiation.</param>
        /// <exception cref="ArgumentException">If service or factory already exists</exception>
        public static void RegisterFactory <TInterface>(Func <TInterface> factory)
            where TInterface : class
        {
            var type = typeof(TInterface);
            var id   = GetTypeId(type);

            lock (internals)
            {
                ThrowIfRegisteredOrInstanciated(type, id);

#if SILVERLIGHT || NETFX_CORE
                factories.Add(id, new FactoryFactoryService(() => factory()));
#else
                factories.Add(id, new FactoryFactoryService(factory));
#endif
                TraceEx.Info("ApplicationServices", "Registered factory for " + type.Name);
            }
        }
Ejemplo n.º 15
0
        // The same as RunTaskSilentlyNoWait.
        public static async void RunTaskSilentlyNoWaitUsingFunc(Func <Task> task, string taskDescription = null)
        {
            Guard.ArgumentNotNull(task, nameof(task));

            try
            {
                Task t = task();
                Console.WriteLine(t.Status);
                await t;
                Console.WriteLine(t.Status);
            }
            catch (Exception ex)
            {
                TraceEx.TraceError(taskDescription != null
                    ? $"{taskDescription} failed: {ex}"
                    : $"Running task failed: {ex}");
            }
        }
        /// <summary>
        /// Registers the a service with a specified interface type.
        /// The service is automatically instanciated on the first call to it.
        /// </summary>
        /// <typeparam name="TInterface">The type of the interface.</typeparam>
        /// <typeparam name="TImplementation">The type of the implementation.</typeparam>
        /// <param name="service">The reference to the service instance.</param>
        public static void Register <TInterface, TImplementation>()
            where TInterface : class
            where TImplementation : class, TInterface, new()
        {
            var type     = typeof(TInterface);
            var implType = typeof(TImplementation);
            var id       = type.GUID;

            lock (internals)
            {
                if (services.ContainsKey(id))
                {
                    throw new ArgumentException("Service of type '" + type.Name + "' is already registered");
                }

                services.Add(id, new LazyEmptyService(implType));
                TraceEx.Info("ApplicationServices", "Registered implementation for " + type.Name);
            }
        }
        /// <summary>
        /// Drops an instance of a service with the specified reference (does not call <see cref="IDisposable.Dispose"/>).
        /// Does not unregister the factory (the object will be recreated if resolved).
        /// </summary>
        /// <param name="obj">The object to drop.</param>
        /// <exception cref="ArgumentNullException">if the argument is null</exception>
        public static void DropInstance(object obj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }

            lock (internals)
            {
                foreach (var item in services.ToArray())
                {
                    if (item.Value == obj)
                    {
                        services.Remove(item.Key);
                        TraceEx.Info("ApplicationServices", "Removed instance for " + (item.Value != null ? item.Value.ToString() : item.Key.ToString()));
                    }
                }
            }
        }
Ejemplo n.º 18
0
        public BaseAndroidController() : base()
        {
            //获取访问语言
            Language = GetLanguage();
            HttpRequest httpRequest = HttpContext.Current.Request;
            string      path        = httpRequest.Path;
            string      RawUrl      = httpRequest.RawUrl;

            TraceEx.Write(SysMessageLevel.SysReceiveInfo, string.Format("访问路径:{0}", RawUrl));
            if (!NoTokenUrl.Contains(path.ToLower()))
            {
                tokenModel = CheckAndGetToken();
                HttpContext.Current.Request.Headers.Add("TokenStatus", tokenModel.CheckResult.ToString());
            }
            else
            {
                HttpContext.Current.Request.Headers.Add("TokenStatus", CheckToken_Success.ToString());
            }
        }
        /// <summary>
        /// Registers a service with a specified resolving type and instance.
        /// </summary>
        /// <typeparam name="TImplementation">The resolving type (interface).</typeparam>
        /// <param name="service">The reference to the service instance.</param>
        /// <exception cref="ArgumentException">If service or factory already exists</exception>
        /// <exception cref="ArgumentNullException"></exception>
        public static void Register <TImplementation>(TImplementation service)
            where TImplementation : class
        {
            if (service == null)
            {
                throw new ArgumentNullException("service");
            }

            var type = typeof(TImplementation);
            var id   = GetTypeId(type);

            lock (internals)
            {
                ThrowIfRegisteredOrInstanciated(type, id);

                services.Add(id, service);
                TraceEx.Info("ApplicationServices", "Registered instance for " + type.Name);
            }
        }
        /// <summary>
        /// Clears all instances (and calls <see cref="IDisposable.Dispose"/>).
        /// </summary>
        public static void ClearInstances()
        {
            lock (internals)
            {
                if (services.Count > 0)
                {
                    foreach (var item in services.Values)
                    {
                        var disposable = item as IDisposable;
                        if (disposable != null)
                        {
                            disposable.Dispose();
                        }
                    }
                }

                services.Clear();
                TraceEx.Info("ApplicationServices", "Cleared");
            }
        }
Ejemplo n.º 21
0
        public static async Task RetryAsync(
            Func <CancellationToken, Task> func,
            Func <Exception, bool>[] errorHandlers,
            TimeSpan[] timeouts,
            CancellationToken cancellationToken  = default(CancellationToken),
            [CallerMemberName] string methodName = null,
            [CallerFilePath] string filePath     = null,
            [CallerLineNumber] int lineNumber    = 0)
        {
            Guard.ArgumentNotNull(func, nameof(func));
            ValidateRetryParameters(errorHandlers, timeouts);

            int retryCount = 0;

            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();
                if (retryCount > 0)
                {
                    await Task.Delay(timeouts[retryCount - 1], cancellationToken);
                }
                try
                {
                    await func(cancellationToken);

                    break;
                }
                catch (Exception ex)
                {
                    if (retryCount++ < timeouts.Length)
                    {
                        if (errorHandlers.Any(handler => handler(ex)))
                        {
                            TraceEx.TraceWarning($"Error occurred at method {methodName} in {filePath} line {lineNumber}, current retry count: {retryCount}", ex);
                            continue;
                        }
                    }
                    throw;
                }
            }
        }
        /// <summary>
        /// Registers the a service with a specified interface type.
        /// The service is automatically instanciated on the first call to it.
        /// </summary>
        /// <typeparam name="TInterface">The type of the interface.</typeparam>
        /// <param name="factory">The factory for the instantiation.</param>
        public static void Register <TInterface>(Func <TInterface> factory)
            where TInterface : class
        {
            var type = typeof(TInterface);
            var id   = type.GUID;

            lock (internals)
            {
                if (services.ContainsKey(id))
                {
                    throw new ArgumentException("Service of type '" + type.Name + "' is already registered");
                }

#if SILVERLIGHT
                services.Add(id, new LazyFactoryService(() => factory()));
#else
                services.Add(id, new LazyFactoryService(factory));
#endif
                TraceEx.Info("ApplicationServices", "Registered factory for " + type.Name);
            }
        }
        /// <summary>
        /// Registers the a service with a specified interface type.
        /// </summary>
        /// <typeparam name="TInterface">The type of the interface.</typeparam>
        /// <typeparam name="TImplementation">The type of the implementation.</typeparam>
        /// <param name="service">The reference to the service instance.</param>
        public static void Register <TImplementation>(TImplementation service)
            where TImplementation : class
        {
            if (service == null)
            {
                throw new ArgumentNullException("service");
            }

            var type = typeof(TImplementation);
            var id   = type.GUID;

            lock (internals)
            {
                if (services.ContainsKey(id))
                {
                    throw new ArgumentException("Service of type '" + type.Name + "' is already registered");
                }

                services.Add(id, service);
                TraceEx.Info("ApplicationServices", "Registered instance for " + type.Name);
            }
        }
Ejemplo n.º 24
0
        private void Refresh(IReadOnlyDictionary <string, object> config, bool silent)
        {
            object value;

            if (config.TryGetValue(_key, out value))
            {
                try
                {
                    T typedValue = _converter != null?_converter(value) : (T)value;

                    if (!object.Equals(Value, typedValue))
                    {
                        TraceEx.TraceInformation(string.Format("Configuration '{0}' is changed from '{1}' to '{2}'.", _key, Value, typedValue));
                        Value = typedValue;
                        if (OnChanged != null)
                        {
                            OnChanged();
                        }
                    }
                }
                catch (InvalidCastException)
                {
                    TraceEx.TraceWarning(string.Format("Cannot cast value '{0}' to type '{1}', original value is kept.", value, typeof(T)));
                    if (!silent)
                    {
                        throw;
                    }
                }
            }
            else
            {
                TraceEx.TraceWarning(string.Format("Cannot find configuration '{0}', original value is kept.", _key));
                if (!silent)
                {
                    throw new KeyNotFoundException(string.Format("Cannot find configuration '{0}'", _key));
                }
            }
        }
Ejemplo n.º 25
0
        public static void Retry(
            Action action,
            Func <Exception, bool>[] errorHandlers,
            TimeSpan[] retryIntervals,
            [CallerMemberName] string methodName = null,
            [CallerFilePath] string filePath     = null,
            [CallerLineNumber] int lineNumber    = 0)
        {
            Guard.ArgumentNotNull(action, nameof(action));
            ValidateRetryParameters(errorHandlers, retryIntervals);

            int retryCount = 0;

            while (true)
            {
                if (retryCount > 0)
                {
                    Thread.Sleep(retryIntervals[retryCount - 1]);
                }
                try
                {
                    action();
                    break;
                }
                catch (Exception ex)
                {
                    if (retryCount++ < retryIntervals.Length)
                    {
                        if (errorHandlers.Any(handler => handler(ex)))
                        {
                            TraceEx.TraceWarning($"Error occurred at method {methodName} in {filePath} line {lineNumber}, current retry count: {retryCount}", ex);
                            continue;
                        }
                    }
                    throw;
                }
            }
        }
Ejemplo n.º 26
0
        public static void ForceDeleteDirectoryWithAllSubDirectories(string directory, int maxDegreeOfParallelism = -1)
        {
            Guard.ArgumentNotNullOrEmpty(directory, nameof(directory));

            if (Directory.Exists(directory))
            {
                try
                {
                    Directory.Delete(directory, true);
                }
                catch
                {
                    try
                    {
                        ForceDeleteAllSubDirectories(directory, maxDegreeOfParallelism);
                        Directory.Delete(directory, true);
                    }
                    catch (Exception ex)
                    {
                        TraceEx.TraceWarning($"Delete directory {directory} failed.", ex);
                    }
                }
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Execute exe
        /// </summary>
        /// <param name="executionInfo">execution info</param>
        /// <param name="stdoutWriter">stdout stream writer, null to ignore stdout</param>
        /// <param name="stderrWriter">stderr stream writer, null to ignore stderr</param>
        /// <param name="timeoutInMilliseconds">timeout in milliseconds, -1 to wait infinitely</param>
        /// <returns>return value of the exe</returns>
        public static int ExecuteExe(ProcessExecutionInfo executionInfo, StreamWriter stdoutWriter, StreamWriter stderrWriter, int timeoutInMilliseconds = Timeout.Infinite)
        {
            Guard.ArgumentNotNull(executionInfo, nameof(executionInfo));
            Guard.ArgumentNotNullOrEmpty(executionInfo.ExeFilePath, $"{nameof(executionInfo)}.{nameof(executionInfo.ExeFilePath)}");
            if (timeoutInMilliseconds < 0 && timeoutInMilliseconds != Timeout.Infinite)
            {
                throw new ArgumentOutOfRangeException(nameof(timeoutInMilliseconds), $"{nameof(timeoutInMilliseconds)} must be equal to or greater than 0, or equal to {Timeout.Infinite}.");
            }

            using (Process buildProcess = new Process())
            {
                buildProcess.StartInfo.FileName         = Environment.ExpandEnvironmentVariables(executionInfo.ExeFilePath);
                buildProcess.StartInfo.UseShellExecute  = false;
                buildProcess.StartInfo.CreateNoWindow   = true;
                buildProcess.StartInfo.Arguments        = executionInfo.Arguments;
                buildProcess.StartInfo.WorkingDirectory = executionInfo.WorkingDirectory == null ? null : Environment.ExpandEnvironmentVariables(executionInfo.WorkingDirectory);

                // set TEMP/TMP variables
                buildProcess.StartInfo.EnvironmentVariables["TEMP"] = Environment.GetEnvironmentVariable("TEMP");
                buildProcess.StartInfo.EnvironmentVariables["TMP"]  = Environment.GetEnvironmentVariable("TMP");
                buildProcess.StartInfo.EnvironmentVariables["PATH"] = Environment.GetEnvironmentVariable("PATH");

                buildProcess.StartInfo.RedirectStandardOutput = true;
                buildProcess.StartInfo.StandardOutputEncoding = Encoding.UTF8;
                buildProcess.StartInfo.RedirectStandardError  = true;
                buildProcess.StartInfo.StandardErrorEncoding  = Encoding.UTF8;

                buildProcess.Start();

                var outputTask = Task.Factory.StartNew(() =>
                {
                    var buffer = new char[512];
                    while (true)
                    {
                        var read = buildProcess.StandardOutput.Read(buffer, 0, 512);
                        if (read > 0)
                        {
                            try
                            {
                                stdoutWriter?.Write(buffer, 0, read);
                            }
                            catch (Exception ex)
                            {
                                TraceEx.TraceError($"Unable to write standard output, details: {ex}");
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }, TaskCreationOptions.LongRunning);

                var errorTask = Task.Factory.StartNew(() =>
                {
                    var buffer = new char[512];
                    while (true)
                    {
                        var read = buildProcess.StandardError.Read(buffer, 0, 512);
                        if (read > 0)
                        {
                            try
                            {
                                stderrWriter?.Write(buffer, 0, read);
                            }
                            catch (Exception ex)
                            {
                                TraceEx.TraceError($"Unable to write error output, details: {ex}");
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }, TaskCreationOptions.LongRunning);

                try
                {
                    if (buildProcess.WaitForExit(timeoutInMilliseconds))
                    {
                        return(buildProcess.ExitCode);
                    }
                    else
                    {
                        buildProcess.Kill();
                        buildProcess.WaitForExit();
                        throw new TimeoutException($"{executionInfo.ExeFilePath} (argument: {executionInfo.Arguments}, working directory: {executionInfo.WorkingDirectory}) didn't exit in {timeoutInMilliseconds} ms. Force to exit.");
                    }
                }
                finally
                {
                    outputTask.Wait();
                    errorTask.Wait();
                }
            }
        }
        private static async Task SetupContextAsync(BuildContext context, BuildRequest buildRequest)
        {
            // Setup XmlContext
            context.XmlContext.AddVariable(Constants.ContextData.IncrementalBuild, buildRequest.IsIncremental);

            if (buildRequest.ContextParams == null || buildRequest.ContextParams.Count == 0)
            {
                TraceEx.TraceWarning(LogMessage.FormatMessage(LogCode.PipelineStartsWithoutContextParameter, BuildActionMapper.GetPipelineName(buildRequest.ActionName)));
            }
            else
            {
                foreach (var contextParam in buildRequest.ContextParams.Where(kvp => !string.IsNullOrEmpty(kvp.Key)))
                {
                    context.XmlContext.AddVariable(contextParam.Key, contextParam.Value ?? string.Empty);
                }
            }

            // TODO: refactor this into a separate component
            if (buildRequest.EntityIdentifier != null)
            {
                context.XmlContext.AddVariable(Constants.EntityIdentifier, buildRequest.EntityIdentifier.ToString());
            }

            if (EnvironmentConfiguration.Environment.Value != null)
            {
                context.XmlContext.AddVariable(
                    Constants.Service.ContentService,
                    EnvironmentConfiguration.Environment.Value.GetValue <string>(Constants.Service.ContentServiceEndpoint).TrimEnd('/'));
            }

            if (CommonServiceConfiguration.PreviewContainerUrl.Value != null)
            {
                context.XmlContext.AddVariable(
                    Constants.PreviewContainerUrl,
                    CommonServiceConfiguration.PreviewContainerUrl.Value.TrimEnd('/'));
            }

            if (CommonServiceConfiguration.CollectionContainerUrl.Value != null)
            {
                context.XmlContext.AddVariable(
                    Constants.CollectionContainerUrl,
                    CommonServiceConfiguration.CollectionContainerUrl.Value.TrimEnd('/'));
            }

            // apply build config
            var buildConfigName = BuildActionMapper.GetBuildConfig(buildRequest.ActionName);

            if (buildRequest.EntityIdentifier != null && buildConfigName != null)
            {
                var organizationId = await context.GetOrganizationIdFromProjectAsync(buildRequest.EntityIdentifier.ProjectId);

                var buildConfig = await EntityAccessor.GetBuildConfigAsync(organizationId, buildConfigName);

                if (buildConfig != null)
                {
                    foreach (var config in buildConfig)
                    {
                        context.XmlContext.AddVariable(config.Key, config.Value);
                    }
                }
            }

            // Setup SharedObject
            if (buildRequest.SharedObject != null)
            {
                foreach (var sharedObject in buildRequest.SharedObject.Where(kvp => !string.IsNullOrEmpty(kvp.Key)))
                {
                    context.SetSharedObject(sharedObject.Key, sharedObject.Value);
                }
            }

            if (buildRequest.QueueInfo != null)
            {
                context.QueueInfo = buildRequest.QueueInfo;
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// 终止系统产生的异常,并以消息的形式提示给用户。
        /// </summary>
        /// <param name="ex">异常</param>
        /// <param name="expectMsgOnError">出错时期待提示的消息。</param>
        public void ExceptionTerminate(Exception ex, string expectMsgOnError)
        {
            MB.Util.APPException appEx = getAppException(ex);// as MB.Util.APPException;
            string reason = string.Empty;

            if (appEx == null)
            {
                appEx = ex.InnerException as MB.Util.APPException;
            }

            if (appEx != null)
            {
                if (appEx.MsgLever == MB.Util.APPMessageType.DisplayToUser)
                {
                    MessageBoxEx.Show(appEx.Message);

                    return;
                }
                else
                {
                    expectMsgOnError = MB.Util.TraceEx.GetErrorMessageByType(appEx.MsgLever) + " " + appEx.Message;
                }
            }
            else
            {
                System.ServiceModel.FaultException <MB.Util.Model.WcfFaultMessage> fex = ex as System.ServiceModel.FaultException <MB.Util.Model.WcfFaultMessage>;
                if (fex != null)
                {
                    if (fex.Detail != null)
                    {
                        if (fex.Detail.MessageType == MB.Util.APPMessageType.DisplayToUser)
                        {
                            MessageBoxEx.Show(fex.Detail.Message);
                            return;
                        }
                        else
                        {
                            reason = fex.Detail.Message + " " + MB.Util.TraceEx.GetErrorMessageByType(fex.Detail.MessageType);
                        }
                    }
                    else
                    {
                        reason = fex.Message;
                    }
                }
                string msg = string.Empty;
                if (string.IsNullOrEmpty(reason))
                {
                    getErrMessage(ex, ref msg);
                }

                TraceEx.Write(msg, APPMessageType.SysErrInfo);
                if (!string.IsNullOrEmpty(ex.StackTrace))
                {
                    TraceEx.Write(ex.StackTrace, APPMessageType.SysErrInfo);
                }
            }

            if (string.IsNullOrEmpty(expectMsgOnError))
            {
                if (string.IsNullOrEmpty(reason))
                {
                    reason = "系统出现未知的异常,请重试!";
                }
                MessageBoxEx.Show(reason);
            }
            else
            {
                MessageBoxEx.Show("系统错误:" + expectMsgOnError);
            }
        }