protected override string PerformWebRequest(IEnumerable <INameValue> head, string query, WebSource source, string putData, bool isPutDataBase64 = false)
 {
     Head     = head;
     QueryRes = query;
     if (!string.IsNullOrWhiteSpace(HasErrorMessage))
     {
         base._errorsTo = new ErrorResultTO();
         base._errorsTo.AddError(HasErrorMessage);
     }
     return(ResponseFromWeb);
 }
Esempio n. 2
0
        protected virtual string PerformWebPostRequest(IEnumerable <NameValue> head, string query, WebSource source, string putData)
        {
            var headerValues = head as NameValue[] ?? head.ToArray();
            var httpClient   = CreateClient(headerValues, query, source);

            if (httpClient != null)
            {
                var address = source.Address;
                if (query != null)
                {
                    address = address + query;
                }
                if (_method == WebRequestMethod.Get)
                {
                    var taskOfString = httpClient.GetStringAsync(new Uri(address));
                    return(taskOfString.Result);
                }
                Task <HttpResponseMessage> taskOfResponseMessage;
                if (_method == WebRequestMethod.Delete)
                {
                    taskOfResponseMessage = httpClient.DeleteAsync(new Uri(address));
                    bool ranToCompletion = taskOfResponseMessage.Status == TaskStatus.RanToCompletion;
                    return(ranToCompletion ? "The task completed execution successfully" : "The task completed due to an unhandled exception");
                }
                if (_method == WebRequestMethod.Post)
                {
                    taskOfResponseMessage = httpClient.PostAsync(new Uri(address), new StringContent(putData));
                    var message = taskOfResponseMessage.Result.Content.ReadAsStringAsync().Result;
                    return(message);
                }
                HttpContent httpContent = new StringContent(putData, Encoding.UTF8);
                var         contentType = headerValues.FirstOrDefault(value => value.Name.ToLower() == "Content-Type".ToLower());
                if (contentType != null)
                {
                    httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType.Value);
                }
                var httpRequest = new HttpRequestMessage(HttpMethod.Put, new Uri(address))
                {
                    Content = httpContent
                };
                taskOfResponseMessage = httpClient.SendAsync(httpRequest);
                var resultAsString = taskOfResponseMessage.Result.Content.ReadAsStringAsync().Result;
                return(resultAsString);
            }
            return(null);
        }
Esempio n. 3
0
 protected virtual string PerformWebRequest(IEnumerable <INameValue> head, string query, WebSource url)
 {
     return(WebSources.Execute(url, WebRequestMethod.Get, query, String.Empty, true, out _errorsTo, head.Select(h => h.Name + ":" + h.Value).ToArray()));
 }
Esempio n. 4
0
        public void WebSources_PerformMultipartWebRequest_SetsContentTypeHeaders_And_ShouldReturnNullWebResponse()
        {
            var address              = "http://www.msn.com/";
            var responseFromWeb      = Encoding.ASCII.GetBytes("response from web request");
            var mockWebClientWrapper = new Mock <IWebClientWrapper>();

            mockWebClientWrapper.Setup(o => o.Headers).Returns(new WebHeaderCollection {
                "a:x", "b:e"
            });
            mockWebClientWrapper.Setup(o => o.UploadData(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <byte[]>()))
            .Returns(responseFromWeb);

            var mockWebResponseWrapper = new Mock <HttpWebResponse>();

            mockWebResponseWrapper.Setup(o => o.StatusCode)
            .Returns(HttpStatusCode.OK);
            mockWebResponseWrapper.Setup(o => o.GetResponseStream())
            .Returns(new MemoryStream(responseFromWeb));

            var mockWebRequest = new Mock <IWebRequest>();

            mockWebRequest.Setup(o => o.Headers)
            .Returns(new WebHeaderCollection
            {
                "Authorization:bear: sdfsfff",
            });
            mockWebRequest.Setup(o => o.ContentType)
            .Returns("Content-Type: multipart/form-data");
            mockWebRequest.Setup(o => o.ContentLength)
            .Returns(Encoding.ASCII.GetBytes(postData).Length);
            mockWebRequest.Setup(o => o.Method)
            .Returns("POST");
            mockWebRequest.Setup(o => o.GetRequestStream())
            .Returns(new MemoryStream());
            mockWebRequest.Setup(o => o.GetResponse())
            .Returns(mockWebResponseWrapper.Object);

            var mockWebRequestFactory = new Mock <IWebRequestFactory>();

            mockWebRequestFactory.Setup(o => o.New(address))
            .Returns(mockWebRequest.Object);

            var source = new WebSource
            {
                Address            = address,
                AuthenticationType = AuthenticationType.Anonymous,
                Client             = new WebClientWrapper
                {
                    Headers = new WebHeaderCollection
                    {
                        "a:x",
                        "b:e",
                        "Content-Type: multipart/form-data"
                    }
                }
            };

            var result = string.Empty;

            try
            {
                result = WebSources.PerformMultipartWebRequest(mockWebRequestFactory.Object, source.Client, source.Address, postData);
            }
            catch (WebException e)
            {
                Assert.Fail("Error connecting to " + source.Address + "\n" + e.Message);
            }
            var client      = source.Client;
            var contentType = client.Headers["Content-Type"];

            Assert.IsNotNull(contentType);
            Assert.AreEqual("multipart/form-data", contentType);

            Assert.AreEqual("response from web request", result);
        }
