Beispiel #1
0
        private Task<string> QueryLoadUsers()
        {
            return Task.Factory.StartNew(() =>
            {
                try
                {
                    usersList.Clear();
                    using (var context = new DatabaseContext())
                    {
                        var user = context.UserAccounts.ToList();

                        foreach (var item in user)
                        {
                            var empname = context.Employees.FirstOrDefault(c => c.EmployeeId == item.EmployeeId);

                            usersList.Add(new UsersLists()
                            {
                                IsAdmin = item.IsAdmin,
                                CustomerServiceManagementAccess = item.CustomerServiceAccess,
                                EmployeeName = empname.FirstName + " " + empname.LastName,
                                LeadManagementAccess = item.LeadManagementAccess,
                                TaskManagementAccess = item.TaskManagementAccess,
                                UserAccountId = item.UserAccountId
                            });
                        }
                    }
                    return null;
                }
                catch (Exception ex)
                {
                    return "Error Message" + ex.Message;
                }
            });
        }
		/// <summary>
		/// Constructor.
		/// </summary>
		public AssignmentService(
			DatabaseContext dbContext, 
			IAssignmentScoreCalculator assignmentScoreCalculator)
		{
			_dbContext = dbContext;
			_assignmentScoreCalculator = assignmentScoreCalculator;
		}
Beispiel #3
0
 public void Update(ContentItem contentItem)
 {
     using (DatabaseContext context = new DatabaseContext())
     {
         context.Update<MSSQL.Entities.ContentItem, ContentItem>(contentItem, new string[] { "Id" });
     }
 }
Beispiel #4
0
        public ContentItem Find(long id, int depth)
        {
            List<ContentItem> contentItems = null;

            using (DatabaseContext context = new DatabaseContext())
            {
                string query = "DECLARE @parent hierarchyId = (SELECT TOP 1 Node FROM [dbo].[ContentItem] WHERE Id = @id);";
                query += "SELECT * FROM [dbo].[ContentItem] WHERE Node = @parent ";

                for (int i = 1; i <= depth; i++)
                {
                    query += " OR Node.GetAncestor(" + i + ") = @parent";
                }

                contentItems = context.Select<MSSQL.Entities.ContentItem, ContentItem>(query, new { id = id, }).ToList();
            }

            if (contentItems != null && contentItems.Any())
            {
                ContentItem parentContentItem = contentItems.Single(contentItem => contentItem.Id == id);
                contentItems.Remove(parentContentItem);
                return ContentItemsToTree(parentContentItem, contentItems);
            }

            return null;
        }
 public IEnumerable<LunchOption> GetOptions(string q = "")
 {
     using (var dbContext = new DatabaseContext())
     {
         return dbContext.LunchOptions.Where(o => o.Name.Contains(q)).ToList();
     }
 }
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            using (var context = new DatabaseContext())
            {
                var Prodcat = new ProductCategory();

                if (ProdCategoryId > 0)
                {
                    var prod = context.ProductCategories.FirstOrDefault
                        (c => c.CategoryID == ProdCategoryId);

                    if (prod != null)
                    {
                        if (lblCategoryId.Visibility == Visibility.Hidden) { lblCategoryId.Visibility = Visibility.Visible; }
                        if (txtCategoryId.Visibility == Visibility.Hidden) { txtCategoryId.Visibility = Visibility.Visible; }
                        Grid.SetRow(lblCategoryName, 1);
                        Grid.SetRow(txtCategoryName, 1); Grid.SetColumn(txtCategoryName, 1);

                        txtCategoryId.Text = Convert.ToString(prod.CategoryID);
                        txtCategoryName.Text = prod.CategoryName;
                    }
                }
                else
                {
                    if (lblCategoryId.Visibility != Visibility.Hidden) { lblCategoryId.Visibility = Visibility.Hidden; }
                    if (txtCategoryId.Visibility != Visibility.Hidden) { txtCategoryId.Visibility = Visibility.Hidden; }
                    Grid.SetRow(lblCategoryName, 0);
                    Grid.SetRow(txtCategoryName, 0); Grid.SetColumn(txtCategoryName, 1);

                    txtCategoryName.Text = "";
                }
            }
        }
