コード例 #1
0
        public static int Increment()
        {
            int result;
            int valueInrement;

            using (EFDbContext context = new EFDbContext())
            {

                result = context.Increment.First().Counter;
                valueInrement = result;

                context.Increment.First().Counter = ++valueInrement;
                context.SaveChanges();
            }
            return result;
        }
コード例 #2
0
        public async Task SendMsg(string content)
        {
            Messages message = new Messages();

            message.nick     = g.nick;
            message.sid      = g.sid;
            message.roomName = g.roomName;
            message.message  = content;
            try
            {
                db.message.Add(message);
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            await this.InvokeTo(c => c.g.inRoom() && c.g.roomName == g.roomName, new { content = content, authorSid = g.sid }, "msgSent");
        }
コード例 #3
0
        public void RemoveBooking(int bookId, string username)//, int bookId)
        {
            var ctx     = new EFDbContext();
            var userId  = ctx.Users.FirstOrDefault(u => u.Login == username).UserID;
            var booking = ctx.Bookings.FirstOrDefault(b => b.BookID == bookId && b.UserID == userId);

            if (booking != null)
            {
                ctx.Bookings.Remove(booking);
                ctx.SaveChanges();

                //Clients.All.receivedNewComment( username, message);
                Clients.All.receivedRemovedBooking(booking.BookID, username, booking.BookedDate);
            }
            else
            {
                Clients.All.failure();
            }
        }
コード例 #4
0
        public void AddBooking(int bookId, string username)//, int bookId)
        {
            var ctx    = new EFDbContext();
            var userId = ctx.Users.FirstOrDefault(u => u.Login == username).UserID;

            if (ctx.Bookings.FirstOrDefault(b => b.BookID == bookId && b.UserID == userId) != null)
            {
                Clients.All.failure();
            }
            else
            {
                var booking = new Booking {
                    BookID = bookId, UserID = userId, Booked = true, Issued = false, BookedDate = DateTime.Now, IssuedDate = null
                };
                ctx.Bookings.Add(booking);
                ctx.SaveChanges();
                Clients.All.receivedNewBooking(booking.BookID, username, booking.BookedDate);
            }
        }
コード例 #5
0
 public void SaveCarFromViewModel(CarModelBrandViewModel viewModel, Car car)
 {
     if (car.CarId == 0)
     {
         EFDbContext.Cars.Add(car);
     }
     else
     {
         Car dbEntry = EFDbContext.Cars.Find(viewModel.Car.CarId);
         if (dbEntry != null)
         {
             dbEntry.Model       = viewModel.Car.Model;
             dbEntry.Model.Brand = viewModel.Car.Model.Brand;
             dbEntry.Price       = viewModel.Car.Price;
             dbEntry.YearOfIssue = viewModel.Car.YearOfIssue;
         }
     }
     EFDbContext.SaveChanges();
 }
コード例 #6
0
 public void SaveOwner(Owner owner)
 {
     if (owner.OwnerId == 0)
     {
         EFDbContext.Owners.Add(owner);
     }
     else
     {
         Owner dbEntry = EFDbContext.Owners.Find(owner.OwnerId);
         if (dbEntry != null)
         {
             dbEntry.FirstName         = owner.FirstName;
             dbEntry.LastName          = owner.LastName;
             dbEntry.DrivingExperience = owner.DrivingExperience;
             dbEntry.BirthDate         = owner.BirthDate;
             dbEntry.Cars = owner.Cars;
         }
     }
     EFDbContext.SaveChanges();
 }
コード例 #7
0
        public IActionResult Details(int id)
        {
            var auction = context.Auctions.Find(id);

            context.Entry(auction).Reference(a => a.User).Load();
            context.Entry(auction).Reference(a => a.Article).Load();
            context.Entry(auction).Reference(a => a.LastBid).Load();

            var winner = context.Users.Find(auction.LastBid.UserId);


            string deadline = (auction.Start + auction.Duration).ToString("yyyy-MM-dd hh:mm");
            var    result   = new AuctionViewModel
            {
                UserName           = auction.User.UserName,
                User               = GetUser(auction.User.UserName),
                Duration           = auction.Duration,
                Start              = auction.Start,
                Article            = auction.Article,
                ArticleId          = auction.ArticleId,
                Name               = auction.Title,
                AuctionDescription = auction.Article.Description,
                Price              = auction.CurrentPrice,
                LastBid            = auction.LastBid,
                IsFinished         = auction.IsFinished,
                HasStarted         = auction.HasStarted,
                Biders             = auction.Biders,
                Min_Bid            = auction.Min_Bid,
                Paid               = auction.Paid,
                Winner             = winner.UserName,
                Deadline           = deadline
            };

            //Checks if the auction has started
            if (auction.Start <= DateTime.Now)
            {
                auction.HasStarted = true;
                result.HasStarted  = true;
                context.SaveChanges();
            }
            //Checks if the auction is over
            if (auction.Duration < DateTime.Now - auction.Start)
            {
                auction.IsFinished = true;
                result.IsFinished  = true;
                context.SaveChanges();
            }
            return(View(result));
        }
コード例 #8
0
        private static void PopulateDate()
        {
            using (var ctx = new EFDbContext())
            {
                for (int i = 1; i < 50; i++)
                {
                    var product = new Product()
                    {
                        Title       = "Think in " + i,
                        Author      = "J",
                        Price       = 100 + i,
                        CategoryId  = (i % 4).ToString(),
                        Description = " " + i + " Great!"
                    };

                    ctx.Products.Add(product);
                    ctx.SaveChanges();
                }
            }
        }
コード例 #9
0
        public void Delete_Book()
        {
            var t = new EFDbContext();
            var r = new EFBookRepository();
            //var b = new Book;
            var count = t.Books.Count();
            var books = t.Books.ToList();
            var id    = books.LastOrDefault();

            if (id != null)
            {
                r.DeleteBook(id.BookId);
            }

            t.SaveChanges();

            var result = t.Books.Count();

            result.Should().Be(count - 1);
        }
コード例 #10
0
        // [InlineData("Oxxxy")]
        // [InlineData("Оруэл")]
        // [InlineData("Замятиг")]

        public void Add_Book()
        {
            var t     = new EFDbContext();
            var count = t.Books.Count();
            var b     = new Book
            {
                BookId      = 17,
                Author      = "Oxxxy",
                Name        = "Gorgorod",
                Publishing  = "BookingMashine",
                Year        = 2015,
                Description = "Любовная история посреди антиутопии."
            };

            t.Books.Add(b);
            t.SaveChanges();
            var result = t.Books.Count();

            result.Should().Be(count + 1);
        }
コード例 #11
0
        public ActionResult Edit(Person person)
        {
            try {
                if (ModelState.IsValid)
                {
                    db.Persons.Add(person);
                    db.SaveChanges();
                    // repository.SavePerson(person);
                    TempData["message"] = string.Format("Zapisano {0} ", person.Name);
                    return(RedirectToAction("Index"));
                }
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }

            return(View(person));
        }
コード例 #12
0
        public ActionResult CreateTickets(Ticket createTickets)
        {
            if (ModelState.IsValid)
            {
                Ticket t = new Ticket();
                t.ProjectName      = createTickets.ProjectName;
                t.DateTimeReceived = DateTime.Now;
                t.EmployeeId       = createTickets.EmployeeId;
                t.Description      = createTickets.Description;

                db.Tickets.Add(t);
                db.SaveChanges();

                return(View("Completed"));
            }
            else
            {
                return(View("Index"));
            }
        }
コード例 #13
0
 public void SaveEntities(Test t)
 {
     using (EFDbContext context = new EFDbContext())
     {
         if (t.id == 0)
         {
             context.tests.Add(t);
         }
         else
         {
             Test dbEntry = context.tests.Find(t.id);
             if (dbEntry != null)
             {
                 dbEntry.id   = t.id;
                 dbEntry.name = t.name;
             }
         }
         context.SaveChanges();
     }
 }
コード例 #14
0
 public IActionResult Create([FromBody] OrderAddVM model)
 {
     if (!ModelState.IsValid)
     {
         var errors = CustomValidator.GetErrorsByModel(ModelState);
         return(BadRequest(errors));
     }
     {
         Order m = new Order
         {
             CarId    = model.Car.Id,
             Price    = float.Parse(model.Car.Price.ToString()),
             ClientId = model.Client.Id,
             Date     = model.Date
         };
         _context.Orders.Add(m);
         _context.SaveChanges();
         return(Ok("Дані добалено"));
     }
 }
コード例 #15
0
        static void Main(string[] args)
        {
            using (var ctx = new EFDbContext())
            {
                var product = new Product()
                {
                    Name        = "name-001",
                    Price       = 1.2M,
                    Description = "des01",
                    Category    = "C1"
                };


                ctx.Products.Add(product);
                ctx.SaveChanges();
            }

            Console.WriteLine("Done.");
            Console.ReadLine();
        }
コード例 #16
0
        public ActionResult Create(Transportfleet transportfleet)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Transportfleets.Add(transportfleet);
                    db.SaveChanges();
                    repository.SaveTransportfleet(transportfleet);

                    return(RedirectToAction("Index"));
                }
            }
            catch (RetryLimitExceededException /* dex */)
            {
                ModelState.AddModelError("", "Nie udało się zapisać");
            }
            Populate(transportfleet.actID);
            return(View(transportfleet));
        }
