Exemple #1
0
        public ActionResult DownloadFile(int Id)
        {
            MembershipHelp mHelp = new MembershipHelp(); var role = mHelp.logingUserRole(User.Identity.Name);
            var            roleId    = db.RoleMasters.Where(w => w.Name == role).Select(s => s.Id).FirstOrDefault();
            var            canDelete = (from m in db.MenuInfoes join rm in db.RoleMenuMappings on m.Id equals rm.MenuInfoId where m.MenuURL.Contains("ArtWorks") && rm.RoleId == roleId select rm.CanDelete).FirstOrDefault();

            if (!canDelete)
            {
                return(RedirectToAction("Index"));
            }

            string filename = db.ArtWorks.Where(w => w.Id == Id).Select(s => s.FileAddressInfo).FirstOrDefault();

            string filepath = AppDomain.CurrentDomain.BaseDirectory + "/Content/Uploads/Originals/" + filename;

            byte[] filedata    = System.IO.File.ReadAllBytes(filepath);
            string contentType = MimeMapping.GetMimeMapping(filepath);

            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = filename,
                Inline   = true,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());

            return(File(filedata, contentType));
        }
 public ActionResult Index()
 {
     var path = HttpContext.Server.MapPath("~\\App_Data\\Kentor.AuthServices.StubIdp.cer");
     var disposition = new ContentDisposition { Inline = false, FileName = Path.GetFileName(path) };
     Response.AppendHeader("Content-Disposition", disposition.ToString());
     return File(path, MediaTypeNames.Text.Plain);
 }
        public static string GetHeaderValue(string fileName, bool inline = false, bool withoutBase = false)
        {
            // If fileName contains any Unicode characters, encode according
            // to RFC 2231 (with clarifications from RFC 5987)
            if (fileName.Any(c => (int)c > 127))
            {
                var str = withoutBase
                    ? "{0}; filename*=UTF-8''{2}"
                    : "{0}; filename=\"{1}\"; filename*=UTF-8''{2}";

                return string.Format(str,
                                     inline ? "inline" : "attachment",
                                     fileName,
                                     CreateRfc2231HeaderValue(fileName));
            }

            // Knowing there are no Unicode characters in this fileName, rely on
            // ContentDisposition.ToString() to encode properly.
            // In .Net 4.0, ContentDisposition.ToString() throws FormatException if
            // the file name contains Unicode characters.
            // In .Net 4.5, ContentDisposition.ToString() no longer throws FormatException
            // if it contains Unicode, and it will not encode Unicode as we require here.
            // The Unicode test above is identical to the 4.0 FormatException test,
            // allowing this helper to give the same results in 4.0 and 4.5.         
            var disposition = new ContentDisposition { FileName = fileName, Inline = inline };
            return disposition.ToString();
        }
        private static string GetFileName(ContentDisposition contentDisposition)
        {
            if (contentDisposition.FileName != null)
            {
                return contentDisposition.FileName;
            }

            var fileName = contentDisposition.Parameters["filename*"];
            if (fileName == null)
            {
                return null;
            }

            var pos = fileName.IndexOf("''", StringComparison.InvariantCulture);
            var encoding = Encoding.UTF8;
            if (pos >= 0)
            {
                try
                {
                    encoding = Encoding.GetEncoding(fileName.Substring(0, pos));
                }
                catch (ArgumentException)
                {
                }
                fileName = fileName.Substring(pos + 2);
            }

            return HttpUtility.UrlDecode(fileName, encoding);
        }
		public void Equals ()
		{
			ContentDisposition dummy1 = new ContentDisposition ();
			dummy1.FileName = "genome.jpeg";
			ContentDisposition dummy2 = new ContentDisposition ("attachment; filename=genome.jpeg");
			Assert.IsTrue (dummy1.Equals (dummy2));
		}
Exemple #6
0
        // Create a new Exchange service object

        public static string SendExchangeMail(string clientEmailAddress, string fileLocation, string gmailUserNamne, string gmailPassword, string gmailFromAddress, string attachmentFilename, string clientName, string bodyType)
        {
            try
            {
                string emailBody = "";

                if (bodyType.ToLower() == "monthly")
                {
                    emailBody = HelperClasses.StringPropertyHelper.getMonthlyEmailBody(clientName);
                }
                else if (bodyType.ToLower() == "weekly")
                {
                    emailBody = HelperClasses.StringPropertyHelper.getMonthlyEmailBody(clientName);
                }
                else
                {
                    emailBody = HelperClasses.StringPropertyHelper.getMonthlyEmailBody(clientName);
                }

                // Command line argument must the the SMTP host.
                SmtpClient client = new SmtpClient();
                client.Port                  = 587;
                client.Host                  = "smtp.gmail.com";
                client.EnableSsl             = true;
                client.Timeout               = 10000;
                client.DeliveryMethod        = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Credentials           = new System.Net.NetworkCredential(gmailUserNamne, gmailPassword);

                MailMessage message     = new MailMessage();
                MailAddress fromAddress = new MailAddress(gmailFromAddress);
                message.From    = fromAddress;
                message.Subject = "LA Care Waste & Abuse Peer-to-Peer Report";
                message.Body    = emailBody;
                message.To.Add(clientEmailAddress);
                message.BodyEncoding = UTF8Encoding.UTF8;
                message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

                if (attachmentFilename != null)
                {
                    System.Net.Mail.Attachment         attachment  = new System.Net.Mail.Attachment(attachmentFilename, System.Net.Mime.MediaTypeNames.Application.Octet);
                    System.Net.Mime.ContentDisposition disposition = attachment.ContentDisposition;
                    disposition.CreationDate     = File.GetCreationTime(attachmentFilename);
                    disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
                    disposition.ReadDate         = File.GetLastAccessTime(attachmentFilename);
                    disposition.FileName         = Path.GetFileName(attachmentFilename);
                    disposition.Size             = new FileInfo(attachmentFilename).Length;
                    disposition.DispositionType  = DispositionTypeNames.Attachment;
                    message.Attachments.Add(attachment);
                }

                client.Send(message);

                return("success");
            }
            catch (Exception ex)
            {
                return(ex.InnerException.ToString());
            }
        }
Exemple #7
0
        public void DownloadBloodcatSet(string setID)
        {
            if (alreadyDownloading)
            {
                MessageBox.Show("Already downloading a beatmap. Parallel downloads are currently not supported, sorry :(");
                return;
            }

            form1.progressBar1.Visible = true;
            form1.button1.Enabled = false;
            alreadyDownloading = true;
            var downloadURL = "http://bloodcat.com/osu/s/" + setID;

            // https://stackoverflow.com/questions/13201059/howto-download-a-file-keeping-the-original-name-in-c
            // Get file name of beatmap (and test if its even valid)
            var request = WebRequest.Create(downloadURL);
            try
            {
                var response = request.GetResponse();
                ContentDisposition contentDisposition = new ContentDisposition(response.Headers["Content-Disposition"]); // using .net's mime.contentdisposition class
                originalFileName = contentDisposition.FileName.ToString();

                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(dlProgressHandler);
                client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(dlCompleteHandler);
                client.DownloadFileAsync(new Uri(downloadURL), Path.Combine(Application.StartupPath, originalFileName + ".partial"));
                // Download to a temp folder (program's folder) because if osu! detects semi downloaded it map it calls it corrupt and deletes/moves it ;-;
            }
            catch (Exception e)
            {
                MessageBox.Show("Invalid beatmap... maybe bloodcat doesn't have it, or you put in an invalid ID (in which case you are a jerk)?");
                form1.progressBar1.Visible = false;
                form1.dataGridView1.Enabled = true;
                alreadyDownloading = false;
            }
        }
        internal static ProvisioningTemplate GetTemplate(Guid templateId)
        {
            HttpContentHeaders headers = null;
            // Get the template via HTTP REST
            var templateStream = HttpHelper.MakeGetRequestForStreamWithResponseHeaders($"{BaseTemplateGalleryUrl}/api/DownloadTemplate?templateId={templateId}", "application/octet-stream", out headers);

            // If we have any result
            if (templateStream != null)
            {
                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(templateStream));
                var cd = new ContentDisposition(headers.ContentDisposition.ToString());
                var openXMLFileName = cd.FileName;

                // Determine the name of the XML file inside the PNP Open XML file
                var xmlTemplateFile = openXMLFileName.ToLower().Replace(".pnp", ".xml");

                // Get the template
                var result = provider.GetTemplate(xmlTemplateFile);
                result.Connector = provider.Connector;
                templateStream.Close();
                return result;

            }
            return null;
        }
Exemple #9
0
 public ActionResult ShowPdfFile(long? d)
 {
     Documentm doc=null;
     long DocNum=0;
     if(d!=null) {
         DocNum=(long)d;
     }
     Patientm patm;
     if(Session["Patient"]==null) {
         return RedirectToAction("Login");
     }
     else {
         patm=(Patientm)Session["Patient"];
     }
     if(DocNum!=0) {
         doc=Documentms.GetOne(patm.CustomerNum,DocNum);
     }
     if(doc==null || patm.PatNum!=doc.PatNum) {//make sure that the patient does not pass the another DocNum of another patient.
         return new EmptyResult(); //return a blank page todo: return page with proper message.
     }
     ContentDisposition cd = new ContentDisposition();
     cd.Inline=true;//the browser will try and show the pdf inline i.e inside the browser window. If set to false it will force a download.
     Response.AppendHeader("Content-Disposition",cd.ToString());
     return File(Convert.FromBase64String(doc.RawBase64),"application/pdf","Statement.pdf");
 }
