Define the path data from code behind in silverlight - silverlight-4.0

I have the following below path data which is in xaml. I want to define the same path data from the code behind.
<Path Data="M 250,40 L200,20 L200,60 Z" />

From Codebehind :
Path orangePath = new Path();
PathFigure pathFigure = new PathFigure();
pathFigure.StartPoint = new Point(250, 40);
LineSegment lineSegment1 = new LineSegment();
lineSegment1.Point = new Point(200, 20);
pathFigure.Segments.Add(lineSegment1);
LineSegment lineSegment2 = new LineSegment();
lineSegment2.Point = new Point(200, 60);
pathFigure.Segments.Add(lineSegment2);
PathGeometry pathGeometry = new PathGeometry();
pathGeometry.Figures = new PathFigureCollection();
pathGeometry.Figures.Add(pathFigure);
orangePath.Data = pathGeometry;
Edit :
//we should have to set this true to draw the line from lineSegment2 to the start point
pathFigure.IsClosed = true;

You need to use a TypeConverter:
Path path = new Path();
string sData = "M 250,40 L200,20 L200,60 Z";
var converter = TypeDescriptor.GetConverter(typeof(Geometry));
path.Data = (Geometry)converter.ConvertFrom(sData);

Disclaimer: I've only done this with the Path as a DataTemplate as a listbox. Should work.
//of course the string could be passed in to a constructor, just going short route.
public class PathData
{
public string Path { get { return "M 250,40 L200,20 L200,60 Z"; } }
}
void foo()
{
var path = new Path() { Stroke = new SolidColorBrush(Colors.Black) };
var data = new PathData();
var binding = new Binding("Path") { Source=data, Mode=BindingMode.OneWay };
path.SetBinding(Path.DataProperty, binding);
}

Related

Simple serialize ODataQueryOptions

I'm trying to:
[EnableQuery]
[HttpGet]
[ODataRoute("")]
public IHttpActionResult Get(ODataQueryOptions<UserODataModel> options)
{
var users = _repository.RetrieveOData();
var serialQuery = JsonConvert.SerializeObject(options, jsonOptions);
//save serialQuery somewhere
return Ok(users);
}
But got
Newtonsoft.Json.JsonSerializationException: 'Error getting value from 'ReadTimeout' on 'Microsoft.Owin.Host.SystemWeb.CallStreams.InputStream'.'
"Timeouts are not supported on this stream."
I know there is already a question about serialize Stream:
Newtonsoft Json.net - how to serialize content of a stream?
But in this case i can't "extract stream value" from ODataQueryOptions, or can I?
Some ideia?
Since we work on the same company, if anyone is interested, we found a way, maybe not the pretty way, to serialize an ODataQueryOptions:
public static ODataQueryOptions DeserializeQueryOptions(SerializedQueryOptions options)
{
var uri = new Uri(teste.OriginalUri);
var model = ODataConfig.Model; //GetEdmModel
var segment = model.EntityContainer.FindEntitySet(options.EdmType);
var newPath = new Microsoft.AspNet.OData.Routing.ODataPath(new EntitySetSegment(segment));
var httpConfiguration = new HttpConfiguration();
httpConfiguration.EnableDependencyInjection();
var request = new HttpRequestMessage(HttpMethod.Get, uri)
{
Properties =
{
{ HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },
}
};
var context = new ODataQueryContext(model, options.EntityType, newPath);
var oDataQueryOptions = new ODataQueryOptions(context, request);
return oDataQueryOptions;
}
public static SerializedQueryOptions SerializeQueryOptions(ODataQueryOptions options)
{
return new SerializedQueryOptions
{
OriginalUri = options.Request.RequestUri.AbsoluteUri,
EdmType = options.Context.NavigationSource.Name,
EntityType = options.Context.ElementClrType
};
}
After you serialize it to an object you can serialize it to a JSON string:
var queryOptionsSerialized = new SerializedQueryOptions()
{
OriginalUri = "http://localhost:25723/odata/users?$skip=0&$top=2&$orderby=fullName&$count=true",
EdmType = "users",
EntityType = typeof(UserODataModel)
};
var json = JsonConvert.SerializeObject(queryOptionsSerialized);
var deserialized = JsonConvert.DeserializeObject<SerializedQueryOptions>(json);
var options = ODataQueryOptionsHelper.DeserializeQueryOptions(deserialized);
In case One is not using OData routing or using an ApiController (not ODataController),
modify the way of Obtaining ODataPath to:
ODataUriParser parser = new ODataUriParser(model, serviceRoot, requestUri);
ODataPath path = parser.ParsePath();
//var newPath = new Microsoft.AspNet.OData.Routing.ODataPath(new EntitySetSegment(segment));
Microsoft.AspNet.OData.Routing.ODataPath newPath = new Microsoft.AspNet.OData.Routing.ODataPath(path.FirstOrDefault());
where the serviceRoot is the Url part other that the path defined in the model.

