/// <summary>
        /// Método usado para criar mais companias, referenciando as novas companias, � 1� compania
        /// Ou compania de referência
        /// </summary>
        /// <param name="company"></param>
        /// <param name="userId"></param>
        /// <param name="companyId"></param>
        /// <returns></returns>
        public InsertCompanyStatus InsertCompany(Company company, int userId, int matrixCompanyId)
        {
            if (GetCompany(company.LegalEntityProfile.CNPJ) != null)
                return InsertCompanyStatus.DuplicateCNPJ;

            var profileManager = new ProfileManager(this);
            LegalEntityProfile original_legalEntityProfile;

            //
            // update the legalEntityProfile
            //
            if (company.LegalEntityProfile != null)
            {
                original_legalEntityProfile = profileManager.GetLegalEntityProfile(company.LegalEntityProfile.CNPJ);
                if (original_legalEntityProfile != null)
                {
                    //update the legalEntityProfile
                    if (!String.IsNullOrEmpty(company.LegalEntityProfile.CompanyName))
                        original_legalEntityProfile.CompanyName = company.LegalEntityProfile.CompanyName;

                    if (!String.IsNullOrEmpty(company.LegalEntityProfile.FantasyName))
                        original_legalEntityProfile.FantasyName = company.LegalEntityProfile.FantasyName;

                    original_legalEntityProfile.Email = company.LegalEntityProfile.Email;
                    original_legalEntityProfile.IE = company.LegalEntityProfile.IE;
                    original_legalEntityProfile.Phone = company.LegalEntityProfile.Phone;
                    original_legalEntityProfile.Address = company.LegalEntityProfile.Address;
                    original_legalEntityProfile.AddressComp = company.LegalEntityProfile.AddressComp;
                    original_legalEntityProfile.AddressNumber = company.LegalEntityProfile.AddressNumber;
                    profileManager.DbContext.SubmitChanges();

                    company.LegalEntityProfile = original_legalEntityProfile;
                }
            }



            //
            //Method to insert a new company
            //
            company.CreatorUserId = userId;
            Insert(company);
            company.ReferenceCompanyId = company.CompanyId;
            company.MatrixId = company.CompanyId;
            if (matrixCompanyId != 0)
            {
                company.ReferenceCompanyId = GetCompany(matrixCompanyId).ReferenceCompanyId;
                company.MatrixId = matrixCompanyId;
            }
            DbContext.SubmitChanges();

            //
            //Method to create a Deposit
            //
            Deposit dep = CreateMatrixDeposit(company.CompanyId);

            //
            //method to create a new role to this company
            //
            Role role = CreateAdminRole(company.CompanyId);

            //
            //method to set all permissions writable to the admin
            //
            var pManager = new PlanManager(this);
            Plan plan = pManager.GetCurrentPlan(company.CompanyId);
            if (plan != null)
            {
                CreatePermissions(plan.PlanId, role.RoleId, company.CompanyId);
            }

            //
            //method to associate the user with the company
            //
            AssociateUser(company.CompanyId, userId, dep.DepositId, /*IsMain*/ true);

            //
            //method to associate the user with the role
            //
            AddUserInRoles(userId, company.CompanyId, role.RoleId);

            //
            // method to create a customer under the Host "Vivina", with the company data of the user
            //
            AddContactInHostCustomer(AddCompanyAsCustomer(company), userId);

            //
            // Configurate the company inserting template of the Best Pratices, Report, etc.
            //
            SetCompanyConfiguration(company);

            //
            // Configure home page
            //
            CreateHomePage(company, userId);

            //SetCompanyPaymentMethods(company);

            return InsertCompanyStatus.Success;
        }
        /// <summary>
        /// M�todo usado para criar a primeira companhia, utilizado na tela de registro
        /// </summary>
        /// <param name="newCompany"></param>
        /// <param name="newUser"></param>
        /// <param name="newProfile"></param>
        /// <returns></returns>
        public InsertCompanyStatus InsertMatrixCompany(Company newCompany, User newUser, Profile profile)
        {
            //
            // Insert the profile
            //
            var pManager = new ProfileManager(this);

            // Profile profile = pManager.GetProfile(newProfile.CPF) ?? newProfile;
            //if (profile.ProfileId == 0)
            pManager.Insert(profile);
            //else
            //{
            //    profile.Name = newProfile.Name;
            //    profile.Email = newProfile.Email;
            //    profile.PostalCode = newProfile.PostalCode;
            //    //profile.Address = newProfile.Address;
            //    profile.AddressComp = newProfile.AddressComp;
            //    profile.AddressNumber = newProfile.AddressNumber;
            //    profile.Phone = newProfile.Phone;
            //    DbContext.SubmitChanges();
            //}

            //
            //Insert Admin user
            //
            Int32 UserId;
            //newUser.ProfileId
            DataClasses.User original_User = GetUserByUserName(newUser.Email);
            if (original_User != null)
            {
                UserId = original_User.UserId;
            }
            else
            {
                MembershipCreateStatus status;
                var membershipManager = new MembershipManager(this);
                newUser.ProfileId = profile.ProfileId;
                membershipManager.Insert(
                    newUser,
                    out status,
                    (Membership.Provider as VivinaMembershipProvider).RequiresValidEmail);

                //
                //verify if the status of the inclusion are ok
                //
                if (status != MembershipCreateStatus.Success)
                {
                    DataManager.Rollback();
                    switch (status)
                    {
                        case MembershipCreateStatus.DuplicateUserName:
                            return InsertCompanyStatus.DuplicatedUserName;
                        case MembershipCreateStatus.InvalidPassword:
                            return InsertCompanyStatus.InvalidPassword;
                        case MembershipCreateStatus.DuplicateEmail:
                            return InsertCompanyStatus.DuplicatedAdminEmail;
                        default:
                            return InsertCompanyStatus.InvalidUser;
                    }
                }
                UserId = newUser.UserId;
            }

            if (newCompany.LegalEntityProfile.IsLiberalProfessional)
                newCompany.LegalEntityProfile.CompanyName = newCompany.LegalEntityProfile.FantasyName = profile.Name;

            var insertCompanyStatus = InsertCompany(newCompany, UserId, 0);

            newCompany.ReferenceCompanyId = newCompany.CompanyId;
            newCompany.MatrixId = newCompany.CompanyId;
            DbContext.SubmitChanges();

            return insertCompanyStatus;
        }
        /// <summary>
        /// Method to add a new COMPANY in a CUSTOMER of the HOST COMPANY
        /// </summary>
        /// <param name="newCompany"></param>
        private Int32 AddCompanyAsCustomer(Company newCompany)
        {
            var customerManager = new CustomerManager(this);

            var customer = new Customer();
            customer.CompanyId = GetHostCompany().CompanyId;
            customer.LegalEntityProfileId = newCompany.LegalEntityProfileId;
            if (customerManager.ExistCustomer(customer))
                customer = customerManager.GetCustomerByLegalEntityProfile(customer.CompanyId,
                                                                           Convert.ToInt32(customer.LegalEntityProfileId));
            else
                customerManager.Insert(customer);
            return customer.CustomerId;
        }
 public void RefreshCompany()
 {
     _company = null;
     Session["_company"] = null;
 }
        /// <summary>
        /// Save the entity
        /// </summary>
        /// <param name="entity"></param>
        public void Save(Company company, Statement statement)
        {
            //
            // Create invoice for the related customer
            //
            statement.StatementTotal = statement.StatementItems.Sum(x => x.Value);
            var list = new List<Parcel>();
            list.Add(new Parcel()
            {
                DueDate = statement.PeriodEnd.AddDays(15),
                Amount = statement.StatementTotal
            });

            var financialManager = new FinancialManager(this);
            var invoice = ConvertStatementToInvoice(company, statement);
            financialManager.Insert(invoice, list);

            //
            // Update data
            //
            statement.Invoice = invoice;
            company.NextStatementDueDate = company.NextStatementDueDate.AddMonths(1);

            //
            // Save statement
            //
            if (statement.StatementId > 0)
            {
                var original = GetStatement(statement.StatementId);
                original.CopyPropertiesFrom(statement);
            }
            else
                DbContext.Statements.InsertOnSubmit(statement);


            DbContext.SubmitChanges();
        }
        /// <summary>
        /// Add all payment methods to the company after configure
        /// </summary>
        /// <param name="company"></param>
        //private void SetCompanyPaymentMethods(Company company)
        //{
        //    PaymentMethodManager manager = new PaymentMethodManager(this);
        //    foreach (PaymentMethod paymentMethod in DbContext.PaymentMethods)
        //    {
        //        CompanyPaymentMethod companyPaymentMethod = new CompanyPaymentMethod();
        //        companyPaymentMethod.PaymentMethodId = paymentMethod.PaymentMethodId;
        //        companyPaymentMethod.CompanyId = company.CompanyId;
        //        manager.InsertCompanyPaymentMethod(companyPaymentMethod);
        //    }
        //}
        /// <summary>
        /// Configurate the company inserting template of the Best Pratices, Report, etc.
        /// </summary>
        /// <param name="company"></param>
        private void SetCompanyConfiguration(Company company)
        {
            //
            //Method to create a Company Configuration
            //
            InsertCompanyConfiguration(new CompanyConfiguration(), company);

            //
            // Accounting Plan
            //
            var accountManager = new AccountManager(this);
            accountManager.RegisterAccountingPlanTemplate(company.CompanyId);

            //
            // Cost Center
            //
            accountManager.RegisterCostCenterTemplate(company.CompanyId);
        }
        /// <summary>
        /// Method to make a search in the company table
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public DataTable SearchCompanies(Company entity)
        {
            string sql =
                "SELECT *,CompanyId,CAST (0 AS bit) as status FROM Company INNER JOIN LegalEntityProfile ON Company.LegalEntityProfileId=LegalEntityProfile.LegalEntityProfileId ";
            string where = "";
            if (entity != null)
            {
                if (!String.IsNullOrEmpty(entity.Activities))
                {
                    DataManager.Parameters.Add("@Activities", "%" + entity.Activities + "%");
                    where = where + " Activities like @Activities AND";
                }

                if (!String.IsNullOrEmpty(entity.LegalEntityProfile.CNPJ))
                {
                    DataManager.Parameters.Add("@CNPJ", "%" + entity.LegalEntityProfile.CNPJ + "%");
                    where = where + " CNPJ like @CNPJ AND";
                }

                if (!String.IsNullOrEmpty(entity.LegalEntityProfile.FantasyName))
                {
                    DataManager.Parameters.Add("@FantasyName", "%" + entity.LegalEntityProfile.FantasyName + "%");
                    where = where + " FantasyName like @FantasyName AND";
                }
                if (!String.IsNullOrEmpty(entity.LegalEntityProfile.IE))
                {
                    DataManager.Parameters.Add("@IE", "%" + entity.LegalEntityProfile.IE + "%");
                    where = where + " IE like @IE AND";
                }
                if (!String.IsNullOrEmpty(entity.LegalEntityProfile.Email))
                {
                    DataManager.Parameters.Add("@Mail", "%" + entity.LegalEntityProfile.Email + "%");
                    where = where + " Email like @Mail AND";
                }
                if (!String.IsNullOrEmpty(entity.LegalEntityProfile.CompanyName))
                {
                    DataManager.Parameters.Add("@Name", "%" + entity.LegalEntityProfile.CompanyName + "%");
                    where = where + " CompanyName like @Name AND";
                }
                if (!String.IsNullOrEmpty(entity.LegalEntityProfile.PostalCode))
                {
                    DataManager.Parameters.Add("@PostalCode", "%" + entity.LegalEntityProfile.PostalCode + "%");
                    where = where + " PostalCode like @PostalCode AND";
                }
                if (entity.NextStatementDueDate != DateTime.MinValue)
                {
                    DataManager.Parameters.Add("@NextDueDate", "%" + entity.NextStatementDueDate + "%");
                    where = where + " NextDueDate like @NextDueDate AND";
                }

                if (entity.StartDate != DateTime.MinValue)
                {
                    DataManager.Parameters.Add("@StartDate", "%" + entity.StartDate + "%");
                    where = where + " StartDate like @StartDate AND";
                }
                if (!String.IsNullOrEmpty(entity.LegalEntityProfile.Phone))
                {
                    DataManager.Parameters.Add("@Telephone", "%" + entity.LegalEntityProfile.Phone + "%");
                    where = where + " Telephone like @Telephone AND";
                }
                if (!String.IsNullOrEmpty(entity.LegalEntityProfile.Website))
                {
                    DataManager.Parameters.Add("@WebSite", "%" + entity.LegalEntityProfile.Website + "%");
                    where = where + " WebSite like @WebSite AND";
                }
                if (where != "")
                {
                    sql += " where" + where.Remove(where.Length - 3, 3);
                }
            }
            return DataManager.ExecuteDataTable(sql);
        }
        /// <summary>
        /// Calculate and generate the statements from a period
        /// </summary>
        /// <param name="company"></param>
        /// <param name="beginPeriod"></param>
        /// <param name="endPeriod"></param>
        internal void GenerateStatement(Company company)
        {
            var statement = new Statement()
            {
                CompanyId = company.CompanyId,
                PeriodBegin = company.NextStatementDueDate.Date.AddMonths(-1),
                PeriodEnd = company.NextStatementDueDate.Date.AddSeconds(-1),
                Name = "Relatório de Utilização do InfoControl (" + company.NextStatementDueDate.AddMonths(-1).ToString("MM/yyyy") + ")"
            };

            ProcessStatementItemActiveUsers(company, statement);

            ProcessStatementItemSite(company, statement);

            Save(company, statement);
        }
        internal void ProcessStatementItemActiveUsers(Company company, Statement statement)
        {
            var item = new StatementItem();
            item.Name = "Usuários";
            item.UnitCost = company.Plan.Package.Price;
            item.Quantity = UserActivesInMonth(statement.CompanyId, statement.PeriodBegin, statement.PeriodEnd);
            item.Value = company.Plan.Package.Price * item.Quantity;

            statement.StatementItems.Add(item);
        }
        private Int32 GenerateAutomaticDebitFileContent(StringBuilder strBuilderContent, Company company,
                                                        Account account, List<Parcel> parcels)
        {
            /* Função responsavel pela configuração do documento de débito automatico.Modelo definido pela FEBRABAN
             * 
             * O modelo/Código é dividido por blocos definidos por letras
             * 
             * Os campos alfanuméricos são representados por letras A e os numéricos por 0
             * Sendo que os campos default estão preenchidos com seus valores corretos
             * 
             * 
             * O modelo de comentário é: Tamanho do campo - descrição do campo
             *
             */


            Int32 totalRows = 0;
            foreach (Parcel parcel in parcels)
            {
                if (!parcel.InvoiceId.HasValue || !parcel.Invoice.CustomerId.HasValue)
                    continue;
                /// B
                {
                    String B_registerCode = "B"; //1

                    String B_customerIdentificationAtCompany = parcel.Invoice.Customer.LegalEntityProfile != null
                                                                   ? parcel.Invoice.Customer.LegalEntityProfile.
                                                                         CompanyName
                                                                   : parcel.Invoice.Customer.Profile.Name;
                    //25 - Identificação única do cliente
                    B_customerIdentificationAtCompany.PadRight(20, ' ').Substring(0, 20);

                    if (parcel.Invoice.Customer.Agency == null) parcel.Invoice.Customer.Agency = String.Empty;
                    String B_debitAgency = parcel.Invoice.Customer.Agency.PadRight(4, ' ').Substring(0, 4); //4

                    if (parcel.Invoice.Customer.AccountNumber == null)
                        parcel.Invoice.Customer.AccountNumber = String.Empty;
                    String B_customerIdentificationAtBank =
                        parcel.Invoice.Customer.AccountNumber.PadRight(14, ' ').Substring(0, 14);
                    //14 -Identificação única utilizada pelo banco

                    String B_optionDate = DateTime.Now.ToShortDateString(); //8
                    String B_reservedSpace = String.Empty.PadLeft(97, ' '); //97
                    String B_operationCode = "1"; //1

                    strBuilderContent.Append(B_registerCode).Append(B_customerIdentificationAtCompany).Append(
                        B_debitAgency);
                    strBuilderContent.Append(B_customerIdentificationAtCompany).Append(B_optionDate).Append(
                        B_reservedSpace).Append(B_operationCode);

                    strBuilderContent.AppendLine();
                    totalRows++;
                }

                /// C
                {
                    String C_registerCode = "C"; //1
                    String C_customerIdentificationAtCompany =
                        parcel.Invoice.Customer.CustomerId.ToString().PadRight(25, ' ').Substring(0, 25); //25
                    String C_debitAgency = parcel.Invoice.Customer.Agency.PadRight(4, ' ').Substring(0, 4); //4
                    String C_customerIdentificationAtBank =
                        parcel.Invoice.Customer.AccountNumber.PadRight(14, ' ').Substring(0, 14);
                    //14 -Identificação única utilizada pelo banco
                    String C_firstOcurrence = String.Empty.PadLeft(40, ' '); //40
                    String C_secondOcurrence = String.Empty.PadLeft(40, ' '); //40
                    String C_reservedSpace = String.Empty.PadLeft(40, ' '); //40
                    String C_operationCode = "2"; //1

                    strBuilderContent.Append(C_registerCode).Append(C_customerIdentificationAtBank).Append(C_debitAgency)
                        .Append(C_customerIdentificationAtBank);
                    strBuilderContent.Append(C_firstOcurrence).Append(C_secondOcurrence).Append(C_reservedSpace).Append(
                        C_operationCode);
                    strBuilderContent.AppendLine();
                    totalRows++;
                }

                ///D
                {
                    String D_registerCode = "C"; //1
                    String D_customerIdentificationAtOriginalCompany = String.Empty.PadLeft(25, ' ');
                    //25 - Identificação do cliente na empresa antiga
                    String D_debitAgency = String.Empty.PadLeft(4, ' '); //4
                    String D_customerIdentificationAtBank = String.Empty.PadLeft(14, ' ');
                    //14 -Identificação única utilizada pelo banco
                    String D_customerIdentificationAtNewCompany = String.Empty.PadLeft(25, ' ');
                    //25 - Identificação do cliente na empresa nova
                    String D_Ocurrence = String.Empty.PadLeft(60, ' '); //60
                    String D_reservedSpace = String.Empty.PadLeft(20, ' '); //20
                    String D_operationCode = "0"; //1

                    strBuilderContent.Append(D_registerCode).Append(D_customerIdentificationAtOriginalCompany).Append(
                        D_debitAgency);
                    strBuilderContent.Append(D_customerIdentificationAtBank).Append(D_customerIdentificationAtNewCompany)
                        .Append(D_Ocurrence);
                    strBuilderContent.Append(D_reservedSpace).Append(D_operationCode);

                    strBuilderContent.AppendLine();
                    totalRows++;
                }

                ///E
                {
                    String E_registerCode = "E"; //1
                    String E_customerIdentificationAtCompany =
                        parcel.Invoice.Customer.CustomerId.ToString().PadRight(25, ' ').Substring(0, 25); //25
                    String E_debitAgency = String.Empty.PadLeft(4, ' '); //4
                    String E_customerIdentificationAtBank =
                        parcel.Invoice.Customer.AccountNumber.PadRight(14, ' ').Substring(0, 14);
                    //14 -Identificação única utilizada pelo banco
                    String E_dueDate = parcel.DueDate.ToShortDateString(); //8
                    String E_debitValue = "000000000000000".PadLeft(15, '0'); //15
                    String E_currencyCode = "03"; //2
                    String E_spaceForCompanyUse = String.Empty.PadLeft(60, ' '); //60
                    String E_reservedSpace = String.Empty.PadLeft(20, ' '); //20
                    String E_operationCode = "0"; //1

                    strBuilderContent.Append(E_registerCode).Append(E_customerIdentificationAtCompany).Append(
                        E_debitAgency);
                    strBuilderContent.Append(E_customerIdentificationAtCompany).Append(E_dueDate).Append(E_debitValue).
                        Append(E_currencyCode);
                    strBuilderContent.Append(E_spaceForCompanyUse).Append(E_reservedSpace).Append(E_operationCode);


                    strBuilderContent.AppendLine();
                    totalRows++;
                }
            }


            return totalRows;
        }
        /// <summary>
        /// Insert a CompanyConfiguration
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="companyId"></param>
        public void InsertCompanyConfiguration(CompanyConfiguration configuration, Company company)
        {
            DbContext.CompanyConfigurations.InsertOnSubmit(configuration);
            DbContext.SubmitChanges();

            company.CompanyConfigurationId = configuration.CompanyConfigurationId;
            DbContext.SubmitChanges();
        }
        private Int32 GenerateAutomaticDebitFileHeader(StringBuilder strBuilderHeader, Company company, Account account,
                                                       Int32 sequentialNumber)
        {
            /* Função responsavel pela configuração do documento de débito automatico.Modelo definido pela FEBRABAN
            * 
            * O modelo/Código é dividido por blocos definidos por letras
            * 
            * Os campos alfanuméricos são representados por letras A e os numéricos por 0
            * Sendo que os campos default estão preenchidos com seus valores corretos
            * 
            * 
            * O modelo de comentário é: Tamanho do campo - descrição do campo
            *
            */

            /// A - Header

            Int32 totalRows = 0;

            String A_registerCode = "A"; //1 - Default
            String A_deliveryCode = "1"; //1 - Default
            String A_conveneCode = "00000000000000000000"; //20 -Definido pelo banco
            String A_companyName = company.LegalEntityProfile.CompanyName.PadRight(20, ' ').Substring(0, 20); //20-
            String A_bankCode = account.Bank.BankNumber.PadLeft(3, '0').Substring(0, 3);
            //3-Código do banco na câmara de compensação
            String A_BankName = account.Bank.ShortName.PadRight(20, ' ');
            String A_createdDate = DateTime.Now.ToShortDateString(); //8
            String A_SequentialNumber = sequentialNumber.ToString().PadLeft(6, '0'); //6-
            String A_layoutVersion = "04"; //2
            String A_serviceIdentification = "DÉBITO AUTOMÁTICO"; //17
            String A_reservedSpace = String.Empty.PadLeft(52, ' '); //52

            strBuilderHeader.Append(A_registerCode).Append(A_deliveryCode).Append(A_conveneCode).Append(A_companyName);
            strBuilderHeader.Append(A_BankName).Append(A_createdDate).Append(A_SequentialNumber).Append(A_layoutVersion)
                .Append(A_serviceIdentification).Append(A_reservedSpace);
            strBuilderHeader.AppendLine();
            totalRows++;

            return totalRows;
        }
        public String GenerateAutomaticDebitFile(Company company, Account account, List<Parcel> parcels,
                                                 Int32 sequentialNumber)
        {
            var strBuilderAutomaticDebitFile = new StringBuilder();
            Int32 totalRows = 0;
            totalRows = GenerateAutomaticDebitFileHeader(strBuilderAutomaticDebitFile, company, account,
                                                         sequentialNumber);
            totalRows += GenerateAutomaticDebitFileContent(strBuilderAutomaticDebitFile, company, account, parcels);
            GenerateAutomaticDebitFileTrailler(strBuilderAutomaticDebitFile, parcels, totalRows);

            return strBuilderAutomaticDebitFile.ToString(0, strBuilderAutomaticDebitFile.Length);
        }
 public void Add(Company company)
 {
     this.company = company;
 }
 private void CreateHomePage(Company company, int userId)
 {
     var manager = new SiteManager(this);
     manager.Save(new WebPage
                      {
                          CompanyId = company.CompanyId,
                          Name = "Página Principal",
                          IsPublished = true,
                          PublishedDate = DateTime.Now,
                          ModifiedDate = DateTime.Now,
                          IsMainPage = true,
                          UserId = userId
                      }, null);
 }
        internal void ProcessStatementItemActiveProducts(Company company, Statement statement)
        {
            var item = new StatementItem();
            item.Name = "Produtos";
            item.Quantity = company.Products.Count();
            item.Value = 0.08m * item.Quantity;
            statement.StatementItems.Add(item);

            item = new StatementItem();
            item.Name = "Imagens de Produtos";
            item.Quantity = company.Products.Sum(p => p.ProductImages.Count());
            item.Value = 0.04m * item.Quantity;
            statement.StatementItems.Add(item);
        }
        private void ConfigureDNSRecords(Company company)
        {
            try
            {
                string zoneTemplate = "zone \"[website]\" IN {type master;file \"zones\\db.[website].txt\";allow-transfer {none;};};";

                File.AppendAllText("D:\\dns\\etc\\named.conf",
                                   zoneTemplate.Replace("[website]", company.LegalEntityProfile.Website),
                                   Encoding.UTF8);

                zoneTemplate = File.ReadAllText("D:\\dns\\etc\\zones\\template.txt", Encoding.UTF8);
                zoneTemplate = zoneTemplate.Replace("[website]", company.LegalEntityProfile.Website);

                File.WriteAllText("D:\\dns\\etc\\zones\\db." + company.LegalEntityProfile.Website + ".txt",
                                  zoneTemplate,
                                  Encoding.UTF8);

            }
            catch { }
        }
        internal void ProcessStatementItemSite(Company company, Statement statement)
        {
            if (!String.IsNullOrEmpty(company.LegalEntityProfile.Website))
            {
                statement.StatementItems.Add(new StatementItem()
                {
                    Name = "Manutenção do Site",
                    Quantity = 1,
                    Value = 50.00m
                });

                ProcessStatementItemActiveProducts(company, statement);
            }
        }
        /// <summary>
        /// This method returns the Admin Company
        /// </summary>
        /// <returns></returns>
        public Company GetHostCompany()
        {
            if (_hostCompany != null)
                return _hostCompany;

            _hostCompany = (from company in DbContext.Companies
                            where company.CompanyId == 1
                            select company).FirstOrDefault();

            _hostCompany.LegalEntityProfile.GetHashCode();
            _hostCompany.LegalEntityProfile.Address.GetHashCode();
            _hostCompany.LegalEntityProfile.Address.City.GetHashCode();
            _hostCompany.LegalEntityProfile.Address.Neighborhood.GetHashCode();
            _hostCompany.Plan.GetHashCode();
            _hostCompany.User.GetHashCode();

            return _hostCompany;
        }
 private Invoice ConvertStatementToInvoice(Company company, Statement statement)
 {
     var customerManager = new CustomerManager(this);
     return new Invoice()
     {
         CompanyId = GetHostCompany().CompanyId,
         CustomerId = customerManager.GetCustomerByLegalEntityProfile(GetHostCompany().CompanyId, company.LegalEntityProfileId).CustomerId,
         EntryDate = DateTime.Now,
         Description = "Manutenção InfoControl"
     };
 }
        /// <summary>
        /// this method insert the productImage
        /// </summary>
        /// <param name="productImage"></param>
        public void InsertProductImage(Company company, ProductImage entity, HttpPostedFile file)
        {
            string virtualPath = company.GetFilesDirectory();
            string fileName = Path.GetFileName(file.FileName);
            entity.ImageUrl = virtualPath + fileName; // set the ImageUrl
            file.SaveAs(HttpContext.Current.Server.MapPath(entity.ImageUrl)); //save the file

            InsertProductImage(entity);
        }
        /// <summary>
        /// This method sends the budget to customer by email 
        /// </summary>
        /// <param name="budgetId"> can't be null</param>
        /// <param name="company">can't be null</param>
        /// <param name="addressFileToAttach"> address of file to attach in email. 
        /// If this parameter is null, the budget(at .html version) will send in body of email.
        /// </param>
        public void SendBudgetToCustomer(int budgetId, Company company, Int32 budgetDocumentTemplateId, string addressFileToAttach)
        {
            Budget budget = GetBudget(budgetId, company.CompanyId);

            budget.BudgetStatusId = (int)BudgetStatus.SentToCustomer;
            DbContext.SubmitChanges();

            string customerMail = budget.CustomerMail ?? budget.Customer.Email;
            string mailBody = String.Empty;

            // case not exist file to attach, the budget is sended in body's email 
            if (String.IsNullOrEmpty(addressFileToAttach))
            {
                mailBody = ApplyBudgetTemplate(budget, budgetDocumentTemplateId).Replace("</body>",
                   "<br /><br />Caso tenha gostado do orçamento e deseja concluir a compra " +
                            "basta clicar no link abaixo:<br />" +
                            "<a href='http://" + company.LegalEntityProfile.Website + "/site/Checkout_Basket.aspx?b=" + budgetId.ToString() +
                            " '>Efetuar Compra</a> ou copie o seguinte endereço no seu navegador: " +
                            company.LegalEntityProfile.Website + "/site/Checkout_Basket.aspx?b=" + budgetId.ToString() + "</body>");
            }
            else
            {
                mailBody = "<br />Caso tenha gostado do orçamento(veja o orçamento no arquivo em anexo) e deseja concluir a compra " +
                                "basta clicar no link abaixo:<br />" +
                                "<a href='http://" + company.LegalEntityProfile.Website + "/site/Checkout_Basket.aspx?b=" + budgetId.ToString() +
                                " '>Efetuar Compra</a> ou copie o seguinte endereço no seu navegador: " +
                                company.LegalEntityProfile.Website + "/site/Checkout_Basket.aspx?b=" + budgetId.ToString();
            }

            Postman.Send(
                "*****@*****.**",
                customerMail,
                "Orçamento solicitado no site " + company.LegalEntityProfile.Website,
                mailBody, new[] { addressFileToAttach });
        }