Beispiel #7
0
		public DbService()
		{
			Context = new DatabaseContext(DbServiceHelper.CreateConnection());
			Context.Database.CommandTimeout = 180;
			GKScheduleTranslator = new GKScheduleTranslator(this);
			GKDayScheduleTranslator = new GKDayScheduleTranslator(this);
			PassJournalTranslator = new PassJournalTranslator(this);
			JournalTranslator = new JournalTranslator(this);
			AccessTemplateTranslator = new AccessTemplateTranslator(this);
			AdditionalColumnTypeTranslator = new AdditionalColumnTypeTranslator(this);
			CardTranslator = new CardTranslator(this);
			CurrentConsumptionTranslator = new CurrentConsumptionTranslator(this);
			DayIntervalTranslator = new DayIntervalTranslator(this);
			DepartmentTranslator = new DepartmentTranslator(this);
			EmployeeTranslator = new EmployeeTranslator(this);
			HolidayTranslator = new HolidayTranslator(this);
			NightSettingTranslator = new NightSettingTranslator(this);
			OrganisationTranslator = new OrganisationTranslator(this);
			PassCardTemplateTranslator = new PassCardTemplateTranslator(this);
			PositionTranslator = new PositionTranslator(this);
			ScheduleTranslator = new ScheduleTranslator(this);
			ScheduleSchemeTranslator = new ScheduleSchemeTranslator(this);
			GKCardTranslator = new GKCardTranslator(this);
			GKMetadataTranslator = new GKMetadataTranslator(this);
			TimeTrackTranslator = new TimeTrackTranslator(this);
			TimeTrackDocumentTypeTranslator = new TimeTrackDocumentTypeTranslator(this);
			TimeTrackDocumentTranslator = new TimeTrackDocumentTranslator(this);
			TestDataGenerator = new TestDataGenerator(this);
			ImitatorUserTraslator = new ImitatorUserTraslator(this);
			ImitatorScheduleTranslator = new ImitatorScheduleTranslator(this);
			ImitatorJournalTranslator = new ImitatorJournalTranslator(this);
		}
        public WizardDialog()
        {
            InitializeComponent();

            //New Up DB Object
            _db = new DatabaseContext();
        }
        public void CreateArrangementWithUsers()
        {
            using (DatabaseContext ctx = new DatabaseContext())
            {
                ArrangementRepository repository = new ArrangementRepository(ctx);
                var arrangement = repository.Add();

                arrangement.Name = "Koops Furness";
                arrangement.BpNumber = "123456789";

                var user1 = new User() {UserName = "******", Email = "*****@*****.**", FullName = "User One"};
                var user2 = new User() {UserName = "******", Email = "*****@*****.**", FullName = "User Two"};

                arrangement.Users.Add(user1);
                arrangement.Users.Add(user2);

                Assert.IsTrue(arrangement.Id == 0);
                Assert.IsTrue(user1.Id == 0);
                Assert.IsTrue(user2.Id == 0);

                ctx.SaveChanges();

                Assert.IsTrue(arrangement.Id > 0);
                Assert.IsTrue(user1.Id > 0);
                Assert.IsTrue(user2.Id > 0);
                Assert.AreEqual(arrangement, user1.Arrangements.Single());
                Assert.AreEqual(arrangement, user2.Arrangements.Single());
            }
        }
 public async Task<ActionResult> NewQuote(QuoteViewModel vm)
 {
     using (var dbContext = new DatabaseContext())
     {
         var quote = new Quote
         {
             Text = vm.Text,
             Submitter = dbContext.Users.Single(u => u.UserName == User.Identity.Name),
             CreatedAt = DateTime.Now,
             Tags = new List<Tag>()
         };
         var user = dbContext.Users.SingleOrDefault(x => x.UserName == vm.Author);
         if (user != null)
         {
             quote.Author = user;
         }
         else
         {
             quote.AlternateAuthor = String.IsNullOrWhiteSpace(vm.Author) ? "Anonymous" : vm.Author;
         }
         dbContext.Quotes.Add(quote);
         vm = new QuoteViewModel(quote);
         await dbContext.SaveChangesAsync();
         QuotesHub.NewQuote(quote);
     }
     return PartialView("_Quote", vm);
 }
        public List<MechanicJob> Get(int itemsPerPage, int currentPage)
        {
            var entities = new DatabaseContext().MechanicJobs
                .Include("Car")
                .Include("Car.CarModel")
                .Include("Car.CarType")
                .Include("MechanicType")
                .OrderBy(o => o.Id)
                .Skip(itemsPerPage * (currentPage - 1))
                .Take(itemsPerPage)
                .ToList();

            var mechanicJobs = entities.Select(s => new MechanicJob
            {
                Id = s.Id,
                Price = s.Price,
                Car = new Car
                {
                    Id = s.Car.Id,
                    CarNumber = s.Car.CarNumber,
                    CarType = new CarType { Id = s.Car.CarType.Id, ArabicName = s.Car.CarType.ArabicName },
                    CarModel = new CarModel { Id = s.Car.CarModel.Id, ArabicName = s.Car.CarModel.ArabicName },
                },
                MechanicType = s.MechanicType,
            })
            .ToList();

            return mechanicJobs;
        }
        private void LoadEmployees(string text)
        {
            using (var context = new DatabaseContext())
            {
                var employee = context.Employees.ToList();

                listEmployees.Items.Clear();
                employeesList.Clear();
                if (employee != null)
                {
                    foreach (var item in employee)
                    {
                        employeesList.Add(new EmployeeView
                        {
                            EmployeeName = item.FirstName + " " + item.MiddleName + " " + item.LastName
                        });
                    }
                }

                foreach (var item in employeesList.Where(c => c.EmployeeName.ToLower().Contains(text.ToLower())).ToList())
                {
                    listEmployees.Items.Add(item.EmployeeName);
                }
            }
        }
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            using (var context = new DatabaseContext())
            {
                if (AccountNumber != null)
                {
                    var account = context.CustomerAccounts.FirstOrDefault(c => c.AccountNumber == AccountNumber);

                    if (account != null)
                    {
                        var customer = context.Customers.FirstOrDefault(c => c.CustomerID == account.CustomerID);
                        var territory = context.Territories.FirstOrDefault(c => c.TerritoryID == account.TerritoryID);
                        var product = context.Products.FirstOrDefault(c => c.ProductID == account.ProductID);
                        var agent = context.Agents.FirstOrDefault(c => c.AgentId == account.AgentId);

                        if (customer != null && territory != null && product != null)
                        {
                            txtAccountNumber.Text = account.AccountNumber;
                            txtDiscount.Text = account.Discount;
                            txtGross.Text = account.Gross;
                            txtNetValue.Text = account.NetValue;
                            txtServiceCharge.Text = account.ServiceCharge;
                            txtCompanyName.Text = customer.CompanyName;
                            txtModeOfPayment.Text = account.ModeOfPayment;
                            txtProduct.Text = product.ProductName;
                            txtTerritory.Text = territory.TerritoryName;
                            txtAgent.Text = agent.AgentName;
                        }
                    }
                }
            }
        }
        public Quote ToQuote(DatabaseContext context)
        {
            var quote = new Quote();
            if (Id != 0)
                quote = context.Quotes.Find(quote.Id);
            else
                quote.CreatedAt = DateTime.Now;
            quote.Text = Text;
            quote.Context = Context;

            if(AuthorId != null && !context.Users.Any(u => u.Id == AuthorId))
                throw new InvalidOperationException();
            if(SubmitterId != null && !context.Users.Any(u => u.Id == SubmitterId))
                throw new InvalidOperationException();

            User author = null;
            User submitter = null;
            if (AuthorId != null)
                author = context.Users.Find(AuthorId);
            if (SubmitterId != null)
                submitter = context.Users.Find(SubmitterId);
            quote.Submitter = submitter;
            quote.Author = author;
            quote.AlternateAuthor = AlternateAuthor;

            quote.Tags = context.Tags.Where(x => Tags.Contains(x.Text)).ToList();
            return quote;
        }