コード例 #17
0
        public ViewResult Register(User user)
        {
            EFDbContext dbContext = new EFDbContext();

            dbContext.Users.Add(new User
            {
                FirstName = user.FirstName,
                LastName  = user.LastName,
                //SurName = null,
                //Age = 25,
                //Country = null,
                Email = user.Email,
                Pass  = user.Pass
            });

            dbContext.SaveChanges();

            ViewBag.Name = user.FirstName;
            return(View());
        }
コード例 #18
0
 static void Main(string[] args)
 {
     using (var ctx = new EFDbContext())
     {
         Department d = new Department();
         d.Name = "IT";
         ctx.Departments.Add(d);
         Employee e = new Employee();
         e.Name = "CG";
         ctx.Employees.Add(e);
         Ticket t = new Ticket();
         t.ProjectName      = "test";
         t.DateTimeReceived = DateTime.Now;
         t.Description      = "teeeest";
         ctx.Tickets.Add(t);
         ctx.SaveChanges();
     }
     Console.WriteLine("ok");
     Console.ReadLine();
 }
コード例 #19
0
        public IHttpActionResult Reject(int orderId, string reason)
        {
            var orderObj = db.AdoptionOrders.Find(orderId);

            if (orderObj != null)
            {
                if (orderObj.Date > DateTime.Now)
                {
                    orderObj.IsRejected      = true;
                    orderObj.RejectReason    = reason;
                    db.Entry(orderObj).State = EntityState.Modified;
                    db.SaveChanges();
                }
                else
                {
                    return(BadRequest("Срок отклонения истек!"));
                }
            }
            return(NotFound());
        }
