Пример #1
0
        public int AddOrder(Order order)
        {
            try
            {
                _db.BeginTransaction();
                // Do transacted updates here
                var poco         = _orderMapper.MapToPoco(order);
                var insertResult = _db.Insert("Orders", "Id", poco);
                var id           = Convert.ToInt32(insertResult);
                foreach (var orderedMeal in poco.OrderedMeals)
                {
                    orderedMeal.OrderId = id;
                    _db.Insert("OrderedMeals", "Id", orderedMeal);
                }

                // Commit
                _db.CompleteTransaction();
                return(id);
            }
            catch (Exception)
            {
                _db.AbortTransaction();
                throw;
            }
        }
Пример #2
0
        private void InsertData()
        {
            var account = new Account()
            {
                //AccessToken = Guid.NewGuid(),
                AccessToken = new Guid("6bd10bc4-1d31-478a-8abc-78560086286b"),
                CreatedBy   = 0,
                CreatedOn   = DateTime.Now,
                UpdatedOn   = DateTime.Now,
                IsEnabled   = true,
                Name        = "Pete Test",
                Notes       = "Just as test account setup in the create initial tables migration",
            };

            _database.Insert(account);

            var accountSetting = new AccountSettings()
            {
                AccountId         = account.Id,
                DocTypeAlias      = "home",
                PropertyTypeAlias = "sitename",
                IsBuiltInProperty = false,
                Permission        = Permissions.Read,
                CreatedOn         = DateTime.Now,
                UpdatedOn         = DateTime.Now,
                Notes             = ""
            };

            _database.Insert(accountSetting);
        }
Пример #3
0
 public void Insert(Order order, OrderItem[] items)
 {
     using (var tx = new TransactionScope())
     {
         order.Total = items.Sum(p => p.Qty * p.UnitPrice);
         db.Insert("Orders", "Id", order);
         foreach (var item in items)
         {
             item.OrderId = order.Id;
             db.Insert("OrderItems", "OrderId,ProductId", item);
         }
         tx.Complete();
     }
 }
Пример #4
0
 /// <summary>
 /// Import the settings export model back into the database. This is destructive.
 /// </summary>
 /// <param name="model">Object of type <see cref="WorkflowSettingsExport"/></param>
 public void ImportSettings(WorkflowSettingsExport model)
 {
     // delete first as this is an import and should be destructive
     _database.Execute("DELETE FROM WorkflowSettings");
     _database.Insert(new WorkflowSettingsPoco
     {
         DefaultApprover   = model.DefaultApprover,
         EditUrl           = model.EditUrl,
         Email             = model.Email,
         ExcludeNodes      = model.ExcludeNodes,
         FlowType          = model.FlowType,
         SendNotifications = model.SendNotifications,
         SiteUrl           = model.SiteUrl
     });
 }
Пример #5
0
        public System.Web.Http.IHttpActionResult AddSeason(Season season)
        {
            if (ModelState.IsValid)
            {
                //get unfilled model fields
            }

            if (season.Season_Title.IsNullOrWhiteSpace() || season.Season_Location.IsNullOrWhiteSpace() ||
                season.Season_Start_Date == DateTime.MinValue || season.Season_End_Date == DateTime.MinValue)
            {
                return(Content(System.Net.HttpStatusCode.BadRequest, "Null fields"));
            }

            UmbracoDatabase db          = ApplicationContext.DatabaseContext.Database;
            var             seasonToAdd = new Season
            {
                Season_Title      = season.Season_Title,
                Season_Location   = season.Season_Location,
                Season_Start_Date = season.Season_Start_Date,
                Season_End_Date   = season.Season_End_Date
            };

            try
            {
                db.Insert(seasonToAdd);
            }
            catch (System.Exception exception)
            {
                return(Content(System.Net.HttpStatusCode.BadRequest, exception));
            }

            return(Ok(seasonToAdd));
        }
        /// <summary>
        /// Adds a property to the favorites
        /// </summary>
        /// <param name="propertyName">
        /// The name of the property to add
        /// </param>
        /// <returns>
        /// Whether or not the property was successfully added
        /// </returns>
        public bool AddFavoriteContent(string propertyName, int userId, bool?setFavorite = true)
        {
            try
            {
                var favoriteProperties = GetAllPropertiesByUser(userId).Where(x => !x.IsFavorite.HasValue || x.IsFavorite.Value);
                var newFavoriteContent = new FavoriteContentModel
                {
                    IsFavorite   = setFavorite,
                    PropertyName = propertyName,
                    UseCount     = 1,
                    UserId       = userId,
                    SortOrder    = favoriteProperties == null ? 0 : favoriteProperties.Count(),
                    LastUpdated  = DateTime.UtcNow
                };

                db.Insert(newFavoriteContent);

                return(true);
            }
            catch (Exception ex)
            {
                LogHelper.Error <FavoriteContentRepository>("Unable to add property" + propertyName + "to the FavoriteContent database table.", ex);
                return(false);
            }
        }
