c# mvc multi language support - c#

I am developing a multi-language site with c#. In my database, my columns continue as en_Title, en_Content. I have a function to get the news, I am sending the active language as a parameter to this function.
Function
public static List<Haberler> GetHaber(string lang)
{
using (BIRLIKB2BEntities db = new BIRLIKB2BEntities())
{
var Haber = db.Database.SqlQuery<Haberler>($"SELECT ID, {lang}_Baslik, {lang}_KisaAciklama, {lang}_Icerik FROM Haberler").ToList();
return Haber;
}
}
I want to pull only the language columns according to the language code that comes here. But I guess entity framework is giving error
Error:
The data reader is incompatible with the specified 'BIRLIKB2BModel.Haberler'. A member of the type, 'Baslik', does not have a corresponding column in the data reader with the same name.
The result of these processes is the output I expected. just reading the columns I send in the function. Is there an alternative way to solve this? can you help?
Table
ID|tr_Baslik|tr_Aciklama|tr_Icerik|en_Baslik|en_Aciklama|en_Icerik
1 | Turkey | Turkey | Turkey |English |English |English|

Related

Net Core 3: Dynamic Model Validation at API runtime

We have 1000 small lookup table editor in database. Each having few rows maximum. Instead of writing 1000 Apis, services, angular proxies we created an Object lookup viewer/editor in grid cell. Small Tables like ProductCodeLookup, AddressType, SupplyCategory, FurnitureType
Also there is API Operator from a webpage, where people can See and Add Rows to the lookup Tables. (see picture link below)
The question came up, how do we dynamically apply Model Validation on the Request Object in API?
Front end validation is on Angular
However, for C#, we want all LookupIds and int category to be 1-100 max. String request members to be 255 characters max. Emails to be in #email regex format etc. We may not know what Object request looks like at runtime, until table is selected.
[HttpPost("[Action]")]
public void AddObject(List<object> addListRequest, string lookupTableName)
{
foreach (var addItem in addListRequest)
{
var addItemCast = addItem.ConvertObjectToTypeWithSerialization(atype);
context.Add(addItemCast);
}
}
This answer for older Net MVC, we are using Net Core 3 API. Dynamically apply validation rules at runtime with ASP.NET MVC 4
Thought there is method to conduct this with new library.
EditorImage

Fill existing SQLite database with data from JSON (or other easily-readable text format) in C#

My database is divided into two parts: language-independent part and localizable part (containing Unicode text strings). For our translation staff it's much more easier to work not with some DB viewing tool but with some text format like JSON (via some tool of course). So I'm looking for a best way to load JSON data into my SQLite database. For now I use the foolowing approach (assume that I already have empty SQLite database):
I deserealise JSON data into C# classes (via Newtonsoft.JSON.dll).
For each of them I manually create INSERT command with paremeters (via System.Data.SQLite.dll) and then fill that parameters with class fields' values
I execute that command.
Is that correct (easiest, reliable) aproach to fill SQLite database with JSON data? Maybe I've missed some useful API?
Any other easily-readable text format (with Unicode support!) which is better to work with in term of C# and SQLite is welcomed.
Try Sqlite.NET, a basic Sqlite client and ORM: https://github.com/praeclarum/sqlite-net
From their wiki:
Once you have defined your entity, you can automatically generate
tables in your database by calling CreateTable:
var db = new SQLiteConnection("foofoo");
db.CreateTable<Stock>();
db.CreateTable<Valuation>();
You can insert rows in the database using Insert. If the table
contains an auto-incremented primary key, then the value for that key
will be available to you after the insert:
public static void AddStock(SQLiteConnection db, string symbol) {
var s = db.Insert(new Stock() {
Symbol = symbol
});
Console.WriteLine("{0} == {1}", s.Symbol, s.Id);
}
Similar methods exist for Update and Delete.
You would get something like this:
AddStock(string jsonString){
var stock = JsonConvert.DeserializeObject<Stock>(jsonString);
db.Insert(stock);
}

Need help with creating a form for a multi-language structure in ASP.NET MVC

I have two tables in my database. The first one is holding category ID's and the second one category names. The reason of holding its values and ids apart is because the website will be multi-language. For example:
tableCategory - id | stringID | dateOfCreation
tableString - id | stringID | value | languageID
// these two tables are connected with their stringIDs,
// so the categories in the tableCategory can have different names
// according to the user's language
Okay, now, I am using LINQ TO SQL and I want to create a form for an admin to insert new category names. For example:
English | Italiano | Français
entertainment | divertimento | divertissement
// where language names are column names and the values are within a textbox
So, how can I accomplish this task by using Html.TextBox or Html.TextBoxFor helpers? Please provide me a good example with describing also the process in the controller and model. I appreciate your help to a newbie in MVC :)
read the blog-link that aligray has posted you, it helped me fixing similar problems :-)

