Accessing IsVisible property of a XAML element's parent in code-behind - xaml

if (span.Text == "Specific String")
{
var spanAncestor = span.Parent.Parent;
spanAncestor.IsVisible = false; // Throws error. Read below.
}
The error I get is:
Error CS1061 'Element' does not contain a definition for 'IsVisible'
and no accessible extension method 'IsVisible' accepting a first
argument of type 'Element' could be found (are you missing a using
directive or an assembly reference?)
The span has as a parent a FormattedString, which has as a parent a Label.
Is there a way to set IsVisible property for the ancestor element?

Parent is of type Element, which does not have an IsVisible property. You need to cast it first
if (parent is VisibleElement)
{
((VisibleElement)parent).IsVisible = false;
}

Adding to Jason's answer, you could save the typecast, since you're already checking the type in the if-clause and do the following using pattern matching:
if (parent is VisibleElement visibleParent)
{
visibleParent.IsVisible = false;
}

Related

Cannot access a #context.field in <SelectedTemplate> in Blazored Typeahead

I have a problem with Typeahead with my Blazor-Server app:
<BlazoredTypeahead style="width: auto" SearchMethod="SearchUser"
#bind-Value="calc.FkCustomerId">
<SelectedTemplate>
#context.AccountCode
</SelectedTemplate>
<ResultTemplate>
#context.CustomerSname (#context.AccountCode)
</ResultTemplate>
</BlazoredTypeahead>
#{
private async Task<IEnumerable<AutolineAccts>> SearchUser(string SelectedUser)
{
return await Task.FromResult(alContext.AutolineAccts.Where(x => x.CustomerSname.Contains(SelectedUser)).ToList());
}
}
The problem I have occurs in the SelectedTemplate part:
'string' does not contain a definition for 'AccountCode' and no accessible extension method 'AccountCode' accepting a first argument of type 'string' could be found
Intellisense is supposed to show me all the fields of AutolineAccts, but it does not. But it works for the #context object within the node
'string' does not contain a definition for 'AccountCode' and no accessible extension method 'AccountCode' accepting a first argument of type 'string' could be found
The conext in <SelectedTemplate> is corresponding to that in #bind-Value, seems that calc.FkCustomerId is a string type value, and it definetely doesn't have a AccountCode property, so the above error occurs.
You can refer to this article for how to use Blazored Typeahead.

How to set focus on Blazor.Typeahead component?

I'm using the BlazorTypeahead component in my project. I would like to set focus on the typeahead textbox, but can't seem to figure out how to do it. Here's my page. The search and value changed methods work fine, so I'm leaving them out.
#page "/"
#using Microsoft.JSInterop
#using Microsoft.AspNetCore.Components
#inject IJSRuntime jsRuntime
#inject Blazored.LocalStorage.ILocalStorageService localStore
<BlazoredTypeahead SearchMethod="SearchMyModel" TItem="MyModel" TValue="MyModel" Value="SelectedMyModel" ValueChanged="MyModelChanged" ValueExpression="#(() => SelectedMyModel)" placeholder="My Model name..." #ref="NewElementHere">
<SelectedTemplate>
#context.Name
</SelectedTemplate>
<ResultTemplate>
#context.Name (#context.AnotherProperty)
</ResultTemplate>
</BlazoredTypeahead>
#code {
//public BlazoredTypeahead<MyModel, MyModel> NewElementHere { get; set; }
ElementReference NewElementHere;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
// Focus the element
await jsRuntime.InvokeAsync<object>("BlazorFocusElement", NewElementHere);
}
}
}
The index.html file has this script in the header.
window.BlazorFocusElement = (element) => {
if (element instanceof HTMLElement) {
element.focus();
}
};
The code above produces the following compile time error:
Error CS0029 Cannot implicitly convert type
'Blazored.Typeahead.BlazoredTypeahead<MyModel, MyModel>' to
'Microsoft.AspNetCore.Components.ElementReference'
If I remove the ElementReference and instead enable [i.e., remove comment] the property in the #code, it'll build, but I get a runtime error An unhandled error has occurred. If I look in the web debugger console it says:
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Derived classes must implement it System.NotImplementedException: Derived classes must
implement it
You can't apply ElementReference to component... BlazoredTypeahead is a component, so you can't do it. The author of the BlazoredTypeahead should have provided a way to do it... Review the methods and properties of this component. Perhaps this component provide such functionality via one of its attributes...
In any case, you can't use the ElementReference here. But I guess you can still use JSInterop to set the focus, even if the input text you want to set focus to has no id attribute. Just look at the Html source, identify the input text element, and contrive a way to set the focus.
Note that if you're using .Net 5.0, you can set the focus from Blazor.

How to setup a web api controller Post method