Пример #7
0
        public int AddRestaurant(Restaurant restaurant)
        {
            var poco = _mapper.MapToPoco(restaurant);

            var id = _db.Insert("Restaurants", "Id", poco);

            return(decimal.ToInt32((decimal)id));
        }
Пример #8
0
 private void CreateAndSaveMediaXml(XElement xml, int id, UmbracoDatabase db)
 {
     var poco = new ContentXmlDto {
         NodeId = id, Xml = xml.ToString(SaveOptions.None)
     };
     var exists = db.FirstOrDefault <ContentXmlDto>("WHERE nodeId = @Id", new { Id = id }) != null;
     int result = exists ? db.Update(poco) : Convert.ToInt32(db.Insert(poco));
 }
Пример #9
0
        public void AddUserToGroup(int groupId, int backofficeUserId)
        {
            var toInsert = new EasyADGroup2User {
                GroupId = groupId, UserId = backofficeUserId
            };

            _database.Insert(toInsert);
        }
Пример #10
0
        public Guid Create(TEntityType entity)
        {
            var id = Guid.NewGuid();

            entity.Id        = id;
            entity.CreatedOn = DateTimeOffset.UtcNow.ToUtc();
            _database.Insert(entity);
            return(id);
        }
Пример #11
0
        public void Save(UmbracoTwenty.Models.ContactFormModel model)
        {
            ContactFormPoco poco = new ContactFormPoco();

            poco.Name    = model.Name;
            poco.Email   = model.Email;
            poco.Subject = model.Subject;
            poco.Message = model.Message;
            poco.Date    = DateTime.Now;
            _database.Insert(poco);
        }
Пример #12
0
        /// <summary>
        /// Get the current workflow settings, or persist an empty instance if none exist
        /// </summary>
        /// <returns>A object of type <see cref="WorkflowSettingsPoco"/> representing the current settings</returns>
        public WorkflowSettingsPoco GetSettings()
        {
            var wsp = new WorkflowSettingsPoco();
            List <WorkflowSettingsPoco> settings = _database.Fetch <WorkflowSettingsPoco>(SqlQueries.GetSettings);

            if (settings.Any())
            {
                wsp = settings.First();
            }
            else
            {
                _database.Insert(wsp);
            }

            if (string.IsNullOrEmpty(wsp.Email))
            {
                wsp.Email = UmbracoConfig.For.UmbracoSettings().Content.NotificationEmailAddress;
            }

            return(wsp);
        }
