Exemple #1
0
        /// <summary>
        /// Initials the specified key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="container">The container.</param>
        public virtual void Initial(TKey key, TContainer container)
        {
            //NOTES: In case like MatrixList<TKey, Object>. Method Add would hard to tell which method is right to call (Add(key, value) of Dictionary or Add(key, List<Value>))
            try
            {
                if (!IsKeyValid(key))
                {
                    throw ExceptionFactory.CreateInvalidObjectException(nameof(key));
                }

                if (!ContainsKey(key))
                {
                    Add(key, container);
                }
            }
            catch (Exception ex)
            {
                throw ex.Handle(new { key, container });
            }
        }
        /// <summary>
        /// Randoms the specified byte length.
        /// </summary>
        /// <param name="byteLength">Length of the byte.</param>
        /// <returns></returns>
        public static CryptoKey Random(int byteLength)
        {
            try
            {
                if (byteLength < 1)
                {
                    throw ExceptionFactory.CreateInvalidObjectException(nameof(byteLength));
                }

                Random rnd = new Random();
                Byte[] b   = new Byte[byteLength];
                rnd.NextBytes(b);

                return(new CryptoKey(b));
            }
            catch (Exception ex)
            {
                throw ex.Handle(new { byteLength });
            }
        }
Exemple #3
0
        /// <summary>
        /// Reads the bytes to stream.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="destinationStream">The destination stream.</param>
        public static void ReadBytesToStream(this string path, Stream destinationStream)
        {
            try
            {
                path.CheckEmptyString(nameof(path));
                destinationStream.CheckNullObject(nameof(destinationStream));

                if (!File.Exists(path))
                {
                    throw ExceptionFactory.CreateInvalidObjectException(nameof(path), data: new { path }, reason: "NotFound");
                }
                using (var stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    stream.CopyTo(destinationStream);
                }
            }
            catch (Exception ex)
            {
                throw ex.Handle(path);
            }
        }
        /// <summary>
        /// Returns a <see cref="System.String" /> that represents this instance.
        /// </summary>
        /// <param name="values">The values.</param>
        /// <returns>A <see cref="System.String" /> that represents this instance.</returns>
        public string ToString(IDictionary <string, string> values)
        {
            if (!IsValid)
            {
                throw ExceptionFactory.CreateInvalidObjectException(nameof(values), values);
            }

            StringBuilder builder = this.CreateStringBuilder();

            values = values ?? new Dictionary <string, string>();

            for (var i = 0; i < dynamicShards.Count; i++)
            {
                string replacedValue;
                builder.Append(staticShards[i]);
                builder.Append(values.TryGetValue(dynamicShards[i], out replacedValue) ? replacedValue : string.Empty);
            }

            builder.Append(staticShards[dynamicShards.Count]);

            return(builder.ToString());
        }
        /// <summary>
        /// Dexmlizes the specified XML.
        /// </summary>
        /// <param name="xml">The XML.</param>
        /// <returns>
        /// JToken.
        /// </returns>
        public static JToken Dexmlize(this XElement xml)
        {
            if (xml != null)
            {
                var version = xml.GetAttributeValue(attributeVersion);

                switch (version.ToLowerInvariant())
                {
                case JsonXmlizer.VersionValue:
                    return(InternalDexmlize(xml));

                case "":
                case JsonXmlSerializer.VersionValue:
                    return(JsonXmlSerializer.InternalToJToken(xml));

                default:
                    throw ExceptionFactory.CreateInvalidObjectException("version", version);
                }
            }

            return(null);
        }
Exemple #6
0
        /// <summary>
        /// Applies the injection.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="staticType">Type of the static.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="injectionCandidate">The injection candidate.</param>
        /// <param name="expectAsLowPriority">if set to <c>true</c> [expect as low priority].</param>
        public static void ApplyInjection <T>(Type staticType, string propertyName, ParameterlessFunctionInjection <T> injectionCandidate, bool expectAsLowPriority = false)
        {
            if (staticType != null && !string.IsNullOrWhiteSpace(propertyName) && injectionCandidate != null)
            {
                var hitProperty = staticType.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.GetProperty).FirstOrDefault(x => x.Name == propertyName);
                if (hitProperty != null)
                {
                    if (typeof(ParameterlessPrioritizedFunctionInjection <T>).IsAssignableFrom(hitProperty.PropertyType))
                    {
                        ParameterlessPrioritizedFunctionInjection <T> existed = hitProperty.GetValue(null) as ParameterlessPrioritizedFunctionInjection <T>;
                        if (existed == null)
                        {
                            if (hitProperty.SetMethod != null)
                            {
                                existed = new ParameterlessPrioritizedFunctionInjection <T>();
                                hitProperty.SetValue(null, existed);
                            }
                            else
                            {
                                throw ExceptionFactory.CreateInvalidObjectException(hitProperty?.Name, new { type = staticType?.FullName, property = hitProperty?.Name });
                            }
                        }

                        if (expectAsLowPriority)
                        {
                            existed.Append(injectionCandidate);
                        }
                        else
                        {
                            existed.Prepend(injectionCandidate);
                        }
                    }
                    else if (hitProperty.PropertyType == typeof(ParameterlessFunctionInjection <>).MakeGenericType(typeof(T)))
                    {
                        hitProperty.SetValue(null, injectionCandidate);
                    }
                }
            }
        }
