Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use JS Isolation (use Js as a module) #21

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions BlazorDB.sln
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31213.239
# Visual Studio Version 17
VisualStudioVersion = 17.4.33403.182
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlazorDB", "src\BlazorDB\BlazorDB.csproj", "{D0180843-D92A-44B7-9893-F2450415F208}"
EndProject
Expand Down
25 changes: 10 additions & 15 deletions example/BlazorDB.Example/BlazorDB.Example.csproj
Original file line number Diff line number Diff line change
@@ -1,21 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<RazorLangVersion>3.0</RazorLangVersion>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<None Include="..\..\src\BlazorDB\wwwroot\blazorDB.js" Link="wwwroot\blazorDB.js">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="3.2.0-rc1.20223.4" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Build" Version="3.2.0-rc1.20223.4" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="3.2.0-rc1.20223.4" PrivateAssets="all" />
<PackageReference Include="System.Net.Http.Json" Version="3.2.0-rc1.20217.1" />
<PackageReference Include="Microsoft.AspNetCore.Components.Web" Version="6.0.13" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="6.0.13" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="6.0.13" PrivateAssets="all" />
<PackageReference Include="System.Net.Http.Json" Version="6.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
89 changes: 38 additions & 51 deletions example/BlazorDB.Example/Program.cs
Original file line number Diff line number Diff line change
@@ -1,57 +1,44 @@
using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text;
using BlazorDB;
using BlazorDB.Example;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace BlazorDB.Example
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddBlazorDB(options =>
{
public class Program
options.Name = "Test";
options.Version = 1;
options.StoreSchemas = new List<StoreSchema>()
{
public static async Task Main(string[] args)
new StoreSchema()
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");

builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddBlazorDB(options =>
{
options.Name = "Test";
options.Version = 1;
options.StoreSchemas = new List<StoreSchema>()
{
new StoreSchema()
{
Name = "Person",
PrimaryKey = "id",
PrimaryKeyAuto = true,
UniqueIndexes = new List<string> { "guid" },
Indexes = new List<string> { "name" }
}
};
});
builder.Services.AddBlazorDB(options =>
{
options.Name = "Test2";
options.Version = 1;
options.StoreSchemas = new List<StoreSchema>()
{
new StoreSchema()
{
Name = "Item",
PrimaryKey = "id",
PrimaryKeyAuto = true,
UniqueIndexes = new List<string> { "guid" },
Indexes = new List<string> { "name" }
}
};
});

await builder.Build().RunAsync();
Name = "Person",
PrimaryKey = "id",
PrimaryKeyAuto = true,
UniqueIndexes = new List<string> { "guid" },
Indexes = new List<string> { "name" }
}
};
});
builder.Services.AddBlazorDB(options =>
{
options.Name = "Test2";
options.Version = 1;
options.StoreSchemas = new List<StoreSchema>()
{
new StoreSchema()
{
Name = "Item",
PrimaryKey = "id",
PrimaryKeyAuto = true,
UniqueIndexes = new List<string> { "guid" },
Indexes = new List<string> { "name" }
}
}
}
};
});

await builder.Build().RunAsync();
1 change: 0 additions & 1 deletion example/BlazorDB.Example/wwwroot/dexie.min.js

This file was deleted.

6 changes: 2 additions & 4 deletions example/BlazorDB.Example/wwwroot/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>BlazorDB.Example</title>
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />
<link href="./css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="./css/app.css" rel="stylesheet" />
</head>

<body>
Expand All @@ -19,8 +19,6 @@
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.webassembly.js"></script>
<script src="dexie.min.js"></script>
<script src="blazorDB.js"></script>
</body>

</html>
8 changes: 4 additions & 4 deletions src/BlazorDB/BlazorDB.csproj
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk.Razor">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
<OutputType>Library</OutputType>
<IsPackable>true</IsPackable>
<RazorLangVersion>3.0</RazorLangVersion>
<RazorLangVersion>6.0</RazorLangVersion>
<LangVersion>Latest</LangVersion>
<AssemblyName>BlazorDB</AssemblyName>
<Version>$(Version)</Version>
Expand All @@ -21,8 +21,8 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.Browser" Version="3.0.0-preview6.19307.2" />
<PackageReference Include="Microsoft.JSInterop" Version="3.1.4" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="6.0.13" />
<PackageReference Include="System.Net.Http.Json" Version="6.0.0" />
</ItemGroup>

</Project>
37 changes: 21 additions & 16 deletions src/BlazorDB/IndexDbManager.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using Microsoft.JSInterop;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.JSInterop;

