Embedding JavaScript engine into .NET




just wondering if anyone has ever tried embedding and actually integrating any js engine into the .net environment. I could find and actually use (after a **LOT** of pain and effort, since it's pretty outdated and not quite finished) spidermonkey-dotnet project. Anyone with experience in this area? Engines like SquirrelFish, V8.. 


Not that I'm not satisfied with Mozilla's Spidermonkey (using it for Rails-like miniframework for custom components inside the core ASP.NET application), but I'd still love to explore a bit further with the options. The command-line solutions are not what I'd need, I cannot rely on anything else than CLR, I need to call methods from/to JavaScript/C# objects.



```
// c# class
public class A
{
    public string Hello(string msg)
    {
        return msg + " whatewer";
    }
}

// js snippet
var a = new A();
console.log(a.Hello('Call me')); // i have a console.log implemented, don't worry, it's not a client-side code :)

```

Just to clarify - I'm not trying to actually program **the application itself** in server-side javascript. It's used solely for writing custom user subapplications (can be seen as some sort of DSL). It's much easier (and safer) to allow normal people programming in js than C#.
Try [Javascript .NET](https://github.com/JavascriptNet/Javascript.Net). It is hosted on GitHub It was originally hosted on CodePlex, [here](http://javascriptdotnet.codeplex.com))


Project discussions: <http://javascriptdotnet.codeplex.com/discussions>


It implements Google V8. You can compile and run JavaScript directly from .NET code with it, and supply CLI objects to be used by the JavaScript code as well. It generates native code from JavaScript.
You can detect the browser in use and display the message. You can even have it hide the page content unless the browser used is Internet Explorer. However, there's no way to use JavaScript (or any other web dev. code) to open a completely separate program.



If you are really determined, you might try looking into something that indirectly opens another program through an object or applet of some kind, like flash or Java applets. I don't think you'll find anything, though.



If this were possible, it would be a security problem. Consider the situation if IE had a known exploit and it were possible to force a page to open in IE regardless of the browser it was originally opened in.



I recommend fixing your site. It's not that difficult to develop pages that work everywhere. If I develop pages in accordance with the W3C recommendations, they work pretty well in Firefox, Safari, Opera, and Chrome. Then it's not too difficult to tweak them to work in IE. I've found that doing it the other way around, targeting IE first then tweaking it to work in other browsers, is much more difficult. Pages that require Microsoft ActiveX plugins are an exception of course, but I think it's well worth the time to find an alternative.



--  

-- Ghodmode JavaScript *itself* has nothing built in for handling query string parameters. 


Code running in a (modern) browser you can use the [`URL` object](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) (which is part of the APIs provided by browsers to JS):





```
var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5"; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);
```









For older browsers (including Internet Explorer), you can use [this polyfill](https://github.com/ungap/url-search-params) or the code from the original version of this answer that predates `URL`:


You could access `location.search`, which would give you from the `?` character on to the end of the URL or the start of the fragment identifier (#foo), whichever comes first.


Then you can parse it with this:





```
function parse_query_string(query) {
  var vars = query.split("&");
  var query_string = {};
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    var key = decodeURIComponent(pair[0]);
    var value = decodeURIComponent(pair[1]);
    // If first entry with this name
    if (typeof query_string[key]  "undefined") {
      query_string[key] = decodeURIComponent(value);
      // If second entry with this name
    } else if (typeof query_string[key]  "string") {
      var arr = [query_string[key], decodeURIComponent(value)];
      query_string[key] = arr;
      // If third or later entry with this name
    } else {
      query_string[key].push(decodeURIComponent(value));
    }
  }
  return query_string;
}

var query_string = "a=1&b=3&c=m2-m3-m4-m5";
var parsed_qs = parse_query_string(query_string);
console.log(parsed_qs.c);
```




You can get the query string from the URL of the current page with:



```
var query = window.location.search.substring(1);
var qs = parse_query_string(query);

``` as i noted learning javascript is a good place to go as it’s used to make webpages more dynamic! the front end engineer career path may work well for you as the lessons you have already done will be completed, but there’s a lot of extra notes and such in it for html and css, as well as adding in the… not [full disclosure] a linux person per se.

something similar to the following should work:

https://www.unix.com/shell-programming-and-scripting/68166-converting-integer-string.html

start simple with just enough code to test the concept.

see if it works and modify/correct as necessary.

then if it still does not work, then post your documented code accordingly along an explanation of what is or is not happening as you expect or desire. You will want to look at the httpwebrequest class and its methods. You can feed it a URL and get back the source (page) to do with as you will. The MSDN articles that come up of you google httpwebrequest will help you. roz2000 –


I don’t have any personal experience with .NET code generation tools, but I can refer you to a very good website that provides information and resources on code generation. Checkout:


 http://www.codegeneration.net/


On this site, you will find interviews, technical articles, book references, and product/tool lists for specific platform. There are some very good resources on OMG Model-Driven Architecture (MDA), Intentional Programming, and other generative programming techniques.


Checkout the .NET page (http://www.codegeneration.net/tiki-index.php?page=NET) for specifics on .NET tools. There is also a complete list of code generators in the left-hand navigation bar (under “Generators”).


Good luck!


————————————  

Chris Peltz, Software Technologist  

Applied Technology Office  

Hewlett-Packard  

chris.peltz@hp.com  

(970) 898-1622 I have now implemented the following solution.


As CodeNotFound pointed out in the comments, IdentityUser used to have a `Roles` property. This is no longer the case in .NET Core. This [comment/issue](https://github.com/aspnet/Identity/issues/1361#issuecomment-348863959) on GitHub seems to be the current solution for .Net Core. I have attempted to implemented it with the following code:


**ApplicationUser**



```
public class ApplicationUser : IdentityUser
{
    public ICollection<ApplicationUserRole> UserRoles { get; set; }
}

```

**ApplicationUserRole**



```
public class ApplicationUserRole : IdentityUserRole<string>
{
    public virtual ApplicationUser User { get; set; }
    public virtual ApplicationRole Role { get; set; }
}

```

**ApplicationRole**



```
public class ApplicationRole : IdentityRole
{
    public ICollection<ApplicationUserRole> UserRoles { get; set; }
}

```

**DBContext**



```
public class ApplicationDbContext
    : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>,
    ApplicationUserRole, IdentityUserLogin<string>,
    IdentityRoleClaim<string>, IdentityUserToken<string>>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<ApplicationUserRole>(userRole =>
        {
            userRole.HasKey(ur => new { ur.UserId, ur.RoleId });

            userRole.HasOne(ur => ur.Role)
                .WithMany(r => r.UserRoles)
                .HasForeignKey(ur => ur.RoleId)
                .IsRequired();

            userRole.HasOne(ur => ur.User)
                .WithMany(r => r.UserRoles)
                .HasForeignKey(ur => ur.UserId)
                .IsRequired();
        });
    }
}

```

**Startup**



```
services.AddIdentity<ApplicationUser, ApplicationRole>(options => options.Stores.MaxLengthForKeys = 128)
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

```

Finally, make sure when you're using it that you eagerly load the User's UserRoles, and then the UserRole's Role like so:



```
this.Users = userManager.Users.Include(u => u.UserRoles).ThenInclude(ur => ur.Role).ToList();

```

I had an issue where the `Role` property of each `UserRole` was null and this was resolved by adding in the `.ThenInclude(ur => ur.Role)` part.


Microsoft doc on multi-level eager loading: <https://docs.microsoft.com/en-us/ef/core/querying/related-data#including-multiple-levels> I've had great success with [wsdl2php](https://github.com/jbarciauskas/wsdl2php). It will automatically create wrapper classes for all objects and methods used in your web service. You are mixing [expressions](https://docs.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression?view=netframework-4.7.1) with [lambda expressions](https://docs.microsoft.com/en-us/dotnet/api/system.linq.expressions.lambdaexpression?view=netframework-4.7.1). There are many posts showing how you can combine lambda expressions, but the essential part is to compose expressions from lambda expression [bodies](https://docs.microsoft.com/en-us/dotnet/api/system.linq.expressions.lambdaexpression.body?view=netframework-4.7.1) and rebind the [parameters](https://docs.microsoft.com/en-us/dotnet/api/system.linq.expressions.lambdaexpression.parameters?view=netframework-4.7.1).


The later is usually achieved by a custom [`ExpressionVisitor`](https://docs.microsoft.com/en-us/dotnet/api/system.linq.expressions.expressionvisitor?view=netframework-4.7.1) like this:



```
using System.Linq.Expressions;

public static class ExpressionExtensions
{
    public static Expression ReplaceParameter(this Expression expression, ParameterExpression source, Expression target)
    {
        return new ParameterReplacer { Source = source, Target = target }.Visit(expression);
    }

    class ParameterReplacer : ExpressionVisitor
    {
        public ParameterExpression Source;
        public Expression Target;
        protected override Expression VisitParameter(ParameterExpression node)
        {
            return node == Source ? Target : base.VisitParameter(node);
        }
    }
}

```

Now regarding the EF Core combined query filters. 


Using dictionaries and expression lists seems overcomplicated for what are you doing. Since [`IMutableEntityType`](https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.metadata.imutableentitytype?view=efcore-2.1) provides read/write access to the [`QueryFilter`](https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.metadata.imutableentitytype.queryfilter?view=efcore-2.1#Microsoft_EntityFrameworkCore_Metadata_IMutableEntityType_QueryFilter), the same can be achieved with a small set of a custom extension methods.


All they go inside a class like this:



```
using System;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

public static class QueryFilterExtensions
{
}

```

First method:



```
public static void AddQueryFilter(this IMutableEntityType target, LambdaExpression filter)
{
    if (target.QueryFilter == null)
        target.QueryFilter = filter;
    else
    {
        var parameter = target.QueryFilter.Parameters[0];
        var left = target.QueryFilter.Body;
        var right = filter.Body.ReplaceParameter(filter.Parameters[0], parameter);
        var body = Expression.AndAlso(left, right);
        target.QueryFilter = Expression.Lambda(body, parameter);
    }
}

```

This is a non generic method which combines the exiting filter with passed filter using `AndAlso` (C# `&&`) operator and shows the aforementioned lambda expression combining principles.


However it's not so useful directly, like inside your entity type configuration loop (it can, but requires you to build manually the lambda expression instead of letting C# compiler do that). So here comes the second method:



```
public static void AddQueryFilter<T>(this IMutableEntityType target, Expression<Func<T, bool>> filter)
{
    LambdaExpression targetFilter = filter;
    if (target.ClrType != typeof(T))
    {
        var parameter = Expression.Parameter(target.ClrType, "e");
        var body = filter.Body.ReplaceParameter(filter.Parameters[0], parameter);
        targetFilter = Expression.Lambda(body, parameter);
    }
    target.AddQueryFilter(targetFilter);
}

```

It's a generic method - not quite type-safe, but allows you to use a compile time lambda expression and bind it to the actual entity type as follows:



```
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
    if (typeof(IDeleted).IsAssignableFrom(entityType.ClrType))
        entityType.AddQueryFilter<IDeleted>(e => e.DateTimeDeleted == null);
}

```

Looks better, isn't it :)


The last custom extension method is complement to (replacement of) the standard EF Core generic [`HasQueryFilter`](https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.metadata.builders.entitytypebuilder-1.hasqueryfilter?view=efcore-2.1#Microsoft_EntityFrameworkCore_Metadata_Builders_EntityTypeBuilder_1_HasQueryFilter_System_Linq_Expressions_Expression_System_Func__0_System_Boolean___) method:



```
public static EntityTypeBuilder<TEntity> AddQueryFilter<TEntity>(this EntityTypeBuilder<TEntity> target, Expression<Func<TEntity, bool>> filter)
    where TEntity : class
{
    target.Metadata.AddQueryFilter(filter);
    return target;
}

```

and allows you to replace



```
this.AddToDict<DbMyEntity>(t => t.Name == null || t.Name == "Something");

```

with the more convenient



```
modelBuilder.Entity<DbMyEntity>()
    .AddQueryFilter(t => t.Name == null || t.Name == "Something");

```

**Update (EF Core 3.0):** `QueryFilter` property has been replaced with `GetQueryFilter` and `SetQueryFilter` extension methods. It doesn't matter what code editor you use for your website, it depends upon the language you use. Visual Studio is good enough for C, C++, C#, Visual Basic, ASP.net, etc. It isn't good for php.


It makes the work of a programmer easier with all its embedded features. it is an design based code editor. That is why I like it. Dreamweaver on the other hand, gives me a chance to learn the codes thoroughly, since it does not come with ready made help plugins and designing features as such.