public static void Insert(StudentToAdd student)
        {

            BandStudentDBEntities db = new BandStudentDBEntities();
            System.Data.Entity.Core.Objects.ObjectParameter OutputID = new System.Data.Entity.Core.Objects.ObjectParameter("OutputID", typeof(int?));
            int StudentIdFromDB = db.InsertStudentData(student.StudentFirstName, student.StudentLastName, student.StudentAddress, student.StudentCity, student.StudentState, student.StudentZipCode, student.StudentPhone, student.PerformanceMedium, student.GraduationYear, student.EmailAddress, OutputID);
            StudentIdFromDB = Convert.ToInt32(OutputID.Value);
            db.SaveChanges();
            db.CreateUpdate_InterestAreas(StudentIdFromDB, student.InterestAreas.BM_Music_Education_Vocal, student.InterestAreas.BM_Music_Education_Instrumental,
                                          student.InterestAreas.BM_Music_Performance_Vocal, student.InterestAreas.BM_Music_Performance_Instrumental,
                                          student.InterestAreas.BM_Music_Elective_Studies_Business, student.InterestAreas.BM_Music_Elective_Studies_Outside_Fields,
                                          student.InterestAreas.MM_Performance_Piano, student.InterestAreas.MM_Performance_Vocal, student.InterestAreas.MM_Collaborative_Piano,
                                          student.InterestAreas.Music_Minor, student.InterestAreas.Instrumental_Ensembles, student.InterestAreas.Choral_Ensembles,
                                          student.InterestAreas.Opera_Theatre, student.InterestAreas.Jaguar_Marching_Band, student.InterestAreas.Other, student.InterestAreas.MM_Concentration_in_Music_Education);
            db.SaveChanges();
        }
