'Firma.Angajare' does not contain a definition for - c#

I am trying to make a project in visual studio 2013 and i have a problem with my code.
This is my code:
namespace Firma
{
public partial class Angajare : System.Web.UI.Page
{
private bool isEdit = false;
private int id = 0;
protected void Page_Load(object sender, EventArgs e)
{
FirmeContext db = new FirmeContext();
Angajare editedAngajare = new Angajare();
if (Request.QueryString.Count == 1 && Request["id"] != null)
{
isEdit = true;
id = Convert.ToInt32(Request["id"]);
editedAngajare = db.Angajari.SingleOrDefault<Angajare>(a => a.IDAngajare == id);
if (editedAngajare != null && !IsPostBack)
txtExperienta.Text = editedAngajare.Experienta.ToString();
}
else
isEdit = false;
{
if (!IsPostBack)
{
PostList.DataSource = db.Posturi.ToList();
PostList.DataTextField = "Denumire";
PostList.DataValueField = "ID";
PostList.DataBind();
AngajatList.DataSource = db.Angajati.ToList();
AngajatList.DataTextField = "Nume";
AngajatList.DataValueField = "ID";
AngajatList.DataBind();
}
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
FirmeContext db = new FirmeContext();
Angajare editedAngajare;
try
{
if (isEdit)
{
editedAngajare = db.Angajari.SingleOrDefault<Angajare>(d => d.IDAngajare == id);
if (editedAngajare != null)
{
editedAngajare.Experienta = int.Parse(txtExperienta.Text);
editedAngajare.Angajat = db.Angajati.SingleOrDefault<Angajat>(n => n.ID == int.Parse(AngajatList.SelectedValue));
editedAngajare.Post = db.Posturi.SingleOrDefault<Post>(p => p.IDPost == int.Parse(PostList.SelectedValue));
db.Entry(editedAngajare).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
litMsg.Text = "Record updated!";
}
}
else
{
Angajare newan = new Angajare();
newan.Experienta = int.Parse(txtExperienta.Text);
int idAngajat=int.Parse(AngajatList.SelectedValue);
newan.Angajat = db.Angajati.SingleOrDefault<Angajat>(n => n.ID == idAngajat);
int idPost = int.Parse(PostList.SelectedValue);
newan.Post = db.Posturi.SingleOrDefault<Post>(p => p.IDPost == idPost);
db.Angajari.Add(newan);
db.Entry(newan).State = System.Data.Entity.EntityState.Added;
db.SaveChanges();
litMsg.Text = "New Record Added!";
}
}
catch (Exception ex)
{
litMsg.Text = "Error: " + ex.Message;
}
}
protected void btnCancel_Click(object sender, EventArgs e)
{
Server.Transfer("Default.aspx");
}
}
}
i have a lot of errors. for example, in this line
editedAngajare = db.Angajari.SingleOrDefault<Angajare>(d => d.IDAngajare == id);
It says :
"Error 10 'Firma.Angajare' does not contain a definition for 'IDAngajare' and no extension method 'IDAngajare' accepting a first argument of type 'Firma.Angajare' could be found (are you missing a using directive or an assembly reference?)"
The same thing for Experienta, Angajat, Post
editedAngajare.Experienta = int.Parse(txtExperienta.Text);
editedAngajare.Angajat = db.Angajati.SingleOrDefault<Angajat>(n => n.ID == int.Parse(AngajatList.SelectedValue));
editedAngajare.Post = db.Posturi.SingleOrDefault<Post>(p => p.IDPost == int.Parse(PostList.SelectedValue));
db.Entry(editedAngajare).State = System.Data.Entity.EntityState.Modified;
I will also show you my database:
public class Angajare
{
[Key]
public int IDAngajare { get; set; }
public int Experienta { get; set; }
public virtual Post Post { get; set; }
public virtual Angajat Angajat { get; set; }
}
public class Angajat
{
[Key]
public int ID { get; set; }
public string Nume { get; set; }
public string Prenume { get; set; }
public DateTime DataAngajare { get; set; }
public virtual ICollection<Angajare> Angajari { get; set; }
}
public class Post
{
[Key]
public int IDPost { get; set; }
public string Denumire { get; set; }
public int ExperientaNecesara { get; set; }
public virtual ICollection<Angajare> Angajari { get; set; }
}
Please help me because i have no idea what is going wrong.
Thanks in advice.

It seems that you have two classes Angajare. One a Web.UI.Page and one in your database model. Try to specify namespace in your linq query.

Related

Error on Edit Object in entityframework An entity object cannot be referenced by multiple instances of Entity ChangeTracker

I get an error when I call this text in my project. An entity object cannot be referenced by multiple instances of Entity Change Tracker.
public static short Udf_Edit_Invoice(tblInvoice inv)
{
using (DbContextModel db = new DbContextModel())
{
using (DbContextTransaction transaction = db.Database.BeginTransaction())
{
try
{
if (db.Entry<tblInvoice>(inv).State == EntityState.Detached)
{
db.Set<tblInvoice>().Attach(inv);
}
db.Entry<tblInvoice>(inv).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
transaction.Commit();
return 1;
}
catch(Exception ee)
{
transaction.Rollback();
return 0;
}
}
}
}
Click Event: (And you can see the click event as follows, which was called inside a form and the information of the main class and the child class is poured into it, and then the editing command is called, which I encounter an error.)
tblInvoice invtPub = new tblInvoice();
private void Btn_Save_Click(object sender, EventArgs e)
{
if (TxtTax.Text == "")
{
TxtTax.Text = "0";
}
Decimal Dec_TotalPrice = 0;
Decimal Dec_TotalTakhfif = 0;
Entities.Entity.tblInvoiceDetail invdObj;
List<Entities.Entity.tblInvoiceDetail> invd = new List<Entities.Entity.tblInvoiceDetail>();
foreach (DataRow Row in FactDt.Rows)
{
invdObj = new Entities.Entity.tblInvoiceDetail();
Dec_TotalPrice += Decimal.Parse(Row["FoodTotalPrice"].ToString());
Dec_TotalTakhfif += Decimal.Parse(Row["FoodDiscount"].ToString());
invdObj.AssetID = int.Parse(Row["FoodID"].ToString());
invdObj.AssetQuantity = Double.Parse(Row["FoodQuantity"].ToString());
invdObj.Discount = Double.Parse(Row["FoodDiscount"].ToString());
invdObj.UnitPrice = Double.Parse(Row["FoodUnitPrice"].ToString());
invdObj.InvoiceID = 0;
invdObj.TotalPrice = Double.Parse(Row["FoodTotalPrice"].ToString());
invd.Add(invdObj);
}
invtPub.CreatorUserID = BLL.Class_GlobalVars.ThisPUserID;
invtPub.CustomerID = long.Parse(Txt_CustomerCode.Text.Trim());
invtPub.DateOfFactor = DateTime.Now;
invtPub.InvoiceTitleID = 0;
invtPub.IsCanceled = false;
invtPub.PayCardOfInvoice = Decimal.Parse(Txt_Card.Text.Trim());
invtPub.PayCashOfInvoice = Decimal.Parse(Txt_Cach.Text.Trim());
invtPub.PayCredOfInvoice = (Decimal.Parse(Txt_Debit.Text.Trim()) < 0 ? Decimal.Parse(Txt_Debit.Text.Trim()) : 0);
invtPub.PayDebtOfInvoice = (Decimal.Parse(Txt_Debit.Text.Trim()) >= 0 ? Decimal.Parse(Txt_Debit.Text.Trim()) : 0);
invtPub.ShamsiDateOfFactor = ShamsiTools.Class_SHamsiTools.UDF_MiladiDateToShmasi(DateTime.Now);
invtPub.StrDescription = Txt_Description.Text.Trim();
invtPub.TaxOfInvoice = Decimal.Parse(TxtTax.Text.Trim());
invtPub.TotalPriceOfFactor = Dec_TotalPrice;
invtPub.TotalPriceOfFactorWithTax = (Decimal.Parse(TxtTax.Text) + Dec_TotalPrice);
invtPub.tblInvoiceDetail = invd;
if (Entities.Classes.Class_tblInvoice.Udf_Edit_Invoice(invtPub) == 1)
{
Lbl_Total_Aglam.Text = "0";
Lbl_Total_Price.Text = "0";
Lbl_Total_Takhfif.Text = "0";
GrPr_Mohasebeh.Enabled = false;
Grpr_Custumer.Enabled = true;
Grpr_Factor.Enabled = true;
FactDt.Rows.Clear();
for (int i = FactDt.Rows.Count - 1; i >= 0; i--)
{
DataRow dr = FactDt.Rows[i];
{
dr.Delete();
}
}
Grd_Factor.DataSource = FactDt;
MessageBox.Show("Edited . . . . . .");
UDF_TXTFactorClear();
UDF_TXTCustomerClear();
}
else
{
}
}
and total error message:
An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
"EntityFramework"
at System.Data.Entity.Core.Objects.ObjectContext.VerifyContextForAddOrAttach(IEntityWrapper wrappedEntity)
at System.Data.Entity.Core.Objects.ObjectContext.AttachSingleObject(IEntityWrapper wrappedEntity, EntitySet entitySet)
at System.Data.Entity.Core.Objects.ObjectContext.AttachTo(String entitySetName, Object entity)
at System.Data.Entity.Internal.Linq.InternalSet`1.<>c__DisplayClassa.<Attach>b__9()
at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Attach(Object entity)
at System.Data.Entity.Internal.InternalEntityEntry.set_State(EntityState value)
at System.Data.Entity.Infrastructure.DbEntityEntry`1.set_State(EntityState value)
at Entities.Classes.Class_tblInvoice.Udf_Edit_Invoice(tblInvoice inv) in E:\Programming\P1\ADVD9\TarkeEtiad\SourceCodeEF\Entities\Classes\Class_tblInvoice.cs:line 77
This: tblInvoice invtPub = new tblInvoice();
[Table("tblInvoice")]
public partial class tblInvoice
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public tblInvoice()
{
tblInvoiceDetail = new HashSet<tblInvoiceDetail>();
}
[Key]
public long InvoiceTitleID { get; set; }
[Required]
public Boolean IsCanceled { get; set; }
[Required]
public int CreatorUserID { get; set; }
[Required]
public long CustomerID { get; set; }
public DateTime DateOfFactor { get; set; }
[Required]
[StringLength(10)]
public string ShamsiDateOfFactor { get; set; }
public decimal? TotalPriceOfFactor { get; set; }
public decimal TaxOfInvoice { get; set; }
public decimal TotalPriceOfFactorWithTax { get; set; }
public decimal PayCashOfInvoice { get; set; } //نقدی
public decimal PayCardOfInvoice { get; set; } //کارتخوان
public decimal PayDebtOfInvoice { get; set; } //بدهی
public decimal PayCredOfInvoice { get; set; } //طلب
[MaxLength(1500)]
public String StrDescription { get; set; }
public virtual tblCustomers tblCustomers { get; set; }
public virtual tblPUsers tblPUsers { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<tblInvoiceDetail> tblInvoiceDetail { get; set; }
}
Don't use any transactions since you only need to add one record.
try this
using (DbContextModel db = new DbContextModel())
{
try
{
var existedInvoice= db.Set<tblInvoice>().FirstOrDefault(i=> i.InvoiceTitleID = inv.InvoiceTitleID );
if (existedInvoice!=null)
{
db.Entry(existedInvoice).CurrentValues.SetValues(inv);
db.SaveChanges();
return 1;
} else return 0;
}
catch(Exception ee)
{
return 0;
}
}

Unable to fetch data from Azure Cosmos DB

I am having the below model class CallbackResponse.cs :
public class CallbackResponse
{
public Callback Data { get; set; }
}
public class Callback
{
public IEnumerable<ReviewInProgressActivityFeed> ActivitiesFeed { get; set; }
}
public class ReviewInProgressActivityFeed
{
public ReviewInProgressStatus ReviewerSession { get; set; }
}
public class ReviewInProgressStatus
{
public Guid ReviewActivityId { get; set; }
public string ReviewerName { get; set; }
public string ReviewComments { get; set; }
public DateTime ActivityDateTime { get; set; }
}
Sample Payload:
{
"data":
{
"activitiesFeed": [
{
"reviewerSession":
{
"reviewActivityId": "dd9937c3-7c01-4a4a-bc8d-05ef37b07ee5",
"ReviewerName": "Verification Team",
"reviewComments": "upload business verification document for further verification.",
"activityDateTime": "2021-03-31T18:34:26.5978962Z"
},
},
{
"reviewerSession":
{
"reviewActivityId": "dd9937c3-7c01-4a4a-bc8d-05ef37b07ee5",
"ReviewerName": "Other Team",
"reviewComments": "other documents required for verification.",
"activityDateTime": "2021-03-31T19:34:26.5978962Z"
},
}
]
}
}
I am trying to get the data from DB via the CallbackResponse model class. Please find the code for below.
public async Task<CallbackResponse> CallbackActivityFeedAsync(Guid Id)
{
CallbackResponse containerItems = new CallbackResponse();
IQueryable<HumanReviewRequest> query = cosmosReviewRequestContainer.GetItemLinqQueryable<HumanReviewRequest>(true);
query = query.Where(x => x.id == Id);
FeedIterator<HumanReviewRequest> feedIterator = query.ToFeedIterator();
while (feedIterator.HasMoreResults)
{
FeedResponse<HumanReviewRequest> r = await feedIterator.ReadNextAsync().ConfigureAwait(false);
foreach (HumanReviewRequest requestModel in r)
{
containerItems = new CallbackResponse
{
Data = new Callback
{
ActivitiesFeed = new List<ReviewInProgressActivityFeed>
{
new ReviewInProgressActivityFeed
{
ReviewerSession = new ReviewInProgressStatus
{
ReviewActivityId = requestModel.ReviewActivities.Select(x => x.ReviewerSession.ReviewActivityId).LastOrDefault(),
ActivityDateTime = requestModel.ReviewActivities.Select(x => x.ReviewerSession.ActivityDateTime).LastOrDefault(),
ReviewComments = requestModel.ReviewActivities.Select(x => x.ReviewerSession.ReviewerComments).LastOrDefault(),
ReviewerName = requestModel.ReviewActivities.Select(x => x.ReviewerSession.ReviewerName).LastOrDefault()
}
}
}
}
};
}
}
return containerItems;
}
The Problem here is I could not able to fetch all the records present in activitiesFeed array in DB. Instead I could only able to fetch the last record in that array(I am using Azure Cosmos DB). Please help me in this.
HumanReviewRequest.cs (which is DB Class)for reference:
public class HumanReviewRequest
{
public Guid Id { get; set; }
public IEnumerable<ReviewActivity> ReviewActivities { get; set; }
public class ReviewActivity
{
public ReviewerSession ReviewerSession { get; set; }
public string UserComments { get; set; }
}
public class ReviewerSession
{
public Guid ReviewActivityId { get; set; }
public Guid ReviewerUserId { get; set; }
public DateTime ActivityDateTime { get; set; }
public string ReviewerComments { get; set; }
}
This is because you are creating a new List<ReviewInProgressActivityFeed>, a new ReviewInProgressActivityFeed and reading only the last element in activitiesFeed for each iteration:
ReviewerSession = new ReviewInProgressStatus
{
ReviewActivityId = requestModel.ReviewActivities.Select(x => x.ReviewerSession.ReviewActivityId).LastOrDefault(),
ActivityDateTime = requestModel.ReviewActivities.Select(x => x.ReviewerSession.ActivityDateTime).LastOrDefault(),
ReviewComments = requestModel.ReviewActivities.Select(x => x.ReviewerSession.ReviewerComments).LastOrDefault(),
ReviewerName = requestModel.ReviewActivities.Select(x => x.ReviewerSession.ReviewerName).LastOrDefault()
}
Try below code instead of the above code:
public async Task<CallbackResponse> CallbackActivityFeedAsync(Guid Id)
{
CallbackResponse containerItems = new CallbackResponse();
containerItems.Data = new Callback();
containerItems.Data.ActivitiesFeed = new List<ReviewInProgressActivityFeed>();
IQueryable<HumanReviewRequest> query = cosmosReviewRequestContainer.GetItemLinqQueryable<HumanReviewRequest>(true);
query = query.Where(x => x.id == Id);
FeedIterator<HumanReviewRequest> feedIterator = query.ToFeedIterator();
while (feedIterator.HasMoreResults)
{
FeedResponse<HumanReviewRequest> r = await feedIterator.ReadNextAsync().ConfigureAwait(false);
if (r != null || r.ReviewActivities != null)
{
foreach (HumanReviewRequest requestModel in r.ReviewActivities)
{
containerItems.Data.ActivitiesFeed.Add(
new ReviewInProgressActivityFeed
{
ReviewerSession = new ReviewInProgressStatus
{
ReviewActivityId = requestModel.ReviewerSession.ReviewActivityId,
ActivityDateTime = requestModel.ReviewerSession.ActivityDateTime,
ReviewComments = requestModel.ReviewerSession.ReviewerComments,
ReviewerName = requestModel.ReviewerSession.ReviewerName
}
});
}
}
}
};
}
}
return containerItems;
}