コード例 #20
0
ファイル: Amusement.svc.cs プロジェクト: hust-mis/YOY
        public Stream Agree(string VisitorID, string InviterID)
        {
            if (string.IsNullOrEmpty(VisitorID) || string.IsNullOrEmpty(VisitorID))
            {
                return(ResponseHelper.Failure("VisitorID或InviterID信息不完全!"));
            }

            try
            {
                using (var db = new EFDbContext())
                {
                    var groups = db.Groups.Where(t => t.VisitorID == VisitorID);
                    if (groups.Count() == 0)
                    {
                        return(ResponseHelper.Failure("该游客没有邀请记录!"));
                    }
                    if (groups.Where(t => t.InviterID == InviterID).Count() == 0)
                    {
                        return(ResponseHelper.Failure("没有该条邀请记录!"));
                    }
                    if (groups.Where(t => t.InviteeState == 1).Count() > 0)
                    {
                        return(ResponseHelper.Failure("该游客已拥有队伍!"));
                    }

                    var query = db.Groups.Where(t => t.VisitorID == VisitorID && t.InviterID == InviterID).Single();
                    query.InviteeState = 1;
                    db.SaveChanges();
                }

                return(ResponseHelper.Success(null));
            }
            catch (Exception ex)
            {
                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                }
                return(ResponseHelper.Failure(ex.Message));
            }
        }