Exemple #2
0
        public ResultadoTransaccion guardarRegistro(ARTICULO articulo)
        {
            try
            {
                PERFECTEntities entidad = new PERFECTEntities();

                System.Data.Entity.Core.Objects.ObjectParameter resultado = new System.Data.Entity.Core.Objects.ObjectParameter("RESULTADO", typeof(string));
                System.Data.Entity.Core.Objects.ObjectParameter mensaje = new System.Data.Entity.Core.Objects.ObjectParameter("MENSAJE", typeof(string));

                entidad.PROG_ARTICULO_ACTUALIZA(articulo.CODIGO_ARTICULO,
                    articulo.NOMBRE_ARTICULO,
                    articulo.NOMBRE_CORTO,
                    articulo.DESCRIPCION,
                    articulo.CODIGO_CATEGORIA,
                    articulo.CLASIFICACION1,
                    articulo.CLASIFICACION2,
                    articulo.CLASIFICACION3,
                    articulo.CLASIFICACION4,
                    articulo.PRESENTACION_BASE,
                    articulo.PERMITE_VENTA,
                    articulo.PERMITE_COMPRA,
                    articulo.CAMBIAR_DESCRIPCION,
                    articulo.CONSULTAR_PRECIO,
                    articulo.PAGA_IMPUESTO,
                    articulo.PRECIO_VENTA,
                    articulo.MANEJA_INVENTARIO,
                    articulo.INVENTARIO_MINIMO,
                    articulo.INVENTARIO_MAXIMO,
                    resultado, mensaje);

                return new ResultadoTransaccion
                {
                    Resultado = resultado.Value.ToString().ToLower() == "ok" ? TipoResultado.Ok : TipoResultado.Error,
                    Mensaje = mensaje.Value.ToString()
                };

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public ResultadoTransaccion guardarRegistro(ARTICULO_CATEGORIA categoria)
        {
            try
            {
                PERFECTEntities entidad = new PERFECTEntities();
                System.Data.Entity.Core.Objects.ObjectParameter resultado = new System.Data.Entity.Core.Objects.ObjectParameter("RESULTADO", typeof(string));
                System.Data.Entity.Core.Objects.ObjectParameter mensaje = new System.Data.Entity.Core.Objects.ObjectParameter("MENSAJE", typeof(string));

                entidad.PROG_ARTICULO_CATEGORIA_ACTUALIZA(categoria.CODIGO_CATEGORIA, categoria.NOMBRE_CATEGORIA, resultado, mensaje);

                return new ResultadoTransaccion
                {
                    Resultado = resultado.Value.ToString().ToLower() == "ok" ? TipoResultado.Ok : TipoResultado.Error,
                    Mensaje = mensaje.Value.ToString()
                };

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public ActionResult InsertCategory(ForumMainCategory maincat)
        {
            if (Request.Cookies["memsid"].Value == "14")
            {
                long memid = Convert.ToInt64(Request.Cookies["memsid"].Value);
                if (maincat.Category != null || maincat.descrip != null)
                {
                    System.Data.Entity.Core.Objects.ObjectParameter output = new System.Data.Entity.Core.Objects.ObjectParameter("rowEffect", typeof(int));
                    db.ForumAddCategory(maincat.Category, maincat.descrip, memid, output, System.DateTime.Now);

                    int i = Convert.ToInt32(output.Value);
                    if (i > 0)
                    {
                        ViewBag.Success = true;
                        ViewBag.message = "Category Added Successfully";
                    }
                    else if (i == -2)
                    {
                        ViewBag.Success = false;
                        ViewBag.message = maincat.Category + " Allredy Exist Please add new Category";
                    }
                    else
                    {
                        ViewBag.Success = false;
                        ViewBag.message = "Unable to add Category";
                    }
                }
                else
                {
                    ViewBag.Success = false;
                    ViewBag.message = "Unable to add Category";
                }
                return View();
            }
            else
            {
                return RedirectToAction("Login", "Home");
            }
        }
Exemple #5
0
        public ResultadoTransaccion borrarRegistro(string codigoArticulo)
        {
            try
            {
                PERFECTEntities entidad = new PERFECTEntities();
                System.Data.Entity.Core.Objects.ObjectParameter resultado = new System.Data.Entity.Core.Objects.ObjectParameter("RESULTADO", typeof(string));
                System.Data.Entity.Core.Objects.ObjectParameter mensaje = new System.Data.Entity.Core.Objects.ObjectParameter("MENSAJE", typeof(string));

                entidad.PROG_ARTICULO_BORRAR(codigoArticulo, resultado, mensaje);

                return new ResultadoTransaccion
                {
                    Resultado = resultado.Value.ToString().ToLower() == "ok" ? TipoResultado.Ok : TipoResultado.Error,
                    Mensaje = mensaje.Value.ToString()
                };

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #6
0
        protected void LogIn(object sender, EventArgs e)
        {
            if (IsValid)
            {
                // Validate the user password
                var manager       = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
                var signinManager = Context.GetOwinContext().GetUserManager <ApplicationSignInManager>();

                ApplicationDbContext context = new ApplicationDbContext();
                // This doen't count login failures towards account lockout
                // To enable password failures to trigger lockout, change to shouldLockout: true


                var user = manager.FindByEmail(Email.Text);

                if (user != null)
                {
                    if (user.Active == false)
                    {
                        FailureText.Text     = "Su cuenta se encuentra desactivada. Favor de comunicarse con equipo de informática.";
                        ErrorMessage.Visible = true;
                    }
                    else if (!user.EmailConfirmed)
                    {
                        FailureText.Text      = "Intento fallido!. Ustede debe confirmar su cuenta antes de utilizar este sistema.";
                        ErrorMessage.Visible  = true;
                        ResendConfirm.Visible = true;
                    }
                    else
                    {
                        var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);

                        switch (result)
                        {
                        case SignInStatus.Success:
                            //IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                            try
                            {
                                ApplicationUser Usuario = context.Users.Where(u => u.Email.Equals(Email.Text, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

                                using (CARAEntities dsCARA = new CARAEntities())
                                {
                                    System.Data.Entity.Core.Objects.ObjectParameter pk_Sesion_Output = new System.Data.Entity.Core.Objects.ObjectParameter("PK_Sesion", typeof(string));

                                    var spc_sesion = dsCARA.SPC_SESION(Usuario.Id, pk_Sesion_Output);

                                    Session["PK_Sesion"] = pk_Sesion_Output.Value.ToString();
                                }

                                Session["Usuario"] = Usuario;

                                if (Usuario.PasswordChanged)
                                {
                                    Response.Redirect("~/App/Entrada", false);
                                }
                                else
                                {
                                    Session["Usuario"]   = null;
                                    Session["PK_Sesion"] = null;
                                    Context.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                                    Response.Redirect("~/Account/ResetPassword");
                                }
                            }
                            catch (Exception)
                            {
                                //Exception err = Server.GetLastError();
                                //Session.Add("LastError", err);
                                //Response.Redirect("~/App/Errores/OtrosError");
                                throw;
                            }

                            break;

                        case SignInStatus.LockedOut:
                            Response.Redirect("/Account/Lockout");
                            break;

                        case SignInStatus.RequiresVerification:
                            Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}",
                                                            Request.QueryString["ReturnUrl"],
                                                            RememberMe.Checked),
                                              true);
                            break;

                        case SignInStatus.Failure:
                        default:
                            FailureText.Text     = "Intento de ingreso fallído.";
                            ErrorMessage.Visible = true;
                            break;
                        }
                    }
                }
                else
                {
                    FailureText.Text     = "No existe una cuenta con el email ingresado. Favor utilizar email de cuenta existente.";
                    ErrorMessage.Visible = true;
                }
            }
        }
        public virtual System.Data.Entity.Core.Objects.ObjectResult<IsUseraBusiness_Result> IsUseraBusiness(int userId)
        {
            //var userIdParameter = userId.HasValue ?
            var userIdParameter = new System.Data.Entity.Core.Objects.ObjectParameter("userId", userId);
                //new System.Data.Entity.Core.Objects.ObjectParameter("userId", typeof(int));

            var test = new List<System.Data.Entity.Core.Objects.ObjectParameter>();
            test.Add(userIdParameter);

            var another = test.ToArray();

            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<IsUseraBusiness_Result>("IsUseraBusiness", another);
        }
        //Insert de un Contrato Arrto de Otras Fig. Ocuapacion
        //Devuelve el Folio de contrato
        public int InsertContratoArrtoOtrasFigOcupacion(ModeloNegocios.ContratoArrto objContratoArrto)
        {
            int FolioContrato = 0;

            System.Data.Entity.Core.Objects.ObjectParameter parametroFolioContrato = new System.Data.Entity.Core.Objects.ObjectParameter("FolioContrato", FolioContrato);

            using (ArrendamientoInmuebleEntities Conn = new ArrendamientoInmuebleEntities())
            {
                try
                {
                    Conn.spuInsertContratoOtrasFigurasOcupacion(

                        objContratoArrto.Fk_IdTipoOcupacion,//Comodato, Prestamo, Conscesión (aplicable solo a Arrendamiento de Otras Fig.)
                        objContratoArrto.OtroTipoOcupacion,
                        objContratoArrto.Fk_IdInmuebleArrendamiento,
                        objContratoArrto.Fk_IdTipoUsoInm, //del BUS
                        objContratoArrto.OtroUsoInmueble,
                        objContratoArrto.Fk_IdTipoMoneda,
                        objContratoArrto.Fk_IdInstitucion,
                        objContratoArrto.NombreInstitucion,
                        objContratoArrto.FechaInicioOcupacion,
                        objContratoArrto.FechaFinOcupacion,
                        objContratoArrto.AreaOcupadaM2,
                        objContratoArrto.MontoPagoMensual,
                        objContratoArrto.MontoPagoPorCajonesEstacionamiento,
                        objContratoArrto.CuotaMantenimiento,
                        objContratoArrto.PtjeImpuesto,
                        objContratoArrto.RIUF,
                        objContratoArrto.Observaciones,
                        objContratoArrto.PropietarioInmueble,
                        objContratoArrto.FuncionarioResponsable,
                        objContratoArrto.Fk_IdUsuarioRegistro,
                        objContratoArrto.CargoUsuarioRegistro,
                        //objetos de Persona Referencia (3):
                        //Responsable de la Ocupacion
                        objContratoArrto.PersonaReferenciaResponsableOcupacion.NombreCargo,
                        objContratoArrto.PersonaReferenciaResponsableOcupacion.Nombre,
                        objContratoArrto.PersonaReferenciaResponsableOcupacion.ApellidoPaterno,
                        objContratoArrto.PersonaReferenciaResponsableOcupacion.ApellidoMaterno,
                        objContratoArrto.PersonaReferenciaResponsableOcupacion.Email,
                        //titular del OIC
                        objContratoArrto.PersonaReferenciaTitularOIC.NombreCargo,
                        objContratoArrto.PersonaReferenciaTitularOIC.Nombre,
                        objContratoArrto.PersonaReferenciaTitularOIC.ApellidoPaterno,
                        objContratoArrto.PersonaReferenciaTitularOIC.ApellidoMaterno,
                        objContratoArrto.PersonaReferenciaTitularOIC.Email,
                        //Capturista
                        objContratoArrto.PersonaReferenciaCapturista.NombreCargo,
                        objContratoArrto.PersonaReferenciaCapturista.Nombre,
                        objContratoArrto.PersonaReferenciaCapturista.ApellidoPaterno,
                        objContratoArrto.PersonaReferenciaCapturista.ApellidoMaterno,
                        objContratoArrto.PersonaReferenciaCapturista.Email,
                        // apartado de seguridad
                        objContratoArrto.CuentaConDictamen,
                        objContratoArrto.FechaDictamen,

                        //
                        objContratoArrto.CadenaOriginal,
                        objContratoArrto.SelloDigital,
                        objContratoArrto.QR,
                        parametroFolioContrato //parametro ouput
                        );

                    Conn.SaveChanges();

                    if (parametroFolioContrato == null)
                    {
                        throw new InvalidOperationException("No se pudo registrar el Contrato de Arrendamiento, vuelva a intentar o reporte a Sistemas");
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("InsertContratoArrtoOtrasFigOcupacion: {0}", ex.Message));
                }
            }//using

            if (parametroFolioContrato.Value != null)
            {
                FolioContrato = Convert.ToInt32(parametroFolioContrato.Value);
            }

            //parametro de retorno, regresa 0 si no hay insert, o el folio > 0 si se realizo el insert
            return(FolioContrato);
        }
        public ActionResult InsertSubCategory(ForumSubCategory subcat)
        {
            if (Request.Cookies["memsid"].Value == "14")
            {


                long memsid = Convert.ToInt64(Request.Cookies["memsid"].Value);
                subcat.StartDate = System.DateTime.Now;
                subcat.StartedBy = Convert.ToInt64(Request.Cookies["memsid"].Value);

                if (subcat.SubCatTitle != null && subcat.SubCatDesc != null)
                {
                    System.Data.Entity.Core.Objects.ObjectParameter output = new System.Data.Entity.Core.Objects.ObjectParameter("rowEffect", typeof(int));
                    db.forumInsertSubCat(subcat.CatId, subcat.SubCatTitle, subcat.SubCatDesc, System.DateTime.Now, memsid, memsid, output);
                    //db.ForumSubCategories.Add(subcat);
                    //i = db.SaveChanges();
                    int i = Convert.ToInt32(output.Value);


                    if (i > 0)
                    {
                        ViewBag.Success = true;
                        ViewBag.message = "sub category Added Succsessfully";
                    }
                    else if (i == -2)
                    {
                        ViewBag.Success = false;
                        ViewBag.message = subcat.SubCatTitle + " Allredy Exist Please add new SubCategory";
                    }
                    else
                    {
                        ViewBag.Success = false;
                        ViewBag.message = "Unable to add SubCategory";
                    }
                }
                else
                {
                    ViewBag.Success = false;
                    ViewBag.message = "Unable to add SubCategory";
                }
                var catlist = (from d in db.ForumMainCategories
                               select new
                               {
                                   d.catid,
                                   d.Category
                               });
                var x = catlist.ToList().Select(c => new SelectListItem
                {
                    Text = c.Category,
                    Value = c.catid.ToString()

                }).ToList();
                ViewBag.category = x;
                return View();
            }
            else
            {
                return RedirectToAction("Login", "Home");
            }
        }
        public JsonResult GetInfo(int id_Report, string columnSelect, string columnGroup, string filtre, int? aseguradora)
        {
            var mensaje = "Exito";
            columnGroup = string.IsNullOrEmpty(columnGroup) ? null : columnGroup;
            var jsonColumnSelect = new List<ColumnSelect>();
            var jsonFiltre = new List<Filtre>();
            var columnSelectL = string.Empty;
            var filtreL = string.Empty;
            var idAseg = 0;
            try
            {
                // convierte la información de JSON a entidades
                jsonColumnSelect = Helpers.Functions.Deserialize<List<ColumnSelect>>(columnSelect);
                jsonFiltre = Helpers.Functions.Deserialize<List<Filtre>>(filtre);

                if (aseguradora != null && aseguradora != 0)
                {
                    var col = System.Configuration.ConfigurationManager.AppSettings["NombreColumnaAseguradora"].ToString();
                    var temp = context.Columna.FirstOrDefault(p => p.Id_Informe == id_Report && p.Nombre.Equals(col));
                    if (temp != null)
                    {
                        idAseg = temp.Id_ColumnasInformes;

                    }
                    else
                    {
                        return Json(new { Mensaje = "No se encontró la columna Aseguradora en el reporte seleccionado, valide con el administrador" });
                    }
                }
            }
            catch (Exception ex)
            {
                return Json(new { Mensaje = "Ocurrió un error al convertir la información a Json" + ex.Message, data = string.Empty, Quantity = false });
            }

            if (jsonColumnSelect.Count > 0)
            {
                try
                {
                    // Convierte la información de entidades a XML par enviar al SP
                    columnSelectL = Helpers.Functions.JsonToXml(columnSelect);
                    filtreL = Helpers.Functions.JsonToXml(filtre);

                    if (idAseg != 0)
                    {
                        var nuevo = @"   <root><value>"+aseguradora+"</value><Id>"+idAseg+@"</Id><Type>2</Type><Option>=</Option></root></Root>";

                        filtreL = filtreL.Replace("</Root>", nuevo);
                    }

                }
                catch (Exception ex)
                {
                    return Json(new { Mensaje = "Ocurrió un error al convertir la información a XML" + ex.Message, data = string.Empty, Quantity = false });
                }

                StringBuilder strXml = new StringBuilder();
                var errorSql = new System.Data.Entity.Core.Objects.ObjectParameter("Mensaje", typeof(string));
                try
                {
                    // Consulta la cantidad de registros obtenidos
                    var count = context.Sp_CantidadRegistrosReporte(id_Report, columnSelectL, filtreL, columnGroup, errorSql).ToList();

                    if (count.Count > 0)
                    {
                        var countReg = count.FirstOrDefault().Value;
                        if (countReg == null || Convert.ToInt32(countReg) > 2000)
                        {
                            return Json(new { Mensaje = "Supera la cantidad de registros máximos, filtre un poco más la información", data = string.Empty, Quantity = true });
                        }
                    }

                    // Obtiene la información
                    var data = context.Sp_ObtieneInformacionDinamica(id_Report, columnSelectL, filtreL,columnGroup, errorSql).ToList();
                    if(!String.IsNullOrEmpty(errorSql.Value.ToString()))
                        return Json(new { Mensaje = "Ocurrió un error al consular la información " + errorSql.Value.ToString(), data = string.Empty, Quantity = false });

                    foreach (var item in data)
                    {
                        strXml.Append(item);
                    }
                }
                catch (Exception ex)
                {
                    return Json(new { Mensaje = "Ocurrió un error al consular la información " + ex.Message, data = string.Empty, Quantity = false });
                }

                if (string.IsNullOrEmpty(strXml.ToString()))
                {
                    return Json(new { Mensaje = mensaje, data = "{\"Reg\":{\"Root\":[]}}", Quantity = false });
                }
                else
                {
                    var json = Helpers.Functions.XmlToJson(strXml.ToString());
                    return Json(new { Mensaje = mensaje, data = json, Quantity = false });
                }

            }

            return Json(new { Mensaje = mensaje, data = string.Empty });
        }
Exemple #11
0
        public PartialViewResult Tab(string id)
        {
            var userId = int.Parse(Session["userId"].ToString());

            System.Data.Entity.Core.Objects.ObjectParameter xmlOut = new System.Data.Entity.Core.Objects.ObjectParameter("xmlOut", typeof(object));
            int?operationId;

            if (id != null)
            {
                operationId = int.Parse(id);
            }
            else
            {
                operationId = null;
            }
            operationId = 1500;

            using (var _context = new Entities())
            {
                var res = _context.WebShellTerm(userId, operationId, xmlOut);
            }
            var         xmlDoc = xmlOut.Value;
            XmlDocument doc    = new XmlDocument();

            doc.LoadXml(xmlDoc.ToString());
            var listViewSourceName = doc.GetElementsByTagName("ShellPageSource")[0].InnerText;
            var groupSourceName    = doc.GetElementsByTagName("ShellPageGroupSource")[0].InnerText;
            var pageTitle          = doc.GetElementsByTagName("ShellTermName")[0].InnerText;

            List <dynamic> listViews = new List <dynamic>();
            List <dynamic> groupList = new List <dynamic>();

            using (var _context = new Entities())
            {
                var listView = (IEnumerable <dynamic>)(_context.GetType().GetProperty(listViewSourceName + "s").GetValue(_context, null));
                listViews = listView.Select(o => o).Take(15).ToList();
                object[] parameters = new object[1];
                parameters[0] = operationId;
                var resp = typeof(Entities).GetMethod(groupSourceName) != null ?
                           (IEnumerable <dynamic>)(typeof(Entities).GetMethod(groupSourceName).Invoke(_context, parameters)) :
                           (IEnumerable <dynamic>)(_context.GetType().GetProperty(groupSourceName + "s").GetValue(_context, null));
                groupList = resp.Select(o => o).ToList();
            }


            List <GroupingModel> resModel    = new List <GroupingModel>();
            List <ListViewModel> resViewList = new List <ListViewModel>();

            foreach (var item in groupList)
            {
                resModel.Add(new GroupingModel()
                {
                    Key  = item.KEY,
                    Name = item.NAME
                });
            }
            foreach (var item in listViews)
            {
                resViewList.Add(new ListViewModel
                {
                    Format = item.ShellTermFormat,
                    Id     = item.ShellTermID,
                    Name   = item.ShellTermName,
                    Key    = item.ShellTermKey,
                    Code   = item.ShellTermStatusID
                });
            }
            //--------------- get Status and Type  source Values ---------------------------------

            List <DropDownModel> finRes = new List <DropDownModel>();



            List <PageSearhcModel> searhSource = new List <PageSearhcModel>();
            List <PageSortModel>   sortSource  = new List <PageSortModel>();



            string pageTypeSourceName   = doc.GetElementsByTagName("ShellPageTypeSource")[0].InnerText;
            string pageStatusSourceName = doc.GetElementsByTagName("ShellPageStatusSource")[0].InnerText;



            var pageSearchNameSource   = doc.GetElementsByTagName("ShellPageSearchName");
            var pageSearchFormatSource = doc.GetElementsByTagName("ShellPageSearchFormat");

            for (int i = 0; i < pageSearchFormatSource.Count; i++)
            {
                searhSource.Add(new PageSearhcModel
                {
                    SearchFormat = pageSearchFormatSource.Item(i).InnerText,
                    SearchName   = pageSearchNameSource.Item(i).InnerText,
                });
            }

            var pageSortNameSource   = doc.GetElementsByTagName("ShellPageSortName");
            var pageSortFormatSource = doc.GetElementsByTagName("ShellPageSortFormat");

            for (int i = 0; i < pageSortFormatSource.Count; i++)
            {
                sortSource.Add(new PageSortModel
                {
                    SortFormat = pageSortFormatSource.Item(i).InnerText,
                    SortName   = pageSortNameSource.Item(i).InnerText,
                });
            }


            List <string> typeSource   = new List <string>();
            List <string> statusSource = new List <string>();

            using (var _context = new Entities())
            {
                var typeSource_  = (IEnumerable <dynamic>)(_context.GetType().GetProperty(pageTypeSourceName + "s").GetValue(_context, null));
                var typeSourceIn = typeSource_.Select(o => o).ToList();

                var statusSource_  = (IEnumerable <dynamic>)(_context.GetType().GetProperty(pageStatusSourceName + "s").GetValue(_context, null));
                var statusSourceIn = statusSource_.Select(o => o).ToList();

                foreach (var item in typeSourceIn)
                {
                    // ???????????????? for specific calss only, need to by dynamic
                    typeSource.Add(item.ShellTermTypeName);
                }

                foreach (var item in statusSourceIn)
                {
                    // ???????????????? for specific calss only, need to by dynamic
                    statusSource.Add(item.ShellTermStatusName);
                }
            }

            finRes.Add(new DropDownModel
            {
                ListView           = resViewList,
                LeftGroupModelList = resModel,
                PageTitle          = pageTitle,
                TypeSource         = typeSource,
                StatusSource       = statusSource,
                PageSearchSource   = searhSource,
                PaegSortSource     = sortSource
            });
            return(PartialView(finRes));
        }
Exemple #12
0
        public static int AddUserByUID(string strUser, Int32 intAPPID)
        {
            Int32 intASID = 0;

            RexrothEntities db        = clsStart.efdbRexroth();
            string          strDomain = "";

            System.Data.Entity.Core.Objects.ObjectParameter pk = new System.Data.Entity.Core.Objects.ObjectParameter("PK", typeof(int));

            System.Data.Entity.Core.Objects.ObjectParameter error = new System.Data.Entity.Core.Objects.ObjectParameter("EMessage", typeof(string));
            Cursor.Current = Cursors.WaitCursor;

            var lstDomains = new string[] { "US", "DE", "MX" };

            if (!(UserExists(strUser)))
            {
                foreach (string strDom in lstDomains)
                {
                    try
                    {
                        //var qry = (from ct in db.tblApp
                        //           where ct.APPID == intAPPID
                        //           select ct).FirstOrDefault();

                        PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, strDom);


                        UserPrincipal user = new UserPrincipal(domainContext);

                        //Specify the search parameters
                        user.Name = strUser;

                        PrincipalSearcher pS = new PrincipalSearcher();
                        pS.QueryFilter = user;

                        PrincipalSearchResult <Principal> results = pS.FindAll();


                        //If necessary, request more details
                        //Principal pc = results.ToList()[0];
                        //DirectoryEntry de = (DirectoryEntry)pc.GetUnderlyingObject();

                        if (results.ToList().Count > 0)
                        {
                            foreach (UserPrincipal usr in results)
                            {
                                //tblAssociate tbl = new tblAssociate();



                                //ObjectParameter name = new ObjectParameter("Name", typeof(String));
                                db.p_SaveChangesEF(usr.GivenName, usr.Surname, usr.SamAccountName, usr.EmailAddress.ToString(), usr.DisplayName, pk, error);

                                if (Convert.ToInt32(pk.Value) == 0)
                                {
                                    MessageBox.Show(error.ToString());
                                }

                                else
                                {
                                    Cursor.Current = Cursors.Default;
                                    MessageBox.Show(usr.DisplayName + " added!", "Credo");
                                }
                            }
                        }
                        else
                        {
                            Cursor.Current = Cursors.Default;
                            MessageBox.Show(strUser + " not found.", "Credo");
                        }
                    }
                    catch (Exception ex)
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show(ex.Message, "Credo");
                    }
                }
            }
            else
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show(strUser + " already exists.", "Credo");
            }
            Cursor.Current = Cursors.Default;

            intASID = Convert.ToInt32(pk.Value);
            return(intASID);
        }
Exemple #13
0
        /// <summary>
        /// 尝试登录(会先注销当前已用户)
        /// </summary>
        /// <param name="login_name">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        internal static bool TrySignIn(string login_name, string password, bool autoLogin = false)
        {
            iHealthEntities db = new iHealthEntities();
            //先通过调用数据库存储过程来判断用户密码是否正确
            var result  = new System.Data.Entity.Core.Objects.ObjectParameter("iscorrect", typeof(string));
            var user_id = new System.Data.Entity.Core.Objects.ObjectParameter("user_id", typeof(int));

            db.VeryfyPassword(login_name, password, result, user_id);
            if (result.Value.ToString().Equals("T"))//密码正确
            {
                //注销之前用户
                SignOut();
                //获取用户详细信息
                var user = db.USERINFO.Find((int)user_id.Value);
                if (user == null)
                {
                    return(false);
                }
                //如果启用自动登录,则将包含登录信息的Cookie存入客户端,
                //以便用户下次访问时通过读取Cookie来自动调用此方法登入系统
                if (autoLogin)
                {
                    //创建一个FormsAuthenticationTicket,它包含登录名以及额外的用户数据。
                    var data   = new TicketUserData(user.LOGIN_NM, user.PASSWORD);
                    var ticket = new FormsAuthenticationTicket
                                     (1, user.USER_ID.ToString(), DateTime.Now,
                                     DateTime.Now.AddDays(7), true, data.ToString());
                    //加密Ticket,变成一个加密的字符串。
                    var cookieValue = FormsAuthentication.Encrypt(ticket);
                    //根据加密结果创建登录Cookie
                    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue)
                    {
                        HttpOnly = true,
                        Secure   = FormsAuthentication.RequireSSL,
                        Domain   = FormsAuthentication.CookieDomain,
                        Path     = FormsAuthentication.FormsCookiePath
                    };
                    cookie.Expires = DateTime.Now.AddDays(7);
                    //写登录Cookie
                    HttpContext.Current.Response.Cookies.Remove(cookie.Name);
                    HttpContext.Current.Response.Cookies.Add(cookie);
                }
                // 设置Session值
                HttpContext.Current.Session[loginID]     = user.USER_ID;
                HttpContext.Current.Session[currentUser] = user;
                HttpContext.Current.Session[loginIP]     = CurrentUserIPAddress;
                switch ((GroupType)user.GROUP_ID)
                {
                case GroupType.Patient:
                    HttpContext.Current.Session[personInfoPage] = "Patient";
                    break;

                case GroupType.Doctor:
                    HttpContext.Current.Session[personInfoPage] = "Doctor";
                    break;

                case GroupType.SupeAdmin:
                case GroupType.WebAccendant:
                case GroupType.CodeAccendant:
                case GroupType.DataAccendant:
                default:
                    HttpContext.Current.Session[personInfoPage] = "Home";
                    break;
                }
                return(true);
            }
            return(false);
        }
        //Insert de un Contrato Arrto.
        //Devuelve el Folio de contrato
        public int InsertContratoArrto(ModeloNegocios.ContratoArrto objContratoArrto)
        {
            int FolioContrato = 0;

            System.Data.Entity.Core.Objects.ObjectParameter parametroFolioContrato = new System.Data.Entity.Core.Objects.ObjectParameter("FolioContrato", FolioContrato);

            using (ArrendamientoInmuebleEntities Conn = new ArrendamientoInmuebleEntities())
            {
                try
                {
                    Conn.spuInsertContratoArrto(
                        objContratoArrto.Fk_IdTipoContrato,      //1=Nac, 2=Ext u 3=OtrasFig
                        objContratoArrto.Fk_IdTipoArrendamiento, //Nuevo, Sust o Cont
                        objContratoArrto.Fk_IdTipoContratacion,  //Automatico, Dictamiando
                        objContratoArrto.Fk_IdInmuebleArrendamiento,
                        objContratoArrto.Fk_NumContratoHistorico,
                        objContratoArrto.Fk_IdContratoArrtoPadre,
                        objContratoArrto.Fk_IdTipoUsoInm,    //del BUS
                        objContratoArrto.OtroUsoInmueble,
                        objContratoArrto.Fk_IdTipoOcupacion, //Comodato, Prestamo, Conscesión (aplicable solo a Arrendamiento de Otras Fig.)
                        objContratoArrto.OtroTipoOcupacion,
                        objContratoArrto.Fk_IdTipoMoneda,
                        objContratoArrto.Fk_IdInstitucion,
                        objContratoArrto.NombreInstitucion,
                        objContratoArrto.FechaInicioOcupacion,
                        objContratoArrto.FechaFinOcupacion,
                        objContratoArrto.AreaOcupadaM2,
                        objContratoArrto.MontoPagoMensual,
                        objContratoArrto.MontoPagoPorCajonesEstacionamiento,
                        objContratoArrto.CuotaMantenimiento,
                        objContratoArrto.PtjeImpuesto,
                        objContratoArrto.FolioEmisionOpinion, //se define como atributo y no como objeto, porque solo se 1 dato: el Id
                        objContratoArrto.NumeroDictamenExcepcionFolioSMOI,
                        objContratoArrto.RIUF,
                        objContratoArrto.Observaciones,
                        objContratoArrto.PropietarioInmueble,
                        objContratoArrto.FuncionarioResponsable,
                        objContratoArrto.Fk_IdUsuarioRegistro,
                        objContratoArrto.CargoUsuarioRegistro,
                        //objetos de Persona Referencia
                        //titular del OIC
                        objContratoArrto.PersonaReferenciaTitularOIC.NombreCargo,
                        objContratoArrto.PersonaReferenciaTitularOIC.Nombre,
                        objContratoArrto.PersonaReferenciaTitularOIC.ApellidoPaterno,
                        objContratoArrto.PersonaReferenciaTitularOIC.ApellidoMaterno,
                        objContratoArrto.PersonaReferenciaTitularOIC.Email,
                        //Capturista
                        objContratoArrto.PersonaReferenciaCapturista.NombreCargo,
                        objContratoArrto.PersonaReferenciaCapturista.Nombre,
                        objContratoArrto.PersonaReferenciaCapturista.ApellidoPaterno,
                        objContratoArrto.PersonaReferenciaCapturista.ApellidoMaterno,
                        objContratoArrto.PersonaReferenciaCapturista.Email,
                        //Objeto de Justipreciacion
                        objContratoArrto.JustripreciacionContrato.Secuencial,
                        objContratoArrto.JustripreciacionContrato.SuperficieDictaminada,
                        objContratoArrto.JustripreciacionContrato.FechaDictamen,
                        objContratoArrto.JustripreciacionContrato.MontoDictaminado,
                        objContratoArrto.JustripreciacionContrato.EstatusAtencion,
                        objContratoArrto.JustripreciacionContrato.NoGenerico,
                        objContratoArrto.JustripreciacionContrato.UnidadMedidaSupRentableDictaminada,
                        // apartado de seguridad
                        objContratoArrto.CuentaConDictamen,
                        objContratoArrto.FechaDictamen,
                        //
                        objContratoArrto.CadenaOriginal,
                        objContratoArrto.SelloDigital,
                        objContratoArrto.QR,
                        parametroFolioContrato //parametro ouput
                        );

                    Conn.SaveChanges();

                    if (parametroFolioContrato == null)
                    {
                        throw new InvalidOperationException("No se pudo registrar el Contrato de Arrendamiento, vuelva a intentar o reporte a Sistemas");
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("InsertContratoArrto: {0}", ex.Message));
                }
            }//using

            if (parametroFolioContrato.Value != null)
            {
                FolioContrato = Convert.ToInt32(parametroFolioContrato.Value);
            }

            //parametro de retorno, regresa 0 si no hay insert, o el folio > 0 si se realizo el insert
            return(FolioContrato);
        }
        public virtual System.Data.Entity.Core.Objects.ObjectResult <p_GetJobs_Result> p_GetJobs(Nullable <System.Guid> pUserGUID, Nullable <int> pStatusCode, System.Data.Entity.Core.Objects.ObjectParameter pErrorCode)
        {
            var pUserGUIDParameter = pUserGUID.HasValue ?
                                     new System.Data.Entity.Core.Objects.ObjectParameter("pUserGUID", pUserGUID) :
                                     new System.Data.Entity.Core.Objects.ObjectParameter("pUserGUID", typeof(System.Guid));

            var pStatusCodeParameter = pStatusCode.HasValue ?
                                       new System.Data.Entity.Core.Objects.ObjectParameter("pStatusCode", pStatusCode) :
                                       new System.Data.Entity.Core.Objects.ObjectParameter("pStatusCode", typeof(int));

            return(((IObjectContextAdapter)this).ObjectContext.ExecuteFunction <p_GetJobs_Result>("p_GetJobs", pUserGUIDParameter, pStatusCodeParameter, pErrorCode));
        }
        public virtual System.Data.Entity.Core.Objects.ObjectResult <p_GetJobStatistics_Result> p_GetJobStatistics(Nullable <System.Guid> pUserGUID, Nullable <bool> pStatsForManager, string pUserType, Nullable <System.Guid> pRegionGUID, Nullable <System.Guid> pTerritoryGUID, Nullable <System.DateTime> pDate, System.Data.Entity.Core.Objects.ObjectParameter pErrorCode)
        {
            var pUserGUIDParameter = pUserGUID.HasValue ?
                                     new System.Data.Entity.Core.Objects.ObjectParameter("pUserGUID", pUserGUID) :
                                     new System.Data.Entity.Core.Objects.ObjectParameter("pUserGUID", typeof(System.Guid));

            var pStatsForManagerParameter = pStatsForManager.HasValue ?
                                            new System.Data.Entity.Core.Objects.ObjectParameter("pStatsForManager", pStatsForManager) :
                                            new System.Data.Entity.Core.Objects.ObjectParameter("pStatsForManager", typeof(bool));

            var pUserTypeParameter = pUserType != null ?
                                     new System.Data.Entity.Core.Objects.ObjectParameter("pUserType", pUserType) :
                                     new System.Data.Entity.Core.Objects.ObjectParameter("pUserType", typeof(string));

            var pRegionGUIDParameter = pRegionGUID.HasValue ?
                                       new System.Data.Entity.Core.Objects.ObjectParameter("pRegionGUID", pRegionGUID) :
                                       new System.Data.Entity.Core.Objects.ObjectParameter("pRegionGUID", typeof(System.Guid));

            var pTerritoryGUIDParameter = pTerritoryGUID.HasValue ?
                                          new System.Data.Entity.Core.Objects.ObjectParameter("pTerritoryGUID", pTerritoryGUID) :
                                          new System.Data.Entity.Core.Objects.ObjectParameter("pTerritoryGUID", typeof(System.Guid));

            var pDateParameter = pDate.HasValue ?
                                 new System.Data.Entity.Core.Objects.ObjectParameter("pDate", pDate) :
                                 new System.Data.Entity.Core.Objects.ObjectParameter("pDate", typeof(System.DateTime));

            return(((IObjectContextAdapter)this).ObjectContext.ExecuteFunction <p_GetJobStatistics_Result>("p_GetJobStatistics", pUserGUIDParameter, pStatsForManagerParameter, pUserTypeParameter, pRegionGUIDParameter, pTerritoryGUIDParameter, pDateParameter, pErrorCode));
        }
        public ActionResult Definitivo(List <string> acquisti)
        {
            try
            {
                foreach (string acquisto in acquisti)
                {
                    //string token = acquisto.Trim().Substring(3, acquisto.Trim().Length - 6);
                    int idOfferta = Utils.DecodeToInt(acquisto.Trim().Substring(3, acquisto.Trim().Length - 6));
                    using (DatabaseContext db = new DatabaseContext())
                    {
                        PersonaModel utente = Session["utente"] as PersonaModel;
                        System.Data.Entity.Core.Objects.ObjectParameter errore = new System.Data.Entity.Core.Objects.ObjectParameter("Errore", typeof(ErrorePagamento));
                        errore.Value = ErrorePagamento.Nessuno;
                        Guid portaleWeb = Guid.Parse(System.Configuration.ConfigurationManager.AppSettings["portaleweb"]);

                        // DEVO CAMBIARE E FARMI TORNARE IL TRANSAZIONE EFFETTUATO
                        int?idPagamento = db.BENE_SAVE_PAGAMENTO(idOfferta, utente.Persona.ID_CONTO_CORRENTE, errore).FirstOrDefault();
                        if ((ErrorePagamento)errore.Value != ErrorePagamento.Nessuno)
                        {
                            return(Json(errore.Value.ToString()));
                        }
                        if (idPagamento == null)
                        {
                            return(Json(Language.ErrorPayment));
                        }

                        TRANSAZIONE pagamento = db.TRANSAZIONE.Include("CONTO_CORRENTE.PERSONA.PERSONA_EMAIL").Where(p => p.ID == idPagamento).SingleOrDefault();
                        // aggiorno punti attuali utente
                        Session["utente"] = new PersonaModel(db.PERSONA.Where(u => u.ID == utente.Persona.ID).FirstOrDefault());
                        PERSONA venditore = pagamento.CONTO_CORRENTE.PERSONA.SingleOrDefault();
                        // impostare invio email pagamento effettuato
                        EmailModel email = new EmailModel(ControllerContext);
                        email.To.Add(new System.Net.Mail.MailAddress(venditore.PERSONA_EMAIL.SingleOrDefault(e => e.TIPO == (int)TipoEmail.Registrazione).EMAIL));
                        string nominativo = (Session["utente"] as PersonaModel).Persona.NOME + " " + (Session["utente"] as PersonaModel).Persona.COGNOME;
                        email.Subject   = String.Format(Email.PaymentSubject, pagamento.NOME, nominativo) + " - " + WebConfigurationManager.AppSettings["nomeSito"];
                        email.Body      = "Pagamento";
                        email.DatiEmail = new SchedaPagamentoViewModel()
                        {
                            Nome       = pagamento.NOME,
                            Compratore = nominativo,
                            Venditore  = venditore.NOME + " " + venditore.COGNOME,
                            Punti      = (int)pagamento.PUNTI,
                            Soldi      = (int)pagamento.SOLDI,
                            Data       = pagamento.DATA_INSERIMENTO,
                        };
                        new EmailController().SendEmail(email);

                        return(Json(new { Messaggio = Language.CompletedPurchase }));
                    }
                }
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                // log errore, invio mail
                Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
                return(Json(ex.ToString()));
            }
            Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
            return(Json(Language.ErrorPayment));
        }
