Can't access ViewDataDictionary object properly on StringTemplate - viewdata

I'm playing with StringTemplate version 3.1.4.6002 as a view engine for an MVC project. I can't seem to access an object being passed to the template and have it render on a webpage. So basically, I have the the following in the controller (in C#):
var layer1 = new { count = "1", label = "Description" };
var layer2 = new { count = "2", label = "Transcription" };
ViewData["layers"] = new object[] {layer1,layer2};
On the view file test.st, I have:
$layers:{
$it.count$
$it.label$
}$
The template does not display anything on the webpage, but if I do this on the test.st:
$layers$
it displays the object as:
{ count=1, label=Description } { count=2, label=Transcription }
which looks like to me a string. So how do I access just the count and the label independently? I've googled a lot already and can't seem to find anything that would fix my problem.
By the way, I'm using Visual Studio V10 and .NET Framework Version4. On the project I have References to Antlr3.Runtime, Antlr3.Runtime.Debug and Antlr3.StringTemplate dlls. Also, I have no problems accessing simple string objects. I've used the tutorial project in here. I can supply more details if required.

Are the count and label fields public or, if they are getters, are they public?

Related

IOleCommandTarget IDM_BLOCKFMT doesn't work when changing windows locale to non-english

I have the following c# .Net code in WPF app code:
public static void ClearList(IHTMLDocument document)
{
if (CanSetBlockFormat(document))
{
OleCommandTargetHelper.Execute(document, MsHtmcid.IDM_BLOCKFMT, new object[] { "Normal" });
}
}
where:
internal static object Execute(IHTMLDocument document, MsHtmcid command, object[] arguments)
{
var commandTarget = (DocObj.IOleCommandTarget)document;
var retVal = new object[] { null };
var hr = commandTarget.Exec(
ref NativeMethods.Guid_MSHTML,
(int)command,
(int)DocObj.OLECMDEXECOPT.DONTPROMPTUSER,
arguments,
retVal);
return retVal[0];
}
This is used for editing and formatting html text in WebView/WPF, where the web browser used is internet explorer and is used as a kind of rich text editor generating required HTML.
In this particular case it is used to remove formatting from bulleted or numbered list.
Can anyone tell me why this code doesn't work the moment I change windows langauge settings to non-english (Austrian for example?)
windows 10 language settings

New to AutoFixture trying to get my head around it and I can't see it helping me

Currently, I'm using custom made fake objects that behind the scenes use NSubstitute which creates the actual objects but it's becoming very hard to maintain as the project grows, so I'm trying to find alternatives and I'm hoping that AutoFixture is the right tool for the job.
I read the documentation and I'm struggling because there's very little to no documentation and I read most of the blog posts by Mark Seemann including the CheatSheet.
One of the things that I'm having hard time to grasp is how to create an object with a constructor that have parameters, in my case I need to pass argument to CsEmbeddedRazorViewEngine as well as HttpRequestBase to ControllerContext.
The way I see it is that I need to create a fake objects and finally create a customization object that injects them to
I also looked into NBuilder it seems slightly more trivial to pass arguments there but I've heard good things about AutoFixture and I would like to give it a try. :)
I'm trying to reduce the amount of fake objects I have so here is a real test, how can I do the same thing with AutoFixture?
[Theory,
InlineData("en-US"),
InlineData("en-us"),
InlineData("en")]
public void Should_return_the_default_path_of_the_view_for_enUS(string language)
{
// Arrange
const string EXPECTED_VIEW_PATH = "~/MyAssemblyName/Views/Home/Index.cshtml";
CsEmbeddedRazorViewEngine engine = CsEmbeddedRazorViewEngineFactory.Create(ASSEMBLY_NAME, VIEW_PATH, string.Empty);
string[] userLanguage = { language };
HttpRequestBase request = FakeHttpRequestFactory.Create(userLanguage);
ControllerContext controllerContext = FakeControllerContextFactory.Create(request);
// Act
ViewEngineResult result = engine.FindPartialView(controllerContext, VIEW_NAME, false);
// Assert
RazorView razorView = (RazorView)result.View;
string actualViewPath = razorView.ViewPath;
actualViewPath.Should().Be(EXPECTED_VIEW_PATH);
}
P.S. I'm using xUnit as my testing framework and NSubstitute as my mocking framework should I install both AutoFixture.Xunit and AutoFixture.AutoNSubstitute?
UPDATE: After learning more and more about it I guess it is not the right tool for the job because I tried to replace my test doubles factories with AutoFixture rather than setting up my SUT with it.
Due to odd reason I thought it's doing the same thing NBuilder is doing and from what I can see they are very different tools.
So after some thinking I think I'll go and change the methods I have on my test doubles factories to objects then use AutoFixture to create my SUT and inject my test doubles to it.
Note: I don't have the source code for the CsEmbeddedRazorViewEngine type and all the other custom types.
Here is how it could be written with AutoFixture:
[Theory]
[InlineAutoWebData("en-US", "about", "~/MyAssemblyName/Views/Home/Index.cshtml")]
[InlineAutoWebData("en-US", "other", "~/MyAssemblyName/Views/Home/Index.cshtml")]
public void Should_return_the_default_path_of_the_view_for_enUS(
string language,
string viewName,
string expected,
ControllerContext controllerContext,
CsEmbeddedRazorViewEngine sut)
{
var result = sut.FindPartialView(controllerContext, viewName, false);
var actual = ((RazorView)result.View).ViewPath;
actual.Should().Be(expected);
}
How it works:
It uses AutoFixture itself together with it's glue libraries for xUnit.net and NSubstitute:
PM> Install-Package AutoFixture.Xunit
PM> Install-Package AutoFixture.AutoNSubstitute
With InlineAutoWebData you actually combine inline values and auto-generated data values by AutoFixture – also including Auto-Mocking with NSubstitute.
internal class InlineAutoWebDataAttribute : CompositeDataAttribute
{
internal InlineAutoWebDataAttribute(params object[] values)
: base(
new InlineDataAttribute(values),
new CompositeDataAttribute(
new AutoDataAttribute(
new Fixture().Customize(
new WebModelCustomization()))))
{
}
}
Remarks:
You could actually replace the WebModelCustomization customization above with AutoNSubstituteCustomization and it could work.
However, assuming that you are using ASP.NET MVC 4, you need to customize the Fixture instance with:
internal class WebModelCustomization : CompositeCustomization
{
internal WebModelCustomization()
: base(
new MvcCustomization(),
new AutoNSubstituteCustomization())
{
}
private class MvcCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<ControllerContext>(c => c
.Without(x => x.DisplayMode));
// Customize the CsEmbeddedRazorViewEngine type here.
}
}
}
Further reading:
Encapsulating AutoFixture Customizations
AutoData Theories with AutoFixture
I ended up doing this.
[Theory,
InlineData("en-US", "Index", "~/MyAssemblyName/Views/Home/Index.cshtml"),
InlineData("en-us", "Index", "~/MyAssemblyName/Views/Home/Index.cshtml"),
InlineData("en", "Index", "~/MyAssemblyName/Views/Home/Index.cshtml")]
public void Should_return_the_default_path_of_the_view(string language, string viewName, string expected)
{
// Arrange
CsEmbeddedRazorViewEngine engine = new CsEmbeddedRazorViewEngineFixture();
ControllerContext controllerContext = FakeControllerContextBuilder.WithLanguage(language).Build();
// Act
ViewEngineResult result = engine.FindPartialView(controllerContext, viewName, false);
// Assert
string actualViewPath = ((RazorView)result.View).ViewPath;
actualViewPath.Should().Be(expected);
}
I encapsulated the details to setup my SUT into a fixture and used the builder pattern to handle my fakes, I think that it's readable and pretty straightforward now.
While AutoFixture looks pretty cool, the learning curve seems long and I will need to invest enough time to understand it, for now, I want to clean-up my unit tests and make them more readable. :)