I am changing my project to post multiple objects to my db table. The issue I am having is, after I changed the Post method I do not know how to return the created route with the Id's of the objects. I have not done this before so I believe I a correct on everything else up until that point.
public async Task<IHttpActionResult> PostNewPurchaseOrderDetail([FromBody]IEnumerable<PurchaseOrderDetail> newPurchaseOrderDetail)
{
try
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
using (var context = new ApplicationDbContext())
{
context.PurchaseOrderDetails.AddRange(newPurchaseOrderDetail);
await context.SaveChangesAsync();
return CreatedAtRoute("PurchaseOrderDetailApi", new { newPurchaseOrderDetail.PurchaseOrderDetailId }, newPurchaseOrderDetail);
}
}
catch (Exception ex)
{
return this.BadRequest(ex.Message);
}
}
Error Message
Error 2 'System.Collections.Generic.IEnumerable' does not contain a definition for 'PurchaseOrderDetailId' and no extension method 'PurchaseOrderDetailId' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?) C:\Development\TexasExterior\TexasExterior\apiControllers\apiPurchaseOrderDetailController.cs 58 98 TexasExterior
The error tells you exactly what the issue is. You variable, newPurchaseOrderDetail is an enumerable of PurchaseOrderDetail, and you're trying to reference a property of PurchaseOrderDetail directly off of it. You need to get a single item from the list before you can call the property. For example:
return CreatedAtRoute("PurchaseOrderDetailApi", new { newPurchaseOrderDetail.First().PurchaseOrderDetailId }, newPurchaseOrderDetail);
Notice the .First(). However, that would only give you the id of the first item in the collection, which is probably not what you want. I'm not sure what your CreatedAtRoute method does or how it works, but you could change the second parameter to expect a collection of ids and then pass something like:
newPurchaseOrderDetail.Select(m => m.PurchaseOrderDetailId)
Which would give you a list of ids.

List of DisposableLazy`2 does not have 'Add' method when called using dynamic variable

Problem
I am facing a problem using dynamically created list of items when Add method is called on dynamicvariable. Consider following code.
IEnumerable<dynamic> plugins = (IEnumerable<dynamic>)field.GetValue(instance);
if (plugins == null)
continue;
dynamic filteredPlugins = null;
foreach (var plugin in plugins)
{
if (filteredPlugins == null)
filteredPlugins = Activator
.CreateInstance(typeof(List<>)
.MakeGenericType(plugin.GetType()));
if (/* this condition does not matter*/)
//filteredPlugins.Add(plugin);
filteredPlugins.GetType().GetMethod("Add")
.Invoke(filteredPlugins, new object[] { plugin });
}
And now, the commented line filteredPlugins.Add(plugin) will throw System.Reflection.TargetInvocationException with the message 'object' does not contain a definition for 'Add' when plugin is of type
System.ComponentModel.Composition.ExportServices.DisposableLazy<IPlugin,IMetadata>
but it works completely perfect when pluginis of type
System.Lazy<IPlugin, IMetadata>
When the reflection is used to call Add method on the instance filteredPlugins instance as is done on the next line - everything works fine for any type.
My question is WHY is not Add method found in case of DisposableLazy type.
Background
This code is part of the method that I use in OnImportsSatisfied() method. I am using two kinds of import - which differs only in RequiredCreationPolicy - on has CreationPolicy.NonShared and the other default value of CreationPolicy.Any.
[ImportMany(RequiredCreationPolicy = CreationPolicy.NonShared)]
private IEnumerable<Lazy<IPlugin, IMetadata>> plugins = null;
For CreationPolicy.NonShared fields the underlaying type in the plugins is DisposableLazy and for CreationPolicy.Any the underlaying type in the plugins is Lazy.
Edit: As asked in the answer - I am using dynamic variable because IPlugin interface can change everytime this method is called and they do not have to have anything in common.
Edit2: I just found similar question C# dynamic type gotcha, so this can be probably closed as duplicite.
Because System.ComponentModel.Composition.ExportServices.DisposableLazy is a private class, the runtime binder is having trouble believing you have permission to use type, where reflection doesn't care.
Which begs the question why are you using dynamics at all in this case. Since DisposableLazy<IPlugin,IMetadata> public interface is it's subclass Lazy<IPlugin, IMetadata> & IDisposable, shouldn't you just be using a List<Lazy<IPlugin, IMetadata>> for either case?
var plugins = (IEnumerable<Lazy<IPlugin, IMetadata>>)field.GetValue(instance);
if (plugins == null)
continue;
var filteredPlugins = new List<Lazy<IPlugin, IMetadata>>();
foreach (var plugin in plugins)
{
if (/* this condition does not matter*/)
filteredPlugins.Add(plugin);
}
}

GXT TextField or TextArea not decode html entites

i use grid cell renderer... and form bindig...
grid cell renderer valus is good
form bindig value is bad (
i tested: ff9 and last chrome
this bug ? or browser error ? or something else ?
sorry i little speak english.... (i use gtranslate)
error picture => http://test.eggproject.hu/gxt/textfieldentitesbugg.PNG
about json(gxt model)
{"ID":1,"user_email":"xxxx#xxxx.com","display_name":"XXX YYYY","user_cegnev":"","user_jogosultsag":"administrator","user_kedvezmeny":0,"user_city":0,"user_irsz":-1,"user_district":3,"user_street":241,"user_hazszam":"2813","user_emelet":"10","user_ajto":"588","user_kapucsengo":"58","user_comment":"óüöú\u0151\u0171áí","first_name":"Harangozo","last_name":"Gabor","user_telephone":"06111111","user_street2":""}
user_comment error displaying just textarea or textfield why ?
This is due to the components each section is using. A grid is essentially a tag which means any HTML encoded data loaded into this table is rendered correctly. Conversely A TextBox is a tag which only displays exactly what can be seen.
A solution is a custom field binding which processes the data in and out.
public class HTMLParserBinding extends FieldBinding {
protected Field<?> field;`
public HTMLParserBinding( Field<?> field, String property ) {
super(field, property);
this.field = field;
}
protected Object onConvertFieldValue( Object value ) {
if (value == null) {
return null;
}
return Format.htmlDecode(value.toString());
}
protected Object onConvertModelValue( Object value ) {
if( value == null ) {
return null;
}
return Format.htmlEncode(value.toString());
}
}