Пример #1
0
        private static int GetServicePort(string address)
        {
            var binding         = CreateBinding(TimeSpan.MaxValue);
            var endPointAddress = new EndpointAddress($"net.tcp://{AddressUtility.ConnectionAddress(address)}/DescriptorService");
            var serviceClient   = new DescriptorServiceClient(binding, endPointAddress);

            try
            {
                var serviceInfos = serviceClient.GetServiceInfos();

                foreach (var item in serviceInfos)
                {
                    if (item.Name == nameof(RuntimeService))
                    {
                        return(item.Port);
                    }
                }

                throw new InvalidOperationException();
            }
            finally
            {
                serviceClient.Close();
            }
        }
Пример #2
0
        public Guid Open(string address, string dataBase, string userID, SecureString password)
        {
            if (this.isConnected == true)
            {
                throw new InvalidOperationException(Resources.Exception_AlreadyConnected);
            }

            this.ipAddress    = AddressUtility.GetIPAddress(address);
            this.serviceInfos = GetServiceInfo(address).ToDictionary(item => item.Name);

            this.OnOpening(EventArgs.Empty);
            return(this.dispatcher.Invoke(() =>
            {
                try
                {
                    return OpenInternal(address, dataBase, userID, password);
                }
                catch
                {
                    this.userContext?.Close(CloseInfo.Empty);
                    this.userContext = null;
                    this.log?.Dispose();
                    this.log = null;
                    this.address = null;
                    throw;
                }
            }));
        }
Пример #3
0
        private Guid OpenInternal(string address, string dataBase, string userID, SecureString password)
        {
            this.address     = AddressUtility.GetDisplayAddress(address);
            this.log         = new LogService(this.address.Replace(':', '_'), userID, AppUtility.UserAppDataPath);
            this.log.Verbose = this.verbose;
            this.userContext = new UserContext(this, this.ipAddress, serviceInfos[nameof(UserService)], userID, password);
            var user = this.userContext.Users[userID];

            user.SetUserState(UserState.Online);
            this.userID    = userID;
            this.authority = user.Authority;

            this.dataBases     = new DataBaseCollection(this, this.ipAddress, dataBase, serviceInfos[nameof(DataBaseCollectionService)]);
            this.domainContext = new DomainContext(this, this.ipAddress, serviceInfos[nameof(DomainService)]);
            this.isConnected   = true;
            this.configs       = new CremaConfiguration(this.ConfigPath);
            this.plugins       = this.container.GetService(typeof(IEnumerable <IPlugin>)) as IEnumerable <IPlugin>;
            foreach (var item in this.plugins)
            {
                var authentication = new Authentication(new AuthenticationProvider(user), item.ID);
                this.authentications.Add(authentication);
                item.Initialize(authentication);
            }

            this.OnOpened(EventArgs.Empty);
            this.token = Guid.NewGuid();
            CremaLog.Info($"Crema opened : {address} {userID}");
            return(token);
        }
        public void IsValidAddress_MassTest()
        {
            String[] realAddresses = GetManyAddresses();
            foreach (string address in realAddresses)
            {
                //Test 1: Check that is valid:
                //either normal or multisig
                bool bNormal = AddressUtility.IsValidAddress(address);
                bool bMulti  = AddressUtility.IsValidMultisigAddress(address);

                //if ends with 0, then multisig
                bool isMultiSig = address.EndsWith("0");
                if (isMultiSig)
                {
                    //MuliSig
                    Assert.AreEqual(false, bNormal);
                    Assert.AreEqual(true, bMulti);
                }
                else
                {
                    //Normal
                    Assert.AreEqual(true, bNormal);
                    Assert.AreEqual(false, bMulti);
                }
            }
        }
        public void IsValidAddress_MassTest_Invalid()
        {
            int iTestCount = 0;

            String[] realAddresses = GetManyAddresses();
            foreach (string address in realAddresses)
            {
                //Change last 3 char

                for (int i = 0; i < address.Length; i++)
                {
                    char[] ach = address.ToCharArray();
                    ach[i] = Convert.ToChar((int)ach[i] + 1); //increment by 1, which will break the checksum

                    //return to string
                    String strMalformedAddress = new string(ach);

                    //No longer valid
                    Assert.AreEqual(false, AddressUtility.IsValidAddress(strMalformedAddress));
                    Assert.AreEqual(false, AddressUtility.IsValidMultisigAddress(strMalformedAddress));
                    iTestCount++;
                }
            }
            Console.WriteLine("Ran {0} combinations", iTestCount);
        }
