Is there a way to access individual elements of an object returned from the helper function in Handlebar java - handlebars.java

public class book {
public String PNR;
public String DepartureStation;
public String ArrivalStation;
}
A custom helper function would return a book object, but is there a way to access {{ book.pnr}} in hbs file

Related

Yii2 working with private property - non db column

I am working with Yii2 and till date using public property for non db columns like following :
public $category_id;
public function rules() {
return [
[['category_id'], 'safe'],
];
}
//// inside $dataProvider
$this->load($params);
it works perfectly. but now I want to make category_id as private so how to manage it inside rules and how to load and also set inside form element on load ?
You may use accessor and mutator for access to your private attribute, for example:
private category_id;
public function setCategory (value)
{
$this->category_id = value;
}
public function getCategory()
{
return $this->category_id;
}
These methods allow to use private attribute just as public attribute with different name in other parts of application. For example, you may use it in rules
public function rules()
{
return [['category', 'safe']];
}
Or in another code:
$model->category = 777

JAXB: serialize private fields and deserialize without a parameter-less contructor

The problem I have involves a pretty complex class structure but I managed to summarize the gist of it in the following simpler example. I need to be able to serialize an object of class MyItem (including private property 'text') and subsequently deserialize it without having a parameter-less constructor available and without being able to create one because it would totally mess up the current logic.
class MyCollection:
#XmlRootElement(name="collection")
public class MyCollection {
public MyCollection() {
this.items = new ArrayList<MyItem>();
}
#XmlElement(name="item")
private List<MyItem> items;
public void addItem(String text) {
this.items.add(new MyItem(text));
}
}
class MyItem:
public class MyItem {
public MyItem(String text) {
this.text = text;
}
#XmlAttribute
private String text;
}
The first requirement (serialize MyItem including private property) is met out of the box and I get the following xml as a result:
<collection>
<item text="FIRST"/>
<item text="SECOND"/>
<item text="THIRD"/>
</collection>
In order to meet the second requirement I decorated class MyItem with attribute #XmlJavaTypeAdapter
#XmlJavaTypeAdapter(MyItemAdapter.class)
public class MyItem {
...
and introduced classes AdaptedMyItem
public class AdaptedMyItem {
private String text;
public void setText(String text) { this.text = text; }
#XmlAttribute
public String getText() { return this.text; }
}
and MyItemAdapter
public class MyItemAdapter extends XmlAdapter<AdaptedMyItem, MyItem> {
#Override
public MyItem unmarshal(AdaptedMyItem adaptedMyItem) throws Exception {
return new MyItem(adaptedMyItem.getText());
}
#Override
public AdaptedMyItem marshal(MyItem item) throws Exception {
AdaptedMyItem result = new AdaptedMyItem();
result.setText("???"); // CANNOT USE item.getText()
return result;
}
}
but this is where I get stuck because in method marshal I cannot access MyItem.text and so I cannot use the standard approach for dealing with immutable classes in JAXB.
Bottomline: I would like to use the class adapter mechanism only when deserializing (because I need to invoke a non-parameterless constructor) but not when serializing (because I cannot access private properties). Would that be possible?

Object reference not set to an instance of an object, Interface

I know that this is one of the most encountered error but I am really struggling to get around it.
i have a property on my Controller:
private readonly ISelectListFactory _selectFactory;
and a method that called to populate the viewbag
private void PopulateLists()
{
var continent = _selectFactory.GetItems();
}
and the interface
public interface ISelectListFactory
{
IEnumerable<SelectListItem> GetItems();
}
and in the controller constructor I have the following:
public LocationController(ISelectListFactory selectFactory)
{
_selectFactory = selectFactory;
}
but I am getting this error Object reference not set to an instance of an object and not sure how to overcome it.
Regards
Make sure you have instantiated this _selectFactory variable somewhere. Like for example:
_selectFactory = new SomeConcreteSelectListFactory();
or if you are using dependency injection you might configure your DI framework to inject it into the constructor:
public class HomeController: Controller
{
private readonly ISelectListFactory _selectFactory;
public HomeController(ISelectListFactory selectFactory)
{
_selectFactory = selectFactory;
}
... some controller actions where you could use the _selectFactory field
}

.NET Dynamic Decision to Call Similar Classes?

C# on .NET 4.5:
public Interface IMyInterface
{
public string DoSomething( string input1 )
}
public MyClass1 : IMyInterface
{
public string DoSomething( string input1 )
{
return "1";
}
}
public MyClass2 : IMyInterface
{
public string DoSomething( string input1 )
{
return "2";
}
}
At runtime, I want to detect the hosting environment, set some kind of "global", and then based on the global always instance and use MyClass1 or MyClass2. I do not want to have a single "MyClass" and then do lots of case logic inside it to detect the environment.
What is a good pattern or practice to do that? Is this actually a good place for Dynamics?
Thanks.
Seems like you need to use Factory. Create a method in Factory class to return MyClass object. Keep the return type of the method as IMyInterface. Within the method, you can execute your hosting logic and depending upon the output of hosting logic, instantiate proper class and return the reference to the object.

IMetadataAware.OnMetadataCreated is never called

I created attribute class to attach metadata to properties, so I can display tooltips for the form's input fields.
HelpAttribute implements IMetadataAware:
Public Class HelpAttribute
Inherits Attribute
Implements System.Web.Mvc.IMetadataAware
Public Sub New(text As String)
_text = text
End Sub
Private _text As String
Public ReadOnly Property Text As String
Get
Return _text
End Get
End Property
Public Sub OnMetadataCreated(metadata As System.Web.Mvc.ModelMetadata) Implements System.Web.Mvc.IMetadataAware.OnMetadataCreated
metadata.AdditionalValues.Add("HelpText", _text)
End Sub
End Class
I utilize this metadata in my extension method:
<Extension()>
Public Function HelpFor(Of TModel, TProperty)(ByVal htmlHelper As HtmlHelper(Of TModel), expression As Expression(Of Func(Of TModel, TProperty))) As MvcHtmlString
Dim metaData = ModelMetadata.FromLambdaExpression(Of TModel, TProperty)(expression, htmlHelper.ViewData)
If metaData.AdditionalValues.ContainsKey("HelpText") Then
Dim helpText = metaData.AdditionalValues("HelpText")
Return MvcHtmlString.Create(String.Format("<span class=""help""></span><div class=""tooltip"" style=""display: none""><div class=""border-top""></div><div class=""close"">close</div><br class=""clear""><div class=""content"">{1}</div></div>", htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(metaData.PropertyName), helpText, metaData.DisplayName))
End If
Return MvcHtmlString.Create(String.Format("<span class=""no_help""></span>", htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(metaData.PropertyName), metaData.DisplayName))
End Function
So I can call Html.HelpFor for any of my model's properties and if it has appropriate metadata I display a help icon which shows the tooltip on click (js).
That all works fine as long as HelpAttribute is defined in the same assembly as the classes that I decorate their properties with. Today I had to move HelpAttribute to a separate dll (different namespace as well), so I did that, I referenced the project and expected it to work. I do not get any compiler errors, the app works fine, but it does not display the help icons. I debuggedd the code and I see that the constructor of HelpAttribute is called for different properties with a proper text, but OnMetadataCreated is never called. Does anyone have an idea why that is and how to fix it?
Another reason this may not be called is if you have the wrong namespace referenced. So
using System.Web.ModelBinding;
will compile and not be hit, but you should be using
using System.Web.Mvc;
Once again I will answer my question myself. Apparently posting things on SO helps me structure the problem in my head. When I moved HelpAttribute to a seperate class library I had to reference System.Web.Mvc for IMetadataAware interface. I use .NET 4.0 and I automatically referenced MVC4 that I installed some time ago for testing purposes. It didn't get me any errors, it just did not work. When I changed System.web.Mvc to ver. 3.0 everything works smoothly.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web;
using System.Web.Mvc;
namespace ColorPickerAttributeExample.Attributes
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class ColorPickerAttribute : Attribute, IMetadataAware
{
private const string Template =
"$('#{0}').ColorPicker({{onSubmit: function(hsb, hex, rgb, el) {{" +
"var self = $(el); self.val(hex);self.ColorPickerHide();}}, onBeforeShow: function () " +
"{{$(this).ColorPickerSetColor(this.value);}}}}).bind('keyup', function(){{ $(this).ColorPickerSetColor(this.value); }});";
public const string ColorPicker = "_ColorPicker";
private int _count;
// if using IoC container, you could inject this into the attribute
internal HttpContextBase Context
{
get { return new HttpContextWrapper(HttpContext.Current); }
}
public string Id
{
get { return "jquery-colorpicker-" + _count; }
}
#region IMetadataAware Members
public void OnMetadataCreated(ModelMetadata metadata)
{
IList<string> list = Context.Items["Scripts"] as IList<string> ?? new List<string>();
_count = list.Count;
metadata.TemplateHint = ColorPicker;
metadata.AdditionalValues[ColorPicker] = Id;
list.Add(string.Format(CultureInfo.InvariantCulture, Template, Id));
Context.Items["Scripts"] = list;
}
#endregion
}
}
using ColorPickerAttributeExample.Attributes;
using System;
namespace ColorPickerAttributeExample.Models
{
public class HomeModel
{
[ColorPicker]
public string ColorPicker { get; set; }
[ColorPicker]
public DateTime ColorPicker2 { get; set; }
}
}
#model dynamic
#{
var picker = ViewData.GetModelAttribute<ColorPickerAttribute>();
if (picker != null)
{
#Html.LabelForModel()
#Html.TextBoxFor(m => m, new {id = ViewData.ModelMetadata.AdditionalValues[ColorPickerAttribute.ColorPicker]})
}
}