Beispiel #15
0
        private Task<string> QueryValidateUser(string str1, string str2)
        {
            return Task.Factory.StartNew(() =>
            {
                try
                {
                    using (var context = new DatabaseContext())
                    {
                        var user = context.UserAccounts.FirstOrDefault(c => c.UserAccountId == str1
                            && c.Password == str2);

                        if (user != null)
                        {
                            empno = str1;
                            mainUser = user;
                            return null;
                        }
                        else
                        {
                            mainUser = null;
                            return "Invalid username or password";
                        }
                    }
                }
                catch (Exception ex)
                {
                    return "Error : " + ex.Message;
                }
            });
        }
Beispiel #16
0
 public ContentItem Add(ContentItem contentItem)
 {
     using (DatabaseContext context = new DatabaseContext())
     {
         return context.AddContentItem<MSSQL.Entities.ContentItem, ContentItem>(contentItem);
     }
 }
Beispiel #17
0
		static IQueryable<Journal> GetFiltered(Filter filter, DatabaseContext context)
		{
			IQueryable<Journal> result = context.Journal;
			if (filter.JournalTypes.Any())
				result = result.Where(x => filter.JournalTypes.Contains(x.JournalType));

			if (filter.ConsumerUIDs.Any())
				result = result.Where(x => filter.ConsumerUIDs.Contains(x.ObjectUID));

			if (filter.DeviceUIDs.Any())
				result = result.Where(x => filter.DeviceUIDs.Contains(x.ObjectUID));

			if (filter.UserUIDs.Any())
				result = result.Where(x => filter.UserUIDs.Contains(x.UserUID));

			if (filter.TariffUIDs.Any())
				result = result.Where(x => filter.TariffUIDs.Contains(x.ObjectUID));

			result = result.Where(x => x.DateTime > filter.StartDate && x.DateTime < filter.EndDate);

			if (filter.IsSortAsc)
				result = result.OrderBy(x => x.DateTime);
			else
				result = result.OrderByDescending(x => x.DateTime);

			return result;
		}
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            using (var context = new DatabaseContext())
            {
                if (SalesStageId > 0)
                {
                    var stage = context.SalesStages.FirstOrDefault(c => c.SalesStageID == SalesStageId);
                    if (stage != null)
                    {
                        lblsaleId.Visibility = Visibility.Visible;
                        txtSalesId.Visibility = Visibility.Visible;
                        Grid.SetRow(lblSaleName, 1);
                        Grid.SetRow(txtSalesStageName, 1); Grid.SetColumn(txtSalesStageName, 1);
                        Grid.SetRow(lblRAnk, 2);
                        Grid.SetRow(txtRankNo, 2); Grid.SetColumn(txtRankNo, 1);

                        txtSalesId.Text = Convert.ToString(stage.SalesStageID);
                        txtRankNo.Text = Convert.ToString(stage.RankNo);
                        txtSalesStageName.Text = stage.SalesStageName;
                    }
                }
                else
                {
                    lblsaleId.Visibility = Visibility.Hidden;
                    txtSalesId.Visibility = Visibility.Hidden;
                    Grid.SetRow(lblSaleName, 0);
                    Grid.SetRow(txtSalesStageName, 0); Grid.SetColumn(txtSalesStageName, 1);
                    Grid.SetRow(lblRAnk, 1);
                    Grid.SetRow(txtRankNo, 1); Grid.SetColumn(txtRankNo, 1);

                    txtSalesStageName.Text = "";
                    txtRankNo.Text = "";
                }
            }
        }
        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            using (var context = new DatabaseContext())
            {
                if (listProducts.SelectedItems != null)
                {
                    foreach (var product in listProducts.SelectedItems)
                    {
                        var convertedProduct = Convert.ToString(product);

                        var prod = context.Products.FirstOrDefault(c => c.ProductName == convertedProduct);

                        passList = prod.ProductName;
                    }
                    Variables.yesClicked = true;
                    var frame = DevExpress.Xpf.Core.Native.LayoutHelper.FindParentObject<NavigationFrame>(this);
                    frame.BackNavigationMode = BackNavigationMode.PreviousScreen;
                    frame.GoBack();
                    LeadForm.isSelectFinish = true;
                }
                else
                {
                    var window = new NoticeWindow();
                    NoticeWindow.message = "Please select a row.";
                    window.Height = 0;
                    window.Top = Application.Current.MainWindow.Top + 8;
                    window.Left = (screenWidth / 2) - (window.Width / 2);
                    if (screenLeftEdge > 0 || screenLeftEdge < -8) { window.Left += screenLeftEdge; }
                    window.ShowDialog();
                }
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            using (var context = new DatabaseContext())
            {
                var lead = context.Leads.FirstOrDefault(c => c.LeadID == LeadId);
                var territory = context.Territories.FirstOrDefault(c => c.TerritoryID == lead.TerritoryID);

                txtCompanyAddress.Text = lead.CompanyAddress;
                txtCompanyName.Text = lead.CompanyName;
                txtLeadId.Text = Convert.ToString(lead.LeadID);
                txtStatus.Text = lead.Status;
                txtTerritory.Text = territory.TerritoryName;
            }

            #region animation onLoading
            double screenWidth = Application.Current.MainWindow.Width;
            if (screenLeftEdge > 0 || screenLeftEdge < -8)
            {
                screenWidth += screenLeftEdge;
            }
            DoubleAnimation animation = new DoubleAnimation(0, this.Width, (Duration)TimeSpan.FromSeconds(0.3));
            DoubleAnimation animation2 = new DoubleAnimation(screenWidth, screenWidth - this.Width, (Duration)TimeSpan.FromSeconds(0.3));
            this.BeginAnimation(Window.WidthProperty, animation);
            this.BeginAnimation(Window.LeftProperty, animation2);
            #endregion
        }
        private void LoadProducts(string text)
        {
            using (var context = new DatabaseContext())
            {
                var products = context.Products.ToList();

                listProducts.Items.Clear();
                productsList.Clear();
                if (products != null)
                {
                    foreach (var product in products)
                    {
                        productsList.Add(new ProductView
                        {
                            ProductName = product.ProductName
                        });
                    }
                }

                foreach (var item in productsList.Where(c => c.ProductName.ToLower().Contains(text.ToLower()) && c.ProductName != " ").OrderBy(c => c.ProductID).ToList())
                {
                    listProducts.Items.Add(item.ProductName);
                }
            }
        }