Can not implicitly convert type 'WindowsFormsApp2.tbl_user' to 'WindowsFormsApp2.BLL.User'

I am trying to create a logIn Form using c# and LINQ to SQL. When I try to verify the entred login with the database data :
private void LogIn_Click(object sender, EventArgs e)
{
User u = d.tbl_user.Where(c => c.username == username.Text && c.pwd == password.Text ).Single();
}
it returns me this Error :
Can not implicitly convert type 'WindowsFormsApp2.tbl_user' to 'WindowsFormsApp2.BLL.User'
Edit : Also I tried to Add data to database but it returns the same Error :
private void ajouter_Click(object sender, EventArgs e)
{
ArticleBLL a = new ArticleBLL()
{
Designiation = des.Text,
Quantite_stock = Convert.ToInt32(quantite.Text),
Magasin = dbContext.tbl_magazin.Where(c => c.libelle == magazin.Text).Select(c => c.id).Single(),
Nature = nature.Text,
Categorie = dbContext.tbl_categorie.Where(c => c.libelle == categorie.Text).Select(c => c.id).Single(),
Date_arrive = DateTime.Parse(date.Text),
Ajoute_par = 1
};
dbContext.tbl_article.InsertOnSubmit(a);
dbContext.SubmitChanges();
}
It gives me a red line under : dbContext.tbl_article.InsertOnSubmit(a); saying that :
Impossible to convert type dbContext.tbl_article.InsertOnSubmit(a);
Heeelp !! I dont know where is the problem .
* Here my ArticleBll.cs :
class ArticleBLL
{
public int Code_article { get; set; }
public string Designiation { get; set; }
public int Quantite_stock { get; set; }
public int Magasin { get; set; }
public string Nature { get; set; }
public decimal Prix { get; set; }
public int Categorie { get; set; }
public DateTime Date_arrive { get; set; }
public int Ajoute_par { get; set; }
}
*Here is my tbl_article : *
my table article image
Hi I think you should try below code:
var u = d.tbl_user.FirstOrDefault(c => c.username == username.Text && c.pwd == password.Text);
And compare why it's not matching with your User class after you can typecast u with user.