Exemple #7
0
        /// <summary>
        /// Creates the temporary assembly.
        /// </summary>
        /// <param name="coreCode">The core code.</param>
        /// <param name="codeReferencedAssembly">The code referenced assembly.</param>
        /// <param name="usingNameSpaces">The using name spaces.</param>
        /// <param name="namespace">The namespace.</param>
        /// <returns>System.String.</returns>
        public string CreateTempAssembly(string coreCode, HashSet <string> codeReferencedAssembly = null, IEnumerable <string> usingNameSpaces = null, string @namespace = null)
        {
            try
            {
                coreCode.CheckNullObject(nameof(coreCode));
                _assemblyProvider.CheckNullObject(nameof(_assemblyProvider));

                var compileResult = _assemblyProvider.CreateRemoteTempAssembly(coreCode, codeReferencedAssembly, usingNameSpaces, @namespace);
                var exceptionInfo = compileResult.GetExceptionInfo();
                if (exceptionInfo == null)
                {
                    return(compileResult.TempAssemblyName);
                }
                else
                {
                    throw ExceptionFactory.CreateOperationException(data: exceptionInfo);
                }
            }
            catch (Exception ex)
            {
                throw ex.Handle(new { coreCode, codeReferencedAssembly });
            }
        }
Exemple #8
0
        /// <summary>
        /// Creates the method invoker.
        /// </summary>
        /// <param name="methodCodeFullName">Full name of the method code.</param>
        /// <returns></returns>
        public static MethodInvoker CreateMethodInvoker(string methodCodeFullName)
        {
            try
            {
                methodCodeFullName.CheckEmptyString(nameof(methodCodeFullName));
                //TODO. Consider simple case in this stage.
                // No generic, no instance. Only static method. {namespace}+.{class}.{method}

                var lastDot = methodCodeFullName.LastIndexOf('.');
                if (lastDot > -1)
                {
                    string method       = methodCodeFullName.Substring(lastDot);
                    var    typeFullName = methodCodeFullName.Substring(0, lastDot);

                    var type = ReflectionExtension.SmartGetType(typeFullName, false);
                    type.CheckNullObjectAsInvalid(nameof(methodCodeFullName), data: new { method, typeFullName });

                    var methodInfo = type.GetMethod(method);
                    methodInfo.CheckNullObjectAsInvalid(nameof(methodCodeFullName), data: new { method, typeFullName });

                    return(new MethodInvoker(methodInfo));
                }
                else
                {
                    throw ExceptionFactory.CreateInvalidObjectException(nameof(methodCodeFullName), data: new { methodCodeFullName });
                }
            }
            catch (BaseException bex)
            {
                throw bex;
            }
            catch (Exception ex)
            {
                throw ex.Handle(new { methodCodeFullName });
            }
        }
        /// <summary>
        /// Initializes static members of the <see cref="EnvironmentCore"/> class.
        /// </summary>
        static EnvironmentCore()
        {
            var baseDirectoryByAppDomain        = AppDomain.CurrentDomain.BaseDirectory;
            var baseDirectoryByAssemblyLocation = Path.GetDirectoryName(typeof(EnvironmentCore).Assembly.Location);

            // NOTE:
            // In IIS Express cases, baseDirectoryByAssemblyLocation would be allocated into asp.net tmp folders, by each library.
            // In other cases, IIS or Console or Windows environments, baseDirectoryByAssemblyLocation should be correct.
            DirectoryInfo baseDirectory = new DirectoryInfo((baseDirectoryByAppDomain.StartsWith(baseDirectoryByAssemblyLocation, StringComparison.OrdinalIgnoreCase)) ?
                                                            baseDirectoryByAssemblyLocation
                 : Path.Combine(baseDirectoryByAppDomain, "bin"));

            if (baseDirectory?.Exists ?? false)
            {
                ApplicationBaseDirectory = baseDirectory.ToString();
            }
            else
            {
                throw ExceptionFactory.CreateInvalidObjectException(nameof(baseDirectory), new
                {
                    baseDirectory = baseDirectory?.ToString(),
                    baseDirectoryByAppDomain,
                    baseDirectoryByAssemblyLocation
                });
            }

            LogDirectory  = Path.Combine(ApplicationBaseDirectory, "logs");
            ApplicationId = System.AppDomain.CurrentDomain.Id;

            var dependencyChain = ReflectionExtension.GetAppDomainAssemblies().GetAssemblyDependencyChain(true);

            AscendingAssemblyDependencyChain = new List <Assembly>(dependencyChain).AsReadOnly();
            dependencyChain.Reverse();

            DescendingAssemblyDependencyChain = dependencyChain.AsReadOnly();

            CommonComponentInfo = typeof(EnvironmentCore).Assembly.GetCustomAttribute <BeyovaComponentAttribute>()?.UnderlyingObject;

            try
            {
                MachineName = Environment.MachineName;
            }
            catch { MachineName = string.Empty; }

            try
            {
                LocalMachineHostName = Dns.GetHostName();

                var host = Dns.GetHostEntry(LocalMachineHostName);
                foreach (var ip in host.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        LocalMachineIpAddress = ip.ToString();
                        break;
                    }
                }
            }
            catch { }

            try
            {
                ProductName = FindProductName();

                if (string.IsNullOrWhiteSpace(ProductName))
                {
                    ProductName = Assembly.GetEntryAssembly()?.FullName;
                }

                if (string.IsNullOrWhiteSpace(ProductName) && AppDomain.CurrentDomain != null)
                {
                    ProductName = AppDomain.CurrentDomain.FriendlyName;
                }
            }
            catch { ProductName = string.Empty; }
        }