Using C# 3.0, we can initialize objects without their constructors for syntactical reasons. Such as ..
ClassName c = new ClassName =
{
Property1 = "Value"
}
I was wondering how this works with Dictionaries and adding the items to them. Any ideas?
class Foo
{
public Dictionary<string,int> DictionaryObject { get; set; }
}
Foo f = new Foo =
{
// ???
}
Thank you for your time!!
class Foo
{
public Dictionary<string,int> DictionaryObject { get; set; }
}
Foo f = new Foo =
{
DictionaryObject = new Dictionary<string,int>
{
{"value1", 42},
{"value2", 43}
}
}
Related
I am trying to add select in blazorise component. Somehow it not showing me dropdown selected values. Please go through below code
Temp.razor file
#page "/temp"
#using Blazorise.DataGrid
<h3>TempComponent</h3>
<DataGrid TItem="ClassA"
Data="#Classes"
Editable="true"
RowUpdated="#OnRowUpdatedAsync">
<DataGridCommandColumn >
<EditCommandTemplate>
<Blazorise.Button Clicked="#context.Clicked"><Icon Name="IconName.Edit" /></Blazorise.Button>
</EditCommandTemplate>
<SaveCommandTemplate>
<Blazorise.Button Clicked="#context.Clicked"><Icon Name="IconName.Save" /></Blazorise.Button>
</SaveCommandTemplate>
</DataGridCommandColumn>
<DataGridColumn TItem="ClassA" Field="#nameof(ClassA.Name)" Caption="Name" Editable="true"/>
<DataGridSelectColumn TItem="ClassA" Field="#nameof(ClassA.B)" Caption="B" Editable="true">
<DisplayTemplate>
#if (#context.B != null)
{
#context.B.Name
}
</DisplayTemplate>
<EditTemplate>
<Select TValue="int" SelectedValue="#selectValue"
SelectedValueChanged="#SelectedValueChangedHandler">
#if (ClassesB != null)
{
foreach (var classB in ClassesB)
{
<SelectItem Value="#(classB.Id)">#(classB.Name)</SelectItem>
}
}
</Select>
</EditTemplate>
</DataGridSelectColumn>
</DataGrid>
#code{
int selectValue = 0;
public class ClassA {
public string Name { get; set; }
public ClassB B { get; set;}
}
public class ClassB {
public int Id { get; set; }
public string Name { get; set; }
}
List<ClassA> Classes = new List<ClassA> {
new ClassA { Name = "Class1", B = new ClassB() { Id = 1, Name = "ClassB1" }},
new ClassA { Name = "Class2", B = new ClassB() { Id = 2, Name = "ClassB2" }}
};
List<ClassB> ClassesB = new List<ClassB> {
new ClassB { Id = 1, Name = "ClassB1" },
new ClassB { Id = 2, Name = "ClassB2" }
};
protected void OnRowUpdatedAsync(SavedRowItem<ClassA, Dictionary<string, object>> e)
{
}
private void SelectedValueChangedHandler(int value)
{
Console.WriteLine("values " + value);
selectValue = value;
}
}
And Current Output Screenshot (select dropdown value not showing )
Whenever user select column then value should be change in list and also display in datagrid.
For this I took reference from https://github.com/Megabit/Blazorise/issues/561
Please help me to solve this issue .
Thanks in advance
public class MyInfo
{
public string Status { get; set; }
public string Class { get; set; }
public string FriendlyName { get; set; }
public string InstanceId { get; set; }
}
string strScript = "Get-PnpDevice";
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(strScript);
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
foreach (PSObject pSObject in results)
{
}
After JsonConvert.SerializeObject(pSObject);
{"CliXml":"<Objs Version=\"1.1.0.1\" xmlns=\"http://schemas.microsoft.com/powershell/2004/04\">\r\n <S>_x000D__x000A_Status Class FriendlyName InstanceId _x000D__x000A_------ ----- ------------ ---------- _x000D__x000A_Unknown HIDClass HID-compliant consumer control device HID\\VID_0..._x000D__x000A_OK System System board ACPI\\PNP0..._x000D__x000A_OK System Motherboard resources ACPI\\PNP0..._x000D__x000A_OK System Motherboard resources SWD\\MSRRA..._x000D__x000A_Unknown HIDClass HID-compliant vendor-defined device HID\\VID_0..._x000D__x000A__x000D__x000A__x000D__x000A_</S>\r\n</Objs>"}
But I need is MyClasss.Class so i can diferentiate or make some condition on it .
1 => Create this classes
public class HardwareDevice
{
public string Name { get; set; }
public List<HardwareProperty> Properties { get; set; }
public HardwareDevice()
{
Properties = new List<HardwareProperty>();
}
}
public class HardwareProperty
{
public string Name { get; set; }
public string Value { get; set; }
}
2 = > Call this method which return List
var hardware = GetHardwareInfo(string "select * from Get-PnpDevice", string scope = "ROOT\\CIMV2")
3 = > here is the method
List<HardwareDevice> GetHardwareInfos(string query, string scope = "ROOT\\CIMV2")
{
List<HardwareDevice> hardwares = new List<HardwareDevice>();
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
foreach (ManagementObject share in searcher.Get())
{
HardwareDevice hrd = new HardwareDevice();
try
{
if (share["Name"] != null)
hrd.Name = share["Name"].ToString().Trim();
else
hrd.Name = share.ToString().Trim();
}
catch
{
hrd.Name = share.ToString().Trim();
}
foreach (PropertyData PC in share.Properties)
{
HardwareProperty property = new HardwareProperty();
property.Name = PC.Name;
if (PC.Value != null && PC.Value.ToString() != "")
{
switch (PC.Value.GetType().ToString())
{
case "System.String[]":
string[] str = (string[])PC.Value;
string str2 = "";
foreach (string st in str)
str2 += st + "&";
property.Value = str2.Trim('&');
break;
case "System.UInt16[]":
ushort[] shortData = (ushort[])PC.Value;
string tstr2 = "";
for (int i = 0; i < shortData.Length; i++)
{
tstr2 += shortData[i].ToString() + "&";
}
property.Value = tstr2.Trim('&');
break;
default:
property.Value = PC.Value.ToString().Trim();
break;
}
}
hrd.Properties.Add(property);
}
hardwares.Add(hrd);
}
}
catch (Exception exp)
{
}
return hardwares;
}
I have a table like this
ReportID ReportName ClassName
-----------------------------------
124 Project Details kipProjectModel
325 Program Master kipProgrammeMaster
543 Resource Master kipResourceMaster
.....
...
..
.----------------------------------
Also I have an API from which it return different JSON reports based on the ID we pass to it
http://myapi.com/reportid=39
So I am getting a JSON report doesnt matter what ever the ID is. But it should desterilize as an object of that class from that table above. Since its a string name I have no idea how to achieve that.
I am using newtonsoft json
Environment is .NET Core 5.0
This method can build a generic list type from class name. Note that class name must be full name, including namespace:
private static Type GetListTypeByElementName(string elementClassName)
{
var genericType = typeof(List<>);
var elementTypes = new Type[] { Type.GetType(elementClassName) };
return genericType.MakeGenericType(elementTypes);
}
If your api response is a "plain" object, not a collection, you can get the type by simply doing:
var reportType = Type.GetType(reportTypeName);
Then you can use it to deserialize with the appropiate overload of DeserializeObject. Example:
var classAList = new List<ClassA> {
new ClassA { ClassAId = 1, ClassAName = "Item A-1" },
new ClassA { ClassAId = 2, ClassAName = "Item A-2" },
new ClassA { ClassAId = 3, ClassAName = "Item A-3" },
new ClassA { ClassAId = 4, ClassAName = "Item A-4" },
new ClassA { ClassAId = 5, ClassAName = "Item A-5" }
};
var classBList = new List<ClassB> {
new ClassB { ClassBId = 1, ClassBName = "Item B-1" },
new ClassB { ClassBId = 2, ClassBName = "Item B-2" },
new ClassB { ClassBId = 3, ClassBName = "Item B-3" },
new ClassB { ClassBId = 4, ClassBName = "Item B-4" },
new ClassB { ClassBId = 5, ClassBName = "Item B-5" }
};
var jsonClassAList = JsonConvert.SerializeObject(classAList);
var jsonClassBList = JsonConvert.SerializeObject(classBList);
var classAClassName = "TestDeserialize.ClassA";
var classBClassName = "TestDeserialize.ClassB";
var deserializedClassAList = JsonConvert.DeserializeObject(jsonClassAList, GetListTypeByElementName(classAClassName));
var deserializedClassBList = JsonConvert.DeserializeObject(jsonClassBList, GetListTypeByElementName(classBClassName));
Note than the deserialized collection will be a List of the correct type, but at compile time it will be a list of objects, without the specific type.
Classes definitions:
class ClassA
{
public int ClassAId { get; set; }
public string ClassAName { get; set; }
}
class ClassB
{
public int ClassBId { get; set; }
public string ClassBName { get; set; }
}
Is it possible to inline initialize an array of the interface type IFooFace with different specific implementations? Or is it not possible and I have to initialize my objects before the array and then just pass them in?
This is how I can do it in C#:
public interface IFooFace
{
int Id { get; }
}
public class Bar : IFooFace
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Zar : IFooFace
{
public int Id { get; set; }
public string MegaName { get; set; }
}
internal class Program
{
public static IFooFace[] Data =
{
new Bar
{
Id = 0,
Name = "first"
},
new Zar
{
Id = 1,
MegaName = "meeeega"
}
};
}
And this is what I tried in TypeScript:
export interface IFooFace {
id: number;
}
export class Bar implements IFooFace {
public id: number;
public name: string;
// a lot of more properties
}
export class Zar implements IFooFace {
public id: number;
public megaName: string;
// a lot of more properties
}
var Data : IFooFace[] = [
// how to initialize my objects here? like in C#?
// this won't work:
// new Bar(){
// id: 0,
// name: "first"
// },
// new Zar() {
// id: 1,
// megaName: "meeeeega"
// }
// this also doesn't work:
// {
// id: 0,
// name: "first"
// },
// {
// id: 1,
// megaName: "meeeeega"
// }
];
No, TypeScript does not have object initializers. #RyanCavanaugh shows possible solution in TS:
class MyClass {
constructor(initializers: ...) { ... }
}
var x = new MyClass({field1: 'asd', 'field2: 'fgh' });
Model::::
public class Model1
{
public string Name { get; set; }
public string ProductName { get; set; }
}
ViewModel::::
public class ViewModel1
{
public List<Model1> model1;
}
controller:::::::::
var sent = entities.Table1.Where<Table1>(o => o.SenderUserId == userId );
ViewModel1 newViewModel = new ViewModel1();
foreach (Table1 gf in sent)
{
var nmodel = new Model1();
nmodel.Name = gf.Name;
nmodel.ProductName = doSomething(gf.ProductName);
// **Here I'm stuck====how do I add nmodel to newViewModel**
//**newViewModel.Add===does not work**
}
return View(newViewModel);
A quick guess based on the code you posted, is that you never instantiated the collection.
public class ViewModel1
{
List<Model1> model1;
public ViewModel1()
{
model1=new List<Model1>();
}
}
......
newViewModel.model1.Add(nmodel);
Change your ViewModel as follows
ViewModel::::
public class ViewModel1
{
public List<Model1> model1 = new List<Model1>();
}
Change your controller as follows:
var sent = entities.Table1.Where<Table1>(o => o.SenderUserId == userId );
ViewModel1 newViewModel = new ViewModel1();
foreach (Table1 gf in sent)
{
var nmodel = new Model1();
nmodel.Name = gf.Name;
nmodel.ProductName = doSomething(gf.ProductName);
newViewModel.model1.Add(nmodel);
}
return View(newViewModel);