Пример #6
0
        public static DescriptorServiceClient CreateServiceClient(string address)
        {
            var binding         = CreateBinding(TimeSpan.MaxValue);
            var endPointAddress = new EndpointAddress($"net.tcp://{AddressUtility.ConnectionAddress(address)}/DescriptorService");
            var serviceClient   = new DescriptorServiceClient(binding, endPointAddress);

            return(serviceClient);
        }
        public CreateShipmentResponse CreateInboundShipment(CreateShipmentRequest createShipmentRequest)
        {
            Address shipsFromAddress = AddressUtility.GetShipFromAddress();

            CreateShipmentResponse createShipmentResponse = null;

            List <InboundShipmentPlanRequestItem> shipmentPlanRequestItems = createShipmentRequest
                                                                             .ShipmentItems
                                                                             .Select(s =>
                                                                                     new InboundShipmentPlanRequestItem
            {
                ASIN           = s.Asin,
                SellerSKU      = s.Sku,
                Quantity       = s.Quantity,
                Condition      = ItemCondition.NewItem.ToString(),
                QuantityInCase = s.QuantityInCase ?? 0
            })
                                                                             .ToList();

            InboundShipmentPlanRequestItemList inboundShipmentPlanRequestItemList = new InboundShipmentPlanRequestItemList
            {
                member = shipmentPlanRequestItems
            };

            CreateInboundShipmentPlanRequest createInboundShipmentPlanRequest = new CreateInboundShipmentPlanRequest
            {
                InboundShipmentPlanRequestItems = inboundShipmentPlanRequestItemList,
                Marketplace     = m_marketPlaceId,
                SellerId        = m_sellerId,
                ShipFromAddress = shipsFromAddress
            };

            CreateInboundShipmentPlanResponse createInboundShipmentPlanResponse = m_fbaInboundServiceMwsClient.CreateInboundShipmentPlan(createInboundShipmentPlanRequest);

            CreateInboundShipmentPlanResult createInboundShipmentPlanResult = createInboundShipmentPlanResponse.CreateInboundShipmentPlanResult;

            if (createInboundShipmentPlanResult.InboundShipmentPlans.member.Any())
            {
                List <InboundShipmentPlan> inboundShipmentPlans = createInboundShipmentPlanResult
                                                                  .InboundShipmentPlans
                                                                  .member
                                                                  .ToList();

                Dictionary <string, ShipmentItem> itemsToBeAddedToShipment = createShipmentRequest
                                                                             .ShipmentItems.ToDictionary(k => k.Sku, v => v);

                DateTime today = DateTime.UtcNow.Date;

                List <CreatedShipment> createdShipments = inboundShipmentPlans
                                                          .Select(inboundShipmentPlan => CreateShipment(inboundShipmentPlan, itemsToBeAddedToShipment, shipsFromAddress, createShipmentRequest.ShipmentName, createShipmentRequest.AreCasesRequired, today))
                                                          .ToList();

                createShipmentResponse = new CreateShipmentResponse(createdShipments);
            }

            return(createShipmentResponse);
        }
