string fname = "";
string filename = "";
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
string filess = files[i].FileName;
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = DateTime.Now.ToString("ddMMMyyyyhhmissmmm") + testfiles[testfiles.Length - 1];
filename = filename + Path.GetFileName(fname);
}
else
{//some code here
fname = DateTime.Now.ToString("ddMMMyyyyhhmissmmm") + file.FileName;
filename = filename + Path.GetFileName(fname);
}
string replacestr = System.Text.RegularExpressions.Regex.Replace(filename, "[^a-zA-Z0-9_]+", " ");
fname = replacestr;
fname = replacestr;
fname = fname.Replace(" ", "").Replace(",", "").Trim();
fname = fname + "";
fname = fname + ".png";
filename = fname;
fname = Path.Combine(context.Server.MapPath("../admin/img/product_images/"), fname);
file.SaveAs(fname);
//some code here
}
}
//Do This Work watermarkenter image description here
Bitmap bmp = new Bitmap(file.InputStream);
Graphics graphicsobj = Graphics.FromImage(bmp);
Brush brush = new SolidBrush(Color.FromArgb(80, 255, 255, 255));
Point postionWaterMark = new Point((enter image description herebmp.Width / 6), (bmp.Height / 2));
graphicsobj.DrawString("Daphnisys Technology", new System.Drawing.Font("Arial", 30, FontStyle.Bold, GraphicsUnit.Pixel), brush, postionWaterMark);
Image img = (Image)bmp;
string filepath = HttpContext.Current.Server.MapPath("../admin/img/product_images/") + filename;
//image.Save(filepath);
img.Save(filepath, System.Drawing.Imaging.ImageFormat.Png);
graphicsobj.Dispose();
Related
I wrote c# code to read emails from my gmail account, using openpop.net library, and save them into a database. Everything is going right but it is so slow in loading the emails. I tried a parallel.for loop but it gave the error:
write method can not begin while other write method is running
Is there any way to use parallel processing in this case?
This is my read emails function:
public void Read_Emails()
{
Pop3Client pop3Client;
if (Session["Pop3Client"] == null)
{
pop3Client = new Pop3Client();
pop3Client.Connect("pop.gmail.com", 995, true);
pop3Client.Authenticate(usermail, pwd, AuthenticationMethod.UsernameAndPassword);
Session["Pop3Client"] = pop3Client;
}
else
{
pop3Client = (Pop3Client)Session["Pop3Client"];
}
int count = pop3Client.GetMessageCount();
for (int i = count; i >= 1; i--)
{
Message message = pop3Client.GetMessage(i);
FFromAdress = message.Headers.From.Address;
ddate = message.Headers.DateSent;
MMessageNO = i; //message.Headers.MessageId;
List<MessagePart> attachments = message.FindAllAttachments();
DataTable dt = get_Health_Institutions();
DataTable dt1 = get_INTERIOR_Institutions();
foreach (DataRow row in dt.Rows){health_result = FFromAdress.Equals(row["mail"]);}
foreach (DataRow row in dt1.Rows){interior_result = FFromAdress.Equals(row["mail"]);}
bool result = FFromAdress.Equals("sersersetrerttrtail.com");
if (health_result == true) //|| interior_result == true)
{ SSubject = message.Headers.Subject.Split(':')[1];
MessagePart body = message.FindFirstHtmlVersion();
body = message.FindFirstPlainTextVersion();
if (body != null)
{
string BBody1 = body.GetBodyAsText();
BBody = BBody1.Replace(' ', '\n');
}
if (attachments.Count == 0)
{
atta_count = 0;
AAtachments_Path = SSubject;
if (CHKsubjectexist_Health_Date(SSubject) == 0)
{ insertmail_health_date(FFromAdress, SSubject, ddate, BBody, AAtachments_Path, MMessageNO, atta_count); }
}
else
{ for (int m = 0; m < attachments.Count; m++)
{
atta_count = attachments.Count;
if (health_result == true & interior_result == false)
{ imagename = "healthRESULT_answer" + m+".jpg"; }
Foldername = SSubject.Trim();
AAtachments_Path = Foldername;
byte[] bdata = attachments[m].Body;
string folderpathh = "d:\\asdf\\" + Foldername;
System.IO.Directory.CreateDirectory(folderpathh);
string pathh = folderpathh + "\\" + imagename;
System.IO.File.WriteAllBytes(pathh, bdata);
////write image
String st = Server.MapPath(imagename);
FileStream fs = new FileStream(st, FileMode.Create, FileAccess.Write);
fs.Write(bdata, 0, bdata.Length);
fs.Close();
}
if (CHKsubjectexist_Health_final(SSubject) == 0)
{ insertmail_Health_Final(FFromAdress, SSubject, ddate, BBody, AAtachments_Path, MMessageNO, atta_count); }
}
}
else if (interior_result == true)
{
SSubject = message.Headers.Subject.Split(':')[1];
MessagePart body = message.FindFirstHtmlVersion();
body = message.FindFirstPlainTextVersion();
if (body != null)
{
string BBody1 = body.GetBodyAsText();
BBody = BBody1.Replace(' ', '\n');
}
if (attachments.Count == 0)
{
atta_count = 0;
AAtachments_Path = SSubject;
}
else
{
for (int m = 0; m < attachments.Count; m++)
{
atta_count = attachments.Count;
imagename = "Interior_answer" + m+".jpg";
Foldername = SSubject.Trim();
AAtachments_Path = Foldername;
byte[] bdata = attachments[m].Body;
string folderpathh = "d:\\asdf\\" + Foldername;
// System.IO.Directory.CreateDirectory(folderpathh);
string pathh = folderpathh + "\\" + imagename;
System.IO.File.WriteAllBytes(pathh, bdata);
////write image
String st = Server.MapPath(imagename);
FileStream fs = new FileStream(st, FileMode.Create, FileAccess.Write);
fs.Write(bdata, 0, bdata.Length);
fs.Close();
}
}
if (CHKsubjectexist_Interior(SSubject) == 0)
{ insertmail_interior(FFromAdress, SSubject, ddate, BBody, AAtachments_Path, MMessageNO, atta_count); }
}
else if (result == true)
{
SSubject = message.Headers.Subject;
if (CHKsubjectexist(SSubject) == 0)
{
MessagePart body = message.FindFirstHtmlVersion();
if (body != null)
{
BBody = body.GetBodyAsText();
}
else
{
body = message.FindFirstPlainTextVersion();
if (body != null)
{
BBody = body.GetBodyAsText();
}
}
if (attachments.Count == 0)
{
AAtachments_Path = " ";
}
else
{
foreach (MessagePart attachment in attachments)
{
atta_count = attachments.Count;
string filenameee = attachment.FileName;
imagename = filenameee.Split('/', '/')[3];
Foldername = SSubject;
AAtachments_Path = Foldername;
byte[] bdata = attachment.Body;
string folderpathh = "d:\\asdf\\" + Foldername;
System.IO.Directory.CreateDirectory(folderpathh);
string pathh = folderpathh + "\\" + imagename;
System.IO.File.WriteAllBytes(pathh, bdata);
////write image
String st = Server.MapPath(imagename);
FileStream fs = new FileStream(st, FileMode.Create, FileAccess.Write);
fs.Write(bdata, 0, bdata.Length);
fs.Close();
}
}
if (CHKsubjectexist(SSubject) == 0)
{ insertmail(FFromAdress, SSubject, ddate, BBody, AAtachments_Path, MMessageNO, atta_count); }
}
}
}
}
I am writing on my pdf-word converter and I just received a really strange exception witch makes no sens to me.
Error:PdfiumViewer.PdfException:{"Unsupported security scheme"}
Its the first time that such a exception appears. but I have to be honest that I never tried to convert more then 3-4 files from pdf to word and right now I am doing more then 100 files.
Here is my code I am sry if its too long but I simply do not know on which line the error occurs
public static void PdfToImage()
{
try
{
Application application = null;
application = new Application();
string path = #"C:\Users\chnikos\Desktop\Test\Batch1\";
foreach (string file in Directory.EnumerateFiles(path, "*.pdf"))
{
var doc = application.Documents.Add();
using (var document = PdfiumViewer.PdfDocument.Load(file))
{
int pagecount = document.PageCount;
for (int index = 0; index < pagecount; index++)
{
var image = document.Render(index, 200, 200, true);
image.Save(#"C:\Users\chnikos\Desktop\Test\Batch1\output" + index.ToString("000") + ".png", ImageFormat.Png);
application.Selection.InlineShapes.AddPicture(#"C:\Users\chnikos\Desktop\Test\Batch1\output" + index.ToString("000") + ".png");
}
string getFileName = file.Substring(file.LastIndexOf("\\"));
string getFileWithoutExtras = Regex.Replace(getFileName, #"\\", "");
string getFileWihtoutExtension = Regex.Replace(getFileWithoutExtras, #".pdf", "");
string fileName = #"C:\Users\chnikos\Desktop\Test\Batch1\" + getFileWihtoutExtension;
doc.PageSetup.PaperSize = WdPaperSize.wdPaperA4;
foreach (Microsoft.Office.Interop.Word.InlineShape inline in doc.InlineShapes)
{
.....
}
doc.PageSetup.TopMargin = 28.29f;
doc.PageSetup.LeftMargin = 28.29f;
doc.PageSetup.RightMargin = 30.29f;
doc.PageSetup.BottomMargin = 28.29f;
application.ActiveDocument.SaveAs(fileName, WdSaveFormat.wdFormatDocument);
doc.Close();
string imagePath = #"C:\Users\chnikos\Desktop\Test\Batch1\";
Array.ForEach(Directory.GetFiles(imagePath, "*.png"), delegate(string deletePath) { File.Delete(deletePath); });
}
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e);
}
}
}
}
Hello I have signature like this:
which is encoded to a DataUrl specifically this string:
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAADICAYAAADGFbfiAAAYlElEQVR4Xu2dC8w1R1nHQSCIgIKVGLmoiLciFwUs... (long string)"
What i want to do is Convert this DataUrl to an PNG Image, and save the image to the device, this is what i am doing so far:
if (newItem.FieldType == FormFieldType.Signature)
{
if (newItem.ItemValue != null)
{
//string completeImageName = Auth.host + "/" + li[i];
string path;
string filename;
string stringName = newItem.ItemValue;
var base64Data = Regex.Match(stringName, #"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
var binData = Convert.FromBase64String(base64Data);
path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
filename = Path.Combine(path, base64Data);
if (!File.Exists(filename))
{
using (var stream = new MemoryStream(binData))
{
//Code crashing here--------------------------
File.WriteAllBytes(filename, binData);
}
}
newItem.ItemValue = filename;
}
}
App.Database.SaveReportItem(newItem);
But my code is making my application to crash specifically in this line:
File.WriteAllBytes(filename, binData);
The sample I am using as reference (Link) is using a PictureBox but with Xamarin there is no use of a pictureBox.
Any Ideas?
As #SLaks mentioned I didn't need a MemoryStream, the problem with my code was the path and the filename for further help this is the working code:
if (newItem.FieldType == FormFieldType.Signature)
{
if (newItem.ItemValue != null)
{
//string completeImageName = Auth.host + "/" + li[i];
string path;
string filename;
string stringName = newItem.ItemValue;
var base64Data = Regex.Match(stringName, #"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
var binData = Convert.FromBase64String(base64Data);
path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//filename = Path.Combine(path, base64Data.Replace(#"/", string.Empty));
long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
string fileName = "Sn" + milliseconds.ToString() + ".PNG";
filename = Path.Combine(path, fileName);
if (!File.Exists(filename))
{
//using (var stream = new MemoryStream(binData))
//{
File.WriteAllBytes(filename, binData);
//}
}
newItem.ItemValue = filename;
}
}
App.Database.SaveReportItem(newItem);
And the image showed:
I just cleaned Mario's code and fine tuned regex:
public string SaveDataUrlToFile(string dataUrl, string savePath)
{
var matchGroups = Regex.Match(dataUrl, #"^data:((?<type>[\w\/]+))?;base64,(?<data>.+)$").Groups;
var base64Data = matchGroups["data"].Value;
var binData = Convert.FromBase64String(base64Data);
System.IO.File.WriteAllBytes(savePath, binData);
return savePath;
}
I am trying to make a web server in C#, i need to get the requested url and then list the files and folders requested.This is good to get the first directory .
For Eg. My webserver root is c:\test when i open localhost i get the contents of test folder. Say Data is subfolder of c:\test, i can click on data from the browser and get into C:\test\data now when i click on any folder then the get request comes with %2F instead of c:\test\data\ok and so i am stuck.
Code to Recieve The Request :
sRequest = sBuffer.Substring(0, iStartPos - 1);
sRequest.Replace("\\", "/");
if ((sRequest.IndexOf(".") < 1) && (!sRequest.EndsWith("/")))
{
sRequest = sRequest + "/";
}
iStartPos = sRequest.LastIndexOf("/") + 1;
sRequestedFile = sRequest.Substring(iStartPos);
sDirName = sRequest.Substring(sRequest.IndexOf("/"), sRequest.LastIndexOf("/") - 3);
if (sDirName == "/")
sLocalDir = sMyWebServerRoot;
else
{
//Get the Virtual Directory
// sLocalDir = GetLocalPath(sMyWebServerRoot, sDirName);
Console.WriteLine("i am here");
sDirName = sDirName.Substring(1, sDirName.Length - 2);
//sDirName = sDirName.Replace("/", "\\");
Console.WriteLine("Amit:" + sDirName);
string test1 = Path.Combine("C:\\test\\", sDirName);
sLocalDir = Path.Combine(#"C:\\test", sDirName);
}
Now to List Dir I have the following Function :
public String listdir(string sLocaldir,string sDirName)
{
string sresult = "";
StringBuilder sb = new StringBuilder();
sb.AppendLine("<html>");
sb.AppendLine("<head>");
sb.AppendLine("<title>Test</title>");
sb.AppendLine("</head>");
sb.AppendLine("<body>");
sb.AppendLine("<h1><center><u>Listing Folders Under " + sLocaldir + "</h1></u></center>");
string[] folderpaths = Directory.GetDirectories(sLocaldir);
sb.AppendLine("<font color=red><font size=5>Listing Directories<br>");
for (int i = 0; i < folderpaths.Length; i++)
{
string fpath = folderpaths[i];
string[] foldernames = fpath.Split('\\');
int j = foldernames.Length - 1;
string fname = foldernames[j];
string fullname;
if (sDirName != "/")
{
//fname= fname + "\\";
fullname = sDirName +"/"+ fname;
//fullname = fullname.Replace("\\", "/");
//fullname = Path.GetPathRoot("C:\\test");
Console.WriteLine("Get full path:" + fullname);
}
else
{
fullname = fname;
}
Console.WriteLine("Full Test:" + fullname);
//sb.AppendLine(string.Format("<img src=file.png height=20 width=20>{1}<br>",
sb.AppendLine(string.Format("<img src=file.png height=20 width=20>{1}<br>",
HttpUtility.HtmlEncode(HttpUtility.UrlEncode(fullname )),
HttpUtility.HtmlEncode(fname)));
}
string[] filePaths = Directory.GetFiles(#"C:\test");
sb.AppendLine("<font color=red><font size=5>Listing Files<br>");
for (int i = 0; i < filePaths.Length; ++i)
{
string name = Path.GetFileName(filePaths[i]);
sb.AppendLine(string.Format("<img src=file.png height=20 width=20>{1}<br>",
HttpUtility.HtmlEncode(HttpUtility.UrlEncode(name)),
HttpUtility.HtmlEncode(name)));
}
sb.AppendLine("</ul>");
sb.AppendLine("</body>");
sb.AppendLine("</html>");
sresult = sb.ToString();
return sresult;
//Console.WriteLine(sresult);
}
Any help would be highly appreciated.
Thank you
%2F is safe encoding for the / symbol. You are HTMLEncoding the / symbol in your code above.
Your approach can be much simpler see:
http://www.codeproject.com/KB/IP/mywebserver.aspx
ImageList imageList = new ImageList();
if (folder != null && System.IO.Directory.Exists(folder))
{
try
{
string[] arrImageName=new string[1000];
int Count = 0;
string CutName;
DirectoryInfo dir = new DirectoryInfo(#folder);
foreach (FileInfo file in dir.GetFiles())
{
try
{
imageList.ImageSize = new Size(140, 140);
imageList.ColorDepth = ColorDepth.Depth32Bit;
Image img1 = Image.FromFile(file.FullName);
CutName = file.FullName;
CutName = CutName.Replace(folder, "");
CutName = CutName.Replace("\\", "");
arrImageName[Count] = CutName;
imageList.Images.Add(FormatImage(imageList.ImageSize.Width, img1));
Count = Count + 1;
}
catch
{
Console.WriteLine("This is not an image file");
}
}
for (int j = 0; j < imageList.Images.Count; j++)
{
this.ListView1.Items.Add((j + 1) + "/" + imageList.Images.Count + " " + "\r\n" + arrImageName[j]);
this.ListView1.Items[j].ImageIndex = j;
}
this.ListView1.View = View.LargeIcon;
this.ListView1.LargeImageList = imageList;
//import(folder);
}
catch (Exception ex)
{
}
}
You cant do this
Image img1 = Image.FromFile(file.FullName);
because a PDF is not an image format and is not understood by .NET.
Here is a thread on how to convert the PDF to an image using a 3rd party library