Пример #13
0
        /// <summary>
        /// Creates the Configuration table
        /// </summary>
        public override void Up()
        {
            //  Environment
            if (_schemaHelper.TableExist <Dto.Environment.Environment100>())
            {
                var sql = new Sql().Where("id != 1");
                _database.Delete <Dto.Environment.Environment100>(sql);

                Alter.Table <Dto.Environment.Environment103>().AddColumn(nameof(Dto.Environment.Environment103.SortOrder)).AsInt32().NotNullable().WithDefaultValue(Constants.Tree.DefaultEnvironmentSortOrder);
                Alter.Table <Dto.Environment.Environment103>().AddColumn(nameof(Dto.Environment.Environment103.Enable)).AsBoolean().NotNullable().WithDefaultValue(true);
                Alter.Table <Dto.Environment.Environment103>().AddColumn(nameof(Dto.Environment.Environment103.ContinueProcessing)).AsBoolean().NotNullable().WithDefaultValue(true);
                Alter.Table <Dto.Environment.Environment103>().AddColumn(nameof(Dto.Environment.Environment103.ColorIndicator)).AsString(7).NotNullable().WithDefaultValue("#df7f48");
            }
            else
            {
                _schemaHelper.CreateTable <Dto.Environment.Environment103>();
                _database.Insert(new Dto.Environment.Environment103
                {
                    Name               = "Default",
                    Icon               = "icon-firewall red",
                    Enable             = true,
                    ContinueProcessing = true,
                    SortOrder          = Constants.Tree.DefaultEnvironmentSortOrder,
                    ColorIndicator     = "#df7f48"
                });
            }

            //  Domain
            if (!_schemaHelper.TableExist <Dto.Domain.Domain100>())
            {
                _schemaHelper.CreateTable <Dto.Domain.Domain100>();
            }

            //  Configuration
            if (!_schemaHelper.TableExist <Dto.Configuration.Configuration100>())
            {
                _schemaHelper.CreateTable <Dto.Configuration.Configuration103>();
            }

            //  Journal
            if (_schemaHelper.TableExist <Dto.Journal.Journal100>())
            {
                Delete.Index("IX_" + nameof(Shield) + "_" + nameof(Dto.Journal.Journal100.Datestamp)).OnTable <Dto.Journal.Journal100>();
                Create.Index("IX_" + nameof(Shield) + "_" + nameof(Dto.Journal.Journal103.Datestamp)).OnTable <Dto.Journal.Journal103>()
                .OnColumn(nameof(Dto.Journal.Journal103.Datestamp)).Ascending().WithOptions().NonClustered();
            }
            else
            {
                _schemaHelper.CreateTable <Dto.Journal.Journal103>();
            }
        }
Пример #14
0
        public IDataType AddPreValueJson(object value, int sortOrder = 0, string alias = "")
        {
            var dtpv = new DataTypePreValueDto
            {
                Alias          = alias,
                Value          = JsonConvert.SerializeObject(value),
                DataTypeNodeId = DataTypeDefinition.Id,
                SortOrder      = sortOrder
            };

            UmbracoDatabase.Insert(dtpv);

            return(this);
        }
Пример #15
0
        public IDataType AddPreValue(string value, int sortOrder = 0, string alias = "")
        {
            var dtpv = new DataTypePreValueDto
            {
                Alias          = alias,
                Value          = value,
                DataTypeNodeId = DataTypeDefinition.Id,
                SortOrder      = sortOrder
            };

            UmbracoDatabase.Insert(dtpv);

            return(this);
        }
Пример #16
0
        /// <summary>
        /// Save the blob back to the database
        /// </summary>
        /// <param name="model"></param>
        public void SavePromos(IEnumerable <PromoModel> model)
        {
            _database.Execute("DELETE FROM PromoteModules");

            // stringify the json to store a simple blob
            List <PromoPoco> toSave = model.Select((p, i) => new PromoPoco
            {
                Promo = JsonConvert.SerializeObject(p)
            }).ToList();

            foreach (PromoPoco m in toSave)
            {
                _database.Insert(m);
            }
        }
Пример #17
0
        public void SaveUserLogins(int memberId, IEnumerable <UserLoginInfo> logins)
        {
            using (var t = _db.GetTransaction())
            {
                //clear out logins for member
                _db.Execute("DELETE FROM ExternalLogins WHERE UserId=@userId", new { userId = memberId });

                //add them all
                foreach (var l in logins)
                {
                    _db.Insert(new ExternalLoginDto
                    {
                        LoginProvider = l.LoginProvider,
                        ProviderKey   = l.ProviderKey,
                        UserId        = memberId
                    });
                }

                t.Complete();
            }
        }
        /// <summary>
        /// Insert a new Auth Token into the custom DB table OR
        /// Update just the auth token if we find a record for the backoffice user already
        /// </summary>
        /// <param name="authToken"></param>
        public static void InsertAuthToken(UmbracoAuthToken authToken)
        {
            //Just to be 100% sure for data sanity that a record for the user does not exist already
            var existingRecord = GetAuthToken(authToken.IdentityId);

            //Insert new record if no item exists already
            if (existingRecord == null)
            {
                //Getting issues with insert & ID being 0 causing a conflict
                Database.Insert(authToken);
            }
            else
            {
                //Update the existing record
                existingRecord.AuthToken   = authToken.AuthToken;
                existingRecord.DateCreated = authToken.DateCreated;

                //Save the existing record we found
                Database.Save(existingRecord);
            }
        }