Пример #8
0
        public static RuntimeServiceClient CreateServiceClient(string address)
        {
            var binding         = CreateBinding(TimeSpan.MaxValue);
            var ip              = AddressUtility.GetIPAddress(address);
            var port            = GetServicePort(address);
            var endPointAddress = new EndpointAddress($"net.tcp://{ip}:{port}/RuntimeService");

            return(new RuntimeServiceClient(binding, endPointAddress));
        }
        public void IsValidAddress_MultiSig()
        {
            var testAddress = "V2357pxG7ohXgqcVEdFrp5c1TGKfW0";

            bool bNormal = AddressUtility.IsValidAddress(testAddress);
            bool bMulti  = AddressUtility.IsValidMultisigAddress(testAddress);

            Assert.AreEqual(false, bNormal);
            Assert.AreEqual(true, bMulti);
        }
Пример #10
0
        public static CremaServiceContext Create(string address)
        {
            var serviceHost = new CremaServiceHost();

            return(new CremaServiceContext(serviceHost)
            {
                Host = AddressUtility.GetIPAddress(address),
                Port = AddressUtility.GetPort(address)
            });
        }
        public void IsValidAddress_Normal()
        {
            var testAddress = "VGKBNdQwed4PRnYCvnhDTaVJi2vmRs";

            bool bNormal = AddressUtility.IsValidAddress(testAddress);
            bool bMulti  = AddressUtility.IsValidMultisigAddress(testAddress);

            Assert.AreEqual(true, bNormal);
            Assert.AreEqual(false, bMulti);
        }
Пример #12
0
        public void ParseForEntireColumnSelections_ShouldAddMaxRowsOnColumnsWithMultipleLetters()
        {
            // Arrange
            var address = "AB:AC";

            // Act
            var result = AddressUtility.ParseEntireColumnSelections(address);

            // Assert
            Assert.AreEqual("AB1:AC" + ExcelPackage.MaxRows, result);
        }
Пример #13
0
        public void ParseForEntireColumnSelections_ShouldAddMaxRows()
        {
            // Arrange
            var address = "A:A";

            // Act
            var result = AddressUtility.ParseEntireColumnSelections(address);

            // Assert
            Assert.AreEqual("A1:A" + ExcelPackage.MaxRows, result);
        }
Пример #14
0
        public void ParseForEntireColumnSelections_ShouldHandleMultipleRanges()
        {
            // Arrange
            var address  = "A:A B:B";
            var expected = string.Format("A1:A{0} B1:B{0}", ExcelPackage.MaxRows);

            // Act
            var result = AddressUtility.ParseEntireColumnSelections(address);

            // Assert
            Assert.AreEqual(expected, result);
        }
Пример #15
0
        public Guid Open(string address, string userID, SecureString password)
        {
            if (this.isConnected == true)
            {
                throw new InvalidOperationException(Resources.Exception_AlreadyConnected);
            }

            this.ipAddress    = AddressUtility.GetIPAddress(address);
            this.serviceInfos = GetServiceInfo(address).ToDictionary(item => item.Name);

            this.OnOpening(EventArgs.Empty);
            return(this.dispatcher.Invoke(() =>
            {
                try
                {
                    this.address = AddressUtility.GetDisplayAddress(address);
                    this.log = new LogService(this.address.Replace(':', '_'), userID, AppUtility.UserAppDataPath);
                    this.log.Verbose = this.verbose;
                    this.userContext = new UserContext(this, this.ipAddress, serviceInfos[nameof(UserService)], userID, password);
                    var user = this.userContext.Users[userID];
                    user.SetUserState(UserState.Online);
                    this.userID = userID;
                    this.authority = user.Authority;

                    this.dataBases = new DataBaseCollection(this, this.ipAddress, serviceInfos[nameof(DataBaseCollectionService)]);
                    this.domainContext = new DomainContext(this, this.ipAddress, serviceInfos[nameof(DomainService)]);
                    this.isConnected = true;
                    this.configs = new CremaConfiguration(this.ConfigPath);
                    this.plugins = this.container.GetService(typeof(IEnumerable <IPlugin>)) as IEnumerable <IPlugin>;
                    foreach (var item in this.plugins)
                    {
                        var authentication = new Authentication(new AuthenticationProvider(user), item.ID);
                        this.authentications.Add(authentication);
                        item.Initialize(authentication);
                    }

                    this.OnOpened(EventArgs.Empty);
                    this.token = Guid.NewGuid();
                    CremaLog.Info($"Crema opened : {address} {userID}");
                    return token;
                }
                catch
                {
                    this.userContext?.Close(CloseInfo.Empty);
                    this.userContext = null;
                    this.log?.Dispose();
                    this.log = null;
                    this.address = null;
                    throw;
                }
            }));
        }
 private string CheckAndFixRangeAddress(string address)
 {
     if (address.Contains(','))
     {
         throw new FormatException("Multiple addresses may not be commaseparated, use space instead");
     }
     address = ConvertUtil._invariantTextInfo.ToUpper(address);
     if (Regex.IsMatch(address, @"[A-Z]+:[A-Z]+"))
     {
         address = AddressUtility.ParseEntireColumnSelections(address);
     }
     return(address);
 }