namespace BlazorDB
{
Expand All @@ -10,9 +10,10 @@ namespace BlazorDB
/// </summary>
public class IndexedDbManager
{
readonly Lazy<Task<IJSObjectReference>> _jsModuleTask;
readonly DbStore _dbStore;
readonly IJSRuntime _jsRuntime;
const string InteropPrefix = "window.blazorDB";
const string InteropPrefix = "blazorDB";
DotNetObjectReference<IndexedDbManager> _objReference;
IDictionary<Guid, WeakReference<Action<BlazorDbEvent>>> _transactions = new Dictionary<Guid, WeakReference<Action<BlazorDbEvent>>>();
IDictionary<Guid, TaskCompletionSource<BlazorDbEvent>> _taskTransactions = new Dictionary<Guid, TaskCompletionSource<BlazorDbEvent>>();
Expand All @@ -32,12 +33,14 @@ internal IndexedDbManager(DbStore dbStore, IJSRuntime jsRuntime)
_objReference = DotNetObjectReference.Create(this);
_dbStore = dbStore;
_jsRuntime = jsRuntime;
_jsModuleTask = new(() => _jsRuntime.InvokeAsync<IJSObjectReference>(
"import", "./_content/BlazorIndexedDB/blazorDB.js").AsTask());
}

public List<StoreSchema> Stores => _dbStore.StoreSchemas;
public int CurrentVersion => _dbStore.Version;
public string DbName => _dbStore.Name;

/// <summary>
/// Opens the IndexedDB defined in the DbStore. Under the covers will create the database if it does not exist
/// and create the stores defined in DbStore.
Expand Down Expand Up @@ -304,7 +307,7 @@ public async Task<IList<TRecord>> Where<TRecord>(string storeName, IEnumerable<I
try
{

return await CallJavascript<IList<TRecord>>(IndexedDbFunctions.WHERE, trans, DbName, storeName, filters);
return await CallJavascript<IList<TRecord>>(IndexedDbFunctions.WHERE, trans, DbName, storeName, filters);
}
catch (JSException jse)
{
Expand All @@ -313,7 +316,7 @@ public async Task<IList<TRecord>> Where<TRecord>(string storeName, IEnumerable<I

return default;
}

/// <summary>
/// Retrieve all the records in a store
/// </summary>
Expand All @@ -335,7 +338,7 @@ public async Task<IList<TRecord>> ToArray<TRecord>(string storeName)

return default;
}

/// <summary>
/// Deletes a record from the store based on the id
/// </summary>
Expand Down Expand Up @@ -424,13 +427,13 @@ public async Task<BlazorDbEvent> ClearTableAsync(string storeName)
[JSInvokable("BlazorDBCallback")]
public void CalledFromJS(Guid transaction, bool failed, string message)
{
if(transaction != Guid.Empty)
if (transaction != Guid.Empty)
{
WeakReference<Action<BlazorDbEvent>> r = null;
_transactions.TryGetValue(transaction, out r);
TaskCompletionSource<BlazorDbEvent> t = null;
_taskTransactions.TryGetValue(transaction, out t);
if(r != null && r.TryGetTarget(out Action<BlazorDbEvent> action))
if (r != null && r.TryGetTarget(out Action<BlazorDbEvent> action))
{
action?.Invoke(new BlazorDbEvent()
{
Expand All @@ -440,7 +443,7 @@ public void CalledFromJS(Guid transaction, bool failed, string message)
});
_transactions.Remove(transaction);
}
else if(t != null)
else if (t != null)
{
t.TrySetResult(new BlazorDbEvent()
{
Expand All @@ -457,21 +460,23 @@ public void CalledFromJS(Guid transaction, bool failed, string message)

async Task<TResult> CallJavascript<TResult>(string functionName, Guid transaction, params object[] args)
{
var _jsModuleReference = await _jsModuleTask.Value;
var newArgs = GetNewArgs(transaction, args);
return await _jsRuntime.InvokeAsync<TResult>($"{InteropPrefix}.{functionName}", newArgs);
return await _jsModuleReference.InvokeAsync<TResult>($"{InteropPrefix}.{functionName}", newArgs);
}
async Task CallJavascriptVoid(string functionName, Guid transaction, params object[] args)
{
var _jsModuleReference = await _jsModuleTask.Value;
var newArgs = GetNewArgs(transaction, args);
await _jsRuntime.InvokeVoidAsync($"{InteropPrefix}.{functionName}", newArgs);
await _jsModuleReference.InvokeVoidAsync($"{InteropPrefix}.{functionName}", newArgs);
}

object[] GetNewArgs(Guid transaction, params object[] args)
{
var newArgs = new object[args.Length + 2];
newArgs[0] = _objReference;
newArgs[1] = transaction;
for(var i = 0; i < args.Length; i++)
for (var i = 0; i < args.Length; i++)
newArgs[i + 2] = args[i];
return newArgs;
}
Expand All @@ -484,12 +489,12 @@ object[] GetNewArgs(Guid transaction, params object[] args)
do
{
transaction = Guid.NewGuid();
if(!_taskTransactions.ContainsKey(transaction))
if (!_taskTransactions.ContainsKey(transaction))
{
generated = true;
_taskTransactions.Add(transaction, tcs);
}
} while(!generated);
} while (!generated);
return (transaction, tcs.Task);
}

Expand All @@ -500,12 +505,12 @@ Guid GenerateTransaction(Action<BlazorDbEvent> action)
do
{
transaction = Guid.NewGuid();
if(!_transactions.ContainsKey(transaction))
if (!_transactions.ContainsKey(transaction))
{
generated = true;
_transactions.Add(transaction, new WeakReference<Action<BlazorDbEvent>>(action));
}
} while(!generated);
} while (!generated);
return transaction;
}

Expand Down
Loading