Esempio n. 5
0
        public override HttpClient CreateClient(IEnumerable <NameValue> head, string query, WebSource source)
        {
            var httpClient = new HttpClient();

            if (source.AuthenticationType == AuthenticationType.User)
            {
                var byteArray = Encoding.ASCII.GetBytes(String.Format("{0}:{1}", source.UserName, source.Password));
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
            }

            if (head != null)
            {
                IEnumerable <NameValue> nameValues = head.Where(nameValue => !String.IsNullOrEmpty(nameValue.Name) && !String.IsNullOrEmpty(nameValue.Value));
                foreach (var nameValue in nameValues)
                {
                    httpClient.DefaultRequestHeaders.TryAddWithoutValidation(nameValue.Name, nameValue.Value);
                }
            }

            var address = source.Address;

            if (!string.IsNullOrEmpty(query))
            {
                address = address + query;
            }
            try
            {
                var baseAddress = new Uri(address);
                httpClient.BaseAddress = baseAddress;
            }
            catch (UriFormatException e)
            {
                //CurrentDataObject.Environment.AddError(e.Message);// To investigate this
                Dev2Logger.Error(e.Message, e); // Error must be added on the environment
                return(httpClient);
            }

            return(httpClient);
        }
Esempio n. 6
0
        public virtual HttpClient CreateClient(IEnumerable <INameValue> head, string query, WebSource source)
        {
            var httpClient = new HttpClient();

            if (source.AuthenticationType == AuthenticationType.User)
            {
                var byteArray = Encoding.ASCII.GetBytes(String.Format("{0}:{1}", source.UserName, source.Password));
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
            }

            if (head != null)
            {
                var nameValues = head.Where(nameValue => !String.IsNullOrEmpty(nameValue.Name) && !String.IsNullOrEmpty(nameValue.Value));
                foreach (var nameValue in nameValues)
                {
                    httpClient.DefaultRequestHeaders.Add(nameValue.Name, nameValue.Value);
                }
            }

            httpClient.DefaultRequestHeaders.Add(UserAgent, GlobalConstants.UserAgentString);

            var address = source.Address;

            if (!string.IsNullOrEmpty(query))
            {
                address = address + query;
            }
            try
            {
                var baseAddress = new Uri(address);
                httpClient.BaseAddress = baseAddress;
            }
            catch (UriFormatException e)
            {
                Dev2Logger.Error(e.Message, e, GlobalConstants.WarewolfError);
                return(httpClient);
            }

            return(httpClient);
        }
