Ejemplo n.º 1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            username.Text = "Hello, " + (String)Session["Email"] + "! This is your ordered tickets";
            // tab info
            TicketServiceRef.Service1Client client = new TicketServiceRef.Service1Client();
            string userId  = (string)Session["Email"];
            string tickets = client.getUserTicket(userId);

            string[] ticketArray = tickets.Split(';');

            if (ticketArray.Length > 0)
            {
                table_info.Visible = true;
            }
            else
            {
                table_info.Visible = false;
            }

            for (int i = 0; i < ticketArray.Length; i++)
            {
                if (ticketArray[i] == String.Empty)
                {
                    break;
                }

                TableRow row          = new TableRow();
                String   attraction   = ticketArray[i].Split('|')[1];
                String   verification = ticketArray[i].Split('|')[2];

                TableCell cell_attraction = new TableCell();
                Label     lab_attraction  = new Label();
                lab_attraction.Text = attraction;
                cell_attraction.Controls.Add(lab_attraction);
                row.Cells.Add(cell_attraction);

                TableCell cell_verification = new TableCell();
                Label     lab_verification  = new Label();
                lab_verification.Text = verification;
                cell_verification.Controls.Add(lab_verification);
                row.Cells.Add(cell_verification);

                table_info.Rows.Add(row);
            }

            // tab spots
            haishengService = new HaishengServiceRef.Service1Client();

            String         json    = haishengService.getSpots();
            SpotRootObject rootObj = JsonConvert.DeserializeObject <SpotRootObject>(json);

            list = rootObj.list;

            for (int i = 0; i < list.Count; i++)
            {
                System.Drawing.Image img = System.Drawing.Image.FromStream(new MemoryStream(list[i].imgBytes));
                //System.Drawing.Image img = System.Drawing.Image.FromStream(new MemoryStream(Encoding.UTF8.GetBytes(list[i].imgStr)));
                int imgHeight = img.Height;
                int imgWidth  = img.Width;

                System.Drawing.Image.GetThumbnailImageAbort dCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
                System.Drawing.Image thumbnailImg = img.GetThumbnailImage(imgWidth, imgHeight, dCallBack, IntPtr.Zero);
                String imgFile = list[i].name + ".jpg";
                thumbnailImg.Save(Path.Combine(HttpContext.Current.Server.MapPath("../ImgCache/"), imgFile), ImageFormat.Jpeg);
                thumbnailImg.Dispose();
            }

            if (!IsPostBack)
            {
                bindList();
            }
        }
Ejemplo n.º 2
0
 public Image ResizeImage(Image origImg, int width, int maxHeight)
 {
     int newHeight = origImg.Height * width / origImg.Width;
     if (newHeight > maxHeight)
     {
         width = origImg.Width * maxHeight / origImg.Height;
         newHeight = maxHeight;
     }
     Image newImg = origImg.GetThumbnailImage(width, newHeight, null, IntPtr.Zero);
     origImg.Dispose();
     return newImg;
 }
