I'm generating an asp:CheckBox dynamically and I need to validate that it is checked with a CustomValidator().
private void AddCheckBox(HtmlGenericControl newDiv, AdditionalFields field)
{
var additionalFieldDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
additionalFieldDiv.Attributes.Add("class", "additional-field-row");
var additionalLabel = new RadLabel();
additionalLabel.Text = field.Label;
additionalLabel.ID = "AdditionalLabel" + field.ControlId;
additionalLabel.CssClass += "title ";
additionalLabel.Width = new Unit(field.LabelWidth ?? 175);
if (field.Required??false) additionalLabel.CssClass += "additional-field-required";
var additionalField = new System.Web.UI.WebControls.CheckBox();
additionalField.ID = "AdditionalField" + field.ControlId;
additionalField.CssClass += "additional-field-checkbox";
additionalField.Width = new Unit(field.Width ?? 200);
var customValidator = new CustomValidator();
customValidator.ID = "CustomValidator" + field.ControlId;
//customValidator.ClientValidationFunction = "CheckBoxValidation(AdditionalField"+ field.ControlId +")";
customValidator.ControlToValidate = "AdditionalField" + field.ControlId;
customValidator.ErrorMessage = string.IsNullOrEmpty(field.ErrorMessage) ? field.Label + " required" : field.ErrorMessage;
customValidator.CssClass += "additional-fields-validator";
customValidator.Display = ValidatorDisplay.Dynamic;
customValidator.ValidationGroup = "valGroup";
customValidator.EnableClientScript = true;
newDiv.Controls.Add(additionalFieldDiv);
additionalFieldDiv.Controls.Add(additionalLabel);
additionalFieldDiv.Controls.Add(additionalField);
if (field.Required ?? false)
{
additionalFieldDiv.Controls.Add(customValidator);
}
}
I get an error if I try to use customValidator.ControlToValidate = "AdditionalField" + field.ControlId;
Control 'AdditionalField9' referenced by the ControlToValidate property of 'CustomValidator9' cannot be validated.
I have several other controls on the page that are in the validation group "valGroup" and I like the CheckBox validated client side. If I can't use the ControlToValidate property do I need to use JavaScript, and if so how do I pass the ID of the CheckBox to validate?
<script type = "text/javascript">
function ValidateCheckBox(sender, args) {
if (document.getElementById("<%=AdditionalField9.ClientID %>").checked == true) {
args.IsValid = true;
} else {
args.IsValid = false;
}
}
</script>
Hope you can help
I'm trying to create a pdf using MigraDoc. Here's a list of the libraries that I'm using:
MigraDoc.DocumentObjectModel
MigraDoc.DocumentObjectModel.Tables
MigraDoc.Rendering
It throws me an error on printer.RenderDocument(). Code below
private async Task SavePDF()
{
filePath = emulatorFolderPath + "/Signed/" + _reportInformationViewModel.SelectedClient.Username + "-" + DateTime.Now.ToString("dd_MM_yyyy HH-mm") + ".pdf";
MigraDocRendering.PdfDocumentRenderer printer = new MigraDocRendering.PdfDocumentRenderer
{
Document = document
};
printer.RenderDocument();
printer.PdfDocument.Save(filePath);
}
PS: I don't need to use a private font.
I've resolved by implementing IFontResolver
I've added a folder Fonts that contains Open-Sans font.
I've created a folder Helpers that contains a class called GenericFontResolver:
public class GenericFontResolver : IFontResolver
{
public string DefaultFontName => "OpenSans";
public byte[] GetFont(string faceName)
{
if (faceName.Contains(DefaultFontName))
{
var assembly = typeof(ReportPreviewAndSignatureViewModel).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream($"PDFDemo.Fonts.{faceName}.ttf");
using (var reader = new StreamReader(stream))
{
var bytes = default(byte[]);
using (var ms = new MemoryStream())
{
reader.BaseStream.CopyTo(ms);
bytes = ms.ToArray();
}
return bytes;
}
}
else
return GetFont(DefaultFontName);
}
public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic)
{
var fontName = string.Empty;
switch (familyName)
{
case "Open Sans":
case "OpenSans":
fontName = "OpenSans";
if (isBold && isItalic)
fontName = $"{fontName}-BoldItalic";
else if (isBold)
fontName = $"{fontName}-Bold";
else if (isItalic)
fontName = $"{fontName}-Italic";
else
fontName = $"{fontName}-Regular";
return new FontResolverInfo(fontName);
default:
break;
}
return null;
}
}
Then, on the constructor of the class that needs the font I've added:
GlobalFontSettings.FontResolver = new GenericFontResolver();
Then, when I'm creating the table you must add:
Style style = document.Styles["Normal"];
style.Font.Name = "OpenSans";
I have form for upload file and i want to upload thumbnail for the file in the same form I am doing that with this part of code :
var basePath2 = Path.Combine(Directory.GetCurrentDirectory() + "\\Thumbnails\\");
bool basePathExists2 = System.IO.Directory.Exists(basePath2);
if (!basePathExists2)
Directory.CreateDirectory(basePath2);
var thumbnailPath = Path.Combine(basePath2, Thumbnail.FileName);
if (!System.IO.File.Exists(thumbnailPath))
{
using (var stream = new FileStream(thumbnailPath, FileMode.Create))
{
await Thumbnail.CopyToAsync(stream);
}
}
I am saving this model to the database:
var fileModel = new FileUploadViewModel
{
Year = createdOn,
PublishedOn = model.PublishedOn,
FileType = File.ContentType,
Extension = extension,
Name = model.Name,
Description = model.Description,
FilePath = filePath,
Author = model.Author,
ThumbnailPath = thumbnailPath,
};
When I want to show the thumbnail in a view, it doesn't work but in src I have the right path, as you can see in this screenshot:
Screenshot with Source of image
In controller :
string uniqueThumbName = null;
if (Thumbnail != null)
{
string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "Thumbnails");
uniqueThumbName=Guid.NewGuid().ToString() + "_" + Thumbnail.FileName;
string filePath2 = Path.Combine(uploadsFolder, uniqueThumbName);
Thumbnail.CopyTo(new FileStream(filePath2, FileMode.Create));
}
var fileModel = new FileUploadViewModel
{
ThumbnailPath=uniqueThumbName,
};
In View :
var thumbPath = "~/Thumbnails/" + file.ThumbnailPath;
<img style="width:80px;height:80px;" src="#thumbPath" asp-append-version="true" />
I'm trying to insert a signature image in a Word document created by a standard-letter generating application. I am using code adapted from various examples found on the web (see below). The application inserts the image, and the space in the document occupied by it is correct, but the image itself is not displayed.
I have tried it with both .png and .jpg images, but neither work; it doesn't appear to be a problem with the image itself.
I have examined the document using the OpenXml SDK Tool, which shows that the image is correctly embedded and encoded as a Base64 data string.
The problem that the SDK Tool does identify is that, compared to a document in which an image is manually inserted (and is correctly displayed), the pic:pic element in the document is rendered with the wrong namespace (a:pic) and it and all child controls are rendered as OpenXmlUnknownElement (see screenshot below).
Can anyone please tell me what is causing the incorrect namespace / element, and how to fix the problem?
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.Drawing;
using System.Drawing.Imaging;
...
using A = DocumentFormat.OpenXml.Drawing;
using A14 = DocumentFormat.OpenXml.Office2010.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
using WP = DocumentFormat.OpenXml.Wordprocessing;
private void ReplacePlaceholderWithImage(MainDocumentPart mainDocumentPart, OpenXmlElement placeholder, string imagePath)
{
if (placeholder != null)
{
ImagePart ip = AddImagePart(mainDocumentPart, imagePath);
string relationshipId = mainDocumentPart.GetIdOfPart(ip);
var drawing = GetDrawing(relationshipId, imagePath);
placeholder.InsertAfterSelf(new WP.Paragraph(new WP.Run(drawing)));
placeholder.Remove();
Console.WriteLine("Picture inserted into picture content control successfully");
}
}
private ImagePart AddImagePart(MainDocumentPart mainDocumentPart, string imagePath)
{
var partType = GetPartTypeForImage(imagePath);
ImagePart ip = mainDocumentPart.AddImagePart(partType);
using (FileStream fileStream = File.Open(imagePath, FileMode.Open))
{
ip.FeedData(fileStream);
}
return ip;
}
private OpenXmlElement GetDrawing(string relationshipId, string imagePath)
{
//calculate dimensions
var size = GetImageDimensions(imagePath);
// Define the reference of the image.
return
new Drawing(
new DW.Inline(
new DW.Extent()
{
Cx = size.Width,
Cy = size.Height
},
new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
new DW.DocProperties() { Id = 1U, Name = "Picture 1" },
new DW.NonVisualGraphicFrameDrawingProperties(new A.GraphicFrameLocks() { NoChangeAspect = true, NoResize = true, NoSelection = true }),
new A.Graphic(new A.GraphicData(new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties()
{
Id = 0U,
Name = Path.GetFileName(imagePath)
},
new PIC.NonVisualPictureDrawingProperties()),
new A.BlipFill(
new A.Blip(
new A.BlipExtensionList(
new A.BlipExtension()
{
Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"
}))
{
Embed = relationshipId,
CompressionState = A.BlipCompressionValues.Print
},
new A.Stretch(new A.FillRectangle())),
new A.ShapeProperties(
new A.Transform2D(new A.Offset() { X = 0L, Y = 0L }, new A.Extents() { Cx = size.Width, Cy = size.Width }),
new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle })))
{
Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
}))
{
DistanceFromTop = 0U,
DistanceFromBottom = 0U,
DistanceFromLeft = 0U,
DistanceFromRight = 0U,
EditId = "50D07946"
});
}
private ImagePartType GetPartTypeForImage(string imagePath)
{
var img = GetImage(imagePath);
if (img.RawFormat.Equals(ImageFormat.Gif))
{
return ImagePartType.Gif;
}
else if (img.RawFormat.Equals(ImageFormat.Png))
{
return ImagePartType.Png;
}
else if (img.RawFormat.Equals(ImageFormat.Jpeg))
{
return ImagePartType.Jpeg;
}
else
{
throw new ApplicationException("Unexpected image type");
}
}
this issue stressed me up some hours and finally I found the reason. That's because the Drawing element Id need to be unique, you can't fix the ID like this
new DW.DocProperties() { Id = 1U, Name = "Picture 1" }
In my case, I have this function to set alt text and update the Id as well:
private static HashSet<uint> _drawingElementIds = new HashSet<uint>();
public static void SetPictureAltText(OpenXmlElement imageContainer, string altText)
{
var docPro = imageContainer.Descendants<DocProperties>().FirstOrDefault();
if (docPro != null)
{
//Make sure new image has unique ID, otherwise some images won't display
var newId = (uint)new Random().Next(10, 10000);
while (_drawingElementIds.Contains(newId))
{
newId = (uint)new Random().Next(10, 10000);
}
_drawingElementIds.Add(newId);
docPro.Id = new UInt32Value(newId);
docPro.Description = altText;
}
}
Cheers,
Nick
Watch your namespaces! I'm guessing you've copied from the same source as I did (which I'm sure was the Microsoft documentation), however the namespaces appear to be wrong in it for the following two properties:
A.BlipFill -> PIC.BlipFill
A.ShapeProperties -> PIC.ShapeProperties
Full code below:
var element = new Drawing(
new DW.Inline(
new DW.Extent()
{
Cx = 5657850L,
Cy = 3771900L
},
new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
new DW.DocProperties() { Id = 1U, Name = "Picture 1" },
new DW.NonVisualGraphicFrameDrawingProperties(new A.GraphicFrameLocks() { NoChangeAspect = true, NoResize = true, NoSelection = true }),
new A.Graphic(new A.GraphicData(new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties()
{
Id = 0U,
Name = "image.png"
},
new PIC.NonVisualPictureDrawingProperties()),
new PIC.BlipFill(
new A.Blip(
new A.BlipExtensionList(
new A.BlipExtension()
{
Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"
}))
{
Embed = relationshipId,
CompressionState = A.BlipCompressionValues.Print
},
new A.Stretch(new A.FillRectangle())),
new PIC.ShapeProperties(
new A.Transform2D(new A.Offset() { X = 0L, Y = 0L }, new A.Extents() { Cx = 5657850L, Cy = 3771900L }),
new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle })))
{
Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
}))
{
DistanceFromTop = 0U,
DistanceFromBottom = 0U,
DistanceFromLeft = 0U,
DistanceFromRight = 0U,
EditId = "50D07946"
});
I am using uploadify for uploading multiple images with progress in ASP.NET MVC3 and I want to upload lets say from url Gallery/Upload/2 to folder with name 2 and Gallery/Upload/3 to folder 3 and so on. I just don´t know how. For get working uploading I used this sample and modified sample upload script to this:
public string Upload(HttpPostedFileBase fileData)
{
var id = 2;
var fotka = new Photo();
fotka.GalleryId = id;
fotka.Description = fileData.FileName;
fotka.Name = fileData.FileName;
db.Photos.Add(fotka);
db.SaveChanges();
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileData.FileName);
var fileName = Path.GetFileName(fileData.FileName);
string path = Server.MapPath("~/Fotky/") + id.ToString() + "\\" + fileNameWithoutExtension;
// var path = Path.Combine(Server.MapPath("~/Fotky/"), galleryId.ToString(), "/", fileNameWithoutExtension);
using (var input = new Bitmap(fileData.InputStream))
{
int width;
int height;
if (input.Width > input.Height)
{
width = 128;
height = 128 * input.Height / input.Width;
}
else
{
height = 128;
width = 128 * input.Width / input.Height;
}
using (var thumb = new Bitmap(width, height))
using (var graphic = Graphics.FromImage(thumb))
{
graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
graphic.DrawImage(input, 0, 0, width, height);
System.IO.Directory.CreateDirectory(Server.MapPath("~/Fotky/") + id.ToString());
using (var output = System.IO.File.Create(path + "_small" + Path.GetExtension(fileName)))
{
thumb.Save(output, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
fileData.SaveAs(path + Path.GetExtension(fileName));
return "ok";
}
as you can see I am using id as 2 as default, but I want to get it from parameters, is it posible? And how? Thank you
No one knows answer? It´s really important for me
You could have your controller action take the id as action argument:
public string Upload(HttpPostedFileBase fileData, string id)
{
...
}
and then pass this id when configuring your plugin:
$("#fileuploader").fileUpload({
'uploader': '#Url.Content("~/Scripts/uploader.swf")',
'cancelImg': '#Url.Content("~/Images/cancel.png")',
'buttonText': 'Select Image',
'script': '#Url.Action("Upload", "Home", new { id = "2" })',
'folder': '#Url.Content("~/uploads")',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
'multi': true,
'auto': true
});