Esempio n. 7
0
 public SiteSearcherMock(WebSource source, string searchString, IDialogService dialogService, Func <WebSource, string, IUrlFetcher> urlFetcherFactory) : base(source, searchString, dialogService, urlFetcherFactory)
 {
 }
 protected override string PerformWebPostRequest(IEnumerable <INameValue> head, string query, WebSource source, string postData)
 {
     Head      = head;
     QueryRes  = query;
     PostValue = postData;
     if (!string.IsNullOrWhiteSpace(HasErrorMessage))
     {
         base._errorsTo = new ErrorResultTO();
         base._errorsTo.AddError(ResponseFromWeb);
     }
     return(ResponseFromWeb);
 }
        public void GetDebugInputs_GivenMockEnvironment_ShouldAddDebugInputItems()
        {
            //---------------Set up test pack-------------------
            const string response = "{\"Location\": \"Paris\",\"Time\": \"May 29, 2013 - 09:00 AM EDT / 2013.05.29 1300 UTC\"," +
                                    "\"Wind\": \"from the NW (320 degrees) at 10 MPH (9 KT) (direction variable):0\"," +
                                    "\"Visibility\": \"greater than 7 mile(s):0\"," +
                                    "\"Temperature\": \"59 F (15 C)\"," +
                                    "\"DewPoint\": \"41 F (5 C)\"," +
                                    "\"RelativeHumidity\": \"51%\"," +
                                    "\"Pressure\": \"29.65 in. Hg (1004 hPa)\"," +
                                    "\"Status\": \"Success\"" +
                                    "}";
            var environment = new ExecutionEnvironment();

            environment.Assign("[[City]]", "PMB", 0);
            environment.Assign("[[CountryName]]", "South Africa", 0);
            environment.Assign("[[Post]]", "Some data", 0);
            var dsfWebPostActivity = new TestDsfWebPostActivity
            {
                Headers = new List <INameValue> {
                    new NameValue("Header 1", "[[City]]")
                },
                QueryString = "http://www.testing.com/[[CountryName]]",
                PostData    = "This is post:[[Post]]"
            };
            var serviceOutputs = new List <IServiceOutputMapping> {
                new ServiceOutputMapping("Location", "[[weather().Location]]", "weather"), new ServiceOutputMapping("Time", "[[weather().Time]]", "weather"), new ServiceOutputMapping("Wind", "[[weather().Wind]]", "weather"), new ServiceOutputMapping("Visibility", "[[Visibility]]", "")
            };

            dsfWebPostActivity.Outputs = serviceOutputs;
            var serviceXml = XmlResource.Fetch("WebService");
            var service    = new WebService(serviceXml)
            {
                RequestResponse = response
            };

            dsfWebPostActivity.OutputDescription = service.GetOutputDescription();
            dsfWebPostActivity.ResponseFromWeb   = response;
            var dataObjectMock = new Mock <IDSFDataObject>();

            dataObjectMock.Setup(o => o.Environment).Returns(environment);
            dataObjectMock.Setup(o => o.EsbChannel).Returns(new Mock <IEsbChannel>().Object);
            dsfWebPostActivity.ResourceID = InArgument <Guid> .FromValue(Guid.Empty);

            var cat = new Mock <IResourceCatalog>();
            var src = new WebSource {
                Address = "www.example.com"
            };

            cat.Setup(a => a.GetResource <WebSource>(It.IsAny <Guid>(), It.IsAny <Guid>())).Returns(src);
            dsfWebPostActivity.ResourceCatalog = cat.Object;
            //---------------Assert Precondition----------------
            Assert.IsNotNull(environment);
            Assert.IsNotNull(dsfWebPostActivity);
            //---------------Execute Test ----------------------
            var debugInputs = dsfWebPostActivity.GetDebugInputs(environment, 0);

            //---------------Test Result -----------------------
            Assert.IsNotNull(debugInputs);
            Assert.AreEqual(4, debugInputs.Count);
        }