Пример #19
0
        public System.Web.Http.IHttpActionResult AddGame(Game game)
        {
            UmbracoDatabase db        = ApplicationContext.DatabaseContext.Database;
            var             gameToAdd = new Game
            {
                Season_Id     = game.Season_Id,
                Game_Date     = game.Game_Date,
                Game_Location = game.Game_Location,
                Opposing_Team = game.Opposing_Team
            };

            try
            {
                db.Insert(gameToAdd);
            }
            catch (System.Exception exception)
            {
                return(Content(System.Net.HttpStatusCode.BadRequest, exception));
            }

            return(Ok(gameToAdd));
        }
Пример #20
0
        public void FlagMigrationAsStarted(IUmbracoMigration migration)
        {
            try
            {
                UmbracoDatabase.OpenSharedConnection();

                using (var transaction = GetTransaction())
                {
                    var row = new MigrationHistory
                    {
                        Completed = false,
                        Name      = migration.GetType().Name,
                        Timestamp = DateTime.UtcNow
                    };

                    UmbracoDatabase.Insert(row);
                    transaction.Complete();
                }
            }
            finally
            {
                UmbracoDatabase.CloseSharedConnection();
            }
        }
 /// <summary>
 /// Create settings
 /// </summary>
 /// <param name="entity">TSetting</param>
 public void Create(TSetting entity)
 {
     _database.Insert(entity);
 }
        public ActionResult SaveProperty(PropertyViewModel propertyModel)
        {
            if (!ModelState.IsValid)
            {
                return(CurrentUmbracoPage());
            }

            //fill the reference number and other data to be calculated
            try
            {
                PropertyDBModel propertyModeltoSave = new PropertyDBModel();

                //Get Max ID from the Database
                var    str       = new Sql().Select("MAX(PropID)+1").From(TABLE_NAME);
                long   nextID    = db.Fetch <long>(str).FirstOrDefault();
                string fullRefNo = propertyModel.ReferenceNo + nextID.ToString();
                string imagePath = StringConstants.IMAGE_PATH + fullRefNo + "/" + StringConstants.THUMBNAIL_FOLDER_NAME;


                //Load Data from view model into business model
                //propertyModeltoSave.PropId = nextID;
                propertyModeltoSave.PropertyTitle      = propertyModel.PropertyTitle;
                propertyModeltoSave.CategoryId         = propertyModel.CategoryId;
                propertyModeltoSave.LocationId         = propertyModel.LocationId;
                propertyModeltoSave.TypeId             = propertyModel.TypeId;
                propertyModeltoSave.ReferenceNo        = fullRefNo;
                propertyModeltoSave.MainFeature        = propertyModel.MainFeature;
                propertyModeltoSave.Address            = propertyModel.Address;
                propertyModeltoSave.TotalSize          = propertyModel.TotalSize;
                propertyModeltoSave.BuildUpArea        = propertyModel.BuildUpArea;
                propertyModeltoSave.ReraPermitNo       = propertyModel.ReraPermitNo;
                propertyModeltoSave.SellPrice          = propertyModel.SellPrice;
                propertyModeltoSave.carparking         = propertyModel.carparking;
                propertyModeltoSave.bedrooms           = propertyModel.bedrooms;
                propertyModeltoSave.baths              = propertyModel.baths;
                propertyModeltoSave.AvailabilityStatus = propertyModel.AvailabilityStatus;
                propertyModeltoSave.DevelopmentStatus  = propertyModel.DevelopmentStatus;
                propertyModeltoSave.ServiceId          = propertyModel.ServiceId;

                propertyModeltoSave.PropertyDetailPageID = fullRefNo;
                propertyModeltoSave.PropertyImagePath    = imagePath;
                propertyModeltoSave.PropertyOwnerId      = 1;
                propertyModeltoSave.UserId    = 1;
                propertyModeltoSave.CreatedOn = System.DateTime.Now;


                db = ApplicationContext.Current.DatabaseContext.Database;


                db.Insert(TABLE_NAME_DB, ID_COLUMN_NAME, propertyModeltoSave);

                TempData["PropertySavedSuccess"] = true;
                TempData["ReferenceNo"]          = fullRefNo;

                //create a detail node in umbrco  content area
                UmbracoUtils utils = new UmbracoUtils();
                utils.CreateDetailContentNode(fullRefNo, null);



                return(RedirectToCurrentUmbracoPage());
            }
            catch (Exception ex)
            {
                ErrorController ec = new ErrorController();
                ec.LogErrorinDb(ex);
                return(CurrentUmbracoPage());
                //log message
            }
            //return PartialView(StringConstants.PARTIAL_VIEW_PATH + PARTIAL_VIEW_CREATE, await Task.FromResult(propertyModel));
        }