C# Enum using values in Sql Server table

At the moment I have a SQL Server 2005 table that looks a bit like:
ID | name | desc
----------------------
1 | ONE | Value One
3 | THREE | Value Three
5 | FIVE | Value Five
This table corresponds with an enum in C# that looks like:
enum MsgTypes{
<summary>Value One</summary>
ONE = 1,
<summary>Value Three</summary>
THREE = 3,
<summary>Value Five</summary>
FIVE = 5
}
So my question is this: Is there a good way to associate the enum to the SQL table so that any changes/additions to the values in the table don't need to be manually made in the c# code?
If you want it to be somewhat dynamic, why make it an enum to start with? Just fetch the details from the table on app startup, and remember them in (say) a Dictionary<int, string>. You could always encapsulate the value within your own value type which enforced the range, if you wanted to.
Alternatively, if you don't mind recompiling, you could fetch it at build time and autogenerate the enum source code.
I had to have a think about something similar recently (refactoring an enum) -- basically I considered using a Dictionary<A, B> to store the enum values in. You could dynamically load from the table to populate the dictionary if you wanted to.
One thing I'd add -- is if you're replacing an enum that already exists with something dynamic you'll have to think about what you're going to do with exceptions raised as part of populating it dynamically.
To me it depends on how often the enums/DB lookup tables change. We have about a half dozen enum/lookups like this in our system, and i don't mind recompiling to add an emum option + DB row becuase:
It doesn't happen very often - probably twice in the past year that i can think of
There is usually new business logic surrounding the new option so coding is necessary anyway.
Another alternative would to implement a custom object with ID, Name, and Desc properties that would encapsulate the database table.
I accept with what Jon is suggesting, but then if you prefer to have your Enum list in the DB and want to use them in your code, you could use TypeTable feature from nHydrate for your project.

How do I get this DataSet to add my new rows and update correctly?

I'm new to C# and .NET in general, coming from a FLOSS background (mostly PHP, Python and Ruby). I have used the Data Source configuration wizard to connect to an MDB file (unfortunately need to do this, as the app this is being used with was written over 5 years ago, and is currently a VB6 app connecting to an Access database). The wizard created a DataSet class JobDataSet with the following DataTables in it (among others):ItemType, Item. ItemRevision
In the MDB, these map to the following tables:
ItemRevisions (
ID: AutoNumber PK,
JobNo: Text,
ItemTypeID: Number,
ItemNo: Number,
RevisedAt: Date/Time,
RevisedBy: Text,
ItemID: Number
)
Items (
ID: AutoNumber PK,
JobNo: Text,
ItemTypeID: Number,
ItemNo: Number
)
ItemTypes: (
ID: AutoNumber PK,
Type: Text
)
Anyway, the following is the code for the method that doesn't work:
private void AddJobItem()
{
itemTypesBindingSource.EndEdit();
JobDataSet.ItemsRow itemsRow = jobDataSet.Items.NewItemsRow();
itemsRow.ItemTypeID = long.Parse(comboBoxItemType.SelectedValue.ToString());
itemsRow.JobNo = JobNo;
itemsRow.ItemNo = (long)numericUpDownItemNo.Value;
jobDataSet.Items.Rows.Add(itemsRow);
jobDataSet.Items.AcceptChanges();
itemsTableAdapter.Update(jobDataSet.Items);
JobDataSet.ItemRevisionsRow itemRevisionsRow = jobDataSet.ItemRevisions.NewItemRevisionsRow();
itemRevisionsRow.ItemTypeID = long.Parse(comboBoxItemType.SelectedValue.ToString());
itemRevisionsRow.JobNo = JobNo;
itemRevisionsRow.ItemNo = (int)numericUpDownItemNo.Value;
itemRevisionsRow.RevisedAt = System.DateTime.Now;
itemRevisionsRow.RevisedBy = Program.AuthForm.Username;
itemRevisionsRow.ItemID = itemsRow.ID;
jobDataSet.ItemRevisions.Rows.Add(itemRevisionsRow);
jobDataSet.ItemRevisions.AcceptChanges();
itemRevisionsTableAdapter.Update(jobDataSet.ItemRevisions);
jobDataSet.AcceptChanges();
}
Basically, the issue is, everything gets set properly as far as the object properties are concerned (checked this by single stepping through the debugger and looking at the values of the objects in question), no exceptions are being thrown. But the primary keys stay -1 instead of setting to an actual database ID, and the data is never actually added to the tables. I'm sure I'm missing something simple here (like I said, new to this, first ADO.NET disconnected layer app), so if anybody could help it would be appreciated.
BY calling AcceptChanges before using the adapter, you are basically saying that all data in the dataset is unmodified and current. The adapter will hence do nothing. Do not call AcceptChanges before running it through the DB, only when the DB operation succeeds it makes sense to "AcceptChanges"

Categories

Resources