Esempio n. 10
0
        /// <summary>
        /// Use eStore B+B function to calcaulate freight(simple version for ajax)
        /// </summary>
        /// <returns></returns>
        public static ShippingResult CalculateBBFreight(string shipToCountry, string shipToZipCode, string shipToState, string cartId, WebSource source = WebSource.Myadvantech)
        {
            ShippingResult        shippingResult  = new ShippingResult();
            List <ShippingMethod> shippingmethods = new List <ShippingMethod>();
            Response response;

            try
            {
                List <FreightOption> freightOptions = Advantech.Myadvantech.DataAccess.MyAdvantechDAL.GetAllFreightOptions();
                foreach (var option in freightOptions)
                {
                    ShippingMethod method = new ShippingMethod();
                    method.MethodName          = option.SAPCode + ": " + option.Description;
                    method.MethodValue         = option.CarrierCode + ": " + option.Description;
                    method.DisplayShippingCost = "N/A";
                    method.ErrorMessage        = "";
                    if (option.EStoreServiceName != null)
                    {
                        method.EstoreServiceName = option.EStoreServiceName;
                    }
                    shippingmethods.Add(method);
                }


                try
                {
                    shippingrate target = new shippingrate();
                    target.Timeout = 30000;
                    //target.Url = "http://buy.advantech.com/services/shippingrate.asmx"; AUS eStore URL

                    DataAccess.bbeStoreFreightAPI.Order order = new DataAccess.bbeStoreFreightAPI.Order();
                    order.StoreId = "ABB";


                    // Shipto settings
                    Address shipto = new Address();
                    shipto.Countrycode = shipToCountry;
                    shipto.Zipcode     = shipToZipCode;
                    shipto.StateCode   = shipToState;
                    order.Shipto       = shipto;
                    order.Billto       = shipto;

                    if (source == WebSource.Myadvantech)
                    {
                        List <Advantech.Myadvantech.DataAccess.cart_DETAIL_V2> cartItems = Advantech.Myadvantech.DataAccess.CartDetailHelper.GetCartDetailByID(cartId);

                        // Loose Items settings
                        List <Item>           items      = new List <Item>();
                        List <cart_DETAIL_V2> LooseItems = cartItems.Where(d => d.otype == 0).ToList();
                        if (LooseItems.Count > 0)
                        {
                            foreach (cart_DETAIL_V2 LooseItem in LooseItems)
                            {
                                items.Add(new Item()
                                {
                                    ProductID = LooseItem.Part_No,
                                    Qty       = (int)LooseItem.Qty
                                });
                            }
                        }

                        // System Items settings
                        List <ConfigSystem>   systems     = new List <ConfigSystem>();
                        List <cart_DETAIL_V2> ParentItems = cartItems.Where(d => d.otype == -1).ToList();
                        foreach (cart_DETAIL_V2 ParentItem in ParentItems)
                        {
                            int          _sys1Qty = 1;
                            ConfigSystem _sys1    = new ConfigSystem();
                            _sys1.Qty       = (int)ParentItem.Qty;
                            _sys1.ProductID = ParentItem.Part_No;
                            _sys1Qty        = _sys1.Qty;

                            List <cart_DETAIL_V2> ChildItems = cartItems.Where(d => d.otype == 1 && d.higherLevel == ParentItem.Line_No).ToList();
                            List <Item>           _ds        = new List <Item>();
                            foreach (cart_DETAIL_V2 ChildItem in ChildItems)
                            {
                                _ds.Add(new Item()
                                {
                                    ProductID = ChildItem.Part_No,
                                    Qty       = (Int32)Math.Ceiling((double)(Convert.ToDouble(ChildItem.Qty / (double)_sys1Qty)))
                                });
                            }

                            _sys1.Details = _ds.ToArray();
                            systems.Add(_sys1);
                        }
                        order.Items   = items.ToArray();
                        order.Systems = systems.ToArray();
                    }
                    else if (source == WebSource.eQuotation)
                    {
                        var quotationMaster = QuoteBusinessLogic.GetQuotationMaster(cartId);
                        if (quotationMaster != null)
                        {
                            List <QuotationDetail> _QuoteDetails = quotationMaster.QuotationDetail;

                            // Loose Items settings
                            List <Item>            items      = new List <Item>();
                            List <QuotationDetail> LooseItems = _QuoteDetails.Where(q => q.ItemType == (int)LineItemType.LooseItem).ToList();
                            if (LooseItems.Count > 0)
                            {
                                foreach (QuotationDetail LooseItem in LooseItems)
                                {
                                    items.Add(new Item()
                                    {
                                        ProductID = LooseItem.partNo,
                                        Qty       = (int)LooseItem.qty
                                    });
                                }
                            }

                            // System Items settings
                            List <ConfigSystem>    systems     = new List <ConfigSystem>();
                            List <QuotationDetail> ParentItems = _QuoteDetails.Where(q => q.ItemType == (int)LineItemType.BTOSParent).ToList();
                            foreach (QuotationDetail ParentItem in ParentItems)
                            {
                                int          _sys1Qty = 1;
                                ConfigSystem _sys1    = new ConfigSystem();
                                _sys1.Qty       = (int)ParentItem.qty;
                                _sys1.ProductID = ParentItem.partNo;
                                _sys1Qty        = _sys1.Qty;

                                List <QuotationDetail> ChildItems = _QuoteDetails.Where(q => q.ItemType == (int)LineItemType.BTOSChild && q.HigherLevel == ParentItem.line_No).ToList();
                                List <Item>            _ds        = new List <Item>();
                                foreach (QuotationDetail ChildItem in ChildItems)
                                {
                                    _ds.Add(new Item()
                                    {
                                        ProductID = ChildItem.partNo,
                                        Qty       = (Int32)Math.Ceiling((double)(Convert.ToDouble(ChildItem.qty / (double)_sys1Qty)))
                                    });
                                }

                                _sys1.Details = _ds.ToArray();
                                systems.Add(_sys1);
                            }
                            order.Items   = items.ToArray();
                            order.Systems = systems.ToArray();
                        }
                    }



                    response = target.getShippingRate(order);
                }
                catch (Exception ex)
                {
                    throw ex;
                }



                if (response != null)
                {
                    if (response.ShippingRates != null)
                    {
                        var normalShippingRatesList = new List <ShippingRate>();
                        foreach (var item in response.ShippingRates)
                        {
                            foreach (var method in shippingmethods)
                            {
                                if (method.EstoreServiceName == item.Nmae)
                                {
                                    method.ShippingCost        = item.Rate;
                                    method.DisplayShippingCost = item.Rate.ToString();
                                    method.ErrorMessage        = string.IsNullOrEmpty(item.ErrorMessage)? "" : item.ErrorMessage;

                                    //配對成功的就移除
                                    normalShippingRatesList.Add(item);
                                }
                            }
                        }
                        var unnormalShippingRatesList = response.ShippingRates.Where(p => !normalShippingRatesList.Any(p2 => p2.Nmae == p.Nmae));
                        if (unnormalShippingRatesList.Any())
                        {
                            shippingResult.Message = string.Join("<br/>", unnormalShippingRatesList.Select(s => s.Nmae).ToList());
                        }
                    }

                    if (response.Boxex[0] != null)
                    {
                        shippingResult.Weight = (double)Decimal.Round(response.Boxex[0].Weight, 2);
                    }



                    shippingResult.Status = response.Status;
                    //if (response.DetailMessages != null)
                    //    shippingResult.DetailMessage += string.Join(",", response.DetailMessages);
                }
                else
                {
                    shippingResult.Message = "No Response. Please select one freight option and manually enter cost.";
                    shippingResult.Status  = "0";
                }
            }
            catch (Exception ex)
            {
                shippingResult.Message       = "Exception occurs. Please contact Myadvantech team.";
                shippingResult.DetailMessage = ex.Message;
                shippingResult.Status        = "0";
            }

            shippingResult.ShippingMethods = shippingmethods;


            return(shippingResult);
        }