Ejemplo n.º 3
0
        public async Task <ActionResult <UserToken> > Create([FromBody] Reclamacao reclamacao)
        {
            //var usuario = await _usuarioRepositorio.PegarUsuarioPeloEmail(reclamacao.Usuario.Email);
            //PasswordHasher<Usuario> passwordHasher = new PasswordHasher<Usuario>();

            //var result = await ApiUsuariosController_signInManager.PasswordSignInAsync(reclamacao.Usuario.UserName, reclamacao.Usuario.PasswordHash,
            // isPersistent: false, lockoutOnFailure: false);

            LoginViewModel login = new LoginViewModel();

            login.Email = reclamacao.Usuario.Email.ToLower();
            login.Senha = reclamacao.Usuario.PasswordHash;

            var usuario = await _usuarioRepositorio.PegarUsuarioPeloEmail(login.Email);


            //PasswordHasher<Usuario> passwordHasher = new PasswordHasher<Usuario>();

            int result = await _apiUsuarios.LoginInterno(login);

            if (result == 0)
            {
                return(View(reclamacao));
            }


            // await _signInManager.PasswordSignInAsync(usuario.UserName, login.Senha,
            //isPersistent: false, lockoutOnFailure: false);

            //await BuildToken(login);


            if (ModelState.IsValid && usuario != null)
            {
                string endereco = "";
                string numero   = "";
                string bairro   = "";
                string cidade   = "";
                string estado   = "";
                string cep      = "";
                string img      = "";

                //
                try
                {
                    HttpClient client   = new HttpClient();
                    var        response = await client.GetStringAsync("https://maps.googleapis.com/maps/api/geocode/json?latlng=" + reclamacao.Latitude + "," + reclamacao.Longitude + "&key=AIzaSyCZWaCsDUe9eZwKkuz5Zzr4l5_k1iERHwY");

                    //var response = await client.GetStringAsync("https://maps.googleapis.com/maps/api/geocode/json?latlng=-21.2716850,-48.4966450&key=AIzaSyCZWaCsDUe9eZwKkuz5Zzr4l5_k1iERHwY");
                    //var endereco = JsonConvert.DeserializeObject(response);
                    //var json_serializer = new JavaScriptSerializer();
                    //var routes_list = (IDictionary<string, object>)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");
                    //Console.WriteLine(routes_list["test"]);
                    //var item = JsonConvert.DeserializeObject<object>(response);


                    ApiGeocoding end = new ApiGeocoding();

                    ApiGeocoding item = JsonConvert.DeserializeObject <ApiGeocoding>(response);



                    //var teste = JsonConvert.DeserializeObject <String> ( item["results"].ToString());

                    //object teste2 = teste["formatted_address"];

                    //var item2 = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(colecao.ToString());


                    //var colecao = item.Where(d => d.Key == "results").Select(d => d.Value);



                    //var colecao2 = colecao.Where(e => e.Key == "address_components").Select(e => e.Value);



                    //string teste = item["formatted_address"];


                    //var item2 = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(item.ToString());

                    numero   = item.results[0].address_components[0].long_name.ToString();  //numero
                    endereco = item.results[0].address_components[1].long_name.ToString();  //endereco
                    bairro   = item.results[0].address_components[2].long_name.ToString();  //bairro
                    cidade   = item.results[0].address_components[3].long_name.ToString();  //cidade
                    estado   = item.results[0].address_components[4].short_name.ToString(); //estado
                    item.results[0].address_components[5].long_name.ToString();             //pais
                    cep = item.results[0].address_components[6].long_name.ToString();       //cep



                    byte[] bytes = Convert.FromBase64String(reclamacao.Imagem);

                    using (MemoryStream myMemStream = new MemoryStream(bytes))
                    {
                        System.Drawing.Image fullsizeImage = System.Drawing.Image.FromStream(myMemStream);

                        var width = 800;

                        var height = 800;
                        System.Drawing.Image newImage = fullsizeImage.GetThumbnailImage(width, height, null, IntPtr.Zero);

                        using (var mst = new MemoryStream())
                        {
                            newImage.Save(mst, System.Drawing.Imaging.ImageFormat.Png);
                            bytes = mst.ToArray();
                        }



                        //bytes = newImage.to

                        using (var myResult = new MemoryStream())
                        {
                            //newImage.Save(myResult, System.Drawing.Imaging.ImageFormat.Png);

                            //string arqImg = "../DenuncieSpam/wwwroot/images/incidentes/" + System.Guid.NewGuid() + ".png";
                            string arqImg = _appEnvironment.WebRootPath + Path.DirectorySeparatorChar + "images" + Path.DirectorySeparatorChar + "incidentes" + Path.DirectorySeparatorChar + System.Guid.NewGuid().ToString() + ".png"; //"/images/incidentes/" + System.Guid.NewGuid() + ".png";

                            while (System.IO.File.Exists(arqImg))
                            {
                                //arqImg = "../DenuncieSpam/wwwroot/images/incidentes/" + System.Guid.NewGuid() + ".png";
                                arqImg = _appEnvironment.WebRootPath + Path.DirectorySeparatorChar + "images" + Path.DirectorySeparatorChar + "incidentes" + Path.DirectorySeparatorChar + System.Guid.NewGuid().ToString() + ".png";
                                //arqImg = "/images/incidentes/" + System.Guid.NewGuid() + ".png";
                            }

                            System.IO.File.WriteAllBytes(arqImg, bytes);

                            reclamacao.Imagem = arqImg;
                        }
                    }


                    //System.IO.Directory.GetFiles("../DenuncieSpam/wwwroot/images/incidentes/System.Guid.NewGuid().png");
                }
                catch (Exception ex)
                {
                }
                reclamacao.Endereco = endereco + ", " + numero + ", " + bairro + ", " + cidade + ", " + estado + ", " + cep;

                reclamacao.Data      = DateTime.Now;
                reclamacao.Telefone  = usuario.Telefone;
                reclamacao.Email     = usuario.Email;
                reclamacao.IdUsuario = usuario.Id;
                await _reclamacaoRepositorio.Inserir(reclamacao);

                _logger.LogInformation("Nova Reclamacao cadastrada");
            }

            _logger.LogError("Erro no cadastro de reclamacao");
            return(View(reclamacao));
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 制作图片的缩略图
        /// </summary>
        /// <param name="originalImage">原图</param>
        /// <param name="width">缩略图的宽(像素)</param>
        /// <param name="height">缩略图的高(像素)</param>
        /// <param name="mode">缩略方式</param>
        /// <returns>缩略图</returns>
        /// <remarks>
        ///        <paramref name="mode"/>:
        ///            <para>HW:指定的高宽缩放(可能变形)</para>
        ///            <para>HWO:指定高宽缩放(可能变形)(过小则不变)</para>
        ///            <para>W:指定宽,高按比例</para>
        ///            <para>WO:指定宽(过小则不变),高按比例</para>
        ///            <para>H:指定高,宽按比例</para>
        ///            <para>HO:指定高(过小则不变),宽按比例</para>
        ///            <para>CUT:指定高宽裁减(不变形)</para>
        /// </remarks>
        public static System.Drawing.Image MakeThumbnail(this System.Drawing.Image originalImage, int width, int height, ThumbnailMode mode)
        {
            int towidth  = width;
            int toheight = height;

            int x  = 0;
            int y  = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;


            switch (mode)
            {
            case ThumbnailMode.UsrHeightWidth:     //指定高宽缩放(可能变形)
                break;

            case ThumbnailMode.UsrHeightWidthBound:     //指定高宽缩放(可能变形)(过小则不变)
                if (originalImage.Width <= width && originalImage.Height <= height)
                {
                    return(originalImage);
                }
                if (originalImage.Width < width)
                {
                    towidth = originalImage.Width;
                }
                if (originalImage.Height < height)
                {
                    toheight = originalImage.Height;
                }
                break;

            case ThumbnailMode.UsrWidth:     //指定宽,高按比例
                toheight = originalImage.Height * width / originalImage.Width;
                break;

            case ThumbnailMode.UsrWidthBound:     //指定宽(过小则不变),高按比例
                if (originalImage.Width <= width)
                {
                    return(originalImage);
                }
                else
                {
                    toheight = originalImage.Height * width / originalImage.Width;
                }
                break;

            case ThumbnailMode.UsrHeight:     //指定高,宽按比例
                towidth = originalImage.Width * height / originalImage.Height;
                break;

            case ThumbnailMode.UsrHeightBound:     //指定高(过小则不变),宽按比例
                if (originalImage.Height <= height)
                {
                    return(originalImage);
                }
                else
                {
                    towidth = originalImage.Width * height / originalImage.Height;
                }
                break;

            case ThumbnailMode.Cut:     //指定高宽裁减(不变形)
                if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                {
                    oh = originalImage.Height;
                    ow = originalImage.Height * towidth / toheight;
                    y  = 0;
                    x  = (originalImage.Width - ow) / 2;
                }
                else
                {
                    ow = originalImage.Width;
                    oh = originalImage.Width * height / towidth;
                    x  = 0;
                    y  = (originalImage.Height - oh) / 2;
                }
                break;

            default:
                break;
            }

            return(originalImage.GetThumbnailImage(towidth, toheight, null, IntPtr.Zero));
        }
Ejemplo n.º 5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Guid id     = Guid.Empty;
                Guid newsid = Guid.Empty;
                if (!String.IsNullOrEmpty(Request.Params["ID"]))
                {
                    id = new Guid(Request.Params["ID"]);
                }
                else if (Request["newsletterid"] != null)
                {
                    if (!String.IsNullOrEmpty(Request.Params["newsletterid"]))
                    {
                        newsid = new Guid(Request.Params["newsletterid"]);
                    }
                    Newsletter imageNews = new Newsletter();

                    imageNews            = Newsletter.Load(newsid);
                    Response.ContentType = "image/jpeg";
                    if (imageNews != null && imageNews.Image != null)
                    {
                        MemoryStream ms = new MemoryStream(imageNews.Image);
                        // create an image object, using the filename we just retrieved
                        System.Drawing.Image imageOriginal = System.Drawing.Image.FromStream(ms);

                        // create the actual thumbnail image
                        System.Drawing.Image thumbnailImage = imageOriginal.GetThumbnailImage(171, 116, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

                        // make a memory stream to work with the image bytes
                        MemoryStream imageStream = new MemoryStream();

                        // put the image into the memory stream
                        thumbnailImage.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg);

                        // make byte array the same size as the image
                        byte[] imageContent = new Byte[imageStream.Length];

                        // rewind the memory stream
                        imageStream.Position = 0;

                        // load the byte array with the image
                        imageStream.Read(imageContent, 0, (int)imageStream.Length);

                        // return byte array to caller with image type
                        Response.ContentType = "image/jpeg";
                        Response.BinaryWrite(imageContent);

                        //Response.BinaryWrite(img.Thumbnail);
                        ms.Dispose();
                        imageStream.Dispose();
                    }
                    else
                    {
                        Response.WriteFile("~/images/EmptyImage.png");
                    }
                }
                PropertyImage image = new PropertyImage();
                image.Id = id;
                if (Request["banner"] != null)
                {
                    image = image.GetByIdbanner();
                }
                else
                {
                    image = image.GetById();
                }
                Response.ContentType = "image/jpeg";
                if (image == null)
                {
                    Response.WriteFile("~/images/EmptyImage.png");
                }
                //else if (string.IsNullOrEmpty(Request["big"]))
                //{
                //    MemoryStream ms = new MemoryStream(image.Image);
                //    // create an image object, using the filename we just retrieved
                //    System.Drawing.Image imageOriginal = System.Drawing.Image.FromStream(ms);

                //    // create the actual thumbnail image
                //    System.Drawing.Image thumbnailImage = imageOriginal.GetThumbnailImage(171, 116, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

                //    // make a memory stream to work with the image bytes
                //    MemoryStream imageStream = new MemoryStream();

                //    // put the image into the memory stream
                //    thumbnailImage.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg);

                //    // make byte array the same size as the image
                //    byte[] imageContent = new Byte[imageStream.Length];

                //    // rewind the memory stream
                //    imageStream.Position = 0;

                //    // load the byte array with the image
                //    imageStream.Read(imageContent, 0, (int)imageStream.Length);

                //    // return byte array to caller with image type
                //    Response.ContentType = "image/jpeg";
                //    Response.BinaryWrite(imageContent);

                //    //Response.BinaryWrite(img.Thumbnail);
                //    ms.Dispose();
                //    imageStream.Dispose();

                //}
                else if (!string.IsNullOrEmpty(Request["med"]))
                {
                    //GetFullImage(image);
                    //return;
                    MemoryStream ms = new MemoryStream(image.Image);
                    // create an image object, using the filename we just retrieved
                    System.Drawing.Image imageOriginal = System.Drawing.Image.FromStream(ms);

                    // create the actual thumbnail image
                    System.Drawing.Image thumbnailImage = imageOriginal.GetThumbnailImage(600, 404, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

                    // make a memory stream to work with the image bytes
                    MemoryStream imageStream = new MemoryStream();

                    // put the image into the memory stream
                    thumbnailImage.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg);

                    // make byte array the same size as the image
                    byte[] imageContent = new Byte[imageStream.Length];

                    // rewind the memory stream
                    imageStream.Position = 0;

                    // load the byte array with the image
                    imageStream.Read(imageContent, 0, (int)imageStream.Length);

                    // return byte array to caller with image type
                    Response.ContentType = "image/jpeg";
                    Response.BinaryWrite(imageContent);

                    //Response.BinaryWrite(img.Thumbnail);
                    ms.Dispose();
                    imageStream.Dispose();
                }
                else if (!string.IsNullOrEmpty(Request["small"]))
                {
                    //GetFullImage(image);
                    //return;
                    MemoryStream ms = new MemoryStream(image.Image);
                    // create an image object, using the filename we just retrieved
                    System.Drawing.Image imageOriginal = System.Drawing.Image.FromStream(ms);

                    // create the actual thumbnail image
                    System.Drawing.Image thumbnailImage = imageOriginal.GetThumbnailImage(396, 276, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

                    // make a memory stream to work with the image bytes
                    MemoryStream imageStream = new MemoryStream();

                    // put the image into the memory stream
                    thumbnailImage.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg);

                    // make byte array the same size as the image
                    byte[] imageContent = new Byte[imageStream.Length];

                    // rewind the memory stream
                    imageStream.Position = 0;

                    // load the byte array with the image
                    imageStream.Read(imageContent, 0, (int)imageStream.Length);

                    // return byte array to caller with image type
                    Response.ContentType = "image/jpeg";
                    Response.BinaryWrite(imageContent);

                    //Response.BinaryWrite(img.Thumbnail);
                    ms.Dispose();
                    imageStream.Dispose();
                }
                else
                {
                    GetFullImage(image);
                }
                if (Request["slide"] != null)
                {
                    GetFullImage(image);
                }
            }
        }
