How to remove curly brackets using C#.?
My Array
{[{ "SKU":"53823","OrderNo":"12345678563423"}]}
I want to get OrderNo How.?
1 answer
-
answered 2021-02-20 12:00
Sam
The first and last curly brackets are preventing you to deserialize the string. How do you get this json string? A quick fix could be something like this:
var json = "{[{ 'SKU':'53823','OrderNo':'12345678563423'}]}"; var jsonFix = json.TrimEnd('}').TrimStart('{'); var obj = JsonConvert.DeserializeObject<List<Item>>(jsonFix); class Item { [JsonProperty("SKU")] public int SKU { get; set; } [JsonProperty("OrderNo")] public string OrderNo { get; set; } }
But note that this isn't the right way to do it. You should change your json serialization!
See also questions close to this topic
-
Filter items in a listbox that have been added with json
Well I'm trying to list items that are from listbox created with UserControl and the text properties are defined with a json file.
This is my .json file:
{ "Games": { "Quantity": 2, "Title0": "SomeGame1", "Description0": "Fps game", "Image0": "Some image link", "Link0": "GameStore.com/Somegame1", "Title1": "SomeGame2", "Description1": "RPG game", "Image1": "Some image link", "Link1": "GameStore.com/Somegame2", } }
This is the code to load the games as items in the listbox:
string JsonFile = Environment.CurrentDirectory @"\Test.json"; dynamic jasonfile = JsonConvert.DeserializeObject(JsonFile); GameUserControl[] Games = new GameUserControl[jasonfile["Games"]["Quantidade"]]; for (int quantity= 0; quantity < Games.Length; quantity++) { Games[quantity] = new GameUserControl(); Games[quantity].Descrição.Content = (jasonfile["Games"]["Title" + quantity]); Games[quantity].jog = (jasonfile["Games"]["Titulo" + quantity]); Games[quantity].lin = (jasonfile["Games"]["Link" + quantity]); string image = jasonfile["Games"]["Image" + quantity]; Games[quantity].imag = new ImageBrush(new BitmapImage(new Uri(image, UriKind.Absolute))); GamesListBox.Items.Add(Games[quantity]); }
This is the code I used in a textbox to try to filter:
if (CollectionViewSource.GetDefaultView(GamesListBox.Items) != null) CollectionViewSource.GetDefaultView(GamesListBox.Items).Filter = (o) => { return o.ToString().ToLower().Contains(Search.Text.ToLower()); };
But it didn't work, the item names are always GameUserContro.Can someone help me?
-
Advantage of .Net Core over WCF for RESTful APIs
We are currently using WCF to create RESTful APIs, it is working fine and has an added advantage that it can be consumed via SOAP too if we ever need to. We have all our systems using Microsoft technologies.
There is no active development on WCF but the current functionality is working fine for us. However, I believe the recommended approach is to start using .Net core for RESTful services. What are the additional advantages .Net core offers over WCF (apart from being platform independent)?
-
Generic class type constraint with a generic class having another constraint
Let's say I have a generic class
public class G<T> { }
and I want to declare final class as
public class F<T> where T : G<T> { }
that seems to be possible, but what if I want to complicate the task and add a constraint to the class G like that
public class A { } public class DA : A { } public class DB : A { } public class G<T> where T : A { }
and finally I want to do this
public class F<T> where T : G<T> { }
that does not work, it says T has to be of type A which is understandable and it looks like I can rewrite it like this
public class F<T, U> where T : G<U> where U : A { }
but in this case the usage has a redundant declaration
public class DF : F<G<DA>, DA> { }
I have to repeat DA twice when using class F even though it is quite clear if I use G as a generic type the generic type of G is DA. Is there a way to avoid this redundancy?
-
Cascading databound <ajaxtoolkit:combobox> and <asp:dropdownlist> in asp.net
I have an
asp.net
search form that includes anajaxToolkit Combobox
and a standardasp DropDownList
. Both controls are bound to two separatedSqlDatasource
components.Something like this:
<ajaxToolkit:ComboBox ID="cbConvenzionato" runat="server" AutoCompleteMode="SuggestAppend" DropDownStyle="DropDownList" DataSourceID="sdsConvenzionati" DataTextField="nome" DataValueField="id" AutoPostBack="true" OnSelectedIndexChanged="cbConvenzionato_SelectedIndexChanged" /> <asp:DropDownList ID="ddlVeicoli" DataSourceID="sdsVeicoli" DataTextField="targa" DataValueField="id" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlVeicoli_SelectedIndexChanged" AppendDataBoundItems="true"> <asp:ListItem Text="TUTTI" Value="" Selected="True" /> </asp:DropDownList> <asp:SqlDataSource ID="sdsConvenzionati" runat="server" ConnectionString="<%$ ConnectionStrings:db %>" ProviderName="<%$ ConnectionStrings:db.ProviderName %>" SelectCommand=" SELECT id, nome FROM anag_convenzionati ORDER BY nome;" /> <asp:SqlDataSource ID="sdsVeicoli" runat="server" EnableCaching="false" CancelSelectOnNullParameter="false" ConnectionString="<%$ ConnectionStrings:db %>" ProviderName="<%$ ConnectionStrings:db.ProviderName %>" SelectCommand=" SELECT id, targa FROM veicoli_contratti WHERE ((@id_convenzionato IS NULL) OR (id_convenzionato = @id_convenzionato)) ORDER BY targa;"> <SelectParameters> <asp:ControlParameter Name="id_convenzionato" ControlID="cbConvenzionato" PropertyName="SelectedValue" Direction="Input" ConvertEmptyStringToNull="true" DbType="Int32" DefaultValue="" /> </SelectParameters> </asp:SqlDataSource>
There's also a third
sqldatasource
(sdsNoleggi
) that feeds agridview
but this's not a problem right now.In code behind I have two event handlers:
protected void cbConvenzionato_SelectedIndexChanged(object sender, EventArgs e) { sdsVeicoli.Select(DataSourceSelectArguments.Empty); Search(); } protected void ddlVeicoli_SelectedIndexChanged(object sender, EventArgs e) { Search(); } private void Search() { sdsNoleggi.Select(DataSourceSelectArguments.Empty); }
I tought in this way I should filter
ddlVeicoli
items after selecting an item incbConvenzionato
... but it's not working... why?If I look into
sdsVeicoli
SelectParameters
in debug I can seeid_convenzionato
being correctly set to selected value (id coming fromcbConvenzionato
) I bet also thatsdsNoleggi
dataset wiil be correctly updated with new values since I did this many times before. So why bound control it's not? I tried also to force addlVeicoli.DataBind()
aftersdsVeicoli.Select()
call ... but this had no effect. -
Swagger UI not working for REST API (asp.net web api2) application
I have asp.net mvc project with .NET Framework 4.7.2 and the same project contains asp.net web api2 controller in a separate folder : Controllers. The solution is legacy. The API are already in use in the PRODUCTION environment. Now I added the Swagger nuget package (Install-Package Swashbuckle -Version 5.6.0) to this existing project. Post that I see a SwaggerConfig.cs added to the App_Start folder of the Solution Explorer.
Here the asp.net mvc controllers are used by App1 pointing to the server: www.app1.com and asp.net web api2 controllers are used by another frontend angular app: App2 pointing to the server : www.app2.com
The complete deployment package for both App1 and App2 are hosted in IIS
Any request related to App1 is handled by www.app1.com and any api request related to App2 (Angular frontend) is handled by App1 only using IIS Rewrite rules at App2 level which redirect any api request to App1 only.
Now in this case when I tried to navigate to www.app1.com/swagger , I see it is loading the SwaggerUI for me, but when I tried to navigate to www.app2.com/swagger it is not working and instead of that it is loading the Angular frontend application
Here goes the App1 and App2 at IIS level:
Can anyone help me here by providing their guidance to fix this issue?
-
Cors error missing allow origin header. MailKit
I have
cors error missing allow origin header
error only on ONE post request. My CORS Policypublic void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("AllowAllOrigins", builder => { builder.SetIsOriginAllowed(_ => true) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); }
Every request work fine, but one POST request fails, it's really weird. Code in controller action which failed use MailKit and SMTP to send email, maybe that's cause
-
Sort,Filter,search in Javascript array
Given values for acctData and balances below, write a function that returns only an array of account numbers, and accepts the following optional parameters:
- user - sortBy (accepts "acctNum" or "balance") - sortDirection (accepts "asc" or "desc"; default to asc)
Execute your function and output the results as an array in console log for the following scenarios:
a) filtered by Bob b) filtered by Charlie c) sorted by acctNum d) filtered by Alice; sorted by balance ascending
acctData = [ { "acctNum": "AAA - 1234", "user": "Alice" }, { "acctNum": "AAA - 5231", "user": "Bob" }, { "acctNum": "AAA - 9921", "user": "Alice" }, { "acctNum": "AAA - 8191", "user": "Alice" } ]; balance = { "AAA - 1234": 4593.22, "AAA - 9921": 0, "AAA - 5231": 232142.5, "AAA - 8191": 4344 };
-
How do I store an array in a PSQL, where it is passed as a parameter $1 to the db query
I am passing a one-dimensional array of three strings to the function, it looks like this going in:
[ '#masprofundo', '#massensual', '#eclectic' ]
The data column is declared thus:
tags TEXT []
This is my function:
const query = `INSERT INTO posts (posted_at, message, link, tags) VALUES (TO_TIMESTAMP($1, 'DD/MM/YYYY HH24:MI'), $2, $3, ARRAY [$4]) RETURNING tags;`; const params = [timestamp, message, link, tags];
Now, postgres believes I want to insert an array containing one item, which is a string of all the values in my tags array. It looks like this:
{ tags: [ '{"#masprofundo","#massensual","#eclectic"}' ] }
What I want to know is, how do I prevent this behaviour, where postGres adds an unnecessary extra layer of quotation marks and parentheses? For further clarification; this is what the row looks like in my terminal.
{"{\"#masprofundo\",\"#massensual\",\"#eclectic\"}"}
I have looked at the docs, and tried a dozen variations on ARRAY[$4]. From what I can see, the docs do not elaborate on inserting arrays as variables. Is there some destructuring that needs to happen? The arrays I pass will be of varying size, and sometimes empty.
Any help is much appreciated.
-
Python: Implementing an n-dimensional matrix/tensor as one dimensional list of elements
So, I have a matrix/tensor class. It consists of a one dimensional numpy array filled with elements and a second array denoting the shape of the matrix.
So for example the matrix:
1 4 2 5 3 6
would have the elements [1,2,3,4,5,6] and shape [3,2]
I'm a little stuck right off the bat. Right now I want to write a getter/setter function and implement mathematical operations like multiplication, but I have no idea how to do it.
I have a rough idea for a setter, with using modulo, but I don't know how I can make it behave dynamically for n-dimensions, since the formula would have to be extended for higher dimensions, right?
As for mathematical operations, I'm absolutely clueless how to do it efficently, without getting stuck in endless nested for-loops
I don't expect anyone to write my code for me, but I was hoping to get some helpful links to similar approaches, since I couldn't find any myself.
-
GroupJoin without having to select contents from joined list
So I've got two classes that I'm trying to combine into a ViewModel for use in the application. I'm trying to find the lambda syntax to perform a left join between the two objects (Actual Delivery, DeliveryHdr). For some context the DeliveryHdr is a scheduled delivery on a schedule and the Actual Delivery is details collected once the delivery is made. I'm using the provided method (CovertToViewModel) to conmbine the two objects and return a list of ViewModels and it functions like I want it to but I'm thinking there has to be an easier way? How can I perform a 1 to 1 left join without having to perform Select's on the joined List like I've done below?
public partial class ActualDelivery { public int ActualDeliveryId { get; set; } public int DeliveryId { get; set; } public string DockDoor { get; set; } public string ArrivalComments { get; set; } public string SetTemp { get; set; } public string Unloader { get; set; } public DateTime? UnloadStart { get; set; } public DateTime? UnloadEnd { get; set; } public int? ActualAmbientFull { get; set; } public int? ActualAmbientMixed { get; set; } public int? ActualReefer { get; set; } public int? ActualCageVault { get; set; } public int? ActualBlc { get; set; } public int? ActualTotalPallets { get; set; } public int? ActualTotalLpns { get; set; } public DateTime? CreatedDttm { get; set; } public string CreatedUser { get; set; } public DateTime? UpdatedDttm { get; set; } public string UpdatedUser { get; set; } }
public partial class DeliveryHdr { public int DeliveryId { get; set; } public DateTime? LoadDate { get; set; } public DateTime? ScheduledTime { get; set; } public DateTime? ArrivalTime { get; set; } public int? LoadNumber { get; set; } public string Shift { get; set; } public string SupplierNumber { get; set; } public string SupplierName { get; set; } public string Carrier { get; set; } public bool? IsCancelled { get; set; } public bool? IsConfirmed { get; set; } public bool? IsBackHaul { get; set; } public int? ActAmbientFullPallets { get; set; } public int? ActAmbientMixedPallets { get; set; } public int? ActReeferPallets { get; set; } public int? ActCageVaultPallets { get; set; } public int? ActBlcpallets { get; set; } public int? ActTotalPallets { get; set; } public int? ActTotalLpns { get; set; } public bool? MarkAsDeleted { get; set; } public string CreatedUser { get; set; } public DateTime? CreatedDttm { get; set; } public string UpdatedUser { get; set; } public DateTime? UpdatedDttm { get; set; } }
public class ActualDeliveriesViewModel { public int DeliveryId { get; set; } public int ActualDeliveryId { get; set; } public string CompositeId { get; set; } public DateTime? LoadDate { get; set; } public DateTime? ScheduledTime { get; set; } public DateTime? ActualTime { get; set; } public string Shift { get; set; } public int? LoadNumber { get; set; } public string SupplierName { get; set; } public string Carrier { get; set; } public bool? IsConfirmed { get; set; } public bool? IsBackHaul { get; set; } public bool? IsCancelled { get; set; } public string DockDoor { get; set; } public string ArrivalComments { get; set; } public string SetTemp { get; set; } public string Unloader { get; set; } public DateTime? UnloadStart { get; set; } public DateTime? UnloadEnd { get; set; } public int? ActualAmbientFull { get; set; } public int? ActualAmbientMixed { get; set; } public int? ActualReefer { get; set; } public int? ActualCageVault { get; set; } public int? ActualBlc { get; set; } public int? ActualTotalPallets { get; set; } public int? ActualTotalLpns { get; set; } }
public List<ActualDeliveriesViewModel> CovertToViewModel(List<DeliveryHdr> deliveries, List<ActualDelivery> actuals) { return deliveries.Where(e => e.MarkAsDeleted == false).GroupJoin(actuals, d => d.DeliveryId, a => a.DeliveryId, (d, a) => new ActualDeliveriesViewModel() { DeliveryId = d.DeliveryId, ActualDeliveryId = a.Select(i => i.ActualDeliveryId).FirstOrDefault(), CompositeId = d.DeliveryId + "_" + a.Select(i => i.ActualDeliveryId).FirstOrDefault(), LoadDate = d.LoadDate, ScheduledTime = d.ScheduledTime, ActualTime = d.ArrivalTime, LoadNumber = d.LoadNumber, SupplierName = d.SupplierName, Carrier = d.Carrier, IsConfirmed = d.IsConfirmed, IsBackHaul = d.IsBackHaul, IsCancelled = d.IsCancelled, DockDoor = a.Select(i => i.DockDoor).FirstOrDefault(), ArrivalComments = a.Select(i => i.ArrivalComments).FirstOrDefault(), SetTemp = a.Select(i => i.SetTemp).FirstOrDefault(), Unloader = a.Select(i => i.Unloader).FirstOrDefault(), UnloadStart = a.Select(i => i.UnloadStart).FirstOrDefault(), UnloadEnd = a.Select(i => i.UnloadEnd).FirstOrDefault(), ActualAmbientFull = a.Select(i => i.ActualAmbientFull).FirstOrDefault(), ActualAmbientMixed = a.Select(i => i.ActualAmbientMixed).FirstOrDefault(), ActualBlc = a.Select(i => i.ActualBlc).FirstOrDefault(), ActualCageVault = a.Select(i => i.ActualCageVault).FirstOrDefault(), ActualReefer = a.Select(i => i.ActualReefer).FirstOrDefault(), ActualTotalPallets = (a.Select(i => i.ActualAmbientFull).FirstOrDefault() + a.Select(i => i.ActualAmbientMixed).FirstOrDefault() + a.Select(i => i.ActualBlc).FirstOrDefault() + a.Select(i => i.ActualCageVault).FirstOrDefault() + a.Select(i => i.ActualReefer).FirstOrDefault()) ?? 0 }).ToList(); }
-
OutputCache an ActionResult that only returns a View
Would it make sense to [OutputCache] something like this?
[HttpGet] public ActionResult About() { return this.View("About"); }
-
The entity type was not found. Ensure that the entity type has been added to the model
I'm new to ASP.NET Core and i'm trying to insert an entity into an Entity Framework Core model scaffolded from a simple existing MariaDB database.
This is the entity model:
public class ScrapeAsincroni { public int Id { get; set; } public string Paese { get; set; } public string Engine { get; set; } public string Keywords { get; set; } }
This is the controller action that is supposed to add the entity:
public JsonResult create(string paese, string engine, string keywords) { ScrapeAsincroni scrapeAsincrono = new ScrapeAsincroni { Paese = paese, Engine = engine, Keywords = keywords }; _context.Add(scrapeAsincrono); try { _context.SaveChangesAsync(); } catch (Exception ex) { return Json(new Dictionary<string, int?> { { "id", null } }); } return Json(new Dictionary<string, int?>{ {"id", scrapeAsincrono.Id} }); }
The database context (_context) has been initialized on the controller's constructor. the line
_context.Add(scrapeAsincrono);
throws the following exception:
System.InvalidOperationException: The entity type 'ScrapeAsincroni' was not found. Ensure that the entity type has been added to the model.
This is the modelBuilder code relative to this model
public partial class ScraperDbContext : DbContext { public ScraperDbContext() { } public ScraperDbContext(DbContextOptions<ScraperDbContext> options) : base(options) { } public virtual DbSet<ScrapeAsincroni> ScrapeAsincroni { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings. optionsBuilder.UseMySql("server=51.255.74.100;port=3306;user=luca.ceccagnoli;password=Hb93#2ql;database=scraper_db", x => x.ServerVersion("10.3.25-mariadb")); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<ScrapeAsincroni>(entity => { entity.HasComment("Informazioni su una ricerca asincrona dello Scraper"); entity.Property(e => e.Id) .HasColumnName("id") .HasColumnType("int(11)"); entity.Property(e => e.Engine) .HasColumnName("engine") .HasColumnType("varchar(255)") .HasCharSet("utf8") .HasCollation("utf8_general_ci"); entity.Property(e => e.Keywords) .IsRequired() .HasColumnName("keywords") .HasColumnType("text") .HasCharSet("utf8") .HasCollation("utf8_general_ci"); entity.Property(e => e.Paese) .HasColumnName("paese") .HasColumnType("varchar(255)") .HasCharSet("utf8") .HasCollation("utf8_general_ci"); }); OnModelCreatingPartial(modelBuilder); } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); }
I can't seem to understand why this happens, and couldn't find any solutions online.
-
Do we have to put all passed in arguments into its own self. variable before using them in another expression in the class?
In the following code:
class Game(object): def __init__(self, screen: pygame.Surface, states: dict, start_state: str): self.done = False self.screen = screen self.clock = pygame.time.Clock() self.fps = 60 self.states = states self.state_name = start_state self.state = self.states[self.state_name]
Why do we put the passed in arguments states and start_state into variables self.states and self.start_states before using them in creating the self.state variable?
Do we have to put all passed in arguments into its own self. variable before using them in another expression in the class?
Would it work if we did the following instead:
self.state = states[state_name]
-
Code redundancy for python regex and if-else blocks
I have this function consisting of if-else blocks matching several regex patterns.
The code is repetitive, and I would like to reduce the repetitive functions.
I have attached the code below.
def get_dates_regex(r): raw_text = r['Raw_Text'] clean_text = (raw_text.replace('\n',' ').replace('\r',' ').strip()).lower() #print(clean_text) date_regex1 = r'\b((date|date:|invoice date:|invoice date|date of issue|issue date:|dated:)\s*\b.*?(\d{1,4}([.\-\/])\d{1,2}([.\-\/])\d{1,4}))\b' date_regex2 = r'\b((date\s*:|date)(\s*\d{1,4}\s*[A-Za-z]+\s*\d{1,4}\b))\b' date_regex3 = r'\b((date\s*:)\s*(\d{1,4}\s*[A-Za-z]+\s*[A-Za-z]+\s*\d{1,4}))\b' date_regex4 = r'\b((date\s*:)(\s*[A-Za-z]{1,9}\s*\d{1,2}(,|\s+)\s*\d{1,4}))\b' date_regex5 = r'\b(date\s*(((\d{1}\s*){1,4}[.\-\/]\s*(\d{1}\s*){2}[.\-\/]\s*(\d{1}\s*){1,4})))\b' due_regex1 = r'\b((due date\s*:|due date)\s+(\d{1,4}([.\-\/])\d{1,2}([.\-\/])\d{1,4}))\b' due_regex2 = r'\b((due date\s*:|due date\s*)(\s+\w+\s+\d{1,2}(,|\s+)\s+\d{1,4}))\b' due_regex3 = r'\b(due date\s*:|due date\s*)\s*((\d{1,4}\s*\w+\s+\d{1,4}))\b' #due_regex2 = r'\b(due\b.*?((\d{1,2}\s*[a-z]+\s*\d{1,4})))\b' try: if ('date' in clean_text) or ('invoice date' in clean_text): #print('date present') date1 = re.search(date_regex1,clean_text) date2 = re.search(date_regex2,clean_text) date3 = re.search(date_regex3,clean_text) date4 = re.search(date_regex4,clean_text) date5 = re.search(date_regex5,clean_text) if date1: #print("Hello") r['Date'] = date1.group(3).strip() elif date2: r['Date'] = date2.group(3).strip() elif date3: r['Date'] = date3.group(3).strip() elif date4: r['Date'] = date4.group(3).strip() else: r['Date'] = date5.group(3).strip() except: r['Date'] = '' #logex() try: if 'due' in clean_text: due_date1 = re.search(due_regex1,clean_text) due_date2 = re.search(due_regex2,clean_text) due_date3 = re.search(due_regex3,clean_text) if due_date1: r['Due_Date'] = due_date1.group(3).strip() elif due_date2: r['Due_Date'] = due_date2.group(3).strip() else: r['Due_Date'] = due_date3.group(3).strip() except: r['Due_Date'] = '' #logex() return r
The main goal is to reduce the repetitiveness of the if else.
-
How to write to Azure storage when the primary region down?
Our application uses RA-GZRS for storage which enables to read data from the secondary when the primary is down, but can't write to it.
Is there a solution which enables application to do both read from and write to storage in the event of an Azure region going down?