Esempio n. 11
0
 public static byte[] Execute(WebSource source, WebRequestMethod method, string relativeUri, byte[] data, bool throwError, out ErrorResultTO errors, string[] headers = null)
 {
     EnsureWebClient(source, headers);
     return(Execute(source.Client, string.Format("{0}{1}", source.Address, relativeUri), method, data, throwError, out errors));
 }
Esempio n. 12
0
 protected override string PerformWebRequest(IEnumerable <NameValue> head, string query, WebSource url)
 {
     return(ResponseFromWeb);
 }
Esempio n. 13
0
        protected virtual string PerformWebPostRequest(IEnumerable <NameValue> head, string query, WebSource source, string postData)
        {
            var webclient = CreateClient(head, query, source);

            if (webclient != null)
            {
                var address = source.Address;
                if (query != null)
                {
                    address = address + query;
                }
                return(webclient.UploadString(address, postData));
            }
            return(null);
        }
        protected virtual string PerformWebRequest(IEnumerable <NameValue> head, string query, WebSource url)
        {
            var client = CreateClient(head, query, url);
            var result = client.DownloadString(url.Address + query);

            return(result);
        }
Esempio n. 15
0
 public void WebSourceContructorWithNullXmlExpectedThrowsArgumentNullException()
 {
     var source = new WebSource(null);
 }
Esempio n. 16
0
 protected override string PerformWebPostRequest(IEnumerable <NameValue> head, string query, WebSource source, string postData)
 {
     Head      = head;
     QueryRes  = query;
     PostValue = postData;
     return(ResponseFromWeb);
 }