Report Viewer and Web Api

In MVC I could generate .xsl or .pdf file with no issues with File(), but with the web Api nothing is happening when the action is fired! This is what I have tried so far.
I have tried a couple of solutions in here including this one Web API and report viewer
but nothing has worked for me.
public HttpResponseMessage Export(ExportVolunteerSearchFilter searchModel)
{
if (searchModel.Equals(null))
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
var volunteers = _volunteersService.ExportAllVolunteersData(searchModel);
ReportViewer ReportViewer1 = new ReportViewer();
ReportViewer1.SizeToReportContent = true;
ReportViewer1.LocalReport.ReportPath =
System.Web.HttpContext.Current.Server.MapPath("~/Reports/VolunteersReport.rdlc");
ReportViewer1.LocalReport.EnableExternalImages = true;
ReportViewer1.LocalReport.DataSources.Clear();
ReportDataSource _rsource = new ReportDataSource("DataSet1", volunteers);
ReportViewer1.LocalReport.DataSources.Add(_rsource);
ReportViewer1.LocalReport.Refresh();
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty;
string encoding = string.Empty;
string extension = string.Empty;
string fileName = "reportVolunteer";
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/Reports/VolunteersReport.rdlc"), FileMode.Open);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xls");
return response;
}
I have done it as:-
response.Content = new PushStreamContent(
async (outstream) =>
{
await getDataMethod(outstream)
},
new MediaTypeHeadrerValue(mediaType:"application/xls"));
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = $"test.xls"
};
return response;

itextsharp setting background opacity not working

I have the following code to set background color to one of my fields but for some reason I can not control the transparency of the background. Can someone please take a look at it and let me know what I am doing wrong. Thanks.
using (var newFileStream = new FileStream(fileNameNew, FileMode.Create))
{
// Open existing PDF
var pdfReader = new PdfReader(existingFileStream);
// PdfStamper, which will create
var stamper = new PdfStamper(pdfReader, newFileStream);
var form = stamper.AcroFields;
var fieldKeys = form.Fields.Keys;
foreach (string fieldKey in fieldKeys)
{
if (fieldKey.Equals("Title"))
{
form.SetFieldProperty(fieldKey, "bgcolor", new BaseColor(System.Drawing.Color.FromArgb(20,225,160,0)),null);
form.SetField(fieldKey, "Test");
}
else
{
form.SetField(fieldKey, "REPLACED!");
}
}
stamper.FormFlattening = true;
stamper.Close();
pdfReader.Close();
}
Just in case anyone else faces the same problem
var pdfReader = new PdfReader(existingFileStream);
// PdfStamper, which will create
var stamper = new PdfStamper(pdfReader, newFileStream);
var form = stamper.AcroFields;
var fieldKeys = form.Fields.Keys;
PdfContentByte background;
foreach (string fieldKey in fieldKeys)
{
if (fieldKey.Equals("Title"))
{
//form.SetFieldProperty(fieldKey, "bgColor", new BaseColor(System.Drawing.Color.FromArgb(125,225,160,0)),null);
form.SetField(fieldKey, "Test");
IList<AcroFields.FieldPosition> pos = form.GetFieldPositions(fieldKey);
PdfContentByte contentBtye = stamper.GetOverContent(pos[0].page);
contentBtye.SetColorFill(new BaseColor(200, 50, 50));
contentBtye.Rectangle(pos.FirstOrDefault().position.Left, pos.FirstOrDefault().position.Bottom, pos.FirstOrDefault().position.Width, pos.FirstOrDefault().position.Height);
PdfGState state = new PdfGState();
state.FillOpacity = 0.5f;
contentBtye.SetGState(state);
contentBtye.Fill();
}
else
{
form.SetField(fieldKey, "REPLACED!");
}
}

