Configuring log4net Programmatically for an AdoNetAppender - asp.net-mvc

I have following code:
public class Log4NetSetup
{
public static void Setup()
{
#region log4net parameters
AdoNetAppenderParameter logDate = new AdoNetAppenderParameter()
{
ParameterName = "#log_date",
DbType = System.Data.DbType.DateTime,
Layout = new RawTimeStampLayout()
};
AdoNetAppenderParameter thread = new AdoNetAppenderParameter()
{
ParameterName = "#thread",
DbType = System.Data.DbType.String,
Size = 255,
Layout = (IRawLayout)new PatternLayout("%thread")
};
AdoNetAppenderParameter logLevel = new AdoNetAppenderParameter()
{
ParameterName = "#log_level",
DbType = System.Data.DbType.String,
Size = 50,
Layout = (IRawLayout)new PatternLayout("%level")
};
AdoNetAppenderParameter logger = new AdoNetAppenderParameter()
{
ParameterName = "#logger",
DbType = System.Data.DbType.String,
Size = 255,
Layout = (IRawLayout)new PatternLayout("%logger")
};
AdoNetAppenderParameter message = new AdoNetAppenderParameter()
{
ParameterName = "#message",
DbType = System.Data.DbType.String,
Size = 4000,
Layout = (IRawLayout)new PatternLayout("%message")
};
AdoNetAppenderParameter exception = new AdoNetAppenderParameter()
{
ParameterName = "#exception",
DbType = System.Data.DbType.String,
Size = 2000,
Layout = (IRawLayout)new ExceptionLayout()
};
#endregion
AdoNetAppender dotNet = new AdoNetAppender()
{
BufferSize = 1,
CommandType = System.Data.CommandType.Text,
ConnectionType = "REDACTED",
ConnectionString = "REDACTED",
CommandText = "REDACTED",
};
dotNet.AddParameter(logDate);
dotNet.AddParameter(thread);
dotNet.AddParameter(logLevel);
dotNet.AddParameter(logger);
dotNet.AddParameter(message);
dotNet.AddParameter(exception);
dotNet.ActivateOptions();
Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
hierarchy.Root.AddAppender(dotNet);
hierarchy.Root.Level = Level.Debug;
hierarchy.Configured = true;
//log4net.Config.BasicConfigurator.Configure(dotNet);
log4net.Config.BasicConfigurator.Configure(hierarchy);
}
}
Then I run that in Global.Asax on startup.
This was working fine in a XML file, but when moving it to code it no longer wants to work.
I was moving this into code and followed many other ways to do this on SO.
None of them seem to work in my situation.
How to configure log4net programmatically from scratch (no config)
and
Can you configure log4net in code instead of using a config file?

Turns out there was an error, it was not causing a problem with the page though.
There was a invalid cast with the following code:
AdoNetAppenderParameter thread = new AdoNetAppenderParameter()
{
ParameterName = "#thread",
DbType = System.Data.DbType.String,
Size = 255,
Layout = (IRawLayout)new PatternLayout("%thread")
};
Specifically:
Layout = (IRawLayout)new PatternLayout("%thread")
It needed to convert the type:
RawLayoutConverter rlc = new RawLayoutConverter();
AdoNetAppenderParameter thread = new AdoNetAppenderParameter()
{
ParameterName = "#thread",
DbType = System.Data.DbType.String,
Size = 255,
Layout = (IRawLayout)rlc.ConvertFrom(new PatternLayout("%thread"))
};

Related

Print WebView with multiple pages in Xamarin UWP

