Exemple #1
0
        /// <summary>Download file.</summary>
        /// <param name="uri">The URI.</param>
        /// <param name="fileName">The filename output.</param>
        public static void Download(Uri uri, string fileName)
        {
            try
            {
                using (WebClient _client = new WebClient())
                {
                    _client.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0)");
                    _client.Proxy = null;
                    _client.DownloadProgressChanged += Client_DownloadProgressChanged;
                    _client.DownloadFileCompleted   += Client_DownloadFileCompleted;

                    // _client.DownloadFileAsync(uri, fileName);
                    object _syncObject = new object();
                    lock (_syncObject)
                    {
                        _client.DownloadFileAsync(uri, fileName, _syncObject);

                        while (_client.IsBusy)
                        {
                        }

                        // This would block the thread until download completes
                        Monitor.Wait(_syncObject);
                    }
                }
            }
            catch (Exception e)
            {
                ExceptionsManager.WriteException(e.Message);
            }
        }
Exemple #2
0
        private static void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            try
            {
                long _bytesReceived = e.BytesReceived;
                long _totalBytes    = e.TotalBytesToReceive;

                Bytes _received = new Bytes(_bytesReceived)
                {
                    Abbreviated = true
                };
                Bytes _total = new Bytes(_totalBytes)
                {
                    Abbreviated = true
                };

                if (_totalBytes == -1)
                {
                    // _total = "?";
                }

                ConsoleManager.WriteOutput("(" + e.ProgressPercentage.ToString("0") + "%) " + _received + " / " + _total);
            }
            catch (Exception ex)
            {
                ExceptionsManager.WriteException(ex.Message);
            }
        }
Exemple #3
0
 /// <summary>Creates a console command instance.</summary>
 /// <param name="command">The console command.</param>
 public static void CreateCommandInstance(string command)
 {
     try
     {
         ConsoleCommand _command = new ConsoleCommand(command);
         string         _result  = InvokeCommandMethod(_command);
         WriteOutput(_result);
     }
     catch (Exception e)
     {
         ExceptionsManager.WriteException(e.Message);
     }
 }
Exemple #4
0
        /// <summary>Invokes the command method.</summary>
        /// <param name="command">The console command.</param>
        /// <returns>The <see cref="string" />.</returns>
        private static string InvokeCommandMethod(ConsoleCommand command)
        {
            Console.Write(Environment.NewLine);

            // Validate the class name and command name:
            // Validate the command name:
            if (!_commandLibraries.ContainsKey(command.LibraryClassName))
            {
                ExceptionsManager.CommandNotRecognized(command);
                return(string.Empty);
            }

            var methodDictionary = _commandLibraries[command.LibraryClassName];

            if (!methodDictionary.ContainsKey(command.Name))
            {
                ExceptionsManager.CommandNotRecognized(command);
                return(string.Empty);
            }

            // Make sure the correct number of required arguments are provided:
            var methodParameterValueList = new List <object>();
            IEnumerable <ParameterInfo> paramInfoList = methodDictionary[command.Name].ToList();

            // Validate proper # of required arguments provided. Some may be optional:
            var requiredParams = paramInfoList.Where(p => p.IsOptional == false);
            var optionalParams = paramInfoList.Where(p => p.IsOptional);
            int requiredCount  = requiredParams.Count();
            int optionalCount  = optionalParams.Count();
            int providedCount  = command.Arguments.Count();

            if (requiredCount > providedCount)
            {
                ExceptionsManager.WriteException(string.Format("Missing required argument. {0} required, {1} optional, {2} provided", requiredCount, optionalCount, providedCount));
                Console.Write(Environment.NewLine);
                return(string.Empty);
            }

            // Make sure all arguments are coerced to the proper type, and that there is a
            // value for every method parameter. The InvokeMember method fails if the number
            // of arguments provided does not match the number of parameters in the
            // method signature, even if some are optional:
            if (paramInfoList.Any())
            {
                // Populate the list with default values:
                methodParameterValueList.AddRange(paramInfoList.Select(param => param.DefaultValue));

                // Now walk through all the arguments passed from the console and assign
                // accordingly. Any optional arguments not provided have already been set to
                // the default specified by the method signature:
                for (var i = 0; i < command.Arguments.Count(); i++)
                {
                    ParameterInfo _parameterInfo = paramInfoList.ElementAt(i);
                    Type          _parameterType = _parameterInfo.ParameterType;
                    try
                    {
                        // Coming from the Console, all of our arguments are passed in as
                        // strings. Coerce to the type to match the method parameter:
                        object value = CoerceArgument(_parameterType, command.Arguments.ElementAt(i));
                        methodParameterValueList.RemoveAt(i);
                        methodParameterValueList.Insert(i, value);
                    }
                    catch (ArgumentException)
                    {
                        string argumentName     = _parameterInfo.Name;
                        string argumentTypeName = _parameterType.Name;
                        string message          = string.Format(string.Empty + "The value passed for argument '{0}' cannot be parsed to type '{1}'", argumentName, argumentTypeName);
                        throw new ArgumentException(message);
                    }
                }
            }

            // Set up to invoke the method using reflection:
            Assembly current = typeof(Program).Assembly;

            // Need the full Namespace for this:
            Type _commandLibraryClass = current.GetType(CommandNamespace + "." + command.LibraryClassName);

            object[] inputArgs = null;
            if (methodParameterValueList.Count > 0)
            {
                inputArgs = methodParameterValueList.ToArray();
            }

            Type typeInfo = _commandLibraryClass;

            // This will throw if the number of arguments provided does not match the number
            // required by the method signature, even if some are optional:
            try
            {
                object result = typeInfo.InvokeMember(command.Name, BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public, null, null, inputArgs);
                return(result.ToString());
            }
            catch (TargetInvocationException e)
            {
                throw e.InnerException;
            }
        }