Exemple #10
0
        public ActionResult DownloadFile(string filename)
        {
            try
            {
                byte[] filedata = _filesHelper.DownloadFile(filename);
                var    dir      = WebConfigurationManager.AppSettings["DirForFeedback"];
                string filepath = dir + filename;
                //byte[] filedata = System.IO.File.ReadAllBytes(filepath);
                string contentType = MimeMapping.GetMimeMapping(filepath);

                var cd = new System.Net.Mime.ContentDisposition
                {
                    FileName = filename,
                    Inline   = true,
                };

                Response.Headers.Add("Content-Disposition", cd.ToString());

                //View file
                //Download file
                //Öppnar excel
                return(File(filedata, contentType));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                ErrorManager.WriteToErrorLog("FileUploadController", "DownloadFile", e.ToString(), e.HResult, User.Identity.Name);
                var errorModel = new CustomErrorPageModel
                {
                    Information  = "Ett fel inträffade vid öppningen av återkopplingsfilen",
                    ContactEmail = ConfigurationManager.AppSettings["ContactEmail"],
                };
                return(View("CustomError", errorModel));
            }
        }
		/// <summary>
		/// Downloads a single file synchronously
		/// </summary>
		/// <param name="url">The URL to download the file from (either a fully qualified URL or an app relative/absolute path)</param>
		/// <param name="sendAuthCookie">Specifies whether the FormsAuthenticationCookie should be sent</param>
		/// <param name="timeout">Timeout in milliseconds</param>
		public FileDownloadResponse DownloadFile(string url, bool sendAuthCookie = false, int? timeout = null)
		{
			Guard.ArgumentNotEmpty(() => url);
			
			url = WebHelper.GetAbsoluteUrl(url, _httpRequest);

			var req = (HttpWebRequest)WebRequest.Create(url);
			req.UserAgent = "SmartStore.NET";

			if (timeout.HasValue)
			{
				req.Timeout = timeout.Value;
			}

			if (sendAuthCookie)
			{
				req.SetFormsAuthenticationCookie(_httpRequest);
			}

			using (var resp = (HttpWebResponse)req.GetResponse())
			{
				using (var stream = resp.GetResponseStream())
				{
					if (resp.StatusCode == HttpStatusCode.OK)
					{
						var data = stream.ToByteArray();
						var cd = new ContentDisposition(resp.Headers["Content-Disposition"]);
						var fileName = cd.FileName;
						return new FileDownloadResponse(data, fileName, resp.ContentType);
					}
				}
			}

			return null;
		}
		public void EqualsHashCode ()
		{
			ContentDisposition dummy1 = new ContentDisposition ();
			dummy1.Inline = true;
			ContentDisposition dummy2 = new ContentDisposition ("inline");
			Assert.IsTrue (dummy1.Equals (dummy2));
			Assert.IsFalse (dummy1 == dummy2);
			Assert.IsTrue (dummy1.GetHashCode () == dummy2.GetHashCode ());
		}
Exemple #13
0
        /// <summary>
        /// Creates MIME-protocols Content-disposition header.
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="inline"></param>
        /// <returns></returns>
        public ContentDisposition CreateContentDisposition(string filename, bool inline = false)
        {
            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = filename,
                Inline   = inline
            };

            return(cd);
        }
