Наследование: MonoBehaviour
Пример #1
0
        private void buttonOK_Click(object sender, EventArgs e)
        {
            UseWaitCursor = true;
            Application.DoEvents();

            try
            {
                if (spotHandelDesisionSixtyDay == null)
                    spotHandelDesisionSixtyDay = new SpotHandelDesisionSixtyDay();

                GetEntity(spotHandelDesisionSixtyDay);

                Company company = new Company
                {
                    CompanyName = HandleComp.Text,
                };
                InvokeUtil.SystemService.UpdateCompanyByName(company);

                Officers officer1 = new Officers { OfficersName = OfficerName1.Text, CID = CID1.Text };
                InvokeUtil.SystemService.UpdateOfficersByArgs(officer1);

                Officers officer2 = new Officers { OfficersName = OfficerName2.Text, CID = CID2.Text };
                InvokeUtil.SystemService.UpdateOfficersByArgs(officer2);

                InvokeUtil.SystemService.EntityUpdate(spotHandelDesisionSixtyDay);
                CloseWindow();
            }
            catch (Exception ex)
            {
                CommonInvoke.ErrorMessageBox(ex);
            }

            UseWaitCursor = false;
        }
    /// <summary>
    /// Run the code example.
    /// </summary>
    /// <param name="user">The DFP user object running the code example.</param>
    public override void Run(DfpUser user) {
      // Get the CompanyService.
      CompanyService companyService =
          (CompanyService) user.GetService(DfpService.v201508.CompanyService);

      // Create an array to store local company objects.
      Company[] companies = new Company[5];

      for (int i = 0; i < 5; i++) {
        Company company = new Company();
        company.name = string.Format("Advertiser #{0}", i);
        company.type = CompanyType.ADVERTISER;
        companies[i] = company;
      }

      try {
        // Create the companies on the server.
        companies = companyService.createCompanies(companies);

        if (companies != null && companies.Length > 0) {
          foreach (Company company in companies) {
            Console.WriteLine("A company with ID = '{0}', name = '{1}' and type = '{2}' was" +
                " created.", company.id, company.name, company.type);
          }
        } else {
          Console.WriteLine("No companies created.");
        }
      } catch (Exception e) {
        Console.WriteLine("Failed to create company. Exception says \"{0}\"", e.Message);
      }
    }
Пример #3
0
    protected void Page_Load(object sender, EventArgs e)
    {
        rptEntities.DataSource = companyFac.GetAllEntities();
        rptEntities.DataBind();

        int id = Convert.ToInt32(Request.QueryString["ID"]);
        if (id != 0)
        {
            ShowCompany.Attributes.Remove("hidden");
            comp = companyFac.GetEntityByID(id);
            PopulateFields();
        }
        else if (Request.QueryString["NewItem"] == "true")
        {
            ShowCompany.Attributes.Remove("hidden");
            comp = new Company();
        }
        else if (Convert.ToInt32(Request.QueryString["DID"]) > 0)
        {
            int deleteID = Convert.ToInt32(Request.QueryString["DID"]);

            companyFac.Delete(deleteID);

            var uri = new Uri(Request.Url.AbsoluteUri);
            string path = uri.GetLeftPart(UriPartial.Path);
            Response.Redirect(path);
        }
    }
        public void ExplicitFlushInsideSecondTransactionProblem()
        {
            var comp1 = new Company("comp1");
            var comp2 = new Company("comp2");
            using(new SessionScope())
            {
                comp1.Create();
                comp2.Create();
            }

            using(new SessionScope(FlushAction.Never))
            {
                using(var tx = new TransactionScope(ondispose: OnDispose.Rollback))
                {
                    var comp2a = Company.Find(comp2.Id);
                    comp2a.Name = "changed";
                    tx.VoteCommit();
                }

                using(var scope = new TransactionScope(ondispose: OnDispose.Rollback))
                {
                    var changedCompanies = AR.FindAllByProperty<Company>("Name", "changed");
                    Assert.AreEqual(1, changedCompanies.Count());
                    var e2a = changedCompanies.First();
                    e2a.Delete();

                    scope.Flush();

                    Assert.AreEqual(0, AR.FindAllByProperty<Company>("Name", "changed").Count());
                }
            }
        }
Пример #5
0
		public void WillAbortDeleteIfUserDoesNotHavePermissions()
		{
			var company = new Company
			{
				Name = "Hibernating Rhinos"
			};
			using (var s = store.OpenSession())
			{
				s.Store(new AuthorizationUser
				{
					Id = UserId,
					Name = "Ayende Rahien",
				});

				s.Store(company);

				s.SetAuthorizationFor(company, new DocumentAuthorization());// deny everyone

				s.SaveChanges();
			}

			using (var s = store.OpenSession())
			{
				s.SecureFor(UserId, "/Company/Rename");

				Assert.Throws<InvalidOperationException>(() => s.DatabaseCommands.Delete(company.Id, null));
			}
		}
Пример #6
0
		public void Can_perform_a_simple_projection_in_a_linq_query()
		{
			using (var store = NewDocumentStore())
			{

				var entity = new Company { Name = "Simple Company", Id = "companies/1" };
				using (var session = store.OpenSession())
				{
					session.Store(entity);
					session.SaveChanges();
				}

				using (var session = store.OpenSession())
				{
					var results = session.Query<Company>()
						.Customize(x => x.WaitForNonStaleResults())
						.Where(x => x.Name == "Simple Company")
						.Select(x => new TheCompanyName { Name = x.Name })
						.ToList();

					Assert.Equal(1, results.Count);
					Assert.Equal("Simple Company", results[0].Name);
				}
			}
		}
Пример #7
0
 public CompInput(string name, Company company, float price, string partInterface, int powerRequirement, float defectiveChance, int mouseDPI, int pollingRate, bool isMechanical)
     : base(name, company, price, partInterface, powerRequirement, defectiveChance)
 {
     this.mouseDPI       = mouseDPI;
     this.pollingRate    = pollingRate;
     this.isMechanical   = isMechanical;
 }
Пример #8
0
    static void Main()
    {
        Individual ivan = new Individual("Ivan");
        Company tech = new Company("Tech OOD");

        MortageAcount firstAcc = new MortageAcount(ivan, 1000, 3);

        MortageAcount mortAcc = new MortageAcount(tech, 20000, 10);

        Console.WriteLine(mortAcc.CalculateInterestAmount(10)); //10 months * 10% / 2 = 10months * 5% from 20 000 = 10 000

        Console.WriteLine(mortAcc.CalculateInterestAmount(24)); //12m * 5% from 20000 and 12m * 10 % from 20000 = 12*1000 + 12*2000 = 36 000

        Console.WriteLine(firstAcc.CalculateInterestAmount(7)); //only 1 month (first 6 are no rate) * 3% from 1000 = 30

        DepositAcount depAcc = new DepositAcount(ivan, 700, 20);

        Console.WriteLine(depAcc.CalculateInterestAmount(99999)); // 0 - amount is 700 which is positive and less than 1000

        LoanAcount loanIndivid = new LoanAcount(ivan, 10000, 10);
        LoanAcount loanCompany = new LoanAcount(tech, 100000, 15);

        Console.WriteLine(loanIndivid.CalculateInterestAmount(3)); // 0 - free 3 months
        Console.WriteLine(loanIndivid.CalculateInterestAmount(4)); // free 3 months --> 1 * 10% from 10000 = 1000

        Console.WriteLine(loanCompany.CalculateInterestAmount(2)); // 0 - free 3 months
        Console.WriteLine(loanCompany.CalculateInterestAmount(4)); // free 2 months --> 2 * 15% from 100000 = 30000
    }
Пример #9
0
        public Company Create(Company company)
        {
            if (company == null)
                throw new ArgumentNullException(nameof(company));

            if (string.IsNullOrEmpty(company.CompanyName))
                throw new ValidationException("Company name cannot be empty.");

            if(company.CompanyName.Length > 200)
                throw new ValidationException("Company name cannot exceed 200 characters.");

            var existing = Get(company.CompanyName);

            if (existing != null)
                throw new ValidationException("Company with same name already exists.");

            var result = new Company
            {
                CompanyName = company.CompanyName
            };

            _context.Companies.Add(result);

            _context.SaveChanges();

            return result;
        }
Пример #10
0
        public void CanReadDocumentWhichWasNotSecured()
        {
            var company = new Company
            {
                Name = "Hibernating Rhinos"
            };
            using (var s = store.OpenSession(DatabaseName))
            {
                s.Store(new client::Raven.Bundles.Authorization.Model.AuthorizationUser
                {
                    Id = UserId,
                    Name = "Ayende Rahien",
                });

                s.Store(company);

                // by not specifying that, we say that anyone can read this
                //s.SetAuthorizationFor(company, new DocumentAuthorization());

                s.SaveChanges();
            }

            using (var s = store.OpenSession(DatabaseName))
            {
                client::Raven.Client.Authorization.AuthorizationClientExtensions.SecureFor(s, UserId, "Company/Bid");

                Assert.NotNull(s.Load<Company>(company.Id));
            }
        }
Пример #11
0
        public void WillAbortWriteIfUserDoesNotHavePermissions()
        {
            var company = new Company
            {
                Name = "Hibernating Rhinos"
            };
            using (var s = store.OpenSession(DatabaseName))
            {
                s.Store(new client::Raven.Bundles.Authorization.Model.AuthorizationUser
                {
                    Id = UserId,
                    Name = "Ayende Rahien",
                });

                s.Store(company);

                client::Raven.Client.Authorization.AuthorizationClientExtensions.SetAuthorizationFor(s, company, new client::Raven.Bundles.Authorization.Model.DocumentAuthorization());// deny everyone

                s.SaveChanges();
            }

            using (var s = store.OpenSession(DatabaseName))
            {
                client::Raven.Client.Authorization.AuthorizationClientExtensions.SecureFor(s, UserId, "Company/Rename");
                company.Name = "Stampeding Rhinos";
                s.Store(company);

                var e = Assert.Throws<ErrorResponseException>(() => s.SaveChanges());

                Assert.Contains("OperationVetoedException", e.Message);
                Assert.Contains("PUT vetoed on document companies/1", e.Message);
                Assert.Contains("Raven.Bundles.Authorization.Triggers.AuthorizationPutTrigger", e.Message);
                Assert.Contains("Could not find any permissions for operation: Company/Rename on companies/1 for user Authorization/Users/Ayende", e.Message);
            }
        }
Пример #12
0
        public void ShouldNotBeNullTest() {
            Company company = null;
            Assert.Throws<ArgumentNullException>(() => company.ShouldNotBeNull("company"));

            Company company2 = new Company();
            company2.ShouldNotBeNull("company2");
        }
