public override int SaveChanges(SaveOptions options) { foreach (ObjectStateEntry entry in ObjectStateManager.GetObjectStateEntries( EntityState.Added | EntityState.Modified)) { if (entry.Entity is Configuration) { ValidateConfigurationAggregate((Configuration)entry.Entity); } else if (entry.Entity is Payment) { ValidatePaymentAggregate((Payment)entry.Entity); if (entry.State == EntityState.Added) { Payment payment = (Payment)entry.Entity; payment.PaymentCode = PaymentCode.NextPaymentCode(this); } } } return base.SaveChanges(options); }
public override int SaveChanges(SaveOptions options) { int returnValue = 0; // 因为我们不调用base.SaveChanges, 我们必须手动关闭链接. // 否则我们将留下许多打开的链接, 最终导致链接瓶颈. // Entity Framework提供了base.SaveChanges内部使用的EnsureConnection和ReleaseConnection. // 这些是内部方法, 所以我们必须使用反射调用它们. var EnsureConnectionMethod = typeof(ObjectContext).GetMethod( "EnsureConnection", BindingFlags.Instance | BindingFlags.NonPublic); EnsureConnectionMethod.Invoke(this, null); // 使用ObjectStateManager.GetObjectStateEntries完成增加,修改,和删除集合. foreach (ObjectStateEntry ose in this.ObjectStateManager.GetObjectStateEntries(EntityState.Added)) { Travel travel = ose.Entity as Travel; if (travel != null) { RetryPolicy retryPolicy = new RetryPolicy(); retryPolicy.Task = new Action(() => { this.InsertIntoTravel(travel.PartitionKey, travel.Place, travel.GeoLocationText, travel.Time); }); retryPolicy.Execute(); returnValue++; } } foreach (ObjectStateEntry ose in this.ObjectStateManager.GetObjectStateEntries(EntityState.Modified)) { Travel travel = ose.Entity as Travel; if (travel != null) { RetryPolicy retryPolicy = new RetryPolicy(); retryPolicy.Task = new Action(() => { this.UpdateTravel(travel.PartitionKey, travel.RowKey, travel.Place, travel.GeoLocationText, travel.Time); }); retryPolicy.Execute(); returnValue++; } } foreach (ObjectStateEntry ose in this.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted)) { Travel travel = ose.Entity as Travel; if (travel != null) { RetryPolicy retryPolicy = new RetryPolicy(); retryPolicy.Task = new Action(() => { this.DeleteFromTravel(travel.PartitionKey, travel.RowKey); }); retryPolicy.Execute(); returnValue++; } } var ReleaseConnectionMethod = typeof(ObjectContext). GetMethod("ReleaseConnection", BindingFlags.Instance | BindingFlags.NonPublic); ReleaseConnectionMethod.Invoke(this, null); return returnValue; }
private static string CustomSaveOfFontsAndImages(SaveOptions.ResourceSavingInfo resourceSavingInfo) { System.IO.BinaryReader reader = new BinaryReader(resourceSavingInfo.ContentStream); byte[] resourceAsBytes = reader.ReadBytes((int)resourceSavingInfo.ContentStream.Length); if (resourceSavingInfo.ResourceType == SaveOptions.NodeLevelResourceType.Font) { Console.WriteLine("Font processed with handler. Length of content in bytes is " + resourceAsBytes.Length.ToString()); // Here You can put code that will save font to some storage, f.e database MemoryStream targetStream = new MemoryStream(); targetStream.Write(resourceAsBytes, 0, resourceAsBytes.Length); } else if (resourceSavingInfo.ResourceType == SaveOptions.NodeLevelResourceType.Image) { Console.WriteLine("Image processed with handler. Length of content in bytes is " + resourceAsBytes.Length.ToString()); // Here You can put code that will save image to some storage, f.e database MemoryStream targetStream = new MemoryStream(); targetStream.Write(resourceAsBytes, 0, resourceAsBytes.Length); } // We should return URI bt which resource will be referenced in CSS(for font) // Or HTML(for images) // This is very siplistic way - here we just return file name or resource. // You can put here some URI that will include ID of resource in database etc. // - this URI will be added into result CSS or HTML to refer the resource return resourceSavingInfo.SupposedFileName; }
///<summary> /// Tidies the XML file by formatting it in alphabetical order. ///</summary> ///<param name="inputXml"></param> ///<param name="saveOptions">Allows choosing between formatted/non-formatter output</param> ///<returns></returns> public string Tidy(string inputXml, SaveOptions saveOptions) { var xmlDoc = XDocument.Parse(inputXml,LoadOptions.PreserveWhitespace); var first = xmlDoc.Elements().First(); first.ReplaceWith(GetOrderedElement(first)); return xmlDoc.Declaration + xmlDoc.ToString(saveOptions); }
private string SaveXElement(object elem, SaveOptions so) { string retVal = null; switch (_mode) { case "Save": using (StringWriter sw = new StringWriter()) { if (_type.Name == "XElement") { (elem as XElement).Save(sw, so); } else if (_type.Name == "XDocument") { (elem as XDocument).Save(sw, so); } retVal = sw.ToString(); } break; case "ToString": if (_type.Name == "XElement") { retVal = (elem as XElement).ToString(so); } else if (_type.Name == "XDocument") { retVal = (elem as XDocument).ToString(so); } break; default: TestLog.Compare(false, "TEST FAILED: wrong mode"); break; } return retVal; }
// ExStart:PrefixForFontsHelper private static string CustomResourcesProcessing(SaveOptions.ResourceSavingInfo resourceSavingInfo) { //----------------------------------------------------------------------------- // It's just example of possible realization of cusstom processing of resources // Referenced in result HTML //----------------------------------------------------------------------------- // 1) In this case we need only do something special // with fonts, so let's leave processing of all other resources // to converter itself if (resourceSavingInfo.ResourceType != SaveOptions.NodeLevelResourceType.Font) { resourceSavingInfo.CustomProcessingCancelled = true; return ""; } // If supplied font resource, process it ourselves // 1) Write supplied font with short name to desired folder // You can easily do anythings - it's just one of realizations _fontNumberForUniqueFontFileNames++; string shortFontFileName = (_fontNumberForUniqueFontFileNames.ToString() + Path.GetExtension(resourceSavingInfo.SupposedFileName)); string outFontPath = _desiredFontDir + "\\" + shortFontFileName; System.IO.BinaryReader fontBinaryReader = new BinaryReader(resourceSavingInfo.ContentStream); System.IO.File.WriteAllBytes(outFontPath, fontBinaryReader.ReadBytes((int)resourceSavingInfo.ContentStream.Length)); // 2) Return the desired URI with which font will be referenced in CSSes string fontUrl = "http:// Localhost:255/document-viewer/GetFont/" + shortFontFileName; return fontUrl; }
public override int SaveChanges(SaveOptions options) { BeforeSaveChanges(this); var result = base.SaveChanges(options); AfterSaveChanges(this); return result; }
/// <summary> /// Преобразовать документ в XML-строку /// </summary> /// <param name="document"> Документ </param> /// <param name="encoding"> Кодировка документа </param> /// <param name="options"> Опции сохранения </param> /// <returns> </returns> public static string ToXml(this XDocument document, Encoding encoding, SaveOptions options) { using (var writer = new EncodedStringWriter(encoding)) { document.Save(writer, options); return writer.ToString(); } }
public void SaveChanges(SaveOptions saveOptions) { if (IsInTransaction) { throw new ApplicationException("A transaction is currently open. Use RollBackTransaction or CommitTransaction instead."); } ((IObjectContextAdapter)_dbContext).ObjectContext.SaveChanges(saveOptions); }
public override int SaveChanges(SaveOptions options) { foreach(ObjectStateEntry objectStateEntry in ObjectStateManager.GetObjectStateEntries(EntityState.Added)) { if(objectStateEntry.Entity is Event) { ((Event)objectStateEntry.Entity).BeforeSave(); } } return base.SaveChanges(options); }
public void SaveChanges(SaveOptions saveOptions) { if (IsInTransaction) { throw new ApplicationException("A transaction is running. Call CommitTransaction instead."); } ((IObjectContextAdapter)_dbContext).ObjectContext.SaveChanges(saveOptions); }
public int SaveChanges(SaveOptions options, bool logChanges) { int result = base.SaveChanges(options); if(SavedChanges != null) SavedChanges(this, null); return result; }
public override int SaveChanges(SaveOptions options) { int result = base.SaveChanges(options); if (SavedChanges != null) SavedChanges(this, new EventArgs()); return result; }
public override int SaveChanges(SaveOptions options) { var changes = ObjectStateManager.GetObjectStateEntries(EntityState.Unchanged); foreach (var change in changes) { var entityWithId = change.Entity as EntityWithId; if (entityWithId != null) ChangeStateOfEntity(ObjectStateManager, entityWithId); } return base.SaveChanges(options); }
public string ToString (SaveOptions options) { StringWriter sw = new StringWriter (); XmlWriterSettings s = new XmlWriterSettings (); s.ConformanceLevel = ConformanceLevel.Auto; s.Indent = options != SaveOptions.DisableFormatting; XmlWriter xw = XmlWriter.Create (sw, s); WriteTo (xw); xw.Close (); return sw.ToString (); }
/// <summary> /// 把 XElement 转换为 XML 格式的字符串 /// </summary> /// <param name="rootElement"></param> /// <param name="saveOptions"></param> /// <returns></returns> public static string ToXmlText(this XElement rootElement, SaveOptions saveOptions) { XDocument xdoc = new XDocument(rootElement); xdoc.Declaration = new XDeclaration("1.0", "gb2312", null); MemoryStream htmlStream = new MemoryStream(); xdoc.Save(htmlStream, saveOptions); string htmlText = Encoding.GetEncoding("GB2312").GetString(htmlStream.ToArray()); htmlStream.Close(); return htmlText; }
public override int SaveChanges(SaveOptions options) { var si = SessionInfo.Get(); if (sharedClient != null && si.currentTopicId != -1 && si.discussion != null) { //added foreach (ObjectStateEntry entry in ObjectStateManager.GetObjectStateEntries(EntityState.Added)) { if (entry.Entity is ArgPoint) { ((ArgPoint) entry.Entity).ChangesPending = false; sharedClient.clienRt.SendStatsEvent(StEvent.BadgeCreated, si.person.Id, si.discussion.Id, si.currentTopicId, DeviceType.Wpf); } } //edited foreach (ObjectStateEntry entry in ObjectStateManager.GetObjectStateEntries(EntityState.Modified)) { if (entry.Entity is ArgPoint) { ((ArgPoint) entry.Entity).ChangesPending = false; sharedClient.clienRt.SendStatsEvent(StEvent.BadgeEdited, SessionInfo.Get().person.Id, si.discussion.Id, si.currentTopicId, DeviceType.Wpf); } } //sources/comments/media modified foreach (ObjectStateEntry entry in ObjectStateManager.GetObjectStateEntries(EntityState.Unchanged)) { if (entry.Entity is ArgPoint) { var ap = (ArgPoint) entry.Entity; if (ap.ChangesPending) { ap.ChangesPending = false; sharedClient.clienRt.SendStatsEvent(StEvent.BadgeEdited, si.person.Id, si.discussion.Id, si.currentTopicId, DeviceType.Wpf); } } } } return base.SaveChanges(options); }
// ExStart:PrefixForURLsHelper private static string Custom_processor_of_embedded_images(SaveOptions.ResourceSavingInfo resourceSavingInfo) { // ____________________________________________________________________________ // This sample method saving strategy method saves image-files in some folder // (including raster image files that are exctracted from that SVGs) // Then it returns specific custom artificial path // to be used as value of 'src' or 'data' relevant attribute in generated host-SVG(or HTML) // ____________________________________________________________________________ //--------------------------------------------------------- // 1) All other files(f.e. fonts) will be processed with converter itself cause for them flag // resourceSavingInfo.CustomProcessingCancelled is set to 'true' //--------------------------------------------------------- if (!(resourceSavingInfo is HtmlSaveOptions.HtmlImageSavingInfo)) { resourceSavingInfo.CustomProcessingCancelled = true; return ""; } //--------------------------------------------------------- // 1) Create target folder if not created yet //--------------------------------------------------------- string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion_PDFToHTMLFormat(); string outDir = dataDir + @"output\36297_files\"; string outPath = outDir + Path.GetFileName(resourceSavingInfo.SupposedFileName); if (!Directory.Exists(outDir)) { Directory.CreateDirectory(outDir); } //--------------------------------------------------------- // 3) Write supplied image to that folder //--------------------------------------------------------- System.IO.BinaryReader reader = new BinaryReader(resourceSavingInfo.ContentStream); System.IO.File.WriteAllBytes(dataDir, reader.ReadBytes((int)resourceSavingInfo.ContentStream.Length)); //--------------------------------------------------------- // 4) Return customized specific URL to be used to refer // just created image in parent SVG (or HTML) //--------------------------------------------------------- HtmlSaveOptions.HtmlImageSavingInfo asHtmlImageSavingInfo = resourceSavingInfo as HtmlSaveOptions.HtmlImageSavingInfo; if (asHtmlImageSavingInfo.ParentType == HtmlSaveOptions.ImageParentTypes.SvgImage) { return "http:// Localhost:255/" + resourceSavingInfo.SupposedFileName; } else { return "http:// Localhost:GetImage/imageID=" + resourceSavingInfo.SupposedFileName; } }
public static HttpContent ToContent(this XElement element, SaveOptions options = SaveOptions.None) { FX.ThrowIfNull(element, "element"); var stream = new MemoryStream(); try { element.Save(stream, options); stream.Position = 0; var content = new StreamContent(stream); return content; } catch { stream.Dispose(); throw; } }
public override int SaveChanges(SaveOptions options) { var changes = this.ObjectStateManager.GetObjectStateEntries( EntityState.Modified | EntityState.Added | EntityState.Deleted); foreach (var change in changes) { var entity = change.Entity as IEntityTracking; if (entity != null) { if (change.State == EntityState.Deleted) { change.ChangeState(EntityState.Modified); entity.IsDeleted = true; } entity.LastUpdated = DateTime.Now.Ticks; } } return base.SaveChanges(options); }
public MsgWithDetails ACSaveChanges(bool autoSaveContextIPlus = true, SaveOptions saveOptions = SaveOptions.AcceptAllChangesAfterSave, bool validationOff = false, bool writeUpdateInfo = true) { MsgWithDetails result = _ObjectContextHelper.ACSaveChanges(autoSaveContextIPlus, saveOptions, validationOff, writeUpdateInfo); if (result == null) { if (ACChangesExecuted != null) { ACChangesExecuted.Invoke(this, new ACChangesEventArgs(ACChangesEventArgs.ACChangesType.ACSaveChanges, true)); } } else { if (ACChangesExecuted != null) { ACChangesExecuted.Invoke(this, new ACChangesEventArgs(ACChangesEventArgs.ACChangesType.ACSaveChanges, false)); } } return(result); }
/// <summary> /// Saves the <paramref name="document"/> to the <paramref name="file"/>. /// </summary> /// <param name="document">The XDocument to save</param> /// <param name="file">The file to save to</param> /// <param name="options">The options passed to XDocument.Save</param> /// <returns></returns> public static async Task SaveAsync(this XDocument document, StorageFile file, SaveOptions options) { if (document == null) { throw new ArgumentNullException("document", "document cannot be null"); } if (file == null) { throw new ArgumentNullException("file", "file cannot be null"); } using (var irStream = await file.OpenAsync(FileAccessMode.ReadWrite)) { using (var wstream = irStream.AsStreamForWrite()) { document.Save(wstream, options); } } }
/// <summary> /// Salva o documento. /// </summary> /// <param name="path">The path.</param> /// <param name="options">The options.</param> /// <param name="encoding">The encoding.</param> /// <returns>TDocument.</returns> public virtual void Save(string path, SaveOptions options = SaveOptions.DisableFormatting, Encoding encoding = null) { var serializer = new DFeSerializer <TDocument>(); if (!options.HasFlag(SaveOptions.None)) { serializer.Options.RemoverAcentos = options.HasFlag(SaveOptions.RemoveAccents); serializer.Options.RemoverEspacos = options.HasFlag(SaveOptions.RemoveSpaces); serializer.Options.FormatarXml = !options.HasFlag(SaveOptions.DisableFormatting); serializer.Options.OmitirDeclaracao = options.HasFlag(SaveOptions.OmitDeclaration); } if (encoding != null) { serializer.Options.Encoding = encoding; } serializer.Serialize(this, path); Xml = File.ReadAllText(path, serializer.Options.Encoding); }
/// <summary> /// Compacts the central file. /// </summary> /// <param name="app"></param> /// <param name="centralPath"></param> public static void CompactCentralFile(this Application app, string centralPath) { if (app == null) { throw new ArgumentNullException(nameof(app)); } if (centralPath == null) { throw new ArgumentNullException(nameof(centralPath)); } var doc = app.OpenDocumentFile(centralPath); var option = new SaveOptions { Compact = true }; doc.Save(option); doc.Close(false); }
public void Save(string filename, SaveOptions options) { XmlWriterSettings s = new XmlWriterSettings(); if ((options & SaveOptions.DisableFormatting) == SaveOptions.None) { s.Indent = true; } #if NET_4_0 if ((options & SaveOptions.OmitDuplicateNamespaces) == SaveOptions.OmitDuplicateNamespaces) { s.NamespaceHandling |= NamespaceHandling.OmitDuplicates; } #endif using (XmlWriter w = XmlWriter.Create(filename, s)) { Save(w); } }
public void SaveOptionAffectsConsolidationDataValidationRanges(bool consolidateDataValidationRanges, int expectedCount) { var options = new SaveOptions { ConsolidateDataValidationRanges = consolidateDataValidationRanges }; var wb = new XLWorkbook(); var ws = wb.AddWorksheet("Sheet"); ws.Range("C2:C5").SetDataValidation().Decimal.Between(1, 5); ws.Range("D2:D5").SetDataValidation().Decimal.Between(1, 5); using (var ms = new MemoryStream()) { wb.SaveAs(ms, options); var wb_saved = new XLWorkbook(ms); Assert.AreEqual(expectedCount, wb_saved.Worksheet("Sheet").DataValidations.Count()); } }
/// <summary> /// Output this <see cref="XDocument"/> to a file. /// </summary> /// <param name="fileName"> /// The name of the file to output the XML to. /// </param> /// <param name="options"> /// If SaveOptions.DisableFormatting is enabled the output is not indented. /// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed. /// </param> public void Save(string fileName, SaveOptions options) { XmlWriterSettings ws = GetXmlWriterSettings(options); if (_declaration != null && !string.IsNullOrEmpty(_declaration.Encoding)) { try { ws.Encoding = Encoding.GetEncoding(_declaration.Encoding); } catch (ArgumentException) { } } using (XmlWriter w = XmlWriter.Create(fileName, ws)) { Save(w); } }
protected void BTN_Attach_Click(object sender, EventArgs e) { QuoteName = (String.IsNullOrEmpty(QuoteName) ? "Aspose .NET Quote Generator" : QuoteName); Stream stream = GenerateStreamFromString(editor1.InnerText); LoadOptions loadOptions = new LoadOptions(); loadOptions.LoadFormat = LoadFormat.Html; Document myDoc = new Document(stream, loadOptions); MemoryStream memStream = new MemoryStream(); myDoc.Save(memStream, SaveOptions.CreateSaveOptions(SaveFormat.Docx)); byte[] byteData = memStream.ToArray(); // Encode the data using base64. string encodedData = System.Convert.ToBase64String(byteData); Entity NewNote = new Entity("annotation"); // Im going to add Note to entity NewNote.Attributes.Add("objectid", new EntityReference("quote", QuoteId)); NewNote.Attributes.Add("subject", QuoteName); // Set EncodedData to Document Body NewNote.Attributes.Add("documentbody", encodedData); // Set the type of attachment NewNote.Attributes.Add("mimetype", @"application/vnd.openxmlformats-officedocument.wordprocessingml.document"); NewNote.Attributes.Add("notetext", "Document Created using template"); // Set the File Name NewNote.Attributes.Add("filename", QuoteName + ".docx"); Guid NewNoteId = Service.Create(NewNote); if (NewNoteId != Guid.Empty) { LBL_Message.Text = "Successfully added to Quote"; } }
public override int SaveChanges(SaveOptions options) { DetectChanges(); if (PersistenceNotification != null) { ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted).ForEach(e => PersistenceNotification.BeforePersistence(e, this)); } var result = base.SaveChanges(SaveOptions.None); if (PersistenceNotification != null) { ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted).ForEach(e => PersistenceNotification.AfterPersistence(e, this)); } if (options.HasFlag(SaveOptions.AcceptAllChangesAfterSave)) { this.AcceptAllChanges(); } return(result); }
//[Variation(Priority = 0, Desc = "Multiple annotations in the tree - up/down - XElement", Param = typeof(XElement))] //[Variation(Priority = 0, Desc = "Multiple annotations in the tree - up/down - XDocument", Param = typeof(XDocument))] public void MultipleAnnotationsInTree2() { Type t = CurrentChild.Param as Type; string xml = @"<A xmlns:p='a1'><B xmlns:q='a2'><C xmlns:p='a1'><D xmlns:q='a2' ><E xmlns:p='a1' /></D></C></B></A>"; XContainer reF = (t == typeof(XElement) ? XElement.Parse(xml) as XContainer : XDocument.Parse(xml) as XContainer); // I want dynamics!!! SaveOptions[] options = new SaveOptions[] { SaveOptions.None, SaveOptions.DisableFormatting, SaveOptions.OmitDuplicateNamespaces, SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces }; foreach (SaveOptions[] opts in Tuples2(options)) { XContainer gp = (t == typeof(XElement) ? XElement.Parse(xml) as XContainer : XDocument.Parse(xml) as XContainer); gp.AddAnnotation(opts[0]); gp.Descendants("C").First().AddAnnotation(opts[1]); TestLog.Compare(reF.ToString(opts[0]), gp.ToString(), "On root - ToString()"); ReaderDiffNSAware.CompareNamespaceAware(opts[0], reF.CreateReader(), gp.CreateReader()); TestLog.Compare(reF.Descendants("B").First().ToString(opts[0]), gp.Descendants("B").First().ToString(), "On C - ToString()"); ReaderDiffNSAware.CompareNamespaceAware(opts[0], reF.Descendants("B").First().CreateReader(), gp.Descendants("B").First().CreateReader()); } }
/// <summary> /// Get source document from Stream /// </summary> public static void GetSrcDocFromStream() { // setup Signature configuration var signConfig = new SignatureConfig { OutputPath = @"c:\Test\Output" }; // instantiating the signature handler without Signature Config object var handler = new SignatureHandler(signConfig); // setup image signature options var signOptions = new PdfSignImageOptions(@"http://groupdocs.com/images/banner/carousel2/conversion.png"); // save options var saveOptions = new SaveOptions(OutputType.String); using (var fileStream = new FileStream(@"C:\test.pdf", FileMode.Open, FileAccess.Read)) { // sign document with image var signedPath = handler.Sign <string>(fileStream, signOptions, saveOptions); Console.WriteLine("Signed file path is: " + signedPath); } }
private string GetXmlString(SaveOptions o) { using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture)) { XmlWriterSettings ws = new XmlWriterSettings(); ws.OmitXmlDeclaration = true; if ((o & SaveOptions.DisableFormatting) == 0) { ws.Indent = true; } if ((o & SaveOptions.OmitDuplicateNamespaces) != 0) { ws.NamespaceHandling |= NamespaceHandling.OmitDuplicates; } using (XmlWriter w = XmlWriter.Create(sw, ws)) { WriteTo(w); } return(sw.ToString()); } }
/// <summary> /// 生成word /// </summary> /// <param name="templatePath">模版路径</param> /// <param name="dataTable">数据源</param> /// <param name="dataSet">生成表格数据源,每个DataTable的TableName为表格的名称</param> public static byte[] GenerateWord(string templatePath, DataTable dataTable, DataSet dataSet = null) { //载入模板 var doc = new Aspose.Words.Document(templatePath); //合并模版,相当于页面的渲染 if (dataTable != null) { doc.MailMerge.Execute(dataTable); } if (dataSet != null) { doc.MailMerge.ExecuteWithRegions(dataSet); } //更新所有域的值(为公式域重新计算值) doc.UpdateFields(); var docStream = new MemoryStream(); doc.Save(docStream, SaveOptions.CreateSaveOptions(SaveFormat.Doc)); return(docStream.ToArray()); }
/// <summary> /// Saves front model by front end. /// </summary> /// <param name="uiapp"></param> /// <param name="blankPath"></param> public static void SaveRevit(this UIApplication uiapp, string blankPath) { if (uiapp == null) { throw new ArgumentNullException(nameof(uiapp)); } if (blankPath == null) { throw new ArgumentNullException(nameof(blankPath)); } var doc = uiapp.ActiveUIDocument.Document; var saveOption = new SaveOptions { Compact = true }; doc.Save(saveOption); uiapp.OpenAndActivateDocument(blankPath); doc.Close(true); }
public string SaveFile(FileDescription fileDescription, Stream stream, SaveOptions saveOptions) { string key = GetOutputPath(fileDescription, saveOptions); stream.Seek(0, SeekOrigin.Begin); S3FileInfo fileInfo = new S3FileInfo(_client, bucketName, key); byte[] buffer = new byte[16384]; //16*1024 using (Stream output = fileInfo.Create()) { int read = stream.Read(buffer, 0, buffer.Length); while (read > 0) { output.Write(buffer, 0, read); read = stream.Read(buffer, 0, buffer.Length); } output.Flush(); output.Close(); } return(fileInfo.FullName); }
public IActionResult Create(WorkbookModel model) { if (!ModelState.IsValid) { return(View(model)); } var book = new ExcelFile(); var sheet = book.Worksheets.Add("Sheet1"); CellStyle style = sheet.Rows[0].Style; style.Font.Weight = ExcelFont.BoldWeight; style.HorizontalAlignment = HorizontalAlignmentStyle.Center; sheet.Columns[0].Style.HorizontalAlignment = HorizontalAlignmentStyle.Center; sheet.Columns[0].SetWidth(50, LengthUnit.Pixel); sheet.Columns[1].SetWidth(150, LengthUnit.Pixel); sheet.Columns[2].SetWidth(150, LengthUnit.Pixel); sheet.Cells["A1"].Value = "ID"; sheet.Cells["B1"].Value = "First Name"; sheet.Cells["C1"].Value = "Last Name"; for (int r = 1; r <= model.Items.Count; r++) { WorkbookItemModel item = model.Items[r - 1]; sheet.Cells[r, 0].Value = item.Id; sheet.Cells[r, 1].Value = item.FirstName; sheet.Cells[r, 2].Value = item.LastName; } SaveOptions options = GetSaveOptions(model.SelectedFormat); using (var stream = new MemoryStream()) { book.Save(stream, options); return(File(stream.ToArray(), options.ContentType, "Create." + model.SelectedFormat.ToLower())); } }
public async Task ExceptionThrownOnServer() { var em1 = await TestFns.NewEm(_serviceName); // ok(true, "Skipped test - OData does not support server interception or alt resources"); var q = new EntityQuery <Order>().Take(1); var orders = await em1.ExecuteQuery(q); var order = orders.First(); order.Freight = order.Freight + .5m; var so = new SaveOptions("SaveAndThrow", tag: "SaveAndThrow"); try { var sr = await em1.SaveChanges(null, so); Assert.Fail("should not get here"); } catch (SaveException se) { Assert.IsTrue(se.Message.Contains("Deliberately thrown"), "message should be correct"); } }
// ExStart:SpecifyPrefixForImagesHelper private static string SavingTestStrategy_1(SaveOptions.ResourceSavingInfo resourceSavingInfo) { // This sample method saving strategy method saves only svg-files in some folder and returns specific path // To be used as value of 'src' or 'data' relevant attribute in generated HTML // All other files will be processed with converter itself cause for them flag // ResourceSavingInfo.CustomProcessingCancelled is set to 'true' // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion_PDFToHTMLFormat(); if (!(resourceSavingInfo is HtmlSaveOptions.HtmlImageSavingInfo)) { resourceSavingInfo.CustomProcessingCancelled = true; return ""; } HtmlSaveOptions.HtmlImageSavingInfo asHtmlImageSavingInfo = (HtmlSaveOptions.HtmlImageSavingInfo)resourceSavingInfo; if ((asHtmlImageSavingInfo.ImageType != HtmlSaveOptions.HtmlImageType.Svg) && (asHtmlImageSavingInfo.ImageType != HtmlSaveOptions.HtmlImageType.ZippedSvg) ) { resourceSavingInfo.CustomProcessingCancelled = true; return ""; } string outFile = dataDir + "SpecifyImages_out.html"; string imageOutFolder = Path.GetFullPath(Path.GetDirectoryName(outFile) + @"\35956_svg_files\"); // ImageOutFolder="C:\AsposeImagesTests\"; if (!Directory.Exists(imageOutFolder)) { Directory.CreateDirectory(imageOutFolder); } string outPath = imageOutFolder + Path.GetFileName(resourceSavingInfo.SupposedFileName); System.IO.BinaryReader reader = new BinaryReader(resourceSavingInfo.ContentStream); System.IO.File.WriteAllBytes(outPath, reader.ReadBytes((int)resourceSavingInfo.ContentStream.Length)); return "/document-viewer/GetImage?path=CRWU-NDWAC-Final-Report-12-09-10-2.pdf&name=" + resourceSavingInfo.SupposedFileName; }
/// <summary> /// Output this <see cref="XDocument"/> to a <see cref="Stream"/>. /// </summary> /// <param name="stream"> /// The <see cref="Stream"/> to output the XML to. /// </param> /// <param name="options"> /// If SaveOptions.DisableFormatting is enabled the output is not indented. /// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed. /// </param> /// <param name="cancellationToken">A cancellation token.</param> public async Task SaveAsync(Stream stream, SaveOptions options, CancellationToken cancellationToken) { XmlWriterSettings ws = GetXmlWriterSettings(options); ws.Async = true; if (_declaration != null && !string.IsNullOrEmpty(_declaration.Encoding)) { try { ws.Encoding = Encoding.GetEncoding(_declaration.Encoding); } catch (ArgumentException) { } } using (XmlWriter w = XmlWriter.Create(stream, ws)) { await WriteToAsync(w, cancellationToken).ConfigureAwait(false); } }
private string GetXmlString(SaveOptions o) { using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture)) { XmlWriterSettings settings = new XmlWriterSettings { OmitXmlDeclaration = true }; if ((o & SaveOptions.DisableFormatting) == SaveOptions.None) { settings.Indent = true; } if ((o & SaveOptions.OmitDuplicateNamespaces) != SaveOptions.None) { settings.NamespaceHandling |= NamespaceHandling.OmitDuplicates; } using (XmlWriter writer2 = XmlWriter.Create(writer, settings)) { this.WriteTo(writer2); } return writer.ToString(); } }
public static bool Load(SaveOptions saveOptions = null) { if (saveOptions == null) { saveOptions = new SaveOptions(); } ProfileLoader.Load(); string path = saveOptions.path; if (File.Exists(path)) { string saveJson = File.ReadAllText(path); if (!LoadFromJson(saveJson)) { BackupCorruptSave(path); return(false); } return(true); } return(false); }
public string GetDownloadLink(string ext) { _Document doc = new _Document(dir + FileId); SaveOptions options = SaveOptions.CreateSaveOptions(FileId); string newFileName = FileId.Split('.')[0] + "." + ext; switch (ext) { case "rtf": doc.Save(dir + newFileName, Aspose.Words.SaveFormat.Rtf); break; case "pdf": doc.Save(dir + newFileName, Aspose.Words.SaveFormat.Pdf); break; default: doc.Save(dir + FileId); break; } return("/api/documents/" + newFileName); }
public int SaveChanges(SaveOptions options, bool markModifiedEntities) { try { if (markModifiedEntities) { foreach (ObjectStateEntry entry in ObjectStateManager.GetObjectStateEntries(EntityState.Modified)) { if (entry.Entity is IExportableEntity) { ((IExportableEntity)entry.Entity).UpdateStatus(EntityStatus.Modified); } } } return base.SaveChanges(options); } catch (Exception ex) { System.Diagnostics.Trace.TraceError(ex.ToString()); throw; } }
public async Task <OperationDetails> SaveExtra(string name, SaveOptions options) { try { var list = GetItems().Where(x => (x.TypeOperation == 1 || x.TypeOperation == 2 || x.TypeOperation == 3) && x.ExtraSend); if (list.Count() == 0) { return(new OperationDetails(false, "Нет анкет для выгрузки", "")); } XDocument xDoc = CreateDoc(list); xDoc.Save(name, options); //mark item unloaded await SendItems(list); return(new OperationDetails(true, "XML файл создан", "")); } catch (Exception ex) { return(new OperationDetails(false, "Не удалось выгрузить анкеты. " + ex.Message, "")); } }
private string GetXmlString(SaveOptions o) { using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture)) { XmlWriterSettings settings = new XmlWriterSettings { OmitXmlDeclaration = true }; if ((o & SaveOptions.DisableFormatting) == SaveOptions.None) { settings.Indent = true; } if ((o & SaveOptions.OmitDuplicateNamespaces) != SaveOptions.None) { settings.NamespaceHandling |= NamespaceHandling.OmitDuplicates; } using (XmlWriter writer2 = XmlWriter.Create(writer, settings)) { this.WriteTo(writer2); } return(writer.ToString()); } }
/// <summary> /// Saves or updates the entity without its children. /// </summary> /// /// <param name="entity"> /// Entity to save or update. /// </param> /// /// <param name="options"> /// Optional options. /// </param> /// /// <returns> /// The number of affected rows. /// </returns> private int Persist(ref VahapYigit.Test.Models.ProcessErrorLog entity, SaveOptions options = null) { if (entity.State != VahapYigit.Test.Models.EntityState.ToInsert && entity.State != VahapYigit.Test.Models.EntityState.ToUpdate) { return(0); } IList <TranslationEnum> errors; if (!entity.IsValid(out errors)) { throw new EntityValidationException(errors); } int rowCount = 0; using (var et = new ExecutionTracerService(tag: entity.State.ToString())) { var parameters = new Dictionary <string, object>(); parameters.Add("@ProcessErrorLog_Id", entity.Id); parameters.Add("@ProcessErrorLog_Date", entity.Date); parameters.Add("@ProcessErrorLog_ProcedureName", entity.ProcedureName); parameters.Add("@ProcessErrorLog_ErrorMessage", entity.ErrorMessage); parameters.Add("@ProcessErrorLog_ErrorSeverity", entity.ErrorSeverity); parameters.Add("@ProcessErrorLog_ErrorState", entity.ErrorState); parameters.Add("@ProcessErrorLog_Data", entity.Data); var collection = base.ToEntityCollection("ProcessErrorLog_Save", parameters, withDeepMapping: false); if (!collection.IsNullOrEmpty()) { entity.Map(collection[0]); rowCount = 1; } return(rowCount); } }
protected void BTN_Download_Click(object sender, EventArgs e) { Stream stream = GenerateStreamFromString(editor1.InnerText); LoadOptions loadOptions = new LoadOptions(); loadOptions.LoadFormat = LoadFormat.Html; Document myDoc = new Document(stream, loadOptions); MemoryStream memStream = new MemoryStream(); myDoc.Save(memStream, SaveOptions.CreateSaveOptions(SaveFormat.Docx)); Response.Clear(); Response.ContentType = "Application/msword"; Response.AddHeader("Content-Disposition", "attachment; filename=" + (String.IsNullOrEmpty(QuoteName) ? "Aspose .NET Quote Generator" : QuoteName) + ".docx"); Response.BinaryWrite(memStream.ToArray()); // myMemoryStream.WriteTo(Response.OutputStream); //works too Response.Flush(); Response.Close(); Response.End(); }
protected ExcelHelper(string inputFile, bool mustExists = false, string summarySheetName = "SUMMARY") { this._defaultSummarySheetName = summarySheetName; this._defaultSaveOptions = new SaveOptions(); _defaultSaveOptions.EvaluateFormulasBeforeSaving = false; _defaultSaveOptions.ValidatePackage = false; bool fileExists = File.Exists(inputFile); if (fileExists == false & mustExists == true) { throw new Exception("File " + inputFile + " not Found"); } else if (fileExists == false & mustExists == false) { try { this._CreateFile(inputFile); this._workbook = new XLWorkbook(XLEventTracking.Disabled); } catch (Exception ex) { //SD.Log(ex.Message + " " + ex.Source, SD.LogLevel.Error, ex.StackTrace); return; } } else if (fileExists == true) { try { this._workbook = new XLWorkbook(XLEventTracking.Disabled); } catch (Exception ex) { //SD.Log(ex.Message, SD.LogLevel.Error, ex.StackTrace); } } this._inputFile = new FileInfo(inputFile); }
private string SaveXElement(object elem, SaveOptions so) { string retVal = null; switch (_mode) { case "Save": using (StringWriter sw = new StringWriter()) { if (_type.Name == "XElement") { (elem as XElement).Save(sw, so); } else if (_type.Name == "XDocument") { (elem as XDocument).Save(sw, so); } retVal = sw.ToString(); } break; case "ToString": if (_type.Name == "XElement") { retVal = (elem as XElement).ToString(so); } else if (_type.Name == "XDocument") { retVal = (elem as XDocument).ToString(so); } break; default: TestLog.Compare(false, "TEST FAILED: wrong mode"); break; } return(retVal); }
/// <summary> /// Word文件填充数据(书签)后导出 /// </summary> /// <param name="path">文件路径</param> /// <param name="dictBookMark">书签数据</param> /// <returns></returns> public static byte[] Report_Word(string path, Dictionary <string, string> dictBookMark) { //载入模板 var doc = new Document(path); //书签绑定值,用于单个字段 //Dictionary<string, string> dictBookMark = new Dictionary<string, string>(); dictBookMark.Add("MedicinalName", "品名-山药"); foreach (string name in dictBookMark.Keys) { var bookmark = doc.Range.Bookmarks[name]; if (bookmark != null) { bookmark.Text = dictBookMark[name]; } } //在MVC中采用,保存文档到流中,使用base.File输出该文件 var docStream = new MemoryStream(); doc.Save(docStream, SaveOptions.CreateSaveOptions(SaveFormat.Doc)); //return File(docStream.ToArray(), "application/msword", "Template.doc"); return(docStream.ToArray()); }
public ActionResult Export() { string tempPath = Server.MapPath($"~/Templates/Template-{FolderName}.doc"); var doc = new Document(tempPath); //载入模板 List <string> images = new List <string>(); DirectoryInfo root = new DirectoryInfo(Server.MapPath($"~/Digital/{FolderName}")); foreach (FileInfo f in root.GetFiles()) { images.Add(f.FullName); } for (int i = 1; i < images.Count + 1; i++) { doc.Range.Replace($"«Number{i}»", Path.GetFileNameWithoutExtension(images[i - 1]), false, false); doc.Range.Replace(new Regex($"Photo{i}&"), new ReplaceAndInsertImage(images[i - 1]), false); } var docStream = new MemoryStream(); doc.Save(docStream, SaveOptions.CreateSaveOptions(SaveFormat.Doc)); return(base.File(docStream.ToArray(), "application/msword", $"{FolderName}班(照片采集)-已完成" + ".doc")); }
/// <summary> /// 根据模板生成自评报告 /// </summary> /// <param name="entity"></param> /// <returns></returns> private bool GenReport(AssessmentPlanEntity entity) { bool b = true; try { pCount = 0; kscoreCount = 0; reallyscore = 0; noSuitScore = 0; bscore = 0; string fileName = Server.MapPath("~/Resource/ExcelTemplate/自评报告模板.doc"); Document doc = new Document(fileName); DataSet ds = GetDataSet(entity); doc.MailMerge.ExecuteWithRegions(ds); string reportName = Server.MapPath(string.Format("~/Resource/ExcelTemplate/SelfReport/{0}-自评报告.doc", entity.PlanName)); doc.Save(reportName, SaveOptions.CreateSaveOptions(SaveFormat.Doc)); b = true; } catch (Exception ex) { b = false; throw ex; } return(b); }
public override int SaveChanges(SaveOptions options) { var changes = this.ObjectStateManager.GetObjectStateEntries( EntityState.Modified | EntityState.Added | EntityState.Deleted); foreach (var change in changes) { var entity = change.Entity as IEntityTracking; if (entity != null) { if (change.State == EntityState.Deleted) { change.ChangeState(EntityState.Modified); entity.IsDeleted = true; } entity.LastUpdated = DateTime.Now.Ticks; } } return(base.SaveChanges(options)); }
public override int SaveChanges(SaveOptions options) { this.DetectChanges(); foreach (var insert in this.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added)) { if (insert.Entity.HasProperty("DateCreated")) { insert.Entity.GetType().GetProperty("DateCreated").SetValue(insert.Entity, DateTime.UtcNow, null); } if (insert.Entity.HasProperty("LastModified")) { insert.Entity.GetType().GetProperty("LastModified").SetValue(insert.Entity, DateTime.UtcNow, null); } } foreach (var update in this.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified)) { if (update.Entity.HasProperty("LastModified")) { update.Entity.GetType().GetProperty("LastModified").SetValue(update.Entity, DateTime.UtcNow, null); } } return(base.SaveChanges(options)); }
public string ToString(SaveOptions options) { var builder = new StringBuilder(); ToString(builder); return builder.ToString(); }
public virtual void Save(string fileName, SaveOptions options) { _xDocument.Save(fileName, options); }
public virtual void Save(TextWriter textWriter, SaveOptions options) { _xDocument.Save(textWriter, options); }
public void Save (Stream stream, SaveOptions options) { XmlWriterSettings s = new XmlWriterSettings (); if ((options & SaveOptions.DisableFormatting) == SaveOptions.None) s.Indent = true; if ((options & SaveOptions.OmitDuplicateNamespaces) == SaveOptions.OmitDuplicateNamespaces) s.NamespaceHandling |= NamespaceHandling.OmitDuplicates; using (var writer = XmlWriter.Create (stream, s)){ Save (writer); } }
public void Save (TextWriter tw, SaveOptions options) { XmlWriterSettings s = new XmlWriterSettings (); if ((options & SaveOptions.DisableFormatting) == SaveOptions.None) s.Indent = true; #if NET_4_0 || MOONLIGHT || MOBILE if ((options & SaveOptions.OmitDuplicateNamespaces) == SaveOptions.OmitDuplicateNamespaces) s.NamespaceHandling |= NamespaceHandling.OmitDuplicates; #endif using (XmlWriter w = XmlWriter.Create (tw, s)) { Save (w); } }
// // Summary: // Serialize this element to a System.IO.TextWriter, optionally disabling formatting. // // Parameters: // textWriter: // The System.IO.TextWriter to output the XML to. // // options: // A System.Xml.Linq.SaveOptions that specifies formatting behavior. public void Save(TextWriter textWriter, SaveOptions options) { Contract.Requires(textWriter != null); }