Beispiel #22
0
		public JournalTranslator(DbService dbService)
		{
			DbService = dbService;
			Context = DbService.Context;
			JournalSynchroniser = new JounalSynchroniser(dbService);
			PassJournalSynchroniser = new PassJounalSynchroniser(dbService);
		}
Beispiel #23
0
 public void Update(Timeline timeline)
 {
     using (DatabaseContext context = new DatabaseContext())
     {
         context.Update<MSSQL.Entities.ContentItem, Timeline>(timeline, new string[] { "Id", "Timestamp" });
     }
 }
        public async Task<IHttpActionResult> CreatePoll(string name)
        {
            using (var dbContext = new DatabaseContext())
            {
                if (string.IsNullOrWhiteSpace(name))
                    return BadRequest().WithReason("A name is required");

                var exists = await GetPolls(dbContext, DateTime.Now)
                    .AnyAsync(p => p.Name == name);
                if (exists)
                    return StatusCode(HttpStatusCode.Conflict)
                        .WithReason("A poll with the same name already exists");

                var currentUser = await dbContext.Users.SingleAsync(u => u.UserName == User.Identity.Name);
                var poll = new LunchPoll
                {
                    Name = name,
                    Date = DateTime.Now,
                    Voters = new List<User>(),
                    Votes = new List<LunchVote>()
                };
                dbContext.LunchPolls.Add(poll);
                await AddToPoll(dbContext, poll, currentUser);
                await dbContext.SaveChangesAsync();

                LunchHub.OnPollChanged(new LunchPollViewModel(poll));
                return Ok();
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["New"] != null)
            {
                int hitchBotId = (int)Session[SessionInfo.HitchBotId];

                var skip = Request.QueryString["skip"];
                int skipOver = 0;

                if (int.TryParse(skip, out skipOver))
                {
                    currentSkip = skipOver;
                }

                using (var db = new DatabaseContext())
                {
                    var imageList = db.Images.Where(l => !l.TimeDenied.HasValue && l.TimeApproved.HasValue && l.HitchBotId == hitchBotId).OrderByDescending(l => l.TimeTaken).Skip(skipOver).Take(50).ToList();
                    var master = Master as imageGrid;

                    master.SetImageSkip(currentSkip);
                    master.SetImages(imageList);
                }
            }
            else
            {
                Response.Redirect("Unauthorized.aspx");
            }
        }