Creating Pivotviewer Collection

I'm trying to create a JIT pivotviewer and I have been kinda struggling a bit. Could someone clear my confusion on how the cxml is dynamically created? Also how should the information be set up for me to request it? I currently have it sitting inside of my database, do I need to create an xml doc for it to load from or can it pull it straight from the db?
For building a JIT PivotViewer collection you start by downloading the JIT example built by Microsoft.
Look around in the solution, when getting started the most important bit is the CollectionFactories project. To create a collection using data from your database you need to create your custom CollectionFactory.
Your custom collectionfactory extends the CollectionFactoryBase class:
class MyCustomCollection : CollectionFactoryBase
the class needs to implement the MakeCollection method, all this method has to do is create an instance of Collection class and add CollectionItems to it.
public override PivotServerTools.Collection MakeCollection(CollectionRequestContext context) {
return MakeCollection();
}
private static PivotServerTools.Collection MakeCollection() {
PivotServerTools.Collection collection = new PivotServerTools.Collection();
collection.Name = "MyImages";
ItemImage[] fileList = ImageListFromDatabase();
foreach (ItemImage image in fileList) {
collection.AddItem(image.Name, image.ImageUrl.ToString(), image.Description, image, null);
}
return collection;
}
Now to use this collection and see it in action, you need to provide the name of the collection for the PivotViewer Silverlight application (PivotServer) in the solution:
default.aspx
<param name="initParams" value="cxml=MyImages.cxml" />