Exemple #18
0
        public static List<esp_Proizvodi_SelectByVrstaNaziv_Result> SelectByVrstaNaziv(int vrstaId, string naziv, int offset, int maxRows)
        {
            System.Data.Entity.Core.Objects.ObjectParameter total = new System.Data.Entity.Core.Objects.ObjectParameter("TotalRows", 0);
            List<esp_Proizvodi_SelectByVrstaNaziv_Result> proizvodi = Connection.dm.esp_Proizvodi_SelectByVrstaNaziv(vrstaId, naziv, offset, maxRows, total).ToList();

            TotalRows = Convert.ToInt32(total.Value);

            return proizvodi;
        }
Exemple #19
0
        public ActionResult IndexA()
        {
            if (Request.IsAuthenticated)
            {
                //Si no ets autenticat, ves a la home.
                var     context = new ExpensesEF.Entities();
                var     model   = new HomeViewModels();
                string  _IdUser;
                decimal sueldoactual;

                _IdUser = context.AspNetUsers.Where(x => x.Email == User.Identity.Name).FirstOrDefault().Id.ToString();
                System.Data.Entity.Core.Objects.ObjectParameter myExpensesThisMonth     = new System.Data.Entity.Core.Objects.ObjectParameter("RetMont", typeof(Decimal));
                System.Data.Entity.Core.Objects.ObjectParameter myExpensesLastMonth     = new System.Data.Entity.Core.Objects.ObjectParameter("RetMontPrevious", typeof(Decimal));
                System.Data.Entity.Core.Objects.ObjectParameter myExpensesThisMonthCard = new System.Data.Entity.Core.Objects.ObjectParameter("RetCurrentCard", typeof(Decimal));
                System.Data.Entity.Core.Objects.ObjectParameter myExpensesThisMonthIncludingNonComputables = new System.Data.Entity.Core.Objects.ObjectParameter("RetMontIncludingComputables", typeof(Decimal));

                context.spGetMonthlyExpenses(context.AspNetUsers.Where(x => x.Id == _IdUser).FirstOrDefault().Id.ToString(), DateTime.Now.Month, DateTime.Now.Year, myExpensesThisMonth, myExpensesLastMonth, myExpensesThisMonthCard, myExpensesThisMonthIncludingNonComputables);

                if (String.IsNullOrEmpty(myExpensesThisMonth.Value.ToString()))
                {
                    model.TotalGastoMensual = 0;
                }
                else
                {
                    model.TotalGastoMensual = Math.Round(Convert.ToDecimal(myExpensesThisMonth.Value.ToString()), 2);
                }

                if (String.IsNullOrEmpty(myExpensesThisMonth.Value.ToString()))
                {
                    model.TotalGastoMensualIncludingNonComputables = 0;
                }
                else
                {
                    model.TotalGastoMensualIncludingNonComputables = Math.Round(Convert.ToDecimal(myExpensesThisMonthIncludingNonComputables.Value.ToString()), 2);
                }



                if (String.IsNullOrEmpty(myExpensesLastMonth.Value.ToString()))
                {
                    model.TotalGastoMensualMesAnterior = 0;
                }
                else
                {
                    model.TotalGastoMensualMesAnterior = Math.Round(Convert.ToDecimal(myExpensesLastMonth.Value.ToString()), 2);
                }

                if (String.IsNullOrEmpty(myExpensesThisMonthCard.Value.ToString()))
                {
                    model.TotalGastoMensualTarjeta = 0;
                }
                else
                {
                    model.TotalGastoMensualTarjeta = Math.Round(Convert.ToDecimal(myExpensesThisMonthCard.Value.ToString()), 2);
                }


                if (String.IsNullOrEmpty(myExpensesThisMonth.Value.ToString()) || (String.IsNullOrEmpty(myExpensesLastMonth.Value.ToString())))
                {
                    model.tpcRespectoMesAnterior = 0;
                }
                else
                {
                    model.tpcRespectoMesAnterior = Math.Round((Math.Round(Convert.ToDecimal(myExpensesThisMonth.Value.ToString()), 2) / Math.Round(Convert.ToDecimal(myExpensesLastMonth.Value.ToString()), 2)) * 100);
                }


                model.EnabletpcRespectoMesAnterior = context.AspNetUsers.Where(u => u.Id == _IdUser).FirstOrDefault().VerTpcGastovsMesAnterior.GetValueOrDefault();


                model.SueldoPrevisto         = _getSueldoActual(context, _IdUser);
                model.AhorroPrevisoMesActual = (model.SueldoPrevisto > 0 ? model.SueldoPrevisto - model.TotalGastoMensualIncludingNonComputables : 0);

                if (Request.Browser.IsMobileDevice == true)
                {
                    model.isMobile = true;
                }


                return(View(model));
            }

            else
            {
                return(RedirectToAction("Index", "Home"));
            }
        }
        public ActionResult AllMem(int? page, membsrebySearching mm)
        {
            int currentPageIndex = page.HasValue ? page.Value : 1;

            System.Data.Entity.Core.Objects.ObjectParameter Count = new System.Data.Entity.Core.Objects.ObjectParameter("Count", typeof(int));
            string searchData = "";
            string criteria = "";
            string bydate = "";
            if(!string.IsNullOrEmpty(mm.searchText) )
            {
                searchData = " And ( .fname like '%" + mm.searchText + "' OR mems.lname like '%" + mm.searchText + "' OR mems.aboutme like '%" + mm.searchText + "')";
            }
            if(!string.IsNullOrEmpty(mm.byday))
            {
                if(mm.byday == "Today")
                {
                    bydate = " And convert(date,mems.regdate) = convert(date,getdate())";
                }
                else if (mm.byday == "Yesterday")
                {
                    bydate = " And convert(date,mems.regdate) = convert(date,getdate()-1)";
                }
                else if (mm.byday == "LastWeek")
                {
                    bydate = " And convert(date,mems.regdate) between convert(date,getdate()-7) and convert(date,getdate())";
                }
            }

            criteria = "mems.Susp= 'N' " + bydate + searchData;
            mm.data = db.memberbySearch(currentPageIndex, defaultPageSize, criteria , Count).ToList();

            mm.TotalCount =Convert.ToInt64(Count.Value);

            mm.pagesize = defaultPageSize;

            return PartialView(mm);

        }