Пример #17
0
        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            AddressUtility adr = new AddressUtility();

            adr.Delivery_ID = DropDownList1.SelectedValue;
            adr.selectAddress();
            TextBoxAddressType.Text  = adr.Address_Type;
            TextBoxAddressLine1.Text = adr.AddressLine1;
            TextBoxAddressLine2.Text = adr.AddressLine2;
            TextBoxZipCode.Text      = adr.ZipCode;
            TextBoxPhone.Text        = adr.Phone;
            addressId = adr.Delivery_ID;
        }
Пример #18
0
        private void InstallService(string exeFilename, string basePath)
        {
            var pathArg            = string.Format("/PATH={0}", basePath);
            var portArg            = string.Format("/PORT={0}", this.Port);
            var httpPortArgs       = string.Format("/HTTPPORT={0}", this.HttpPort ?? AddressUtility.GetDefaultHttpPort(this.Port));
            var displayNameArg     = string.Format("/DisplayName={0}", this.DisplayName);
            var serviceNameArg     = string.Format("/ServiceName={0}", this.ServiceName);
            var comment            = string.Format("/Comment={0}", this.Comment);
            var commandLineOptions = new string[] { pathArg, portArg, displayNameArg, serviceNameArg, comment, httpPortArgs };
            var installer          = new AssemblyInstaller(exeFilename, commandLineOptions);

            installer.Install(null);
            installer.Commit(null);
        }
Пример #19
0
        /// <summary>
        /// Recalculate this <paramref name="range"/> with the specified <paramref name="options"/>.
        /// </summary>
        /// <param name="range">The range to be calculated.</param>
        /// <param name="options">Settings for this calculation.</param>
        /// <param name="setResultStyle">Indicates whether or not to set the cell's style based on the calculation result.</param>
        public static void Calculate(this ExcelRangeBase range, ExcelCalculationOption options, bool setResultStyle = false)
        {
            Init(range.myWorkbook);
            var parser = range.myWorkbook.FormulaParser;

            parser.InitNewCalc();
            if (range.IsName)
            {
                range = AddressUtility.GetFormulaAsCellRange(range.Worksheet.Workbook, range.Worksheet, range.Address);
            }
            var dc = DependencyChainFactory.Create(range, options);

            CalcChain(range.myWorkbook, parser, dc, setResultStyle);
        }