Пример #23
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="poco"></param>
 public void InsertTask(WorkflowTaskInstancePoco poco)
 {
     _database.Insert(poco);
 }
Пример #24
0
 /// <summary>
 /// Create state
 /// </summary>
 /// <param name="entity">TState</param>
 public void Create(TState entity)
 {
     _database.Insert(entity);
 }
Пример #25
0
        public async Task <HttpResponseMessage> Upload()
        {
            if (!this.Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            UmbracoDatabase db       = ApplicationContext.DatabaseContext.Database;
            var             provider = new MultipartFormDataStreamProvider(Path.GetTempPath());
            await Request.Content.ReadAsMultipartAsync(provider);

            var file = provider.FileData.Count > 0 ? provider.FileData.First() : null;

            // check if any file is uploaded
            if (file == null)
            {
                return(this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "No file uploaded"));
            }

            string fileName      = file.Headers.ContentDisposition.FileName.Trim('"');
            string fileExtension = fileName.Substring(fileName.LastIndexOf('.') + 1);

            // check if the file of the required type
            if (fileExtension != "csv")
            {
                return(this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Required format *.csv"));
            }

            string gameId = provider.FormData.GetValues("gameId").First();
            var    game   = new Game();

            // check if game is selected
            if (gameId != "undefined")
            {
                // get game instance for uploaded file
                game = db.SingleOrDefault <Game>(new Sql()
                                                 .Select("*")
                                                 .From("Games")
                                                 .Where(string.Format("Game_Id = {0}", Int32.Parse(gameId))));
            }
            else
            {
                return(this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "No game selected"));
            }

            // get all stat types to parse file
            var statTypes = db.Fetch <StatType>(new Sql()
                                                .Select("*")
                                                .From("StatTypes"));


            string[] csvFileContent = File.ReadAllLines(file.LocalFileName);
            foreach (string line in csvFileContent.Skip(1))
            {
                if (!line.IsNullOrWhiteSpace())
                {
                    string[] words      = line.Split(','); // contains period, time, descr, playerid
                    int      statTypeId = 0;
                    foreach (var statType in statTypes)
                    {
                        // parse *description* from CSV to match it with StatType
                        if (words[2].Contains(statType.Stat_Type_Keyphrase))
                        {
                            statTypeId = statType.Stat_Type_Id;
                            break;
                        }
                    }

                    var stat = new Stat
                    {
                        Game_Id   = game.Game_Id,
                        Period    = Int32.Parse(words[0]),
                        Stat_Time = new DateTime(game.Game_Date.Year, game.Game_Date.Month, game.Game_Date.Day,
                                                 Int32.Parse(words[1].Substring(0, words[1].LastIndexOf(':'))),
                                                 Int32.Parse(words[1].Substring(words[1].LastIndexOf(':') + 1)), 0),
                        Stat_Type_Id = statTypeId,
                        Player_Id    = Int32.Parse(words[3])
                    };
                    db.Insert(stat);
                }
            }

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
Пример #26
0
 public void Insert <T>(T form) where T : CustomForm
 {
     _db.Insert(form);
 }
Пример #27
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="poco"></param>
 public void InsertInstance(WorkflowInstancePoco poco)
 {
     _database.Insert(poco);
 }
Пример #28
0
        public Product Insert(Product product)
        {
            var id = db.Insert("Products", "Id", product);

            return(product);
        }
 public void Insert <T>(T record)
 {
     db.Insert(record);
 }
 /// <summary>
 /// Create Statistic
 /// </summary>
 /// <param name="entity">TImageStatistic</param>
 public void Create(TImageStatistic entity)
 {
     _database.Insert(entity);
 }