I have these two methods:
public MessagesPage(ContactModel input)
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
ConversationsList = new ObservableCollection<ConversationModel>();
ContactModel ConversationPartner = new ContactModel();
ConversationPartner = input;
...
}
And the input which is the parameter in the method above, I also would like to use it in this method (they're in the same class)
private async void Send()
{
Guid guid = Guid.NewGuid();
string ID = guid.ToString();
ConversationModel conversationObject = new ConversationModel()
{
id = ID,
converseeID = dataClass.loggedInUser.uid,
message = Message,
created_at = DateTime.UtcNow
};
await CrossCloudFirestore.Current
.Instance
.GetCollection("contacts")
.GetDocument(ConversationPartner.id)
.GetCollection("conversations")
.GetDocument(ID)
.SetDataAsync(conversationObject);
Message = string.Empty;
}
because as you can see, in .GetDocument, it needs the id of ConversationPartner. I would get object reference not set to an instance of an object when the Send() method is called because it doesn't have access to ContactModel input in MessagesPage above.
you need to declare ConversationPartner as a class level variable, not inside of of a specific method. This will make it available throughout your class
ContactModel ConversationPartner;
public MessagesPage(ContactModel input)
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
ConversationsList = new ObservableCollection<ConversationModel>();
ConversationPartner = input;
...
}
Related
I have a following method in my command handler that gets variables from another method,im trying to pass those variable into the CreateUser(NewAccount); method but it always comes back as null
public async Task ExecuteAsync(CreateUserAccountCommand command)
{
var result = await _client.CreateUser(GetAccountFrom(command)); // so this line gets the variables from GetAccountFrom(command)
_httpContextAccessor.HttpContext.Items["CreateUserAccountCommand"] = result;
}
private Account GetAccountFrom(CreateUserAccountCommand command)
{
var NewAccount = new Account();
NewAccount.FirstName = command.FirstName;
NewAccount.LastName = command.LastName;
return NewAccount()
}
however when i call CreateUser to pass in the variables into NewAccount thats coming from GetAccountFrom(command) it passes it in as a null
public System.Threading.Tasks.Task<Account> CreateUser(Account NewAccount,)
{
return base.Channel.CreateUser(NewAccount);
}
What am i doing wrong?
You are creating a new instance of NewAccount in your return statement.
private Account GetAccountFrom(CreateUserAccountCommand command)
{
var newAccount = new Account();
newAccount.FirstName = command.FirstName;
newAccount.LastName = command.LastName;
return newAccount; // <- Return the variable
}
You are creating object with new keyword. All you need to do is to return this object from your method with simple call:
return NewAccount;
The way you do it now is that you are returning result of NewAccount() method (whatever it is, apparently null), which is not what you want.
Also you might want to inspect why NewAccount() returns always null.
Your code has many anti patterns but it seems like you have a method somewhere in the base newAccount(); This is why inheritance should be avoided (for beginners and mids)
also the convention for private local variables lowercase.. as to NOT CONFUSE yourself.
private Account GetAccountFrom(CreateUserAccountCommand command)
{
var newAccount = new Account();
newAccount.FirstName = command.FirstName;
newAccount.LastName = command.LastName;
return newAccount;
}
or to completely avoid confusion just do this
private Account GetAccountFrom(CreateUserAccountCommand command)
{
return new Account{
FirstName = command.FirstName,
LastName = command.LastName,
}
}
But to avoid anti-patterns and spaghetti code you should really make an extension method which is much more S.O.L.I.D !
namespace you.company
{
public static CommandExtensions{
public static Account GetAccountFrom(this CreateUserAccountCommand command)
{
return new Account
{
FirstName = command.FirstName,
LastName = command.LastName,
};
}
}
I am trying to make a Master-Detail Navigation using help of this github example. The relevant code sample from my project is -
MasterPageItem.cs
namespace Demo.MenuItems
{
public class MasterPageItem
{
public string Title { get; set; }
public string IconSource { get; set; }
public Type TargetType { get; set; }
}
}
MainPage.Xaml.cs
public partial class MainPage : MasterDetailPage
{
public MainPage()
{
InitializeComponent();
masterPage.ListView.ItemSelected += OnItemSelected;
if (Device.RuntimePlatform == Device.UWP)
{
MasterBehavior = MasterBehavior.Popover;
}
Detail = new NavigationPage(new HomePage());
}
void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var item = e.SelectedItem as MasterPageItem;
if (item != null)
{
Detail = new NavigationPage((Page)Activator.CreateInstance(item.TargetType));
masterPage.ListView.SelectedItem = null;
IsPresented = false;
}
}
}
MasterPage.Xaml.cs
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MasterPage : ContentPage
{
public ListView ListView { get { return listView; } }
public MasterPage()
{
InitializeComponent();
var masterPageItems = new List<MasterPageItem>();
masterPageItems.Add(new MasterPageItem
{
Title = "Help",
IconSource = "icon-1.jpg",
TargetType = typeof(WebPage)
});
listView.ItemsSource = masterPageItems;
}
}
It works if no data is required to pass in detail page. However, I need to pass one string value url in page WebPage, but I am unable to figure out how to pass string value or any data in following line -
Detail = new NavigationPage((Page)Activator.CreateInstance(item.TargetType));
For e.g., following is the code sample for the page WebPage -
public WebPage (string URL)
{
InitializeComponent ();
Browser.Source = URL;
}
Here I am unable to figure out, how should I pass url from Master-Detail Navigation?
Generalized Way :
//This will create instance of the page using the parameterized constructor you defined in each DetailPages
Detail = new NavigationPage((Page)Activator.CreateInstance(item.TargetType, myStringParam));
//Your Each Detail Page should have parametrized constructor.
public MyPage (string param)
{
InitializeComponent ();
Browser.Source = param;
}
Here, you can serialize the c# object and pass JSON string into myStringParam. Your page receives this in page’s parameterized constructor you defined and there, you can deserialize, thus you can pass complex objects as JSON into a page as well as simple string.
If you want to add parameterized constructor in only one DetailPage then:
if(item.TargetType == typeof(WebPage))
{
Detail = new NavigationPage((Page)Activator.CreateInstance(item.TargetType, myStringParam));
}
else
{
Detail = new NavigationPage((Page)Activator.CreateInstance(item.TargetType));
}
//Your Page would be:
public WebPage (string URL)
{
InitializeComponent ();
Browser.Source = URL;
}
Yes you can Activator.CreateInstance Method as many overloads
Detail = new NavigationPage((Page)Activator.CreateInstance(item.TargetType, url));
All the overloads can be found here
Activator.CreateInstance Method
The one you want is here
Activator.CreateInstance Method (Type, Object[])
Parameters
type Type: System.Type
The type of object to create
args Type: System.Object[]
An array of arguments that match in number,
order, and type the parameters of the constructor to invoke. If args
is an empty array or null, the constructor that takes no parameters
(the default constructor) is invoke
I am trying to pass data from a view model (VM) to ParentViewPagerVM to ChildTabVM. In my first VM I get the data which I want to pass to ChildTabVM. I could not find any solution how to do that.
FirstViewModel.cs
public MvxCommand GoToLocationInfoCommand
{
get
{
return new MvxCommand(
() => ShowViewModel<LocationViewPager>(new { param = "Test"}));
}
}
ParentViewPagerViewModel.cs
public void Init(string param)
{
Debug.WriteLine("Paramter: " + ZipCode);
}
ParentViewPagerFragment.cs
if (viewPager != null)
{
var fragments = new List<MvxCachingFragmentStatePagerAdapter.FragmentInfo>
{
new MvxCachingFragmentStatePagerAdapter.FragmentInfo(
"Tab1", typeof(Child1Fragment), typeof(Child1ViewModel)),
new MvxCachingFragmentStatePagerAdapter.FragmentInfo(
"Tab2", typeof(Child2Fragment), typeof(Child2ViewModel)),
new MvxCachingFragmentStatePagerAdapter.FragmentInfo(
"Tab3", typeof(Child3Fragment), typeof(Child3ViewModel))
};
viewPager.Adapter = new MvxCachingFragmentStatePagerAdapter(
Activity, ChildFragmentManager, fragments);
}
Since I am making a tabView, I can't find a way to pass data from my ParentViewPagerVM to Child1VM. Any idea?
MvxCachingFragmentStatePagerAdapter.FragmentInfo constructor provides an option for passing parameters to the ViewModel type you want to have constructed.
public FragmentInfo(
string title,
Type fragmentType,
Type viewModelType,
object parameterValuesObject = null);
Implementation Example
Assuming you have a property ZipCode on your ParentViewPagerViewModel you can pass as a parameter.
var fragments = new List<MvxCachingFragmentStatePagerAdapter.FragmentInfo>
{
new MvxCachingFragmentStatePagerAdapter.FragmentInfo(
title: "Tab1",
fragmentType: typeof(Child1Fragment),
viewModel: typeof(Child1ViewModel),
parameterValuesObject: new { zipCode = ViewModel.ZipCode})
};
Then in your Child ViewModel retrieve it via the Init
public void Init(int zipCode)
{
// Do stuff with zipCode
}
Is there any way to access a private constructor from controller to model?
The controller containing method calling the model is as follows:
public ActionResult ReadXML()
{
XmlSerializer reader = new XmlSerializer(typeof(List<Asseted>));
TextReader textReader = new StreamReader(#"D:\Tial2.xml");
List<Asseted> asseted;
List<Asseted> list = new List<Asseted>();
asseted = (List<Asseted>)reader.Deserialize(textReader);
textReader.Close();
for (int i = 0; i < asseted.Count; i++)
{
string data123 = Convert.ToString(asseted[i].PopertyValue);
string data234 = Convert.ToString(asseted[i].PropertyName);
list.Add(new Asseted(data123,data234));
}
return View();
}
The model containing the Method to be called is as follows:
[XmlRoot]
public class Asseted
{
string pName, pValue;
private string data234;
private string data123;
private Asseted(string data234, string data123)
{
// TODO: Complete member initialization
PropertyName = data234;
PopertyValue = data123;
}
[XmlElement]
public string PropertyName { get; set; }
[XmlElement]
public string PopertyValue { get; set; }
}
Is there any way to access a private constructor from controller to model?
While it may be arguable if this is the right way to solve your problem, the question itself can be answered with YES. And it's not even very hard with reflection.
ConstructorInfo constructor = typeof(Asseted).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
new[] { typeof(string), typeof(string) },
null);
Asseted instance = constructor.Invoke(new[] {
"data234",
"data123"
}) as Asseted;
Basically you get the type (Asseted), get the constructor that matches your known parameter types and invoke it. Done.
Additional Note:
Depending on your compiler and actual code, you might run into a TypeAccessException.
I would like to point to a row.
Get the Oid(the parameter I want to pass).
When I click a button on the ribbon. It will open MifarePasswordForm. I would like to pass Oid to MifarePasswordForm so that the Oid can be saved in Mifare Card but I'm stuck at getting the Oid. So far, this is what I've got.
public void barButtonItem1_ItemClick()
{
staff entity = gridView.GetRow(gridView.GetSelectedRows()[0]) as staff;
entity.Oid;
MifarePasswordForm modalForm = new MifarePasswordForm();
modalForm.ShowDialog();
RefreshData();
}
This is my password form.
public MifarePasswordForm(int _iD)
{
InitializeComponent();
int iD = _iD;
}
Updated code
public void barButtonItem1_ItemClick()
{
staff entity = gridView.GetRow(gridView.GetSelectedRows()[0]) as staff;
MifarePasswordForm modalForm = new MifarePasswordForm(entity.Oid);
modalForm.ShowDialog();
RefreshData();
}
public MifarePasswordForm(int _iD)
{
InitializeComponent();
int iD = _iD;
textBox1.Text += iD;
}
What you can do is, pass your parameter to form in the constructor itself OR, make a public property and access it after creating formInstance and assign it your designated value.
e.g.
MifarePasswordForm modalForm = new MifarePasswordForm(entity.Oid);
modalForm.ShowDialog();