Exemple #14
0
 public ActionResult Export(string FileContent, string FileName)
 {
     var cd = new ContentDisposition
     {
         FileName = FileName + ".csv",
         Inline = false
     };
     Response.AddHeader("Content-Disposition", cd.ToString());
     return Content(FileContent, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
 }
Exemple #15
0
        public UploadedFile(string filename,
            ContentType contentType,
            ContentDisposition contentDisposition,
            string tempFilename)
        {
            ContentDisposition = contentDisposition;
              ContentType = contentType;

              Filename = filename;
              _tempFilename = tempFilename;
        }
 public SerializableContentDisposition(ContentDisposition contentDisposition)
 {
     CreationDate = contentDisposition.CreationDate;
     DispositionType = contentDisposition.DispositionType;
     FileName = contentDisposition.FileName;
     Inline = contentDisposition.Inline;
     ModificationDate = contentDisposition.ModificationDate;
     Parameters = new SerializableCollection(contentDisposition.Parameters);
     ReadDate = contentDisposition.ReadDate;
     Size = contentDisposition.Size;
 }
        public void CopyTo(ContentDisposition contentDisposition)
        {
            contentDisposition.CreationDate = CreationDate;
            contentDisposition.DispositionType = DispositionType;
            contentDisposition.FileName = FileName;
            contentDisposition.Inline = Inline;
            contentDisposition.ModificationDate = ModificationDate;
            contentDisposition.ReadDate = ReadDate;
            contentDisposition.Size = Size;

            Parameters.CopyTo(contentDisposition.Parameters);
        }
Exemple #18
0
        private static string GetFileName(HttpWebResponse response)
        {
            var contentDisposition = response.Headers["Content-Disposition"];
            if (contentDisposition.IsNullOrEmpty())
                return null;

            var disposition = new ContentDisposition(contentDisposition);
            if (disposition.FileName.IsNullOrEmpty())
                return null;

            return disposition.FileName;
        }
		private SerializableContentDisposition(ContentDisposition disposition) {
			CreationDate = disposition.CreationDate;
			DispositionType = disposition.DispositionType;
			FileName = disposition.FileName;
			Inline = disposition.Inline;
			ModificationDate = disposition.ModificationDate;
			Parameters = new StringDictionary();
			foreach (string k in disposition.Parameters.Keys)
				Parameters.Add(k, disposition.Parameters[k]);
			ReadDate = disposition.ReadDate;
			Size = disposition.Size;
		}
        internal void SetContentDisposition(ContentDisposition scd)
        {
            scd.CreationDate = CreationDate;
            scd.DispositionType = DispositionType;
            scd.FileName = FileName;
            scd.Inline = Inline;
            scd.ModificationDate = ModificationDate;
            Parameters.SetColletion(scd.Parameters);

            scd.ReadDate = ReadDate;
            scd.Size = Size;
        }
        public async Task <JsonResult> SaveProposalInfo(SendProposalViewModel viewModel)
        {
            var postedFileWithoutExtension = Path.GetFileNameWithoutExtension(viewModel.Attachment.FileName);

            viewModel.Proposal_File = Utilities.SaveImage(Server, viewModel.Attachment, postedFileWithoutExtension, Constant.FILE_PATH_FOR_LEADS_PROPOSAL);
            tbl_crm_leads updateLead = Mapper.Map <SendProposalViewModel, tbl_crm_leads>(viewModel);

            ResponseMessage responseMessage = await leadsManager.SaveProposalInfoAsync(updateLead).ConfigureAwait(false);

            if (responseMessage.Type == Constant.RESPONSE_MESSAGE_TYPE_SUCCESS)
            {
                var root     = Server.MapPath(Constant.FILE_PATH_FOR_LEADS_PROPOSAL);
                var fileName = viewModel.Proposal_File;
                var path     = Path.Combine(root, fileName);
                path = Path.GetFullPath(path);

                var message = new MailMessage();
                message.To.Add(new MailAddress(viewModel.To));                                            // replace with valid value
                message.From    = new MailAddress(ConfigurationManager.AppSettings["CRM_EMAIL_ADDRESS"]); // replace with valid value
                message.Subject = viewModel.Subject;
                message.Body    = viewModel.Message;
                Attachment attachment = new Attachment(path, MediaTypeNames.Application.Octet);
                System.Net.Mime.ContentDisposition disposition = attachment.ContentDisposition;
                message.Attachments.Add(attachment);

                message.IsBodyHtml = true;

                using (var smtp = new SmtpClient())
                {
                    var credential = new NetworkCredential
                    {
                        UserName = ConfigurationManager.AppSettings["CRM_EMAIL_ADDRESS"],  // replace with valid value
                        Password = ConfigurationManager.AppSettings["CRM_EMAIL_PASSWORD"]  // replace with valid value
                    };
                    smtp.Credentials = credential;
                    smtp.Host        = "smtp.gmail.com";
                    smtp.Port        = 587;
                    smtp.EnableSsl   = true;
                    await smtp.SendMailAsync(message);
                }

                return(new JsonResult {
                    Data = new { status = true }
                });
            }
            else
            {
                return(new JsonResult {
                    Data = new { status = false }
                });
            }
        }
        public Task SendRawEmail(string htmlBody, string subject, string[] to, string from, bool isHtmlBody, string attachedFileName, string fileContent)
        {
            AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlBody, Encoding.UTF8, "text/html");

            MailMessage mailMessage = new MailMessage();

            mailMessage.From = new MailAddress(from);
            mailMessage.To.Add(new MailAddress(to.FirstOrDefault()));

            mailMessage.Subject         = subject;
            mailMessage.SubjectEncoding = Encoding.UTF8;

            if (htmlBody != null)
            {
                mailMessage.AlternateViews.Add(htmlView);
            }

            if (attachedFileName.Trim() != "")
            {
                string folderName = "Attachment";
                string attachPath = Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot"), folderName);
                attachPath = (Path.Combine(attachPath, attachedFileName));

                if (System.IO.File.Exists(attachPath))
                {
                    try
                    {
                        System.Net.Mail.Attachment objAttach = new System.Net.Mail.Attachment(attachPath);
                        objAttach.ContentType = new ContentType(fileContent);
                        System.Net.Mime.ContentDisposition disposition = objAttach.ContentDisposition;
                        disposition.DispositionType  = "attachment";
                        disposition.CreationDate     = System.IO.File.GetCreationTime(attachPath);
                        disposition.ModificationDate = System.IO.File.GetLastWriteTime(attachPath);
                        disposition.ReadDate         = System.IO.File.GetLastAccessTime(attachPath);
                        mailMessage.Attachments.Add(objAttach);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            RawMessage          rawMessage = new RawMessage(ConvertMailMessageToMemoryStream(mailMessage));
            SendRawEmailRequest request    = new SendRawEmailRequest(rawMessage);

            Amazon.RegionEndpoint          regionEndPoint = Amazon.RegionEndpoint.USWest2;
            AmazonSimpleEmailServiceConfig config         = new AmazonSimpleEmailServiceConfig();

            config.RegionEndpoint = regionEndPoint;
            AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(_mailSettings.AwsAccessKeyId, _mailSettings.AwsSecretAccessKey, config);

            return(client.SendRawEmailAsync(request));
        }
        public ActionResult GeneratePDF()
        {
            var url = "http://www.google.com";
            byte[] pdfBuf = PDFHelper.ConvertToPdf(PDFHelper.DataType.URL, url, "DocumentTitle");

            var cd = new ContentDisposition
            {
                FileName = "DocName.pdf",
                Inline = false // always prompt the user for downloading, set to true if you want the browser to try to show the file inline
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());
            return File(pdfBuf, "application/pdf");
        }       
        public ActionResult DownloadExtension()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "/vss-extension.json";
            byte[] data = System.IO.File.ReadAllBytes(path);

            var header = new ContentDisposition
            {
                FileName = "vss-extension.json",
                Inline = false
            };

            Response.AppendHeader("Content-Disposition", header.ToString());

            return File(data, "application/force-download");
        }
Exemple #25
0
 public static string GetHeaderValue(string fileName)
 {
     try
     {
         ContentDisposition disposition = new ContentDisposition
         {
             FileName = fileName
         };
         return disposition.ToString();
     }
     catch (FormatException)
     {
         return CreateRfc2231HeaderValue(fileName);
     }
 }
 protected string GetHeaderValue(string fileName)
 {
    try
    {
       ContentDisposition contentDisposition = new ContentDisposition
                                                  {
                                                     FileName = fileName,
                                                     Inline = Inline
                                                  };
       return contentDisposition.ToString();
    }
    catch (FormatException ex)
    {
       return "FormatException";
    }
 }
Exemple #27
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = ContentType;
            if (!string.IsNullOrEmpty(FileDownloadName))
            {
                string str = new ContentDisposition { FileName = this.FileDownloadName, Inline = Inline }.ToString();
                context.HttpContext.Response.AddHeader("Content-Disposition", str);
            }

            WriteFile(response);
        }
Exemple #28
0
        ActionResult Download(Guid id, bool inline)
        {
            using (var db = ApplicationDbContext.Create())
            {
                ManagedFile file = db.Files.Where(x => x.Id == id)
                                   .Include(x => x.CatalogRecord)
                                   .Include(x => x.CatalogRecord.Organization).FirstOrDefault();
                if (file == null)
                {
                    //TODO error page?
                    return(RedirectToAction("Index"));
                }

                // For non-public files, or unpublished files, verify that the user should have access.
                // For public files, anybody can download.
                if (!file.IsPublicAccess ||
                    file.CatalogRecord.Status != CatalogRecordStatus.Published)
                {
                    EnsureUserIsAllowed(file.CatalogRecord, db);
                    EnsureUserCanDownload(file.CatalogRecord.Organization);
                }

                string processingDirectory = SettingsHelper.GetProcessingDirectory(file.CatalogRecord.Organization, db);
                string path = Path.Combine(processingDirectory, file.CatalogRecord.Id.ToString());
                path = Path.Combine(path, file.Name);

                // Use the PublicName as the downloaded file name.
                string fileDownloadName = file.Name;

                var cd = new System.Net.Mime.ContentDisposition
                {
                    FileName = fileDownloadName,
                    Inline   = inline,
                };
                Response.AppendHeader("Content-Disposition", cd.ToString());

                // Set the MIME type.
                string ext      = Path.GetExtension(cd.FileName).ToLower();
                string mimeType = MediaTypeNames.Application.Octet;
                if (ext == ".pdf")
                {
                    mimeType = MediaTypeNames.Application.Pdf;
                }

                return(File(path, mimeType));
            }
        }
Exemple #29
0
        /// <summary>
        /// Creates MIME-protocols Content-disposition header.
        /// </summary>
        /// <param name="filename">Name which will be added to header</param>
        /// <param name="file">physical file name</param>
        /// <param name="path">path to physical file</param>
        /// <param name="inline">inline or not</param>
        /// <returns></returns>
        public ContentDisposition CreateContentDisposition(string filename, string file, string path, bool inline = false)
        {
            var size = GetFileSize(path, file);

            if (!size.HasValue)
            {
                return(CreateContentDisposition(filename, inline));
            }
            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = filename,
                Inline   = inline,
                Size     = size.Value
            };

            return(cd);
        }
        //public ActionResult Install()
        //{
        //    return File(Url.Content("~/installChocolatey.ps1"), "text/plain");
        //}

        public FileResult InstallerBatchFile()
        {
            const string batchFile = @"@echo off
SET DIR=%~dp0%

%systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -ExecutionPolicy Bypass -Command ""((new-object net.webclient).DownloadFile('https://chocolatey.org/install.ps1','install.ps1'))""
%systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -ExecutionPolicy Bypass -Command ""& '%DIR%install.ps1' %*""
SET PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin";

            var contentDisposition = new ContentDisposition
            {
                FileName = "installChocolatey.cmd",
                Inline = true,
            };
            Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
            return File(Encoding.ASCII.GetBytes(batchFile), "text/plain");
        }
        internal static ContentDispositionWrapper GetSerializeableContentDisposition(ContentDisposition cd)
        {
            if (cd == null)
                return null;

            ContentDispositionWrapper scd = new ContentDispositionWrapper();
            scd._creationDate = cd.CreationDate;
            scd._dispositionType = cd.DispositionType;
            scd._fileName = cd.FileName;
            scd._inline = cd.Inline;
            scd._modificationDate = cd.ModificationDate;
          //  scd._parameters = CollectionWrapper.GetSerializeableCollection(cd.Parameters);            
            scd._readDate = cd.ReadDate;
            scd._size = cd.Size;

            return scd;
        }
        internal void SetContentDisposition(ContentDisposition scd)
        {
            scd.CreationDate = _creationDate;
            scd.DispositionType = _dispositionType;
            scd.FileName = _fileName;
            scd.Inline = _inline;
            if (_modificationDate <= DateTime.MinValue)
                _modificationDate = _creationDate;
            scd.ModificationDate = _modificationDate;
            
            //_parameters.SetColletion(scd.Parameters);

            if (_readDate <= DateTime.MinValue)
                _readDate = _creationDate;
            scd.ReadDate = _readDate;
            scd.Size = _size;
        }
        internal static SerializeableContentDisposition GetSerializeableContentDisposition(ContentDisposition cd)
        {
            if (cd == null)
                return null;

            var scd = new SerializeableContentDisposition();
            scd.CreationDate = cd.CreationDate;
            scd.DispositionType = cd.DispositionType;
            scd.FileName = cd.FileName;
            scd.Inline = cd.Inline;
            scd.ModificationDate = cd.ModificationDate;
            scd.Parameters = SerializeableCollection.GetSerializeableCollection(cd.Parameters);
            scd.ReadDate = cd.ReadDate;
            scd.Size = cd.Size;

            return scd;
        }
        /// <summary>
        /// Downloads exported image.
        /// </summary>
        /// <param name="key">Key.</param>
        /// <returns>Result.</returns>
        public ActionResult DownloadExportedImage(string key)
        {
            byte[]       fileData  = {};
            ActionResult ret       = null;
            string       extension = string.Empty;

            Api.Export.ExportKey exportKey        = null;
            string             fullPhysicalPath   = string.Empty;
            ContentDisposition contentDisposition = null;

            if (Api.Export.ExportKey.TryParse(key, out exportKey))
            {
                extension = System.Enum.GetName(typeof(Models.ImageExportFormat), exportKey.Format).ToLowerInvariant();

                fullPhysicalPath = System.Web.HttpContext.Current.Server.MapPath(string.Format("~/App_Data/Exports/{0}/{1}.{2}",
                                                                                               exportKey.PresentationId, exportKey.ToString(), extension));
            }

            if (System.IO.File.Exists(fullPhysicalPath))
            {
                fileData = ServiceAdapter.ImageToPdfComposer.TryCompose(fullPhysicalPath);

                if (fileData == null)
                {
                    fileData = System.IO.File.ReadAllBytes(fullPhysicalPath);
                    System.IO.File.Delete(fullPhysicalPath);
                }
            }

            contentDisposition = new System.Net.Mime.ContentDisposition()
            {
                FileName = string.Format("image.{0}", extension),
                Inline   = false
            };

            Response.AppendHeader("Content-Disposition", contentDisposition.ToString());

            Response.Headers.Remove("Cache-Control");
            Response.Headers.Remove("Pragma");
            Response.Headers.Remove("Expires");

            ret = File(fileData, "application/octet-stream");

            return(ret);
        }
    public void CopyTo(ContentDisposition disposition)
    {
      if (disposition == null)
        return;

      disposition.Inline = Inline;
      disposition.DispositionType = DispositionType;
      disposition.FileName = FileName;
      disposition.CreationDate = CreationDate;
      disposition.ModificationDate = ModificationDate;
      disposition.ReadDate = ReadDate;
      if (Size != -1L)
        disposition.Size = Size;

      foreach (string k in Parameters.Keys)
        if (disposition.Parameters.ContainsKey(k) == false)
          disposition.Parameters.Add(k, Parameters[k]);
    }
        public async Task <ActionResult> Download(Guid id, string format, string authToken)
        {
            using (var web = new System.Net.Http.HttpClient())
            {
                web.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authToken);

                var stream = await web.GetStreamAsync(WebConfigurationManager.AppSettings["ServiceUrl"] + "/response/ExportResponse?requestID=" + id + "&format=" + format);

                var contentDisposition = new System.Net.Mime.ContentDisposition
                {
                    FileName = "response." + format,
                    Inline   = false
                };
                Response.AppendHeader("Content-Disposition", contentDisposition.ToString());

                return(File(stream, "application/octet-stream"));
            }
        }