コード例 #21
0
        /// <summary>
        /// 绑定LocalSense
        /// </summary>
        /// <param name="VisitorID">游客ID</param>
        /// <param name="LocatorID">LocalSense定位设备的ID</param>
        /// <returns>绑定结果</returns>
        public Stream BindingLocators(string VisitorID, string LocatorID)
        {
            if (string.IsNullOrEmpty(VisitorID) || string.IsNullOrEmpty(LocatorID))
            {
                return(ResponseHelper.Failure("游客ID或定位设备ID不能为空"));
            }
            if (EFHelper.GetAll <Visitor>().Where(t => t.VisitorID == VisitorID && t.VisitorState == 1).Count() == 0)
            {
                return(ResponseHelper.Failure("找不到该游客或未激活!"));
            }
            try
            {
                using (var db = new EFDbContext())
                {
                    var locators = db.Locators.Where(t => t.LocatorID == LocatorID);
                    if (locators.Count() == 0)
                    {
                        return(ResponseHelper.Failure("找不到该定位设备!"));
                    }
                    if (locators.Single().LocatorState == 1)
                    {
                        return(ResponseHelper.Failure("该定位设备已进行过绑定!"));
                    }

                    locators.Single().LocatorState = 1;
                    locators.Single().VisitorID    = VisitorID;

                    db.SaveChanges();
                }

                return(ResponseHelper.Success(null));
            }
            catch (Exception ex)
            {
                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                }
                return(ResponseHelper.Failure(ex.Message));
            }
        }
コード例 #22
0
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginViewModel model, string returnUrl)
        {
            string provider       = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (EFDbContext db = new EFDbContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile {
                            UserName = model.UserName
                        });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return(RedirectToLocal(returnUrl));
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            return(View(model));
        }
コード例 #23
0
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider       = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                // 将新用户插入到数据库
                using (EFDbContext db = new EFDbContext())
                {
                    User user = db.Users.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // 检查用户是否已存在
                    if (user == null)
                    {
                        // 将名称插入到配置文件表
                        db.Users.Add(new User {
                            UserName = model.UserName
                        });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return(RedirectToLocal(returnUrl));
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "用户名已存在。请输入其他用户名。");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            return(View(model));
        }