Convert and save MvcHtmlString to Image or PDF

I am currently working on an application that basically builds an MvcHtmlString by mapping a HtmlTemplate with some data dynamically.
What I want to be able to do is to Convert and save this MvcHtmlString as an Image/ PDF to my local disk.
Here is my function that produces the MvcHtmlString after mapping:
public static MvcHtmlString Map(this IDictionary<string, object> row, string htmlTemplate)
{
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(htmlTemplate);
foreach (var key in row.Keys)
{
var elements = htmlDoc.DocumentNode.SelectSingleNode("//body")
.Descendants()
.Where(d => d.Attributes
.Any(a => a.Name == "class" && a.Value == key));
if (elements != null && elements.Count() > 0)
{
foreach (var element in elements)
{
object attributeValue = null;
row.TryGetValue(key, out attributeValue);
if (element.HasChildNodes)
{
// We only get the first img element within the element
// as we dont expect there to be more than one <img> tag
// within a parent element
var imgChildNode = element.Descendants("img").FirstOrDefault();
if (imgChildNode != null)
{
imgChildNode.SetAttributeValue("src", attributeValue.ToString());
}
else
{
element.InnerHtml = string.Empty;
element.InnerHtml = attributeValue.ToString();
}
}
else
{
element.InnerHtml = string.Empty;
element.InnerHtml = attributeValue.ToString();
}
}
}
}
var sw = new StringWriter();
htmlDoc.Save(new StringWriter(sw.GetStringBuilder()));
var htmlString = MvcHtmlString.Create(sw.ToString());
return htmlString;
}
And then I am using this function to save an image (But this just renders a black block)
private void SaveImageFromHtml(MvcHtmlString html)
{
var decodedHtml = html.ToHtmlString();
Bitmap m_Bitmap = new Bitmap(600, 800);
PointF point = new PointF(0, 0);
SizeF maxSize = new System.Drawing.SizeF(600, 800);
HtmlRenderer.HtmlRender.Render(Graphics.FromImage(m_Bitmap), decodedHtml,
point, maxSize);
m_Bitmap.Save(#"D:\Test.png", ImageFormat.Png);
}
Any help will be appreciated!
Found the reason. The HtmlRenderer library that I was using didnt support "float" in css markup and hence the output image was messed up

iTextSharp XmlWorker: right-to-left

After a long time of struggling with this not-so-friendly API, I am finally making progress, but now I've come to a really nasty issue.. I have placed "dir" attributes in various places in my html with the value being "rtl".. but the XMLWorker doesn't seem to respect that at all. Does anyone know of a workaround? Here's my method:
public static void Generate<TModel>(string templateFile, TModel model, string outputFile, IEnumerable<string> fonts)
{
string template = System.IO.File.ReadAllText(templateFile);
string result = Razor.Parse(template, model);
using (var fsOut = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
using (var stringReader = new StringReader(result))
{
var document = new Document();
var pdfWriter = PdfWriter.GetInstance(document, fsOut);
pdfWriter.InitialLeading = 12.5f;
document.Open();
var xmlWorkerHelper = XMLWorkerHelper.GetInstance();
var cssResolver = new StyleAttrCSSResolver();
//cssResolver.AddCss(cssFile);
var xmlWorkerFontProvider = new XMLWorkerFontProvider();
foreach (string font in fonts)
{
xmlWorkerFontProvider.Register(font);
}
var cssAppliers = new CssAppliersImpl(xmlWorkerFontProvider);
var htmlContext = new HtmlPipelineContext(cssAppliers);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
PdfWriterPipeline pdfWriterPipeline = new PdfWriterPipeline(document, pdfWriter);
HtmlPipeline htmlPipeline = new HtmlPipeline(htmlContext, pdfWriterPipeline);
CssResolverPipeline cssResolverPipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
XMLWorker xmlWorker = new XMLWorker(cssResolverPipeline, true);
XMLParser xmlParser = new XMLParser(xmlWorker);
xmlParser.Parse(stringReader);
document.Close();
}
}
I've created a sample to show how to parse and display RTL data using XMLWorker. Download it from here.