Saving KML file, I get System out of memory exception - c#

I'm trying to export kml file. for some reason I keep getting system out of memory exception. kindly find my code below
SharpKml.Dom.Kml root = new SharpKml.Dom.Kml();
root.Feature = doc;
SharpKml.Engine.KmlFile kmlFile = SharpKml.Engine.KmlFile.Create(root, true);
try
{
using (var stream = File.OpenWrite(kmlFileName))
kmlFile.Save(stream);
}
catch
{
throw;
}
it explodes on KmlFile.Save(stream). please help

Next code works fine for me
try
{
LineString lineString = new LineString()
{
AltitudeMode = AltitudeMode.Absolute,
Tessellate = true,
Coordinates = new CoordinateCollection()
};
Vector prevCoordinates = new Vector(45.883144378662109, 13.902674674987793, -71.5);
lineString.Coordinates.Add(prevCoordinates);
Placemark placemark = new Placemark()
{
Name = "Coordinate log",
Geometry = lineString
};
placemark.AddStyle(new Style()
{
Line = new LineStyle()
{
ColorMode = ColorMode.Normal,
Width = 3,
Color = new Color32(255, 255, 0, 0),
OuterWidth = 1,
OuterColor = new Color32(150, 255, 255, 255),
},
});
KmlFile kml = KmlFile.Create(placemark, false);
using (var stream = System.IO.File.OpenWrite(telemFileName + ".kml"))
{
kml.Save(stream);
}
}
catch (IOException)
{
//file in use
}
catch (Exception ex)
{
logger.Error("Exception: " + ex);
}

Related

Occasional OutOfMemoryException on Bitmap Processing Over The Network