Пример #20
0
 public void SaveContact()
 {
     try
     {
         IContactModel model = new ContactModel();
         model.Name  = AddressUtility.checkName(Name);
         model.Email = AddressUtility.checkEmail(Email);
         model.Phone = AddressUtility.checkPhone(Phone);
         AddressBook.EditItemMenu(SaveModel.Email, model);
         EventAggregationProvider.EventAggregator.Publish(AddressBook.ListAllMenu());
         TryClose();
     }
     catch (AddressException ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Пример #21
0
        /// <summary>
        /// Check and fix an address (string address)
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public static string CheckAndFixRangeAddress(
            string address)
        {
            if (address.Contains(','))
            {
                throw new FormatException(
                          ExcelConditionalFormattingConstants.Errors.CommaSeparatedAddresses);
            }

            address = ConvertUtil._invariantTextInfo.ToUpper(address);

            if (Regex.IsMatch(address, @"[A-Z]+:[A-Z]+"))
            {
                address = AddressUtility.ParseEntireColumnSelections(address);
            }

            return(address);
        }
Пример #22
0
        private void InitCremaService()
        {
            var repoPath = DirectoryUtility.Prepare(CremaDbPath, "_repo");

            using (var bootstrap = new CremaBootstrapper())
            {
                bootstrap.CreateRepository(repoPath, "crema", false);
            }

            Service                = new CremaService();
            Service.BasePath       = repoPath;
            Service.MultiThreading = true;
            Service.Port           = 4004;
            Service.HttpPort       = AddressUtility.GetDefaultHttpPort(Service.Port);

            Service.Open();

            CremaHost = Service.GetService <ICremaHost>();
        }
Пример #23
0
        public static async Task <DataBaseInfo[]> GetDataBasesAsync(string address)
        {
            var serviceHost   = new CremaHostServiceHost();
            var clientContext = new ClientContext(serviceHost)
            {
                Host = AddressUtility.GetIPAddress(address),
                Port = AddressUtility.GetPort(address)
            };
            var token = Guid.Empty;

            try
            {
                token = await clientContext.OpenAsync();

                return(await serviceHost.GetDataBaseInfosAsync());
            }
            finally
            {
                await clientContext.CloseAsync(token, 0);
            }
        }
Пример #24
0
 public void AddContact()
 {
     try
     {
         var           name  = AddressUtility.checkName(Name);
         var           email = AddressUtility.checkEmail(Email);
         var           phone = AddressUtility.checkPhone(Phone);
         IContactModel cm    = new ContactModel();
         cm.Name  = name;
         cm.Email = email;
         cm.Phone = phone;
         AddressBook.AddItemMenu(cm);
         EventAggregationProvider.EventAggregator.Publish(AddressBook.ListAllMenu());
         MessageBox.Show(string.Format("Hello {0} {1} {2}!", Name, Email, Phone)); //Don't do this in real life :)
         TryClose();
     }
     catch (AddressException ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Пример #25
0
        /// <summary>
        /// Update the records in <see cref="ExcelPivotCacheRecords"/> and any referencing <see cref="ExcelPivotTable"/>s.
        /// </summary>
        /// <param name="resourceManager">The <see cref="ResourceManager"/> to retrieve translations from (optional).</param>
        public void UpdateData(ResourceManager resourceManager = null)
        {
            var sourceRange = this.GetSourceRangeAddress();

            // If the source range is an Excel pivot table or named range, resolve the address.
            if (sourceRange.IsName)
            {
                sourceRange = AddressUtility.GetFormulaAsCellRange(this.Workbook, sourceRange.Worksheet, sourceRange.Address);
            }

            // Update all cacheField names assuming the shape of the pivot cache definition source range remains unchanged.
            for (int col = sourceRange.Start.Column; col < sourceRange.Columns + sourceRange.Start.Column; col++)
            {
                int fieldIndex = col - sourceRange.Start.Column;
                this.CacheFields[fieldIndex].Name = sourceRange.Worksheet.Cells[sourceRange.Start.Row, col].Value.ToString();
            }

            // Update all cache record values.
            var worksheet = sourceRange.Worksheet;
            var range     = new ExcelRange(worksheet, worksheet.Cells[sourceRange.Start.Row + 1, sourceRange.Start.Column, sourceRange.End.Row, sourceRange.End.Column]);

            this.CacheRecords.UpdateRecords(range);

            this.StringResources.LoadResourceManager(resourceManager);

            // Refresh pivot tables.
            foreach (var pivotTable in this.GetRelatedPivotTables())
            {
                pivotTable.RefreshFromCache(this.StringResources);
            }

            // Remove the 'u' xml attribute from each cache item to prevent corrupting the workbook, since Excel automatically adds them.
            foreach (var cacheField in this.CacheFields)
            {
                if (cacheField.HasSharedItems)
                {
                    cacheField.RemoveXmlUAttribute();
                }
            }
        }
Пример #26
0
        protected void ButtonCheckOut_Click(object sender, EventArgs e)
        {
            AddressUtility adr = new AddressUtility();

            if (String.IsNullOrEmpty(addressId))
            {
                /*if (adr.addressIsRepeat())
                 * {
                 *  addressId = adr.Delivery_ID;
                 *  DropDownList1.Items.FindByValue(addressId).Selected = true;
                 * }
                 * else
                 * {*/
                adr.Address_Type = TextBoxAddressType.Text;
                adr.UserName     = Session["user"].ToString();
                adr.Phone        = TextBoxPhone.Text;
                adr.AddressLine1 = TextBoxAddressLine1.Text;
                adr.AddressLine2 = TextBoxAddressLine2.Text;
                adr.ZipCode      = TextBoxZipCode.Text;
                adr.insertAddress();
                addressId = adr.Delivery_ID;
                //}
            }
            ShoppingCartUtility cart = new ShoppingCartUtility();

            cart.ID = Request.QueryString["id"].ToString();
            cart.readRecordById();
            OrderUtility order = new OrderUtility();

            order.PizzaSize   = cart.PizzaSize;
            order.PizzaStyle  = cart.PizzaStyle;
            order.Price       = cart.Price;
            order.Toppings    = cart.Toppings;
            order.UserName    = cart.UserName;
            order.Delivery_ID = addressId;
            order.insertOrder();
            cart.removeRecord();
            Response.Redirect("Thanks.aspx?OrderID=" + order.OrderId);
        }
        public void IsValidAddress_Bad()
        {
            String[] astr = new string[]
            {
                "",
                null,
                "XYZ",
                "01234562-*73738434",
                "V2399990",
                "VGKBNdQwed4PRnYCvnhDTaVJi2vmRs--------",
                "VGKBNdQwed4PRnYCvnhDTaVJi2vmR"
            };

            foreach (String testAddress in astr)
            {
                bool bNormal = AddressUtility.IsValidAddress(testAddress);
                bool bMulti  = AddressUtility.IsValidMultisigAddress(testAddress);

                Assert.AreEqual(false, bNormal);
                Assert.AreEqual(false, bMulti);
            }
        }
        internal void SetAddress(string address)
        {
            var dvAddress = AddressUtility.ParseEntireColumnSelections(address);

            SetXmlNodeString(_sqrefPath, dvAddress);
        }
Пример #29
0
 /// <summary>
 /// Attempts to parse the <see cref="NameFormula"/> as an address, evaluating reference functions and
 /// nested named ranges as necessary.
 /// </summary>
 /// <returns>The formula as an <see cref="ExcelRangeBase"/> if it is an address, null otherwise.</returns>
 public ExcelRangeBase GetFormulaAsCellRange()
 {
     return(AddressUtility.GetFormulaAsCellRange(this.Workbook, this.LocalSheet, this.NameFormula));
 }
Пример #30
0
        public async Task Accept()
        {
            // Add cancellation token to allow cancel from any point calling Dispose()
            _server._connectionManager.AddConnection(this);
            _cancellationTokenSource = new CancellationTokenSource();
            Interlocked.Exchange(ref _timeoutTimestamp, DateTime.UtcNow.Add(_server.Options.LiveTimeout).Ticks);

            try
            {
                _stream = _client.GetStream();
                if (_server.Certificate != null)
                {
                    var ssl = new SslStream(_stream, false);
                    await ssl.AuthenticateAsServerAsync(_server.Certificate);

                    _stream = ssl;
                }
                _reader           = new System.IO.StreamReader(_stream);
                _writer           = new System.IO.StreamWriter(_stream);
                _writer.AutoFlush = true;

                Kooboo.Mail.Smtp.SmtpSession session = new Smtp.SmtpSession(this.Client.Address.ToString());

                // Service ready
                await WriteLineAsync(session.ServiceReady().Render());

                var commandline = await _reader.ReadLineAsync();

                var cancellationToken = _cancellationTokenSource.Token;
                while (!cancellationToken.IsCancellationRequested && commandline != null)
                {
                    var response = session.Command(commandline);
                    if (response.SendResponse)
                    {
                        var responseline = response.Render();
                        await WriteLineAsync(responseline);
                    }

                    if (response.SessionCompleted)
                    {
                        await Kooboo.Mail.Transport.Incoming.Receive(session);

                        session.ReSet();
                    }

                    if (response.Close)
                    {
                        Dispose();
                        break;
                    }

                    // When enter the session state, read till the end .
                    if (session.State == SmtpSession.CommandState.Data)
                    {
                        var externalto = AddressUtility.GetExternalRcpts(session);
                        var counter    = externalto.Count();

                        Kooboo.Data.Log.Instance.Email.Write("--recipants");
                        Kooboo.Data.Log.Instance.Email.WriteObj(externalto);
                        Kooboo.Data.Log.Instance.Email.WriteObj(session.Log);

                        if (counter > 0)
                        {
                            if (!Kooboo.Data.Infrastructure.InfraManager.Test(session.OrganizationId, Data.Infrastructure.InfraType.Email, counter))
                            {
                                await WriteLineAsync("550 you have no enough credit to send emails");

                                Dispose();
                                break;
                            }
                        }

                        var data = await _stream.ReadToDotLine(TimeSpan.FromSeconds(60));

                        var dataresponse = session.Data(data);

                        if (dataresponse.SendResponse)
                        {
                            await WriteLineAsync(dataresponse.Render());
                        }

                        if (dataresponse.SessionCompleted)
                        {
                            await Kooboo.Mail.Transport.Incoming.Receive(session);

                            var tos = session.Log.Keys.Where(o => o.Name == SmtpCommandName.RCPTTO);

                            string subject = "TO: ";
                            if (tos != null)
                            {
                                foreach (var item in tos)
                                {
                                    if (item != null && !string.IsNullOrWhiteSpace(item.Value))
                                    {
                                        subject += item.Value;
                                    }
                                }
                            }

                            if (counter > 0)
                            {
                                Kooboo.Data.Infrastructure.InfraManager.Add(session.OrganizationId, Data.Infrastructure.InfraType.Email, counter, subject);
                            }

                            session.ReSet();

                            OnDataCompleted();
                        }

                        if (dataresponse.Close)
                        {
                            Dispose();
                        }
                    }

                    if (!cancellationToken.IsCancellationRequested)
                    {
                        commandline = await _reader.ReadLineAsync();
                    }
                }
            }
            catch (ObjectDisposedException)
            {
                // Caused by our active connection closing, no need to handle as exception
            }
            catch (Exception ex)
            {
                try
                {
                    if (_client.Connected)
                    {
                        await WriteLineAsync("550 Internal Server Error");
                    }
                }
                catch
                {
                }
                Kooboo.Data.Log.Instance.Exception.Write(ex.Message + "\r\n" + ex.StackTrace + "\r\n" + ex.Source);
            }
            finally
            {
                _server._connectionManager.RemoveConnection(Id);
                Dispose();
            }
        }