Exemple #21
0
        public static void Save(Evento item)
        {
            // si necesitamos que un procedure devuelva el valor de un id hacemos esto
            //https://social.msdn.microsoft.com/Forums/en-US/5e56547d-75f0-4688-8069-8328de24f332/error-when-calling-a-stored-procedure?forum=adodotnetentityframework
            // si no sabemos como activar la ventana  del link de arriba checamos esto
            //http://stackoverflow.com/questions/3729920/cant-find-ado-net-entity-model-browser-window-in-vs2010

            TransactionOptions options = new TransactionOptions();

            options.IsolationLevel = IsolationLevel.ReadCommitted;
            options.Timeout        = new TimeSpan(0, 5, 0);
            try
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
                {
                    System.Data.Entity.Core.Objects.ObjectParameter EventoId = new System.Data.Entity.Core.Objects.ObjectParameter("EventoId", item.EventoId);
                    using (var db = new Entities(ConnectionStringHelper.ConnectionString()))
                    {
                        try
                        {
                            db.st_InsEvento(EventoId,
                                            item.Titulo,
                                            item.Imagen,
                                            item.FechaEvento,
                                            item.Direccion,
                                            item.Establecimiento,
                                            item.PrecioRegular,
                                            item.Promocion,
                                            item.Preventa,
                                            item.EventoTipo.EventoTipoId,
                                            item.Ciudad.CiudadId,
                                            item.Latitud,
                                            item.Longitud,
                                            item.LinkEventoFacebook,
                                            item.LinkComprarBoleto,
                                            item.Estatus,
                                            item.Perfil.PerfilId
                                            );

                            int eventoid = (item.EventoId > 0) ? item.EventoId : Convert.ToInt32(EventoId.Value);

                            //TRABAJADMOS CON EVENTOPERFIL
                            //eliminamos los tags de EventoPerfil que tenga asignado

                            if (item.lPerfil != null)
                            {
                                if (item.lPerfil.Count > 0)
                                {
                                    //eliminamos las bandas que este evento tenga asignado

                                    db.st_DelEventoPerfil(eventoid, 3);

                                    foreach (Perfil EP in item.lPerfil)
                                    {
                                        // validamos si la banda existe en la lista de perfil
                                        var banda = db.Perfil.Where(x => x.Nombre == EP.Nombre && x.PerfilTipoId == 2).FirstOrDefault();
                                        // si existe entonces insertamos normalmente
                                        if (banda != null)
                                        {
                                            // podemos corregir en el sp que no tome el nombre si no que del resultado de linq
                                            //asignamos el id (banda.perfilId)
                                            db.st_InsEventoPerfil(eventoid,
                                                                  EP.Nombre);
                                        }
                                        //si no existe significa que burlaron el jquery y no debemos insertar.
                                    }
                                }
                            }

                            // TRABAJAMOS CON EVENTOTAG

                            if (item.lTag != null)
                            {
                                if (item.lTag.Count > 0)
                                {
                                    //eliminamos los tags que este evento tenga asignado
                                    db.st_DelEventoTag(eventoid, 3);

                                    foreach (Tag ET in item.lTag)
                                    {
                                        // validamos si el tag existe en la lista de tags
                                        var tag = db.Tag.Where(x => x.Nombre == ET.Nombre).FirstOrDefault();
                                        //si no existe entonces significa que es un tag nuevo lo insertamos en la tabla tags
                                        if (tag == null)
                                        {
                                            TagDAO.Save(ET);
                                            //System.Data.Entity.Core.Objects.ObjectParameter TagId = new System.Data.Entity.Core.Objects.ObjectParameter("TagId", ET.TagId);
                                            //db.st_InsEventoTag(eventoid, ET.Nombre);
                                        }
                                        db.st_InsEventoTag(eventoid, ET.Nombre);
                                        //// si existe entonces significa que el tag existe y solo insertamos la relacion
                                        //else
                                        //{
                                        //    //System.Data.Entity.Core.Objects.ObjectParameter TagId = new System.Data.Entity.Core.Objects.ObjectParameter("TagId", ET.TagId);
                                        //    db.st_InsEventoTag(eventoid, ET.Nombre);
                                        //}
                                    }
                                }
                            }

                            // TRABAJAMOS CON EVENTOVIDEO

                            if (item.lEventoVideo != null)
                            {
                                if (item.lEventoVideo.Count > 0)
                                {
                                    //eliminamos los videos que este evento tenga asignado
                                    db.st_DelEventoVideo(eventoid, 3);

                                    foreach (EventoVideo EV in item.lEventoVideo)
                                    {
                                        if (!String.IsNullOrWhiteSpace(EV.UrlVideo))
                                        {
                                            string urlformato = getUrlEmbed(EV.UrlVideo);
                                            if (!String.IsNullOrWhiteSpace(urlformato))
                                            {
                                                db.st_InsEventoVideo(eventoid, urlformato);
                                            }
                                        }
                                    }
                                }
                            }
                            scope.Complete();
                        }
                        catch (Exception ex)
                        {
                            scope.Dispose();
                            throw ex;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
        //[HttpPost]
        //[ValidateAntiForgeryToken]
        //public async Task<ActionResult> GetVehiculo( String placa)
        //(Nullable<decimal> monto, Nullable<System.DateTime> fecha, Nullable<int> idTipoVenta, Nullable<int> idCliente, Nullable<decimal> saldo,
        //string placa, Nullable<decimal> interes, Nullable<short> plazo, Nullable<int> idPeriodoPago, string descripcion)
        public async Task <Boolean> InsertarVentaFinanciamiento(string pmonto, string pfecha, string pidTipoVenta, string pidCliente, string psaldo,
                                                                string pplaca, string pinteres, string pplazo)
        {
            //if (placa == null)
            //{
            //    // return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            //    return false;
            //}
            bool inserto = false;

            try
            {
                Decimal  monto       = Convert.ToDecimal(pmonto);
                DateTime fecha       = Convert.ToDateTime(pfecha);
                int      idTipoVenta = Convert.ToInt32(pidTipoVenta);
                int      idCliente   = Convert.ToInt32(pidCliente);

                if (idTipoVenta == 2)
                {//financiamiento
                    if (pplazo != null)
                    {
                        if (pplazo != string.Empty)
                        {
                            pplazo = pplazo.Substring(0, pplazo.IndexOf(" Meses"));
                        }
                    }
                    Decimal saldo   = Convert.ToDecimal(psaldo);
                    Decimal interes = Convert.ToDecimal(pinteres);
                    Int16   plazo   = Convert.ToInt16(pplazo);
                    System.Data.Entity.Core.Objects.ObjectParameter returnId = new System.Data.Entity.Core.Objects.ObjectParameter("idVenta", typeof(int)); //Create Object parameter to receive a output value.It will behave like output parameter

                    int venta = db.InsertarVentaFinanciamiento(monto, fecha, idTipoVenta, idCliente, saldo, pplaca, interes, plazo, 1, " ", returnId);
                    if (int.Parse(returnId.Value.ToString()) > 0)
                    {
                        //RedirectToAction("Index");
                        inserto = true;
                        // return true;
                    }
                }
                else
                {// contado
                    TVenta tVenta = new TVenta();
                    tVenta.Monto       = Convert.ToDecimal(pmonto);
                    tVenta.Fecha       = Convert.ToDateTime(pfecha);
                    tVenta.IdTipoVenta = Convert.ToInt32(pidTipoVenta);
                    tVenta.IdCliente   = Convert.ToInt32(pidCliente);
                    tVenta.Placa       = pplaca;
                    tVenta.Saldo       = tVenta.Monto;

                    db.TVenta.Add(tVenta);
                    await db.SaveChangesAsync();

                    RedirectToAction("Index");
                    inserto = true;
                    //return true;

                    //revisar que el web config este seteado con el mismo idtipofinanciamiento de la BD tabla ctipoVenta (2)
                    //if (tVenta.IdTipoVenta == Int32.Parse(WebConfigurationManager.AppSettings["TipoVentaFinanciamiento"]))
                    //    return RedirectToAction("Create", "Financiamientos", new { idVenta = tVenta.IdVenta });
                }
            }
            catch (Exception e) {
                return(false);
            }

            RedirectToAction("Index");

            return(inserto);
        }
Exemple #23
0
        private int GuardarRegistro()
        {
            int           PK_Paciente = 0;
            DatosInternos ca_paciente = new DatosInternos();

            DateTime FE_Nacimiento  = Convert.ToDateTime(this.txtNacimiento.Text);
            int      FK_Centro      = this.m_PK_Centro;
            int      FK_GrupoEtnico = Convert.ToInt32(this.ddlGrupoEtnico.SelectedValue);
            string   NR_Expediente  = this.txtExpediente.Text;
            int      FK_Genero      = Convert.ToInt32(this.ddlGenero.SelectedValue);

            PK_Sesion = Session["PK_Sesion"].ToString();

            System.Data.Entity.Core.Objects.ObjectParameter myOutputParamString = new System.Data.Entity.Core.Objects.ObjectParameter("PK_Paciente", typeof(int));

            try
            {
                using (CARAEntities dsCARA = new CARAEntities())
                {
                    var spc = dsCARA.SPC_PACIENTE(FE_Nacimiento, FK_Centro, FK_GrupoEtnico, NR_Expediente, FK_Genero, myOutputParamString);

                    PK_Paciente = Convert.ToInt32(myOutputParamString.Value);

                    dsCARA.SPC_SESION_ACTIVIDAD(PK_Sesion, "Paciente", "C", null, FK_Centro, null, null);

                    this.lblIUP.Text = PK_Paciente.ToString();

                    ca_paciente = new DatosInternos()
                    {
                        PK_Paciente    = PK_Paciente,
                        FK_Centro      = FK_Centro,
                        FE_Nacimiento  = FE_Nacimiento,
                        FK_GrupoEtnico = FK_GrupoEtnico,
                        DE_GrupoEtnico = this.ddlGrupoEtnico.SelectedItem.Text,
                        NR_Expediente  = NR_Expediente,
                        FK_Genero      = FK_Genero,
                        DE_Genero      = this.ddlGenero.SelectedItem.Text
                    };



                    foreach (ListItem item in lbxRaza.Items)
                    {
                        if (item.Selected)
                        {
                            dsCARA.SPC_RAZA_PACIENTE(PK_Paciente, Convert.ToInt32(item.Value));
                        }
                    }

                    Session["CA_Paciente"] = ca_paciente;
                }
            }
            catch (Exception ex)
            {
                string mensaje;

                if (ex.InnerException == null)
                {
                    mensaje = ex.Message;
                }
                else
                {
                    mensaje = ex.InnerException.Message;
                }

                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Error ", "sweetAlert('Error','" + mensaje + "','error')", true);
            }

            return(PK_Paciente);
        }