Esempio n. 17
0
        protected virtual string PerformWebRequest(IEnumerable <INameValue> head, string query, WebSource source, string putData)
        {
            var headerValues = head as NameValue[] ?? head.ToArray();
            var httpClient   = CreateClient(headerValues, query, source);

            if (httpClient != null)
            {
                try
                {
                    var    address = BuildQuery(query, source);
                    string resultAsString;
                    switch (_method)
                    {
                    case WebRequestMethod.Get:
                        var taskOfString = httpClient.GetStringAsync(new Uri(address));
                        resultAsString = taskOfString.Result;
                        break;

                    case WebRequestMethod.Post:
                        var taskOfResponseMessage = httpClient.PostAsync(new Uri(address), new StringContent(putData));
                        resultAsString = taskOfResponseMessage.Result.Content.ReadAsStringAsync().Result;
                        break;

                    case WebRequestMethod.Delete:
                        taskOfResponseMessage = httpClient.DeleteAsync(new Uri(address));
                        resultAsString        = taskOfResponseMessage.Result.Content.ReadAsStringAsync().Result;
                        break;

                    case WebRequestMethod.Put:
                        resultAsString = PerformPut(putData, headerValues, httpClient, address);
                        break;

                    default:
                        resultAsString = $"Invalid Request Method: {_method}";
                        break;
                    }
                    return(resultAsString);
                }
                catch (WebException webEx)
                {
                    if (webEx.Response is HttpWebResponse httpResponse)
                    {
                        using (var responseStream = httpResponse.GetResponseStream())
                        {
                            var reader = new StreamReader(responseStream);
                            return(reader.ReadToEnd());
                        }
                    }
                }
            }
            return(null);
        }
Esempio n. 18
0
 protected override string PerformWebRequest(IEnumerable <INameValue> head, string query, WebSource url)
 {
     if (!string.IsNullOrWhiteSpace(HadErrorMessage))
     {
         base._errorsTo = new ErrorResultTO();
         base._errorsTo.AddError(HadErrorMessage);
     }
     return(ResponseFromWeb);
 }
 protected override string PerformWebPostRequest(IEnumerable <NameValue> head, string query, WebSource source,
                                                 string putData)
 {
     return(ResponseFromWeb);
 }
