I got System.FormatException from trying replacing a part of string with value
I have a javascript file and it contains below js script
(function() {
try {
var click = new MouseEvent('click', {bubbles: true, cancelable: true, view: window});
var field = document.querySelector('input[type="email"]');
setTimeout(function() {
field.dispatchEvent(click);
field.focus();
field.value="{0}";
}, 500);
return true;
} catch(err) {
return false;
}
})();
And I read that as string using below code:
var path = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory) + "\\Resources\\script\\myjavascript.js";
var raw = File.ReadAllText(path);
var args = new object[] { "my_username" };
Console.WriteLine(raw, args);
I got error: Exception thrown: 'System.FormatException' in mscorlib.dll
As I try to replace {0} with "my_username". Can anybody help me?
Thanks.
Answer based on PepitoSh approach is below:
var path = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory) + "\\Resources\\script\\myjavascript.js";
var raw = File.ReadAllText(path);
var script = raw.Replace("{0}", "my_username");
Console.WriteLine(script);
2 answers
-
answered 2018-07-12 04:47
Mihail Stancescu
You have to escape all other
{
and}
and leave only"{0}"
for thestring.format
to work.Also I would add a js object with properties for all variables and use that as an argument or a global object in js scripts, so I only have to replace the values once for multiple scripts.
-
answered 2018-07-12 04:51
PepitoSh
Since indeed you have to escape the curly braces that are not part of the formatting, I'd recommend another approach in this specific case:
var path = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory) + "\\Resources\\script\\myjavascript.js"; var raw = File.ReadAllText(path); raw = raw.Replace("{0}", "my_username"); Console.WriteLine(raw);
See also questions close to this topic
-
hive jdbc driver: javax.xml.stream.XMLStreamException: Trying to output second root, <r>
I am using the Hive JDBC 3.1 driver (from Hortontworks or official, I have the same issues) in a c# application (Dundas) and I get the error:
hive jdbc driver: javax.xml.stream.XMLStreamException: Trying to output second root,
I really cannot say much more, as the java stack trace is swallowed, and Dundas is a third party application which I did not develop and is not open source. It does use the JDBC driver to connect to hive (the odbc driver is not an option as it is utterly bugged) hence the java stack trace in a C# application (and yes I am talking to support as well, but I was hoping that someone else encountered (and fixed!) the same issue).
Using the driver standalone, via a Java standalone class works fine.
The connection from Dundas works fine, it is getting data that fails.
Any idea what I could do to fix this?
-
Changing variables on BindingSource.Filter Change
2 ComboBoxes, both with a DataSource set to a DataSet.
When I change the value of Box1 I use a Filter on the second DataSource to change the entries in Box2. I want to change some local variables to take the value of the Box1 and Box2. But On the Initializing of Box1 and the filter-setting of Box2 the SelectedIndexChanged-Event does not fire (even if there are now new entries selected).
I could now fire the events by hand, but that seems dirty to me. Someone an idea what events could fire after the Initializing and the Filter setting?private void MainForm_Load(object sender, EventArgs e) { ServicesTableAdapter.Fill(DataSet.Services); OrderObject_SELTableAdapter.Fill(DataSet.OrderObject_SEL, null); ComboBoxObjects_SelectedIndexChanged(ComboBoxObjects, EventArgs.Empty); ComboBoxReference_SelectedIndexChanged(ComboBoxReference, EventArgs.Empty); } private void ComboBoxObjects_SelectedIndexChanged(object sender, EventArgs e) { object selectedValue = ((ComboBox) sender)?.SelectedValue; if (selectedValue == null) return; _selectedObject = (Guid) selectedValue; ServicesBindingSource.Filter = "ObjectFK = '" + _selectedObject + "'"; ComboBoxReference_SelectedIndexChanged(ComboBoxReference, EventArgs.Empty); } private void ComboBoxReference_SelectedIndexChanged(object sender, EventArgs e) { if (ComboBoxReference.SelectedValue != null) _selectedReference = (Guid) ComboBoxReference.SelectedValue; }
-
why when i change reference A's value, the original instance doesn't change?
I'm writing a script for locking scale of objects in Unity.
Since
objectTransformScale = objectTransform.localScale
.Changes made on
objectTransformScale
should also affectobjectTransform.localScale
, but it doesn't.Hence I have to set the value back as
objectTransform.localScale = objectTransformScale;
Why doesn't it work?
public string demension; private Transform objectTransform; private Vector3 objectTransformScale; private float originalX; private float originalY; private float originalZ; // Use this for initialization void Start () { objectTransform = GetComponent<Transform>(); objectTransformScale = objectTransform.localScale; originalX = objectTransformScale.x; originalY = objectTransformScale.y; originalZ = objectTransformScale.z; } // Update is called once per frame void Update () { objectTransformScale = objectTransform.localScale; if (demension.Equals("x")) { objectTransformScale.x = originalX; } else if(demension.Equals("y")) { objectTransformScale.y = originalY; } else if(demension.Equals("z")) { objectTransformScale.z = originalZ; } else if (demension.Equals("a")) { objectTransformScale.z = originalZ; objectTransformScale.y = originalY; objectTransformScale.x = originalX; } //The scale of object won't be locked if I command the line below. objectTransform.localScale = objectTransformScale; }
-
GraphQL with .NET Core: Unable to parse input as a type
I am currently exploring graphql and am running into issues trying to get my mutations to work. The error I am receiving is:
Variable '$article' is invalid. Unable to parse input as a 'ArticleInput' type. Did you provide a List or Scalar value accidentally?
My GraphQL query looks as follows:
mutation($article: ArticleInput!){ createArticle(article: $article){ title } }
with query variable
$article
defined as:{ "article": { "title": "test mutation", "description": "test desc for mutation" } }
The class responsible for defining the mutation:
public class ArticleMutation : ObjectGraphType { public ArticleMutation(IArticleService articleService) { Name = "Mutation"; Field<ArticleType>( "createArticle", arguments: new QueryArguments( new QueryArgument<NonNullGraphType<ArticleInputType>> { Name = "article" } ), resolve: context => { var articleViewModel = context.GetArgument<ArticleViewModel>("article"); return articleService.Create(articleViewModel); }); } }
and finally the type that the input is failing to be parsed into:
public class ArticleInputType : InputObjectGraphType { public ArticleInputType() { Name = "ArticleInput"; Field<StringGraphType>("title"); Field<StringGraphType>("description"); } }
Why is this happening and how can I overcome it?
-
Receiving an assembly error in docker container, but not on local machines
We are having a problem with our solution when it's hosted in a windows container that I don't encounter on my local. I have a WebAPI project using .Net Framework 4.6.2. It is referencing a custom Nuget package we wrote targeting net461;net462;netstandard2.0;. As I said in my title when I run this on my local machine everything is fine. When we publish it to a docker container image: microsoft/dotnet-framework:4.7-windowsservercore-10.0.14393.1884 we get the following error when we try to hit one of the end points in the Nuget Package. Could anyone suggest a solution or possible next trouble shooting step? We've been throwing some guesses based on Stack Overflow searches, but haven't found anything that works.
The ProjectAPI service is now running, press Control+C to exit. 2019-02-18 08:33:12,522 ERROR lobalExceptionLogger: CustomNugetPackageName Exception System.IO.FileNotFoundException: Could not load file or assembly 'System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified. File name: 'System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' at CustomNugetPackageName.Controllers.ReportsController.GetReport(Int32 reportId, Report& report, IHttpActionResult& unauthorized) at CustomNugetPackageName.Controllers.ReportsController.GetReport(Int32 reportId) at lambda_method(Closure , Object , Object[] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_2.<GetExecutor>b__2(Object instance, Object[] methodParameters) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__6.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__6.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__5.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__6.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__6.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__5.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__6.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__6.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__5.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__3.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()
I've tried setting binding redirects int he WebAPI project like so:
<dependentAssembly> <assemblyIdentity name="System.Net.Http" culture="neutral" publicKeyToken="b03f5f7f11d50a3a" /> <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" /> </dependentAssembly>
When I add that the application silently fails when I try to use Autofac to inject the NetStandard app to the WebAPI project. I've been really stumped on what could possibly be going on that's causing it to break in the container.
Here is my Autofac module and startup if you that matters:
Module:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using API.Claims; using API.ControllerBase; using Autofac; using Autofac.Integration.WebApi; using ReportingServiceBase.Base; using Module = Autofac.Module; namespace ReportingAPIBase.Initializers { /// <summary> /// /// </summary> public class ReportingStartupModule : Module { /// <summary> /// /// </summary> public int RestrictAccessValue { get; set; } /// <inheritdoc /> protected override void Load(ContainerBuilder builder) { builder.RegisterModule(new ReportingServiceModule()); var assembly = Assembly.GetExecutingAssembly(); // this List<Type> controllers = (from t in assembly.GetTypes() where t.IsClass && typeof(ApiControllerBase).IsAssignableFrom(t) select t).ToList(); // Add Restrict Attribute foreach (Type controller in controllers) { TypeDescriptor.AddAttributes(controller, new API.Claims.RestrictAttribute(RestrictAccessValue, ClaimValues.FullAccess | ClaimValues.ReadOnly)); } builder.RegisterApiControllers(assembly); } } }
Startup
using System.Reflection; using System.Web.Http; using System.Web.Http.ExceptionHandling; using API.Base; using API.Common; using API.Jwt; using API.RoleManager; using Autofac; using Autofac.Integration.WebApi; using AutoMapper; using AutoMapper.Configuration; using log4net.Config; using Microsoft.Owin; using Microsoft.Owin.FileSystems; using Microsoft.Owin.StaticFiles; using Model.Reporting; using Owin; using ReportingAPIBase.Initializers; using Service; using Service.Utilities; [assembly: XmlConfigurator(ConfigFile = "l4n.config", Watch = true)] namespace API { public class Startup { public void Configuration(IAppBuilder app) { // Configure Web API for self-host. var config = new HttpConfiguration(); // Register modules and types var builder = new ContainerBuilder(); builder.RegisterModule(new ReportingDataPointsModule()); // FAILS HERE builder.RegisterModule(new ReportingStartupModule() { RestrictAccessValue = Claims.ClaimTypes.Reports }); builder.RegisterModule(new ServiceModule()); builder.RegisterModule(new EfModule()); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // Register service handles config.Services.Add(typeof(IExceptionLogger), new GlobalExceptionLogger()); builder.RegisterWebApiFilterProvider(config); MapperConfigurationExpression mapperConfig = new AutoMapperConfiguration().Configure(); Mapper.Initialize(mapperConfig); Mapper.AssertConfigurationIsValid(); // Build container var container = builder.Build(); config.DependencyResolver = new AutofacWebApiDependencyResolver(container); // The Autofac middleware must go before any Web Api middleware app.UseAutofacMiddleware(container); app.UseAutofacWebApi(config); WebApiConfig.Register(config, container); // Non-Autofac OWIN pipeline app.UseJsonWebTokens(container.Resolve<IRoleManager>()); app.UseRoleManager(container.Resolve<IRoleManager>()); app.UseWebApi(config); // Ensures configuration is ready config.EnsureInitialized(); } }
-
Relationship - EF Core
I'm having some trouble to get into EF Core relationship.
I didn't know how to search it properly, so I've not found what I need, but I got somewhere.
I have these two classes:
Expense:
public class Expense : Entity { public string Title { get; set; } public string Description { get; set; } public decimal Amount { get; set; } public List<ExpenseType> Types { get; set; } public ValidationResult ValidationResult { get; private set; } public bool IsValid { get { var fiscal = new ExpenseIsValidValidation(); ValidationResult = fiscal.Valid(this); return ValidationResult.IsValid; } }}
ExepenseType:
public class ExpenseType : Entity { #region properties public string Name { get; private set; } public string Description { get; private set; } public ValidationResult ValidationResult { get; private set; } public bool IsValid { get { var fiscal = new ExpenseTypeIsValidValidation(); ValidationResult = fiscal.Valid(this); return ValidationResult.IsValid; } }}
During the ToListAsync in ExpenseType, the EF adds the column "expenseId" to the query, but this column does not exist.
My database has three tables, one for each class, and one for the relationship. (Expense, ExpenseType and Expense_ExpenseType)
By looking for the solution here on StackOverflow I found that I should have a class for the third table. Here it is:
public class Expense_ExpenseType { public int ExpenseId { get; set; } public Expense Expense { get; set; } public int ExpenseTypeId { get; set; } public ExpenseType ExpenseType { get; set; } }
My idea is that I can have an ExpenseType without having an Expense, and I can have an Expense without ExpeseType or with as many as I want of them.
So ExpenseType hasn't any Expense.
I'm not sure what I should do now. Should I Map using optionsBuilder? How? Should I ReWrite the database?
-
C#: adding button, textbox, combobox, checkbox and DataGrid
In WPF I have a stack panel in which I keep adding different UI elements say checkbox, button, combobox and textbox. It works perfectly fine with these UI elements, but when I'm adding DataGrid, the later elements added are overlapped with DataGrid. Can't we add DataGrid as any other normal UI element to stack panel?
-
Communicating between viewModels using interfaces in manner of MVVM
I have tried to use MVVM Light messaging to communicate between different viewModels, but with time it gets quite messy and hard to understand from where and where to all the messages are flying so I wanted to ask about other solution how to communicate between viewModels using Interfaces. The provided code works well, but I am not sure if Interfaces are mend to be used this way.. So here I have defined interface and class that implements it:
public interface ISelectProject { event EventHandler<SelectedProjectEventArgs> MessageReceived; void ProjectSelected(...); } public class SelectProject : ISelectProject { public event EventHandler<SelectedProjectEventArgs> MessageReceived; public void ProjectSelected(..) { MessageReceived?.Invoke(this,new SelectedProjectEventArgs(...)); } }
Afterwards I inject SelectProject class into these tree viewModels using constructor injection(code not shown here). Then in viewModelA I invoke MessageReceived event and all the other viewModels subscribe to the event.
public class ViewModelA : ViewModelBase { public ViewModelA(ISelectProject selectProject) { _selectProject = selectProject; _selectProject.ProjectSelected; } } public class ViewModelB : ViewModelBase { public ViewModelB(ISelectProject selectProject) { _selectProject = selectProject; _selectProject.MessageReceived += (s, data) => { ... }; } } public class ViewModelC : ViewModelBase { public ViewModelC(ISelectProject selectProject) { _selectProject = selectProject; _selectProject.MessageReceived += (s, data) => { ... }; } }
My question are:
1) Does this somehow violate MVVM pratice?
2) Is it considered a good practice to communicate between viewModels like this?
3) Does this solution introduces any risks, for example memory leaks, etc.
Thank you!
-
WPF MVVM compliant way to open views
I would love to find a simple and MVVM compliant way, to open a new view from the MainWindow.
I have already worked through some instructions and tutorials. But somehow none really worked or it was a mixture of code behind.
I would like to open a view after pressing a button and edit an ObservableCollection in it.
I have already created DataTemplates in App.xaml and mapped the ViewModels with the respective views. But I don't know how to cleanly open a separate window from the MainWindow (MainViewModel) via an ICommand for another ViewModel.