Пример #13
0
        public void CannotReadDocumentWithoutPermissionToIt()
        {
            var company = new Company
            {
                Name = "Hibernating Rhinos"
            };
            using (var s = store.OpenSession(DatabaseName))
            {
                s.Store(new client::Raven.Bundles.Authorization.Model.AuthorizationUser
                {
                    Id = UserId,
                    Name = "Ayende Rahien",
                });

                s.Store(company);

                client::Raven.Client.Authorization.AuthorizationClientExtensions.SetAuthorizationFor(s, company, new client::Raven.Bundles.Authorization.Model.DocumentAuthorization());// deny everyone

                s.SaveChanges();
            }

            using (var s = store.OpenSession(DatabaseName))
            {
                client::Raven.Client.Authorization.AuthorizationClientExtensions.SecureFor(s, UserId, "Company/Bid");

                var readVetoException = Assert.Throws<ReadVetoException>(() => s.Load<Company>(company.Id));

                Assert.Equal(@"Document could not be read because of a read veto.
The read was vetoed by: Raven.Bundles.Authorization.Triggers.AuthorizationReadTrigger
Veto reason: Could not find any permissions for operation: Company/Bid on companies/1 for user Authorization/Users/Ayende.
No one may perform operation Company/Bid on companies/1
", readVetoException.Message);
            }
        }
        public void Created_Audit_Fields_Should_be_Set_After_Save_With_Children()
        {
            CompanyIdentification companyIdentification1 =
                new CompanyIdentification
                {
                    Identification = "1"
                };
            CompanyIdentification companyIdentification2 =
                new CompanyIdentification
                {
                    Identification = "2"
                };
            Company company =
                new Company
                {
                    Name = "Peopleware NV",
                    Identifications = new[] { companyIdentification1, companyIdentification2 }
                };

            Company savedCompany = Repository.Save(company);

            Assert.AreSame(company, savedCompany);
            Assert.AreEqual(UserName, company.CreatedBy);
            Assert.AreEqual(m_Now, company.CreatedAt);

            Assert.AreEqual(2, company.Identifications.Count);
            foreach (CompanyIdentification companyIdentification in company.Identifications)
            {
                Assert.AreEqual(UserName, companyIdentification.CreatedBy);
                Assert.AreEqual(m_Now, companyIdentification.CreatedAt);
            }
        }
Пример #15
0
        public static void saveCompany(Company company)
        {
            try
            {
                using (db = new TIB_Model())
                {
                    if (company.Id != 0)
                    {
                        db.Company.Attach(company);
                        db.Entry(company).State = EntityState.Modified;
                    }
                    else
                    {
                        db.Company.Add(company);
                    }

                    db.SaveChanges();
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #16
0
 public ActionResult Edit()
 {
     Company company = new Company();
     BusinessLogicHandler myHandler = new BusinessLogicHandler();
     company = myHandler.GetCompanyDetail();
     return View(company);
 }
        /// <summary>
        /// Get a security token
        /// </summary>
        /// <param name="company"></param>
        /// <param name="scope"></param>
        /// <param name="invalidateCache">if set to true, requests a new token even if a valid one is already in the cache</param>
        /// <returns></returns>
        public Token Get(Company company = null, string scope = "panoptix.read", bool invalidateCache = false)
        {
            var now = DateTime.UtcNow;
            Token token;

            // so that instances created by different applications (as indicated by id passed at construction) don't clobber each other
            var cacheKey = String.Format("{0}:{1}:{2}", clientId, company == null ? string.Empty: company.Id, scope);

            // check to see if we already have a token that will be valid for at least the next five minutes
            if (!invalidateCache && Cache.ContainsKey(cacheKey) && Cache[cacheKey].ExpirationTime > now.AddMinutes(5))
            {
                token = Cache[cacheKey];
            }
            else
            {
                var contentList = new List<KeyValuePair<string, string>>
                        {
                            new KeyValuePair<string, string>("grant_type", "client_credentials")
                        };

                if (company != null && company.Id != null)
                {
                    contentList.Add(new KeyValuePair<string, string>("jci_company_id", company.Id));
                    contentList.Add(new KeyValuePair<string, string>("scope", scope));
                }

                token = FetchToken(company, cacheKey, Cache, contentList);
            }
            return token;
        }
Пример #18
0
        public void DocumentWithoutPermissionWillBeFilteredOutSilently()
        {
            var company = new Company
            {
                Name = "Hibernating Rhinos"
            };
            using (var s = store.OpenSession())
            {
                s.Store(new AuthorizationUser
                {
                    Id = UserId,
                    Name = "Ayende Rahien",
                });

                s.Store(company);

                s.SetAuthorizationFor(company, new DocumentAuthorization());// deny everyone

                s.SaveChanges();
            }

            using (var s = store.OpenSession())
            {
                s.SecureFor(UserId, "Company/Bid");

                Assert.Equal(0, s.Advanced.LuceneQuery<Company>()
                                    .WaitForNonStaleResults()
                                    //.ToList()
                                    .Lazily().Value
                                    .Count());
            }
        }
		public void Understanding()
		{
			using (var documentStore = NewDocumentStore())
			{
				#region session_usage_1
				string companyId;
				using (var session = documentStore.OpenSession())
				{
					var entity = new Company { Name = "Company" };
					session.Store(entity);
					session.SaveChanges();
					companyId = entity.Id;
				}

				using (var session = documentStore.OpenSession())
				{
					var entity = session.Load<Company>(companyId);
					Console.WriteLine(entity.Name);
				}
				#endregion

				#region session_usage_2
				using (var session = documentStore.OpenSession())
				{
					var entity = session.Load<Company>(companyId);
					entity.Name = "Another Company";
					session.SaveChanges(); // will send the change to the database
				}
				#endregion
			}
		}
Пример #20
0
    private static void Main()
    {
        Customer customerOne = new Individual("Radka Piratka");
        Customer customerTwo = new Company("Miumiunali Brothers");

        Account[] accounts =
        {
            new Deposit(customerOne, 7000, 5.5m, 18),
            new Deposit(customerOne, 980, 5.9m, 12),
            new Loan(customerOne, 20000, 7.2m, 2),
            new Loan(customerOne, 2000, 8.5m, 9),
            new Mortgage(customerOne, 14000, 5.4m, 5),
            new Mortgage(customerOne, 5000, 4.8m, 10),
            new Deposit(customerTwo, 10000, 6.0m, 12),
            new Mortgage(customerTwo, 14000, 6.6m, 18),
            new Loan(customerTwo, 15000, 8.9m, 2),
            new Loan(customerTwo, 7000, 7.5m, 12),
        };

        foreach (Account account in accounts)
        {
            Console.WriteLine(account);
        }

        Deposit radkaDeposit = new Deposit(customerOne, 980, 5.9m, 12);
        Deposit miumiuDeposit = new Deposit(customerTwo, 10000, 6.0m, 12);

        Console.WriteLine();
        Console.WriteLine("Current balance: {0}", radkaDeposit.WithdrawMoney(150));
        Console.WriteLine("Current balance: {0}", radkaDeposit.DepositMoney(1500));
        Console.WriteLine("Current balance: {0}", miumiuDeposit.WithdrawMoney(5642));
        Console.WriteLine("Current balance: {0}", miumiuDeposit.DepositMoney(1247));
    }
        public void Should_Create_Company()
        {
            try
            {
                var personContext = new PersonsContext();
                var uow = new UnitOfWork<PersonsContext>();
                var companyRepository = new CompanyRepository(uow);
                var company = new Company
                {
                    Name = "P",
                    Email = "*****@*****.**"
                };

                companyRepository.Add(company);

                Assert.IsNotNull(personContext.Companies.FirstOrDefault(c => c.Name == "P"));
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                         Console.WriteLine(("Property: {0} Error: {1}"), validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }
        }
Пример #22
0
 public Connector1C(Company c, bool enableDebug = false)
 {
     string logFileName = DateTime.Now.ToString().Replace(":", "-");
     importLogFile = new StreamWriter(logFileName + ".txt");
     this.DEBUG = enableDebug;
     this.company = c;
 }
        public void DirtyCheckingTest()
        {
            CompanyIdentification companyIdentification1 =
                new CompanyIdentification
                {
                    Identification = "1"
                };
            CompanyIdentification companyIdentification2 =
                new CompanyIdentification
                {
                    Identification = "2"
                };
            Company company =
                new Company
                {
                    Name = "Peopleware NV",
                    Identifications = new[] { companyIdentification1, companyIdentification2 }
                };
            Repository.Save(company);
            Session.Evict(company);

            /* Set Number to null (but Number is defined as int) */
            /*
            using (ISession session = NhConfigurator.SessionFactory.OpenSession())
            {
                using (ITransaction trans = session.BeginTransaction())
                {
                    session.CreateQuery(@"update CompanyIdentification set Number = null").ExecuteUpdate();
                    trans.Commit();
                }
            }
            */
            new DirtyChecking(NhConfigurator.Configuration, NhConfigurator.SessionFactory, Assert.Fail, Assert.Inconclusive).Test();
        }
 protected Company GetDataForm()
 {
     Company company = new Company();
     if (!string.IsNullOrEmpty(txtName.Text))
     {
         company.Company_Name = txtName.Text;
     }
     else
     {
         return null;
     }
     company.Company_Phone = txtPhoneNumber.Text;
     company.Company_Email = txtEmail.Text;
     company.Company_Address = txtAddress.Text;
     company.Company_Description = txtDescription.Text;
     string filePath = "";
     System.Drawing.Image image;
     if (fuLogo.HasFile)
     {
         image = System.Drawing.Image.FromStream(fuLogo.PostedFile.InputStream);
     }
     else
     {
         filePath = WebHelper.Instance.GetWebsitePath() + "App_Themes/images/other/no_image.png";
         image = System.Drawing.Image.FromFile(filePath);
     }
     String data = WebHelper.Instance.ImageToBase64(image, System.Drawing.Imaging.ImageFormat.Png);
     company.Company_Logo = data;
     return company;
 }
        public void saveUpdateCompany(Company company)
        {
            CompanyFrm cFrm = new CompanyFrm(company);
            bool result = (bool)cFrm.ShowDialog();
            cFrm.Close();

            if (result)
            {
                try
                {
                    Generic<Company> gen = new Generic<Company>();
                    if (company.Id == 0)
                        gen.Add(company);
                    else
                        gen.Update(company, company.Id);

                    gen.Dispose();
                    MessageBox.Show("The company was saved successfully", "Company saved", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    Console.Write(ex.ToString());
                    MessageBox.Show("There was a problem saving this company to the database. Please try again later or contact a sysadmin.", "Database Error", MessageBoxButton.OK, MessageBoxImage.Information);
                }

                // reload companies and refresh ListBox
                loadCompanies();
            }
        }
Пример #26
0
        public void Will_limit_replication_history_size_on_items_marked_with_not_for_replication()
        {
            var store1 = CreateStore();

            using (var session = store1.OpenSession())
            {
                var entity = new Company {Name = "Hibernating Rhinos"};
                session.Store(entity);
                session.Advanced.GetMetadataFor(entity)["Raven-Not-For-Replication"] = "true";
                session.SaveChanges();
            }

            for (int i = 0; i < 100; i++)
            {
                using (var session = store1.OpenSession())
                {
                    var company = session.Load<Company>(1);
                    company.Name = i%2 == 0 ? "a" : "b";
                    session.SaveChanges();
                }
            }

            using (var session = store1.OpenSession())
            {
                var company = session.Load<Company>(1);
                var ravenJArray = session.Advanced.GetMetadataFor(company).Value<RavenJArray>(Constants.RavenReplicationHistory);
                Assert.Equal(50, ravenJArray.Length);
            }

        }
Пример #27
0
       private void Init()
       {
           if (settings==null)
           {
               throw new ArgumentNullException("Please provide valid SAP Settings");
           }
           if(_company==null)
           {
               
               _company = new Company
                              {
                                  language = BoSuppLangs.ln_English,
                                  Server = settings.ServerName,
                                  DbServerType =BoDataServerTypes.dst_MSSQL2008,//(BoDataServerTypes)Enum.Parse(typeof(BoDataServerTypes), settings.Servertype),
                                  UseTrusted = false,
                                  DbPassword = settings.DbPassword,
                                  DbUserName = settings.Dbusrname,
                                  UserName = settings.UserName,
                                  Password = settings.Password,
                                  CompanyDB = settings.CompanyName,
                                // LicenseServer = "10.0.0.2:3000"

                              };
               ConnectToCompany();
               return;
           }
           ConnectToCompany();
           
       }
Пример #28
0
    protected void cmpRegister(object sender, EventArgs e)
    {
        Company cmp = new Company();
        bool signed = false;
        if (validator.checkCompanyEmail(registerEmail))
        {
            registerEmail.Attributes["placeholder"] = "This mail address is in use.";
            return;
        }
        validateRegister();
        if (confirmRegister)
        {
            cmp.CompanyName = registerCompanyName.Text;
            cmp.Email = registerEmail.Text;
            cmp.Password = registerPassword.Text;
            cmp.Address = registerAddress.Text;
            cmp.Phone = registerPhone.Text;
            cmp.CityID = int.Parse(registerCity.SelectedValue);
            signed = cmp.SignUp();
        }

        if (signed)
        {
            Session["Company"] = cmp;

            Response.Redirect("Home.aspx");
        }
    }
Пример #29
0
 static double SumUpSalaries(Company c)
 {
     return
         (from e in c.Query.Descendants<EmployeeType>()
          select e.Salary
         ).Sum();
 }
Пример #30
0
        private void buttonOK_Click(object sender, EventArgs e)
        {
            UseWaitCursor = true;
            Application.DoEvents();

            try
            {
                if (reviewOptionApprove == null)
                    reviewOptionApprove = new ReviewOptionApprove();

                GetEntity(reviewOptionApprove);

                Company company = new Company
                {
                    CompanyName = Party.Text,
                    CompanyAddress = PartyAddress.Text,
                    JuridicalPerson = LegalRepre.Text,
                    Mobile = Tel.Text
                };
                InvokeUtil.SystemService.UpdateCompanyByName(company);

                InvokeUtil.SystemService.EntityUpdate(reviewOptionApprove);
                CloseWindow();
            }
            catch (Exception ex)
            {
                CommonInvoke.ErrorMessageBox(ex);
            }

            UseWaitCursor = false;
        }
Пример #31
0
        private void Seed(MyDataContext context)
        {
            var roleAdmin = new Role {
                Id = 1, Name = "Administrator", Description = "Administrator"
            };
            var roleSuperUser = new Role {
                Id = 2, Name = "SuperUser", Description = "Super User"
            };
            var roleApplicationUser = new Role {
                Id = 4, Name = "ApplicationUser", Description = "Application User"
            };

            context.Roles.Add(roleAdmin);
            context.Roles.Add(roleSuperUser);
            context.Roles.Add(roleApplicationUser);
            context.SaveChanges();

            var userAdmin = new User {
                Id = 1, IdentityName = "admin", DisplayName = "admin", EmailAddress = "*****@*****.**", Roles = new List <Role>()
            };

            userAdmin.Roles.Add(roleAdmin);
            userAdmin.Roles.Add(roleSuperUser);
            userAdmin.Roles.Add(roleApplicationUser);
            context.Users.Add(userAdmin);

            var superUser = new User {
                Id = 2, IdentityName = "super user", DisplayName = "super user", EmailAddress = "*****@*****.**", Roles = new List <Role>()
            };

            superUser.Roles.Add(roleSuperUser);
            superUser.Roles.Add(roleApplicationUser);
            context.Users.Add(superUser);

            var appUser = new User {
                Id = 3, IdentityName = "app user", DisplayName = "app user", EmailAddress = "*****@*****.**", Roles = new List <Role>()
            };

            appUser.Roles.Add(roleApplicationUser);
            context.Users.Add(appUser);

            context.SaveChanges();

            var functionIct = new Function {
                Id = 1, Code = "ICT", Name = "ICT"
            };
            var functionManagement = new Function {
                Id = 2, Code = "MAN", Name = "Management"
            };
            var functions = new List <Function> {
                functionIct, functionManagement
            };

            functions.ForEach(s => context.Functions.Add(s));
            context.SaveChanges();

            for (int i = 1; i <= 10; i++)
            {
                var subFunctionIct = new SubFunction {
                    Id = 1, Code = "ICT-" + i, Name = "ICT - " + i, Function = functionIct
                };
                context.SubFunctions.Add(subFunctionIct);
            }
            for (int i = 1; i <= 5; i++)
            {
                var subFunctionManagement = new SubFunction {
                    Id = 1, Code = "MAN-" + i, Name = "Management - " + i, Function = functionManagement
                };
                context.SubFunctions.Add(subFunctionManagement);
            }
            context.SaveChanges();

            var countryNL = new Country {
                Id = 1, Code = "NL", Name = "The Netherlands"
            };
            var countryBE = new Country {
                Id = 2, Code = "BE", Name = "Belgium"
            };
            var countries = new List <Country> {
                countryNL, countryBE
            };

            countries.ForEach(c => context.Countries.Add(c));
            context.SaveChanges();

            var mainCompany1 = new MainCompany {
                Id = 10, Name = "M - 1"
            };
            var mainCompany2 = new MainCompany {
                Id = 20, Name = "M - 2"
            };
            var mainCompanies = new List <MainCompany> {
                mainCompany1, mainCompany2
            };

            mainCompanies.ForEach(x => context.MainCompanies.Add(x));
            context.SaveChanges();

            var companyA = new Company {
                Id = 1, Name = "A", MainCompany = mainCompany1
            };
            var companyB = new Company {
                Id = 2, Name = "B", MainCompany = mainCompany1
            };
            var companyC = new Company {
                Id = 3, Name = "C", MainCompany = mainCompany2
            };
            var companies = new List <Company> {
                companyA, companyB, companyC
            };

            companies.ForEach(x => context.Companies.Add(x));
            context.SaveChanges();

            var employees = new List <Employee>
            {
                new Employee {
                    Id = 1, Assigned = null, Country = countryNL, Company = companyA, FirstName = "Bill", LastName = "Smith", Email = "*****@*****.**", EmployeeNumber = 1001, HireDate = Convert.ToDateTime("01/12/1990"), Function = functionManagement, SubFunction = functionManagement.SubFunctions.First()
                },
                new Employee {
                    Id = 2, Assigned = 1, Country = countryNL, Company = companyB, FirstName = "Jack", LastName = "Smith", Email = "*****@*****.**", EmployeeNumber = 1002, HireDate = Convert.ToDateTime("12/12/1997"), Function = functionManagement, SubFunction = functionManagement.SubFunctions.First()
                },
                new Employee {
                    Id = 3, Assigned = 2, Country = countryNL, Company = companyC, FirstName = "Mary", LastName = "Gates", Email = "*****@*****.**", EmployeeNumber = 1003, HireDate = Convert.ToDateTime("03/03/2000"), Function = functionIct, SubFunction = functionIct.SubFunctions.ToArray()[1]
                },
                new Employee {
                    Id = 4, Assigned = null, Country = countryNL, Company = companyA, FirstName = "John", LastName = "Doe", Email = "*****@*****.**", EmployeeNumber = 1004, HireDate = Convert.ToDateTime("11/11/2011"), Function = functionIct, SubFunction = functionIct.SubFunctions.ToArray()[2]
                },
                new Employee {
                    Id = 5, Assigned = 0, Country = countryBE, Company = companyB, FirstName = "Chris", LastName = "Cross", Email = "*****@*****.**", EmployeeNumber = 1005, HireDate = Convert.ToDateTime("05/05/1995"), Function = functionIct, SubFunction = functionIct.SubFunctions.ToArray()[3]
                },
                new Employee {
                    Id = 6, Assigned = 1, Country = countryBE, Company = companyC, FirstName = "Niki", LastName = "Myers", Email = "*****@*****.**", EmployeeNumber = 1006, HireDate = Convert.ToDateTime("06/05/1995"), Function = functionIct, SubFunction = functionIct.SubFunctions.ToArray()[4]
                },
                new Employee {
                    Id = 7, Assigned = null, Country = countryBE, Company = companyA, FirstName = "Joseph", LastName = "Hall", Email = "*****@*****.**", EmployeeNumber = 1007, HireDate = Convert.ToDateTime("07/05/1995"), Function = functionIct, SubFunction = functionIct.SubFunctions.ToArray()[5]
                },
                new Employee {
                    Id = 8, Assigned = 0, Country = countryBE, Company = companyB, FirstName = "Daniel", LastName = "Wells", Email = "*****@*****.**", EmployeeNumber = 1008, HireDate = Convert.ToDateTime("08/05/1995"), Function = functionIct, SubFunction = functionIct.SubFunctions.ToArray()[6]
                },
                new Employee {
                    Id = 9, Assigned = 1, Country = countryNL, Company = companyC, FirstName = "Robert", LastName = "Lawrence", Email = "*****@*****.**", EmployeeNumber = 1009, HireDate = Convert.ToDateTime("09/05/1995"), Function = functionIct, SubFunction = functionIct.SubFunctions.ToArray()[7]
                },
                new Employee {
                    Id = 10, Assigned = 0, Country = countryNL, Company = companyA, FirstName = "Reginald", LastName = "Quinn", Email = "*****@*****.**", EmployeeNumber = 1010, HireDate = Convert.ToDateTime("10/05/1995"), Function = functionIct, SubFunction = functionIct.SubFunctions.ToArray()[8]
                },
                new Employee {
                    Id = 11, Assigned = 2, Country = countryNL, Company = companyB, FirstName = "Quinn", LastName = "Quick", Email = "*****@*****.**", EmployeeNumber = 1011, HireDate = Convert.ToDateTime("11/05/1995"), Function = functionIct, SubFunction = functionIct.SubFunctions.ToArray()[9]
                },
                new Employee {
                    Id = 12, Assigned = null, Country = countryNL, Company = companyC, FirstName = "Test", LastName = "User", Email = "*****@*****.**", EmployeeNumber = 1012, HireDate = Convert.ToDateTime("11/05/2012"), Function = functionIct, SubFunction = functionIct.SubFunctions.ToArray()[0]
                },
            };

            employees.ForEach(x => context.Employees.Add(x));
            context.SaveChanges();

            var products = new List <Product>
            {
                new Product {
                    Id = 1, Code = "AR-5381", Name = "Adjustable Race"
                },
                new Product {
                    Id = 2, Code = "BA-8327", Name = "Bearing Ball"
                },
                new Product {
                    Id = 3, Code = "BE-2349", Name = "BB Ball Bearing"
                },
                new Product {
                    Id = 4, Code = "BE-2908", Name = "Headset Ball Bearings"
                },
                new Product {
                    Id = 316, Code = "BL-2036", Name = "Blade"
                },
                new Product {
                    Id = 317, Code = "CA-5965", Name = "LL Crankarm"
                },
                new Product {
                    Id = 318, Code = "CA-6738", Name = "ML Crankarm"
                },
                new Product {
                    Id = 319, Code = "CA-7457", Name = "HL Crankarm"
                },
                new Product {
                    Id = 320, Code = "CB-2903", Name = "Chainring Bolts"
                },
                new Product {
                    Id = 321, Code = "CN-6137", Name = "Chainring Nut"
                },
                new Product {
                    Id = 322, Code = "CR-7833", Name = "Chainring"
                }
            };

            products.ForEach(x => context.Products.Add(x));
            context.SaveChanges();

            const int numOUs    = 5000;
            var       generator = new LipsumGenerator();
            var       list      = new List <OU>();

            for (int i = 1000000; i < 1000000 + numOUs; i++)
            {
                var ou = new OU
                {
                    Code = i.ToString(CultureInfo.InvariantCulture),
                    Name = string.Join(" ", generator.GenerateWords(3))
                };

                list.Add(ou);
            }

            BulkInsert(context, context.OUs, list);
        }
Пример #32
0
        public ActionResult Edit(CompanyEditView editView, int[] selectedIndustries, string submitbutton)
        {
            if (editView.company.name == null)
            {
                TempData["EmptyName"] = ViewData;
                return(RedirectToAction("Edit", editView.company.Id));
            }
            if (!editView.company.isMinMaxGood())
            {
                TempData["MinMax"] = ViewData;
                return(RedirectToAction("Edit", editView.company.Id));
            }
            Company comp = new Company();

            if (submitbutton == "Save")
            {
                comp = dbNew.Companies.Find(editView.company.Id);
                if (comp == null)
                {
                    return(HttpNotFound());
                }
            }

            if (comp.name != editView.company.name && dbNew.Companies.FirstOrDefault(co => co.name == editView.company.name) != null)
            {
                TempData["NameExist"] = ViewData;
                return(RedirectToAction("Edit", comp.Id));
            }
            else
            {
                comp.Industries.Clear();
                comp.getCompanyChanges(editView.company);

                if (editView.company.PrimaryIndustryId == null && selectedIndustries != null)
                {
                    comp.PrimaryIndustryId = selectedIndustries[new Random().Next(0, selectedIndustries.Count())];
                }
                else if (editView.company.PrimaryIndustryId != null && selectedIndustries == null)
                {
                    comp.Industries.Add(dbNew.Industries.Find(editView.company.PrimaryIndustryId));
                }


                // comp.Industries.Clear();
                if (selectedIndustries != null)
                {
                    //получаем выбранные курсы
                    foreach (var c in dbNew.Industries.Where(ind => selectedIndustries.Contains(ind.Id)))
                    {
                        comp.Industries.Add(c);
                    }
                }


                if (submitbutton == "Save")
                {
                    dbNew.Entry(comp).State = EntityState.Modified;
                }
                else
                {
                    dbNew.Companies.Add(comp);
                }
                dbNew.SaveChanges();
                return(RedirectToAction("Index"));
            }
        }
        private string CreateAwardBatchRptFile(Objects.Preservation preservation, Company company, string workingDir, string preservationName, string exceptions, IDictionary <Guid, BindingList <DocumentAttributeValue> > fullDocumentAttributes)
        {
            logger.InfoFormat("CreateAwbReportFile - work dir {0} eccezioni {1}", workingDir, exceptions);

            try
            {
                if (string.IsNullOrEmpty(workingDir))
                {
                    throw new Exception("Working directory non configurata correttamente.");
                }

                if (preservation.Documents == null)
                {
                    throw new Exception(string.Format("Nessun documento associato alla conservazione con id {0}", preservation.IdPreservation));
                }

                if (exceptions == null)
                {
                    exceptions = string.Empty;
                }

                var nDoc = preservation.Documents.Count();

                var dtHlp       = preservation.Documents.Select(x => x.DateMain).Min();
                var sDataMinima = dtHlp.HasValue ? dtHlp.Value.ToString("dd/MM/yyyy") : "N.D.";

                dtHlp = preservation.Documents.Select(x => x.DateMain).Max();
                var sDataMassima = dtHlp.HasValue ? dtHlp.Value.ToString("dd/MM/yyyy") : "N.D.";

                var sFileNameBatch = Path.Combine(workingDir, "LOTTI_" + preservationName + ".xml");
                var sFileBatchXsl  = Path.Combine(workingDir, "LOTTI_" + preservationName + ".xsl");

                //Scrive il file XSLT di trasformazione del AwardBatch Xml
                ArchiveCompany archiveCompany = null;
                var            list           = GetArchiveCompany(preservation.Archive.IdArchive, company.CompanyName);
                if (list != null && list.Count > 0)
                {
                    archiveCompany = list[0];
                }

                File.WriteAllText(sFileBatchXsl, archiveCompany.AwardBatchXSLTFile);

                //generazione oggetto AwbReport che sarà poi serializzato come file Xml
                AwbReport report = new AwbReport();
                BindingList <Objects.AwardBatch> batches = GetPreservationAwardBatches(preservation.IdPreservation);

                //elenco dei lotti
                List <AwbBatch> batchList = new List <AwbBatch>();
                foreach (Objects.AwardBatch awardBatch in batches)
                {
                    batchList.Add(new AwbBatch
                    {
                        Descrizione = awardBatch.Name,
                        Files       = GetAwardBatchFiles(preservation, awardBatch.IdAwardBatch, fullDocumentAttributes)
                    });
                }

                //elenco dei file
                report.Batches = batchList.ToArray();

                //salva nella cartella di destinazione
                report.SaveAs(sFileNameBatch, sFileBatchXsl);
                logger.Info("CreateAwbReportFile - ritorno al chiamante");

                return(string.Empty);
            }
            catch (Exception e)
            {
                logger.Error(e);
                return(e.Message + " ===> " + e.Source);
            }
        }
        public async Task <ViewResult> DatabaseOperations()
        {
            // CREATE operation

            /*
             *    Company MyCompany = new Company();
             * MyCompany.symbol = "MCOB";
             * MyCompany.name = "ISM";
             * MyCompany.date = "ISM";
             * MyCompany.isEnabled = true;
             * MyCompany.type = "ISM";
             * MyCompany.iexId = "ISM";
             *
             * Quote MyCompanyQuote1 = new Quote();
             * //MyCompanyQuote1.EquityId = 123;
             * MyCompanyQuote1.date = "11-23-2018";
             * MyCompanyQuote1.open = 46.13F;
             * MyCompanyQuote1.high = 47.18F;
             * MyCompanyQuote1.low = 44.67F;
             * MyCompanyQuote1.close = 47.01F;
             * MyCompanyQuote1.volume = 37654000;
             * MyCompanyQuote1.unadjustedVolume = 37654000;
             * MyCompanyQuote1.change = 1.43F;
             * MyCompanyQuote1.changePercent = 0.03F;
             * MyCompanyQuote1.vwap = 9.76F;
             * MyCompanyQuote1.label = "Nov 23";
             * MyCompanyQuote1.changeOverTime = 0.56F;
             * MyCompanyQuote1.symbol = "MCOB";
             *
             * Quote MyCompanyQuote2 = new Quote();
             * //MyCompanyQuote1.EquityId = 123;
             * MyCompanyQuote2.date = "11-23-2018";
             * MyCompanyQuote2.open = 46.13F;
             * MyCompanyQuote2.high = 47.18F;
             * MyCompanyQuote2.low = 44.67F;
             * MyCompanyQuote2.close = 47.01F;
             * MyCompanyQuote2.volume = 37654000;
             * MyCompanyQuote2.unadjustedVolume = 37654000;
             * MyCompanyQuote2.change = 1.43F;
             * MyCompanyQuote2.changePercent = 0.03F;
             * MyCompanyQuote2.vwap = 9.76F;
             * MyCompanyQuote2.label = "Nov 23";
             * MyCompanyQuote2.changeOverTime = 0.56F;
             * MyCompanyQuote2.symbol = "MCOB";
             *
             * dbContext.Companies.Add(MyCompany);
             * dbContext.Quotes.Add(MyCompanyQuote1);
             * dbContext.Quotes.Add(MyCompanyQuote2);
             */
            // Create Course object

            Course MyCourse = new Course();

            MyCourse.Name    = "BAIS";
            MyCourse.Credits = 33;
            //MyCourse.Id = 1;

            //Create Student object

            Student MyStudent = new Student();

            MyStudent.Name     = "Siva";
            MyStudent.Location = "Orlando";
            //MyStudent.Id = 1;
            MyStudent.CourseId     = 1;
            MyStudent.EnrollmentId = 2;

            //Create Enrollment object

            Enrollment MyEnrollment = new Enrollment();

            MyEnrollment.course  = MyCourse;
            MyEnrollment.student = MyStudent;
            //MyEnrollment.Id = 1;

            MyEnrollment.Grade = "A+";

            dbContext.Courses.Add(MyCourse);
            dbContext.Students.Add(MyStudent);
            dbContext.Enrollments.Add(MyEnrollment);

            dbContext.SaveChanges();

            // READ operation
            Company CompanyRead1 = dbContext.Companies
                                   .Where(c => c.symbol == "MCOB")
                                   .First();

            Company CompanyRead2 = dbContext.Companies
                                   .Include(c => c.Quotes)
                                   .Where(c => c.symbol == "MCOB")
                                   .First();

            // UPDATE operation
            CompanyRead1.iexId = "MCOB";
            dbContext.Companies.Update(CompanyRead1);
            //dbContext.SaveChanges();
            await dbContext.SaveChangesAsync();

            // DELETE operation
            //dbContext.Companies.Remove(CompanyRead1);
            //await dbContext.SaveChangesAsync();

            return(View());
        }
Пример #35
0
        public IActionResult GetById(Guid id)
        {
            Company company = _companyApplicationService.GetById(id);

            return(CreateResponse(company));
        }
Пример #36
0
        public static ServiceResponseResult AddNewUser(Login login, Person person, LoginRole loginRole)
        {
            using (var db = new KeysEntities())
            {
                try
                {
                    db.Login.Add(login);
                    //person.LoginId = login.Id;
                    person.Id = login.Id;
                    db.Person.Add(person);
                    loginRole.PersonId = person.Id;
                    db.LoginRole.Add(loginRole);
                    switch (loginRole.RoleId)
                    {
                    case 4:
                        var owner = new Owners {
                            Person = person
                        };
                        db.Owners.Add(owner);
                        break;

                    case 5:
                        var tenant = new Tenant
                        {
                            Person = person,
                            IsCompletedPersonalProfile = false,
                            HasProofOfIdentity         = false,
                            CreatedOn = DateTime.UtcNow,
                            CreatedBy = login.Id,
                            UpdatedOn = DateTime.UtcNow,
                            IsActive  = true,
                            Address   = new Address
                            {
                                CountryId = 1,
                                IsActive  = true,
                            }
                        };
                        db.Tenant.Add(tenant);
                        break;

                    case 6:
                        var com = new Company
                        {
                            UpdatedBy = login.Email,
                            CreatedOn = DateTime.UtcNow,
                            CreatedBy = login.Email,
                            UpdatedOn = DateTime.UtcNow,
                            IsActive  = true,
                            Address   = new Address   //Bug Fix #2075
                            {
                                CountryId = 1,
                                IsActive  = true
                            },
                            Address1 = new Address     //Bug Fix #2075
                            {
                                CountryId = 1,
                                IsActive  = true
                            }
                        };
                        var sp = new ServiceProvider {
                            Person = person, Company = com, IsProfileComplete = false
                        };
                        db.ServiceProvider.Add(sp);
                        break;
                    }
                    db.SaveChanges();
                    return(new ServiceResponseResult {
                        IsSuccess = true
                    });
                }
                catch (Exception ex)
                {
                    return(new ServiceResponseResult {
                        IsSuccess = false
                    });
                }
            }
        }
Пример #37
0
        public static ServiceResponseResult AddNewRoleToUser(int roleId, Person person)
        {
            using (var db = new KeysEntities())
            {
                var login     = db.Login.FirstOrDefault(x => x.Id == person.Id);
                var loginRole = new LoginRole
                {
                    RoleId          = roleId,
                    PersonId        = person.Id,
                    IsActive        = true,
                    PendingApproval = false
                };

                db.LoginRole.Add(loginRole);
                db.SaveChanges();
                switch (roleId)
                {
                case 4:
                    var owner = new Owners {
                        Person = person
                    };
                    db.Owners.Add(owner);
                    break;

                case 5:
                    var tenant = new Tenant
                    {
                        Id = person.Id,
                        IsCompletedPersonalProfile = false,
                        HasProofOfIdentity         = false,
                        CreatedOn = DateTime.UtcNow,
                        CreatedBy = person.Id,
                        UpdatedOn = DateTime.UtcNow,
                        IsActive  = true,
                        Address   = new Address
                        {
                            CountryId = 1,
                            IsActive  = true,
                        }
                    };
                    db.Tenant.Add(tenant);
                    break;

                case 6:
                    var com = new Company
                    {
                        UpdatedBy = login.Email,
                        CreatedOn = DateTime.UtcNow,
                        CreatedBy = login.Email,
                        UpdatedOn = DateTime.UtcNow,
                        IsActive  = true,
                        Address   = new Address   //Bug Fix #2075
                        {
                            CountryId = 1,
                            IsActive  = true
                        },
                        Address1 = new Address     //Bug Fix #2075
                        {
                            CountryId = 1,
                            IsActive  = true
                        }
                    };
                    var sp = new ServiceProvider {
                        Id = person.Id, Company = com, IsProfileComplete = false
                    };
                    db.ServiceProvider.Add(sp);
                    break;
                }
                try
                {
                    db.SaveChanges();
                    return(new ServiceResponseResult {
                        IsSuccess = true
                    });
                }
                catch (Exception e)
                {
                    return(new ServiceResponseResult {
                        IsSuccess = false
                    });
                }
            }
        }
Пример #38
0
 public abstract void Add(Company c);
Пример #39
0
        private void cOTPcs_Load(object sender, EventArgs e)
        {
            listView1.View = View.Details;

            listView1.Columns.Add("RB");
            listView1.Columns.Add("otpID");
            listView1.Columns.Add("customerID");
            listView1.Columns.Add("dateCreated");
            listView1.Columns.Add("napomena");
            listView1.Columns.Add("primID");
            listView1.Columns.Add("userID");
            listView1.Columns.Add("fillID");

            listView2.View = View.Details;

            listView2.Columns.Add("RB");
            listView2.Columns.Add("Name");
            listView2.Columns.Add("CodePartFull");
            listView2.Columns.Add("SN");
            listView2.Columns.Add("CN");

            //Thread myThread = new Thread(fillSifrarnik);
            //myThread.Start();

            otpID = qc.GetAllOTPID();
            if (otpID[0] != -1)
            {
                for (int i = 0; i < otpID.Count(); i++)
                {
                    this.comboBox1.Items.Add(otpID[i]);
                }
            }

            customerID = qc.GetAllOTPcustomerID();
            if (customerID[0] != -1)
            {
                for (int i = 0; i < customerID.Count(); i++)
                {
                    this.comboBox2.Items.Add(customerID[i]);
                }
            }

            dateCreated = qc.GetAllOTPdateCreated();
            if (!dateCreated[0].Equals("nok"))
            {
                for (int i = 0; i < dateCreated.Count(); i++)
                {
                    this.comboBox3.Items.Add(dateCreated[i]);
                }
            }

            Company temCmp = new Company();

            cmpList = temCmp.GetAllCompanyInfoSortByName();

            if (cmpList.Count != 0)
            {
                for (int i = 0; i < temCmp.Count; i++)
                {
                    this.comboBox4.Items.Add(cmpList[i].Name);
                }
            }

            Program.LoadStop();
            this.Focus();
        }
Пример #40
0
 public abstract void Remove(Company c);
Пример #41
0
        public async Task RevertRevisionOutsideTheWindow()
        {
            var company = new Company {
                Name = "Company Name"
            };

            using (var store = GetDocumentStore())
            {
                await RevisionsHelper.SetupRevisions(Server.ServerStore, store.Database);

                using (var session = store.OpenAsyncSession())
                {
                    await session.StoreAsync(company);

                    await session.SaveChangesAsync();
                }

                await Task.Delay(2000);

                using (var session = store.OpenAsyncSession())
                {
                    company.Name = "Hibernating Rhinos";
                    await session.StoreAsync(company);

                    await session.SaveChangesAsync();
                }

                await Task.Delay(5000);

                DateTime last = DateTime.UtcNow;
                last = last.AddSeconds(-3);

                using (var session = store.OpenAsyncSession())
                {
                    company.Name = "Hibernating Rhinos 2";
                    await session.StoreAsync(company);

                    await session.SaveChangesAsync();
                }

                await Task.Delay(2000);

                var db = await GetDocumentDatabaseInstanceFor(store);

                RevertResult result;
                using (var token = new OperationCancelToken(db.Configuration.Databases.OperationTimeout.AsTimeSpan, db.DatabaseShutdown))
                {
                    result = (RevertResult)await db.DocumentsStorage.RevisionsStorage.RevertRevisions(last, TimeSpan.FromSeconds(1), onProgress : null,
                                                                                                      token : token);
                }

                Assert.Equal(3, result.ScannedRevisions);
                Assert.Equal(1, result.ScannedDocuments);
                Assert.Equal(1, result.RevertedDocuments);

                using (var session = store.OpenAsyncSession())
                {
                    var companiesRevisions = await session.Advanced.Revisions.GetForAsync <Company>(company.Id);

                    Assert.Equal(4, companiesRevisions.Count);

                    Assert.Equal("Hibernating Rhinos", companiesRevisions[0].Name);
                    Assert.Equal("Hibernating Rhinos 2", companiesRevisions[1].Name);
                    Assert.Equal("Hibernating Rhinos", companiesRevisions[2].Name);
                    Assert.Equal("Company Name", companiesRevisions[3].Name);
                }
            }
        }
Пример #42
0
 public CompanyDTO(Company company)
 {
     name        = company.Name;
     catchPhrase = company.CatchPhrase;
     bs          = company.Bs;
 }
Пример #43
0
        public void Main()
        {
            Console.WriteLine("获取反射类开始!");
            IDBHelper iDBHelper = SimpleFactory.getClass();
            //IDBHelper iDBHelper1 = SimpleFactory.getClass();
            //5.调用方法
            Company company = iDBHelper.Find(1);



            #region  创建带构造函数对象
            {
                //Console.WriteLine("*********************Reflection创建带构造函数参数的对象*************************");
                //Assembly assembly3 = Assembly.LoadFrom("HomeWork.SqlHelper.dll"); //dll名称(需要后缀)
                //Type type = assembly3.GetType("HomeWork.SqlHelper.SqlServerHelper");
                //object obj = Activator.CreateInstance(type);
                //object obj1 = Activator.CreateInstance(type, new object[] { "你好" });
                //object obj2 = Activator.CreateInstance(type, new object[] { 123 });
                //object obj3 = Activator.CreateInstance(type, new object[] { 123, "你好" });
                //Type type1 = typeof(SqlServerHelper);
            }
            #endregion


            #region  反射调用方法
            {
                //Type type1 = typeof(ReflectionTest);
                ////普通调用方式
                //ReflectionTest reflectionTest = new ReflectionTest();
                //reflectionTest.Show1();
                //reflectionTest.Show2(123);
                //reflectionTest.Show3(123);
                ////reflectionTest.Show4
                //ReflectionTest.Show5("Richard");

                ////Console.WriteLine("*********************Reflection调用普通方法*************************");
                //Assembly assembly3 = Assembly.LoadFrom("HomeWork.SqlHelper.dll"); //dll名称(需要后缀)
                //Type type = assembly3.GetType("HomeWork.SqlHelper.ReflectionTest");
                //object objTet = Activator.CreateInstance(type);
                ////objTet.Show();
                //MethodInfo Show1 = type.GetMethod("Show1");
                //object oResutl1 = Show1.Invoke(objTet, new object[] { });
                //object oResutl = Show1.Invoke(objTet, new object[0]);

                //MethodInfo Show2 = type.GetMethod("Show2");
                //object oResutl2 = Show2.Invoke(objTet, new object[] { 123 });

                ////Console.WriteLine("*********************Reflection调用普重载方法*************************");
                //MethodInfo Show33 = type.GetMethod("Show3",new Type[] { typeof(DateTime)});
                //object oResutl33 = Show33.Invoke(objTet, new object[] { DateTime.Now });
                //Console.WriteLine($"{ typeof(DateTime) }>>>>>oResutl33执行完的参数值{oResutl33}");


                //MethodInfo Show3 = type.GetMethod("Show3", new Type[] { typeof(int), typeof(string) });
                //object oResutl3 = Show3.Invoke(objTet, new object[] { 123, "阳光下的微笑" });

                //MethodInfo Show3_1 = type.GetMethod("Show3", new Type[] { typeof(string), typeof(int) });
                //object oResutl3_1 = Show3_1.Invoke(objTet, new object[] { "明日梦", 234 });

                //MethodInfo Show3_2 = type.GetMethod("Show3", new Type[] { typeof(int) });
                //object oResutl3_2 = Show3_2.Invoke(objTet, new object[] { 345 });

                //MethodInfo Show3_3 = type.GetMethod("Show3", new Type[] { typeof(string) });
                //object oResutl3_3 = Show3_3.Invoke(objTet, new object[] { "赤" });

                //MethodInfo Show3_4 = type.GetMethod("Show3", new Type[0]);
                //object oResutl3_4 = Show3_4.Invoke(objTet, new object[] { });

                //Console.WriteLine("*********************Reflection调用私有方法*************************");
                //MethodInfo Show4 = type.GetMethod("Show4", BindingFlags.NonPublic | BindingFlags.Instance);
                //object oResutl4 = Show4.Invoke(objTet, new object[] { "伟文" });

                //MethodInfo Show5 = type.GetMethod("Show5", BindingFlags.Static | BindingFlags.Public);
                //object oResutl5 = Show5.Invoke(objTet, new object[] { "追逐梦想的人。。" });
                //object oResutl5_1 = Show5.Invoke(null, new object[] { "you。。" });
            }
            #endregion

            #region 泛型类与方法


            {
                Console.WriteLine("*********************Reflections实例化泛型类+调用泛型方法*************************");
                {
                    //GenericMethod genericMethod = new GenericMethod();
                    //genericMethod.Show<int, string, DateTime>(123, "黄大仙", DateTime.Now);
                    //Assembly assembly3 = Assembly.LoadFrom("HomeWork.SqlHelper.dll"); //dll名称(需要后缀)
                    //Type type = assembly3.GetType("HomeWork.SqlHelper.GenericMethod");
                    //object genericTest = Activator.CreateInstance(type);
                    //MethodInfo show = type.GetMethod("Show");
                    ////注意:需要指定泛型方法的泛型类型
                    //MethodInfo show1 = show.MakeGenericMethod(new Type[] { typeof(int), typeof(string), typeof(DateTime) });
                    //show1.Invoke(genericTest, new object[] { 123, "黄大仙", DateTime.Now });//如果是泛型方法,需要先确定类型,再执行方法,注意:指定的类型和传入的参数类型必须匹配
                }
                {
                    //Assembly assembly3 = Assembly.LoadFrom("HomeWork.SqlHelper.dll"); //dll名称(需要后缀)
                    //Console.WriteLine(typeof(GenericClass<,,>));
                    ////这个能获取到的刷个1 否则刷个2
                    ////Type type = assembly3.GetType("HomeWork.SqlHelper.GenericClass`3");
                    ////MethodInfo show = type.GetMethod("Show");
                    ////MethodInfo show2 = show.MakeGenericMethod(new Type[] { typeof(DateTime), typeof(int), typeof(string) });

                    //Type type = assembly3.GetType("HomeWork.SqlHelper.GenericClass`3");
                    //Type type1 = type.MakeGenericType(new Type[] { typeof(int), typeof(string), typeof(DateTime) });
                    //object genericObj = Activator.CreateInstance(type1);
                    //MethodInfo show1 = type1.GetMethod("Show");
                    //show1.Invoke(genericObj, new object[] { 234, "工程师 冯兆", DateTime.Now });

                    ////GenericClass genericClass = new DB.SqlServer.GenericClass();
                    //GenericClass<int, string, DateTime> genericClass = new GenericClass<int, string, DateTime>();
                    //genericClass.Show(234, "工程师 冯兆", DateTime.Now);
                }
                {
                    //Assembly assembly = Assembly.LoadFrom("HomeWork.SqlHelper.dll"); //dll名称(需要后缀)
                    //Type type = assembly.GetType("HomeWork.SqlHelper.GenericDouble`1");
                    //Type type1 = type.MakeGenericType(new Type[] { typeof(int) });
                    //var obj = Activator.CreateInstance(type1);
                    //MethodInfo show = type1.GetMethod("Show");
                    //MethodInfo show1 = show.MakeGenericMethod(new Type[] { typeof(string), typeof(DateTime) });
                    ////show1.Invoke(obj,new object[] { "cxx",DateTime.Now});
                    //show1.Invoke(obj, new object[] { 456, "cxx", DateTime.Now });
                }
                {
                    //反射:IOC
                    //反射应用于哪些框架;
                    //IOC框架;反射+配置文件+工厂==IOC框架中应用;

                    //反射--MVC
                    //dll: HomeWork.SqlHelper.dll
                    //type: HomeWork.SqlHelper.GenericDouble
                    //就可以创建对象
                    //type可以获取到Method===Method名称--字符串
                    //  dll名称+类名称+方法名称===可以调用这个方法
                    // localhost://Home/Index/123== 可以调用到MVC项目中的某一个Action,你们觉得这是用的什么技术?
                    //MVC中调用方法就是反射的真实写照。。

                    //反射在ORM中的应用:
                    //ORM---对象关系映射,就是通过对类的达成对数据库的操作;
                    //方法、属性、字段

                    //People people = new People();
                    //people.Id = 123;
                    //people.Name = "赤";
                    //people.Description = "高级班VIP学员";
                    ////people.Age = 34;
                    //Console.WriteLine($"people.Id={people.Id}");
                    //Console.WriteLine($"people.Name={people.Name}");
                    //Console.WriteLine($"people.Description={people.Description}");
                    //如果说People加了一个字段或者或者加了几个属性,普通方式=必须要修改代码--导致代码不稳定;
                    //反射的时候,在获取值的时候可以不用修改代码。。

                    //那反射怎么做呢?
                    //Type type = typeof(User);
                    //object oPeople = Activator.CreateInstance(type);
                    ////oPeople.Id=
                    //foreach (PropertyInfo prop in type.GetProperties())
                    //{
                    //    if (prop.Name.Equals("Id"))
                    //    {
                    //        prop.SetValue(oPeople, 123);
                    //    }
                    //    else if (prop.Name.Equals("Name"))
                    //    {
                    //        prop.SetValue(oPeople, "赤");
                    //    }
                    //    //Console.WriteLine(prop.Name);
                    //}
                    //foreach (FieldInfo field in type.GetFields()) //获取所有的字段
                    //{
                    //    if (field.Name.Equals("Description"))
                    //    {
                    //        field.SetValue(oPeople, "高级班VIP学员");
                    //    }
                    //    //Console.WriteLine(field.Name);
                    //}
                    //foreach (PropertyInfo prop in type.GetProperties())
                    //{
                    //    Console.WriteLine(prop.GetValue(oPeople));
                    //}
                    //foreach (FieldInfo field in type.GetFields()) //获取所有的字段
                    //{
                    //    Console.WriteLine(field.GetValue(oPeople));
                    //}
                    ////准备给大家来一个手写ORM;ORM--就是通过类的使用达成对数据库的使用;无非就是增删改查;

                    {
                        //SqlServerHelper sqlServerHelper = new SqlServerHelper();
                        ////Company company = sqlServerHelper.QueryCompany(1);
                        //Company company = sqlServerHelper.Find<Company>(1);
                        //User user = sqlServerHelper.Find<User>(1);
                        //Console.WriteLine(company);
                        //Console.WriteLine(user);
                    }
                    //升级一下。。
                    //如果我想要来查询Usernew?

                    {
                        //Type type = typeof(SqlServerHelper);
                        //type.ge
                    }
                }
            }

            #endregion
            Console.ReadLine();
            Console.WriteLine("获取反射类完成!");
        }
Пример #44
0
        public async Task DontRevertToConflicted()
        {
            // put at 8:30
            // conflicted at 8:50
            // resolved at 9:10
            // will revert to 9:00

            using (var store1 = GetDocumentStore(options: new Options
            {
                ModifyDatabaseRecord = record =>
                {
                    record.ConflictSolverConfig = new ConflictSolver
                    {
                        ResolveToLatest = false,
                        ResolveByCollection = new Dictionary <string, ScriptResolver>()
                    };
                }
            }))
                using (var store2 = GetDocumentStore())
                {
                    DateTime last = default;
                    await RevisionsHelper.SetupRevisions(Server.ServerStore, store1.Database);

                    using (var session = store2.OpenAsyncSession())
                    {
                        await session.StoreAsync(new Company(), "keep-conflicted-revision-insert-order");

                        await session.SaveChangesAsync();

                        var company = new Company
                        {
                            Name = "Name2"
                        };
                        await session.StoreAsync(company, "foo/bar");

                        await session.SaveChangesAsync();
                    }

                    using (var session = store1.OpenAsyncSession())
                    {
                        var company = new Company
                        {
                            Name = "Name1"
                        };
                        await session.StoreAsync(company, "foo/bar");

                        await session.SaveChangesAsync();

                        var companiesRevisions = await session.Advanced.Revisions.GetForAsync <Company>("foo/bar");

                        Assert.Equal(1, companiesRevisions.Count);
                    }

                    await SetupReplicationAsync(store2, store1);

                    WaitUntilHasConflict(store1, "foo/bar");

                    last = DateTime.UtcNow;

                    using (var session = store1.OpenAsyncSession())
                    {
                        var company = new Company
                        {
                            Name = "Resolver"
                        };
                        await session.StoreAsync(company, "foo/bar");

                        await session.SaveChangesAsync();
                    }

                    var db = await GetDocumentDatabaseInstanceFor(store1);

                    RevertResult result;
                    using (var token = new OperationCancelToken(db.Configuration.Databases.OperationTimeout.AsTimeSpan, db.DatabaseShutdown))
                    {
                        result = (RevertResult)await db.DocumentsStorage.RevisionsStorage.RevertRevisions(last.Add(TimeSpan.FromMinutes(1)), TimeSpan.FromMinutes(60),
                                                                                                          onProgress : null, token : token);
                    }

                    Assert.Equal(4, result.ScannedRevisions);
                    Assert.Equal(2, result.ScannedDocuments);
                    Assert.Equal(0, result.RevertedDocuments);

                    using (var session = store1.OpenAsyncSession())
                    {
                        var companiesRevisions = await session.Advanced.Revisions.GetForAsync <Company>("foo/bar");

                        Assert.Equal(3, companiesRevisions.Count);
                    }
                }
        }
Пример #45
0
 private CompanyResponse ToCompanyResponse(Company company)
 {
     return(new CompanyResponse
     {
         Id = company.Id,
         Name = company.Name,
         Country = company.Country,
         Pro = company.Pro,
         Voys = company.Voys?.Select(v => new VoyResponse
         {
             Id = v.Id,
             Account = v.Account,
             Altitude = v.Altitude,
             Cargo = v.Cargo,
             Cargo_Charterer = v.Cargo_Charterer,
             Consignee = v.Consignee,
             Contract = v.Contract,
             Eta = v.Eta,
             Etb = v.Etb,
             Etc = v.Etc,
             Etd = v.Etd,
             Facility = v.Facility,
             LastKnowPosition = v.LastKnowPosition,
             Latitude = v.Latitude,
             Laycan = v.Laycan,
             Owner_Charterer = v.Owner_Charterer,
             Pod = v.Pod,
             Pol = v.Pol,
             Sf = v.Sf,
             Shipper = v.Shipper,
             Voy_number = v.Voy_number,
             Opinions = v.Opinions?.Select(o => new OpinionResponse
             {
                 Id = o.Id,
                 Description = o.Description,
                 Qualification = o.Qualification
             }).ToList(),
             Statuses = v.Statuses?.Select(s => new StatusResponse
             {
                 Id = s.Id,
                 AllFast = s.AllFast,
                 Anchored = s.Anchored,
                 Arrival = s.Arrival,
                 Commenced = s.Commenced,
                 DateUpdate = s.DateUpdate,
                 Name_status = s.Name_status,
                 Pob = s.Pob,
                 Alerts = s.Alerts?.Select(a => new AlertResponse
                 {
                     Id = a.Id,
                     Alert_Description = a.Alert_Description,
                     Alert_Date = a.Alert_Date,
                     AlertImages = a.AlertImages?.Select(ai => new AlertImageResponse
                     {
                         Id = ai.Id,
                         Title = ai.Title,
                         ImageUrl = ai.ImageUrl
                     }).ToList(),
                 }).ToList(),
                 Holds = s.Holds?.Select(h => new HoldResponse
                 {
                     Id = h.Id,
                     Actual_Quantity = h.Actual_Quantity,
                     First_Charge = h.First_Charge,
                     Hold_Number = h.Hold_Number,
                     Is_Empty = h.Is_Empty,
                     Is_Full = h.Is_Full,
                     Last_Charge = h.Last_Charge,
                     Max_Quantity = h.Max_Quantity
                 }).ToList(),
             }).OrderByDescending(st => st.DateUpdateLocal).Take(1).ToList(),
             Voyimages = v.Voyimages?.Select(vi => new VoyImageResponse
             {
                 Id = vi.Id,
                 Title = vi.Title,
                 ImageUrl = vi.ImageUrl
             }).ToList(),
             Port = ToPortResponse(v.Port),
             Vessel = ToVesselResponse(v.Vessel),
             Employee = ToEmployeeResponse(v.Employee)
         }).ToList(),
     });
 }
Пример #46
0
        public void ExternalWebOpportunityCreate()
        {
            int             id     = 1;
            CommunityDaysDb db     = new CommunityDaysDb();
            var             status = new OpportunityStatus
            {
                OpportunityStatusId          = id,
                OpportunityStatusDescription = "First status"
            };

            var user = new UserProfile
            {
                UserId   = id,
                UserName = "******"
            };

            var company = new Company
            {
                CompanyId   = id,
                CompanyName = "First Company"
            };

            db.Company.Add(company);
            db.UserProfiles.Add(user);
            db.OpportunityStatus.Add(status);
            db.SaveChanges();

            // Arrange
            OpportunityController controller = new OpportunityController();
            var model = new Opportunity
            {
                OpportunityId                    = id,
                OpportunityStatusId              = id,
                CompanyId                        = id,
                MinNumberofVolunteers            = id,
                MaxNumberofVolunteers            = id,
                OpportunityLocationName          = "ABERFELDY",
                OpportunityPostcode              = "BD23 1PT",
                OpportunityTitle                 = "BREADALBANE CANOE CLUB EVENT",
                OpportunityDescription           = "ASSIST AS HELPERS AT OUR SLALOM KAYAKING COMPETITION IN ABERFELDY 1ST & 2ND OF APRIL - CAR PARKING, CATERING TENT, HELPING CHILDREN GET IN AND OUT OF BOATS, HELP CARRY BOATS, ETC. OUR OTHER COMPETITION AT GRANDTULLY ON THE 30TH AND 31ST OF MARCH WOULD BENEFIT FROM ANY HELPERS AS WELL. IT IS A PREMIER EVENT AND SOME PREVIOUS OLYMPIC MEDALISTS COMPETE THERE. THE ADVENTURE SHOW ALSO FILMS THE EVENT.",
                OpportunityDate                  = System.DateTime.Now.AddDays(5).ToShortDateString(),
                OpportunityCreatedDate           = System.DateTime.Now,
                OpportunityAdditionalInformation = "Created: " + System.DateTime.Now.ToString()
            };

            /*var parentmodel = new OpportunityViewModelExternalWeb.ViewModels.OpportunityViewModel
             * {
             *  Opportunity = model,
             *  EventDate = System.DateTime.Now
             * };
             *
             * // Act
             * var redirectToRouteResult = controller.Create(model) as RedirectToRouteResult;
             * //ViewResult result = controller.Edit(id) as ViewResult;
             * //Opportunity modelResult = (Opportunity)result.ViewData.Model;
             *
             * // Assert
             * Assert.IsNotNull(redirectToRouteResult);
             * Assert.AreEqual("Index", redirectToRouteResult.RouteValues["Action"]);
             * Assert.AreEqual("OpportunityController", redirectToRouteResult.RouteValues["controller"]);
             * //Assert.AreEqual(model.OpportunityId, modelResult.OpportunityId);
             * */
        }
Пример #47
0
        public async Task <IList <ICompany> > GetAll()
        {
            StorageFile file = await GetFilePath();

            Stream stream = await file.OpenStreamForReadAsync();

            XDocument xDoc;

            using (stream)
            {
                xDoc = XDocument.Load(stream);
            }

            var companies    = xDoc.Descendants("Company");
            var listToReturn = new List <ICompany>();

            foreach (var xElement in companies)
            {
                var todos     = new List <Todo>();
                var histories = new List <HistoryPost>();
                var employees = new List <Employee>();

                foreach (var todo in xElement.Descendants("Todo"))
                {
                    string[] temdDateAsString = todo.Element("Date").Value.Split('-');
                    todos.Add(new Todo()
                    {
                        Id          = int.Parse(todo.Element("Id").Value),
                        Date        = new DateTime(int.Parse(temdDateAsString[0]), int.Parse(temdDateAsString[1]), int.Parse(temdDateAsString[2].Substring(0, 2))),
                        Description = todo.Element("Description").Value
                    });
                }

                foreach (var history in xElement.Descendants("HistoryPost"))
                {
                    string[] temdDateAsString = history.Element("Date").Value.Split('-');
                    histories.Add(new HistoryPost()
                    {
                        Id   = int.Parse(history.Element("Id").Value),
                        Date = new DateTime(int.Parse(temdDateAsString[0]), int.Parse(temdDateAsString[1]), int.Parse(temdDateAsString[2].Substring(0, 2))),
                        Post = history.Element("Post").Value
                    });
                }

                foreach (var employee in xElement.Descendants("Employee"))
                {
                    employees.Add(new Employee()
                    {
                        Id       = int.Parse(employee.Element("Id").Value),
                        Name     = employee.Element("Name").Value,
                        Phone    = employee.Element("Phone").Value,
                        Mobile   = employee.Element("Mobile").Value,
                        Email    = employee.Element("Email").Value,
                        Position = employee.Element("Position").Value
                    });
                }

                var company = new Company()
                {
                    Id     = int.Parse(xElement.Element("Id").Value),
                    Name   = xElement.Element("Name").Value,
                    Phone  = xElement.Element("Phone").Value,
                    City   = xElement.Element("City").Value,
                    Street = xElement.Element("Street").Value
                };

                company.Todos.AddRange(todos);
                company.Histories.AddRange(histories);
                company.Employees.AddRange(employees);

                listToReturn.Add(company);
            }

            return(listToReturn);
        }
Пример #48
0
        /// <summary>
        /// Выполняет полное копирование объекта, реализация интерфейса ICloneable
        /// </summary>
        /// <returns>Результат копирования</returns>
        public SearchFlightsRQBody Clone()
        {
            var result = new SearchFlightsRQBody();

            result.MultiOWRequestedSegmentNumber = MultiOWRequestedSegmentNumber;

            result.RequestedFlightInfo         = new RequestElements.FlightDirection();
            result.RequestedFlightInfo.ODPairs = new RequestElements.FlightPairList();
            result.Passengers = new List <Passenger>();

            result.RequestedFlightInfo.AroundDates = RequestedFlightInfo.AroundDates;
            result.RequestedFlightInfo.Direct      = RequestedFlightInfo.Direct;
            result.RequestedFlightInfo.Type        = RequestedFlightInfo.Type;
            result.RequestedFlightInfo.SubType     = RequestedFlightInfo.SubType;

            foreach (var seg in RequestedFlightInfo.ODPairs)
            {
                result.RequestedFlightInfo.ODPairs.Add(seg.FullCopy());
            }

            foreach (var pass in Passengers)
            {
                var tmpPass = new Passenger();
                tmpPass.Count = pass.Count;
                tmpPass.Type  = pass.Type;

                result.Passengers.Add(tmpPass);
            }

            if (Restrictions != null)
            {
                result.Restrictions = new RequestElements.AdditionalSearchInfo();
                result.Restrictions.ClassPreference = new RequestElements.ClassPrefList();
                result.Restrictions.ClassPreference.AddRange(Restrictions.ClassPreference);
                result.Restrictions.CurrencyCode              = Restrictions.CurrencyCode;
                result.Restrictions.PrivateFaresOnly          = Restrictions.PrivateFaresOnly;
                result.Restrictions.SourcePreference          = Restrictions.SourcePreference;
                result.Restrictions.MaxConnectionTime         = Restrictions.MaxConnectionTime;
                result.Restrictions.ResultsGrouping           = Restrictions.ResultsGrouping;
                result.Restrictions.MaxResultCount            = Restrictions.MaxResultCount;
                result.Restrictions.PriceRefundType           = Restrictions.PriceRefundType;
                result.Restrictions.AsyncSearch               = Restrictions.AsyncSearch;
                result.Restrictions.AdditionalPublicFaresOnly = Restrictions.AdditionalPublicFaresOnly;
                result.Restrictions.MaxConnections            = Restrictions.MaxConnections;

                if (Restrictions.CompanyFilter != null)
                {
                    result.Restrictions.CompanyFilter = new List <Company>();
                    foreach (var oldComp in Restrictions.CompanyFilter)
                    {
                        var comp = new Company();
                        comp.Code          = oldComp.Code;
                        comp.Include       = oldComp.Include;
                        comp.SegmentNumber = oldComp.SegmentNumber;

                        result.Restrictions.CompanyFilter.Add(comp);
                    }
                }
            }

            if (EndUserData != null)
            {
                result.EndUserData = new EndUserDataDataItem();
                result.EndUserData.EndUserBrowserAgent = EndUserData.EndUserBrowserAgent;
                result.EndUserData.EndUserIP           = EndUserData.EndUserIP;
                result.EndUserData.RequestOrigin       = EndUserData.RequestOrigin;
            }

            return(result);
        }
Пример #49
0
        public static void Initialize(AlfavoxDbContext context)
        {
            // EnsureCreated will cause the database to be created
            // whenever it's needed to be. If it's already there
            // it won't do anything
            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

            // Check if specified table has any data in it
            // if not, then create some dummy data
            if (context.Compenies.Any() && context.Employees.Any())
            {
                return;
            }

            // Create loads of Dummy Data
            var products = new Product[]
            {
                new Product()
                {
                    Title = "Video Chat", BriefContent = "najlepszy sposób na wzrost konwersji w..", Type = ProductType.Customer
                },
                new Product()
                {
                    Title = "Omnichannel Desktop", BriefContent = "zwiększ zysk swojej firmy", Type = ProductType.Employee
                }
            };

            foreach (var product in products)
            {
                context.Products.Add(product);
            }
            context.SaveChanges();

            var locations = new Location[]
            {
                new Location()
                {
                    Country = "Poland", City = "Bielsko-Biała", PostCode = "7777"
                },
                new Location()
                {
                    Country = "Poland", City = "Warszawa", PostCode = "8888"
                },
            };

            foreach (var location in locations)
            {
                context.Locations.Add(location);
            }
            context.SaveChanges();

            var employees = new Employee[]
            {
                new Employee()
                {
                    FirstName = "Paweł", LastName = "Rudnicki", Position = "Software Engineer"
                },
                new Employee()
                {
                    FirstName = "Jan", LastName = "Kowalski", Position = "Quality Assurance"
                }
            };

            foreach (var employee in employees)
            {
                context.Employees.Add(employee);
            }
            context.SaveChanges();

            var company = new Company()
            {
                Name = "Alfavox"
            };

            context.Compenies.Add(company);
            context.SaveChanges();
        }
Пример #50
0
        // GET Company By ID
        public ActionResult Company(string idUser)
        {
            Company company = dbContext.Companies.Where(c => c.CompanySecondID.Equals(idUser)).FirstOrDefault();

            return(View(company));
        }
Пример #51
0
 public void CreateCompany(Company company)
 {
     this.Db.Companies.Add(company);
     this.Db.SaveChanges();
 }
Пример #52
0
 private void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
 {
     company = (Company)e.SelectedItem;
 }
Пример #53
0
 public CompanyPlantsService(Company company)
 {
     _company = company;
 }
Пример #54
0
        public void CanUseSpacesInCounterAndCompareExchangeNames()
        {
            using (var store = GetDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    var company = new Company
                    {
                        Name = "HR"
                    };

                    session.Store(company, "companies/1");

                    session.CountersFor(company).Increment("Total Likes", 11);

                    session.SaveChanges();
                }

                using (var session = store.OpenSession(new SessionOptions
                {
                    TransactionMode = TransactionMode.ClusterWide
                }))
                {
                    session.Advanced.ClusterTransaction.CreateCompareExchangeValue("Total Uses", 55);

                    session.SaveChanges();
                }

                using (var session = store.OpenSession())
                {
                    Assert.Equal(11, session.CountersFor("companies/1").Get("Total Likes"));
                }

                using (var session = store.OpenSession(new SessionOptions
                {
                    TransactionMode = TransactionMode.ClusterWide
                }))
                {
                    Assert.Equal(55, session.Advanced.ClusterTransaction.GetCompareExchangeValue <int>("Total Uses").Value);
                }

                using (var session = store.OpenSession())
                {
                    var query = session.Query <Company>()
                                .Select(x => new
                    {
                        TotalUses = RavenQuery.CmpXchg <int>("Total Uses")
                    });

                    var queryAsString = query.ToString();
                    Assert.Contains("cmpxchg(\"Total Uses\")", queryAsString);

                    var result = query.First();
                    Assert.Equal(55, result.TotalUses);
                }

                using (var session = store.OpenSession())
                {
                    var query = session.Query <Company>()
                                .Select(x => new
                    {
                        Name       = x.Name + " " + x.Name,
                        TotalLikes = RavenQuery.Counter(x, "Total Likes")
                    });

                    var queryAsString = query.ToString();
                    Assert.Contains("counter(x, \"Total Likes\")", queryAsString);

                    var result = query.First();
                    Assert.Equal(11, result.TotalLikes);
                }

                using (var session = store.OpenSession())
                {
                    var query = session.Query <Company>()
                                .Select(x => new
                    {
                        TotalLikes = RavenQuery.Counter(x, "Total Likes")
                    });

                    var queryAsString = query.ToString();
                    Assert.Contains("counter(x, 'Total Likes')", queryAsString);

                    var result = query.First();
                    Assert.Equal(11, result.TotalLikes);
                }
            }
        }
Пример #55
0
 public void Remove(Company company)
 {
     _context.Companies.Remove(company);
 }
Пример #56
0
        public async Task <int> UpdateAsync(Company company)
        {
            var cmd = QueriesCreatingHelper.CreateQueryUpdate(company);

            return(await DALHelper.Execute(cmd, dbTransaction : DbTransaction, connection : DbConnection));
        }
Пример #57
0
 public void Add(Company company)
 {
     _context.Companies
     .Add(company);
 }
Пример #58
0
        private IActionResult ImportCompany(Stream input)
        {
            var errors  = new ErrorManager();
            var account = this.CurrentAccount();
            var models  = new List <ModelWrapper <Company> >();

            EachRow(input, (row, EachColumn) => {
                var model = new Company {
                    Account = account, Source = DataSource.Excel
                };

                EachColumn((column, value) => {
                    switch (column)
                    {
                    case 1: {
                        if (string.IsNullOrEmpty(value))
                        {
                            errors.Error($"Empty name: [row: {row}][column: {column}]");
                        }
                        else
                        {
                            model.Name = value;
                        }
                    }
                    break;

                    case 2: {
                        if (string.IsNullOrEmpty(value))
                        {
                            errors.Error($"Empty industry: [row: {row}][column: {column}]");
                        }
                        else
                        {
                            value.Split('|').Where(x => !string.IsNullOrWhiteSpace(x)).ToList().ForEach(x => {
                                    var node = FindIndustry(x);
                                    if (node == null)
                                    {
                                        errors.Error($"Cannot find industry: [row: {row}][column: {column}][value: {x}]");
                                    }
                                    else
                                    {
                                        model.Industries.Add(node);
                                    }
                                });
                        }
                    }
                    break;

                    case 3: {
                        if (!string.IsNullOrEmpty(value))
                        {
                            value.Split('|').Where(x => !string.IsNullOrWhiteSpace(x)).ToList().ForEach(x => {
                                    var node = FindIndustry(x);
                                    if (node == null)
                                    {
                                        errors.Error($"Cannot find industry: [row: {row}][column: {column}][value: {x}]");
                                    }
                                    else
                                    {
                                        model.Industries.Add(node);
                                    }
                                });
                        }
                    }
                    break;

                    case 4: {
                        if (string.IsNullOrEmpty(value))
                        {
                            errors.Error($"Empty type: [row: {row}][column: {column}]");
                        }
                        else
                        {
                            model.Type = GetEnumValue <CompanyType>(value);
                            if (model.Type == null)
                            {
                                errors.Error($"Invalid company type: [row: {row}][column: {column}]");
                            }
                        }
                    }
                    break;

                    case 5: {
                        if (string.IsNullOrEmpty(value))
                        {
                            errors.Error($"Empty status: [row: {row}][column: {column}]");
                        }
                        else
                        {
                            model.Status = GetEnumValue <CompanyStatus>(value);
                            if (model.Status == null)
                            {
                                errors.Error($"Invalid company status: [row: {row}][column: {column}]");
                            }
                        }
                    }
                    break;

                    default:
                        break;
                    }
                });

                models.Add(new ModelWrapper <Company>(model, row));
            });

            models.GroupBy(x => x.Model.Name).ToList().ForEach(group => {
                if (group.Count() > 1)
                {
                    errors.Error($"Repeations items: [rows: { string.Join(", ", group.Select(x => x.Row)) }]");
                }
            });

            try {
                errors.ThrowIfError();

                var companies = this.GetMonCollection <Company>();
                var newModels = models.Select(x => x.Model).Where(model => !companies.Exist(x => x.Name.Equals(model.Name)));
                if (newModels.Count() > 0)
                {
                    companies.InsertMany(newModels);
                }

                return(Content($"Great!!! there are no problems found. [total: {models.Count}][insert: {newModels.Count()}]"));
            } catch (Exception ex) {
                return(Content(ex.Message));
            }
        }
Пример #59
0
 public void start()
 {
     PlayerCompany = new Company("California Technology");
     intial_settings();
     testPause();
 }
Пример #60
0
 public void Update(Company company)
 {
     _context.Entry(company).State = EntityState.Modified;
 }