Ejemplo n.º 1
0
        private void btnRemoveStudentIDDocuments_Click(object sender, EventArgs e)
        {
            DialogResult Rtn = MessageBox.Show("Are You Sure You Wish To Remove This File?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (Rtn == DialogResult.Yes)
            {
                Data.Models.File FileToRemove = (Data.Models.File)fileStudentIDDocumentBindingSource.Current;

                using (var Dbconnection = new MCDEntities())
                {
                    //Data.Models.File x = (from a in Dbconnection.Files
                    //                      where a.)
                    List <StudentIDDocument> x = (from a in Dbconnection.StudentIDDocuments
                                                  where a.FileID == FileToRemove.FileID
                                                  select a).ToList <StudentIDDocument>();
                    foreach (StudentIDDocument doc in x)
                    {
                        Dbconnection.Entry(doc).State = EntityState.Deleted;
                    }

                    Dbconnection.SaveChanges();
                };
                this.refreshStudentIDDocumnets();
            }
        }
Ejemplo n.º 2
0
        private void btnStudentPictureAdd_Click(object sender, EventArgs e)
        {
            StudentPictureToUploaded = FileHandeling.UploadFile(UseMultipleFileSelect: false, AutomaicallyAddFileToDatabase: false, ImagesOnly: true);

            if (StudentPictureToUploaded.Count > 0)
            {
                if (CurrentStudentID != 0)
                {
                    using (var Dbconnection = new MCDEntities())
                    {
                        Data.Models.File f = StudentPictureToUploaded.FirstOrDefault <Data.Models.File>();
                        Dbconnection.Files.Add(f);
                        Dbconnection.SaveChanges();

                        //Dbconnection.Files.Attach(f);
                        Dbconnection.StudentPhotos.Add(new StudentPhoto()
                        {
                            FileID         = f.FileID,
                            StudentID      = CurrentStudentID,
                            DateUpdated    = DateTime.Now,
                            StudentPhotoID = 0
                        });
                        Dbconnection.SaveChanges();
                    };
                }
            }

            ShowStudentPicture();
            switchStudentPictureButtons();
        }
Ejemplo n.º 3
0
        public async Task <ActionResult> Register(RegisterViewModel model, HttpPostedFileBase upload)
        {
            if (this.ModelState.IsValid)
            {
                var user = new User
                {
                    UserName  = model.Email,
                    Email     = model.Email,
                    FirstName = model.FirstName,
                    LastName  = model.LastName
                };

                if (upload != null && upload.ContentLength > 0)
                {
                    var avatar = new Data.Models.File
                    {
                        FileName    = Path.GetFileName(upload.FileName),
                        FileType    = FileType.Avatar,
                        ContentType = upload.ContentType,
                        CreatedOn   = DateTime.Now
                    };

                    using (var reader = new BinaryReader(upload.InputStream))
                    {
                        avatar.Content = reader.ReadBytes(upload.ContentLength);
                    }

                    user.Files.Add(avatar);
                }

                var result = await this.UserManager.CreateAsync(user, model.Password);

                if (user.Email == "*****@*****.**")
                {
                    result = await this.UserManager.AddToRoleAsync(user.Id, "Admin");
                }
                else
                {
                    result = await this.UserManager.AddToRoleAsync(user.Id, "User");
                }

                if (result.Succeeded)
                {
                    await this.SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
                    return(this.RedirectToAction("Index", "Home"));
                }

                this.AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(this.View(model));
        }
Ejemplo n.º 4
0
        public static Boolean RemoveFile(Data.Models.File FileToRemove)
        {
            Boolean Rtn = false;

            List <Data.Models.File> x = new List <Data.Models.File>();

            x.Add(FileToRemove);
            Rtn = RemoveFile(x);
            return(Rtn);
        }
Ejemplo n.º 5
0
        public async Task <ActionResult <Patch> > PutFile([FromRoute] int id, [FromBody] File file)
        {
            Data.Models.File fileToUpdate = await context.Files.SingleAsync(x => x.Id == id);

            fileToUpdate.Removed = file.Removed;
            await context.SaveChangesAsync();

            cache.Remove(Constants.PatchCacheKey);

            return(Ok());
        }
        public async Task <ActionResult> Register(RegisterViewModel model, HttpPostedFileBase upload)
        {
            if (this.ModelState.IsValid)
            {
                var user = new User
                {
                    UserName  = model.Email,
                    Email     = model.Email,
                    FirstName = model.FirstName,
                    LastName  = model.LastName
                };

                if (upload != null && upload.ContentLength > 0)
                {
                    var avatar = new Data.Models.File
                    {
                        FileName    = Path.GetFileName(upload.FileName),
                        FileType    = FileType.Avatar,
                        ContentType = upload.ContentType,
                        CreatedOn   = DateTime.Now
                    };

                    using (var reader = new BinaryReader(upload.InputStream))
                    {
                        avatar.Content = reader.ReadBytes(upload.ContentLength);
                    }

                    user.Files.Add(avatar);
                }

                var result = await this.UserManager.CreateAsync(user, model.Password);

                if (user.Email == "*****@*****.**")
                {
                    result = await this.UserManager.AddToRoleAsync(user.Id, "Admin");
                }
                else
                {
                    result = await this.UserManager.AddToRoleAsync(user.Id, "User");
                }

                if (result.Succeeded)
                {
                    await this.SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    return(this.RedirectToAction("Index", "Home"));
                }

                this.AddErrors(result);
            }

            return(this.View(model));
        }
        public override void GetAttachment()
        {
            if (checkTempFolderExists())
            {
                Data.Models.File CurrentFile = Common.FileHandeling.FileHandeling.GetFile(this.FileID);

                this.AttachmentFileName      = CurrentFile.FileName;
                this.AttachmentFileExtension = CurrentFile.FileExtension;


                System.IO.File.WriteAllBytes(AttachemntPath + "\\" + this.FileID.ToString() + "_" + this.AttachmentFullFileName, CurrentFile.FileImage);
            }
        }
Ejemplo n.º 8
0
        public static Boolean RemoveFile(int FileID)
        {
            Boolean Rtn = false;

            using (var Dbconnection = new MCDEntities())
            {
                Data.Models.File f = (from a in Dbconnection.Files
                                      where a.FileID == FileID
                                      select a).FirstOrDefault <Data.Models.File>();
                Dbconnection.Files.Remove(f);
                Dbconnection.SaveChanges();
                Rtn = true;
            };
            return(Rtn);
        }
Ejemplo n.º 9
0
        private void btnRemoveAttachment_Click(object sender, EventArgs e)
        {
            DialogResult res = MessageBox.Show("Are You Sure?", "Attchment Removal", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);

            if (res == DialogResult.Yes)
            {
                Data.Models.File FileToRemove = (Data.Models.File)filesBindingSource.Current;

                using (var Dbconnection = new MCDEntities())
                {
                    Dbconnection.MessageTemplates.Attach(CurrentMessageTemplate);
                    Dbconnection.Files.Attach(FileToRemove);
                    CurrentMessageTemplate.Files.Remove(FileToRemove);
                    Dbconnection.Files.Remove(FileToRemove);
                };
                this.refreshMessage();
            }
        }
Ejemplo n.º 10
0
        public async Task <ActionResult <Patch> > PostFile([FromRoute] int id, IFormCollection collection)
        {
            IFormFile file      = collection.Files[0];
            string    comment   = collection["Comment"].ToString();
            string    appUserId = collection["AppUserId"].ToString();

            _ = int.TryParse(collection["NufUserId"].ToString(), out int nufUserId);
            string extension = collection["Extension"].ToString();

            if (file.Length > MaxLength)
            {
                return(BadRequest("file size too big"));
            }

            CloudBlockBlob blob = await SaveFileToBlob(file, "mp3s", id);

            var newFile = new Data.Models.File
            {
                Name        = blob.Name,
                Comment     = comment,
                DateCreated = DateTime.UtcNow,
                AppUserId   = appUserId,
                NufUserId   = nufUserId,
                IsBlob      = true,
                Extension   = extension,
                Size        = (int)blob.Properties.Length,
                PatchFiles  = new List <Data.Models.PatchFile>()
            };
            var newPatchFile = new Data.Models.PatchFile {
                PatchId = id
            };

            newFile.PatchFiles.Add(newPatchFile);

            context.Files.Add(newFile);
            await context.SaveChangesAsync();

            cache.Remove(Constants.PatchCacheKey);

            var returnFile = mapper.Map <File>(newFile);

            return(CreatedAtAction("PostFile", returnFile));
        }
Ejemplo n.º 11
0
        private void dgvEnrollmentFiles_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            switch (e.ColumnIndex)
            {
            case 0:
                folderBrowserDialogToDownloadFile.ShowDialog();
                if (System.IO.Directory.Exists(folderBrowserDialogToDownloadFile.SelectedPath))
                {
                    EnrollmentFiles  EF = (EnrollmentFiles)enrollmentFilesBindingSource.Current;
                    Data.Models.File f  = Common.FileHandeling.FileHandeling.GetFile(EF.FileID);
                    MemoryStream     ms = new MemoryStream(f.FileImage);
                    //write to file
                    FileStream file = new FileStream(folderBrowserDialogToDownloadFile.SelectedPath + "\\" + f.FileName + "." + f.FileExtension, FileMode.Create, FileAccess.Write);

                    ms.WriteTo(file);
                    file.Close();
                    ms.Close();
                }
                break;
            }
        }
Ejemplo n.º 12
0
        private void dgvStudentIDDocuments_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            switch (e.ColumnIndex)
            {
            case 0:


                var FileObj        = fileStudentIDDocumentBindingSource.Current;
                Data.Models.File x = new Data.Models.File();
                //loop through the properties of the object you want to covert:
                foreach (PropertyInfo pi in FileObj.GetType().GetProperties())
                {
                    try
                    {
                        //get the value of property and try
                        //to assign it to the property of T type object:
                        x.GetType().GetProperty(pi.Name).SetValue(x, pi.GetValue(FileObj, null), null);
                    }
                    catch { }
                }

                folderBrowserDialogForDownloading.ShowDialog();

                if (folderBrowserDialogForDownloading.SelectedPath.Length > 0)
                {
                    try
                    {
                        Data.Models.File CurrentFile = FileHandeling.GetFile(x.FileID);
                        string           path        = folderBrowserDialogForDownloading.SelectedPath + "\\" + x.FileName;
                        System.IO.File.WriteAllBytes(path, CurrentFile.FileImage);
                        MessageBox.Show(x.FileName + ", Successfully Saved to: " + path, "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                break;
            }
        }
Ejemplo n.º 13
0
        private void btnStudentPictureUpdate_Click(object sender, EventArgs e)
        {
            List <Data.Models.File> FileToUpdate = FileHandeling.UploadFile(UseMultipleFileSelect: false, AutomaicallyAddFileToDatabase: false, ImagesOnly: true);


            Data.Models.File f = StudentPictureToUploaded.FirstOrDefault <Data.Models.File>();
            if (CurrentStudentID != 0)
            {
                using (var Dbconnection = new MCDEntities())
                {
                    Dbconnection.Files.Attach(f);
                    Dbconnection.Entry(f).State = EntityState.Modified;
                    f.FileImage = FileToUpdate.First <Data.Models.File>().FileImage;
                    Dbconnection.SaveChanges();
                };
            }
            else
            {
                f.FileImage = FileToUpdate.First <Data.Models.File>().FileImage;
            }
            ShowStudentPicture();
        }
Ejemplo n.º 14
0
        private static User GetFileUser(Data.Models.File src)
        {
            var user = new User();

            if (src.AppUser != null)
            {
                user.Id        = src.AppUser.Id;
                user.NufUserId = src.AppUser.NufUserId.ToString();
                user.Username  = src.AppUser.UserName;
            }
            else if (src.NufUser != null)
            {
                user.NufUserId = src.NufUser.Id.ToString();
                user.Username  = src.NufUser.Username;
            }
            else
            {
                user = null;
            }

            return(user);
        }
Ejemplo n.º 15
0
        public NotificationViewModel UploadFiles(List <IFormFile> files, Guid referId, string tableName)
        {
            if (files != null)
            {
                foreach (var file in files)
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        file.CopyTo(memoryStream);
                        var byteArray = memoryStream.ToArray();
                        var newFile   = new Data.Models.File()
                        {
                            Id        = Guid.NewGuid(),
                            ReferId   = referId,
                            TableName = tableName,
                            Type      = "Arquivo",
                            FileName  = file.FileName,
                            MIME      = file.ContentType,
                            Priority  = 0,
                            FileBytes = byteArray
                        };
                        _unitOfWork.File.Add(newFile);
                    }
                }

                _unitOfWork.Commit();

                return(new NotificationViewModel()
                {
                    Message = "Arquivo incluso com sucesso.",
                    Title = "Sucesso!",
                    Status = true
                });
            }
            return(null);
        }
Ejemplo n.º 16
0
        public void sendMessage()
        {
            MailMessage mail = new MailMessage();

            client = new SmtpClient(this.Host, this.PortNumber);
            client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);

            if (this.DisplayName.Length > 0)
            {
                mail.From = new MailAddress(this.FromAddress, this.DisplayName);
            }
            else
            {
                mail.From = new MailAddress(this.FromAddress);
            }


            string[] items = this.ToAddress.Split(';');
            if (items.Length > 0)
            {
                foreach (string EAddress in items)
                {
                    if (EAddress.Length > 0)
                    {
                        mail.To.Add(EAddress.Trim());
                    }
                }
            }
            else
            {
                mail.To.Add(this.ToAddress.Trim());
            }



            mail.Subject = this.Subject;
            mail.Body    = this.Body;

            ////Depreciated will be remove soon - 10 April 2017
            //if (_Attachments != null)
            //{
            //    foreach (Attachment myAttachment in _Attachments)
            //    { mail.Attachments.Add(myAttachment); }
            //}

            if (EmailAttachments != null)
            {
                List <int> AddFileID = new List <int>();
                foreach (EmailAttachmentMetaData myAttachment in EmailAttachments)
                {
                    if (myAttachment.CurrentAttachmentType == AttachmentType.PathBasedAttachment)
                    {
                        mail.Attachments.Add(new Attachment(myAttachment.AttachmentPath));
                    }
                    if (myAttachment.CurrentAttachmentType == AttachmentType.DatabaseImageAttachment)
                    {
                        try
                        {
                            using (var Dbconnection = new MCDEntities())
                            {
                                Data.Models.File FileImage = (from a in Dbconnection.Files
                                                              where a.FileID == myAttachment.DatabaseFileID
                                                              select a).FirstOrDefault();

                                MemoryStream ms        = new MemoryStream(FileImage.FileImage);
                                string       sFileName = FileImage.FileName + "." + FileImage.FileExtension;
                                mail.Attachments.Add(new Attachment(ms, sFileName));
                            };
                        }
                        catch (Exception ex)
                        {
                            System.Windows.Forms.MessageBox.Show("Error getting attachment from database : " + ex.Message);
                        }
                    }
                }
            }


            if (RequireAuthentication)
            {
                client.Credentials = new System.Net.NetworkCredential(UserName, Password);
            }
            if (this.RequireSSL)
            {
                client.EnableSsl = true;
            }

            int retryCount = 0;;

            try
            {
                // string userState = "test message1";

                client.SendAsync(mail, "Start");
            }
            catch (SmtpFailedRecipientsException ex)
            {
                for (int i = 0; i < ex.InnerExceptions.Length; i++)
                {
                    SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
                    if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable)
                    {
                        System.Windows.Forms.MessageBox.Show("Delivery failed - retrying in 5 seconds. Retry Attempt " + retryCount + 1 + "of 3.", "Connection Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, System.Windows.Forms.MessageBoxDefaultButton.Button1);
                        //System.Threading.Thread.Sleep(1);
                        if (retryCount < 2)
                        {
                            string userState = "test message1";
                            client.SendAsync(mail, userState);
                        }
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("Failed to deliver message to {0}",
                                                             ex.InnerExceptions[i].FailedRecipient, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Exception caught in RetryIfBusy(): {0}",
                                                     ex.ToString(), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 17
0
        // full: delete diff post for api remote
        public async Task Push(string name = "", bool full = false)
        {
            if (string.IsNullOrEmpty(name))
            {
                name = Option.CurrentRemote;
            }

            Logger.LogInformation($"Push to remote {name}.");

            if (Option.Remotes.TryGetValue(name, out var remote))
            {
                Logger.LogInformation($"Detect remote {remote.Name} ({Enum.GetName(typeof(RemoteType), remote.Type)}).");
                switch (remote.Type)
                {
                case RemoteType.LocalFS:
                {
                    await toLocalFS(remote);
                }
                break;

                case RemoteType.RemoteFS:
                {
                    throw new NotSupportedException("Not support pushing to remote file system, please push to local file system and sync to remote.");
                }

                case RemoteType.Api:
                {
                    await Connect(name);

                    Logger.LogInformation($"Fetch remote posts.");

                    await Remote.SetOptions(await Local.GetOptions());

                    await SyncRecordRepository(Local.PostService, Remote.PostService, full);

                    await SyncRecordRepository(Local.PageService, Remote.PageService, full);

                    await SyncRecordRepository(Local.LayoutService, Remote.LayoutService, full);
                }
                break;

                case RemoteType.Git:
                {
                    await Connect(name);

                    string tempDist = Path.Join(Environment.CurrentDirectory, "temp/dist");

                    Logger.LogInformation("Generate data.");

                    await toLocalFS(new RemoteOption
                        {
                            Uri  = tempDist,
                            Type = RemoteType.LocalFS,
                            Name = remote.Name
                        });

                    FSExtensions.CopyDirectory(tempDist, GitTempFolder);

                    Logger.LogInformation("Load git config.");

                    string userName = Option.Properties[$"remote.{remote.Name}.git.username"],
                           password = Option.Properties[$"remote.{remote.Name}.git.password"];

                    {
                        if (string.IsNullOrEmpty(userName))
                        {
                            userName = ConsoleExtensions.Input("Input username: "******"Input password: "******"Commit to git.");

                        LibGit2Sharp.Commands.Stage(repo, "*");

                        var signature = new LibGit2Sharp.Signature(
                            new Identity("AcBlog.Tools.Sdk", "tools.sdk@acblog"), DateTimeOffset.Now);
                        repo.Commit(DateTimeOffset.Now.ToString(), signature, signature, new CommitOptions
                            {
                                AllowEmptyCommit = true
                            });

                        Logger.LogInformation($"Push to {repo.Head.RemoteName}.");

                        PushOptions options = new PushOptions
                        {
                            CredentialsProvider = new CredentialsHandler(
                                (url, usernameFromUrl, types) =>
                                new UsernamePasswordCredentials()
                                {
                                    Username = string.IsNullOrEmpty(userName) ? usernameFromUrl : userName,
                                    Password = password
                                })
                        };
                        repo.Network.Push(repo.Head, options);
                    }
                }
                break;
                }
            }
            else
            {
                throw new Exception("No remote");
            }

            async Task toLocalFS(RemoteOption remote)
            {
                FSBuilder fsBuilder = new FSBuilder(remote.Uri);

                fsBuilder.EnsureDirectoryEmpty();

                List <Post> posts = new List <Post>();

                await foreach (var item in Local.PostService.GetAllItems().IgnoreNull())
                {
                    Logger.LogInformation($"Loaded Post {item.Id}: {item.Title}");
                    posts.Add(item);
                }

                List <Layout> layouts = new List <Layout>();

                await foreach (var item in Local.LayoutService.GetAllItems().IgnoreNull())
                {
                    Logger.LogInformation($"Loaded Layout {item.Id}");
                    layouts.Add(item);
                }

                List <Page> pages = new List <Page>();

                await foreach (var item in Local.PageService.GetAllItems().IgnoreNull())
                {
                    Logger.LogInformation($"Loaded Page {item.Id}: {item.Title}");
                    pages.Add(item);
                }

                var baseAddress = Option.Properties[$"remote.{remote.Name}.generator.baseAddress"];

                List <Data.Models.File> files = new List <Data.Models.File>();

                {
                    string path = Path.Join(Environment.CurrentDirectory, AssetsPath);
                    if (Directory.Exists(path))
                    {
                        foreach (var file in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories))
                        {
                            var id             = Path.GetRelativePath(Environment.CurrentDirectory, file).Replace('\\', '/');
                            Data.Models.File f = new Data.Models.File
                            {
                                Id  = id,
                                Uri = string.IsNullOrWhiteSpace(baseAddress) ? $"/{id}" : $"{baseAddress.TrimEnd('/')}/{id}"
                            };
                            files.Add(f);
                        }
                    }
                }

                Logger.LogInformation("Build data.");
                {
                    BlogOptions options = await Local.GetOptions();

                    BlogBuilder builder = new BlogBuilder(options, Path.Join(remote.Uri));
                    await builder.Build();

                    await builder.BuildPosts(posts);

                    await builder.BuildLayouts(layouts);

                    await builder.BuildPages(pages);

                    await builder.BuildFiles(files);
                }

                {
                    if (!string.IsNullOrEmpty(baseAddress))
                    {
                        Logger.LogInformation("Build sitemap.");
                        var sub = fsBuilder.CreateSubDirectoryBuilder("Site");
                        {
                            var siteMapBuilder = await Local.BuildSitemap(baseAddress);

                            await using var st     = sub.GetFileRewriteStream("sitemap.xml");
                            await using var writer = XmlWriter.Create(st, new XmlWriterSettings { Async = true });
                            siteMapBuilder.Build().WriteTo(writer);
                        }
                        Logger.LogInformation("Build feed.");
                        {
                            var feed = await Local.BuildSyndication(baseAddress);

                            await using (var st = sub.GetFileRewriteStream("atom.xml"))
                            {
                                await using var writer = XmlWriter.Create(st, new XmlWriterSettings { Async = true });
                                feed.GetAtom10Formatter().WriteTo(writer);
                            }
                            await using (var st = sub.GetFileRewriteStream("rss.xml"))
                            {
                                await using var writer = XmlWriter.Create(st, new XmlWriterSettings { Async = true });
                                feed.GetRss20Formatter().WriteTo(writer);
                            }
                        }
                    }
                }
                {
                    string assetsPath = Path.Join(Environment.CurrentDirectory, AssetsPath);
                    if (Directory.Exists(assetsPath))
                    {
                        Logger.LogInformation("Copy assets.");
                        FSExtensions.CopyDirectory(assetsPath, Path.Join(remote.Uri, AssetsPath));
                    }
                }
            }
        }
Ejemplo n.º 18
0
        public async Task<ActionResult> Register(RegisterViewModel model, HttpPostedFileBase upload)
        {
            if (this.ModelState.IsValid)
            {
                var user = new User
                {
                    UserName = model.Email,
                    Email = model.Email,
                    FirstName = model.FirstName,
                    LastName = model.LastName
                };

                if (upload != null && upload.ContentLength > 0)
                {
                    var avatar = new Data.Models.File
                    {
                        FileName = Path.GetFileName(upload.FileName),
                        FileType = FileType.Avatar,
                        ContentType = upload.ContentType,
                        CreatedOn = DateTime.Now
                    };

                    using (var reader = new BinaryReader(upload.InputStream))
                    {
                        avatar.Content = reader.ReadBytes(upload.ContentLength);
                    }

                    user.Files.Add(avatar);
                }

                var result = await this.UserManager.CreateAsync(user, model.Password);

                if (user.Email == "*****@*****.**")
                {
                    result = await this.UserManager.AddToRoleAsync(user.Id, "Admin");
                }
                else
                {
                    result = await this.UserManager.AddToRoleAsync(user.Id, "User");
                }

                if (result.Succeeded)
                {
                    await this.SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                    return this.RedirectToAction("Index", "Home");
                }

                this.AddErrors(result);
            }

            return this.View(model);
        }
Ejemplo n.º 19
0
        private Boolean ValidateStep()
        {
            Boolean bRtn = true;

            switch (CurrentPosition)
            {
            case 0:



                try
                {
                    //ToDo - Catch All Verification and validation on fields before saving.
                    //check and adds the new student to the database or updates the exsiting one.


                    Student StudentObj = (Student)studentBindingSource.Current;
                    using (var Dbconnection = new MCDEntities())
                    {
                        if (StudentObj.ObjectState == EntityObjectState.Added)
                        {
                            Student StudentFound;


                            using (var DbconnectionInner = new MCDEntities())
                            {
                                StudentFound = (from a in Dbconnection.Students
                                                where a.StudentIDNumber.Contains(txtStudentIDNumber.Text)
                                                select a).FirstOrDefault <Student>();
                            };

                            if (txtStudentIDNumber.Text.Length != 0 && StudentFound != null)
                            {
                                //throw new DbEntityValidationException("(ID Number Invalid) - ID Number Already Exists in the System Please Re-Enter ID Number Or Search Again!");
                                //MetroMessageBox.Show(this, "(ID Number Invalid) - ID Number Already Exists in the System Please Re-Enter ID Number Or Search Again!", "Error Message", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
                                MessageBox.Show("(ID Number Invalid) - ID Number Already Exists in the System Please Re-Enter ID Number Or Search Again!", "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                bRtn = false;
                                break;
                            }
                            else
                            {
                                Student NewStudent = new Student()
                                {
                                    StudentID              = 0,
                                    StudentIDNumber        = txtStudentIDNumber.Text.ToString(),
                                    EthnicityID            = Convert.ToInt32(cboStudentEthnicity.SelectedValue),
                                    GenderID               = Convert.ToInt32(cboStudentGender.SelectedValue),
                                    MartialStatusID        = Convert.ToInt32(cboStudentMartialStatus.SelectedValue),
                                    QualificationLevelID   = Convert.ToInt32(cboStudentHighestQualificationLevel.SelectedValue),
                                    StudentCurrentPosition = "",
                                    StudentlInitialDate    = DateTime.Now,
                                    Individual             = new Individual()
                                    {
                                        IndividualID         = 0,
                                        IndividualFirstName  = txtStudentFirstName.Text,
                                        IndividualSecondName = txtStudentSecondName.Text,
                                        IndividualLastname   = txtStudentLastname.Text,
                                        TitleID = Convert.ToInt32(cboStudentTitle.SelectedValue),
                                    }
                                };

                                Dbconnection.Students.Add(NewStudent);
                                Dbconnection.SaveChanges();
                                CurrentStudentID = NewStudent.StudentID;
                                //CurrentSelectedStudent = NewStudent;

                                if (StudentPictureToUploaded.Count > 0)
                                {
                                    Data.Models.File f = StudentPictureToUploaded.FirstOrDefault <Data.Models.File>();
                                    Dbconnection.Files.Add(f);
                                    Dbconnection.SaveChanges();

                                    Dbconnection.StudentPhotos.Add(new StudentPhoto()
                                    {
                                        FileID         = f.FileID,
                                        StudentID      = CurrentStudentID,
                                        DateUpdated    = DateTime.Now,
                                        StudentPhotoID = 0
                                    });
                                    Dbconnection.SaveChanges();
                                }


                                StudentObj             = NewStudent;
                                StudentObj.ObjectState = EntityObjectState.Modified;
                                IsClosingPrematurly    = false;
                            }
                        }

                        if (StudentObj.ObjectState == EntityObjectState.Modified)
                        {
                            Dbconnection.Students.Attach(StudentObj);
                            StudentObj.Individual.IndividualFirstName  = txtStudentFirstName.Text;
                            StudentObj.Individual.IndividualSecondName = txtStudentSecondName.Text;
                            StudentObj.Individual.IndividualLastname   = txtStudentLastname.Text;
                            StudentObj.Individual.TitleID   = Convert.ToInt32(cboStudentTitle.SelectedValue);
                            StudentObj.StudentIDNumber      = txtStudentIDNumber.Text.ToString();
                            StudentObj.EthnicityID          = Convert.ToInt32(cboStudentEthnicity.SelectedValue);
                            StudentObj.GenderID             = Convert.ToInt32(cboStudentGender.SelectedValue);
                            StudentObj.MartialStatusID      = Convert.ToInt32(cboStudentMartialStatus.SelectedValue);
                            StudentObj.QualificationLevelID = Convert.ToInt32(cboStudentHighestQualificationLevel.SelectedValue);

                            Dbconnection.Entry(StudentObj).State = System.Data.Entity.EntityState.Modified;
                            Dbconnection.SaveChanges();
                        }

                        StudentObj.ObjectState = EntityObjectState.Modified;
                    };
                    CurrentSelectedStudent          = StudentObj;
                    studentBindingSource.DataSource = StudentObj;
                }
                catch (DbEntityValidationException dbEx)
                {
                    foreach (DbEntityValidationResult entityErr in dbEx.EntityValidationErrors)
                    {
                        foreach (DbValidationError error in entityErr.ValidationErrors)
                        {
                            MessageBox.Show(error.ErrorMessage, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    bRtn = false;
                }
                //studentBindingSource.ResetCurrentItem();
                break;

            case 1:
                break;

            case 2:
                break;

            case 3:
                break;

            case 4:
                break;

            case 5:
                break;

            case 6:
                break;

            case 7:
                break;

            default:
                bRtn = false;
                break;
            }

            return(bRtn);
        }
Ejemplo n.º 20
0
        public async Task <IActionResult> UploadProductImage(string data = null)
        {
            ProductFile prodFile = null;

            Data.Models.File file     = null;
            IFormFile        formFile = null;

            string fileName = null, fileFormat = null;

            try
            {
                if (Request != null &&
                    Request.Form != null &&
                    Request.Form.Keys != null &&
                    Request.Form.Keys.Count > 0 &&
                    Request.Form != null &&
                    Request.Form.Files != null)
                {
                    string key = Request.Form.Keys.FirstOrDefault(l => l.StartsWith("ProdFileID"));

                    if (!string.IsNullOrEmpty(key))
                    {
                        prodFile = Helper.JSonCamelDeserializeObject <ProductFile>(Request.Form[key]);

                        if (prodFile != null && prodFile.Product_Id > 0)
                        {
                            formFile = Request.Form.Files.FirstOrDefault(f => f.Name == key);

                            if (formFile != null && !string.IsNullOrEmpty(formFile.FileName))
                            {
                                int offset = 0;

                                if (Request.Form.Keys.Any(k => k == "offset"))
                                {
                                    if (!int.TryParse(Request.Form["offset"].ToString(), out offset))
                                    {
                                        offset = 0;
                                    }
                                }

                                fileName   = _dbi.GetProductFileName(prodFile.Product_Id, offset: offset);
                                fileFormat = Path.GetExtension(formFile.FileName);
                                fileFormat = fileFormat.StartsWith(".") ? fileFormat : $".{fileFormat}";

                                file = new Data.Models.File()
                                {
                                    RecordState = RecordState.Added,
                                    UID         = fileName.ToSlug(),
                                    Name        = fileName,
                                    Format      = fileFormat,
                                    IsImage     = true,
                                    IsUploaded  = false
                                };

                                file = _dbi.ManageModel(file);

                                prodFile.File_Id     = file.ID;
                                prodFile.RecordState = RecordState.Added;
                                prodFile             = _dbi.ManageModel(prodFile);

                                prodFile.File = file;



                                string ftpHost     = _config["Ftp:assets:host"];
                                string ftpUserName = _config["Ftp:assets:user"];
                                string ftppassword = _config["Ftp:assets:password"];
                                bool   ftpIgnoreCertificateErrors = true;


                                using (var ftpClient = new FtpClient(
                                           new FtpClientConfiguration()
                                {
                                    Host = ftpHost,
                                    Username = ftpUserName,
                                    Password = ftppassword,
                                    EncryptionType = FtpEncryption.Implicit,
                                    IgnoreCertificateErrors = ftpIgnoreCertificateErrors
                                }))
                                {
                                    await ftpClient.LoginAsync();

                                    using (var fileStream = formFile.OpenReadStream())
                                    {
                                        string ftpFilePath = $"/wwwroot/images/{file.UID}/optz/{fileName}{fileFormat}";

                                        using (var writeStream = await ftpClient.OpenFileWriteStreamAsync(ftpFilePath))
                                        {
                                            await fileStream.CopyToAsync(writeStream);
                                        }
                                    }
                                }

                                file.IsUploaded = true;
                                file            = _dbi.ManageModel(file);
                            }
                        }
                    }
                }

                return(Json(prodFile.Simplify(true)));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
            finally
            {
                prodFile = null;
                formFile = null;
            }
        }