Exemple #37
0
        /// <summary>
        /// Renders the content.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="path">The path.</param>
        /// <param name="contentType">Type of the content.</param>
        /// <param name="inline">if set to <c>true</c> [inline].</param>
        /// <returns></returns>
        private ActionResult RenderContent(string fileName, string path, string contentType, bool inline)
        {
            string lowerpath = path.ToLower();

            if (lowerpath.StartsWith("http") || lowerpath.StartsWith("www"))
            {
                return(new RedirectResult(path));
            }

            ContentDisposition contentDisposition = new System.Net.Mime.ContentDisposition
            {
                FileName = fileName,
                Inline   = inline,
            };

            Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
            return(File(path, contentType));
        }
        /// <summary>
        /// Downloads the specified file by id.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public ActionResult Download(int id, Guid identityToken)
        {
            try
            {
                FileViewModel      file = _fileService.GetFileByIdAndIdentityToken(id, identityToken);
                ContentDisposition contentDisposition = new System.Net.Mime.ContentDisposition
                {
                    FileName = file.FileName,
                    Inline   = false,
                };

                Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
                return(File(file.Content, file.ContentType));
            }
            catch (Exception)
            {
                return(RedirectToAction("Index", "Home"));
            }
        }
	public override void ProcessRequest(HttpContext context)
	{
		if (!BXPrincipal.Current.IsCanOperate("UpdateSystem"))
		{
			BXAuthentication.AuthenticationRequired();
			return;
		}
		if (context.Request.QueryString["original"] != null)
		{
			System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition();
			cd.FileName = "web.config";

			context.Response.ContentType = "application/x-octet-stream";
			context.Response.AddHeader("Content-Disposition", cd.ToString());
			context.Response.TransmitFile(HostingEnvironment.MapPath("~/web.config"));			
			return;
		}
		if (context.Request.QueryString["convert4"] != null)
		{
			System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition();
			cd.FileName = "web.config";

			context.Response.ContentType = "application/x-octet-stream";
			context.Response.AddHeader("Content-Disposition", cd.ToString());
			context.Response.ContentEncoding = Encoding.UTF8;
			
			XmlWriterSettings ws = new XmlWriterSettings();
			ws.Indent = true;
			ws.IndentChars = "\t";
			ws.Encoding = Encoding.UTF8;			

			using (XmlWriter xml = XmlWriter.Create(context.Response.OutputStream, ws))
			{
				MakeConfig(xml);
			}

			context.Response.End();
			return;
		}
		
		base.ProcessRequest(context);
	}
        public FileResult Obtener_Archivo_Validado(String pSigString, String pNum_DNI)
        {
            String s_Nombre     = "Archivo_PDF_Verificado.pdf";
            String pRutaArchivo = string.Concat(System.Web.Hosting.HostingEnvironment.MapPath("~/DocumentosGenerados/"), "Firma_Electrina" + pNum_DNI + ".pdf");

            byte[] archivo = ObtenerArchivo_ValTopaz(pSigString, pRutaArchivo);
            if (archivo == null)
            {
                s_Nombre = "NO SE CUMPLE LAS VALIDACIONES PARA MOSTRAR EL ARCHIVO";
            }
            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName     = s_Nombre,
                Inline       = false,
                CreationDate = DateTime.Now
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());
            return(File(archivo, MediaTypeNames.Application.Octet));
        }
        public ActionResult Index(string filename, string ext)
        {
            if (string.IsNullOrEmpty(filename) || string.IsNullOrEmpty(ext)) return HttpNotFound();

            filename = filename + "." + ext;
            Document document = ReaderFactory.GetDocumentReader().GetDocument(filename);
            if (document == null)
            {
                return HttpNotFound();
            }
            
            var cd = new ContentDisposition
            {
                FileName = document.FileName,
                Inline = false,
            };
            Response.AppendHeader("Content-Disposition", cd.ToString());
            var contentType = GetContentType(document.FileName);
            return File(document.FileData, contentType);
        }
Exemple #42
0
        public void Test2()
        {
            var contentDispositionHeader = new System.Net.Mime.ContentDisposition()
            {
                FileName        = "foo bar.pdf",
                DispositionType = "attachment"
            };

            var result = contentDispositionHeader.ToString();

            _output.WriteLine(result);

            var parsed = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue.Parse(result);

            Assert.Equal("foo bar.pdf", parsed.FileName);

            var parsed0 = System.Net.Http.Headers.ContentDispositionHeaderValue.Parse(result);

            Assert.Equal("foo bar.pdf", parsed0.FileName);
        }
 public static void WriteResponse(HttpResponse response, byte[] filearray, string type)
 {
     response.ClearContent();
     response.Buffer = true;
     response.Cache.SetCacheability(HttpCacheability.Private);
     response.ContentType = "application/pdf";
     ContentDisposition contentDisposition = new ContentDisposition();
     contentDisposition.FileName = "SaldoDotacao.pdf";
     contentDisposition.DispositionType = type;
     response.AddHeader("Content-Disposition", contentDisposition.ToString());
     response.BinaryWrite(filearray);
     HttpContext.Current.ApplicationInstance.CompleteRequest();
     try
     {
         response.End();
     }
     catch (System.Threading.ThreadAbortException)
     {
     }
 }