Esempio n. 20
0
    static void Main(string[] args)
    {
        Console.ForegroundColor = ConsoleColor.Cyan;
        Console.WriteLine("AeroNovelTool by AE Ver." + Version.date);
        Console.ForegroundColor = ConsoleColor.White;
        if (args.Length >= 2)
        {
            switch (args[0].ToLower())
            {
            case "epub":
            {
                if (!DirectoryExist(args[1]))
                {
                    return;
                }
                var gen = new AeroNovelEpub.GenEpub();
                for (int i = 2; i < args.Length; i++)
                {
                    switch (args[i])
                    {
                    case "--t2s":
                        gen.cc_option = AeroNovelEpub.ChineseConvertOption.T2S; break;

                    case "--no-info":
                        gen.addInfo = false;
                        break;

                    case "--no-indent-adjust":
                        gen.indentAdjust = false;
                        break;
                    }
                }

                EpubFile      e          = gen.Gen(args[1]);
                List <string> creators   = new List <string>();
                string        dateString = DateTime.Today.ToString("yyyyMMdd");
                e.dc_creators.ForEach((x) =>
                    {
                        if (x.refines.Count > 0)
                        {
                            foreach (var refine in x.refines)
                            {
                                if (refine.name == "role")
                                {
                                    if (refine.value != "aut")
                                    {
                                        return;
                                    }
                                }
                            }
                        }
                        creators.Add(x.value);
                    });
                try
                {
                    e.meta.ForEach((x) => { if (x.name == "dcterms:modified")
                                            {
                                                dateString = x.value.Replace("-", "").Substring(0, 8);
                                            }
                                   });
                }
                catch (ArgumentOutOfRangeException)
                {
                    Log.Warn("Error at getting modified date in metadata");
                }

                e.filename = $"[{string.Join(",", creators)}] {e.title} [{dateString}]";
                if (args.Length >= 3 && DirectoryExist(args[2]))
                {
                    e.Save(args[2]);
                }
                else
                {
                    e.Save("");
                }
            }
            break;

            case "txt":
                if (!DirectoryExist(args[1]))
                {
                    return;
                }
                GenTxt.Gen(args[1]);
                break;

            case "bbcode":
                if (!DirectoryExist(args[1]))
                {
                    return;
                }
                if (args.Length >= 3)
                {
                    if (DirectoryExist(args[2]))
                    {
                        GenBbcode.output_path        = Path.Combine(args[2], GenBbcode.output_path);
                        GenBbcode.output_path_single = Path.Combine(args[2], GenBbcode.output_path_single);
                    }
                }
                GenBbcode.GenSingle(args[1]);
                break;

            case "epub2comment":
                if (!FileExist(args[1]))
                {
                    return;
                }
                Epub2Comment e2c = new Epub2Comment(args[1]);
                if (args.Length > 2)
                {
                    switch (args[2])
                    {
                    case "BlackMagic-Cloud":
                        e2c.setTextTranslation = new BlackMagic_Cloud();
                        break;

                    case "BlackMagic-Dog":
                        e2c.setTextTranslation = new BlackMagic_Dog();
                        break;

                    case "Glossary":
                        if (args.Length > 3)
                        {
                            e2c.glossaryDocPath = args[3];
                        }
                        else
                        {
                            Log.Error("Should give glossary document.");
                        }
                        break;
                    }
                }
                e2c.Proc();
                break;

            case "epub2atxt":
                if (!FileExist(args[1]))
                {
                    return;
                }
                Epub2Atxt.Proc(args[1]);
                break;

            case "html2comment":
                if (!FileExist(args[1]))
                {
                    return;
                }
                Html2Comment.Proc(args[1]);
                break;

            case "atxt2bbcode":
                if (!FileExist(args[1]))
                {
                    return;
                }
                GenBbcode.Proc(args[1]);
                break;

            case "kakuyomu2comment":
            {
                var xhtml = WebSource.KakuyomuEpisode(args[1]);
                var atxt  = Html2Comment.ProcXHTML(xhtml.text);
                File.WriteAllText("output_kakuyomu2comment.txt", atxt);
                Log.Note("output_kakuyomu2comment.txt");
            }
            break;

            case "websrc":
            {
                TextEpubItemFile[] xhtmls;
                string             dirname = "output_websrc_";
                if (args[1].Contains("kakuyomu.jp"))
                {
                    xhtmls   = WebSource.KakuyomuAuto(args[1]);
                    dirname += "kakuyomu";
                }
                else
                {
                    Log.Error("什么网站");
                    break;
                }
                if (xhtmls != null)
                {
                    Directory.CreateDirectory(dirname);
                    foreach (var xhtml in xhtmls)
                    {
                        Save(xhtml, dirname);
                    }
                }
            }
            break;

            case "atxtcc":
            {
                if (!FileExist(args[1]))
                {
                    return;
                }
                bool t2s = false, s2t = false, replace = false;
                for (int i = 2; i < args.Length; i++)
                {
                    switch (args[i])
                    {
                    case "t2s": t2s = true; break;

                    case "s2t": s2t = true; break;

                    case "replace": replace = true; break;
                    }
                }
                if (t2s)
                {
                    AeroNovelEpub.AtxtChineseConvert.ProcT2C(args[1], replace);
                }
                else if (s2t)
                {
                    //Not Implemented
                }
            }
            break;

            case "atxt2inlinehtml":
                if (File.Exists(args[1]))
                {
                    Atxt2InlineHTML.ConvertSave(args[1], $"output_inlineHTML_{Path.GetFileNameWithoutExtension(args[1])}.txt");
                    break;
                }
                if (Directory.Exists(args[1]))
                {
                    var outputPath = "output_inlineHTML_" + Path.GetFileName(args[1]);
                    Directory.CreateDirectory(outputPath);
                    Atxt2InlineHTML.ConvertSaveDir(args[1], outputPath);
                    break;
                }
                Log.Warn("Nothing happens. Make sure there is a file or folder to process.");
                break;

            case "analyze":
                if (Directory.Exists(args[1]))
                {
                    if (args.Length >= 3)
                    {
                        int chap = 0;
                        if (!int.TryParse(args[2], out chap))
                        {
                            Log.Error("Chapter number!");
                        }
                        Statistic.AnalyzeProject(args[1], chap);
                        break;
                    }
                    Statistic.AnalyzeProject(args[1]);
                    break;
                }
                break;

            default:
                Log.Warn("Nothing happens. " + usage);
                break;
            }
        }
        else
        {
            Log.Warn(usage);
        }
    }