Ejemplo n.º 6
0
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            Page.Validate("vgAdd");
            if (Page.IsValid)
            {
                var q = (from ir in dbIR.IRTransactions
                         where ir.Id == Convert.ToInt32(Request.QueryString["Id"])
                         select ir).FirstOrDefault();

                q.TicketNo           = txtTicketNo.Text;
                q.CrisisId           = Convert.ToInt32(ddlCrisis.SelectedValue);
                q.From               = txtFrom.Text;
                q.Subject            = txtSubject.Text;
                q.Room               = txtRoom.Text;
                q.Date               = Convert.ToDateTime(txtDate.Text);
                q.Status             = ddlStatus.SelectedValue;
                q.WhenIncidentHappen = Convert.ToDateTime(txtWhenIncident.Text);
                q.WhenAware          = rblWhenAware.SelectedValue;
                q.WhoInvolved        = txtWhosInvolved.Text;
                q.WhatHappened       = txtWhatHappened.Text;
                q.Investigation      = txtInvestigation.Text;
                q.ActionTaken        = txtActionTaken.Text;
                q.Recommendation     = txtRecommendation.Text;
                q.PreparedBy         = Guid.Parse(Membership.GetUser().ProviderUserKey.ToString());

                //chk if solved
                if (ddlStatus.SelectedValue == "Solved")
                {
                    q.DateSolved   = DateTime.Now;
                    q.ResolvedTime = String.Format("{0} hours, {1} minutes",
                                                   DateTime.Now.Subtract(q.StartDate.Value).Hours,
                                                   DateTime.Now.Subtract(q.StartDate.Value).Minutes);
                }

                //dbIR.SubmitChanges();

                int tranId = q.Id;

                //uploaded imgs
                if (FileUpload1.HasFiles)
                {
                    foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
                    {
                        string fileName = Path.GetFileName(postedFile.FileName);
                        postedFile.SaveAs(Server.MapPath("~/photo-evidence/") + tranId + "_" + fileName);

                        //create thumbnail
                        System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath("~/photo-evidence/") + tranId + "_" + fileName);
                        System.Drawing.Image bmp1  = image.GetThumbnailImage(100, 100, null, IntPtr.Zero);
                        bmp1.Save(Server.MapPath("~/photo-evidence/") + tranId + "_" + "thumb_" + fileName);

                        //record to db
                        EvidencePhoto ep = new EvidencePhoto();
                        ep.IrId      = tranId;
                        ep.ImagePath = fileName;

                        dbIR.EvidencePhotos.InsertOnSubmit(ep);
                    }
                    //dbIR.SubmitChanges();
                }

                //delete associated depts
                var deleteDepts = (from d in dbIR.DepartmentsInvolveds
                                   where d.IRId == Convert.ToInt32(Request.QueryString["Id"])
                                   select d).ToList();

                dbIR.DepartmentsInvolveds.DeleteAllOnSubmit(deleteDepts);

                //re-add selected
                foreach (ListItem item in lstDepartments.Items)
                {
                    if (item.Selected)
                    {
                        DepartmentsInvolved di = new DepartmentsInvolved();
                        di.IRId         = Convert.ToInt32(Request.QueryString["Id"]);
                        di.DepartmentId = Convert.ToInt32(item.Value);
                        dbIR.DepartmentsInvolveds.InsertOnSubmit(di);
                    }
                }

                dbIR.SubmitChanges();

                //audit trail
                DBLogger.Log("Update", "Updated IR with status of: " + q.Status,
                             q.TicketNo);

                Response.Redirect("~/ir/ir.aspx");
            }
        }
        public ActionResult Index(CustomerRegistration Cust, IEnumerable <HttpPostedFileBase> file)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (Request.Form["Submit"] != null)
                    {
                        string FirstName = "", LastName = "", Email = "", Phone1 = "", Phone2 = "", Phone3 = "", Password = "",
                               TempPass = "", ZipCode = "", ProfilePhoto = "", HouseType = "", Address = "", IsCars = "",
                               Occupation = "", CompanyName = "", Phone = "", FieldName1 = "", RenamedImageName = "", FileName2 = "";
                        int NoOfCars = 0, UserId;

                        //bool IsHavingCars = false;

                        List <spUpdateCustomerForWeb_Result> CustDetails = null;
                        UserId = Convert.ToInt32(Session["UserId"].ToString());


                        if (Cust.FirstName != null)
                        {
                            FirstName            = Cust.FirstName.ToString();
                            Session["FirstName"] = FirstName;
                        }
                        if (Cust.LastName != null)
                        {
                            LastName            = Cust.LastName.ToString();
                            Session["LastName"] = LastName;
                        }

                        if (Cust.PhoneNo1 != null)
                        {
                            Phone1 = Cust.PhoneNo1.ToString();
                        }

                        Phone = Phone1;//Change 29Dec16

                        if (Cust.ZipCode != null)
                        {
                            ZipCode = Cust.ZipCode.ToString();
                        }
                        if (Cust.HouseType != null)
                        {
                            HouseType = Cust.HouseType.ToString();
                        }

                        if (Cust.Address != null)
                        {
                            Address = Cust.Address.ToString();
                        }
                        if (Cust.IsCars != null)
                        {
                            IsCars = Cust.IsCars.ToString();
                        }
                        if (Cust.NumberofCars != null)
                        {
                            if (IsCars == "Yes")
                            {
                                NoOfCars = Convert.ToInt32(Cust.NumberofCars.ToString());
                            }
                            else
                            {
                                NoOfCars = 0;
                            }
                        }
                        if (Cust.Occupation != null)
                        {
                            if (Cust.Occupation.ToString() == "Business Owner")
                            {
                                Occupation = "Self Employed";
                            }
                            else
                            {
                                Occupation = Cust.Occupation.ToString();
                            }
                        }
                        if (Cust.CompanyName != null)
                        {
                            CompanyName = Cust.CompanyName.ToString();
                        }

                        //Save Details of Profile Picture

                        if (Cust.IsProfilePhotoChanged == "Yes")
                        {
                            if (file == null)
                            {
                            }
                            else
                            {
                                foreach (var f in file)
                                {
                                    if (f != null)
                                    {
                                        if (f.ContentLength > 0)
                                        {
                                            int      MaxContentLength      = 1024 * 1024 * 4; //Size = 4 MB
                                            string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf", ".jpe", ".jpeg" };
                                            if (!AllowedFileExtensions.Contains
                                                    (f.FileName.Substring(f.FileName.LastIndexOf('.')).ToLower()))
                                            {
                                                ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
                                            }
                                            else if (f.ContentLength > MaxContentLength)
                                            {
                                                ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
                                            }
                                            else
                                            {
                                                var fileName = Path.GetFileName(f.FileName);
                                                //var Name = Path.GetFileNameWithoutExtension(f.FileName);
                                                var path = Path.Combine(Server.MapPath("~/UploadedDoc"), fileName);
                                                //Save file on server.
                                                //f.SaveAs(path);

                                                //Convert input file to Base 64 string

                                                byte[] binaryData;
                                                binaryData = new Byte[f.InputStream.Length];
                                                long bytesRead = f.InputStream.Read(binaryData, 0, (int)f.InputStream.Length);
                                                f.InputStream.Close();
                                                string base64String = System.Convert.ToBase64String(binaryData, 0, binaryData.Length);

                                                string FileName1 = "";

                                                string FieldName      = "";
                                                string ProfilePicFile = "";

                                                string ProfilePic = Cust.ProfilePhoto.ToString().Replace("C:\\fakepath\\", "");

                                                if (ProfilePic == fileName)
                                                {
                                                    FileName1      = System.Web.HttpContext.Current.Server.MapPath("~/ProfilePicture/" + Cust.Email.ToString() + "_" + UserId + ".txt");
                                                    FieldName      = "ProfilePicture";
                                                    FileName2      = Cust.Email.ToString() + "_" + UserId + ".txt";
                                                    ProfilePicFile = System.Web.HttpContext.Current.Server.MapPath("~/UploadedImages/ProfilePicture/" + Cust.Email.ToString() + "_" + UserId + ".png");
                                                    bool   CheckFile1  = BrokerUtility.CheckFile(ProfilePicFile);
                                                    byte[] imageBytes1 = Convert.FromBase64String(base64String);

                                                    //MemoryStream ms1 = new MemoryStream(imageBytes1, 0, imageBytes1.Length);
                                                    MemoryStream ms1 = new MemoryStream(binaryData, 0, binaryData.Length);

                                                    //ms1.Write(imageBytes1, 0, imageBytes1.Length);
                                                    ms1.Write(binaryData, 0, binaryData.Length);

                                                    System.Drawing.Image image1 = System.Drawing.Image.FromStream(ms1, true);

                                                    //image1.Save(System.Web.HttpContext.Current.Server.MapPath("~/UploadedImages/ProfilePicture/" + Cust.Email.ToString() + "_" + UserId + ".png"), System.Drawing.Imaging.ImageFormat.Png);
                                                    System.Drawing.Image thumbnail = image1.GetThumbnailImage(200, 200, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
                                                    thumbnail.Save(System.Web.HttpContext.Current.Server.MapPath("~/UploadedImages/ProfilePicture/" + Cust.Email.ToString() + "_" + UserId + ".png"), System.Drawing.Imaging.ImageFormat.Png);

                                                    FieldName1       = "ProfilePictureImg";
                                                    RenamedImageName = Cust.Email.ToString() + "_" + UserId + ".png";

                                                    //Check for the file already exist or not
                                                    bool CheckFile = BrokerUtility.CheckFile(FileName1);
                                                    if (CheckFile)
                                                    {
                                                        //Create a text file of Base 64 string
                                                        bool result = BrokerUtility.WriteFile(FileName1, base64String);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                        }

                        //Save the Details of Customer

                        CustDetails = BrokerWebDB.BrokerWebDB.SaveCustomerProfileDetails(FirstName, LastName, Phone, Address, ZipCode, HouseType, IsCars, NoOfCars, Occupation, CompanyName, FileName2, RenamedImageName, Cust.IsProfilePhotoChanged, UserId, "", "", "");

                        if (CustDetails.Count > 0)
                        {
                            //TempData["CustDetails"] = Cust;
                            return(RedirectToAction("CustomerProfile", "Profile"));
                        }
                        else
                        {
                            return(View());
                        }
                        //BrokerUtility.SaveCustomerBasicDetails(FirstName, LastName, Phone, Email, Address, ZipCode, TempPass, Encryptrandom, HouseType, IsCars, NoOfCars, Occupation, CompanyName);
                    }
                    else if (Request.Form["Cancel"] != null)
                    {
                        //TempData["CustDetails"] = Cust;
                        return(RedirectToAction("CustomerProfile", "Profile"));
                        //return View("","")
                    }
                }
                catch (Exception Ex)
                {
                    BrokerUtility.ErrorLog(Convert.ToInt32(Session["UserId"].ToString()), "Index_POST_Wesite", Ex.Message.ToString(), "CustomerRegistrationController.cs_Index_POST", BrokerUtility.GetIPAddress(Session["UserId"].ToString()));
                    return(View());
                }
                return(View());
            }
            else
            {
                return(View());
            }
        }
Ejemplo n.º 8
0
        protected void BtnUpload_Click(object sender, EventArgs e)
        {
            string Map = Server.MapPath("/DesktopModules/Pacientes");

            if (Directory.Exists(Map) == true)
            {
                ConnectionDispensario.Statics.LogCatcher.AddLog("El directorio existe", Map, this, Session);
                if (Directory.Exists(Map + "\\ArchivosPacientes") == false)
                {
                    ConnectionDispensario.Statics.LogCatcher.AddLog("Intentando crear directorio", Map, this, Session);
                    Directory.CreateDirectory(Map + "\\ArchivosPacientes");
                }
                else
                {
                    ConnectionDispensario.Statics.LogCatcher.AddLog("El directorio Archivos de pacientes existe", Map, this, Session);
                }
                Paciente t_p = Session[SessionPaciente] as Paciente;
                string   NomenclaturaPaciente = "Paciente" + t_p.ID.ToString();

                if (Directory.Exists(Map + "\\ArchivosPacientes\\" + NomenclaturaPaciente) == false)
                {
                    Directory.CreateDirectory(Map + "\\ArchivosPacientes\\" + NomenclaturaPaciente);
                }
                if (UPLFileUpload.HasFile)
                {
                    char[] splitter  = { '.' };
                    string extension = UPLFileUpload.FileName.Split(splitter)[1];
                    if (extension.ToLower() == "jpg" || extension.ToLower() == "jpeg" || extension.ToLower() == "png" || extension.ToLower() == "bmp")
                    {
                        string Second;
                        string Minute;
                        string Hour;
                        string Day;
                        string Month;
                        string Year;

                        DateTime N = DateTime.Now;

                        if (N.Second.ToString().Length == 1)
                        {
                            Second = "0" + N.Second.ToString();
                        }
                        else
                        {
                            Second = N.Second.ToString();
                        }
                        if (N.Minute.ToString().Length == 1)
                        {
                            Minute = "0" + N.Minute.ToString();
                        }
                        else
                        {
                            Minute = N.Minute.ToString();
                        }
                        if (N.Hour.ToString().Length == 1)
                        {
                            Hour = "0" + N.Hour.ToString();
                        }
                        else
                        {
                            Hour = N.Hour.ToString();
                        }
                        if (N.Day.ToString().Length == 1)
                        {
                            Day = "0" + N.Day.ToString();
                        }
                        else
                        {
                            Day = N.Day.ToString();
                        }
                        if (N.Month.ToString().Length == 1)
                        {
                            Month = "0" + N.Month.ToString();
                        }
                        else
                        {
                            Month = N.Month.ToString();
                        }
                        if (N.Year.ToString().Length == 1)
                        {
                            Year = "0" + N.Year.ToString();
                        }
                        else
                        {
                            Year = N.Year.ToString();
                        }

                        string filename = Year + Month + Day + Hour + Minute + Second;



                        UPLFileUpload.SaveAs(Map + "\\ArchivosPacientes\\" + NomenclaturaPaciente + "\\" + filename + "." + extension);

                        System.Drawing.Image I = System.Drawing.Image.FromFile(Map + "\\ArchivosPacientes\\" + NomenclaturaPaciente + "\\" + filename + "." + extension);
                        System.Drawing.Image.GetThumbnailImageAbort G = new System.Drawing.Image.GetThumbnailImageAbort(delegateforthat);
                        System.Drawing.Image T = I.GetThumbnailImage(100, 100, G, IntPtr.Zero);
                        T.Save(Map + "\\ArchivosPacientes\\" + NomenclaturaPaciente + "\\" + "THMB" + filename + "." + extension);
                    }
                }
            }
            else
            {
            }
        }
        public ActionResult APSPCustomerSignUp(MeinekeCustomerSignUp Cust, IEnumerable <HttpPostedFileBase> file)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    string FirstName = "", LastName = "", Email = "", Phone1 = "", Phone2 = "", Phone3 = "", Password = "",
                           TempPass = "", ZipCode = "", ProfilePhoto = "", HouseType = "", Address = "", IsCars = "",
                           Occupation = "", CompanyName = "", Phone = "", FieldName1 = "", RenamedImageName = "", FileName2 = "", NoofEmployee = "", EstPremium = "", Website = "";
                    int NoOfCars = 0, UserId = 0;

                    List <uspSaveCustomerBasicDetails_Result> User1 = null;
                    //UserId = Convert.ToInt32(Session["UserId"].ToString());

                    if (Cust.FirstName != null)
                    {
                        FirstName = Cust.FirstName.ToString();
                    }
                    if (Cust.LastName != null)
                    {
                        LastName = Cust.LastName.ToString();
                    }
                    if (Cust.CompanyName != null)
                    {
                        CompanyName = Cust.CompanyName.ToString();
                    }
                    if (Cust.Address != null)
                    {
                        Address = Cust.Address.ToString();
                    }
                    if (Cust.EmailId != null)
                    {
                        Email = Cust.EmailId.ToString();
                    }
                    if (Cust.PhoneNo != null)
                    {
                        Phone = Cust.PhoneNo.ToString();
                    }
                    if (Cust.Website != null)
                    {
                        Website = Cust.Website.ToString();
                    }
                    if (Cust.ZipCode != null)
                    {
                        ZipCode = Cust.ZipCode.ToString();
                    }
                    if (Cust.NoofEmployees != null)
                    {
                        NoofEmployee = Cust.NoofEmployees.ToString();
                    }
                    if (Cust.EstPremium != null)
                    {
                        EstPremium = Cust.EstPremium.ToString();
                    }

                    string random        = BrokerWSUtility.GetRandomNumber();
                    string Encryptrandom = BrokerUtility.EncryptURL(random);
                    Session["random"] = Encryptrandom;

                    User1 = BrokerUtility.SaveCustomerBasicDetails(FirstName, LastName, Phone, Email, Address, ZipCode, TempPass, Encryptrandom, HouseType, IsCars, NoOfCars, Occupation, CompanyName, NoofEmployee, EstPremium, Website, "APSP");
                    int Flag = 0;

                    if (User1.Count > 0)
                    {
                        UserId             = Convert.ToInt32(User1[0].UserId.ToString());
                        Session["UserId"]  = UserId;
                        Session["EmailId"] = User1[0].EmailId.ToString();

                        //////////////////// Access Profile Pic and Resume Files //////////////////////////
                        if (file == null)
                        {
                        }
                        else
                        {
                            foreach (var f in file)
                            {
                                if (f != null)
                                {
                                    if (f.ContentLength > 0)
                                    {
                                        int      MaxContentLength      = 1024 * 1024 * 4; //Size = 4 MB
                                        string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf", ".jpe", ".jpeg" };
                                        if (!AllowedFileExtensions.Contains
                                                (f.FileName.Substring(f.FileName.LastIndexOf('.')).ToLower()))
                                        {
                                            ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
                                        }
                                        else if (f.ContentLength > MaxContentLength)
                                        {
                                            ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
                                        }
                                        else
                                        {
                                            var fileName = Path.GetFileName(f.FileName);
                                            //var Name = Path.GetFileNameWithoutExtension(f.FileName);
                                            var path = Path.Combine(Server.MapPath("~/UploadedDoc"), fileName);
                                            //Save file on server.
                                            //f.SaveAs(path);

                                            //Convert input file to Base 64 string

                                            byte[] binaryData;
                                            binaryData = new Byte[f.InputStream.Length];
                                            long bytesRead = f.InputStream.Read(binaryData, 0, (int)f.InputStream.Length);
                                            f.InputStream.Close();
                                            string base64String = System.Convert.ToBase64String(binaryData, 0, binaryData.Length);

                                            string FileName1 = "";
                                            //  string FileName2 = "";
                                            string FieldName = "";

                                            string ProfilePic = Cust.ProfilePicture.ToString().Replace("C:\\fakepath\\", "");

                                            if (ProfilePic == fileName)
                                            {
                                                FileName1 = System.Web.HttpContext.Current.Server.MapPath("~/ProfilePicture/" + Cust.EmailId.ToString() + "_" + UserId + ".txt");
                                                FieldName = "ProfilePicture";
                                                FileName2 = Cust.EmailId.ToString() + "_" + UserId + ".txt";

                                                //Save Image on Server also.

                                                // Convert byte[] to Image

                                                byte[]       imageBytes1 = Convert.FromBase64String(base64String);
                                                MemoryStream ms1         = new MemoryStream(imageBytes1, 0, imageBytes1.Length);

                                                ms1.Write(imageBytes1, 0, imageBytes1.Length);
                                                System.Drawing.Image image1 = System.Drawing.Image.FromStream(ms1, true);

                                                //image1.Save(System.Web.HttpContext.Current.Server.MapPath("~/UploadedImages/ProfilePicture/" + Email + "_" + UserId + ".png"), System.Drawing.Imaging.ImageFormat.Png);

                                                System.Drawing.Image thumbnail = image1.GetThumbnailImage(200, 200, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
                                                thumbnail.Save(System.Web.HttpContext.Current.Server.MapPath("~/UploadedImages/ProfilePicture/" + Email + "_" + UserId + ".png"), System.Drawing.Imaging.ImageFormat.Png);

                                                FieldName1       = "ProfilePictureImg";
                                                RenamedImageName = Cust.EmailId.ToString() + "_" + UserId + ".png";
                                            }

                                            //Check for the file already exist or not
                                            bool CheckFile = BrokerUtility.CheckFile(FileName1);
                                            if (CheckFile)
                                            {
                                                //Create a text file of Base 64 string
                                                bool result = BrokerUtility.WriteFile(FileName1, base64String);

                                                if (result)
                                                {
                                                    Flag = BrokerUtility.SaveBrokerFiles(FileName2, UserId, FieldName, FieldName1, RenamedImageName);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        // Send Verification Link on Email Id

                        //string random = BrokerWSUtility.GetRandomNumber();

                        bool EmailFlag = false;

                        EmailFlag = BrokerWSUtility.SendRegistrationEmailFromWebSite(Session["EmailId"].ToString(), Session["random"].ToString(), Session["UserId"].ToString(), "Customer");
                        //EmailFlag = true;
                        if (EmailFlag)
                        {
                            ViewBag.VerificationMessage  = "You are registered successfully but yet not activated. ";
                            ViewBag.VerificationMessage1 = "Please accept your verification email.";
                            ViewBag.Company = "APSP";
                            return(View("CustomerSuccess"));
                        }
                        else
                        {
                            //If User registerd successfully, but verification link has not
                            //been sent over EmailId
                            //ViewBag.VerificationMessage = "You are registered successfully but yet not activated. <br/>Please accept your verification email.";
                            ViewBag.Company = "APSP";
                            return(View("CustomerError"));
                        }
                    }
                }
                catch (Exception Ex)
                {
                    BrokerUtility.ErrorLog(Convert.ToInt32(Session["UserId"].ToString()), "Index_POST_Wesite", Ex.Message.ToString(), "CustomerRegistrationController.cs_Index_POST", BrokerUtility.GetIPAddress(Session["UserId"].ToString()));
                    return(View());
                }
                return(View());
            }
            return(View());
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Creates a JpegFrame from a System.Drawing.Image
        /// </summary>
        /// <param name="source">The Image to create a JpegFrame from</param>
        public JpegFrame(System.Drawing.Image source, uint quality = 100, uint?ssrc = null, uint?sequenceNo = null, uint?timeStamp = null) : this()
        {
            //Must calculate correctly the Type, Quality, FragmentOffset and Dri
            uint TypeSpecific = 0, Type = 0, Quality = quality, Width = (uint)source.Width, Height = (uint)source.Height;

            byte[] RestartInterval = null; List <byte> QTables = new List <byte>();

            //Save the image in Jpeg format and request the PropertyItems from the Jpeg format of the Image
            using (System.IO.MemoryStream temp = new System.IO.MemoryStream())
            {
                //Create Encoder Parameters for the Jpeg Encoder
                System.Drawing.Imaging.EncoderParameters parameters = new System.Drawing.Imaging.EncoderParameters(3);
                // Set the quality
                parameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Quality);
                // Set the render method to Progressive
                parameters.Param[1] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.RenderMethod, (int)System.Drawing.Imaging.EncoderValue.RenderProgressive);
                // Set the scan method to Progressive
                parameters.Param[2] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.ScanMethod, (int)System.Drawing.Imaging.EncoderValue.ScanMethodNonInterlaced);

                //Determine if there are multiple frames in the image
                //if(source.FrameDimensionsList.Count() > 0)
                //{
                //    System.Drawing.Imaging.FrameDimension dimension = new System.Drawing.Imaging.FrameDimension(source.FrameDimensionsList[0]);
                //    int frameCount = source.GetFrameCount(dimension);
                //    if (frameCount > 1)
                //    {
                //        ///Todo -  Handle Multiple Frames from a System.Drawing.Image (Gif)
                //        ///Perhaps the sender should just SetActiveFrame and then we will use the active frame
                //    }
                //}

                if (source.Width > JpegFrame.MaxWidth || source.Height > JpegFrame.MaxHeight)
                {
                    using (System.Drawing.Image thumb = source.GetThumbnailImage(JpegFrame.MaxWidth, JpegFrame.MaxHeight, null, IntPtr.Zero))
                    {
                        //Save the source to the temp stream using the jpeg coded and given encoder params
                        thumb.Save(temp, JpegCodecInfo, parameters);
                    }
                }
                else
                {
                    //Save the source to the temp stream using the jpeg coded and given encoder params
                    source.Save(temp, JpegCodecInfo, parameters);
                }

                //Check for the EOI Marker
                temp.Seek(-1, System.IO.SeekOrigin.Current);

                //If present we will ignore it when creating the packets
                long endOffset = temp.ReadByte() == Tags.EndOfInformation ? temp.Length - 2 : temp.Length;

                //Enure at the beginning
                temp.Seek(0, System.IO.SeekOrigin.Begin);

                //Read the JPEG Back from the stream so it's pixel format is JPEG
                Image = System.Drawing.Image.FromStream(temp, false, true);

                //Determine if there are Quantization Tables which must be sent
                if (Image.PropertyIdList.Contains(0x5090) && Image.PropertyIdList.Contains(0x5091))
                {
                    //QTables.AddRange((byte[])Image.GetPropertyItem(0x5090).Value); //16 bit
                    //QTables.AddRange((byte[])Image.GetPropertyItem(0x5091).Value); //16 bit
                    //This is causing the QTables to be read on the reciever side
                    Quality |= 128;
                }
                else
                {
                    //Values less than 128 cause QTables to be generated on reciever side
                    Quality = 127;
                }

                //Determine if there is a DataRestartInterval
                if (Image.PropertyIdList.Contains(0x0203))
                {
                    RestartInterval = Image.GetPropertyItem(0x0203).Value;
                    Type            = 64;
                }
                else
                {
                    Type = 63;
                }

                //used for reading the JPEG data
                int Tag, TagSize,
                //The max size of each Jpeg RtpPacket (Allow for any overhead)
                    BytesInPacket = RtpPacket.MaxPayloadSize - 200;

                //The current packet
                RtpPacket currentPacket = new RtpPacket(temp.Length < BytesInPacket ? (int)temp.Length : BytesInPacket);
                SynchronizationSourceIdentifier = currentPacket.SynchronizationSourceIdentifier = (ssrc ?? (uint)SynchronizationSourceIdentifier);
                currentPacket.TimeStamp         = (uint)(timeStamp ?? Utility.DateTimeToNptTimestamp(DateTime.UtcNow));
                currentPacket.SequenceNumber    = (ushort)(sequenceNo ?? 1);
                currentPacket.PayloadType       = JpegFrame.RtpJpegPayloadType;

                //Where we are in the current packet
                int currentPacketOffset = 0;

                //Determine if we need to write OnVif Extension?
                if (Width > MaxWidth || Height > MaxHeight)
                {
                    //packet.Extensions = true;

                    //Write Extension Headers
                }

                //Ensure at the begining
                temp.Seek(0, System.IO.SeekOrigin.Begin);

                //Find a Jpeg Tag while we are not at the end of the stream
                //Tags come in the format 0xFFXX
                while ((Tag = temp.ReadByte()) != -1)
                {
                    //If the prefix is a tag prefix then read another byte as the Tag
                    if (Tag == Tags.Prefix)
                    {
                        //Get the Tag
                        Tag = temp.ReadByte();

                        //If we are at the end break
                        if (Tag == -1)
                        {
                            break;
                        }

                        //Determine What to do for each Tag

                        //Start and End Tag (No Length)
                        if (Tag == Tags.StartOfInformation)
                        {
                            continue;
                        }
                        else if (Tag == Tags.EndOfInformation)
                        {
                            break;
                        }

                        //Read Length Bytes
                        byte h = (byte)temp.ReadByte(), l = (byte)temp.ReadByte();

                        //Calculate Length
                        TagSize = h * 256 + l;

                        //Correct Length
                        TagSize -= 2; //Not including their own length

                        //QTables are copied when Quality is > 127
                        if (Tag == Tags.QuantizationTable && Quality > 127)
                        {
                            //byte Precision = (byte)temp.ReadByte();//Discard Precision
                            //if (Precision != 0) throw new Exception("Only 8 Bit Precision is Supported");

                            temp.ReadByte();//Discard Table Id (And Precision which is in the same byte)

                            byte[] table = new byte[TagSize - 1];

                            temp.Read(table, 0, TagSize - 1);

                            QTables.AddRange(table);
                        }
                        else if (Tag == Tags.DataRestartInterval) //RestartInterval is copied
                        {
                            //Make DRI?
                            //Type = 64;
                            //RestartInterval = CreateRtpDataRestartIntervalMarker((int)temp.Length, 1, 1, 0x3fff);
                            throw new NotImplementedException();
                        }
                        //Last Marker in Header before EntroypEncodedScan
                        else if (Tag == Tags.StartOfScan)
                        {
                            //Read past the Start of Scan
                            temp.Seek(TagSize, System.IO.SeekOrigin.Current);

                            //Create RtpJpegHeader and CopyTo currentPacket advancing currentPacketOffset
                            {
                                byte[] data = CreateRtpJpegHeader(TypeSpecific, 0, Type, Quality, Width, Height, RestartInterval, QTables);

                                data.CopyTo(currentPacket.Payload, currentPacketOffset);

                                currentPacketOffset += data.Length;
                            }

                            //Determine how much to read
                            int packetRemains = BytesInPacket - currentPacketOffset;

                            //How much remains in the stream relative to the endOffset
                            long streamRemains = endOffset - temp.Position;

                            //A RtpJpegHeader which must be in the Payload of each Packet (8 Bytes without QTables and RestartInterval)
                            byte[] RtpJpegHeader = CreateRtpJpegHeader(TypeSpecific, 0, Type, Quality, Width, Height, RestartInterval, null);

                            //While we are not done reading
                            while (temp.Position < endOffset)
                            {
                                //Read what we can into the packet
                                packetRemains -= temp.Read(currentPacket.Payload, currentPacketOffset, packetRemains);

                                //Update how much remains
                                streamRemains = endOffset - temp.Position;

                                //Add current packet
                                Add(currentPacket);

                                //Determine if we need to adjust the size and add the packet
                                if (streamRemains < BytesInPacket - 8)
                                {
                                    //8 for the RtpJpegHeader and this will cause the Marker be to set
                                    packetRemains = (int)(streamRemains + 8);
                                }
                                else
                                {
                                    //Size is normal
                                    packetRemains = BytesInPacket;
                                }

                                //Make next packet
                                currentPacket = new RtpPacket(packetRemains)
                                {
                                    TimeStamp      = currentPacket.TimeStamp,
                                    SequenceNumber = (ushort)(currentPacket.SequenceNumber + 1),
                                    SynchronizationSourceIdentifier = currentPacket.SynchronizationSourceIdentifier,
                                    PayloadType = JpegFrame.RtpJpegPayloadType,
                                    Marker      = packetRemains < BytesInPacket || temp.Position >= endOffset
                                };

                                //Correct FragmentOffset
                                System.Array.Copy(BitConverter.GetBytes(Utility.ReverseUnsignedInt((uint)temp.Position)), 1, RtpJpegHeader, 1, 3);

                                //Todo
                                //Restart Interval
                                //

                                //Copy header
                                RtpJpegHeader.CopyTo(currentPacket.Payload, 0);

                                //Set offset in packet.Payload
                                packetRemains -= currentPacketOffset = 8;
                            }
                        }
                        else //Skip past tag
                        {
                            temp.Seek(TagSize, System.IO.SeekOrigin.Current);
                        }
                    }
                }

                //To allow the stream to be closed
                Image = new System.Drawing.Bitmap(Image);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Capture the next frame from the video feed
        /// </summary>
        private void timer1_Tick(object sender, System.EventArgs e)
        {
            try
            {
                // pause the timer
                this.timer1.Stop();

                // get the next frame;
                SendMessage(mCapHwnd, WM_CAP_GET_FRAME, 0, 0);

                // copy the frame to the clipboard
                SendMessage(mCapHwnd, WM_CAP_COPY, 0, 0);

                // paste the frame into the event args image
                if (ImageCaptured != null)
                {
                    // get from the clipboard
                    tempObj = Clipboard.GetDataObject();
                    tempImg = (System.Drawing.Bitmap) tempObj.GetData(System.Windows.Forms.DataFormats.Bitmap);
                    GC.Collect();
                    /*
                    * For some reason, the API is not resizing the video
                    * feed to the width and height provided when the video
                    * feed was started, so we must resize the image here
                    */
                    x.WebCamImage = tempImg.GetThumbnailImage(m_Width, m_Height, null, System.IntPtr.Zero);

                    // raise the event
                    this.ImageCaptured(this, x);
                }

                // restart the timer
                Application.DoEvents();
                if (! bStopped)
                    this.timer1.Start();
            }

            catch (Exception excep)
            {
                LibUSBLauncher.Log.Instance.Out(excep);
                this.Stop(); // stop the process
            }
        }
Ejemplo n.º 12
0
        private void ImportPhoto(string[] imgFileNames)
        {
            string       jsBlock          = string.Empty;
            string       templateFileName = Server.MapPath("/RailExamBao/RandomExam/ProgressBar.htm");
            StreamReader reader           = new StreamReader(@templateFileName, System.Text.Encoding.GetEncoding("gb2312"));
            string       html             = reader.ReadToEnd();

            reader.Close();
            Response.Write(html);
            Response.Flush();
            System.Threading.Thread.Sleep(200);

            // 添加滚动条效果
            jsBlock = "<script>SetPorgressBar('正准备导入照片数据','0.00'); </script>";
            Response.Write(jsBlock);
            Response.Flush();

            OracleAccess db = new OracleAccess();

            string errorMessage = string.Empty;

            // 循环批量导入照片文件
            for (int i = 0; i < imgFileNames.Length; i++)
            {
                // 滚动条效果
                System.Threading.Thread.Sleep(10);
                jsBlock = "<script>SetPorgressBar('正在导入照片数据','" +
                          ((double)((i + 1) * 100) / (double)imgFileNames.Length).ToString("0.00") + "'); </script>";
                Response.Write(jsBlock);
                Response.Flush();

                string f_n          = imgFileNames[i];
                int    lastPathChar = f_n.LastIndexOf("\\");
                string filename     = f_n.Substring(lastPathChar + 1, f_n.LastIndexOf(".") - lastPathChar - 1);

                // TODO: 导入单张照片
                try
                {
                    System.Drawing.Image image     = System.Drawing.Image.FromFile(imgFileNames[i]);
                    System.Drawing.Image thumbnail = image.GetThumbnailImage(120, 150, null, IntPtr.Zero);
                    MemoryStream         ms        = new MemoryStream();
                    thumbnail.Save(ms, ImageFormat.Jpeg);
                    byte[] byteImage = ms.ToArray();

                    string workno = filename.Substring(0, 8);
                    string name   = filename.Replace(workno, "");

                    string  strSql = "select * from Employee where Work_No='" + workno + "' and Employee_Name='" + name + "'";
                    DataSet ds     = db.RunSqlDataSet(strSql);

                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        //添加
                        XmlDocument doc = new XmlDocument();
                        doc.Load(Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, "web.config"));
                        XmlNode node  = doc.SelectSingleNode("configuration/dataConfiguration/@defaultDatabase");
                        string  value = node.Value;

                        if (value == "Oracle")
                        {
                            System.Data.OracleClient.OracleParameter para1 = new System.Data.OracleClient.OracleParameter("p_photo", OracleType.Blob);
                            System.Data.OracleClient.OracleParameter para2 = new System.Data.OracleClient.OracleParameter("p_id", OracleType.Number);
                            para1.Value = byteImage;
                            para2.Value = Convert.ToInt32(ds.Tables[0].Rows[0]["Employee_ID"]);

                            IDataParameter[] paras = new IDataParameter[] { para1, para2 };

                            Pub.RunAddProcedureBlob(false, "USP_EMPLOYEE_IMAGE", paras, byteImage);
                        }
                    }
                    else
                    {
                        errorMessage += "图片【" + filename + "】在系统中查询不到对应的员工信息\n";
                    }

                    image.Dispose();
                    ms.Dispose();
                    thumbnail.Dispose();
                }
                catch
                {
                    errorMessage += "文件【" + filename + "】不是图片或者文件名错误\n";
                }

                System.Threading.Thread.Sleep(10);
                jsBlock = "<script>SetPorgressBar('正在导入图片','" + ((double)((i + 1) * 100) / (double)imgFileNames.Length) + "'); </script>";
                Response.Write(jsBlock);
                Response.Flush();
            }

            if (errorMessage != string.Empty)
            {
                Response.Write("<script>window.returnValue='" + errorMessage + "',window.close();</script>");
                return;
            }

            // 处理完成
            jsBlock = "<script>SetCompleted('照片数据导入完毕'); </script>";
            Response.Write(jsBlock);
            Response.Flush();
        }
Ejemplo n.º 13
0
        protected void butGuardarEmpresa_Click(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsValid)
                {
                    return;
                }


                IEmpresaFacturacion empresa = EmpresaFacturacionFactory.GetEmpresaFacturacion();
                empresa.EmpresaFacturacionID = this.txtEmpresaID.Text == "" ? 0 : Convert.ToInt32(this.txtEmpresaID.Text);
                empresa.RazonSocial          = this.txtRazonSocial.Text;
                empresa.Email          = this.txtEMail.Text;
                empresa.Wan            = this.txtWan.Text;
                empresa.Predeterminada = this.chkPredeterminada.Checked;
                empresa.Cuerpos        = this.txtCuerpos.Text == string.Empty ? 0 : int.Parse(this.txtCuerpos.Text);
                empresa.NroCUIT        = this.txtCUITTipo.Text + this.txtCUITNro.Text + this.txtCUITDigitoVerificador.Text;
                if (empresa.EstadoEmpresa == NegociosSisPackInterface.SisPack.EstadoEmpresa.Ninguno)
                {
                    empresa.EstadoEmpresa = NegociosSisPackInterface.SisPack.EstadoEmpresa.Habilitada;
                }

                //Domicilio
                IDatosDomicilio domicilio = (IDatosDomicilio)this.phDomicilio.FindControl("domicilio");
                empresa.Domicilio.DomicilioID           = domicilio.DomicilioID;
                empresa.Domicilio.Calle                 = domicilio.Calle;
                empresa.Domicilio.CalleNro              = domicilio.CalleNro;
                empresa.Domicilio.Localidad.LocalidadID = domicilio.LocalidadID;
                empresa.Domicilio.Telefono              = domicilio.Telefono;

                //Logo
                // Verificamos que se esté guardando un logo, de lo contrario se muestra error.
                if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
                {
                    // Tomamos el nombre del archivo y obtenemos su extensión para ver si es PNG.
                    string   nombreLogo         = System.IO.Path.GetFileName(File1.PostedFile.FileName);
                    string[] nombreLogoSeparado = nombreLogo.Split('.');

                    if (!nombreLogoSeparado[nombreLogoSeparado.Length - 1].Equals("png") && !nombreLogoSeparado[nombreLogoSeparado.Length - 1].Equals("PNG") && !nombreLogoSeparado[nombreLogoSeparado.Length - 1].ToUpper().Equals("JPG"))
                    {
                        Exception ex = new Exception("La extensión del logo a guardar no es válida.");
                        throw ex;
                    }
                    else
                    {
                        // Verificamos si se ha creado la carpeta para archivos, de lo contrario se crea.
                        string carpetaDestino   = "Archivos";
                        bool   existeDirectorio = Directory.Exists(Request.PhysicalApplicationPath + "\\" + carpetaDestino);
                        if (!existeDirectorio)
                        {
                            // Especificamos el directorio activo actual.
                            string directorioActivo = Request.PhysicalApplicationPath;
                            // Creamos la nueva carpeta para guardar los logos.
                            string nuevaCarpeta = System.IO.Path.Combine(directorioActivo, carpetaDestino);
                            System.IO.Directory.CreateDirectory(nuevaCarpeta);
                        }

                        // Verificamos si se ha creado la carpeta para logos, de lo contrario se crea.
                        string carpetaLogos  = "LogosEmpresas";
                        bool   existeCarpeta = Directory.Exists(Request.PhysicalApplicationPath + "\\" + carpetaDestino + "\\" + carpetaLogos);
                        if (!existeCarpeta)
                        {
                            // Especificamos el directorio activo actual.
                            string directorioActivo = Request.PhysicalApplicationPath;
                            // Creamos la nueva carpeta para guardar los archivos.
                            string nuevaCarpeta = System.IO.Path.Combine(directorioActivo + "\\" + carpetaDestino, carpetaLogos);
                            System.IO.Directory.CreateDirectory(nuevaCarpeta);
                        }

                        // Redimensionamos la imagen al tamaño obligatorio 356 x 56.
                        int ancho = 356;
                        int alto  = 56;

                        // Guardamos la imagen en la carpeta seleccionada.
                        File1.PostedFile.SaveAs(Request.PhysicalApplicationPath + carpetaDestino + "\\" + carpetaLogos + "\\" + nombreLogo);

                        //Accedemos a la imagen guardada para poder redimensionarla.
                        string imagenUrl = carpetaDestino + "/" + carpetaLogos + "/" + nombreLogo;

                        System.Drawing.Image nuevaImagen = System.Drawing.Image.FromFile(Server.MapPath(imagenUrl));
                        System.Drawing.Image.GetThumbnailImageAbort dummyCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
                        System.Drawing.Image imagenRedimensionada = nuevaImagen.GetThumbnailImage(ancho, alto, dummyCallBack, IntPtr.Zero);

                        // Liberamos las imagenes utilizadas.
                        nuevaImagen.Dispose();
                        // Salvamos la imagen redimensionada.
                        imagenRedimensionada.Save(Request.PhysicalApplicationPath + carpetaDestino + "\\" + carpetaLogos + "\\" + nombreLogo, ImageFormat.Png);
                        // Liberamos las imagenes utilizadas y liberamos memoria.
                        imagenRedimensionada.Dispose();
                        GC.Collect();

                        // Guardamos la nueva imagen redimensionada.
                        empresa.Logo = nombreLogo;
                    }
                }
                else if ((this.txtLogoActual.Text != "") && (this.File1.Disabled == true))
                {
                    empresa.Logo = this.txtLogoActual.Text;
                }
                else
                {
                    Exception ex = new Exception("Seleccione un logo a guardar.");
                    throw ex;
                }

                // Datos para delfos
                empresa.Web                 = txtDirWeb.Text;
                empresa.NumeIIBB            = txtNumeroIIBB.Text;
                empresa.FechaInicio         = Convert.ToDateTime(txtFechaInicio.Text);
                empresa.NumeEstablecimiento = txtNumeroEstablecimiento.Text;
                empresa.Telefono            = domicilio.Telefono;
                empresa.CondicionIVA        = ddlCondicionIva.SelectedItem.Text;
                empresa.CertificadoDigital  = txtCertificadoDigital.Text;
                empresa.Texto               = this.txtTexto.Text.Trim();
                try
                {
                    if (empresa.Guardar(usuario))
                    {
                        string script = "<script language='javascript'>\n";
                        script += "alert('Los datos se guardaron correctamente.');\n";
                        script += "window.location.href = 'ABMEmpresasFacturacionConsul.aspx';\n";
                        script += "</script>";
                        Page.RegisterStartupScript("scriptOk", script);
                    }
                    else
                    {
                        string script = "<script language='javascript'>\n";
                        script += "alert('Los datos no se guardaron debido a errores.');\n";
                        script += "</script>";

                        Page.RegisterStartupScript("scriptError", script);
                    }
                }
                catch (Exception ex)
                {
                    string mensaje = ex.Message;
                    try
                    {
                        mensaje = this.TraducirTexto(ex.Message);
                        if (mensaje == "Errores.Invalidos.EmpresaNoActualizable.NoPuedeSerPredeterminada")
                        {
                            mensaje = "No puede ser empresa predeterminada por que no cumple con las propiedades de ser unica y estar asociada a todas las agencias.";
                        }

                        if (mensaje == "" || mensaje == null)
                        {
                            mensaje = ex.Message;
                        }
                    }
                    catch (Exception)
                    {
                        mensaje = ex.Message;
                    }
                    ((ErrorWeb)this.phErrores.Controls[0]).setMensaje(mensaje);
                }
            }
            catch (Exception ex)
            {
                string mensaje = ex.Message;
                try
                {
                    mensaje = this.TraducirTexto(ex.Message);
                    if (mensaje == "" || mensaje == null)
                    {
                        mensaje = ex.Message;
                    }
                }
                catch (Exception)
                {
                    mensaje = ex.Message;
                }
                ((ErrorWeb)this.phErrores.Controls[0]).setMensaje(mensaje);
            }
        }