I'm running the following code in LinqPad 5:
var client = new MongoClient(#"mongodb://192.168.0.108:27017");
var db = client.GetDatabase("Stfc");
var fitCollection = db.GetCollection<ModelFit>("RecentFits");
var fits = fitCollection.AsQueryable();
var captureCollection = db.GetCollection<Capture>("Captures");
var captures = captureCollection.AsQueryable();
var classificationCollection = db.GetCollection<Classification>("Classifications");
var classifications = classificationCollection.AsQueryable();
var modelsDir = new DirectoryInfo(#"\\iansdesktop\Shared\Stfc\mymodels");
var imagesDir = new DirectoryInfo(#"\\iansdesktop\Shared\Stfc\Images");
var classificationDir = new DirectoryInfo(#"C:\Users\Ian\Documents\Projects\Output\StfcBot\Classification");
var capturesById = captures.ToDictionary(x => x.Id);
var systems = classifications
.Where(x => x.Label == "system");
var count = systems.Count();
var i = 0;
var pen = new Pen(Color.FromArgb(255, 255, 0, 0));
foreach (var classification in systems)
{
var capture = capturesById[classification.CaptureId];
var img = imagesDir.File(capture.ImageName);
var srcFile = imagesDir.File(capture.ImageName);
var destFile = classificationDir.File(capture.ImageName);
while (!destFile.Exists)
{
try
{
using (var bmp = Bitmap.FromFile(srcFile.FullName))
using (var dest = new Bitmap(bmp))
{
using (var g = Graphics.FromImage(dest))
{
g.DrawEllipse(pen, capture.X - 20, capture.Y - 20, 40, 40);
}
dest.Save(destFile.FullName);
dest.Dispose();
bmp.Dispose();
}
destFile.Refresh();
destFile.Name.Dump();
}
catch (IOException ex)
{
ex.Dump();
Thread.Sleep(30_000);
}
}
++i;
if (i % 10 == 0)
{
i.ToProgressSummary(count).Dump();
}
}
Am I missing anything, or could this be a bug in LinqPad?
Turns out this is because the bitmap was being loaded from a network path, and the network was occasionally disconnecting.
The documentation states:
You must keep the stream open for the lifetime of the Bitmap.
Bitmap Constructors (See Remarks)
The OOM exception obfuscates what is going on for some reason, but the underlying stream was being closed.
The solution is to copy the file locally and operate on that local copy:
var tmpFile = new DirectoryInfo(Path.GetTempPath()).File(srcFile.Name);
while (!destFile.Exists)
{
srcFile.CopyTo(tmpFile.FullName);
try
{
using (var bmp = Bitmap.FromFile(tmpFile.FullName))
using (var dest = new Bitmap(bmp))
{
.
}
destFile.Refresh();
destFile.Name.Dump();
}
catch (IOException ex)
{
...
}
finally
{
tmpFile.Delete();
}
}
Of course if the network still disconnects an exception occurs, but at least it's a sensible and understandable error instead of OOM.

How to Suppy Data Model to Print Function

I have a Print function which calls by different forms in my Project. Previously I was using DataSet as on my parameter, Now I switched to Data model. I am not sure how to retrieve information from different data model each time. Here is my old code.
public static void Print(string templeteID, DataSet dsSource,bool bPreview)
{
try
{
TPX.HMI.BusinessLogic.SystemSetting.ReportTemplate bll = new TPX.HMI.BusinessLogic.SystemSetting.ReportTemplate();
DataSet dsTemp = bll.RetrieveReportTemplateByID(templeteID);
if (dsTemp.Tables[0].Rows.Count > 0)
{
FileStream fs = new FileStream(Application.StartupPath + #"\\temp.repx", FileMode.Create);
Byte[] aryFile = dsTemp.Tables[0].Rows[0]["TemplateFile"] as Byte[];
fs.Write(aryFile, 0, aryFile.Length);
fs.Close();
}
string reportPatch = Application.StartupPath + #"\\temp.repx";
//开始打印
if (!System.IO.File.Exists(reportPatch))
{
MessageBox.Show(TPX.LanguageHelper.GetSystemKeyValue(GlobalParameters.Language, "TPX_TF_HMI_Print_TemplateError"));
return;
}
System.IO.FileStream stream = new System.IO.FileStream(reportPatch, System.IO.FileMode.Open);
XtraReport mReport = DevExpress.XtraReports.UI.XtraReport.FromStream(stream, true);
stream.Close();
if (dsSource != null) //传入数据集
{
mReport.DataSource = dsSource;
mReport.DataMember = dsSource.Tables[dsSource.Tables.Count - 1].TableName;
}
mReport.Name = "TPX";
mReport.RequestParameters = false;
mReport.PrintingSystem.ShowPrintStatusDialog = false;
mReport.PrintingSystem.ShowMarginsWarning = false;
if (!string.IsNullOrEmpty(GlobalParameters.DefaultPrinter))
mReport.PrintingSystem.PageSettings.PrinterName = GlobalParameters.DefaultPrinter;
mReport.CreateDocument();
if (bPreview)
mReport.ShowPreviewDialog();
else
mReport.Print();
}
catch (Exception ex)
{
MessageBox.Show((TPX.LanguageHelper.GetSystemKeyValue(GlobalParameters.Language, "TPX_TF_HMI_Print_TemplatePrintEx")) + ex.Message);
}
}

File used by another process ; PDF.JS ; iText

I'm using PDF.JS to display document that I upload to the server in canvas element using PDF.JS that's working perfectely. That time i'm using iTextSharp to digitally sign the document. When i try to sign the document an Exception is throwed (Exception.IO.Exception) The file is already used by another process. here is my Code for uploding the file :)
[HttpPost]
public async Task<JsonResult> Upload()
{
string fileName = null;
try
{
foreach (string item in Request.Files)
{
var fileContent = Request.Files[item];
if(fileContent != null && fileContent.ContentLength > 0)
{
var inputStream = fileContent.InputStream;
fileName = fileContent.FileName;
string path = Path.Combine(Server.MapPath("~/UploadFolder"), fileName);
using (fileContent.InputStream)
{
using (var stream = new FileStream(path, FileMode.Create))
{
await inputStream.CopyToAsync(stream);
}
}
}
}
}
catch (Exception e)
{
return Json("Upload failed");
}
return Json(fileName);
}
There's how i display PDF in canvas
$(document).ready(function () {
$("#btn2").click(function () {
var url = document.getElementById("document-to-sign").getAttribute("required-document");
if (url != "" && url != null) {
var pdfDoc = null,
pageNum = 1,
pageRendering = false,
pageNumPending = null,
scale = 1.5,
canvas = document.getElementById('document-to-sign'),
ctx = canvas.getContext('2d');
function renderPage(num) {
pageRendering = true;
pdfDoc.getPage(num).then(function (page) {
var viewport = page.getViewport(scale);
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
var renderTask = page.render(renderContext);
renderTask.promise.then(function () {
pageRendering = false;
if (pageNumPending !== null) {
renderPage(pageNumPending);
pageNumPending = null;
}
});
});
document.getElementById('page_num').textContent = pageNum;
}
function queueRenderPage(num) {
if (pageRendering) {
pageNumPending = num;
} else {
renderPage(num);
}
}
function onPrevPage() {
if (pageNum <= 1) {
return;
}
pageNum--;
queueRenderPage(pageNum);
}
document.getElementById('prev').addEventListener('click', onPrevPage);
function onNextPage() {
if (pageNum >= pdfDoc.numPages) {
return;
}
pageNum++;
queueRenderPage(pageNum);
}
document.getElementById('next').addEventListener('click', onNextPage);
PDFJS.getDocument(url).then(function (pdfDoc_) {
pdfDoc = pdfDoc_;
document.getElementById('page_count').textContent = pdfDoc.numPages;
renderPage(pageNum);
});
PDFJS.disableStream = true;
$("#document-to-sign").removeAttr("required-document");
}
});
I finally that's how i'm signing the document (Adding the empty field to sign)
public static void AddField(string src,
Double x1X, Double x1Y, Double x2X, Double x2Y, int page,
string User)
{
try
{
PdfReader reader = new PdfReader(src);
using (PdfStamper s = new PdfStamper(reader, new FileStream(src, FileMode.Open)))
{
PdfFormField field = PdfFormField.CreateSignature(s.Writer);
field.FieldName = "Signature de " + User;
field.SetWidget(new Rectangle(Convert.ToSingle(x1X), Convert.ToSingle(x1Y), Convert.ToSingle(x2X), Convert.ToSingle(x2Y)), PdfAnnotation.HIGHLIGHT_PUSH);
field.Flags = PdfAnnotation.FLAGS_PRINT;
s.AddAnnotation(field, page);
}
}
catch (Exception e)
{
logger.Fatal(e.ToString());
throw e;
}
}
I'm stacked in this line
using (PdfStamper s = new PdfStamper(reader, new FileStream(src, FileMode.Open)))
EDIT:
I'm just adding the siging field in this step. Signing the document will be the next task, in console application i'm singing the document with a self-certificate.
Upload the document, and adding the signing field and signing it will be further :)
Sorry for the confussion.
Thanks a lot. :)
I just found what i'm missing in reading the file
refer to this
Cannot access the file because it is being used by another process
i was passing the url of the file instead of reading the all bytes from stream
PdfReader reader = new PdfReader(src);
PdfReader reader = new PdfReader(System.IO.File.ReadAllBytes(filePath))

A Generic error occurred in GDI+ while saving image to file system [duplicate]

I have made one console application in which I have pre-generated all images as same as nopCommerce does for generating images.
Here is my code:
thumbFileName = !String.IsNullOrEmpty(seoFileName) ?
string.Format("{0}_{1}_{2}.{3}", pictureId.ToString("0000000"), seoFileName, _productThumbPictureSize, lastPart) :
string.Format("{0}_{1}.{2}", pictureId.ToString("0000000"), _productThumbPictureSize, lastPart);
if (_generatePictures)
{
if (storeInDb)
{
storeInDb = GetSettingByKey<bool>("media.images.storeindb");
}
// byte defaultImageQuality = GetSettingByKey<byte>("mediasettings.defaultimagequality");
if (storeInDb)
{
pictureBinary = GetPictureByProductId(Id);
}
else
{
pictureBinary = LoadPictureFromFile(pictureId, mimeType);
}
if (pictureBinary == null || pictureBinary.Length == 0)
{
url = GetDefaultPictureUrl(_productThumbPictureSize);
return url;
}
if (isNew)
{
DeletePictureThumbs(pictureId);
//we do not validate picture binary here to ensure that no exception ("Parameter is not valid") will be thrown
var picture = UpdatePicture(pictureId,
pictureBinary,
mimeType,
seoFileName,
false);
}
if (pictureBinary.Length != 0)
{
//Generating Images
string newpath = "Thumbs";
var _path = Path.Combine(_imagesPath, newpath);
var thumbFilePath = GetPictureLocalPath(thumbFileName, _path);//"C:\\Users\\Developer\\Documents\\Server2\\Solr Plugin Branch Nop-310\\Presentation\\Nop.Web\\Content\\Images\\Thumbs\\"+thumbFileName;
if (!File.Exists(thumbFilePath))
{
using (var stream = new MemoryStream(pictureBinary))
{
Bitmap b = null;
try
{
//try-catch to ensure that picture binary is really OK. Otherwise, we can get "Parameter is not valid" exception if binary is corrupted for some reasons
b = new Bitmap(stream );
}
catch (ArgumentException exc)
{
string msg = exc.ToString();
string fullmsg = string.Format("Error generating picture thumb. ID={0}", pictureId);
InsertSystemLog(msg, fullmsg);
}
if (b == null)
{
//bitmap could not be loaded for some reasons
return url;
}
var newSize = CalculateDimensions(b.Size, _productThumbPictureSize);
if (newSize.Width < 1)
newSize.Width = 1;
if (newSize.Height < 1)
newSize.Height = 1;
using (var newBitMap = new Bitmap(newSize.Width, newSize.Height))
{
using (var g = Graphics.FromImage(newBitMap))
{
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.CompositingQuality = CompositingQuality.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawImage(b, 0, 0, newSize.Width, newSize.Height);
var ep = new EncoderParameters();
ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 80L);
ImageCodecInfo ici = GetImageCodecInfoFromExtension(lastPart);
if (ici == null)
ici = GetImageCodecInfoFromMimeType("image/jpeg");
try
{
newBitMap.Save(thumbFilePath, ici, ep);
}
catch (ArgumentException exc)
{
string msg = exc.ToString();
string fullmsg = string.Format("Unable to save Picture ID={0}", pictureId);
InsertSystemLog(msg, fullmsg);
}
}
}
b.Dispose();
}
}
}
I got GDI+ error at following line:
b = new Bitmap(stream);
Error:
The log entry message.Short message: A generic error occurred in GDI+.
The details for the log entry.Full message: at System.Drawing.Image.FromStream(Stream stream)
Notice that all images are saved on file system. And folder has write permission. And this error occurred on live site only not at localhost.

SSRS wont publish report but it returns successful as if it did

public static void ListFolders()
{
HomeFolderListing = new List<string>();
ReportingServiceSoapClient rs = new ReportingServiceSoapClient();
rs.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
CatalogItem[] HomeFolders = null;
string reportPath = "/";
rs.ListChildren(reportPath, true, out HomeFolders);
foreach (var homeF in HomeFolders)
{
if (homeF.Name.ToString().ToLower().Contains("base"))
{
if (homeF.Path.ToString().ToLower().Contains("/data sources/"))
{
}
else
{
Console.WriteLine("Adding reporting folder: " + homeF.Name.ToString());
HomeFolderListing.Add(homeF.Path.ToString());
}
}
}
}
public static void PublishReport()
{
foreach (string HomeFold in HomeFolderListing)
{
ReportingServiceSoapClient rs = new ReportingServiceSoapClient();
rs.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
BatchHeader bh = new BatchHeader();
string batchID = null;
rs.CreateBatch(out batchID);
bh.BatchID = batchID;
Byte[] definition = null;
Warning[] warnings = null;
try
{
FileStream stream = File.OpenRead(ReportInformation.Report2Deploy);
definition = new Byte[stream.Length];
stream.Read(definition, 0, (int)stream.Length);
stream.Close();
}
catch (Exception ex)
{
}
try
{
string filename = ReportInformation.ReportDeployNameOnly;
Console.WriteLine("Deploying Report: " + filename + " to: " + HomeFold);
rs.CreateReport(bh, filename, HomeFold, true, definition, null, out warnings);
if (warnings != null)
{
foreach (Warning warning in warnings)
{
Console.WriteLine(warning.Message);
}
}
else
Console.WriteLine("Report: {0} created successfully with no warnings", filename);
}
catch (Exception ex)
{
}
}
}
when i execute rs.CreateReport() it comes back as if it was successful with no warning, however, when i view the server it just isn't there. And yes I've looking in all the folders.
Are you sure there is no error? There's an empty catch block. The documenation says to catch a SoapException. Try this in the catch:
catch (SoapException e)
{
//Do something with the error, sample code write to console
Console.WriteLine(e.Detail.InnerXml.ToString());
}
Taken from:
http://msdn.microsoft.com/en-us/library/aa225813(v=sql.80).aspx

Categories