Beispiel #26
0
 public static UserEntity CreateActiveUser(string email, Role role)
 {
     using (var context = new DatabaseContext())
     {
         var passwordManager = new PasswordManager(new Configuration());
         var salt = passwordManager.GenerateSalt();
         var hashedPassword = passwordManager.HashPassword(Password, salt);
         var enctyptedSecurePhrase = passwordManager.EncryptSecurePhrase(Phrase);
         var user = new UserEntity
         {
             Id = Guid.NewGuid(),
             Email = email,
             FirstName = email,
             LastName = email,
             Role = role,
             UserState = UserState.Activated,
             PasswordSalt = salt,
             HashedPassword = hashedPassword,
             EncryptedSecurePhrase = enctyptedSecurePhrase,
             FirstSecurePhraseQuestionCharacterIndex = 0,
             SecondSecurePhraseQuestionCharacterIndex = 1,
         };
         context.Users.Add(user);
         context.SaveChanges();
         return user;
     }
 }
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            using (var context = new DatabaseContext())
            {
                var markstrat = new MarketingStrategy();

                if (MarketingStrategiesId > 0)
                {
                    var markstarte = context.MarketingStrategies.FirstOrDefault(c => c.MarketingStrategyId == MarketingStrategiesId);
                    if (markstarte != null)
                    {
                        lblMarketingStrategyId.Visibility = Visibility.Visible;
                        txtMarketingStrategyId.Visibility = Visibility.Visible;

                        Grid.SetRow(lblMarketingStrategyName, 1);
                        Grid.SetRow(txtMarketingStrategyName, 1); Grid.SetColumn(txtMarketingStrategyName, 1);

                        txtMarketingStrategyId.Text = Convert.ToString(markstarte.MarketingStrategyId);
                        txtMarketingStrategyName.Text = markstarte.Description;
                    }
                }
                else
                {
                    lblMarketingStrategyId.Visibility = Visibility.Hidden;
                    txtMarketingStrategyId.Visibility = Visibility.Hidden;

                    Grid.SetRow(lblMarketingStrategyName, 0);
                    Grid.SetRow(txtMarketingStrategyName, 0); Grid.SetColumn(txtMarketingStrategyName, 1);

                    txtMarketingStrategyName.Text = "";
                }
            }
        }
 public void Setup()
 {
     using (DatabaseContext ctx = new DatabaseContext())
     {
         ctx.Database.Delete();
         ctx.Database.Create();
     }
 }