コード例 #24
0
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider       = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                // Добавление нового пользователя в базу данных
                using (EFDbContext db = new EFDbContext())
                {
                    User user = db.Users.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Проверка наличия пользователя в базе данных
                    if (user == null)
                    {
                        // Добавление имени в таблицу профиля
                        db.Users.Add(new User {
                            UserName = model.UserName
                        });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return(RedirectToLocal(returnUrl));
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "Имя пользователя уже существует. Введите другое имя пользователя.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            return(View(model));
        }
コード例 #25
0
 private static void SeedCars(EFDbContext context)
 {
     //  Перевірка чи колекція автомобілів не пуста
     if (!context.Cars.Any())
     {
         //  Додавання у БД колекцію автомобілів
         context.Cars.AddRange(new List <AppCar> {
             new AppCar
             {
                 Mark     = "Mercedes",
                 Model    = "GLA",
                 Age      = 2021,
                 Capacity = 3.1F,
                 Fuel     = "Бензин",
                 Image    = "https://www.mercedes-benz.ua/passengercars/mercedes-benz-cars/" +
                            "models/gla/gla-h247/specifications/alternative-drive/_" +
                            "jcr_content/par/productinfotextimage/media2/slides/videoimageslide/image.MQ6.7.20201208163725.jpeg"
             },
             new AppCar
             {
                 Mark     = "BMW",
                 Model    = "X7",
                 Age      = 2021,
                 Capacity = 3.1F,
                 Fuel     = "Бензин",
                 Image    = "https://www.bmw.ua/content/dam/bmw/common/all-models/x-series/x7/2018/Inspire/bmw-x7-inspire-radiating-presence-01.jpg"
             },
             new AppCar
             {
                 Mark     = "Toyota",
                 Model    = "RAV4",
                 Age      = 2021,
                 Capacity = 3.1F,
                 Fuel     = "Бензин",
                 Image    = "https://www.ixbt.com/img/n1/news/2020/5/1/rav-4-prime-1280x720_large.jpg"
             }
         });
         //  Збереження данних
         context.SaveChanges();
     }
 }
コード例 #26
0
 public static void SaveSysLog(string uId, string clientIP, string summary, string moduleName)
 {
     try
     {
         EFDbContext _context = new EFDbContext();
         SysLog      sysLog   = new SysLog();
         sysLog.Type       = 10;
         sysLog.UId        = uId;
         sysLog.ClientIP   = clientIP;
         sysLog.ServerName = "";
         sysLog.Summary    = summary;
         sysLog.ModuleName = moduleName;
         sysLog.CreateDT   = DateTime.Now;
         _context.SysLog.Add(sysLog);
         _context.SaveChanges();
     }
     catch (Exception ex)
     {
         return;
     }
 }
コード例 #27
0
        public IHttpActionResult SetUser(Guid userId, Guid orgId, string userName)
        {
            var db = new EFDbContext();

            if (!db.AdpotionCandidates.Any(x => x.PortalUserId == userId))
            {
                db.AdpotionCandidates.Add(new AdpotionCandidate
                {
                    PortalUserId = userId,
                    CreatedAt    = DateTime.Now,
                    OrgId        = orgId,
                    UserName     = userName
                });
                db.SaveChanges();
                return(Ok(true));
            }
            else
            {
                return(Ok(true));
            }
        }
コード例 #28
0
        // [TestMethod]
        public void TestInsertLocation()
        {
            var context = new EFDbContext();

            context.Locations.Add(new Location()
            {
                City              = "Breda",
                kidDiscount       = 0.0m,
                Country           = "Netherlands",
                Name              = "Pathe Breda",
                Province          = "Noord Brant",
                Rooms             = 4,
                SeniorDiscount    = 0.0m,
                StudentDiscount   = 0.0m,
                TicketPriceLong   = 0.0m,
                TicketPriceNormal = 0.0m,
            });

            context.SaveChanges();
            //      Assert.IsNotNull(context.Locations.ToList().Find(l => l.Name == "Pathe Breda"));
        }
コード例 #29
0
 public static string StringSymvol(string TypeConstruction = "BB")
 {
     using (EFDbContext context = new EFDbContext())
     {
         if (context.ListUniqueNumber.Any())
         {
             string ListId= context.ListUniqueNumber.Select(a=>a.UniqueNumber).First();
             context.ListUniqueNumber.Remove(context.ListUniqueNumber.First());
             context.SaveChanges();
             return ListId;
         }
     }
     string SymbolString = "";
     int number = Increment();
     for (int s = 8; s > number.ToString().Length; s--)
     {
         SymbolString = "0" + SymbolString;
     }
     var ValueString = TypeConstruction + SymbolString + number;
     return ValueString;
 }
コード例 #30
0
        //  [TestMethod]
        public void TestInsertFilm()
        {
            var context = new EFDbContext();

            context.Films.Add(new Film()
            {
                Name         = "50 shades of Maikel",
                Language     = "NL",
                LanguageSubs = "",
                Age          = 18,
                FilmType     = 1,
                Description  = "Niet een familiefilm",
                Image        = null,
                Length       = 90,
                Is3D         = false,
                Location     = context.Locations.ToList()[0],
            });

            context.SaveChanges();
            //       Assert.AreEqual(0, context.Films.Count());
        }
コード例 #31
0
 public static void SaveAliSMSErrorLog(string errorMsg, string mobile, string templateCode)
 {
     try
     {
         EFDbContext _context = new EFDbContext();
         SysLog      sysLog   = new SysLog();
         sysLog.Type       = 10;
         sysLog.UId        = "AliDaYu";
         sysLog.ClientIP   = "";
         sysLog.ServerName = "";
         sysLog.Summary    = "错误:" + errorMsg + " 模板编号:" + templateCode;
         sysLog.ModuleName = "阿里大鱼短信发送失败,手机号码为:" + mobile;
         sysLog.CreateDT   = DateTime.Now;
         _context.SysLog.Add(sysLog);
         _context.SaveChanges();
     }
     catch (Exception ex)
     {
         return;
     }
 }
コード例 #32
0
        public ActionResult Create(Packs packs)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Packss.Add(packs);
                    db.SaveChanges();
                    repository.SavePacks(packs);

                    return(RedirectToAction("Index"));
                }
            }
            catch (RetryLimitExceededException /* dex */)
            {
                ModelState.AddModelError("", "Nie udało się zapisać");
            }
            Populate(packs.WarehousesID);
            Populate1(packs.personID);
            return(View(packs));
        }
