I am using xamarin forms MVVM pattern. I am using picker and assign itemdisplaybinging and itemssource dynamically from sqlite database. I have attached images.
In AddItems.xaml:
enter code here
<Picker ItemDisplayBinding="{Binding itemlist.ItemName}"
ItemsSource="{Binding itemlist.ItemID}" Title="Select Item..."
Style="{StaticResource PickerFrameStyle}"></Picker>
In AddItems.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ERPSoftware.ViewModel;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace ERPSoftware.Pages.Add
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class AddItems : ContentPage
{
public AddItems()
{
InitializeComponent();
var vm = new AddViewModel();
this.BindingContext = vm;
}
}
}
In AddViewModel.cs(ViewModel):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
using ERPSoftware.Models;
using ERPSoftware.SQLiteDatabase;
using System.Runtime.CompilerServices;
namespace ERPSoftware.ViewModel
{
public class AddViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private bool _IsBusy;
//public ICommand AddItemCommand { protected get; set; }
public ItemPickerPageModel _ItemPickerPageModel;
UETrackDatabase uETrackDatabase = new UETrackDatabase();
private List<ItemPickerPageModel> _itemlist=new List<ItemPickerPageModel>();
public AddViewModel()
{
IsBusy = false;
ItemPickerPageModel = new ItemPickerPageModel();
var ItemList = uETrackDatabase.GetItemPicker();
if (ItemList.Count > 0)
{
foreach(var list in ItemList)
{
_itemlist.Add(new ItemPickerPageModel {ItemID=list.ItemID,ItemName=list.ItemName });
}
}
}
public List<ItemPickerPageModel> itemlist
{
get { return _itemlist; }
private set {
_itemlist = value;
OnPropertyChanged();
}
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
I attached viewmodel screen with this. The Picker shows empty when running the project. Please help me to resolve this issue.
enter image description here
Regards,
Manthiram C
Your making a little bit confusion between the Bindings in the Picker.
<Picker ItemDisplayBinding="{Binding ItemName}"
ItemsSource="{Binding itemlist}"
Title="Select Item..."
Style="{StaticResource PickerFrameStyle}"></Picker>
Related
My ModelState is getting false everytime i run the code .This is simply a file upload mvc .net core code. Migration is also perfectly executed. However whenever i try to submit the form after uploading an image the form gets reset. Due to which it failed to get store in the database.
Model code (Image.cs)
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace FileUpload.Models
{
public class Image
{
[Key]
public int Iid { get; set; }
[Required]
public string Iname { get; set; }
[Required]
[NotMapped]
public IFormFile Iimg { get; set; }
}
}
Controller Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using FileUpload.Data;
using FileUpload.Models;
using Microsoft.AspNetCore.Hosting;
using System.IO;
namespace FileUpload.Controllers
{
public class ImagesController : Controller
{
private readonly AppDbContext _context;
private readonly IWebHostEnvironment _hostEnvironment;
public ImagesController(AppDbContext context, IWebHostEnvironment hostEnvironment)
{
_context = context;
_hostEnvironment = hostEnvironment;
}
// GET: Images
public async Task<IActionResult> Index()
{
return View(await _context.Images.ToListAsync());
}
// GET: Images/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var image = await _context.Images
.FirstOrDefaultAsync(m => m.Iid == id);
if (image == null)
{
return NotFound();
}
return View(image);
}
// GET: Images/Create
public IActionResult Create()
{
return View();
}
// POST: Images/Create
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Image image)
{
if (ModelState.IsValid)
{
if(image.Iimg != null)
{
string wwwRootPath = _hostEnvironment.WebRootPath;
string fileName = Path.GetFileNameWithoutExtension(image.Iimg.FileName);
string ext = Path.GetExtension(image.Iimg.FileName);
image.Iname = fileName + DateTime.Now.ToString("yymmssfff") + ext;
string path = Path.Combine(wwwRootPath + "/Image/" + fileName);
using (var fileStream = new FileStream(path, FileMode.Create))
{
await image.Iimg.CopyToAsync(fileStream);
}
}
_context.Add(image);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(image);
}
}
Using .net core I'm implementing class library to push bulk emails into Email server.Email server will consume my email list and gives feedback after complete.this will take 20-30 seconds.When I got feedback from email server I need to fire method.
I have referred this article to implement event handler.But when I debug it
EventHandler OnFeedbackReceived
parameter is null.see image below
This is class library code.
using System;
using System.Text;
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Collections.Generic;
namespace OSH_EmailServerLibrary
{
public static class EmailMQServerLibrary
{
public static event EventHandler<EmailFeedbackEventArgs> OnFeedbackReceived;
public static void PushToMQ(List<EmailMessage> _emailList)
{
//
// Long RabbitMQ msg push code here
//
EmailMessageFeedback feedback = new EmailMessageFeedback { Description = "Completed", SuccessCount = 10, FailedCount = 0 };
SendFeedback(feedback);
Console.ReadLine();
}
private static EmailMessageFeedback SendFeedback(EmailMessageFeedback feedback)
{
if (OnFeedbackReceived != null)
{
OnFeedbackReceived(feedback, new
EmailFeedbackEventArgs(feedback));
}
return feedback;
}
}
public class EmailFeedbackEventArgs : EventArgs
{
public EmailFeedbackEventArgs(EmailMessageFeedback _feedback)
{
feedback = _feedback;
}
public EmailMessageFeedback feedback { get; set; }
}
}
This is how I user it in a console application
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using OSH_EmailServerLibrary;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
namespace EmailServerSenderSampleConsole
{
class Program
{
static void Main(string[] args)
{
List<EmailMessage> _emailList = _emails.GetAllEmailToSend();
EmailMQServerLibrary.PushToMQ(_emailList);
EmailMQServerLibrary.OnFeedbackReceived += EmailMQServerLibrary_OnFeedbackReceived;
}
private static void EmailMQServerLibrary_OnFeedbackReceived(object sender, EmailFeedbackEventArgs e)
{
}
}
}
Finally Fixed my issue.Issue was not in my class library.Issue was I did subscribe event after PushToMQ() in my console application which is wrong..Thank you so much #Hans Passant helping me out.
here is my corrected answer.I think this will help others like me.
Class Library >>
using System;
using System.Text;
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Collections.Generic;
namespace OSH_EmailServerLibrary
{
public static class EmailMQServerLibrary
{
public static event EventHandler<EmailFeedbackEventArgs> OnFeedbackReceived;
public static void PushToMQ(List<EmailMessage> _emailList)
{
//
// Long RabbitMQ msg push code here
//
EmailMessageFeedback feedback = new EmailMessageFeedback { Description = "Completed", SuccessCount = 10, FailedCount = 0 };
SendFeedback(feedback);
Console.ReadLine();
}
private static EmailMessageFeedback SendFeedback(EmailMessageFeedback feedback)
{
if (OnFeedbackReceived != null)
{
OnFeedbackReceived(feedback, new
EmailFeedbackEventArgs(feedback));
}
return feedback;
}
}
public class EmailFeedbackEventArgs : EventArgs
{
public EmailFeedbackEventArgs(EmailMessageFeedback _feedback)
{
feedback = _feedback;
}
public EmailMessageFeedback feedback { get; set; }
}
}
Console Application >>
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using OSH_EmailServerLibrary;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
namespace EmailServerSenderSampleConsole
{
class Program
{
static void Main(string[] args)
{
List<EmailMessage> _emailList = _emails.GetAllEmailToSend();
EmailMQServerLibrary.OnFeedbackReceived +=
EmailMQServerLibrary_OnFeedbackReceived; //-- worked
EmailMQServerLibrary.PushToMQ(_emailList);
//EmailMQServerLibrary.OnFeedbackReceived +=
EmailMQServerLibrary_OnFeedbackReceived; -- Not working like this
}
private static void EmailMQServerLibrary_OnFeedbackReceived(object sender, EmailFeedbackEventArgs e)
{
}
}
}
I have google a lot about building CustomRenderer to display custom navigationpage on xamarin form (to display gradient on navigationbar) but did not succeed.
here is my code:
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace BillerApp
{
public class GradientNavigationBar: NavigationPage
{
public GradientNavigationBar(Page page): base(page)
{
}
public GradientNavigationBar() : base()
{
}
public static readonly BindableProperty StartColorProperty = BindableProperty.Create(
nameof(StartColor),
typeof(Color),
typeof(GradientNavigationBar),
Color.Default);
public static readonly BindableProperty EndColorProperty = BindableProperty.Create(
nameof(EndColor),
typeof(Color),
typeof(GradientNavigationBar),
Color.Default);
public Color StartColor {
get { return (Color)GetValue(StartColorProperty); }
set { SetValue(StartColorProperty, value); }
}
public Color EndColor
{
get { return (Color)GetValue(EndColorProperty); }
set { SetValue(EndColorProperty, value); }
}
}
}
and following is the renderer on Xamarin.Droid
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Xamarin.Forms;
using BillerApp;
using Xamarin.Forms.Platform.Android;
using Android.Graphics.Drawables;
using BillerApp.Droid;
using System.ComponentModel;
[assembly: ExportRenderer(typeof(GradientNavigationBar), typeof(GrandientNavigationBarRenderer))]
namespace BillerApp.Droid
{
[Activity(Name = "com.companyname.BillerApp.MainActivity")]
public class GrandientNavigationBarRenderer: Xamarin.Forms.Platform.Android.AppCompat.NavigationPageRenderer
{
//public GrandientNavigationBarRenderer(Context context): base(context){} //can not use this constructor
protected override void OnElementChanged(ElementChangedEventArgs<NavigationPage> e)
{
base.OnElementChanged(e); // I got Invalid Cast Exception if Inherit from NavigationRenderer
if (e.OldElement != null || Element == null)
{
return;
}
var p = this.Element as GradientNavigationBar;
var context = (Activity)this.Context;
var sc = new int[] { p.StartColor.ToAndroid(), p.EndColor.ToAndroid() };
var grad = new GradientDrawable(GradientDrawable.Orientation.TopBottom, sc);
var t = context.ActionBar; // here i got null
t.SetSplitBackgroundDrawable(grad);
context.ActionBar.SetBackgroundDrawable(grad);
}
}
}
this is what i am trying to achieve:
I am using VS 2015 Community edition and have updated SDK tools to date
I would do it simply by adding something like this to your layout folder:
toolbar_gradient.xml
<gradient
android:type="linear"
android:startColor="#F3A183"
android:endColor="#EC6F66"
android:angle="270"/>
</shape>
Then in your Toolbar.xml add this line of code:
android:background="#layout/toolbar_gradient"
I have a ScoreDataModelsController that contains the following Action Method:
public ActionResult Getnames()
{
return View(db.ScoreDataModels.ToList());
}
In Views I have the corresponding ScoreDataModels folder containing Getnames.cshtml:
#model IEnumerable<WebApplication1.Models.ScoreDataModel>
#{
ViewBag.Title = "Get Names";
Layout = "~/Views/Shared/_emptyLayout.cshtml";
}
<table class="table">
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
</tr>
}
</table>
This all works fine. Now I would like to make this data (i.e. Names) accessible as json/XML using REST. I have managed to get the ApiController working with the standard settings and by opening http://.../api/Andi i get the values from the string[] in XML format:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebApplication1.Controllers
{
public class AndiController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2", "und en dritte" };
//Here I need help: ScoreDataModelsController sdm = new ScoreDataModelsController();
// var res = from r in sdm
}
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
// POST api/<controller>
public void Post([FromBody]string value)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
}
Now, instead of "value1, value2 ..." I would like to get the names from my ScoreDataModel / ScoreDataModelsController.
The ScoreDataModel looks like this. I have used this model to create the controller and view by scaffolding in Visual Studio:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace WebApplication1.Models
{
public class ScoreDataModel
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public int Score { get; set; }
}
}
I would very much appreciate if you could lead me into the right direction to get this REST API working with my existing data controller / data model.
Create a central class which holds your data access logic, something like this:
public class DataRepository
{
private DatabaseContext db = new DatabaseContext();
public List<ScoreDataModel> GetNames()
{
return db.ScoreDataModels.ToList();
}
}
Now you can use this class to access your data from both the MVC controller and the api controller:
public class AndiController : ApiController
{
private DataRepository dbRepo = new DataRepository();
public IEnumerable<ScoreDataModel> Get()
{
List<ScoreDataModel> names = dbRepo.GetNames();
return names;
}
}
use this
var data= db.ScoreDataModels.ToList()
List<String>list=new List<String>();
foreach(var r in data)
{
list.add(r.Name);
}
return list;
$ I am able to create Menu Item in administration section
Plugin-->Import Product
however when i click on it, it gives me
error resource cannot be found. Please help on this
matter. I have attached model, view, controller and other related code below.
*************Model*************
namespace Nop.Plugin.Import.Product.Models
{
public class ImportProductModel
{
public string Button1 { get; set; }
}
}
**********Controller*************
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Nop.Admin.Models.Catalog;
using Nop.Core.Domain.Catalog;
using Nop.Core.Infrastructure;
using Nop.Plugin.Import.Product.Models;
using Nop.Services.Catalog;
using ns_5OClock;
namespace Nop.Plugin.Import.Product.Controllers
{
class ImportProductController : Controller
{
//
// GET: /DisplayTime/
public ActionResult Index(ImportProductModel model)
{
if (!String.IsNullOrEmpty(model.Button1))
{
CreateProduct();
}
return View();
}
//
}
}
*************View (ImportProduct.cshtml) **********
#{
Layout = "";
}
#model Nop.Plugin.Import.Product.Models.ImportProductModel
<table>
<tr>
<td>
<button title="Click to Create Products"
style="width:300px;height:60px" name="Button1"></button>
</td>
</tr>
</table>
***************Plugin (ImportProduct) **********************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Nop.Core.Plugins;
using Nop.Web.Framework.Web;
namespace Nop.Plugin.Import.Product
{
public class ImportProduct : BasePlugin, IAdminMenuPlugin
{
public void BuildMenuItem(Telerik.Web.Mvc.UI.MenuItemBuilder menuItemBuilder)
{
menuItemBuilder.Text("Import Product");
//menuItemBuilder.Url("/Plugins/ProductImport/Index");
menuItemBuilder.Route("Plugin.Import.Product.ImportProduct");
}
}
}
**************Route Provider ****************
using System.Web.Mvc;
using System.Web.Routing;
using Nop.Web.Framework.Mvc.Routes;
namespace Nop.Plugin.Import.Product
{
public partial class RouteProvider : IRouteProvider
{
public void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute("Plugin.Import.Product.ImportProduct",
"Plugins/Import/ImportProduct",
new { controller = "Import", action = "ImportProduct" },
new[] { "Nop.Plugin.Import.Product.Controllers" }
);
}
public int Priority
{
get
{
return 0;
}
}
}
}
Please check in your route register
routes.MapRoute("Plugin.Import.Product.ImportProduct",
"Plugins/Import/ImportProduct",
new { controller = "ImportProduct", action = "Index" },
new[] { "Nop.Plugin.Import.Product.Controllers" }
);