Beispiel #29
0
 public IEnumerable<Timeline> FindAllPublicTimelines()
 {
     using (DatabaseContext context = new DatabaseContext())
     {
         string query = "SELECT [Timeline].[Id],BackgroundUrl,[RootContentItemId],[IsPublic],[BeginDate],[EndDate],[Title],[Description],[Timeline].[Timestamp] FROM [dbo].[Timeline] JOIN [dbo].[ContentItem] ON [dbo].[Timeline].[RootContentItemId] = [dbo].[ContentItem].[Id] where IsPublic=1";
         return context.Select<MSSQL.Entities.TimelineJoinContentItem, Timeline>(query);
     }
 }
Beispiel #30
0
 public AccountController()
 {
     DatabaseContext db = new DatabaseContext();
     userStore = new UserStore<ApplicationUser>(db);
     userManager = new ApplicationUserManager(userStore);
     UserManager = userManager;
     passwordHasher = new PasswordHasher();
 }
Beispiel #31
0
 public UnitOfWork(DatabaseContext databaseContext)
 {
     this._databaseContext = databaseContext;
 }
Beispiel #32
0
 public GradeRepository(DatabaseContext dbContext) : base(dbContext)
 {
 }
Beispiel #33
0
 public App(IConfiguration config, DatabaseContext databaseContext, IServiceProvider serviceProvider)
 {
     _config          = config;
     _databaseContext = databaseContext;
     _serviceProvider = serviceProvider;
 }
 public UpdateWorkUnitCommandHandler(DatabaseContext context, IMapper mapper)
 {
     this.context = context;
     this.mapper  = mapper;
 }
        /// <summary>
        ///     Handles post data.
        /// </summary>
        /// <param name="entityData">The entity data.</param>
        /// <param name="returnMap">if set to <c>true</c> [return map].</param>
        /// <returns></returns>
        private HttpResponseMessage HandlePost(JsonEntityQueryResult entityData, bool returnMap)
        {
            Stopwatch sw = Stopwatch.StartNew( );
            long      t1;

            // resolve all entity ids above our 'known id hi watermark' that actually do exist
            entityData.ResolveIds( );

            long id = entityData.Ids.FirstOrDefault( );
            IDictionary <long, IEntity> map = null;

            if (id >= JsonEntityQueryResult.BaseNewId)
            {
                // create
                EventLog.Application.WriteTrace("Creating entity " + id);
                EntityData newEntityData = entityData.GetEntityData(id);

                t1 = sw.ElapsedMilliseconds;

                DatabaseContext.RunWithRetry(() =>
                {
                    using (DatabaseContext context = DatabaseContext.GetContext(true))
                    {
#pragma warning disable 618
                        var svc = new EntityInfoService();
#pragma warning restore 618

                        map = svc.CreateEntityGetMap(newEntityData);

                        IEntity entity = map[newEntityData.Id.Id];
                        id             = entity == null ? -1 : entity.Id;

                        context.CommitTransaction();
                    }
                });


                EventLog.Application.WriteTrace("EntityPost create took {0} msec ({1} to de-json)",
                                                sw.ElapsedMilliseconds, t1);
            }
            else
            {
                map = new Dictionary <long, IEntity>( );

                EventLog.Application.WriteTrace("Updating entity " + id);
                EntityData newEntityData = entityData.GetEntityData(id);

                t1 = sw.ElapsedMilliseconds;


                DatabaseContext.RunWithRetry(() =>
                {
                    using (DatabaseContext context = DatabaseContext.GetContext(true))
                    {
#pragma warning disable 618
                        var svc = new EntityInfoService();
#pragma warning restore 618
                        svc.UpdateEntity(newEntityData);

                        context.CommitTransaction();
                    }
                });

                EventLog.Application.WriteTrace("EntityPost update took {0} msec ({1} to de-json)",
                                                sw.ElapsedMilliseconds, t1);
            }


            HttpResponseMessage httpResponseMessage;

            if (returnMap)
            {
                /////
                // Create a custom response message so the infrastructure framework doesn't serialize it twice.
                /////
                httpResponseMessage = new HttpResponseMessage
                {
                    Content = new StringContent(DictionaryToJson(map))
                };

                httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            }
            else
            {
                httpResponseMessage = new HttpResponseMessage <long>(id);
            }

            return(httpResponseMessage);
        }