Can we bind dynamic data (dataset or list) to a control in WPF

I have a user control...and the base page(s) which uses this user control has a dataset which will be used by the user control.
My dataset is dynamic...means..it can have different number of columns depending upon which page my usercontrol is implemented. Is there any control in wpf which i can use to bind this dataset (without knowing the column information) ...i mean similar to datagrid/gridview in 2.0 ?
Take a look at the WPF toolkit, this contains a Grid which meets your requirements.
This toolkit is built by Microsoft, and part of the Microsoft Shared Source Initiative (see the link I provided).
It's not supported my Microsoft though, so if you get a bug you can use their forums but not call MS support.
If you do want to do it yourself, you can for example write some code that takes a List<T>, you get the generic type, get the properties, iterate over them, write the column headers, iterate over all the items in the list and write all the properties.
I wrote this code a while back to write a List to an HTML table, I hope it's useful:
public void PrintList<T>(List<T> list)
{
if(null!=list.FirstOrDefault())
{
Type t = typeof(list[0]);
PropertyInfo[] properties = t.GetProperties();
// properties = list of all properties.
print("<table><tr>");
foreach(var property in properties)
{
// print property title
print(string.Format("<th>{0}</th>", property.Name));
}
print("</tr>");
foreach(var item in list)
{
print("<tr>");
foreach(var property in properties)
{
var propertyValue = t.InvokeMember(property.Name, BindingFlags.GetProperty, null, item, new object[] {});
print(string.Format("<td>{0}</td>", propertyValue));
}
print("</tr>");
}
print("</table>");
}
}

ASP MVC to Silverlight MVVM issues

I am converting an asp.net MVC application to silverlight, and due to the fact I was doing some 'non-standard' things in my mvc app, I am having a hard time trying to work out how to implement it in Silverlight MVVM.
Basically I was generating all my views from metadata, including links, buttons etc. One example of this that I can't get my head around how to do in Silverlight is that I passed in an action collection to my view, and had a html helper class that then converted these actions into links
public static string GenericLinks(this HtmlHelper htmlHelper, int location, bool inTable, int? parentRecordId, List<ModelAction>
actions)
{
int actionNo = 1;
StringBuilder text = new StringBuilder();
foreach (var action in actions)
{
if (action.LocationType == location)
{
if (inTable)
text.Append("<td>");
else
if (actionNo > 1)
text.Append(" | ");
text.Append(htmlHelper.ActionLink(action.Label, action.ActionTypeLookup.CodeName, new { actionId = action.ModelActionId,
parentRecordId = parentRecordId }));
if (inTable)
text.Append("</td>");
actionNo++;
}
}
return text.ToString();
}
This really worked well in MVC.
What would the equivent be in MVVM?
I would expect I could do something much more eligent, more along the lines of creating my actions in my viewmodel, and somehow binding to those actions in my view...
For something like that you would probably need to create a custom control. Then you could put it in your view and bind it to the collection of Actions which would exist in your ViewModel.

Resources