Merging C# code in Xamarin Android

I got the code of detecting poor grammar from here - Detecting Poor grammar
I am new to C# and Xamarin. I want to merge this code into my speech to text conversion app.
I tried to do it, but I am not getting the desired results.
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Widget;
using Android.OS;
using Android.Speech;
using Android.Util;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net;
namespace SpeechToText
{
[Activity(Label = "SpeechToText", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity, IRecognitionListener
{
public const string Tag = "VoiceRec";
SpeechRecognizer Recognizer { get; set; }
Intent SpeechIntent { get; set; }
TextView Label { get; set; }
TextView Label1 { get; set; }
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
Recognizer = SpeechRecognizer.CreateSpeechRecognizer(this);
Recognizer.SetRecognitionListener(this);
SpeechIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech);
SpeechIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm);
SpeechIntent.PutExtra(RecognizerIntent.ExtraCallingPackage, PackageName);
var button = FindViewById<Button>(Resource.Id.btn);
button.Click += ButtonClick;
var Grammarbutton = FindViewById<Button>(Resource.Id.btn1);
Grammarbutton.Click += new EventHandler(ButtonClick2);
Label = FindViewById<TextView>(Resource.Id.tv);
Label1 = FindViewById<TextView>(Resource.Id.tv1);
}
private void ButtonClick(object sender, EventArgs e)
{
Recognizer.StartListening(SpeechIntent);
}
public void OnResults(Bundle results)
{
var matches = results.GetStringArrayList(SpeechRecognizer.ResultsRecognition);
if (matches != null && matches.Count > 0)
{
Label.Text = matches[0];
}
}
private void ButtonClick2(object sender, EventArgs e)
{
var api = new GingerItApi();
for (; ; )
{
Console.Write("Text to check: ");
var text = Label.Text;
if (string.IsNullOrEmpty(text)) break;
try
{
var result = api.Check(text);
if (result?.Corrections?.Count != 0)
{
for (int i = 0; i < result.Corrections.Count; i++)
{
var item = result.Corrections[i];
var mistakes = string.Join(", ", item.Mistakes.Select(x => $"\"{text.Substring(x.From, x.To - x.From + 1)}\""));
var suggestions = string.Join(", ", item.Suggestions.Select(x => $"\"{x.Text}\""));
Label1.Text = $" {i + 1}: {mistakes} >> {suggestions}";
}
}
else
{
Console.WriteLine("Looks okay.\n");
}
}
catch (Exception ex)
{
Console.WriteLine($"**Error: {ex.Message}\n");
}
}
}
public void OnReadyForSpeech(Bundle #params)
{
Log.Debug(Tag, "OnReadyForSpeech");
}
public void OnBeginningOfSpeech()
{
Log.Debug(Tag, "OnBeginningOfSpeech");
}
public void OnEndOfSpeech()
{
Log.Debug(Tag, "OnEndOfSpeech");
}
public void OnError([GeneratedEnum] SpeechRecognizerError error)
{
Log.Debug("OnError", error.ToString());
}
public void OnBufferReceived(byte[] buffer) { }
public void OnEvent(int eventType, Bundle #params) { }
public void OnPartialResults(Bundle partialResults) { }
public void OnRmsChanged(float rmsdB) { }
}
}
class GingerItApi
{
public CheckResult Check(string text)
{
var request = WebRequest.Create($"https://services.gingersoftware.com/Ginger/correct/jsonSecured/GingerTheTextFull?callback=jQuery172015406464511272344_1490987331365&apiKey=GingerWebSite&lang=US&clientVersion=2.0&text={text}&_=1490987518060") as HttpWebRequest;
WebResponse response = null;
try
{
response = request.GetResponse();
if (response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
string data = reader.ReadToEnd();
var first = data.IndexOf('{');
var last = data.LastIndexOf('}');
var json = data.Substring(first, last - first + 1);
return JsonConvert.DeserializeObject<CheckResult>(json);
}
}
}
catch (Exception)
{
throw;
}
return null;
}
}
public class LrnFrgOrigIndx
{
[JsonProperty("From")]
public int From { get; set; }
[JsonProperty("To")]
public int To { get; set; }
}
public class Mistake
{
[JsonProperty("Definition")]
public string Definition { get; set; }
[JsonProperty("CanAddToDict")]
public bool CanAddToDict { get; set; }
[JsonProperty("From")]
public int From { get; set; }
[JsonProperty("To")]
public int To { get; set; }
}
public class Suggestion
{
[JsonProperty("Definition")]
public string Definition { get; set; }
[JsonProperty("LrnCatId")]
public int LrnCatId { get; set; }
[JsonProperty("Text")]
public string Text { get; set; }
}
public class Correction
{
[JsonProperty("Confidence")]
public int Confidence { get; set; }
[JsonProperty("From")]
public int From { get; set; }
[JsonProperty("LrnFrg")]
public string LrnFrg { get; set; }
[JsonProperty("LrnFrgOrigIndxs")]
public IList<LrnFrgOrigIndx> LrnFrgOrigIndxs { get; set; }
[JsonProperty("Mistakes")]
public IList<Mistake> Mistakes { get; set; }
[JsonProperty("ShouldReplace")]
public bool ShouldReplace { get; set; }
[JsonProperty("Suggestions")]
public IList<Suggestion> Suggestions { get; set; }
[JsonProperty("To")]
public int To { get; set; }
[JsonProperty("TopLrnCatId")]
public int TopLrnCatId { get; set; }
[JsonProperty("Type")]
public int Type { get; set; }
[JsonProperty("UXFrgFrom")]
public int UXFrgFrom { get; set; }
[JsonProperty("UXFrgTo")]
public int UXFrgTo { get; set; }
}
public class Sentence
{
[JsonProperty("FromIndex")]
public int FromIndex { get; set; }
[JsonProperty("IsEnglish")]
public bool IsEnglish { get; set; }
[JsonProperty("ToIndex")]
public int ToIndex { get; set; }
}
public class CheckResult
{
[JsonProperty("Corrections")]
public IList<Correction> Corrections { get; set; }
[JsonProperty("Sentences")]
public IList<Sentence> Sentences { get; set; }
}
I want to get the recognized speech, send it to grammar corrector, and display the output.
Please help me to solve this, or at least help me to further research the problem.
Thank you.
You have put an infinite loop in your code. Please remove it.
For example:
private void ButtonClick2(object sender, EventArgs e)
{
var api = new GingerItApi();
Console.Write("Text to check: ");
var text = Label.Text;
if (!string.IsNullOrEmpty(text))
{
try
{
var result = api.Check(text);
if (result?.Corrections?.Count != 0)
{
for (int i = 0; i < result.Corrections.Count; i++)
{
var item = result.Corrections[i];
var mistakes = string.Join(", ", item.Mistakes.Select(x => $"\"{text.Substring(x.From, x.To - x.From + 1)}\""));
var suggestions = string.Join(", ", item.Suggestions.Select(x => $"\"{x.Text}\""));
Label1.Text = $" {i + 1}: {mistakes} >> {suggestions}";
}
}
else
{
Label1.Text = "Looks okay.\n";
Console.WriteLine("Looks okay.\n");
}
}
catch (Exception ex)
{
Console.WriteLine($"**Error: {ex.Message}\n");
}
}
}
And the result is:

Binding combobox BindingList Winforms C#

Ok, so I have been facing this issue several times now but I always seemed to figure it out.
This time, ive been stuck and ive tried multiple things, but nothing is working.
I have a combobox of customers in a customer form. When i create a new customer, my combobox is not updating. It only refreshes when closing and re-opening the form.
I am aware of the "ugly and quick" solutions, but I don't want to use this unless I have no other choise. So ive been using BindingLists because of the events... BUT this is not working in my case.
Ive been staring to this for a time now, let it aside, tried again, but keep on failing.
Does anyone know whats missing in this puzzle?
Now the code: Presenter
public class CustomerPresenter
{
private tbl_customer customer = new tbl_customer();
private CustomerView customerView = new CustomerView();
public CustomerPresenter(tbl_customer customer, CustomerView customerView)
{
this.customer = customer;
this.customerView = customerView;
customerView.customerPresenter = this;
}
// Get a list of customers
public List<tbl_customer> customerList;
public BindingList<tbl_customer> getCustomers()
{
using (var customers = new DBCrownfishEntities())
{
var customer = from c in customers.tbl_customer
where c.IsDeleted == false
select c;
this.customerList = customer.ToList();
var listBinding = new BindingList<tbl_customer>(this.customerList);
return listBinding;
}
}
public void testAdd()
{
tbl_customer customer = new tbl_customer();
customer.CustomerPrefix = "Pref";
customer.CustomerName = "Name";
customer.CustomerAddress = "Address";
customer.CustomerPostalCode = "1111";
customer.CustomerCity = "City";
customer.CustomerCountry = "Country";
customer.CustomerCountryCode = "BE";
customer.CustomerVat = "123456789";
customer.hasVatNumber = true;
try
{
using (var cust = new DBCrownfishEntities())
{
cust.tbl_customer.Add(customer);
cust.SaveChanges();
MessageBox.Show("A new customer is succesfully added!");
}
}
catch (EntityException exception)
{
MessageBox.Show(exception.InnerException.Message.ToString(), "Error Connecting database");
}
catch (Exception)
{
throw;
}
}
}
View:
BindingSource bsCustomers = new BindingSource();
private void CustomerView_Load(object sender, EventArgs e)
{
bsCustomers.DataSource = customerPresenter.getCustomers();
cbCustomers.DataSource = bsCustomers;
cbCustomers.DisplayMember = "CustomerName";
cbCustomers.ValueMember = "CustomerId";
radioButton1_CheckedChanged(null, null);
}
private void button1_Click_1(object sender, EventArgs e)
{
customerPresenter.testAdd();
}
Model:
public partial class tbl_customer
{
public tbl_customer()
{
this.tbl_invoices = new HashSet<tbl_invoices>();
}
public int CustomerID { get; set; }
public string CustomerPrefix { get; set; }
public string CustomerName { get; set; }
public string CustomerEmailaddress { get; set; }
public string CustomerAddress { get; set; }
public string CustomerPostalCode { get; set; }
public string CustomerCity { get; set; }
public string CustomerVat { get; set; }
public string CustomerCountryCode { get; set; }
public string CustomerCountry { get; set; }
public bool IsDeleted { get; set; }
public bool hasVatNumber { get; set; }
public virtual ICollection<tbl_invoices> tbl_invoices { get; set; }
}

Categories

Resources