コード例 #33
0
ファイル: AccountController.cs プロジェクト: solomon00/judge
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginViewModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (EFDbContext db = new EFDbContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
コード例 #34
0
        // Begin of core PUT/POST execution method, values can be edited, or request can be aborted
        async Task handler_StoreFileRequestStartedAsync(object sender, Eventing.Args.StoreFileRequestEventArgs e)
        {
            string ExtFile = "";
            int FolderId = 0;
            if (TempData["FolderId"] != null)
            {
                FolderId = Convert.ToInt32(TempData["FolderId"]);
                TempData["FolderId"] = FolderId;
            }

            if (e.Param.FileStatusItem.StorageInfo.FilePath != 
                Server.MapPath("~/Files/ServiceGallery/" + FolderId + "/") + e.Param.FileStatusItem.FileName)
            {
                ExtFile = "ErrorPath";
            }
            // GetFileExtension Ext = new GetFileExtension();
            var extt = Path.GetExtension(e.Param.FileStatusItem.FileName);
            if (extt != ".jpg" && extt != ".png" && extt != ".jpeg" && extt != ".gif")
            {
                ExtFile = "ErrorExt";
            }

            if (ExtFile != "" && ExtFile == "ErrorPath")
            {
                e.Param.FileStatusItem.ErrorMessage = "مسیر فایل اشتباه است .";
                e.Param.FileStatusItem.Success = false;
            }
            if (ExtFile != "" && ExtFile == "ErrorExt")
            {
                e.Param.FileStatusItem.ErrorMessage = "نوع فایل معتبر نیست .";
                e.Param.FileStatusItem.Success = false;

            }
            if (ExtFile == "")
            {
                EFDbContext EFDbContext = new EFDbContext();
                string Filen = e.Param.FileStatusItem.FileName;

                int find = Filen.LastIndexOf(".");
                // var ext = Filen.Substring(find, Filen.Length - find);
                var MainName = Filen.Substring(0, find);
                MainName = ChangeUnKnownCharacters(MainName);
                e.Param.FileStatusItem.FileName = DateTime.Now.Ticks + MainName + extt;
                e.Param.FileStatusItem.UpdateStatus(true);

                ServiceTabFile Item = new ServiceTabFile();
                Item.File = e.Param.FileStatusItem.FileName;
                Item.ServiceTabId = FolderId;
                EFDbContext.ServiceTabFiles.Add(Item);
                EFDbContext.SaveChanges();

            }
            e.Context.PipelineControl.Message.MessageText += string.Format(_logpattern, "log-post", "StoreFileRequestStartedAsync", DateTime.Now.ToLongTimeString());
        }