Beispiel #36
0
 public RatingsRepository(DatabaseContext context)
 {
     db = context;
 }
Beispiel #37
0
        public PersonRepository(DatabaseContext databaseContext)
        {
            Guard.ArgumentNotNull(databaseContext, nameof(databaseContext));

            _persons = databaseContext.Persons;
        }
 public ReviewRepository(DatabaseContext context) : base(context)
 {
 }
 public QLHoaDon()
 {
     InitializeComponent();
     session = new DatabaseContext();
 }
Beispiel #40
0
 public RequisitionController(DatabaseContext databaseContext)
 {
     _databaseContext = databaseContext;
 }
Beispiel #41
0
 public CategoryRepository(DatabaseContext databaseContext) : base(databaseContext)
 {
 }
Beispiel #42
0
 public Repository(DatabaseContext context)
 {
     this.context = context;
     entities     = context.Set <T>();
 }
 public UserTypeResponsitory(DatabaseContext dbContext) : base(dbContext)
 {
 }
Beispiel #44
0
 public QuestionRepository(DatabaseContext context)
 {
     _context = context;
 }
 public VeiculosRepository(DatabaseContext _db)
 {
     db = _db;
 }
 public InventoryController(DatabaseContext _context)
 {
     this.context = _context;
 }
 public MenuMasterViewComponent(DatabaseContext context)
 {
     _context = context;
 }
Beispiel #48
0
 /// <summary>
 /// Default constructor of the controller
 /// </summary>
 /// <remarks>This constructor shouldn't be used directly on code. Called by the runtime</remarks>
 /// <param name="context">Context connection of the database</param>
 public historicdataController(DatabaseContext context)
 {
     db = context;
 }
Beispiel #49
0
 public ChallengeService(DatabaseContext context)
 {
     _context = context;
 }
Beispiel #50
0
 public VaccineRepo(DatabaseContext context)
     : base(context)
 {
 }
Beispiel #51
0
 public EditModel(DatabaseContext context)
 {
     _context = context;
 }
Beispiel #52
0
 public BookHasStudentRepository(DatabaseContext context) : base(context)
 {
 }
 public PurchaseRepository(DatabaseContext context) : base(context)
 {
 }
Beispiel #54
0
 public MusicRepository(DatabaseContext context)
 {
     _context = context;
 }
 public GuardianEfficiencyRepository(DatabaseContext databaseContext)
 {
     _databaseContext = databaseContext;
 }
Beispiel #56
0
 public DeleteScheduleCommandHandler(DatabaseContext context)
 {
     this.context = context;
 }
Beispiel #57
0
 public PoemController(DatabaseContext database)
 {
     this.database = database;
 }
 public OrdersController(DatabaseContext context)
 {
     _context = context;
 }
 public Handler(DatabaseContext context, IMapper mapper) : base(context, mapper)
 {
 }
Beispiel #60
0
 public AuditService(DatabaseContext databaseContext)
 {
     this._databaseContext = databaseContext;
 }