I am trying to print web page in xamarin forms. I am using DependencyService to print webview, which I have implemented in android successfully.
For Windows UWP,
I referred to this link:
https://forums.xamarin.com/discussion/91163/problem-with-printing-webview-in-uwp-phone
The approach used in this is printing only the first page of the webpage.
Edit :
I created an interface IPrint providing only the html source to the function.
public interface IPrint
{
void PrintAsync(string htmlSource);
}
In PrintAsync function (in Windows UWP project),
async void IPrint.PrintAsync(string htmlSource)
{
ViewToPrint.NavigateToString(htmlSource);
ViewToPrint.LoadCompleted += ViewToPrint_LoadCompleteAsync;
}
When WebView is completely loaded,
private async void ViewToPrint_LoadCompleteAsync(object sender, Windows.UI.Xaml.Navigation.NavigationEventArgs e)
{
if (PrintDoc != null)
{
printDoc.AddPages -= PrintDoc_AddPages;
printDoc.GetPreviewPage -= PrintDoc_GetPreviewPage;
printDoc.Paginate -= PrintDoc_Paginate;
}
this.printDoc = new PrintDocument();
try
{
printDoc.AddPages += PrintDoc_AddPages;
printDoc.GetPreviewPage += PrintDoc_GetPreviewPage;
printDoc.Paginate += PrintDoc_Paginate;
bool showprint = await PrintManager.ShowPrintUIAsync();
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
PrintDoc = null;
GC.Collect();
}
To add pages in PrintDocument,
private void PrintDoc_AddPages(object sender, AddPagesEventArgs e)
{
printDoc.AddPage(ViewToPrint);
printDoc.AddPagesComplete();
}
To implement multiple pages printing,
I referred this link : https://stackoverflow.com/a/17222629/6366591
I changed AddPages function to the following, but it doesn't seem to work for me.
private void PrintDoc_AddPages(object sender, AddPagesEventArgs e)
{
rectangleList = GetWebPages(ViewToPrint, new Windows.Foundation.Size(100d, 150d));
foreach (Windows.UI.Xaml.Shapes.Rectangle rectangle in rectangleList)
{
printDoc.AddPage(rectangle);
}
printDoc.AddPagesComplete();
}
You can find GetWebPages() function here.
List<Windows.UI.Xaml.Shapes.Rectangle> GetWebPages(Windows.UI.Xaml.Controls.WebView webView, Windows.Foundation.Size page)
{
// ask the content its width
var _WidthString = webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollWidth.toString()" }).GetResults();
int _ContentWidth;
if (!int.TryParse(_WidthString, out _ContentWidth))
throw new Exception(string.Format("failure/width:{0}", _WidthString));
webView.Width = _ContentWidth;
// ask the content its height
var _HeightString = webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollHeight.toString()" }).GetResults();
int _ContentHeight;
if (!int.TryParse(_HeightString, out _ContentHeight))
throw new Exception(string.Format("failure/height:{0}", _HeightString));
webView.Height = _ContentHeight;
// how many pages will there be?
var _Scale = page.Width / _ContentWidth;
var _ScaledHeight = (_ContentHeight * _Scale);
var _PageCount = (double)_ScaledHeight / page.Height;
_PageCount = _PageCount + ((_PageCount > (int)_PageCount) ? 1 : 0);
// create the pages
var _Pages = new List<Windows.UI.Xaml.Shapes.Rectangle>();
for (int i = 0; i < (int)_PageCount; i++)
{
var _TranslateY = -page.Height * i;
var _Page = new Windows.UI.Xaml.Shapes.Rectangle
{
Height = page.Height,
Width = page.Width,
Margin = new Windows.UI.Xaml.Thickness(5),
Tag = new Windows.UI.Xaml.Media.TranslateTransform { Y = _TranslateY },
};
_Page.Loaded += (s, e) =>
{
var _Rectangle = s as Windows.UI.Xaml.Shapes.Rectangle;
var _Brush = GetWebViewBrush(webView);
_Brush.Stretch = Windows.UI.Xaml.Media.Stretch.UniformToFill;
_Brush.AlignmentY = Windows.UI.Xaml.Media.AlignmentY.Top;
_Brush.Transform = _Rectangle.Tag as Windows.UI.Xaml.Media.TranslateTransform;
_Rectangle.Fill = _Brush;
};
_Pages.Add(_Page);
}
return _Pages;
}
WebViewBrush GetWebViewBrush(Windows.UI.Xaml.Controls.WebView webView)
{
// resize width to content
var _OriginalWidth = webView.Width;
var _WidthString = webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollWidth.toString()" }).GetResults();
int _ContentWidth;
if (!int.TryParse(_WidthString, out _ContentWidth))
throw new Exception(string.Format("failure/width:{0}", _WidthString));
webView.Width = _ContentWidth;
// resize height to content
var _OriginalHeight = webView.Height;
var _HeightString = webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollHeight.toString()" }).GetResults();
int _ContentHeight;
if (!int.TryParse(_HeightString, out _ContentHeight))
throw new Exception(string.Format("failure/height:{0}", _HeightString));
webView.Height = _ContentHeight;
// create brush
var _OriginalVisibilty = webView.Visibility;
webView.Visibility = Windows.UI.Xaml.Visibility.Visible;
var _Brush = new WebViewBrush
{
SourceName = webView.Name,
Stretch = Windows.UI.Xaml.Media.Stretch.Uniform
};
_Brush.Redraw();
// reset, return
webView.Width = _OriginalWidth;
webView.Height = _OriginalHeight;
webView.Visibility = _OriginalVisibilty;
return _Brush;
}
#Jerry Nixon's method worked well on my side. Since his code sample was posted on that thread about five years ago. For current UWP APIs, I just done a little changes(e.g, webView.InvokeScriptAsync). I also saw that you call the webView.InvokeScriptAsync method in your code. That's good. But you call the GetResults() method, I did not suggest you call GetResults() method. Because invoking javascript code sometimes will take you a lot of time. You might get the exception A method was called at an unexpected time.
Then, I also noticed that your printing flow is a bit of a mess. Please read Print from your app to learn the standardized printing process.
You could check the official code sample Printing sample for details.
The following was the updated code of your code snippet:
async Task<List<Windows.UI.Xaml.Shapes.Rectangle>> GetWebPages(Windows.UI.Xaml.Controls.WebView webView, Windows.Foundation.Size page)
{
// ask the content its width
var _WidthString = await webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollWidth.toString()" });
int _ContentWidth;
if (!int.TryParse(_WidthString, out _ContentWidth))
throw new Exception(string.Format("failure/width:{0}", _WidthString));
webView.Width = _ContentWidth;
// ask the content its height
var _HeightString = await webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollHeight.toString()" });
int _ContentHeight;
if (!int.TryParse(_HeightString, out _ContentHeight))
throw new Exception(string.Format("failure/height:{0}", _HeightString));
webView.Height = _ContentHeight;
// how many pages will there be?
var _Scale = page.Width / _ContentWidth;
var _ScaledHeight = (_ContentHeight * _Scale);
var _PageCount = (double)_ScaledHeight / page.Height;
_PageCount = _PageCount + ((_PageCount > (int)_PageCount) ? 1 : 0);
// create the pages
var _Pages = new List<Windows.UI.Xaml.Shapes.Rectangle>();
for (int i = 0; i < (int)_PageCount; i++)
{
var _TranslateY = -page.Height * i;
var _Page = new Windows.UI.Xaml.Shapes.Rectangle
{
Height = page.Height,
Width = page.Width,
Margin = new Windows.UI.Xaml.Thickness(5),
Tag = new Windows.UI.Xaml.Media.TranslateTransform { Y = _TranslateY },
};
_Page.Loaded +=async (s, e) =>
{
var _Rectangle = s as Windows.UI.Xaml.Shapes.Rectangle;
var _Brush = await GetWebViewBrush(webView);
_Brush.Stretch = Windows.UI.Xaml.Media.Stretch.UniformToFill;
_Brush.AlignmentY = Windows.UI.Xaml.Media.AlignmentY.Top;
_Brush.Transform = _Rectangle.Tag as Windows.UI.Xaml.Media.TranslateTransform;
_Rectangle.Fill = _Brush;
};
_Pages.Add(_Page);
}
return _Pages;
}
async Task<WebViewBrush> GetWebViewBrush(Windows.UI.Xaml.Controls.WebView webView)
{
// resize width to content
var _OriginalWidth = webView.Width;
var _WidthString = await webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollWidth.toString()" });
int _ContentWidth;
if (!int.TryParse(_WidthString, out _ContentWidth))
throw new Exception(string.Format("failure/width:{0}", _WidthString));
webView.Width = _ContentWidth;
// resize height to content
var _OriginalHeight = webView.Height;
var _HeightString = await webView.InvokeScriptAsync("eval",
new[] { "document.body.scrollHeight.toString()" });
int _ContentHeight;
if (!int.TryParse(_HeightString, out _ContentHeight))
throw new Exception(string.Format("failure/height:{0}", _HeightString));
webView.Height = _ContentHeight;
// create brush
var _OriginalVisibilty = webView.Visibility;
webView.Visibility = Windows.UI.Xaml.Visibility.Visible;
var _Brush = new WebViewBrush
{
SourceName = webView.Name,
Stretch = Windows.UI.Xaml.Media.Stretch.Uniform
};
_Brush.Redraw();
// reset, return
webView.Width = _OriginalWidth;
webView.Height = _OriginalHeight;
webView.Visibility = _OriginalVisibilty;
return _Brush;
}
I used the Printing sample and put my above updated code in it and do some relevant changes, then I could print all web pages successfully.

SharpDX / XAudio2 : Sending a SourceVoice through a SubmixVoice

I can't figure this out, how do I route a SourceVoice through a Submixvoice? The C++ examples on the net suggest I can use effect chains, but there's no EffectChain constructor or functions that accept voices. Here're the basics:
private XAudio2 xa = null;
private MasteringVoice mv = null;
private SourceVoice sv = null;
private SubmixVoice sm = null;
private SoundStream ss = null;
private AudioBuffer ab = null;
private WaveFormat wf = null;
private FilterParameters fp;
private bool sv_playing = false;
private void button1_Click(object sender, EventArgs e)
{
if (null == xa)
{
xa = new XAudio2();
mv = new MasteringVoice(xa);
var nativefilestream = new NativeFileStream(
#"c:\dev\beat_loop.wav",
NativeFileMode.Open,
NativeFileAccess.Read,
NativeFileShare.Read);
ss = new SoundStream(nativefilestream);
wf = ss.Format;
ab = new AudioBuffer
{
Stream = ss.ToDataStream(),
AudioBytes = (int)ss.Length,
Flags = BufferFlags.EndOfStream
};
fp.Frequency = 1.0f;
fp.OneOverQ = 1.0f;
fp.Type = FilterType.LowPassFilter;
}
if (sv_playing)
{
if (null != sv)
{
sv.Stop();
sv.Dispose();
sv = null;
}
}
if (null == sv)
{
sv = new SourceVoice(xa, wf,VoiceFlags.None,1.0f, true);
sv.SubmitSourceBuffer(ab, ss.DecodedPacketsInfo);
sv.BufferEnd += new Action<IntPtr>(sv_BufferEnd);
sm = new SubmixVoice(xa, ss.Format.Channels, ss.Format.SampleRate, VoiceSendFlags.UseFilter,10);
sm.SetFilterParameters(fp);
// HOW DO I TELL sv TO ROUTE THROUGH sm??
sv.Start();
sv_playing = true;
}
}
You can use the VoiceSendDescriptor class to route source voices to submix voices
VoiceSendDescriptor vs = new VoiceSendDescriptor(VoiceSendFlags.None, sm);
sv.SetOutputVoices(vs);

OOXML : keep images displayed after moving the header content to to the body

I am using open XML SDK and I want to move the content of content control (containing images) from the header to the body, the problem that images does not show after moving. After copying the content control content I am adding the image parts in this way :
foreach (var headerPart in wordDocument.MainDocumentPart.HeaderParts)
{
SdtBlock sdtToSave = this.FindSdtBlock(contentControlTag, headerPart );
if (sdtToSave != null)
{
foreach (var imagePart in headerPart.ImageParts)
{
ImagePart newPart = mainPart.AddImagePart(imagePart.ContentType);
this.GenerateImagePartContent(newPart, imagePart.GetStream()); }
}
}
private void GenerateImagePartContent(ImagePart imagePart, Stream partStream)
{
imagePart.FeedData(partStream);
partStream.Close();
}
then if I add this lines :
Paragraph paragraph = sdtToSave.SdtContentBlock.GetFirstChild<Paragraph>();
Run run = new Run();
paragraph.Append(run);
run.Append(this.GenerateDrawing(mainPart.GetIdOfPart(newPart)));
private Drawing GenerateDrawing(String relationshipID)
{
Drawing drawing1 = new Drawing();
Inline inline1 = new Inline() { DistanceFromTop = (UInt32Value)0U, DistanceFromBottom = (UInt32Value)0U, DistanceFromLeft = (UInt32Value)0U, DistanceFromRight = (UInt32Value)0U };
Extent extent1 = new Extent() { Cx = 152400L, Cy = 152400L };
EffectExtent effectExtent1 = new EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L };
DocProperties docProperties1 = new DocProperties() { Id = (UInt32Value)1U, Name = "Image 1" };
NonVisualGraphicFrameDrawingProperties nonVisualGraphicFrameDrawingProperties1 = new NonVisualGraphicFrameDrawingProperties();
A.GraphicFrameLocks graphicFrameLocks1 = new A.GraphicFrameLocks() { NoChangeAspect = true };
graphicFrameLocks1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
nonVisualGraphicFrameDrawingProperties1.Append(graphicFrameLocks1);
A.Graphic graphic1 = new A.Graphic();
graphic1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
A.GraphicData graphicData1 = new A.GraphicData() { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" };
Pic.Picture picture1 = new Pic.Picture();
picture1.AddNamespaceDeclaration("pic", "http://schemas.openxmlformats.org/drawingml/2006/picture");
Pic.NonVisualPictureProperties nonVisualPictureProperties1 = new Pic.NonVisualPictureProperties();
Pic.NonVisualDrawingProperties nonVisualDrawingProperties1 = new Pic.NonVisualDrawingProperties() { Id = (UInt32Value)0U, Name = "AddTo_Blink.png" };
Pic.NonVisualPictureDrawingProperties nonVisualPictureDrawingProperties1 = new Pic.NonVisualPictureDrawingProperties();
nonVisualPictureProperties1.Append(nonVisualDrawingProperties1);
nonVisualPictureProperties1.Append(nonVisualPictureDrawingProperties1);
Pic.BlipFill blipFill1 = new Pic.BlipFill();
A.Blip blip1 = new A.Blip() { Embed = relationshipID };
A.BlipExtensionList blipExtensionList1 = new A.BlipExtensionList();
A.BlipExtension blipExtension1 = new A.BlipExtension() { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" };
A14.UseLocalDpi useLocalDpi1 = new A14.UseLocalDpi() { Val = false };
useLocalDpi1.AddNamespaceDeclaration("a14", "http://schemas.microsoft.com/office/drawing/2010/main");
blipExtension1.Append(useLocalDpi1);
blipExtensionList1.Append(blipExtension1);
blip1.Append(blipExtensionList1);
A.Stretch stretch1 = new A.Stretch();
A.FillRectangle fillRectangle1 = new A.FillRectangle();
stretch1.Append(fillRectangle1);
blipFill1.Append(blip1);
blipFill1.Append(stretch1);
Pic.ShapeProperties shapeProperties1 = new Pic.ShapeProperties();
A.Transform2D transform2D1 = new A.Transform2D();
A.Offset offset1 = new A.Offset() { X = 0L, Y = 0L };
A.Extents extents1 = new A.Extents() { Cx = 152400L, Cy = 152400L };
transform2D1.Append(offset1);
transform2D1.Append(extents1);
A.PresetGeometry presetGeometry1 = new A.PresetGeometry() { Preset = A.ShapeTypeValues.Rectangle };
A.AdjustValueList adjustValueList1 = new A.AdjustValueList();
presetGeometry1.Append(adjustValueList1);
shapeProperties1.Append(transform2D1);
shapeProperties1.Append(presetGeometry1);
picture1.Append(nonVisualPictureProperties1);
picture1.Append(blipFill1);
picture1.Append(shapeProperties1);
graphicData1.Append(picture1);
graphic1.Append(graphicData1);
inline1.Append(extent1);
inline1.Append(effectExtent1);
inline1.Append(docProperties1);
inline1.Append(nonVisualGraphicFrameDrawingProperties1);
inline1.Append(graphic1);
drawing1.Append(inline1);
return drawing1;
}
all images are shown at the end of body.
From the OXML SDK productivity tool I can see that bookmarks are used to insert images inside a paragraph.
To summarize, I want to know how to keep images when moving content controls from header to the body.
Regards.
When you add your image part to the mainPart, it will be given a relId which is unlikely to be the same as the relId it had in the headerPart. So you'll have to adjust the relId in the drawing (Embed = relationshipID) to match.

Set a binding programmatically between a component and a value from a list

I'm developing a application in Silverlight 3 and I have a dynamic form, I generate this form from a list of attributes (key-value) I'd like to know, how can I set a binding between the component (CheckBox, TextBox, ...) and the value of the attribute?
This code is only the first approximation to the solution, no the definitive code:
int numeroFila = 0;
MainPage rootPage = ((App)Application.Current).RootVisual as MainPage;
rootPage.NuevoElementoWindowInstance.NuevoElementoInstance.ListadoAtributos.Children.Clear();
foreach (var atributo in ListaAtributos)
{
string tipoAtributo = ObtenerDefinicionAtributo(atributo.Key);
FrameworkElement campoDatos;
TextBlock bloqueTexto = new TextBlock();
bloqueTexto.Text = atributo.Key;
bloqueTexto.Margin = new Thickness(10,3,0,0);
switch (tipoAtributo)
{
case "Boolean":
CheckBox campoBooleano = new CheckBox();
campoBooleano.Name = atributo.Key;
campoBooleano.IsChecked = ObtenerValorCampoBooleano(atributo.Value);
campoDatos = campoBooleano;
break;
case "DateTime":
DatePicker campoFecha = new DatePicker();
try
{
campoFecha.DisplayDate = DateTime.Parse(atributo.Value);
}
catch (Exception)
{
campoFecha.DisplayDate = DateTime.Now;
}
campoDatos = campoFecha;
break;
default:
TextBox campoTexto = new TextBox();
campoTexto.Text = atributo.Value == null ? "" : atributo.Value;
campoDatos = campoTexto;
break;
}
campoDatos.Margin = new Thickness(0,1,10,1);
rootPage.NuevoElementoWindowInstance.NuevoElementoInstance.ListadoAtributos.RowDefinitions.Add(new RowDefinition());
Grid.SetColumn(campoDatos, 1);
Grid.SetColumn(bloqueTexto, 0);
Grid.SetRow(campoDatos, numeroFila);
Grid.SetRow(bloqueTexto, numeroFila);
rootPage.NuevoElementoWindowInstance.NuevoElementoInstance.ListadoAtributos.Children.Add(bloqueTexto);
rootPage.NuevoElementoWindowInstance.NuevoElementoInstance.ListadoAtributos.Children.Add(campoDatos);
numeroFila++;
}
}
I have found the solution. This is the code:
int numeroFila = 0;
MainPage rootPage = ((App)Application.Current).RootVisual as MainPage;
rootPage.NuevoElementoWindowInstance.NuevoElementoInstance.ListadoAtributos.Children.Clear();
foreach (var atributo in ListaAtributos)
{
string tipoAtributo = ObtenerDefinicionAtributo(atributo.Key);
FrameworkElement campoDatos;
TextBlock bloqueTexto = new TextBlock();
bloqueTexto.Margin = new Thickness(10,3,0,0);
Binding bind = new Binding();
bind.Source = atributo;
bind.Path = new PropertyPath("Key");
bind.Mode = System.Windows.Data.BindingMode.TwoWay;
bloqueTexto.SetBinding(TextBlock.TextProperty, bind);
switch (tipoAtributo)
{
case "Boolean":
CheckBox campoBooleano = new CheckBox();
campoBooleano.Name = atributo.Key;
campoBooleano.IsChecked = ObtenerValorCampoBooleano(atributo.Value);
bind = new Binding();
bind.Source = atributo;
bind.Path = new PropertyPath("Value");
bind.Mode = System.Windows.Data.BindingMode.TwoWay;
campoBooleano.SetBinding(CheckBox.IsCheckedProperty, bind);
campoDatos = campoBooleano;
break;
case "DateTime":
DatePicker campoFecha = new DatePicker();
try
{
campoFecha.DisplayDate = DateTime.Parse(atributo.Value);
}
catch (Exception)
{
campoFecha.DisplayDate = DateTime.Now;
}
bind = new Binding();
bind.Source = atributo;
bind.Path = new PropertyPath("Value");
bind.Mode = System.Windows.Data.BindingMode.TwoWay;
campoFecha.SetBinding(DatePicker.TextProperty, bind);
campoDatos = campoFecha;
break;
default:
TextBox campoTexto = new TextBox();
atributo.Value = atributo.Value == null ? "" : atributo.Value;
bind = new Binding();
bind.Source = atributo;
bind.Path = new PropertyPath("Value");
bind.Mode = System.Windows.Data.BindingMode.TwoWay;
campoTexto.SetBinding(TextBox.TextProperty, bind);
campoDatos = campoTexto;
break;
}
//this.GetType().GetProperty("").GetGetMethod().Invoke(new Object(), null);
campoDatos.Margin = new Thickness(0,1,10,1);
rootPage.NuevoElementoWindowInstance.NuevoElementoInstance.ListadoAtributos.RowDefinitions.Add(new RowDefinition());
Grid.SetColumn(campoDatos, 1);
Grid.SetColumn(bloqueTexto, 0);
Grid.SetRow(campoDatos, numeroFila);
Grid.SetRow(bloqueTexto, numeroFila);
rootPage.NuevoElementoWindowInstance.NuevoElementoInstance.ListadoAtributos.Children.Add(bloqueTexto);
rootPage.NuevoElementoWindowInstance.NuevoElementoInstance.ListadoAtributos.Children.Add(campoDatos);
numeroFila++;
}
However now, I need to set a Converter to the CheckBox, because al "Values" are string and I need to convert string-boolean

Open XML SDK - image not showing in excel

I'm able to successfully create a spreadsheet, and I appear to have added the image via code, the problem is that when I open the spreadsheet, there is no image. Here is my code:
public static void CreateSpreadsheetWorkbook(string filepath)
{
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet" };
sheets.Append(sheet);
string sImagePath = #"C:\temp\install_button.png";
DrawingsPart drawingsPart = worksheetPart.AddNewPart<DrawingsPart>();
ImagePart imagePart = drawingsPart.AddImagePart(ImagePartType.Png, worksheetPart.GetIdOfPart(drawingsPart));
using (FileStream stream = new FileStream(sImagePath, FileMode.Open))
{
imagePart.FeedData(stream);
}
workbookpart.Workbook.Save();
spreadsheetDocument.Close();
}
Thanks
Stu
Normally when I can't figure out why something doesn't work when dealing with the Open XML SDK I use the Open XML SDK 2.0 Productivity Tool to figure out what the code should be. I will normally create a blank worksheet in Excel, add a picture and then save the document. Then I will open that document in the Productivity tool and click the Reflect code button to see how to recreate that document. I did that to see how to answer your question and got the following code to create a worksheet part:
// Adds child parts and generates content of the specified part.
public void CreateWorksheetPart(WorksheetPart part)
{
DrawingsPart drawingsPart1 = part.AddNewPart<DrawingsPart>("rId2");
GenerateDrawingsPart1Content(drawingsPart1);
ImagePart imagePart1 = drawingsPart1.AddNewPart<ImagePart>("image/png", "rId1");
GenerateImagePart1Content(imagePart1);
SpreadsheetPrinterSettingsPart spreadsheetPrinterSettingsPart1 = part.AddNewPart<SpreadsheetPrinterSettingsPart>("rId1");
GenerateSpreadsheetPrinterSettingsPart1Content(spreadsheetPrinterSettingsPart1);
GeneratePartContent(part);
}
// Generates content of drawingsPart1.
private void GenerateDrawingsPart1Content(DrawingsPart drawingsPart1)
{
Xdr.WorksheetDrawing worksheetDrawing1 = new Xdr.WorksheetDrawing();
worksheetDrawing1.AddNamespaceDeclaration("xdr", "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing");
worksheetDrawing1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
Xdr.TwoCellAnchor twoCellAnchor1 = new Xdr.TwoCellAnchor(){ EditAs = Xdr.EditAsValues.OneCell };
Xdr.FromMarker fromMarker1 = new Xdr.FromMarker();
Xdr.ColumnId columnId1 = new Xdr.ColumnId();
columnId1.Text = "0";
Xdr.ColumnOffset columnOffset1 = new Xdr.ColumnOffset();
columnOffset1.Text = "0";
Xdr.RowId rowId1 = new Xdr.RowId();
rowId1.Text = "0";
Xdr.RowOffset rowOffset1 = new Xdr.RowOffset();
rowOffset1.Text = "0";
fromMarker1.Append(columnId1);
fromMarker1.Append(columnOffset1);
fromMarker1.Append(rowId1);
fromMarker1.Append(rowOffset1);
Xdr.ToMarker toMarker1 = new Xdr.ToMarker();
Xdr.ColumnId columnId2 = new Xdr.ColumnId();
columnId2.Text = "0";
Xdr.ColumnOffset columnOffset2 = new Xdr.ColumnOffset();
columnOffset2.Text = "171429";
Xdr.RowId rowId2 = new Xdr.RowId();
rowId2.Text = "0";
Xdr.RowOffset rowOffset2 = new Xdr.RowOffset();
rowOffset2.Text = "171429";
toMarker1.Append(columnId2);
toMarker1.Append(columnOffset2);
toMarker1.Append(rowId2);
toMarker1.Append(rowOffset2);
Xdr.Picture picture1 = new Xdr.Picture();
Xdr.NonVisualPictureProperties nonVisualPictureProperties1 = new Xdr.NonVisualPictureProperties();
Xdr.NonVisualDrawingProperties nonVisualDrawingProperties1 = new Xdr.NonVisualDrawingProperties(){ Id = (UInt32Value)2U, Name = "Picture 1", Description = "eprs_reports_arrow.png" };
Xdr.NonVisualPictureDrawingProperties nonVisualPictureDrawingProperties1 = new Xdr.NonVisualPictureDrawingProperties();
A.PictureLocks pictureLocks1 = new A.PictureLocks(){ NoChangeAspect = true };
nonVisualPictureDrawingProperties1.Append(pictureLocks1);
nonVisualPictureProperties1.Append(nonVisualDrawingProperties1);
nonVisualPictureProperties1.Append(nonVisualPictureDrawingProperties1);
Xdr.BlipFill blipFill1 = new Xdr.BlipFill();
A.Blip blip1 = new A.Blip(){ Embed = "rId1", CompressionState = A.BlipCompressionValues.Print };
blip1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
A.Stretch stretch1 = new A.Stretch();
A.FillRectangle fillRectangle1 = new A.FillRectangle();
stretch1.Append(fillRectangle1);
blipFill1.Append(blip1);
blipFill1.Append(stretch1);
Xdr.ShapeProperties shapeProperties1 = new Xdr.ShapeProperties();
A.Transform2D transform2D1 = new A.Transform2D();
A.Offset offset1 = new A.Offset(){ X = 0L, Y = 0L };
A.Extents extents1 = new A.Extents(){ Cx = 171429L, Cy = 171429L };
transform2D1.Append(offset1);
transform2D1.Append(extents1);
A.PresetGeometry presetGeometry1 = new A.PresetGeometry(){ Preset = A.ShapeTypeValues.Rectangle };
A.AdjustValueList adjustValueList1 = new A.AdjustValueList();
presetGeometry1.Append(adjustValueList1);
shapeProperties1.Append(transform2D1);
shapeProperties1.Append(presetGeometry1);
picture1.Append(nonVisualPictureProperties1);
picture1.Append(blipFill1);
picture1.Append(shapeProperties1);
Xdr.ClientData clientData1 = new Xdr.ClientData();
twoCellAnchor1.Append(fromMarker1);
twoCellAnchor1.Append(toMarker1);
twoCellAnchor1.Append(picture1);
twoCellAnchor1.Append(clientData1);
worksheetDrawing1.Append(twoCellAnchor1);
drawingsPart1.WorksheetDrawing = worksheetDrawing1;
}
// Generates content of imagePart1.
private void GenerateImagePart1Content(ImagePart imagePart1)
{
System.IO.Stream data = GetBinaryDataStream(imagePart1Data);
imagePart1.FeedData(data);
data.Close();
}
// Generates content of spreadsheetPrinterSettingsPart1.
private void GenerateSpreadsheetPrinterSettingsPart1Content(SpreadsheetPrinterSettingsPart spreadsheetPrinterSettingsPart1)
{
System.IO.Stream data = GetBinaryDataStream(spreadsheetPrinterSettingsPart1Data);
spreadsheetPrinterSettingsPart1.FeedData(data);
data.Close();
}
// Generates content of part.
private void GeneratePartContent(WorksheetPart part)
{
Worksheet worksheet1 = new Worksheet();
worksheet1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
SheetDimension sheetDimension1 = new SheetDimension(){ Reference = "A1" };
SheetViews sheetViews1 = new SheetViews();
SheetView sheetView1 = new SheetView(){ TabSelected = true, WorkbookViewId = (UInt32Value)0U };
sheetViews1.Append(sheetView1);
SheetFormatProperties sheetFormatProperties1 = new SheetFormatProperties(){ DefaultRowHeight = 15D };
SheetData sheetData1 = new SheetData();
PageMargins pageMargins1 = new PageMargins(){ Left = 0.7D, Right = 0.7D, Top = 0.75D, Bottom = 0.75D, Header = 0.3D, Footer = 0.3D };
PageSetup pageSetup1 = new PageSetup(){ Orientation = OrientationValues.Portrait, Id = "rId1" };
Drawing drawing1 = new Drawing(){ Id = "rId2" };
worksheet1.Append(sheetDimension1);
worksheet1.Append(sheetViews1);
worksheet1.Append(sheetFormatProperties1);
worksheet1.Append(sheetData1);
worksheet1.Append(pageMargins1);
worksheet1.Append(pageSetup1);
worksheet1.Append(drawing1);
part.Worksheet = worksheet1;
}
#region Binary Data
private string imagePart1Data ="lots of binary data here";
private System.IO.Stream GetBinaryDataStream(string base64String)
{
return new System.IO.MemoryStream(System.Convert.FromBase64String(base64String));
}
#endregion
I recommend you do the same with your image and play around with the generated code in order to get it to work since as you can see just adding one picture to a new slide is a lot of code.

Resources