When I am saving an image, it is getting saved by the Barcode name.
But If I modify the barcode name, then the image is gone, not saving.
I have noticed while debugging that the if(System.IO.File.Exists(imageFilePath)) is not executing when I am updating the barcode. But at the time of saving a new one, its executing.
How to correct this?
Updating code
public object Update(ItemEntity item)
{
var val = _itemRepository.Save(item);
if (item.ImageFileName != string.Empty || item.ImageOriginalFileName != string.Empty)
{
string result = JsonConvert.SerializeObject(val);
var definition = new { Success = false, EntryMode = string.Empty, BarCode = string.Empty, ItemCode = string.Empty };
var info = JsonConvert.DeserializeAnonymousType(result, definition);
if (info.Success)
{
if (!string.IsNullOrEmpty(item.ImageOriginalFileName))
this.SaveImage(item.ImageFileName, (item.ImageOriginalFileName == "BARCODE" ? info.ItemCode : item.ImageOriginalFileName == "BARCODEYes" ? item.Barcode : item.ImageOriginalFileName));
}
}
if (item.DeleteImageFileName != string.Empty && item.ImageFileName == string.Empty) // Image file removed but no new image file is uploaded[Bug Id :34754 -No image is uploaded, when a user re-uploads an image after deleting a previous one.]
{
this.DeleteImage(item.DeleteImageFileName);
}
return val;
}
Saving Code
public void SaveImage(string fileName, string originalFileName)
{
string tempFileName = fileName;
if (!string.IsNullOrEmpty(tempFileName))
{
// move file from temp location to actual loation
var webAppPath = System.Web.Hosting.HostingEnvironment.MapPath("~");
var splitPath = webAppPath.Split("\\".ToCharArray()).ToList();
var upLevel = splitPath.Count - 1; // one level up
splitPath = splitPath.Take(upLevel).ToList();
var UIFolder = "WebUI";
splitPath.AddRange(new string[] { UIFolder, "Temp", "ImageUpload", CurrentSession.UserId.Value.ToString(), "ItemImage" });
var webUIPath = splitPath.Aggregate((i, j) => i + "\\" + j);
var imageFilePath = Path.Combine(webUIPath.EnsureEndsWith('\\'), tempFileName);
if (System.IO.File.Exists(imageFilePath))
{
splitPath = webAppPath.Split("\\".ToCharArray()).ToList();
upLevel = splitPath.Count - 1; // one level up
splitPath = splitPath.Take(upLevel).ToList();
splitPath.AddRange(new string[] { "Shared", "ItemImage" });
webUIPath = splitPath.Aggregate((i, j) => i + "\\" + j);
// Check existence of folder, create if not found and Delete-Create if found
if (!Directory.Exists(webUIPath))
{
Logger.Debug("Create directory :" + webUIPath);
Directory.CreateDirectory(webUIPath);
}
originalFileName = originalFileName + ".jpg";
var imagDestPath = Path.Combine(webUIPath.EnsureEndsWith('\\'), originalFileName);
if (File.Exists(imagDestPath))
{
GC.Collect();
GC.WaitForPendingFinalizers();
Logger.Debug("Delete File :" + imagDestPath);
File.Delete(imagDestPath);
}
byte[] bytes = System.IO.File.ReadAllBytes(imageFilePath);
FileStream fs = new FileStream(imagDestPath, FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(bytes);
bw.Close();
}
}
}
Related
I have a piece of code which works nicely. However I need to close the file so I can perform file.move() function, this doesn't work because the file is used by another process. I need to use the correct file handle - can you guide me in the right direction?
static void DSCheckForDuplicates(string incomingfolder, string incomingarchivefolder, string quarantinefolder)
{
string[] F1 = Directory.GetFiles(incomingfolder);
string fname = "";
long FileOne;
long FileTwo;
bool FilesAreTrullyIdentical;
string FileStatusValue = "";
string Result = "";
string NewLocation = "";
foreach (string fileName in F1)
{
// FILE EXCLUSION LIST FROM DUPLICATE FILE CHECKS
if (fileName.Contains("xxx.DAT") || fileName.Contains("xxx.txt") || fileName.Contains("OrderHead.txt") )
{
Console.WriteLine("\nKnown file type..");
}
else
{
fname = Path.GetFileName(fileName);
FilesAreTrullyIdentical = false;
Console.WriteLine("Files present : The file is {0}...Press any key\n", fileName);
//Console.ReadKey();
if (File.Exists(incomingarchivefolder + #"\" + fname))
{
DuplicateFlag = true;
FileStatusValue = "DuplicateFilename";
DuplicateFileCounter++;
Narative += string.Format("\n________________________________________________________________________________________________________________\nFile Exception :{0}\n####################\n", DuplicateFileCounter );
Narative += string.Format ("Same filename exists in the two compared directories, Checking potential duplicate file contents in :{0}................\n", fileName);
FileInfo f1 = new FileInfo(fileName);
FileOne = f1.Length;
FileInfo f2 = new FileInfo(incomingarchivefolder + #"\" + fname);
FileTwo = f2.Length;
//if (FileOne == FileTwo)
//{
byte[] firstHash = MD5.Create().ComputeHash(f1.OpenRead());
byte[] secondHash = MD5.Create().ComputeHash(f2.OpenRead());
for (int i = 0; i < firstHash.Length; i++)
{
FilesAreTrullyIdentical = true;
if (firstHash[i] != secondHash[i])
FilesAreTrullyIdentical = false;
}
if (FilesAreTrullyIdentical == true)
{
FileStatusValue = "DuplicationFileNameDuplicateContents";
Console.WriteLine("Processed : WARNING!!! identical FILES contents FOUND {0}\n and {1}\n..............\n", fileName, incomingarchivefolder + #"\" + fname);
Narative += string.Format("\tProcessed : Please delete from incoming, WARNING!!! identical FILES contents\n\nPLEASE DELETE FILE:\t{0}..............\n", fileName);
Result = Path.GetFileName(fileName);
NewLocation += quarantinefolder + "\\" + Result;
Console.WriteLine("\n\n {0} ->\nMoving to {1} , press any key", fileName, NewLocation);
Console.ReadKey();
//File.Move(fileName, NewLocation); // THIS DOESNT WORK
You could capture the stream from f1.OpenRead() into a variable & pass that calling Close() when your done, instead however you should put the stream and MD5 reference within a using construct as currently you leave them undisposed. (This will also close the stream for you)
byte[] firstHash;
using (var stream = f1.OpenRead())
using (var md5 = MD5.Create())
{
firstHash = md5.ComputeHash(stream);
}
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);
}
}
}
}
I'm using DotNetZip library to make multi-file zip archive and download it on the fly (no need to wait for download to start). However I can't make it to download instantly. From browser dev console, in network tab I noticed that first zip file is "transferred" and after being fully transferred it starts downloading.
Here is code fragment:
using (var vZipArchive = new ZipFile())
{
if (vFilesTable.Rows.Count > 0)
{
string vPathFormat = null;
string vKeyName = null;
string vPrimKey = null;
string vFileName = null;
vZipArchive.CompressionLevel = CompressionLevel.BestSpeed;
vZipArchive.CompressionMethod = CompressionMethod.Deflate;
vZipArchive.Comment = "Document Archive";
foreach (DataRow vFile in vFilesTable.Rows)
{
if (vKeyFieldName != null && !string.IsNullOrEmpty(vKeyFieldName))
{
vPathFormat = "{0}/";
}
else
{
vPathFormat = "/";
}
if (vFile.Table.Columns.Contains("FileName") && vFile.Table.Columns.Contains("PrimKey"))
{
vPrimKey = vFile["PrimKey"].ToString();
vFileName = vFile["FileName"].ToString();
if (vKeyFieldName != null)
{
vKeyName = vFile[vKeyFieldName].ToString();
}
string vPath = null;
if (vKeyFieldName != null)
{
vPath = string.Format(vKeyFieldName + " " + vPathFormat + "{1}", vKeyName, vFileName);
}
else
{
vPath = string.Format(vPathFormat + vFileName);
}
using (var vFileStream = vUserContext.GetFileStream(vRecordSource.ViewName, new Guid(vPrimKey)))
{
vFileStream.Position = 0;
vZipArchive.AddEntry(vPath, vFileStream);
}
}
else
{
throw new Exception("Select 'FileName' and 'PrimKey' fields in underlying DataSource");
}
} //end loop
pContext.Response.Clear();
pContext.Response.BufferOutput = false;
pContext.Response.ContentType = "application/zip";
pContext.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}.zip\"", vZipName));
vZipArchive.Save(pContext.Response.OutputStream);
}
else
{
return;
}
}
I also tried using ZipOutputStream and SharpCompress.dll library.
So, what I am missing to make it work? Or its impossible?
I am creating the nested folders dynamically for a document library and uploading files. The below code is working fine. but the issues is whenever i uploading the file to the existence folder the ID of the document for the uploaded documents is not in sequence. Suppose if i am uploading a file to path projects\PRJ1\Assignment, fist time it was creating the folders and file with ID's(1\2\3\4) respectively . If i upload other document to the same folder the id of the folders is not changing but the id of the file is 8. i am not unable to find the id 5,6,7 in the document library.
using (CSOM.ClientContext clientContext = new CSOM.ClientContext(SPserverUrl))
{
clientContext.Credentials = new System.Net.NetworkCredential(Username, Password, Domain);
CSOM.Web _Site = clientContext.Web;
// string listrootfolder = "Testlist";
CSOM.List _List = _Site.Lists.GetByTitle("Testlist");
clientContext.Load(_List.RootFolder);
clientContext.ExecuteQuery();
string listrootfolder = _List.RootFolder.Name.ToString();
var folder = CreateFolder(clientContext.Web, "Testlist", folderpath);
// uploading the document
CSOM.FileCreationInformation newFile = new CSOM.FileCreationInformation();
// newFile.Content = System.IO.File.ReadAllBytes(#"D:\Testupload.docx");
byte[] bytes = Convert.FromBase64String(objReqDocumentDetials.FileData.ToString());
newFile.Content = bytes;
// newFile.Url = objDocumentDetials.AttachmentName.ToString() + DateTime.Now.ToString("ddMMyyyyHHmmsss") + "." + objDocumentDetials.FileType.ToString();
newFile.Url = objReqDocumentDetials.FileName.ToString() + "." + objReqDocumentDetials.FileType.ToString();
newFile.Overwrite = true;
Microsoft.SharePoint.Client.File _UploadingFile = folder.Files.Add(newFile);
var item = _UploadingFile.ListItemAllFields;
// var folder = item.GetFolder("account/" + folderName);
// item["Year"] = DateTime.Now.Year.ToString();
// item.Update();
clientContext.Load(_UploadingFile, f => f.ListItemAllFields);
clientContext.ExecuteQuery();
}
public CSOM.Folder CreateFolder(CSOM.Web web, string listTitle, string fullFolderPath)
{
if (string.IsNullOrEmpty(fullFolderPath))
throw new ArgumentNullException("fullFolderPath");
CSOM.List list = web.Lists.GetByTitle(listTitle);
return CreateFolderInternal(web, list.RootFolder, fullFolderPath);
}
public CSOM.Folder CreateFolderInternal(CSOM.Web web, CSOM.Folder parentFolder, string fullFolderPath)
{
var folderUrls = fullFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string folderUrl = folderUrls[0];
var curFolder = parentFolder.Folders.Add(folderUrl);
web.Context.Load(curFolder);
web.Context.ExecuteQuery();
if (folderUrls.Length > 1)
{
var folderPath = string.Join("/", folderUrls, 1, folderUrls.Length - 1);
return CreateFolderInternal(web, curFolder, folderPath);
}
return curFolder;
}
The issue was fixed after redefined the CreateFolder and CreateFolderInternal methods as below
public CSOM.Folder CreateFolder(CSOM.Web web, string listTitle, string fullFolderPath)
{
var folderUrls = fullFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
CSOM.List _List = web.Lists.GetByTitle(listTitle);
web.Context.Load(_List.RootFolder);
web.Context.ExecuteQuery();
string listrootfolder = _List.RootFolder.Name.ToString();
web.Context.Load(web, w => w.ServerRelativeUrl);
web.Context.ExecuteQuery();
string root = "";
for (int i = 0; i < folderUrls.Length; i++)
{
root = folderUrls[i].ToString();
string targetFolderUrl = "/" + listrootfolder + "/" + string.Join("/", folderUrls, 0, i + 1);
var folder1 = web.GetFolderByServerRelativeUrl(targetFolderUrl);
web.Context.Load(folder1);
bool exists = false;
try
{
web.Context.ExecuteQuery();
exists = true;
}
catch (Exception ex)
{
}
if (!exists)
{
if (i == 0)
{
CreateFolderInternal(web, _List.RootFolder, root);
}
else
{
web.Context.Load(web, w => w.ServerRelativeUrl);
web.Context.ExecuteQuery();
var targetfolderUrls = targetFolderUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string jj = string.Join("/", targetfolderUrls, 0, targetfolderUrls.Length - 1);
CSOM.Folder folder = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + jj);
web.Context.Load(folder);
web.Context.ExecuteQuery();
SPCreateFolderInternal(web, folder, root);
}
}
else
{
//already folder exists
}
}
CSOM.Folder finalfolder = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + listrootfolder + "/" + fullFolderPath);
web.Context.Load(finalfolder);
web.Context.ExecuteQuery();
return finalfolder;
}
private void CreateFolderInternal(CSOM.Web web, CSOM.Folder parentFolder, string fullFolderPath)
{
try
{
var curFolder = parentFolder.Folders.Add(fullFolderPath);
web.Context.Load(curFolder);
web.Context.ExecuteQuery();
}
catch (System.Exception ex)
{
}
}
I am working with a project where I am generating PDF Files from PSR Files. The PDF Files works fine if its a single page but if It has more than two PSR Files and I generate two files it does not open on iPad and works fine on Desktop.
The Third library tool I am using here is 'dbatuotrack' and I am using C#.
Can anyone please guide me how to resolve this problem?
Thanks,
S.
foreach (var pdfform in pdfPagesID)
{
//dbAutoTrack.PDFWriter.Document objDoc = null;
//dbAutoTrack.PDFWriter.Page objPage = null;
objDoc = new dbAutoTrack.PDFWriter.Document();
pdfPagesID.Clear();
pdfPagesID = GetSpecPageID(pdfform);
if (pdfPagesID.Count > 1)
{
foreach (var pdfPage in pdfPagesID)
{
dbAutoTrack.PDFWriter.Page objPage2 = null;
var lastItem = pdfPagesID.Last();
prefixPageID = prefixSpecPageID(pdfPage);
suffixPageIDPSR = prefixPageID + ".psr";
if (File.Exists(PSRPath + suffixPageIDPSR))
{
objDs = new CDatasheet(this.PSRPath + suffixPageIDPSR, false);
objDs.pdfDbHelper = pdfhelper;
//Giving the specformId as SpecFornName
pdfFormName = "Form" + pdfform + ".pdf";
if (!(pdfPage == pdfPagesID.First()))
{
objPage2 = objDs.Generate_PDFReport();
objDoc.Pages.Add(objPage2);
}
else
{
objPage = objDs.Generate_PDFReport();
objDoc.Pages.Add(objPage);
}
if (objPage != null)
{
if (pdfWithNotePage == true && pdfPage.Equals(lastItem))
{
objNotePage = objDs.GetNotePage();
objDoc.Pages.Add(objPage);
objDoc.Pages.Add(objNotePage);
}
else
{
//objDoc.Pages.Add(objPage);
//objDoc.Pages.Add(objPage2);
}
fsOutput = new FileStream(TemplatePath + pdfFormName, FileMode.Create, FileAccess.Write);
objDoc.Generate(fsOutput);
}
if (fsOutput != null)
{
fsOutput.Close();
fsOutput.Dispose();
fsOutput = null;
}
}
}
objDoc = null;
objPage = null;
}
This how I tweaked the code to make it work. Thanks for the suggestion DJ KRAZE
foreach (var pdfform in pdfPagesID)
{
//dbAutoTrack.PDFWriter.Document objDoc = null;
//dbAutoTrack.PDFWriter.Page objPage = null;
objDoc = new dbAutoTrack.PDFWriter.Document();
pdfPagesID.Clear();
pdfPagesID = GetSpecPageID(pdfform);
if (pdfPagesID.Count > 1)
{
foreach (var pdfPage in pdfPagesID)
{
dbAutoTrack.PDFWriter.Page objPage2 = null;
var lastItem = pdfPagesID.Last();
prefixPageID = prefixSpecPageID(pdfPage);
suffixPageIDPSR = prefixPageID + ".psr";
if (File.Exists(PSRPath + suffixPageIDPSR))
{
objDs = new CDatasheet(this.PSRPath + suffixPageIDPSR, false);
objDs.pdfDbHelper = pdfhelper;
//Giving the specformId as SpecFornName
pdfFormName = "Form" + pdfform + ".pdf";
if (!(pdfPage == pdfPagesID.First()))
{
objPage2 = objDs.Generate_PDFReport();
objDoc.Pages.Add(objPage2);
}
else
{
objPage = objDs.Generate_PDFReport();
objDoc.Pages.Add(objPage);
}
if (objPage != null)
{
if (pdfWithNotePage == true && pdfPage.Equals(lastItem))
{
objNotePage = objDs.GetNotePage();
objDoc.Pages.Add(objPage);
objDoc.Pages.Add(objNotePage);
}
else
{
//objDoc.Pages.Add(objPage);
//objDoc.Pages.Add(objPage2);
}
}
}
}
fsOutput = new FileStream(TemplatePath + pdfFormName, FileMode.Create, FileAccess.Write);
objDoc.Generate(fsOutput);
//This region was the problem, disposing the output everytime.
//Needed it to be included after completion of iteration
if (fsOutput != null)
{
fsOutput.Close();
fsOutput.Dispose();
fsOutput = null;
}
}