public ActionResult Retroceso(int min, int max) { IRepository repository = new Model.Repository(); var cuestionario = repository.FindEntitySet <Cuestionario>(c => c.Id >= min && c.Id < max + 1).OrderBy(c => c.Id); return(Json(cuestionario.ToList())); }
public ActionResult Index() { IRepository repository = new Model.Repository(); var cuestionario = repository.FindEntitySet <Cuestionario>(c => c.Id > 0 && c.Id < 6).OrderBy(c => c.Id); return(View(cuestionario)); }
public ActionResult Add(Paciente paciente, Usuario usuario) { IRepository repository = new Model.Repository(); int id = 0; string strMensaje = "No se pudo actualizar la información, intentelo más tarde"; bool okResult = false; if (paciente.IdPaciente > 0) { id = paciente.IdPaciente; Pacientes UpdatePaciente = repository.FindEntity <Pacientes>(c => c.IdPaciente == paciente.IdPaciente); if (UpdatePaciente != null) { Paciente actualizar = new Paciente(); strMensaje = actualizar.actualizar(usuario, paciente); okResult = true; } } else { id = paciente.IdPaciente; Paciente actualizar = new Paciente(); okResult = true; strMensaje = actualizar.crear(usuario, paciente); } return(Json(new Response { IsSuccess = okResult, Message = strMensaje, Id = id }, JsonRequestBehavior.AllowGet)); }
// GET: Home public ActionResult Index() { IRepository repository = new Model.Repository(); var objResult = repository.FindEntity <Usuarios>(c => true); return(View(objResult)); }
public ActionResult Index(string email, string password, bool?recordar) { IRepository repository = new Model.Repository(); var objUsu = repository.FindEntity <Usuario>(c => c.CorreoElectronico == email && c.Activo == true); int id = 0; string strMensaje = "El usuario y/o contraseña son incorrectos."; recordar = recordar == null ? false : true; if (objUsu != null) { if (CryproHelper.Confirm(password, objUsu.Password, CryproHelper.Supported_HA.SHA512)) { id = -1; SessionHelper.AddUserToSession(objUsu.Id.ToString(), (bool)recordar); SessionHelper.ActualizarSession(objUsu); if (objUsu.Rol_Id == 1) { strMensaje = Url.Content("~/Home"); } } } return(Json(new Response { IsSuccess = true, Message = strMensaje, Id = id }, JsonRequestBehavior.AllowGet)); }
public ActionResult ListaUsuarios(string val, string valSearch, int?page) { ViewBag.CurrentSort = val; ViewBag.Buscar = valSearch; IRepository repository = new Model.Repository(); List <Usuarios> objProduct = new List <Usuarios>(); if (string.IsNullOrEmpty(valSearch)) { objProduct = repository.FindEntitySet <Usuarios>(c => true).OrderBy(c => c.IdUsuario).ToList(); } else { objProduct = repository.FindEntitySet <Usuarios>(c => true && (c.NombreUsuario.ToString().Contains(valSearch) || c.TipoUsuario.Contains(valSearch))).OrderBy(c => c.IdUsuario).ToList(); } if (val == "IdUsuario)" || string.IsNullOrEmpty(val)) { val = "IdUsuario)"; objProduct = objProduct.OrderBy(c => c.IdUsuario).ToList(); } ViewBag.Order = val; int pageSize = 5; int pageNumber = page ?? 1; return(PartialView(objProduct.ToPagedList(pageNumber, pageSize))); }
public ActionResult Eliminar(int Id) { string strMensaje = "No se encontro el diagnostico que desea eliminar"; bool okResult = false; IRepository repository = new Model.Repository(); var objProd = repository.FindEntity <Diagnosticos>(c => c.IdDiagnostico == Id); if (objProd != null) { try { repository.Delete(objProd); strMensaje = "Se elimino el diagnostico correctamente"; okResult = true; } catch (Exception) { strMensaje = "No Se puede eliminir el diagnostico"; okResult = true; } } return(Json(new Response { IsSuccess = okResult, Message = strMensaje, Id = Id }, JsonRequestBehavior.AllowGet)); }
public ActionResult Activar(string Token) { if (!string.IsNullOrEmpty(Token)) { IRepository repository = new Model.Repository(); var objUsu = repository.FindEntity <Usuario>(c => c.Token == Token); if (objUsu != null) { ViewBag.Mensaje = "Cuenta Activada"; objUsu.Token = ""; objUsu.Activo = true; repository.Update(objUsu); } else { ViewBag.Mensaje = "La cuenta no se pudo activar"; } } else { ViewBag.Mensaje = "La cuenta no se pudo activar"; } return(View()); }
public ActionResult ListaPacientes(string val, string valSearch, int?page) { ViewBag.CurrentSort = val; ViewBag.Buscar = valSearch; IRepository repository = new Model.Repository(); List <Pacientes> objProduct = new List <Pacientes>(); if (string.IsNullOrEmpty(valSearch)) { objProduct = repository.FindEntitySet <Pacientes>(c => true).OrderBy(c => c.IdPaciente).ToList(); } else { objProduct = repository.FindEntitySet <Pacientes>(c => true && (c.ApellidoPaterno.Contains(valSearch) || c.ApellidoMaterno.Contains(valSearch))).OrderBy(c => c.Dni).ToList(); } if (val == "IdPaciente" || string.IsNullOrEmpty(val)) { val = "IdPaciente"; objProduct = objProduct.OrderBy(c => c.IdPaciente).ToList(); } ViewBag.Order = val; int pageSize = 5; int pageNumber = page ?? 1; return(PartialView(objProduct.ToPagedList(pageNumber, pageSize))); }
public ActionResult Get(int Id) { string strMensaje = "No se encontro la Historia que desea editar"; IRepository repository = new Model.Repository(); var objProd = repository.FindEntity <Historias>(c => c.IdHistoria == Id); if (objProd != null) { Historia historia = new Historia { IdHistoria = objProd.IdHistoria, CodigoDiagnostico = objProd.CodigoDiagnostico, Motivo = objProd.Motivo, Tratamiento = objProd.Tratamiento, Fecha = objProd.Fecha, DniPsicologo = objProd.DniPsicologo, Observacion = objProd.Observacion }; return(Json(new Response { IsSuccess = true, Id = Id, Result = historia }, JsonRequestBehavior.AllowGet)); } return(Json(new Response { IsSuccess = false, Message = strMensaje, Id = Id }, JsonRequestBehavior.AllowGet)); }
public ActionResult Add(Administrador admin, Usuario usuario) { IRepository repository = new Model.Repository(); int id = 0; string strMensaje = "No se pudo actualizar la información, intentelo más tarde"; bool okResult = false; if (usuario.IdUsuario > 0) { id = usuario.IdUsuario; Usuarios UpdatePaciente = repository.FindEntity <Usuarios>(c => c.IdUsuario == usuario.IdUsuario); if (UpdatePaciente != null) { Administrador actualizar = new Administrador(); strMensaje = actualizar.Actualizar(usuario, admin); okResult = true; } } else { id = admin.IdAdministrador; Administrador actualizar = new Administrador(); okResult = true; strMensaje = actualizar.crear(usuario, admin); } return(Json(new Response { IsSuccess = okResult, Message = strMensaje, Id = id }, JsonRequestBehavior.AllowGet)); }
// GET: Productos public ActionResult Index() { IRepository repository = new Model.Repository(); var objProduct = repository.FindEntitySet <Productos>(c => true).OrderBy(c => c.Nombre); return(View(objProduct)); }
public string actualizar(Usuario usuario, Paciente paciente) { string strMensaje = "Error"; IRepository repository = new Model.Repository(); Usuarios UpdatePaciente = repository.FindEntity <Usuarios>(c => c.IdUsuario == usuario.IdUsuario); string strPass = CryproHelper.ComputeHash(usuario.Contraseña, CryproHelper.Supported_HA.SHA512, null); Pacientes objUsuID = repository.FindEntity <Pacientes>(c => c.IdUsuario == UpdatePaciente.IdUsuario); if (objUsuID != null) { UpdatePaciente.NombreUsuario = usuario.NombreUsuario; UpdatePaciente.Contraseña = strPass; UpdatePaciente.Correo = usuario.Correo; repository.Update(UpdatePaciente); objUsuID.Dni = paciente.Dni; objUsuID.Nombres = paciente.Nombres; objUsuID.ApellidoPaterno = paciente.ApellidoPaterno; objUsuID.ApellidoMaterno = paciente.ApellidoMaterno; objUsuID.Direccion = paciente.Direccion; objUsuID.Edad = paciente.Edad; objUsuID.Sexo = paciente.Sexo; objUsuID.Profesion = paciente.Profesion; objUsuID.FechaNacimiento = Convert.ToDateTime(paciente.FechaNacimiento); objUsuID.Telefono = paciente.Telefono; repository.Update(objUsuID); strMensaje = "Se actualizaron sus datos"; } return(strMensaje); }
public static int CitasHoy() { IRepository repository = new Model.Repository(); var fecha = DateTime.Now.ToString("dd/MM/yyyy"); var objProduct = repository.FindEntitySet <Citas>(c => c.IdCita > 0).Where(c => c.Hora_inicial.Value.ToString("dd/MM/yyyy").Substring(0, 10).Equals(fecha)).Count(); return(objProduct); }
public static AspNetUsers GetUserById(string id) { Repository<AspNetUsers> userRepository = new Repository<AspNetUsers>(); var user = userRepository.Find(w => w.Id.Equals(id)); return user; }
public static int PacientesTotalesSexo(string sexo) { IRepository repository = new Model.Repository(); var objProduct = repository.FindEntitySet <Pacientes>(c => c.Sexo.Equals(sexo)).Count(); return(objProduct); }
public static int HistoriasTotales() { IRepository repository = new Model.Repository(); var objProduct = repository.FindEntitySet <Historias>(c => true).Count(); return(objProduct); }
public static DateTime FechaFinal() { IRepository repository = new Model.Repository(); Citas cantidadcitas = repository.FindEntitySet <Citas>(c => c.IdCita > 0).Last(); return(Convert.ToDateTime(cantidadcitas.Hora_final)); }
public static string nombres_Psicologo(string dni) { IRepository repository = new Model.Repository(); var nombres = repository.FindEntity <Psicologos>(c => c.Dni == dni).Nombres; var apellidoPaterno = repository.FindEntity <Psicologos>(c => c.Dni == dni).ApellidoPaterno; var apellidoMaterno = repository.FindEntity <Psicologos>(c => c.Dni == dni).ApellidoMaterno; return(nombres + " " + apellidoPaterno + " " + apellidoMaterno); }
public MainForm() { InitializeComponent(); //File.WriteAllText("repo.db4o", ""); _repository = new Repository("repo.db4o"); PupulateTreeView(myListView1, _repository.GetAll<Entry>()); Changed += MainFormChanged; }
public static string nombres(string id) { IRepository repository = new Model.Repository(); var objProduct2 = repository.FindEntity <Pacientes>(c => c.Dni == id).Nombres; var objProduct3 = repository.FindEntity <Pacientes>(c => c.Dni == id).ApellidoPaterno; var objProduct4 = repository.FindEntity <Pacientes>(c => c.Dni == id).ApellidoMaterno; return(objProduct2 + " " + objProduct3 + " " + objProduct4); }
public JsonResult Pacientes_Nombres(string id) { IRepository repository = new Model.Repository(); var events2 = repository.FindEntity <Citas>(c => c.IdCita == Convert.ToInt32(id)).DniPaciente; var objProduct2 = repository.FindEntity <Pacientes>(c => c.Dni == events2).Nombres; return(new JsonResult { Data = objProduct2, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); }
public ActionResult Get(int Id) { string strMensaje = "No se encontro el diagnostico que desea editar"; IRepository repository = new Model.Repository(); var diagnostico = repository.FindEntity <Diagnosticos>(c => c.IdDiagnostico == Id); var diag2 = repository.FindEntity <Pacientes>(c => c.Dni == diagnostico.DniPaciente); if (diagnostico != null) { Diagnostico diag = new Diagnostico { IdDiagnostico = diagnostico.IdDiagnostico, DniPaciente = diagnostico.DniPaciente, Fecha = diagnostico.Fecha, Esquizoide = diagnostico.Esquizoide, Evitativo = diagnostico.Evitativo, Depresivo = diagnostico.Depresivo, Dependiente = diagnostico.Dependiente, Histriónico = diagnostico.Histriónico, Narcisista = diagnostico.Narcisista, Antisocial = diagnostico.AgresivoSádico, AgresivoSádico = diagnostico.AgresivoSádico, Compulsivo = diagnostico.Compulsivo, Negativista = diagnostico.Negativista, Autodestructiva = diagnostico.Autodestructiva, Esquizotípica = diagnostico.Esquizotípica, Límite = diagnostico.Límite, Paranoide = diagnostico.Paranoide, Ansiedad = diagnostico.Ansiedad, Somatoformo = diagnostico.Somatoformo, Bipolar = diagnostico.Bipolar, Distímico = diagnostico.Distímico, DependenciaAlcohol = diagnostico.DependenciaAlcohol, DependenciaSustancias = diagnostico.DependenciaSustancias, EstrésPostraumático = diagnostico.EstrésPostraumático, DesordenPensamiento = diagnostico.DesordenPensamiento, DepresiónMayor = diagnostico.DepresiónMayor, DesordenDelusional = diagnostico.DesordenDelusional, Sinceridad = diagnostico.Sinceridad, DeseabilidadSocial = diagnostico.DeseabilidadSocial, Devaluación = diagnostico.Devaluación, Validez = diagnostico.Validez }; return(Json(new Response { IsSuccess = true, Id = Id, Result = diag, Result2 = diag2.Nombres, Result3 = diag2.ApellidoPaterno, Result4 = diag2.ApellidoMaterno }, JsonRequestBehavior.AllowGet)); } return(Json(new Response { IsSuccess = false, Message = strMensaje, Id = Id }, JsonRequestBehavior.AllowGet)); }
public ActionResult ListaPsicologos3(int?page) { IRepository repository = new Model.Repository(); List <Psicologos> objProduct = new List <Psicologos>(); objProduct = repository.FindEntitySet <Psicologos>(c => true).OrderBy(c => c.IdPsicologo).ToList(); int pageSize = 3; int pageNumber = page ?? 1; return(PartialView(objProduct.ToPagedList(pageNumber, pageSize))); }
public string GetFileFromDb(long tableId) { Repository<Model.TableModels> tablesRepository = new Repository<Model.TableModels>(new OasisProjectDbDataContext()); var table = tablesRepository.Find(w => w.Id == tableId); if (table != null) { System.IO.File.WriteAllBytes(filePath, table.Content.ToArray()); } return null; }
public ActionResult GetHorarios() { IRepository repository = new Model.Repository(); var events = repository.FindEntitySet <Citas>(c => true).ToList(); return(Json(events.AsEnumerable().Select(e => new { Id = e.IdCita.ToString(), title = nombres(e.DniPaciente), start = e.Hora_inicial.Value.ToString("yyyy-MM-ddTHH:mm"), end = e.Hora_final.Value.ToString("yyyy-MM-ddTHH:mm") }).ToList(), JsonRequestBehavior.AllowGet)); }
public static long GetSpreadsheetIdByName(string userId, string spreadsheetName) { //AddLog("GetSpreadsheetIdByName"); IRepository<Model.TableModels> spreadsheetRepository = new Repository<TableModels>(); var spreadsheet = spreadsheetRepository.Find(w => w.Name.Equals(spreadsheetName) && w.AuthorId_Id.Equals(userId)); if (spreadsheet != null) return spreadsheet.Id; return 0; }
public ActionResult Index() { if (HttpContext.Session["TipoUsuario"] == null) { return(RedirectToAction("Index", "Account")); } else { IRepository repository = new Model.Repository(); var objResult = repository.FindEntity <Usuarios>(c => true); return(View(objResult)); } }
public ActionResult Add(Diagnostico diag) { IRepository repository = new Model.Repository(); int id = 0; string strMensaje = "No se pudo actualizar la información, intentelo más tarde"; bool okResult = false; if (diag.IdDiagnostico > 0) { id = diag.IdDiagnostico; Diagnosticos diagnostico = repository.FindEntity <Diagnosticos>(c => c.IdDiagnostico == diag.IdDiagnostico); if (diagnostico != null) { diagnostico.Esquizoide = diag.Esquizoide; diagnostico.Evitativo = diag.Evitativo; diagnostico.Depresivo = diag.Depresivo; diagnostico.Dependiente = diag.Dependiente; diagnostico.Histriónico = diag.Histriónico; diagnostico.Narcisista = diag.Narcisista; diagnostico.AgresivoSádico = diag.AgresivoSádico; diagnostico.Compulsivo = diag.Compulsivo; diagnostico.Negativista = diag.Negativista; diagnostico.Autodestructiva = diag.Autodestructiva; diagnostico.Esquizotípica = diag.Esquizotípica; diagnostico.Límite = diag.Límite; diagnostico.Paranoide = diag.Paranoide; diagnostico.Ansiedad = diag.Ansiedad; diagnostico.Somatoformo = diag.Somatoformo; diagnostico.Bipolar = diag.Bipolar; diagnostico.Distímico = diag.Distímico; diagnostico.DependenciaAlcohol = diag.DependenciaAlcohol; diagnostico.DependenciaSustancias = diag.DependenciaSustancias; diagnostico.EstrésPostraumático = diag.EstrésPostraumático; diagnostico.DesordenPensamiento = diag.DesordenPensamiento; diagnostico.DepresiónMayor = diag.DepresiónMayor; diagnostico.DesordenDelusional = diag.DesordenDelusional; diagnostico.Sinceridad = diag.Sinceridad; diagnostico.DeseabilidadSocial = diag.DeseabilidadSocial; diagnostico.Devaluación = diag.Devaluación; diagnostico.Validez = diag.Validez; } //Productos objUpdateProd = (Productos)objProd; repository.Update(diagnostico); strMensaje = "Se actualizo el diagnostico"; okResult = true; } return(Json(new Response { IsSuccess = okResult, Message = strMensaje, Id = id }, JsonRequestBehavior.AllowGet)); }
public ActionResult Add(Historia objProd) { IRepository repository = new Model.Repository(); int id = 0; string strMensaje = "No se pudo actualizar la información, intentelo más tarde"; bool okResult = false; if (objProd.IdHistoria > 0) { id = objProd.IdHistoria; Historias objUpdateProd = repository.FindEntity <Historias>(c => c.IdHistoria == objProd.IdHistoria); if (objUpdateProd != null) { //objUpdateProd.Codigo = objProd.Codigo; objUpdateProd.Motivo = objProd.Motivo; objUpdateProd.Observacion = objProd.Observacion; objUpdateProd.CodigoDiagnostico = objProd.CodigoDiagnostico; objUpdateProd.Fecha = objProd.Fecha; objUpdateProd.DniPsicologo = objProd.DniPsicologo; objUpdateProd.Tratamiento = objProd.Tratamiento; } //Productos objUpdateProd = (Productos)objProd; repository.Update(objUpdateProd); strMensaje = "Se actualizo la Historia"; okResult = true; } else { string coder = PatronClinicoHelper.aletorio(); var objResultado = repository.Create(new Historias { Codigo = coder, CodigoDiagnostico = objProd.CodigoDiagnostico, Motivo = objProd.Motivo, Tratamiento = objProd.Tratamiento, Fecha = DateTime.Now, DniPsicologo = objProd.DniPsicologo, Observacion = objProd.Observacion }); id = objResultado.IdHistoria; if (objResultado != null) { okResult = true; strMensaje = "Se agrego la historia correctamente"; } } return(Json(new Response { IsSuccess = okResult, Message = strMensaje, Id = id }, JsonRequestBehavior.AllowGet)); }
public static DateTime FechaIni() { IRepository repository = new Model.Repository(); try { Citas cantidadcitas = repository.FindEntitySet <Citas>(c => c.IdCita > 0).Last(); return(Convert.ToDateTime(cantidadcitas.Hora_inicial)); } catch (Exception) { throw; } }
public ActionResult ResetPass(string tkn) { if (!string.IsNullOrEmpty(tkn)) { IRepository repository = new Model.Repository(); tkn = Server.UrlEncode(tkn); ViewBag.tkn = tkn; var objUsu = repository.FindEntity <Usuario>(c => c.Token == tkn); if (objUsu != null) { return(View()); } } return(RedirectToAction("Index", "Home")); }
public ActionResult GetAllHorarios() { IRepository repository = new Model.Repository(); var events = repository.FindEntitySet <Horarios>(c => true).ToList(); return(Json(events.AsEnumerable().Select(e => new { Id = e.Id.ToString(), title = e.Descripcion, start = e.FechaInicio.Value.ToString("yyyy-MM-ddTHH:mm"), end = e.FechaFinal.Value.ToString("yyyy-MM-ddTHH:mm"), dniPsicologo = e.DniPsicologo.ToString(), Psicologo = nombres_Psicologo(e.DniPsicologo) }).ToList(), JsonRequestBehavior.AllowGet)); }
public static string ConsultarFechafin(DateTime fechafinal) { IRepository repository = new Model.Repository(); int cantidadcitas = repository.FindEntitySet <Citas>(c => true).Last().IdCita; Citas objProduct = repository.FindEntitySet <Citas>(c => c.IdCita == cantidadcitas).First(); if (objProduct.Hora_final < fechafinal) { return(fechafinal.ToString()); } else { return("error"); } }
private static void InsertAlbumArt(Guid albumId, IPicture pic, ref Repository repo) { if (repo.Images.Count(x => x.LinkedId == albumId) > 0) return; var bitmap = ImageUtilities.ImageFromBuffer(pic.Data.ToArray()); var img = new Image { Height = (int) bitmap.Height, Id = Guid.NewGuid(), ImageData = pic.Data.ToArray(), LinkedId = albumId, Size = (int) ImageSize.ExtraLarge, Url = "", Width = (int) bitmap.Width }; repo.Images.InsertOnSubmit(img); repo.SubmitChanges(); }
public bool SaveFileToDb(string filePath, long tableId) { byte[] file; using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { using (var reader = new BinaryReader(stream)) { file = reader.ReadBytes((int)stream.Length); } } Repository<Model.TableModels> tablesRepository = new Repository<Model.TableModels>(new OasisProjectDbDataContext()); var table = tablesRepository.Find(w => w.Id == tableId); if (table != null) { table.Content = file; tablesRepository.Commit(); } return false; }
private bool IsUserAdmin(string userId, long spreadsheetId) { Repository<Model.TableModels> spreadsheetRepository = new Repository<TableModels>(); var spreadsheet = spreadsheetRepository.Find(w => w.Id == spreadsheetId && w.AdministratorId_Id.Equals(userId)); return spreadsheet != null; }
public async Task<ActionResult> RegisterByInvite(RegisterByInviteViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { // если создание прошло успешно, то добавляем роль пользователя await UserManager.AddToRoleAsync(user.Id, UserRoles.Redactors.ToString()); await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); // Дополнительные сведения о том, как включить подтверждение учетной записи и сброс пароля, см. по адресу: http://go.microsoft.com/fwlink/?LinkID=320771 // Отправка сообщения электронной почты с этой ссылкой // 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, "Подтверждение учетной записи", "Подтвердите вашу учетную запись, щелкнув <a href=\"" + callbackUrl + "\">здесь</a>"); Repository<AspNetUsers> userRepository = new Repository<AspNetUsers>(); var newUser = userRepository.Find(w => w.Email.Equals(model.Email)); if (newUser != null && newUser.CloudmailinEmail == null) { newUser.CloudmailinEmail = string.Format(Constants.PathConstants.Email, newUser.Email.Replace("@", "at")); if (newUser.Units == 0) { newUser.Units = 1; } userRepository.Commit(); if (model.adminEmail != null) { var admin = userRepository.Find(a => a.Email == SendMailHelper.Decrypt(model.adminEmail)); var redactor = new Model.TableRedactorModels() { Administrator_Id = admin.Id, TableId = -1, UserId_Id = newUser.Id }; redactorsRepository.Commit(); } } return RedirectToAction("Index", "Home"); } AddErrors(result); } // Появление этого сообщения означает наличие ошибки; повторное отображение формы return View(model); }
private static void ParseEmail(long emailId, string userId) { // AddLog("ParseEmail" + "emailId: " + emailId.ToString() + "userId: " + userId.ToString()); IRepository<EmailModels> emailRepository = new Repository<EmailModels>(); var email = emailRepository.Find(w => w.Id == emailId); //AddLog("Email: " + email.Content); if (email != null) { // AddLog("email != null"); IRepository<EmailParsingRulesModels> emailParsingRulesRepository = new Repository<EmailParsingRulesModels>(); var emailParsingRules = emailParsingRulesRepository.FindAll(w => w.AuthorId_Id.Equals(userId) && w.Status.Equals(Model.Enums.RuleStatusEnums.Active.ToString())).OrderBy(j => j.Name).ToList(); if (emailParsingRules != null && emailParsingRules.Any()) { // AddLog("emailParsingRules != null && emailParsingRules.Any()"); foreach (var rule in emailParsingRules) { if (rule.Email.Contains(email.From)) { bool b = true; if (rule.Subject != null) { if (!email.Subject.Equals(rule.Subject)) { b = false; } } if (b && rule.PlainContains != null) { if (!email.Content.Contains(rule.PlainContains)) { b = false; } } // AddLog(rule.IsUpdatingRule.ToString()); if (b) ParseEmailData(emailId, rule.Id); } } } } }
private static void ParseCellValue(EmailModels email, EmailDataParsingRulesModels dataParsingRule, int row, bool CopyRuleFromPreviousOrder) { // AddLog("ParseCellValue"); var path = SpreadsheetHelper.GetSpreadsheetPathById((long)dataParsingRule.TableId_Id); if (path != null) { var name = dataParsingRule.TableId_Id.ToString(); SpreadsheetExtension.LoadDocument(name, path); IWorkbook workbook = SpreadsheetExtension.GetCurrentDocument(name); Worksheet worksheet = workbook.Worksheets[dataParsingRule.Worksheet]; var value = BeforeParseValueFromEmail(email, dataParsingRule); if (value != null) { if (dataParsingRule.IsUpdatingRule) { if (CopyRuleFromPreviousOrder) { worksheet.Cells[row, dataParsingRule.ColumnForUpdate].CopyFrom(worksheet.Cells[row + 1, dataParsingRule.ColumnForUpdate], PasteSpecial.Formats); } worksheet.Cells[row, dataParsingRule.ColumnForUpdate].Value = value.Replace("\n", " "); } else { if (CopyRuleFromPreviousOrder) { worksheet.Cells[row, dataParsingRule.Column].CopyFrom(worksheet.Cells[row + 1, dataParsingRule.Column], PasteSpecial.Formats); } worksheet.Cells[row, dataParsingRule.Column].Value = value.Replace("\n", " "); } } workbook.SaveDocument(path); SpreadsheetExtension.CloseDocument(name); Repository<ParsedCells> parsedCellsRepository = new Repository<ParsedCells>(); var cell = new ParsedCells { Column = dataParsingRule.Column, Content = value, EmailId_Id = email.Id, TableId_Id = dataParsingRule.TableId_Id, Worksheet = dataParsingRule.Worksheet, WorksheetName = worksheet.Name }; parsedCellsRepository.Add(cell); parsedCellsRepository.Commit(); } }
private static void InsertEmailLink(long emailId, Model.SaveEmailProperty parsingRule, int row, string author_Id, bool CopyRuleFromPreviousOrder) { try { IRepository < Model.TableModels > tablesRepository = new Repository<TableModels>(); var tableId = tablesRepository.Find(w => w.Name==parsingRule.TableId && w.AuthorId_Id == author_Id).Id; // AddLog(tableId.ToString()); var worksheetId = Convert.ToInt32(parsingRule.Worksheet); var column = (int)Enum.Parse(typeof(ColumnEnums), parsingRule.Column); var path = SpreadsheetHelper.GetSpreadsheetPathById(tableId); if (path != null) { IRepository<TableModels> spreadsheetRepository = new Repository<TableModels>(); var name = spreadsheetRepository.Find(w => w.Id == tableId).Name; SpreadsheetExtension.LoadDocument(name, path); IWorkbook workbook = SpreadsheetExtension.GetCurrentDocument(name); if (workbook.Worksheets.Count < worksheetId + 1) { int startWorksheets = workbook.Worksheets.Count; for (int i = 0; i < worksheetId - startWorksheets + 1; i++) { workbook.Worksheets.Add(); } } Worksheet worksheet = workbook.Worksheets[worksheetId]; var cell = worksheet.Cells[row, column]; // AddLog("InsertEmailLink - " + "worksheet.Cells[" + row + ", " + column+"];"); if (parsingRule.SaveEmailProp != null) { worksheet.Hyperlinks.Add(cell, "javascript:OpenPopup(" + emailId + ")", false, "O"); cell.CopyFrom(worksheet.Cells[row + 1, column], PasteSpecial.Formats); } else if (parsingRule.DefaultValue != null) { if (CopyRuleFromPreviousOrder) { worksheet.Cells[row, column].CopyFrom(worksheet.Cells[row + 1, column], PasteSpecial.Formats); } worksheet.Cells[row, column].Value = parsingRule.DefaultValue; } byte[] size = workbook.SaveDocument(DocumentFormat.Xlsx); tablesRepository.Find(w => w.Id == tableId).Size = size.Length; tablesRepository.Commit(); workbook.SaveDocument(path); SpreadsheetExtension.CloseDocument(name); } } catch { } }
private void ProcessTrack(string path, ref Track track, ref Repository repo) { var file = TagLib.File.Create(path); track.Name = file.Tag.Title; track.TrackNumber = (int) file.Tag.Track; track.Duration = (int) file.Properties.Duration.TotalSeconds; track.BPM = (int) file.Tag.BeatsPerMinute; track.BitRate = file.Properties.AudioBitrate; track.Comments = file.Tag.Comment; track.Composer = ""; foreach (var composer in file.Tag.Composers.Take(file.Tag.Composers.Count() - 1)) { track.Composer += composer + "; "; } track.Composer += file.Tag.Composers.Count() > 0 ? file.Tag.Composers.Last() : ""; track.DiscNumber = (int) file.Tag.Disc; track.SampleRate = file.Properties.AudioSampleRate; track.Year = (int) file.Tag.Year; track.MBID = string.IsNullOrEmpty(file.Tag.MusicBrainzTrackId) ? (Guid?)null : new Guid(file.Tag.MusicBrainzTrackId); track.Genre = file.Tag.FirstGenre; var artistId = GetArtist(file.Tag, ref repo); track.ArtistId = artistId; track.AlbumId = GetAlbum(artistId, file.Tag, ref repo); if (file.Tag.Pictures.Count() > 0) { var pic = file.Tag.Pictures[0]; InsertAlbumArt(track.AlbumId, pic, ref repo); } }
public ActionResult EditSpreadsheet(long id) { var userId = UserHelper.GetUserByEmail(User.Identity.Name).Id; if (IsUserAdmin(userId, id)) { Repository<Model.TableModels> spreadsheetRepository = new Repository<TableModels>(); var spreadsheet = spreadsheetRepository.Find(w => w.Id == id); if (spreadsheet != null) { ViewBag.SpreadsheetId = id; return View(spreadsheet); } } return RedirectToAction("ManageSpreadsheets"); }
public static string GetPartOfPageForLangById(string id, string lang) { InternationalizationRepository = new Repository<InternationalizationPartsOfPage>(); var currentRow = InternationalizationRepository.Find(c => c.ID.IndexOf(id)>-1); string result = (string)currentRow.GetType().GetProperties().Where(p => p.Name.ToLower().Contains(lang)).FirstOrDefault().GetValue(currentRow, null); return result==null ? "":result.ToString(); }
public ActionResult ManageSpreadsheets() { var userId = UserHelper.GetUserByEmail(User.Identity.Name).Id; Repository<Model.TableModels> spreadsheetRepository = new Repository<TableModels>(); var spreadsheets = spreadsheetRepository.FindAll(w => w.AdministratorId_Id.Equals(userId)); if (spreadsheets != null && spreadsheets.Any()) { return View(spreadsheets.ToList()); } return View(); }
public ActionResult EditSpreadsheet(TableModels model) { try { var userId = UserHelper.GetUserByEmail(User.Identity.Name).Id; if (ModelState.IsValid && IsUserAdmin(userId, model.Id)) { var dateTime = DateTime.Now; Repository<Model.TableModels> spreadsheetRepository = new Repository<Model.TableModels>(); var spreadsheet = spreadsheetRepository.Find(w => w.Id == model.Id); if (spreadsheet != null) { spreadsheet.Name = model.Name; } spreadsheetRepository.Commit(); long brandNewTable = spreadsheetRepository.Find(w => w.AuthorId_Id == userId && w.CreationDate == dateTime).Id; return RedirectToAction("Spreadsheet", new { id = brandNewTable }); } } catch (Exception) { } return RedirectToAction("ManageSpreadsheets"); }
private Guid GetAlbum(Guid artistId, Tag tag, ref Repository repo) { Guid id; lock (albumLock) { var album = repo.Albums.FirstOrDefault(x => x.ArtistId == artistId && x.Name == tag.Album); if (album == null) { album = new Album {Id = Guid.NewGuid()}; album.MBID = string.IsNullOrEmpty(tag.MusicBrainzReleaseId) ? (Guid?) null : new Guid(tag.MusicBrainzReleaseId); album.Name = tag.Album; album.ArtistId = artistId; repo.Albums.InsertOnSubmit(album); repo.SubmitChanges(); } id = album.Id; } return id; }
private Guid GetArtist(Tag tag, ref Repository repo) { Guid id; lock (artistLock) { var artist = repo.Artists.FirstOrDefault(x => x.Name == tag.FirstArtist); if (artist == null) { artist = new Artist {Id = Guid.NewGuid()}; artist.MBID = string.IsNullOrEmpty(tag.MusicBrainzArtistId) ? (Guid?) null : new Guid(tag.MusicBrainzArtistId); artist.Name = tag.FirstArtist; repo.Artists.InsertOnSubmit(artist); repo.SubmitChanges(); } id = artist.Id; } return id; }
public int ForLocalTestReceive(long id) { Repository<Model.EmailModels> emailsRepository = new Repository<Model.EmailModels>(); var email = emailsRepository.Find(w => w.Id == id); var subject = email.Subject; var content = email.Content; var contentHtml = email.ContentHtml; Oasis.Models.MailinData.MailEnvelope envelope = new MailinData.MailEnvelope() { From = "*****@*****.**", To = "*****@*****.**" }; Oasis.Models.MailinData.MailHeaders headers = new MailinData.MailHeaders() { Date = DateTime.Now, Subject = subject }; Receive(new Oasis.Models.MailinData() { Envelope = envelope, Headers = headers, Plain = content, Html = contentHtml }); return 1; }
private static void ParseEmailData(long emailId, long ruleId) { // AddLog("ParseEmailData"); IRepository<EmailModels> emailRepository = new Repository<EmailModels>(); var email = emailRepository.Find(w => w.Id == emailId); if (email != null) { int row = -1; List<int> rows = new List<int>(); IRepository<EmailParsingRulesModels> emailParsingRulesRepository = new Repository<EmailParsingRulesModels>(); var emailParsingRule = emailParsingRulesRepository.Find(w => w.Id == ruleId); if (emailParsingRule != null) { // AddLog("emailParsingRule != null"); List<Models.TablesList> tablesList = new List<Models.TablesList>(); IRepository<Model.SaveEmailProperty> saveEmailPropertiesRepository = new Repository<Model.SaveEmailProperty>(); var allDefaultValues = saveEmailPropertiesRepository.FindAll(i => i.EmailParsingRulesModelsId == emailParsingRule.Id).ToList(); IRepository<Model.TableModels> tablesRepository = new Repository<TableModels>(); IRepository<EmailDataParsingRulesModels> emailDataParsingRulesRepository = new Repository<EmailDataParsingRulesModels>(); var emailDataParsingRules = emailDataParsingRulesRepository.FindAll( w => w.EmailParsingRulesModelsId_Id == emailParsingRule.Id && w.Status.Equals(Model.Enums.RuleStatusEnums.Active.ToString())).OrderBy(r => r.Name).ToList(); if (emailDataParsingRules != null && emailDataParsingRules.Count != 0) { // AddLog("emailDataParsingRules.Count != 0"); foreach (var dataParsingRule in emailDataParsingRules) { if (tablesList.Find(w => w.TableId == dataParsingRule.TableId_Id && w.IsChecked) == null && dataParsingRule.Status != Model.Enums.RuleStatusEnums.Paused.ToString()) { var name = dataParsingRule.TableId_Id.ToString(); var path = SpreadsheetHelper.GetSpreadsheetPathById((long)dataParsingRule.TableId_Id); try { SpreadsheetExtension.LoadDocument(name, path); IWorkbook workbook = SpreadsheetExtension.GetCurrentDocument(name); Worksheet worksheet = workbook.Worksheets[ emailParsingRule.EmailDataParsingRulesModels.FirstOrDefault().Worksheet]; if (emailParsingRule.IsUpdatingRule) { var changing = emailParsingRule.EmailDataParsingRulesModels.FirstOrDefault( w => w.IsUpdatindIndex && w.EmailParsingRulesModelsId_Id == emailParsingRule.Id); var changingIndex = BeforeParseValueFromEmail(email, changing); if (path != null) { foreach (var c in worksheet.Columns[dataParsingRule.Column].ExistingCells) { var value = c.Value.ToString(); if (value.Equals(changingIndex)) { row = c.RowIndex; rows.Add(row); } } byte[] size = workbook.SaveDocument(DocumentFormat.Xlsx); tablesRepository.Find(t => t.Id == dataParsingRule.TableId_Id).Size = size.Length; tablesRepository.Commit(); workbook.SaveDocument(path); SpreadsheetExtension.CloseDocument(name); } } else { worksheet.Rows.Insert(1); row = 1; } if (row != -1) { var author_Id = emailParsingRule.AuthorId_Id; foreach (var defaultValue in allDefaultValues) { if (emailParsingRule.Status != Model.Enums.RuleStatusEnums.Paused.ToString()) { InsertEmailLink(emailId, defaultValue, row, author_Id, emailParsingRule.CopyRuleFromPreviousOrder); } } foreach ( var dataParsing in emailParsingRule.EmailDataParsingRulesModels.Where( w => w.TableId_Id == dataParsingRule.TableId_Id)) { if (dataParsing.Status != Model.Enums.RuleStatusEnums.Paused.ToString()) { if (emailParsingRule.IsUpdatingRule) { foreach (var rowForUpdate in rows) { ParseCellValue(email, dataParsing, rowForUpdate, emailParsingRule.CopyRuleFromPreviousOrder); } rows.Clear(); } else { ParseCellValue(email, dataParsing, row, emailParsingRule.CopyRuleFromPreviousOrder); } } } tablesList.Add(new TablesList { IsChecked = true, TableId = (long)dataParsingRule.TableId_Id }); } } catch { AddLog("Table not found"); } } } } else if (allDefaultValues != null) { var tablesInallDefaultValues = allDefaultValues.GroupBy(a => a.TableId).Select(g => g.First()); foreach (var defaultValue in tablesInallDefaultValues) { try { var name = tablesRepository.Find(w => w.Name == defaultValue.TableId && w.AuthorId_Id == emailParsingRule.AuthorId_Id).Name; var path = SpreadsheetHelper.GetSpreadsheetPathById(tablesRepository.Find(w => w.Name == defaultValue.TableId && w.AuthorId_Id == emailParsingRule.AuthorId_Id).Id); SpreadsheetExtension.LoadDocument(name, path); IWorkbook workbook = SpreadsheetExtension.GetCurrentDocument(name); Worksheet worksheet = workbook.Worksheets[ Convert.ToInt32(defaultValue.Worksheet)]; worksheet.Rows.Insert(1); row = 1; byte[] size = workbook.SaveDocument(DocumentFormat.Xlsx); tablesRepository.Find(w => w.Name == defaultValue.TableId && w.AuthorId_Id == emailParsingRule.AuthorId_Id).Size = size.Length; tablesRepository.Commit(); workbook.SaveDocument(path); SpreadsheetExtension.CloseDocument(name); } catch (Exception ex) { AddLog(ex.Message); } } foreach (var defaultValue in allDefaultValues) { InsertEmailLink(emailId, defaultValue, row, emailParsingRule.AuthorId_Id, emailParsingRule.CopyRuleFromPreviousOrder); } } } } }