Exemple #44
0
        public ActionResult GetCandidateReportPdf(long id)
        {
            // return link file of Candidate report
            long clientId = -1;

            if (!long.TryParse(Session["ClientId"].ToString(), out clientId))
            {
                return(RedirectToAction("ErrorDontHavePermission", "Error"));
            }
            var candidate = db.Candidates.FirstOrDefault(s => (s.CandidateId == id && s.ClientId == clientId));

            if (candidate == null)
            {
                return(RedirectToAction("ErrorDontHavePermission", "Error"));
            }
            try
            {
                var attachment = db.AttachmentFiles.Where(s => s.CandidateId == id).OrderByDescending(s => s.AttachmentFileId).Take(1).Single();
                if (attachment != null)
                {
                    byte[] filedata    = System.IO.File.ReadAllBytes(attachment.Link);
                    string contentType = MimeMapping.GetMimeMapping(attachment.Link);

                    var cd = new System.Net.Mime.ContentDisposition
                    {
                        FileName = attachment.FileName,
                        Inline   = true,
                    };

                    Response.AppendHeader("Content-Disposition", cd.ToString());

                    return(File(filedata, contentType));
                }

                return(RedirectToAction("Error", "Error"));
            }
            catch (Exception e)
            {
                return(RedirectToAction("Error", "Error"));
            }
        }
        public override void ExecuteResult(ControllerContext context) {
            if (context == null) {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = ContentType;

            if (!String.IsNullOrEmpty(FileDownloadName)) {
                // From RFC 2183, Sec. 2.3:
                // The sender may want to suggest a filename to be used if the entity is
                // detached and stored in a separate file. If the receiving MUA writes
                // the entity to a file, the suggested filename should be used as a
                // basis for the actual filename, where possible.
                ContentDisposition disposition = new ContentDisposition() { FileName = FileDownloadName };
                string headerValue = disposition.ToString();
                context.HttpContext.Response.AddHeader("Content-Disposition", headerValue);
            }

            WriteFile(response);
        }
Exemple #46
0
        public IActionResult Download(string docPath, bool?ieDownload)
        {
            string filename = Path.GetFileName(docPath);
            string filepath = docPath;

            byte[] filedata    = System.IO.File.ReadAllBytes(filepath);
            string contentType = MediaTypeNames.Application.Pdf;

            if (ieDownload == null || Convert.ToBoolean(ieDownload) == false)
            {
                var cd = new System.Net.Mime.ContentDisposition
                {
                    FileName = filename,
                    Inline   = false,
                };
                HttpContext.Response.Headers["Content-Disposition"] = cd.ToString();
            }


            return(File(filedata, contentType));
        }
Exemple #47
0
        public ActionResult DownloadVersion(Guid id, string sha)
        {
            using (var db = ApplicationDbContext.Create())
            {
                ManagedFile file = db.Files.Where(x => x.Id == id)
                                   .Include(x => x.CatalogRecord)
                                   .Include(x => x.CatalogRecord.Organization).FirstOrDefault();
                if (file == null)
                {
                    //TODO error page?
                    return(RedirectToAction("Index"));
                }

                EnsureUserIsAllowed(file.CatalogRecord, db);
                EnsureUserCanDownload(file.CatalogRecord.Organization);

                string processingDirectory = SettingsHelper.GetProcessingDirectory(file.CatalogRecord.Organization, db);
                string path = Path.Combine(processingDirectory, file.CatalogRecord.Id.ToString());


                using (var repo = new LibGit2Sharp.Repository(path))
                {
                    var blob = repo.Lookup <Blob>(sha);

                    var cd = new System.Net.Mime.ContentDisposition
                    {
                        FileName = file.Name,//always uses the current file name right now...
                        Inline   = false,
                        Size     = blob.Size
                    };

                    var contentStream = blob.GetContentStream();

                    Response.AppendHeader("Content-Disposition", cd.ToString());
                    return(new FileStreamResult(contentStream, "application/octet-stream"));
                }
            }
        }
        /// <summary>
        /// Downloads exported video.
        /// </summary>
        /// <param name="key">Key.</param>
        /// <returns>Result.</returns>
        public ActionResult DownloadExportedVideo(string key)
        {
            byte[]       fileData = {};
            ActionResult ret      = null;

            Api.Export.ExportKey exportKey        = null;
            string             fullPhysicalPath   = string.Empty;
            ContentDisposition contentDisposition = null;

            if (Api.Export.ExportKey.TryParse(key, out exportKey))
            {
                fullPhysicalPath = System.Web.HttpContext.Current.Server.MapPath(string.Format("~/App_Data/Exports/{0}/{1}.mp4",
                                                                                               exportKey.PresentationId, exportKey.ToString()));
            }

            if (System.IO.File.Exists(fullPhysicalPath))
            {
                fileData = System.IO.File.ReadAllBytes(fullPhysicalPath);
                System.IO.File.Delete(fullPhysicalPath);
            }

            contentDisposition = new System.Net.Mime.ContentDisposition()
            {
                FileName = "video.mp4",
                Inline   = false
            };

            Response.AppendHeader("Content-Disposition", contentDisposition.ToString());

            Response.Headers.Remove("Cache-Control");
            Response.Headers.Remove("Pragma");
            Response.Headers.Remove("Expires");

            ret = File(fileData, "application/octet-stream");

            return(ret);
        }
Exemple #49
0
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="content"></param>
        /// <param name="attachmentPath"></param>
        /// <param name="email"></param>
        public void SendMailMessage(UserMailViewEntity mailEntity, CompanyEmailAccountEntity emailAccountEntity)
        {
            string remark = string.Empty;

            #region 发送前错误判断 (提前判断错误,会很大提升性能)
            if (string.IsNullOrEmpty(mailEntity.EMail))
            {
                remark = "当前用户没有填写邮箱";
                bllMail.UpdateSendStatus(mailEntity.MailID, remark, UserMailStatus.SendFail);
                return;
            }

            if (!mailFormatReg.IsMatch(mailEntity.EMail))
            {
                remark = "当前用户邮箱格式错误";
                bllMail.UpdateSendStatus(mailEntity.MailID, remark, UserMailStatus.SendFail);
                return;
            }

            if (string.IsNullOrEmpty(mailEntity.BookListPath))
            {
                remark = "当前所属文章附件没有设置文件路径";
                bllMail.UpdateSendStatus(mailEntity.MailID, remark, UserMailStatus.SendFail);
                return;
            }
            #endregion

            MailMessage message      = null;
            SmtpClient  client       = null;
            Attachment  myAttachment = null;
            try
            {
                //设置 收件人和发件人地址
                MailAddress from = new MailAddress(emailAccountEntity.EmailName, sendName);
                MailAddress to   = new MailAddress(mailEntity.EMail, mailEntity.LoginName);

                message = new MailMessage(from, to);

                string attachPath = attachDomain + mailEntity.BookListPath;
                if (File.Exists(attachPath))
                {
                    FileInfo fileInfo = new FileInfo(attachPath);
                    myAttachment = new Attachment(attachPath, MediaTypeNames.Application.Octet);
                    //MIME协议下的一个对象,用以设置附件的创建时间,修改时间以及读取时间
                    System.Net.Mime.ContentDisposition disposition = myAttachment.ContentDisposition;
                    disposition.CreationDate     = File.GetCreationTime(attachPath);
                    disposition.ModificationDate = File.GetLastWriteTime(attachPath);
                    disposition.ReadDate         = File.GetLastAccessTime(attachPath);
                    disposition.FileName         = fileInfo.Name;;
                }
                else
                {
                    remark = "该附件存在";
                    bllMail.UpdateSendStatus(mailEntity.MailID, remark, UserMailStatus.SendFail);
                    return;
                }

                message.Attachments.Add(myAttachment);
                message.Subject      = "开卷网络附带书单";
                message.Body         = "书单测试主体";
                message.BodyEncoding = Encoding.GetEncoding("gb2312");
                message.IsBodyHtml   = true;
                message.Priority     = MailPriority.High;

                client         = new SmtpClient();
                client.Timeout = 100000;
                client.Host    = emailAccountEntity.EmailSMTPHost;
                client.UseDefaultCredentials = false;
                client.Credentials           = new NetworkCredential(emailAccountEntity.EmailName, emailAccountEntity.EmailPassword);
                client.DeliveryMethod        = SmtpDeliveryMethod.Network;

                client.Send(message);

                remark = "发送成功";
                bllMail.UpdateSendStatus(mailEntity.MailID, remark, UserMailStatus.SendSuccess);
                Interlocked.Increment(ref successMailNum);
            }
            catch (Exception ex)
            {
                remark = "发送失败";
                bllMail.UpdateSendStatus(mailEntity.MailID, remark, UserMailStatus.SendFail);
                LogUtilExpand.WriteLog("邮件ID:" + mailEntity.MailID + "发送失败(异常信息如下:)");
                LogUtilExpand.WriteLog(ex);

                if (message != null)
                {
                    message.Dispose();
                }

                if (client != null)
                {
                    client.Dispose();
                }
            }
        }
Exemple #50
0
        public async Task <IActionResult> Get(string id)
        {
            try
            {
                var fileInfo = await filesService.GetFileInfoAsync(id).ConfigureAwait(false);

                if (fileInfo == null)
                {
                    var nodeConnections = connectionsService.GetNodeConnections().Where(conn => conn.NodeWebSocket.State == WebSocketState.Open);
                    foreach (var nodeConnection in nodeConnections)
                    {
                        var filesInfo = await nodeRequestSender.GetFilesInformationAsync(new List <string> {
                            id
                        }, nodeConnection.Node.Id).ConfigureAwait(false);

                        if (!filesInfo.Any())
                        {
                            continue;
                        }
                        Uri fileUri     = new Uri($"https://{nodeConnection.Node.Domains.FirstOrDefault()}:{nodeConnection.Node.NodesPort}/api/Files/{id}");
                        var fileRequest = WebRequest.CreateHttp(fileUri);
                        fileRequest.Method = HttpMethods.Get;
                        var fileResponse = (HttpWebResponse)await fileRequest.GetResponseAsync().ConfigureAwait(false);

                        var    contentDisposition = fileResponse.Headers["content-disposition"];
                        string filename           = id;
                        if (contentDisposition != null)
                        {
                            System.Net.Mime.ContentDisposition disposition = new System.Net.Mime.ContentDisposition(contentDisposition);
                            filename = disposition.FileName;
                        }
                        return(File(fileResponse.GetResponseStream(), MediaTypeNames.Application.Octet, filename));
                    }
                    return(StatusCode(StatusCodes.Status404NotFound));
                }
                if (fileInfo.Storage == "Local" || string.IsNullOrWhiteSpace(fileInfo.Storage))
                {
                    LocalFileStorage localFileStorage = new LocalFileStorage();
                    if (fileInfo != null && fileInfo.Url != null)
                    {
                        return(File(await localFileStorage.GetStreamAsync(fileInfo.Url).ConfigureAwait(false), MediaTypeNames.Application.Octet, fileInfo.FileName));
                    }
                    else if (fileInfo != null && fileInfo.Url == null && fileInfo.NodeId != NodeSettings.Configs.Node.Id)
                    {
                        NodeVm nodeInformation = await nodesService.GetAllNodeInfoAsync(fileInfo.NodeId).ConfigureAwait(false);

                        Uri fileUri     = new Uri($"https://{nodeInformation.Domains.FirstOrDefault()}:{nodeInformation.NodesPort}/api/Files/{fileInfo.Id}");
                        var fileRequest = WebRequest.CreateHttp(fileUri);
                        fileRequest.Method = HttpMethods.Get;
                        var fileResponse = await fileRequest.GetResponseAsync().ConfigureAwait(false);

                        return(File(fileResponse.GetResponseStream(), MediaTypeNames.Application.Octet, fileInfo.FileName));
                    }
                    else
                    {
                        return(NotFound());
                    }
                }
                else if (!string.IsNullOrWhiteSpace(fileInfo.Storage))
                {
                    var stream = await fileStorage.GetStreamAsync(fileInfo.Id).ConfigureAwait(false);

                    return(File(stream, MediaTypeNames.Application.Octet, fileInfo.FileName));
                }
                else
                {
                    return(NotFound());
                }
            }
            catch (DownloadFileException ex)
            {
                if (ex.InnerException is WebException webException)
                {
                    Console.WriteLine(ex.InnerException.ToString());
                    return(StatusCode(StatusCodes.Status503ServiceUnavailable));
                }
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
            catch (ObjectDoesNotExistsException)
            {
                return(NotFound());
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
        internal static SerializeableContentDisposition GetSerializeableContentDisposition(System.Net.Mime.ContentDisposition cd)
        {
            if (cd == null)
            {
                return(null);
            }

            SerializeableContentDisposition scd = new SerializeableContentDisposition();

            scd.CreationDate     = cd.CreationDate;
            scd.DispositionType  = cd.DispositionType;
            scd.FileName         = cd.FileName;
            scd.Inline           = cd.Inline;
            scd.ModificationDate = cd.ModificationDate;
            scd.Parameters       = SerializeableCollection.GetSerializeableCollection(cd.Parameters);
            scd.ReadDate         = cd.ReadDate;
            scd.Size             = cd.Size;

            return(scd);
        }
Exemple #52
0
        public async Task Invoke(HttpContext httpContext)
        {
            ClearCacheIfTimeout();

            Stream oldStream = httpContext.Response.Body;
            Stream memStream = null;
            int    imageId   = -1;

            try
            {
                // (other middleware) => (we're here) => MVC
                var      endpointFeature = httpContext.Features[typeof(IEndpointFeature)] as IEndpointFeature;
                Endpoint endpoint        = endpointFeature?.Endpoint;

                if (endpoint != null)
                {
                    var descriptor = endpoint.Metadata.GetMetadata <ControllerActionDescriptor>();
                    if (descriptor?.ControllerName == ImageCachingOptions.ControllerName && descriptor?.ActionName == ImageCachingOptions.ActionName)
                    {
                        imageId = Convert.ToInt32(httpContext.Request.RouteValues["id"]);
                        var      dirInfo = new DirectoryInfo(ImageCachingOptions.CacheDirectoryPath);
                        FileInfo file    = dirInfo.GetFiles(imageId + "_*.bmp").FirstOrDefault();
                        if (file != null)
                        {
                            int underscoreIndex = file.Name.IndexOf('_');
                            var cd = new System.Net.Mime.ContentDisposition
                            {
                                FileName = file.Name.Substring(underscoreIndex + 1),
                                Inline   = false
                            };
                            httpContext.Response.Headers.Add("Content-Disposition", cd.ToString());

                            using (var img = Image.Load(file.FullName))
                            {
                                // For production application we would recommend you create a FontCollection
                                // singleton and manually install the ttf fonts yourself as using SystemFonts
                                // can be expensive and you risk font existing or not existing on a deployment
                                // by deployment basis.
                                Font font = SystemFonts.CreateFont("Arial", 10);

                                using (var img2 = img.Clone(ctx => ApplyScalingWaterMarkSimple(ctx, font, "This is from cache", Color.White, 5)))
                                {
                                    using var m = new MemoryStream();
                                    img2.Save(m, new SixLabors.ImageSharp.Formats.Bmp.BmpEncoder());
                                    m.Seek(0, SeekOrigin.Begin);
                                    await m.CopyToAsync(httpContext.Response.Body);
                                }
                            }
                            lastCacheHit = DateTime.UtcNow;
                            return;
                        }
                        else
                        {
                            memStream = new MemoryStream();
                            httpContext.Response.Body = memStream;
                        }
                    }
                }


                await Next(httpContext);

                // (other middleware) <= (we're here) <= MVC
                // here we can save the image in the cache
                if (memStream != null && httpContext.Response.ContentType == "image/bmp")
                {
                    var dirInfo = new DirectoryInfo(ImageCachingOptions.CacheDirectoryPath);
                    if (dirInfo.GetFileSystemInfos("*.bmp").Length >= ImageCachingOptions.CacheCapacity)
                    {
                        return;
                    }
                    if (httpContext.Response.Headers.TryGetValue("Content-Disposition", out var values))
                    {
                        var cd   = new ContentDisposition(values);
                        var path = Path.Combine(ImageCachingOptions.CacheDirectoryPath, imageId + "_" + cd.FileName);
                        using var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
                        memStream.Position   = 0;
                        await memStream.CopyToAsync(fileStream);

                        lastCacheHit = DateTime.UtcNow;
                    }
                }
            }
            finally
            {
                if (memStream != null)
                {
                    memStream.Position = 0;
                    await memStream.CopyToAsync(oldStream);

                    httpContext.Response.Body = oldStream;
                }
            }
        }
Exemple #53
0
        public object SendEmailAsync(TblRecieveEmail objSendEmail)
        {
            var             response    = new { Code = 0 };
            string          errorEmail  = "";
            TblEmailConfigs emailConfig = db.TblEmailConfigs.FirstOrDefault <TblEmailConfigs>();

            #region add list to send email
            List <TblRecieveEmail> lstRecieveEmail = new List <TblRecieveEmail>();
            lstRecieveEmail.Add(new TblRecieveEmail()
            {
                From           = emailConfig.UserName,
                To             = objSendEmail.To,
                Bcc            = objSendEmail.Bcc,
                Cc             = objSendEmail.Cc,
                Subject        = objSendEmail.Subject,
                SendDate       = objSendEmail.SendDate,
                EmailContents  = objSendEmail.EmailContents,
                IsDelete       = objSendEmail.IsDelete,
                CreateBy       = objSendEmail.CreateBy,
                UserId         = objSendEmail.UserId,
                OrganizationId = objSendEmail.OrganizationId,
                StepStatus     = objSendEmail.StepStatus,
                StatusEmail    = objSendEmail.StatusEmail,
                IsConfirm      = objSendEmail.IsConfirm,
                AttachFile     = objSendEmail.AttachFile,
                CreateDate     = DateTime.Now,
            });
            #endregion
            try
            {
                SmtpClient client  = CommonFunction.InstanceSendClient();
                string[]   emailCC = objSendEmail.Cc != null?objSendEmail.Cc.Split(';') : null;

                using (var emailMessage = new MailMessage())
                {
                    emailMessage.To.Add(new MailAddress(objSendEmail.To));
                    if (emailCC != null)
                    {
                        foreach (var item in emailCC)
                        {
                            if (!string.IsNullOrEmpty(item))
                            {
                                emailMessage.CC.Add(new MailAddress(item));
                            }
                        }
                    }

                    emailMessage.From    = new MailAddress(emailConfig.UserName);
                    emailMessage.Subject = objSendEmail.Subject;
                    //Models.Common.CommonFunction.strDomainCV +
                    string imgUrl = AccountManagement.Common.CommonFunction.strDomainCV + emailConfig.Signature;
                    string img    = "<p></br><img src='" + imgUrl + "'></img></p>";
                    emailMessage.Body       = objSendEmail.EmailContents + img;
                    emailMessage.IsBodyHtml = true;

                    if (!string.IsNullOrEmpty(objSendEmail.AttachFile))
                    {
                        string[] attached = objSendEmail.AttachFile.Split(';');
                        if (attached != null)
                        {
                            for (int i = 0; i < attached.Count(); i++)
                            {
                                string       filepath = attached[i];
                                FileStream   fs       = new FileStream(AccountConstant.PathURL + filepath, FileMode.Open, FileAccess.Read);
                                StreamReader s        = new StreamReader(fs);
                                s.Close();
                                fs = new FileStream(AccountConstant.PathURL + filepath, FileMode.Open, FileAccess.Read);
                                System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(MediaTypeNames.Text.Plain);
                                Attachment attachment          = new Attachment(fs, ct);
                                attachment.ContentDisposition.Inline = true;
                                System.Net.Mime.ContentDisposition disposition = attachment.ContentDisposition;
                                disposition.CreationDate     = File.GetCreationTime(AccountConstant.PathURL + filepath);
                                disposition.ModificationDate = File.GetLastWriteTime(AccountConstant.PathURL + filepath);
                                disposition.ReadDate         = File.GetLastAccessTime(AccountConstant.PathURL + filepath);
                                disposition.FileName         = Path.GetFileName(AccountConstant.PathURL + filepath);
                                disposition.Size             = new FileInfo(AccountConstant.PathURL + filepath).Length;
                                disposition.DispositionType  = DispositionTypeNames.Attachment;
                                emailMessage.Attachments.Add(attachment);
                            }
                        }
                    }
                    try
                    {
                        client.Send(emailMessage);
                    }
                    catch (SmtpFailedRecipientException ex)
                    {
                        SmtpStatusCode statusCode = ex.StatusCode;
                        errorEmail = ex.StatusCode.ToString();
                        if (statusCode == SmtpStatusCode.MailboxBusy || statusCode == SmtpStatusCode.MailboxUnavailable || statusCode == SmtpStatusCode.TransactionFailed)
                        {
                            // wait 5 seconds, try a second time
                            Thread.Sleep(5000);
                            client.Send(emailMessage);
                        }
                        else
                        {
                            throw;
                        }
                    }
                    finally
                    {
                        if (lstRecieveEmail.Count > 0)
                        {
                            db.TblRecieveEmail.AddRange(lstRecieveEmail);
                            db.SaveChanges();
                            if (errorEmail == SmtpStatusCode.MailboxBusy.ToString() || errorEmail == SmtpStatusCode.MailboxUnavailable.ToString() || errorEmail == SmtpStatusCode.TransactionFailed.ToString())
                            {
                                response = new { Code = 2 };
                            }
                            else
                            {
                                response = new { Code = 1 };
                            }
                        }
                        emailMessage.Dispose();
                    }
                }
                #region lưu các email đã gửi đi
                #endregion
                return(response);
            }
            catch (Exception ex)
            {
                return(response);

                throw ex;
            }
        }
        public ActionResult InvoiceDigitalSignPDF(long obId)
        {
            string url         = ConfigurationManager.AppSettings.Get("InvoicePDFPreview") + obId.ToString();
            String pfxPath     = ConfigurationManager.AppSettings.Get("PFXFileForInvoice");
            string pfxpassword = ConfigurationManager.AppSettings.Get("PFXFileForInvoiceKey");

            // PdfDocument pdf = new PdfDocument();
            CLayer.Invoice data     = BLayer.Invoice.GetInvoiceByOfflineBooking(obId);
            string         filename = "";

            if (data.InvoiceNumber == "")
            {
                filename = "Invoice_" + data.InvoiceId.ToString() + ".pdf";
            }
            else
            {
                filename = "Invoice_" + data.InvoiceNumber + ".pdf";
            }

            string filepath = Server.MapPath(INVOICE_FOLDER) + filename;

            //var thread = new Thread(() => pdf.LoadFromHTML(url, false, false, false));
            //thread.SetApartmentState(ApartmentState.STA);
            //thread.Start();
            //thread.Join();

            WebClient wc = new WebClient();

            wc.DownloadFile(url, filepath);


            // pdf.SaveToFile(filepath);
            //pdf.PageSettings.Margins.Top = 2.2F;
            //pdf.PageSettings.Margins.Left = 2.2F;
            //pdf.PageSettings.Margins.Right = 2.2F;
            // pdf.Close();

            //pdf = new PdfDocument();
            PdfDocument pdf = new PdfDocument();

            pdf.LoadFromFile(filepath);

            PdfCertificate digi      = new PdfCertificate(pfxPath, pfxpassword);
            PdfSignature   signature = new PdfSignature(pdf, pdf.Pages[0], digi, "Staybazar.com");

            signature.ContactInfo         = "Staybazar.com";
            signature.Certificated        = true;
            signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges;

            pdf.SaveToFile(filepath);
            pdf.Close();


            byte[] filedata    = System.IO.File.ReadAllBytes(filepath);
            string contentType = MimeMapping.GetMimeMapping(filepath);

            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = filename,
                Inline   = true,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());

            return(File(filedata, contentType));
        }
Exemple #55
0
    /// <summary>
    /// 发送电子邮件函数
    /// </summary>
    /// <param name="txtHost">电子邮件服务主机名称</param>
    /// <param name="txtFrom">发送人地志</param>
    /// <param name="txtPass">发信人密码</param>
    /// <param name="txtTo">收信人地址</param>
    /// <param name="txtSubject">邮件标题</param>
    /// <param name="txtBody">邮件内容</param>
    /// <param name="isBodyHtml">是否采用HTML编码</param>
    /// <param name="priority">电子邮件的优先级别</param>
    /// <param name="encoding">内容采用的编码方式</param>
    /// <param name="files">附件(可选填)</param>
    /// <returns>操作结果</returns>
    public static string SendMail(string txtHost, string txtFrom, string txtPass, string txtTo, string txtSubject, string txtBody, bool isBodyHtml, MailPriority priority, System.Text.Encoding encoding, params string[] files)
    {
        //电子邮件附件
        Attachment data = null;
        //传送的电子邮件类
        MailMessage message = new MailMessage(txtFrom, txtTo);

        //设置标题
        message.Subject = txtSubject;
        //设置内容
        message.Body = txtBody;
        //是否采用HTML编码
        message.IsBodyHtml = isBodyHtml;
        //电子邮件的优先级别
        message.Priority = priority;
        //内容采用的编码方式
        message.BodyEncoding = encoding;
        try
        {
            //添加附件
            if (files.Length > 0 && files != null)
            {
                for (int i = 0; i < files.Length; i++)
                {
                    //实例话电子邮件附件,并设置类型
                    data = new Attachment(files[i], System.Net.Mime.MediaTypeNames.Application.Octet);
                    //实例邮件内容
                    System.Net.Mime.ContentDisposition disposition = data.ContentDisposition;
                    //取得建档日期
                    disposition.CreationDate = System.IO.File.GetCreationTime(files[i]);
                    //取得附件修改日期
                    disposition.ModificationDate = System.IO.File.GetLastWriteTime(files[i]);
                    //取得读取日期
                    disposition.ReadDate = System.IO.File.GetLastAccessTime(files[i]);
                    //设定文件名称
                    System.IO.FileInfo fi = new System.IO.FileInfo(files[i]);
                    disposition.FileName = fi.Name.ToString();
                    //添加附件
                    message.Attachments.Add(data);
                }
            }
            //实例从送电子邮件类
            SmtpClient client = new SmtpClient();
            client.EnableSsl             = true;
            client.UseDefaultCredentials = false;
            //设置电子邮件主机名称
            client.Host = txtHost;

            //取得寄信人认证
            client.Credentials = new NetworkCredential(txtFrom, txtPass);
            //发送电子邮件
            client.Send(message);
            return("OK");
        }
        catch (Exception Err)
        {
            //返回错误信息
            return(Err.Message);
        }
        finally
        {
            //销毁电子邮件附件
            if (data != null)
            {
                data.Dispose();
            }
            //销毁传送的电子邮件实例
            message.Dispose();
        }
    }
Exemple #56
0
 bool Equals(ContentDisposition other)
 {
     return(other != null && ToString() == other.ToString());
 }
Exemple #57
0
        static List <Archive> GetResponse(string url)
        {
            List <Archive> archives = new List <Archive>();
            int            count    = 0;
            int            y        = Console.CursorTop;
            int            x        = Console.CursorLeft;
            Thread         t        = new Thread(() => DisplayWaiting());

            try
            {
                t.Start();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        string line, original, urlId, timestamp, fileName, localPath, localPathTimestamp;
                        Uri    uri;
                        while ((line = reader.ReadLine()) != null)
                        {
                            urlId     = @webUrl + line.Split(' ')[2] + "id_/" + @line.Split(' ')[3];
                            timestamp = line.Split(' ')[2];
                            fileName  = urlId.Split('/')[urlId.Split('/').Length - 1].Split('?')[0];
                            original  = @line.Split(' ')[3];

                            uri = new Uri(original);


                            if (urlId.EndsWith("/") || !fileName.Contains("."))
                            {
                                fileName = defaultIndexFile;
                            }


                            if (!string.IsNullOrEmpty(response.GetResponseHeader("content-disposition")))
                            {
                                System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition(response.GetResponseHeader("content-disposition"));
                                fileName = cd.FileName;
                            }

                            localPath  = uri.Host + "/" + uri.AbsolutePath.Replace(fileName, "");
                            localPath += HttpUtility.UrlEncode(uri.Query.Replace("?", ""));
                            localPath += "/" + fileName;
                            localPath  = localPath.Replace("//", "/");
                            localPath  = string.Join("_", localPath.Split(':', '*', '?', '"', '<', '>', '|'));

                            localPathTimestamp  = uri.Host + "/" + timestamp + uri.AbsolutePath.Replace(fileName, "");
                            localPathTimestamp += HttpUtility.UrlEncode(uri.Query.Replace("?", ""));
                            localPathTimestamp += "/" + fileName;
                            localPathTimestamp  = localPathTimestamp.Replace("//", "/");

                            archives.Add(new Archive()
                            {
                                UrlKey             = line.Split(' ')[0],
                                Timestamp          = long.Parse(timestamp),
                                Original           = original,
                                Digest             = line.Split(' ')[1],
                                MimeType           = line.Split(' ')[4],
                                StatusCode         = line.Split(' ')[5],
                                Length             = int.Parse(line.Split(' ')[6]),
                                UrlId              = urlId,
                                Filename           = fileName,
                                LocalPath          = localPath,
                                LocalPathTimestamp = localPathTimestamp
                            });
                            count++;
                        }

                        Console.SetCursorPosition(x, y);
                        Console.Write(" ".PadRight(Console.WindowWidth, ' '));
                        Console.SetCursorPosition(x, y);
                        Console.WriteLine("Found " + archives.Count + " total item(s).       ");
                        Console.WriteLine(" with " + GetLatestOnly(archives).Count + " unique/latest item(s).       ");
                        Console.WriteLine();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.SetCursorPosition(x, y);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
            }
            finally
            {
                t.Abort();
                t.Join();
                Console.ResetColor();
            }
            return(archives);
        }
Exemple #58
0
        public ActionResult sendFileThoughMail(string reciverEmailAddress, int FileId)
        {
            MembershipHelp mHelp = new MembershipHelp(); var role = mHelp.logingUserRole(User.Identity.Name);
            var            roleId  = db.RoleMasters.Where(w => w.Name == role).Select(s => s.Id).FirstOrDefault();
            var            canEdit = (from m in db.MenuInfoes join rm in db.RoleMenuMappings on m.Id equals rm.MenuInfoId where m.MenuURL.Contains("ArtWorks") && rm.RoleId == roleId select rm.CanEdit).FirstOrDefault();

            if (!canEdit)
            {
                return(RedirectToAction("Index"));
            }

            string returnString = "";
            var    saftyModel   = db.SafetyModels.FirstOrDefault();

            for (int l = 0; l < 2; l++)
            {
                var body = "";

                if (l == 1)
                {
                    body = "Email is sent To " + reciverEmailAddress + " using the Login Id = " + User.Identity.Name.ToString();
                }

                if (l == 1)
                {
                    reciverEmailAddress = saftyModel.Email;
                }

                var senderEmail   = new MailAddress(saftyModel.Email, "Interior Design Firm");
                var receiverEmail = new MailAddress(reciverEmailAddress, "Interior Desgin");

                var password = saftyModel.MailPassword;
                var FileName = "File is attached ";

                string beginHtmlTag = "<html><head></head><body>";
                body = body + "<BR> Please , have a look on the attached file";
                string endHtmlTag = "</body></html>";
                var    smtp       = new SmtpClient
                {
                    Host                  = "smtp.gmail.com",
                    Port                  = 587,
                    EnableSsl             = true,
                    DeliveryMethod        = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials           = new NetworkCredential(senderEmail.Address, password)
                };
                using (var mess = new MailMessage(senderEmail, receiverEmail)
                {
                    Subject = FileName,
                    Body = beginHtmlTag + body + endHtmlTag
                })
                {
                    mess.IsBodyHtml = true;
                    try
                    {
                        if (FileId.ToString() != string.Empty)
                        {
                            var    artWork       = db.ArtWorks.Where(w => w.Id == FileId).FirstOrDefault();
                            var    FileAddress   = Path.Combine(Server.MapPath("~/Content/Uploads/Originals"), artWork.FileAddressInfo);
                            string fileExtension = Path.GetExtension(FileAddress);

                            if (fileExtension.ToString().ToUpper() == ".EXE" || fileExtension.ToString().ToUpper() == ".DLL" || fileExtension.ToString().ToUpper() == ".ZIP")
                            {
                                return(RedirectToAction("Index"));
                            }

                            string filepath = FileAddress;
                            byte[] filedata = System.IO.File.ReadAllBytes(filepath);
                            // check if the file size is greater than 25 mb
                            if (26214400 < filedata.Length)
                            {
                                returnString = "File size can not be greater than 25 MB";
                                int trhoughException = 1 / Convert.ToInt32("0");
                            }

                            string contentType = MimeMapping.GetMimeMapping(filepath);

                            var cd = new System.Net.Mime.ContentDisposition
                            {
                                FileName = artWork.FileAddressInfo,
                                Inline   = false
                            };
                            Response.AppendHeader("Content-Disposition", cd.ToString());

                            MemoryStream ms = new MemoryStream(File(filedata, contentType).FileContents);

                            mess.Attachments.Add(new Attachment(ms, artWork.FileAddressInfo, contentType));
                            smtp.Send(mess);
                            returnString = "Mail is sent to " + reciverEmailAddress;
                        }
                    }
                    catch (Exception ex)
                    {
                        if (returnString == "")
                        {
                            returnString = "Please , Check the Net Connection or Email Address";
                        }
                    }
                }
            }

            return(Json(returnString, JsonRequestBehavior.AllowGet));
        }
Exemple #59
0
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="mailContent">内容</param>
        /// <param name="mailContent">路径</param>
        /// <returns></returns>
        public bool SendEmailff(string title, string mailContent, string path)
        {
            string        emailRecipient     = System.Configuration.ConfigurationManager.AppSettings["EmailRecipientList"];
            List <string> emailRecipientList = emailRecipient.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList <string>();
            string        ccRecipient        = System.Configuration.ConfigurationManager.AppSettings["CcRecipientList"];
            List <string> ccRecipientList    = ccRecipient.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList <string>();

            MailMessage msg = new MailMessage();

            foreach (string e in emailRecipientList)
            {
                msg.To.Add(e.Trim());
            }
            if (ccRecipientList != null && ccRecipientList.Count > 0)
            {
                foreach (string c in ccRecipientList)
                {
                    msg.CC.Add(c.Trim());
                }
            }

            if (path != string.Empty)
            {
                //添加附件
                System.Net.Mail.Attachment myAttachment = new System.Net.Mail.Attachment(
                    path, System.Net.Mime.MediaTypeNames.Application.Octet);
                //MIME协议下的一个对象,用以设置附件的创建时间,修改时间以及读取时间
                System.Net.Mime.ContentDisposition disposition = myAttachment.ContentDisposition;
                //用smtpclient对象里attachments属性,添加上面设置好的myattachment
                msg.Attachments.Add(myAttachment);
            }

            MailAddress fromAddr = new MailAddress(this.EmailAccount);

            msg.From = fromAddr;
            // msg.From = new MailAddress("*****@*****.**", "邮件", System.Text.Encoding.UTF8);
            msg.Subject = title;                             //邮件标题

            msg.SubjectEncoding = System.Text.Encoding.UTF8; //邮件标题编码
            msg.Body            = mailContent;               //邮件内容
            msg.BodyEncoding    = System.Text.Encoding.UTF8; //邮件内容编码
            msg.IsBodyHtml      = false;                     //是否是HTML邮件
            msg.Priority        = MailPriority.Normal;       //邮件优先级
            SmtpClient client = new SmtpClient();

            client.UseDefaultCredentials = true;
            client.Credentials           = new System.Net.NetworkCredential("*****@*****.**", "IT2016@"); //注册的邮箱和密码
            client.Host      = "smtp.qiye.163.com";
            client.Port      = 587;
            client.EnableSsl = true;

            object userState = msg;

            try
            {
                //client.SendAsync(msg, userState);
                client.Send(msg);
                // msg.Attachments.Dispose();
                // File.Delete(path);
                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(false);
            }
        }
Exemple #60
0
        public bool sendmail1(string name, string userid, string em, Int32 iii)
        {
            try
            {
                QRCodeEncoder qe = new QRCodeEncoder();
                qe.QRCodeEncodeMode   = QRCodeEncoder.ENCODE_MODE.BYTE;
                qe.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;
                System.Drawing.Image im = qe.Encode(iii.ToString());

                MemoryStream ms = new MemoryStream();
                im.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                byte[] bt = ms.ToArray();

                MemoryStream da = new MemoryStream(bt);

                MailMessage mess = new MailMessage("*****@*****.**", em);
                mess.Subject = "AHRMS welcomes you " + name + "";


                Attachment data = new Attachment(da, "myimage.jpeg", "image/jpeg");
                System.Net.Mime.ContentDisposition disposition = data.ContentDisposition;
                disposition.CreationDate     = System.DateTime.Now;
                disposition.ModificationDate = System.DateTime.Now;
                disposition.DispositionType  = DispositionTypeNames.Attachment;

                mess.Attachments.Add(data);
                mess.Body = "Hi" + "," + name + "" + Environment.NewLine + Environment.NewLine +


                            "AHRMS" + Environment.NewLine +
                            "Advance Human Resource Management Systems" + Environment.NewLine + Environment.NewLine +

                            "Thank You for regiserting with AHRMS" + Environment.NewLine +
                            "Your USERID is" + "     " + userid + "   " + "   " + "" + Environment.NewLine + Environment.NewLine + Environment.NewLine +
                            "For any further details please contact on the below mailID" + Environment.NewLine +
                            Environment.NewLine +
                            "*****@*****.**" + Environment.NewLine + Environment.NewLine +
                            "Your QR code is attached in the mail please download it" + Environment.NewLine + Environment.NewLine +
                            "Regards" + Environment.NewLine + "AHRMS" + Environment.NewLine + "Admin" + Environment.NewLine +
                            @"<img  src=""../Images/logo.png"" />" +
                            Environment.NewLine + Environment.NewLine +
                            "Note:- This is System generated mail Please do not reply to this mail id" + Environment.NewLine + Environment.NewLine +
                            "Thank You for visiting AHRMS";

                System.Configuration.Configuration config   = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
                MailSettingsSectionGroup           settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");

                SmtpClient sc = new SmtpClient();
                sc.Credentials = new NetworkCredential(settings.Smtp.Network.UserName, settings.Smtp.Network.Password);
                sc.EnableSsl   = true;

                sc.EnableSsl = true;
                sc.Send(mess);
                return(true);
            }
            catch (Exception db)
            {
                String ss = db.Message.ToString();
                string sw = db.Source.ToString();
                string sd = db.HResult.ToString();
                errorlog(ss, sw, sd);
                return(false);
            }
        }