diff --git a/.vs/MoralisDotNetSdk/DesignTimeBuild/.dtbcache.v2 b/.vs/MoralisDotNetSdk/DesignTimeBuild/.dtbcache.v2 index c50fa15..41395fa 100644 Binary files a/.vs/MoralisDotNetSdk/DesignTimeBuild/.dtbcache.v2 and b/.vs/MoralisDotNetSdk/DesignTimeBuild/.dtbcache.v2 differ diff --git a/.vs/MoralisDotNetSdk/v17/.futdcache.v1 b/.vs/MoralisDotNetSdk/v17/.futdcache.v1 index 900da95..1427329 100644 Binary files a/.vs/MoralisDotNetSdk/v17/.futdcache.v1 and b/.vs/MoralisDotNetSdk/v17/.futdcache.v1 differ diff --git a/Moralis.AuthApi.Integrated.Tests/NewtonsoftJsonSerializer.cs b/Moralis.AuthApi.Integrated.Tests/NewtonsoftJsonSerializer.cs index b084c85..b93d97e 100644 --- a/Moralis.AuthApi.Integrated.Tests/NewtonsoftJsonSerializer.cs +++ b/Moralis.AuthApi.Integrated.Tests/NewtonsoftJsonSerializer.cs @@ -1,85 +1,85 @@ -using Moralis.Platform.Abstractions; -using System; -using System.Collections.Generic; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using System.Runtime.Serialization; -using System.Globalization; +//using Moralis.Platform.Abstractions; +//using System; +//using System.Collections.Generic; +//using Newtonsoft.Json; +//using Newtonsoft.Json.Serialization; +//using System.Runtime.Serialization; +//using System.Globalization; -namespace Moralis.AuthApi.Integrated.Tests -{ - public class NewtonsoftJsonSerializer : IJsonSerializer - { - public IDictionary DefaultOptions { get; set; } +//namespace Moralis.AuthApi.Integrated.Tests +//{ +// public class NewtonsoftJsonSerializer : IJsonSerializer +// { +// public IDictionary DefaultOptions { get; set; } - public NewtonsoftJsonSerializer() - { - DefaultOptions = new Dictionary(); - DefaultOptions.Add("NullValueHandling", NullValueHandling.Ignore); - DefaultOptions.Add("ReferenceLoopHandling", ReferenceLoopHandling.Serialize); - DefaultOptions.Add("DateFormatString", "yyyy-MM-ddTHH:mm:ss.fffZ"); - } +// public NewtonsoftJsonSerializer() +// { +// DefaultOptions = new Dictionary(); +// DefaultOptions.Add("NullValueHandling", NullValueHandling.Ignore); +// DefaultOptions.Add("ReferenceLoopHandling", ReferenceLoopHandling.Serialize); +// DefaultOptions.Add("DateFormatString", "yyyy-MM-ddTHH:mm:ss.fffZ"); +// } - public T Deserialize(string json, IDictionary options = null) - { - if (options is { }) - { - return JsonConvert.DeserializeObject(json, OptionsToSettings(options)); - } - else - { - return JsonConvert.DeserializeObject(json); - } - } +// public T Deserialize(string json, IDictionary options = null) +// { +// if (options is { }) +// { +// return JsonConvert.DeserializeObject(json, OptionsToSettings(options)); +// } +// else +// { +// return JsonConvert.DeserializeObject(json); +// } +// } - public string Serialize(object target, IDictionary options = null) - { - if (options is { }) - { - return JsonConvert.SerializeObject(target, OptionsToSettings(options)); - } - else - { - return JsonConvert.SerializeObject(target); - } - } +// public string Serialize(object target, IDictionary options = null) +// { +// if (options is { }) +// { +// return JsonConvert.SerializeObject(target, OptionsToSettings(options)); +// } +// else +// { +// return JsonConvert.SerializeObject(target); +// } +// } - private JsonSerializerSettings OptionsToSettings(IDictionary options) - { - JsonSerializerSettings settings = new JsonSerializerSettings() - { - //CheckAdditionalContent = options.ContainsKey("CheckAdditionalContent") ? (bool)options["CheckAdditionalContent"] : false, - //ConstructorHandling = options.ContainsKey("ConstructorHandling") ? (ConstructorHandling)options["ConstructorHandling"] : ConstructorHandling.Default, - //Context = options.ContainsKey("Context") ? (StreamingContext)options["Context"] : new StreamingContext(), - //ContractResolver = options.ContainsKey("ContractResolver") ? (IContractResolver)options["ContractResolver"] : null, - //Converters = options.ContainsKey("Converters") ? (List)options["Converters"] : null, - //Culture = options.ContainsKey("Culture") ? (CultureInfo)options["Culture"] : null, - //DateFormatHandling = options.ContainsKey("DateFormatHandling") ? (DateFormatHandling)options["DateFormatHandling"] : DateFormatHandling.IsoDateFormat, - DateFormatString = options.ContainsKey("DateFormatString") ? (string)options["DateFormatString"] : null, - //DateParseHandling = options.ContainsKey("DateParseHandling") ? (DateParseHandling)options["DateParseHandling"] : DateParseHandling.DateTime, - //DateTimeZoneHandling = options.ContainsKey("DateTimeZoneHandling") ? (DateTimeZoneHandling)options["DateTimeZoneHandling"] : DateTimeZoneHandling.Utc, - //DefaultValueHandling = options.ContainsKey("DefaultValueHandling") ? (DefaultValueHandling)options["DefaultValueHandling"] : DefaultValueHandling.Ignore, - //Error = options.ContainsKey("Error") ? (EventHandler)options["Error"] : null, - //FloatFormatHandling = options.ContainsKey("FloatFormatHandling") ? (FloatFormatHandling)options["FloatFormatHandling"] : FloatFormatHandling.DefaultValue, - //FloatParseHandling = options.ContainsKey("FloatParseHandling") ? (FloatParseHandling)options["FloatParseHandling"] : FloatParseHandling.Double, - //Formatting = options.ContainsKey("Formatting") ? (Formatting)options["Formatting"] : Formatting.None, - //MaxDepth = options.ContainsKey("MaxDepth") ? (int?)options["MaxDepth"] : null, - //MetadataPropertyHandling = options.ContainsKey("MetadataPropertyHandling") ? (MetadataPropertyHandling)options["MetadataPropertyHandling"] : MetadataPropertyHandling.Default, - //MissingMemberHandling = options.ContainsKey("MissingMemberHandling") ? (MissingMemberHandling)options["MissingMemberHandling"] : MissingMemberHandling.Ignore, - NullValueHandling = options.ContainsKey("NullValueHandling") ? (NullValueHandling)options["NullValueHandling"] : NullValueHandling.Ignore, - //ObjectCreationHandling = options.ContainsKey("ObjectCreationHandling") ? (ObjectCreationHandling)options["ObjectCreationHandling"] : ObjectCreationHandling.Auto, - //PreserveReferencesHandling = options.ContainsKey("PreserveReferencesHandling") ? (PreserveReferencesHandling)options["PreserveReferencesHandling"] : PreserveReferencesHandling.None, - ReferenceLoopHandling = options.ContainsKey("ReferenceLoopHandling") ? (ReferenceLoopHandling)options["ReferenceLoopHandling"] : ReferenceLoopHandling.Ignore, - //ReferenceResolverProvider = options.ContainsKey("ReferenceResolverProvider") ? (Func)options["ReferenceResolverProvider"] : null, - //SerializationBinder = options.ContainsKey("SerializationBinder") ? (ISerializationBinder)options["SerializationBinder"] : null, - //StringEscapeHandling = options.ContainsKey("StringEscapeHandling") ? (StringEscapeHandling)options["StringEscapeHandling"] : StringEscapeHandling.Default, - //TraceWriter = options.ContainsKey("TraceWriter") ? (ITraceWriter)options["TraceWriter"] : null, - //TypeNameAssemblyFormatHandling = options.ContainsKey("TypeNameAssemblyFormatHandling") ? (TypeNameAssemblyFormatHandling)options["TypeNameAssemblyFormatHandling"] : TypeNameAssemblyFormatHandling.Full, - //TypeNameHandling = options.ContainsKey("TypeNameHandling") ? (TypeNameHandling)options["TypeNameHandling"] : TypeNameHandling.None - }; +// private JsonSerializerSettings OptionsToSettings(IDictionary options) +// { +// JsonSerializerSettings settings = new JsonSerializerSettings() +// { +// //CheckAdditionalContent = options.ContainsKey("CheckAdditionalContent") ? (bool)options["CheckAdditionalContent"] : false, +// //ConstructorHandling = options.ContainsKey("ConstructorHandling") ? (ConstructorHandling)options["ConstructorHandling"] : ConstructorHandling.Default, +// //Context = options.ContainsKey("Context") ? (StreamingContext)options["Context"] : new StreamingContext(), +// //ContractResolver = options.ContainsKey("ContractResolver") ? (IContractResolver)options["ContractResolver"] : null, +// //Converters = options.ContainsKey("Converters") ? (List)options["Converters"] : null, +// //Culture = options.ContainsKey("Culture") ? (CultureInfo)options["Culture"] : null, +// //DateFormatHandling = options.ContainsKey("DateFormatHandling") ? (DateFormatHandling)options["DateFormatHandling"] : DateFormatHandling.IsoDateFormat, +// DateFormatString = options.ContainsKey("DateFormatString") ? (string)options["DateFormatString"] : null, +// //DateParseHandling = options.ContainsKey("DateParseHandling") ? (DateParseHandling)options["DateParseHandling"] : DateParseHandling.DateTime, +// //DateTimeZoneHandling = options.ContainsKey("DateTimeZoneHandling") ? (DateTimeZoneHandling)options["DateTimeZoneHandling"] : DateTimeZoneHandling.Utc, +// //DefaultValueHandling = options.ContainsKey("DefaultValueHandling") ? (DefaultValueHandling)options["DefaultValueHandling"] : DefaultValueHandling.Ignore, +// //Error = options.ContainsKey("Error") ? (EventHandler)options["Error"] : null, +// //FloatFormatHandling = options.ContainsKey("FloatFormatHandling") ? (FloatFormatHandling)options["FloatFormatHandling"] : FloatFormatHandling.DefaultValue, +// //FloatParseHandling = options.ContainsKey("FloatParseHandling") ? (FloatParseHandling)options["FloatParseHandling"] : FloatParseHandling.Double, +// //Formatting = options.ContainsKey("Formatting") ? (Formatting)options["Formatting"] : Formatting.None, +// //MaxDepth = options.ContainsKey("MaxDepth") ? (int?)options["MaxDepth"] : null, +// //MetadataPropertyHandling = options.ContainsKey("MetadataPropertyHandling") ? (MetadataPropertyHandling)options["MetadataPropertyHandling"] : MetadataPropertyHandling.Default, +// //MissingMemberHandling = options.ContainsKey("MissingMemberHandling") ? (MissingMemberHandling)options["MissingMemberHandling"] : MissingMemberHandling.Ignore, +// NullValueHandling = options.ContainsKey("NullValueHandling") ? (NullValueHandling)options["NullValueHandling"] : NullValueHandling.Ignore, +// //ObjectCreationHandling = options.ContainsKey("ObjectCreationHandling") ? (ObjectCreationHandling)options["ObjectCreationHandling"] : ObjectCreationHandling.Auto, +// //PreserveReferencesHandling = options.ContainsKey("PreserveReferencesHandling") ? (PreserveReferencesHandling)options["PreserveReferencesHandling"] : PreserveReferencesHandling.None, +// ReferenceLoopHandling = options.ContainsKey("ReferenceLoopHandling") ? (ReferenceLoopHandling)options["ReferenceLoopHandling"] : ReferenceLoopHandling.Ignore, +// //ReferenceResolverProvider = options.ContainsKey("ReferenceResolverProvider") ? (Func)options["ReferenceResolverProvider"] : null, +// //SerializationBinder = options.ContainsKey("SerializationBinder") ? (ISerializationBinder)options["SerializationBinder"] : null, +// //StringEscapeHandling = options.ContainsKey("StringEscapeHandling") ? (StringEscapeHandling)options["StringEscapeHandling"] : StringEscapeHandling.Default, +// //TraceWriter = options.ContainsKey("TraceWriter") ? (ITraceWriter)options["TraceWriter"] : null, +// //TypeNameAssemblyFormatHandling = options.ContainsKey("TypeNameAssemblyFormatHandling") ? (TypeNameAssemblyFormatHandling)options["TypeNameAssemblyFormatHandling"] : TypeNameAssemblyFormatHandling.Full, +// //TypeNameHandling = options.ContainsKey("TypeNameHandling") ? (TypeNameHandling)options["TypeNameHandling"] : TypeNameHandling.None +// }; - return settings; - } - } +// return settings; +// } +// } -} +//} diff --git a/Moralis.AuthApi.Integrated.Tests/Program.cs b/Moralis.AuthApi.Integrated.Tests/Program.cs index e88521f..8fd65c9 100644 --- a/Moralis.AuthApi.Integrated.Tests/Program.cs +++ b/Moralis.AuthApi.Integrated.Tests/Program.cs @@ -3,7 +3,8 @@ using System.Threading.Tasks; using Moralis; using Moralis.AuthApi.Client; -using Moralis.Platform; +using Moralis.AuthApi.Interfaces; +using Moralis.Models; namespace Moralis.AuthApi.Integrated.Tests { @@ -13,23 +14,25 @@ static void Main(string[] args) { List testGroups = TestGroups(); + MoralisClient.ConnectionData = new ServerConnectionData() + { + AuthenticationApiUrl = "https://auth-api.do-prod-1.moralis.io/", + ApplicationID = "foCDSL08ibUWfLHunP6RrCxPGKE6HpwYiiLa5QPV", + DappUrl = "https://ltvaqg1whdgl.usemoralis.com:2053/server", + ApiKey = "1kXrzei19HNrb3YvkLaBbOAuRo6SGcmGqmlZ2E6FYFZ2QnqO46rn3xsAX6eRMBns", + MasterKey = "RU70zK1m50qEuaLNHBTM2PlqOQ7OzYuVeImcMq4w" + }; + foreach (IIntegratedTest test in testGroups) { - ServerConnectionData connectionData = new ServerConnectionData() - { - AuthenticationApiUrl = "https://auth-api.do-prod-1.moralis.io/", - ApplicationID = "APP_ID", - ServerURI = "http://www.moralis.io" - }; - - //MoralisClient.Initialize("https://auth-api.do-prod-1.moralis.io/"); - Moralis.MoralisClient client = new Moralis.MoralisClient(connectionData,null,null,new NewtonsoftJsonSerializer(), new AuthApiClient()); string addr = "0xBa878d88c71E0091613798C53B6c72aDd9b9A6a7"; Console.WriteLine($"Executing test set: {test.GetType().Name} ...\n-----------------------------------------"); + IAuthClientApi authClient = MoralisClient.AuthenticationApi; + Task testTask = - Task.Run(() => test.RunTests(client.AuthenticationApi, addr)); + Task.Run(() => test.RunTests(authClient, addr)); testTask.Wait(); diff --git a/Moralis.Platform.Integrated.Tests/CreateObjectTests.cs b/Moralis.Platform.Integrated.Tests/CreateObjectTests.cs deleted file mode 100644 index e366213..0000000 --- a/Moralis.Platform.Integrated.Tests/CreateObjectTests.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace Moralis.Platform.Integrated.Tests -{ - class CreateObjectTests : IIntegratedTest - { - - private IntegratedTestResult testResults; - public async Task RunTests(MoralisClient moralisClient) - { - testResults = new IntegratedTestResult(); - - Console.WriteLine("Running test CreateHero"); - - if (await CreateHero(moralisClient)) - { - testResults.PassedTests.Add("CreateHero", "PASSED"); - } - else - { - testResults.FailedTests.Add("CreateHero", "FAILED"); - Console.WriteLine("\tFAILED"); - } - - return testResults; - } - - private async Task CreateHero(MoralisClient moralisClient) - { - bool result = true; - - try - { - Hero h1 = moralisClient.Create(); - h1.Name = GetTestName(); - - System.Random rand = new System.Random((int)DateTime.Now.Ticks); - h1.Strength = rand.Next(20) + 3; - h1.Level = rand.Next(10) + 1; - h1.Warcry = "Decaf is a lie!"; - - await h1.SaveAsync(); - } - catch (Exception exp) - { - result = false; - } - - return result; - } - - private static string GetTestName() - { - string[] names = { "Clem the Great", "Sion the Bold", "Bob", "D@ve", "Oogmar the Deft", "Alesdair the Blessed", "Seviel the Mighty", "Master Adept Xactant", "Semaphore the Beautiful", "Gamemaster Nexnang" }; - - System.Random rand = new System.Random((int)DateTime.Now.Ticks); - - int x = rand.Next(names.Length); - - return names[x]; - } - } -} diff --git a/Moralis.Platform.Integrated.Tests/Hero.cs b/Moralis.Platform.Integrated.Tests/Hero.cs deleted file mode 100644 index 2a1081e..0000000 --- a/Moralis.Platform.Integrated.Tests/Hero.cs +++ /dev/null @@ -1,25 +0,0 @@ -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Integrated.Tests -{ - internal class Hero : MoralisObject - { - public Hero() : base("Hero") - { - Name = String.Empty; - Warcry = String.Empty; - Bag = new List(); - } - - public int Strength { get; set; } - public int Level { get; set; } - public string Name { get; set; } - public string Warcry { get; set; } - public DateTime BirthDay { get; set; } - public List Bag { get; set; } - - public int X { get; set; } - public int Y { get; set; } - public int Z { get; set; } - } -} diff --git a/Moralis.Platform.Integrated.Tests/IIntegratedTest.cs b/Moralis.Platform.Integrated.Tests/IIntegratedTest.cs deleted file mode 100644 index ee1433a..0000000 --- a/Moralis.Platform.Integrated.Tests/IIntegratedTest.cs +++ /dev/null @@ -1,9 +0,0 @@ - - -namespace Moralis.Platform.Integrated.Tests -{ - interface IIntegratedTest - { - Task RunTests(MoralisClient moralisClient); - } -} diff --git a/Moralis.Platform.Integrated.Tests/IntegratedTestResult.cs b/Moralis.Platform.Integrated.Tests/IntegratedTestResult.cs deleted file mode 100644 index fd0de0a..0000000 --- a/Moralis.Platform.Integrated.Tests/IntegratedTestResult.cs +++ /dev/null @@ -1,20 +0,0 @@ - -namespace Moralis.Platform.Integrated.Tests -{ - class IntegratedTestResult - { - - public IDictionary FailedTests { get; set; } - public IDictionary PassedTests { get; set; } - - public IntegratedTestResult() - { - FailedTests = new Dictionary(); - PassedTests = new Dictionary(); - } - - public bool HasFailedTests() => FailedTests.Count > 0; - - public int TestCount() => FailedTests.Count + PassedTests.Count; - } -} diff --git a/Moralis.Platform.Integrated.Tests/LiveQueryTests.cs b/Moralis.Platform.Integrated.Tests/LiveQueryTests.cs deleted file mode 100644 index 6816ebe..0000000 --- a/Moralis.Platform.Integrated.Tests/LiveQueryTests.cs +++ /dev/null @@ -1,151 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Moralis; -using Moralis.Platform.Objects; -using Moralis.Platform.Queries; -using Moralis.Platform.Queries.Live; -using Moralis.Platform.Services.ClientServices; - -namespace Moralis.Platform.Integrated.Tests -{ - class LiveQueryTests : IIntegratedTest - { - private IntegratedTestResult testResults; - - int OnConnectedEventCounter = 0; - int OnSubscribedEventCounter = 0; - int OnUnsubscribedEventCounter = 0; - int OnErrorEventCounter = 0; - int OnCreateEventCounter = 0; - int OnUpdateEventCounter = 0; - int OnDeleteEventCounter = 0; - - public async Task RunTests(MoralisClient moralisClient) - { - testResults = new IntegratedTestResult(); - - Console.WriteLine("Running test TestLiveQuery"); - - if (await TestLiveQuery(moralisClient)) - { - testResults.PassedTests.Add("TestLiveQuery", "PASSED"); - } - else - { - testResults.FailedTests.Add("TestLiveQuery", "FAILED"); - Console.WriteLine("\tFAILED"); - } - - return testResults; - } - - public async Task TestLiveQuery(MoralisClient moralisClient) - { - bool result = true; - - try - { - var moralisQueryPlayerData = await moralisClient.Query(); - - // Setup subscription - MoralisLiveQueryCallbacks callbacks = setupLiveQuerySubscription(moralisQueryPlayerData); - MoralisLiveQueryClient lqc = moralisQueryPlayerData.Subscribe(callbacks); - - Thread.Sleep(2000); - - System.Random rand = new System.Random((int)DateTime.Now.Ticks); - - int x = rand.Next(25) + 3; - - PlayerData p1 = moralisClient.Create(); - p1.Name = GetTestName(); - p1.TokenCount = x; - await p1.SaveAsync(); - - x = rand.Next(25) + 3; - - PlayerData p2 = moralisClient.Create(); - p2.Name = GetTestName(); - p2.TokenCount = x; - await p2.SaveAsync(); - - // Get the records created - IEnumerable recs = await moralisQueryPlayerData.FindAsync(); - - // Update data - foreach (PlayerData pd in recs) - { - x = rand.Next(25) + 3; - pd.TokenCount = x; - await pd.SaveAsync(); - } - - // Get the records created - recs = await moralisQueryPlayerData.FindAsync(); - - // Delete data - foreach (PlayerData pd in recs) - { - await pd.DeleteAsync(); - } - - if (OnConnectedEventCounter != 1) result = false; - else if (OnSubscribedEventCounter != 1) result = false; - else if (OnErrorEventCounter != 0) result = false; - else if (OnCreateEventCounter != 2) result = false; - else if (OnUpdateEventCounter != 2) result = false; - else if (OnDeleteEventCounter != 2) result = false; - } - catch (Exception exp) - { - result = false; - } - - return result; - - } - - private MoralisLiveQueryCallbacks setupLiveQuerySubscription(MoralisQuery playerData) - { - MoralisLiveQueryCallbacks moralisLiveQueryCallbacks = new MoralisLiveQueryCallbacks(); - - moralisLiveQueryCallbacks.OnConnectedEvent += (() => { OnConnectedEventCounter++; }); - moralisLiveQueryCallbacks.OnSubscribedEvent += ((requestId) => { OnSubscribedEventCounter++; }); - moralisLiveQueryCallbacks.OnUnsubscribedEvent += ((requestId) => { OnUnsubscribedEventCounter++; }); - moralisLiveQueryCallbacks.OnErrorEvent += ((ErrorMessage em) => - { - OnErrorEventCounter++; - }); - moralisLiveQueryCallbacks.OnCreateEvent += ((item, requestId) => - { - OnCreateEventCounter++; - }); - moralisLiveQueryCallbacks.OnUpdateEvent += ((item, requestId) => - { - OnUpdateEventCounter++; - }); - moralisLiveQueryCallbacks.OnDeleteEvent += ((item, requestId) => - { - OnDeleteEventCounter++; - }); - - return moralisLiveQueryCallbacks; - } - - private static string GetTestName() - { - string[] names = { "Clem the Great", "Sion the Bold", "Bob", "D@ve", "Oogmar the Deft", "Alesdair the Blessed", "Seviel the Mighty", "Master Adept Xactant", "Semaphore the Beautiful", "Gamemaster Nexnang" }; - - System.Random rand = new System.Random((int)DateTime.Now.Ticks); - - int x = rand.Next(names.Length); - - x = rand.Next(names.Length); - - return names[x]; - } - } -} diff --git a/Moralis.Platform.Integrated.Tests/NewtonsoftJsonSerializer.cs b/Moralis.Platform.Integrated.Tests/NewtonsoftJsonSerializer.cs deleted file mode 100644 index 283cb93..0000000 --- a/Moralis.Platform.Integrated.Tests/NewtonsoftJsonSerializer.cs +++ /dev/null @@ -1,85 +0,0 @@ -using Moralis.Platform.Abstractions; -using System; -using System.Collections.Generic; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using System.Runtime.Serialization; -using System.Globalization; - -namespace Moralis.Platform.Integrated.Tests -{ - public class NewtonsoftJsonSerializer : IJsonSerializer - { - public IDictionary DefaultOptions { get; set; } - - public NewtonsoftJsonSerializer() - { - DefaultOptions = new Dictionary(); - DefaultOptions.Add("NullValueHandling", NullValueHandling.Ignore); - DefaultOptions.Add("ReferenceLoopHandling", ReferenceLoopHandling.Serialize); - DefaultOptions.Add("DateFormatString", "yyyy-MM-ddTHH:mm:ss.fffZ"); - } - - public T Deserialize(string json, IDictionary options = null) - { - if (options is { }) - { - return JsonConvert.DeserializeObject(json, OptionsToSettings(options)); - } - else - { - return JsonConvert.DeserializeObject(json); - } - } - - public string Serialize(object target, IDictionary options = null) - { - if (options is { }) - { - return JsonConvert.SerializeObject(target, OptionsToSettings(options)); - } - else - { - return JsonConvert.SerializeObject(target); - } - } - - private JsonSerializerSettings OptionsToSettings(IDictionary options) - { - JsonSerializerSettings settings = new JsonSerializerSettings() - { - //CheckAdditionalContent = options.ContainsKey("CheckAdditionalContent") ? (bool)options["CheckAdditionalContent"] : false, - //ConstructorHandling = options.ContainsKey("ConstructorHandling") ? (ConstructorHandling)options["ConstructorHandling"] : ConstructorHandling.Default, - //Context = options.ContainsKey("Context") ? (StreamingContext)options["Context"] : new StreamingContext(), - //ContractResolver = options.ContainsKey("ContractResolver") ? (IContractResolver)options["ContractResolver"] : null, - //Converters = options.ContainsKey("Converters") ? (List)options["Converters"] : null, - //Culture = options.ContainsKey("Culture") ? (CultureInfo)options["Culture"] : null, - //DateFormatHandling = options.ContainsKey("DateFormatHandling") ? (DateFormatHandling)options["DateFormatHandling"] : DateFormatHandling.IsoDateFormat, - DateFormatString = options.ContainsKey("DateFormatString") ? (string)options["DateFormatString"] : null, - //DateParseHandling = options.ContainsKey("DateParseHandling") ? (DateParseHandling)options["DateParseHandling"] : DateParseHandling.DateTime, - //DateTimeZoneHandling = options.ContainsKey("DateTimeZoneHandling") ? (DateTimeZoneHandling)options["DateTimeZoneHandling"] : DateTimeZoneHandling.Utc, - //DefaultValueHandling = options.ContainsKey("DefaultValueHandling") ? (DefaultValueHandling)options["DefaultValueHandling"] : DefaultValueHandling.Ignore, - //Error = options.ContainsKey("Error") ? (EventHandler)options["Error"] : null, - //FloatFormatHandling = options.ContainsKey("FloatFormatHandling") ? (FloatFormatHandling)options["FloatFormatHandling"] : FloatFormatHandling.DefaultValue, - //FloatParseHandling = options.ContainsKey("FloatParseHandling") ? (FloatParseHandling)options["FloatParseHandling"] : FloatParseHandling.Double, - //Formatting = options.ContainsKey("Formatting") ? (Formatting)options["Formatting"] : Formatting.None, - //MaxDepth = options.ContainsKey("MaxDepth") ? (int?)options["MaxDepth"] : null, - //MetadataPropertyHandling = options.ContainsKey("MetadataPropertyHandling") ? (MetadataPropertyHandling)options["MetadataPropertyHandling"] : MetadataPropertyHandling.Default, - //MissingMemberHandling = options.ContainsKey("MissingMemberHandling") ? (MissingMemberHandling)options["MissingMemberHandling"] : MissingMemberHandling.Ignore, - NullValueHandling = options.ContainsKey("NullValueHandling") ? (NullValueHandling)options["NullValueHandling"] : NullValueHandling.Ignore, - //ObjectCreationHandling = options.ContainsKey("ObjectCreationHandling") ? (ObjectCreationHandling)options["ObjectCreationHandling"] : ObjectCreationHandling.Auto, - //PreserveReferencesHandling = options.ContainsKey("PreserveReferencesHandling") ? (PreserveReferencesHandling)options["PreserveReferencesHandling"] : PreserveReferencesHandling.None, - ReferenceLoopHandling = options.ContainsKey("ReferenceLoopHandling") ? (ReferenceLoopHandling)options["ReferenceLoopHandling"] : ReferenceLoopHandling.Ignore, - //ReferenceResolverProvider = options.ContainsKey("ReferenceResolverProvider") ? (Func)options["ReferenceResolverProvider"] : null, - //SerializationBinder = options.ContainsKey("SerializationBinder") ? (ISerializationBinder)options["SerializationBinder"] : null, - //StringEscapeHandling = options.ContainsKey("StringEscapeHandling") ? (StringEscapeHandling)options["StringEscapeHandling"] : StringEscapeHandling.Default, - //TraceWriter = options.ContainsKey("TraceWriter") ? (ITraceWriter)options["TraceWriter"] : null, - //TypeNameAssemblyFormatHandling = options.ContainsKey("TypeNameAssemblyFormatHandling") ? (TypeNameAssemblyFormatHandling)options["TypeNameAssemblyFormatHandling"] : TypeNameAssemblyFormatHandling.Full, - //TypeNameHandling = options.ContainsKey("TypeNameHandling") ? (TypeNameHandling)options["TypeNameHandling"] : TypeNameHandling.None - }; - - return settings; - } - } - -} diff --git a/Moralis.Platform.Integrated.Tests/PlayerData.cs b/Moralis.Platform.Integrated.Tests/PlayerData.cs deleted file mode 100644 index ac6fe3b..0000000 --- a/Moralis.Platform.Integrated.Tests/PlayerData.cs +++ /dev/null @@ -1,11 +0,0 @@ -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Integrated.Tests -{ - class PlayerData : MoralisObject - { - public long TokenCount { get; set; } - public string Name { get; set; } - public PlayerData() : base("PlayerData") { } - } -} diff --git a/Moralis.Platform.Integrated.Tests/ProgramTests.cs b/Moralis.Platform.Integrated.Tests/ProgramTests.cs deleted file mode 100644 index d9d38a8..0000000 --- a/Moralis.Platform.Integrated.Tests/ProgramTests.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Moralis; -using Moralis.Platform; -using Moralis.Web3Api.Client; -using Moralis.SolanaApi.Client; - -namespace Moralis.Platform.Integrated.Tests -{ - class ProgramTests - { - static void Main(string[] args) - { - List testGroups = TestGroups(); - - foreach (IIntegratedTest test in testGroups) - { - ServerConnectionData conData = new ServerConnectionData() - { - ApplicationID = "APPLICATION ID", - ServerURI = "SERVER URI", - MasterKey = "SERVER MASTER KEY" - }; - - //MoralisClient.Initialize(true, "1kXrzei19HNrb3YvkLaBbOAuRo6SGcmGqmlZ2E6FYFZ2QnqO46rn3xsAX6eRMBns"); // "https://arw2wxg84h6b.moralishost.com:2053/server"); - MoralisClient moralis = new MoralisClient(conData, new Web3ApiClient(), new SolanaApiClient(), new NewtonsoftJsonSerializer()); - string addr = "0xBa878d88c71E0091613798C53B6c72aDd9b9A6a7".ToLower(); - - Console.WriteLine($"Executing test set: {test.GetType().Name} ...\n-----------------------------------------"); - - Task testTask = - Task.Run(() => test.RunTests(moralis)); - testTask.Wait(); - IntegratedTestResult result = testTask.Result; - - Console.WriteLine($"Tests run: {result.TestCount()}, {result.PassedTests.Count} passed, {result.FailedTests.Count} failed."); - - Console.WriteLine("\n\n"); - } - } - - static List TestGroups() - { - List groups = new List(); - - groups.Add(new CreateObjectTests()); - groups.Add(new QueryTests()); - groups.Add(new LiveQueryTests()); - - return groups; - } - } -} diff --git a/Moralis.Platform.Integrated.Tests/QueryTests.cs b/Moralis.Platform.Integrated.Tests/QueryTests.cs deleted file mode 100644 index 5997567..0000000 --- a/Moralis.Platform.Integrated.Tests/QueryTests.cs +++ /dev/null @@ -1,239 +0,0 @@ -using Moralis.Platform.Queries; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Moralis.Platform.Integrated.Tests -{ - class QueryTests : IIntegratedTest - { - - private IntegratedTestResult testResults; - public async Task RunTests(MoralisClient moralisClient) - { - testResults = new IntegratedTestResult(); - - Console.WriteLine("Please note that these tests require that you have created \n a series of Hero records. If any tests fail please double check \nyour DB for a 'Hero' table with records."); - Console.WriteLine("Additionally, you may need to adjust either tests or yor data to match each other."); - Console.WriteLine("Running test FetchFirstQuery"); - if (await FetchFirstQuery(moralisClient)) - { - testResults.PassedTests.Add("FetchFirstQuery", "PASSED"); - } - else - { - testResults.FailedTests.Add("FetchFirstQuery", "FAILED"); - Console.WriteLine("\tFAILED"); - } - - await Task.Delay(250); - - Console.WriteLine("Running test FindQuery"); - if (await FindQuery(moralisClient)) - { - testResults.PassedTests.Add("FindQuery", "PASSED"); - } - else - { - testResults.FailedTests.Add("FindQuery", "FAILED"); - Console.WriteLine("\tFAILED"); - } - - await Task.Delay(250); - - Console.WriteLine("Running test WhereEqualToQuery"); - if (await WhereEqualToQuery(moralisClient)) - { - testResults.PassedTests.Add("WhereEqualToQuery", "PASSED"); - } - else - { - testResults.FailedTests.Add("WhereEqualToQuery", "FAILED"); - Console.WriteLine("\tFAILED"); - } - - await Task.Delay(250); - - Console.WriteLine("Running test WhereGreaterThanQuery"); - if (await WhereGreaterThanQuery(moralisClient)) - { - testResults.PassedTests.Add("WhereGreaterThanQuery", "PASSED"); - } - else - { - testResults.FailedTests.Add("WhereGreaterThanQuery", "FAILED"); - Console.WriteLine("\tFAILED"); - } - - await Task.Delay(250); - - Console.WriteLine("Running test WhereLessThanQuery"); - if (await WhereLessThanQuery(moralisClient)) - { - testResults.PassedTests.Add("WhereLessThanQuery", "PASSED"); - } - else - { - testResults.FailedTests.Add("WhereLessThanQuery", "FAILED"); - Console.WriteLine("\tFAILED"); - } - - await Task.Delay(250); - - Console.WriteLine("Running test CompoundQuery"); - if (await CompoundQuery(moralisClient)) - { - testResults.PassedTests.Add("CompoundQuery", "PASSED"); - } - else - { - testResults.FailedTests.Add("CompoundQuery", "FAILED"); - Console.WriteLine("\tFAILED"); - } - - return testResults; - } - - private async Task FetchFirstQuery(MoralisClient moralisClient) - { - bool result = false; - - try - { - MoralisQuery q = await moralisClient.Query(); - - Hero h = await q.FirstAsync(); - - if (h != null) - { - result = true; - } - } - catch (Exception exp) - { - result = false; - } - - return result; - } - - private async Task FindQuery(MoralisClient moralisClient) - { - bool result = false; - - try - { - MoralisQuery q = await moralisClient.Query(); - - IEnumerable heros = await q.FindAsync(); - - if (heros != null && heros.Count() > 0) - { - result = true; - } - } - catch (Exception exp) - { - result = false; - } - - return result; - } - - private async Task WhereEqualToQuery(MoralisClient moralisClient) - { - bool result = false; - - try - { - MoralisQuery q = await moralisClient.Query(); - q = q.WhereEqualTo("Level", 2); - IEnumerable heros = await q.FindAsync(); - - if (heros != null && heros.Count() > 0) - { - result = true; - } - } - catch (Exception exp) - { - result = false; - } - - return result; - } - - private async Task WhereGreaterThanQuery(MoralisClient moralisClient) - { - bool result = false; - - try - { - MoralisQuery q = await moralisClient.Query(); - q = q.WhereGreaterThan("Level", 2); - IEnumerable heros = await q.FindAsync(); - - if (heros != null && heros.Count() > 0) - { - result = true; - } - } - catch (Exception exp) - { - result = false; - } - - return result; - } - - private async Task WhereLessThanQuery(MoralisClient moralisClient) - { - bool result = false; - - try - { - MoralisQuery q = await moralisClient.Query(); - q = q.WhereLessThan("Level", 7); - IEnumerable heros = await q.FindAsync(); - - if (heros != null && heros.Count() > 0) - { - result = true; - } - } - catch (Exception exp) - { - result = false; - } - - return result; - } - - private async Task CompoundQuery(MoralisClient moralisClient) - { - bool result = false; - - try - { - MoralisQuery q = await moralisClient.Query(); - q = q.WhereLessThan("Level", 7) - .WhereGreaterThan("Strength", 3); - - IEnumerable heros = await q.FindAsync(); - - if (heros != null && heros.Count() > 0) - { - result = true; - } - } - catch (Exception exp) - { - result = false; - } - - return result; - } - } -} diff --git a/Moralis.Web3Api.Integrated.Tests/AccountTests.cs b/Moralis.Web3Api.Integrated.Tests/AccountTests.cs index 73b906c..423ff8d 100644 --- a/Moralis.Web3Api.Integrated.Tests/AccountTests.cs +++ b/Moralis.Web3Api.Integrated.Tests/AccountTests.cs @@ -1,9 +1,6 @@ using System; using System.Collections.Generic; -using System.Text; using System.Threading.Tasks; -using Moralis.Web3Api.Api; -using Moralis.Web3Api.CloudApi; using Moralis.Web3Api.Interfaces; using Moralis.Web3Api.Models; diff --git a/Moralis.Web3Api.Integrated.Tests/ProgramTests.cs b/Moralis.Web3Api.Integrated.Tests/ProgramTests.cs index d5fc0d1..d176b87 100644 --- a/Moralis.Web3Api.Integrated.Tests/ProgramTests.cs +++ b/Moralis.Web3Api.Integrated.Tests/ProgramTests.cs @@ -1,4 +1,5 @@ -using Moralis.Web3Api.Interfaces; +using Moralis.Models; +using Moralis.Web3Api.Interfaces; using System; using System.Collections.Generic; using System.Threading.Tasks; @@ -12,16 +13,27 @@ static void Main(string[] args) { List testGroups = TestGroups(); + MoralisClient.ConnectionData = new ServerConnectionData() + { + AuthenticationApiUrl = "https://auth-api.do-prod-1.moralis.io/", + ApplicationID = "foCDSL08ibUWfLHunP6RrCxPGKE6HpwYiiLa5QPV", + DappUrl = "https://ltvaqg1whdgl.usemoralis.com:2053/server", + ApiKey = "1kXrzei19HNrb3YvkLaBbOAuRo6SGcmGqmlZ2E6FYFZ2QnqO46rn3xsAX6eRMBns", + MasterKey = "RU70zK1m50qEuaLNHBTM2PlqOQ7OzYuVeImcMq4w", + Web3ApiUrl = "https://deep-index.moralis.io/api/v2" + }; + + foreach (IIntegratedTest test in testGroups) { - //MoralisClient.Initialize(true, "1kXrzei19HNrb3YvkLaBbOAuRo6SGcmGqmlZ2E6FYFZ2QnqO46rn3xsAX6eRMBns"); // "https://arw2wxg84h6b.moralishost.com:2053/server"); - MoralisClient.Initialize("https://arw2wxg84h6b.moralishost.com:2053/server"); string addr = "0xBa878d88c71E0091613798C53B6c72aDd9b9A6a7".ToLower(); Console.WriteLine($"Executing test set: {test.GetType().Name} ...\n-----------------------------------------"); + IWeb3Api apiClient = MoralisClient.Web3Api; + Task testTask = - Task.Run(() => test.RunTests(MoralisClient.Web3Api, addr)); + Task.Run(() => test.RunTests(apiClient, addr)); testTask.Wait(); IntegratedTestResult result = testTask.Result; diff --git a/MoralisDotNet.Platform.Tests/MoralisClientTests.cs b/MoralisDotNet.Platform.Tests/MoralisClientTests.cs deleted file mode 100644 index dae22de..0000000 --- a/MoralisDotNet.Platform.Tests/MoralisClientTests.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.IO; -using System.Net; -using System.Runtime.CompilerServices; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Services.ClientServices; -using Moralis.Platform.Services.Models; - -namespace Moralis.Platform.Tests -{ - [TestClass] - public class MoralisClientTests - { - [TestMethod] - public void LiveQueryServerUri_isSet() - { - MoralisService client = new MoralisService("1234", "https://api.moralis.com/server", "1234", new NewtonsoftJsonSerializer()); - - Assert.AreEqual("wss://api.moralis.com/server", client.ServerConnectionData.LiveQueryServerURI); - } - - } -} diff --git a/MoralisDotNet.Platform.Tests/MoralisFileServiceTests.cs b/MoralisDotNet.Platform.Tests/MoralisFileServiceTests.cs deleted file mode 100644 index 709d0eb..0000000 --- a/MoralisDotNet.Platform.Tests/MoralisFileServiceTests.cs +++ /dev/null @@ -1,96 +0,0 @@ -using System; -using System.IO; -using System.Net; -using System.Runtime.CompilerServices; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Services.ClientServices; -using Moralis.Platform.Services.Models; - -namespace Moralis.Platform.Tests -{ - [TestClass] - public class MoralisFileServiceTests - { - [TestMethod] - [AsyncStateMachine(typeof(MoralisFileServiceTests))] - public Task TestFileControllerSaveWithInvalidResult() - { - Tuple response = new Tuple(HttpStatusCode.Accepted, null); - Mock mockRunner = CreateMockRunner(response); - MoralisFileState state = new MoralisFileState - { - name = "bekti.png", - mediatype = "image/png" - }; - - MoralisFileService controller = new MoralisFileService(mockRunner.Object, new NewtonsoftJsonSerializer()); - return controller.SaveAsync(state, dataStream: new MemoryStream(), sessionToken: null, progress: null).ContinueWith(t => Assert.IsTrue(t.IsFaulted)); - } - - [TestMethod] - [AsyncStateMachine(typeof(MoralisFileServiceTests))] - public Task TestFileControllerSaveWithEmptyResult() - { - Tuple response = new Tuple(HttpStatusCode.Accepted, "{}"); - Mock mockRunner = CreateMockRunner(response); - MoralisFileState state = new MoralisFileState - { - name = "bekti.png", - mediatype = "image/png" - }; - - MoralisFileService controller = new MoralisFileService(mockRunner.Object, new NewtonsoftJsonSerializer()); - return controller.SaveAsync(state, dataStream: new MemoryStream(), sessionToken: null, progress: null).ContinueWith(t => Assert.IsTrue(t.IsFaulted)); - } - - [TestMethod] - [AsyncStateMachine(typeof(MoralisFileServiceTests))] - public Task TestFileControllerSaveWithIncompleteResult() - { - Tuple response = new Tuple(HttpStatusCode.Accepted, "{\"name\":\"newBekti.png\" }"); - Mock mockRunner = CreateMockRunner(response); - MoralisFileState state = new MoralisFileState - { - name = "bekti.png", - mediatype = "image/png" - }; - - MoralisFileService controller = new MoralisFileService(mockRunner.Object, new NewtonsoftJsonSerializer()); - return controller.SaveAsync(state, dataStream: new MemoryStream(), sessionToken: null, progress: null).ContinueWith(t => Assert.IsTrue(t.IsFaulted)); - } - - [TestMethod] - [AsyncStateMachine(typeof(MoralisFileServiceTests))] - public Task TestFileControllerSave() - { - MoralisFileState state = new MoralisFileState - { - name = "bekti.png", - mediatype = "image/png" - }; - - return new MoralisFileService(CreateMockRunner(new Tuple(HttpStatusCode.Accepted, " {\"name\":\"newBekti.png\", \"url\":\"https://www.parse.com/newBekti.png\" }")).Object, new NewtonsoftJsonSerializer()).SaveAsync(state, dataStream: new MemoryStream(), sessionToken: null, progress: null).ContinueWith(t => - { - Assert.IsFalse(t.IsFaulted); - MoralisFileState newState = t.Result; - - Assert.AreEqual(state.mediatype, newState.mediatype); - Assert.AreEqual("newBekti.png", newState.name); - Assert.AreEqual("https://www.parse.com/newBekti.png", newState.SecureLocation.AbsoluteUri); - }); - } - - private Mock CreateMockRunner(Tuple response) - { - Mock mockRunner = new Mock(); - mockRunner.Setup(obj => obj.RunCommandAsync(It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny())).Returns(Task.FromResult(response)); - - return mockRunner; - } - } -} diff --git a/MoralisDotNet.Platform.Tests/MoralisFileStateTests.cs b/MoralisDotNet.Platform.Tests/MoralisFileStateTests.cs deleted file mode 100644 index f76fe5c..0000000 --- a/MoralisDotNet.Platform.Tests/MoralisFileStateTests.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moralis.Platform.Objects; -using Moralis.Platform.Services; - -namespace Moralis.Platform.Tests -{ - [TestClass] - public class MoralisFileStateTests - { - [TestMethod] - public void TestSecureUrl() - { - Uri unsecureUri = new Uri("http://files.parsetfss.com/yolo.txt"); - Uri secureUri = new Uri("https://files.parsetfss.com/yolo.txt"); - Uri randomUri = new Uri("http://random.server.local/file.foo"); - - MoralisFileState state = new MoralisFileState - { - name = "A", - url = unsecureUri, - mediatype = null - }; - - Assert.AreEqual(unsecureUri, state.url); - Assert.AreEqual(secureUri, state.SecureLocation); - - // Make sure the proper port was given back. - Assert.AreEqual(443, state.SecureLocation.Port); - - state = new MoralisFileState - { - name = "B", - url = randomUri, - mediatype = null - }; - - Assert.AreEqual(randomUri, state.url); - Assert.AreEqual(randomUri, state.url); - } - } -} diff --git a/MoralisDotNet.Platform.Tests/MoralisFileTests.cs b/MoralisDotNet.Platform.Tests/MoralisFileTests.cs deleted file mode 100644 index b6ba209..0000000 --- a/MoralisDotNet.Platform.Tests/MoralisFileTests.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.IO; -using System.Runtime.CompilerServices; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Services; -using Moralis.Platform.Services.ClientServices; -using Moralis.Platform.Utilities; - -namespace Moralis.Platform.Tests -{ - [TestClass] - public class FileTests - { - [TestMethod] - [AsyncStateMachine(typeof(FileTests))] - public Task TestFileSave() - { - Mock mockController = new Mock(); - mockController.Setup(obj => obj.SaveAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny())).Returns(Task.FromResult(new MoralisFileState { name = "newBekti.png", url = new Uri("https://www.parse.com/newBekti.png"), mediatype = "image/png" })); - Mock> mockCurrentUserController = new Mock>(); - - MoralisService client = new MoralisService(new ServerConnectionData { Test = true }, new NewtonsoftJsonSerializer(), new MutableServiceHub { FileService = mockController.Object, CurrentUserService = mockCurrentUserController.Object }); - - MoralisFile file = new MoralisFile("bekti.jpeg", new MemoryStream { }, "image/jpeg"); - - Assert.AreEqual("bekti.jpeg", file.name); - Assert.AreEqual("image/jpeg", file.MimeType); - Assert.IsTrue(file.IsDirty); - - return file.SaveAsync(client).ContinueWith(task => - { - Assert.IsFalse(task.IsFaulted); - Assert.AreEqual("newBekti.png", file.name); - Assert.AreEqual("image/png", file.MimeType); - Assert.AreEqual("https://www.parse.com/newBekti.png", file.url.AbsoluteUri); - Assert.IsFalse(file.IsDirty); - }); - } - - [TestMethod] - public void TestSecureUrl() - { - Uri unsecureUri = new Uri("http://files.parsetfss.com/yolo.txt"); - Uri secureUri = new Uri("https://files.parsetfss.com/yolo.txt"); - Uri randomUri = new Uri("http://random.server.local/file.foo"); - - MoralisFile file = MoralisFileExtensions.Create("Foo", unsecureUri); - Assert.AreEqual(secureUri, file.url); - - file = MoralisFileExtensions.Create("Bar", secureUri); - Assert.AreEqual(secureUri, file.url); - - file = MoralisFileExtensions.Create("Baz", randomUri); - Assert.AreEqual(randomUri, file.url); - } - } -} diff --git a/MoralisDotNet.Platform.Tests/MoralisLiveQueryClientTests.cs b/MoralisDotNet.Platform.Tests/MoralisLiveQueryClientTests.cs deleted file mode 100644 index 562f37c..0000000 --- a/MoralisDotNet.Platform.Tests/MoralisLiveQueryClientTests.cs +++ /dev/null @@ -1,149 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net.WebSockets; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Queries; -using Moralis.Platform.Queries.Live; -using Moralis.Platform.Services.ClientServices; - -namespace Moralis.Platform.Tests -{ - [TestClass] - public class MoralisLiveQueryClientTests - { - - - ServerConnectionData connectionData = new ServerConnectionData() - { - ApplicationID = "1234", - LiveQueryServerURI = "wss://test.moralis.io/doesnotexist", - Test = true - }; - - [TestMethod] - public void MoralisLiveQueryClient_ReceivesConnectResponseOnSubscribe() - { - NewtonsoftJsonSerializer serializer = new NewtonsoftJsonSerializer(); - - bool onConnectedCalled = false; - ConnectRequest msg = new ConnectRequest() - { - applicationId = connectionData.ApplicationID - }; - - ActionEvent ae = new ActionEvent() - { - Object = null, - op = OperationTypes.connected.ToString(), - requestId = 1 - }; - - string json = serializer.Serialize(msg, serializer.DefaultOptions); - string testValue = serializer.Serialize(ae, serializer.DefaultOptions); - - Mock mockWsClient = CreateMockWebSocket(testValue); - - SubscribableWebSocket subClient = new SubscribableWebSocket(new byte[0], connectionData, 1, "abcd", "DEADBEEF", new NewtonsoftJsonSerializer()); - subClient.OnGeneralMessage += (string s) => - { - System.Diagnostics.Debug.WriteLine(s); - }; - - subClient.OnEventMessage += (byte[] buffer, int bufferSize) => { - Assert.IsTrue(buffer.Length == testValue.Length); - Assert.IsTrue(buffer.Length == bufferSize); - - string s = Encoding.UTF8.GetString(buffer); - - Assert.AreEqual(s, testValue); - - QueryEventMessage opMsg = (QueryEventMessage)serializer.Deserialize(s); - - Assert.AreEqual(opMsg.op, OperationTypes.connected.ToString()); - - - }; - subClient.SetWebsocket(mockWsClient.Object); - - ILiveQueryCallbacks callbacks = new LiveQueryCallbacks(); - - MoralisQuery query = new MoralisQuery(default, default, default, serializer, "MoralisObject"); - - MoralisLiveQueryClient mlqc = - new MoralisLiveQueryClient(query, connectionData, - callbacks, subClient, "DEADBEEF", "abcd"); - - mlqc.OnConnected += () => { - onConnectedCalled = true; - subClient.ClientStatus = LiveQueryClientStatusTypes.Closed; - }; - - mlqc.Subscribe(); - - long ticks = DateTime.Now.Ticks; - Task.Run(() => { while ( (DateTime.Now.Ticks - ticks) < 2000 || !mlqc.ClientStatus.Equals(LiveQueryClientStatusTypes.Closed)) ; }) - .Wait(); - - Assert.IsTrue(onConnectedCalled); - } - - private Mock CreateMockWebSocket(string responseMessage) - { - int buffIndex = 0; - - Mock mockWsClient = new Mock(); - mockWsClient.SetupGet(obj => obj.State).Returns(WebSocketState.Open); - mockWsClient.Setup(obj => obj.ConnectAsync(It.IsAny(), It.IsAny())).Returns(Task.CompletedTask); - mockWsClient.Setup(obj => obj.SendAsync(It.IsAny>(), - It.IsAny(), - It.IsAny(), - It.IsAny())).Returns(Task.CompletedTask); - mockWsClient.Setup(obj => obj.ReceiveAsync(It.IsAny>(), - It.IsAny())) - .Returns((ArraySegment a, CancellationToken b) => - { - WebSocketReceiveResult wsrr = new WebSocketReceiveResult(a.Count, WebSocketMessageType.Text, false); - byte[] buf = Encoding.UTF8.GetBytes(responseMessage); - - if (buf.Length < 1) return Task.FromResult(new WebSocketReceiveResult(0, WebSocketMessageType.Text, true) ); - - if (buffIndex >= buf.Length) - { - wsrr = new WebSocketReceiveResult(0, WebSocketMessageType.Text, true); - } - - int count = 0; - - for (int i = 0; i < a.Count; i++) - { - if (buffIndex >= buf.Length) - { - wsrr = new WebSocketReceiveResult(count, WebSocketMessageType.Text, true); - break; - } - - if (buf[buffIndex] == 0) break; - - a[i] = buf[buffIndex]; - buffIndex++; - count++; - if (buffIndex >= buf.Length) - { - wsrr = new WebSocketReceiveResult(count, WebSocketMessageType.Text, true); - break; - } - } - a = new ArraySegment(a.Array, 0, count); - - return Task.FromResult(wsrr); - }); - return mockWsClient; - } - } -} diff --git a/MoralisDotNet.Platform.Tests/SubscribableWebSocketTests.cs b/MoralisDotNet.Platform.Tests/SubscribableWebSocketTests.cs deleted file mode 100644 index abe5878..0000000 --- a/MoralisDotNet.Platform.Tests/SubscribableWebSocketTests.cs +++ /dev/null @@ -1,215 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net.WebSockets; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Queries.Live; - -namespace Moralis.Platform.Tests -{ - [TestClass] - public class SubscribableWebSocketTests - { - ServerConnectionData connectionData = new ServerConnectionData() - { - ApplicationID = "1234", - LiveQueryServerURI = "wss://test.moralis.io/doesnotexist", - Test = true - }; - - [TestMethod] - public void LiveQueryClient_ReturnsExpectedResult() - { - byte[] buffer = new byte[256]; - string testValue = "This is a test."; - - IClientWebSocket ws = CreateMockWebSocket(testValue).Object; - - bool eventCalled = false; - SubscribableWebSocket subClient = new SubscribableWebSocket(new byte[0], connectionData, 1, null, null, new NewtonsoftJsonSerializer()); - subClient.OnGeneralMessage += (string s) => - { - System.Diagnostics.Debug.WriteLine(s); - }; - - subClient.OnEventMessage += (byte[] buffer, int bufferSize) => { - Assert.IsTrue(buffer.Length == testValue.Length); - Assert.IsTrue(buffer.Length == bufferSize); - - string s = Encoding.UTF8.GetString(buffer); - - Assert.AreEqual(s, testValue); - eventCalled = true; - - subClient.ClientStatus = LiveQueryClientStatusTypes.Closed; - }; - - subClient.SetWebsocket(ws); - - subClient.Subscribe(); - - Assert.IsTrue(eventCalled); - } - - [TestMethod] - public void LiveQueryClient_HandlesLargeResult() - { - NewtonsoftJsonSerializer jsonConvert = new NewtonsoftJsonSerializer(); - Dictionary x = new Dictionary(); - - for (int i = 0; i < 50; i++) - { - x.Add(i, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"); - } - string testValue = jsonConvert.Serialize(x); - - IClientWebSocket ws = CreateMockWebSocket(testValue).Object; - - bool eventCalled = false; - SubscribableWebSocket subClient = new SubscribableWebSocket(new byte[0], connectionData, 1, null, null, new NewtonsoftJsonSerializer()); - subClient.OnGeneralMessage += (string s) => - { - System.Diagnostics.Debug.WriteLine(s); - }; - - subClient.OnEventMessage += (byte[] buffer, int bufferSize) => { - Assert.IsTrue(buffer.Length == testValue.Length); - Assert.IsTrue(buffer.Length == bufferSize); - - string s = Encoding.UTF8.GetString(buffer); - - Assert.AreEqual(s, testValue); - - Dictionary y = (Dictionary)jsonConvert.Deserialize>(s); - - Assert.AreEqual(y.Keys.Count, x.Keys.Count); - - eventCalled = true; - - subClient.ClientStatus = LiveQueryClientStatusTypes.Closed; - }; - - subClient.SetWebsocket(ws); - - subClient.Subscribe(); - - Assert.IsTrue(eventCalled); - } - - - [TestMethod] - public void LiveQueryClient_SendsConnectionRequestOnSubscribe() - { - NewtonsoftJsonSerializer jsonConvert = new NewtonsoftJsonSerializer(); - bool eventCalled = false; - ConnectRequest msg = new ConnectRequest() - { - applicationId = connectionData.ApplicationID - //, - //InstallationId = "abcd", - //SessionToken = "DEADBEEF" - }; - - ActionEvent ae = new ActionEvent() - { - Object = null, - op = OperationTypes.connect.ToString(), - requestId = 1 - }; - - string json = jsonConvert.Serialize(msg, jsonConvert.DefaultOptions); - string testValue = jsonConvert.Serialize(ae, jsonConvert.DefaultOptions); - - Mock mockWsClient = CreateMockWebSocket(testValue); - - mockWsClient.Setup(obj => obj.SendAsync(It.IsAny>(), - It.IsAny(), - It.IsAny(), - It.IsAny())) - .Callback, WebSocketMessageType, bool, CancellationToken>((a,b,c,d) => { - string s = Encoding.UTF8.GetString(a.Array); - - Assert.AreEqual(json, s); - - eventCalled = true; - }) - .Returns(Task.CompletedTask); - - SubscribableWebSocket subClient = new SubscribableWebSocket(new byte[0], connectionData, 1, "abcd", "DEADBEEF", new NewtonsoftJsonSerializer()); - subClient.OnGeneralMessage += (string s) => - { - System.Diagnostics.Debug.WriteLine(s); - }; - - subClient.OnEventMessage += (byte[] buffer, int bufferSize) => { - Assert.IsTrue(buffer.Length == testValue.Length); - Assert.IsTrue(buffer.Length == bufferSize); - - string s = Encoding.UTF8.GetString(buffer); - - Assert.AreEqual(s, testValue); - - QueryEventMessage opMsg = (QueryEventMessage)jsonConvert.Deserialize(s); - - Assert.AreEqual(opMsg.op, OperationTypes.connect); - - subClient.ClientStatus = LiveQueryClientStatusTypes.Closed; - }; - subClient.SetWebsocket(mockWsClient.Object); - - subClient.Subscribe(); - - Assert.IsTrue(eventCalled); - } - - private Mock CreateMockWebSocket(string testValue) - { - int buffIndex = 0; - - Mock mockWsClient = new Mock(); - mockWsClient.SetupGet(obj => obj.State).Returns(WebSocketState.Open); - mockWsClient.Setup(obj => obj.ConnectAsync(It.IsAny(), It.IsAny())).Returns(Task.CompletedTask); - mockWsClient.Setup(obj => obj.SendAsync(It.IsAny>(), - It.IsAny(), - It.IsAny(), - It.IsAny())).Returns(Task.CompletedTask); - mockWsClient.Setup(obj => obj.ReceiveAsync(It.IsAny>(), - It.IsAny())) - .Returns((ArraySegment a, CancellationToken b) => - { - WebSocketReceiveResult wsrr = new WebSocketReceiveResult(a.Count, WebSocketMessageType.Text, false); - byte[] buf = Encoding.UTF8.GetBytes(testValue); - if (buffIndex >= buf.Length) - { - wsrr = new WebSocketReceiveResult(0, WebSocketMessageType.Text, true); - } - - int count = 0; - - for (int i = 0; i < a.Count; i++) - { - if (buf[buffIndex] == 0) break; - - a[i] = buf[buffIndex]; - buffIndex++; - count++; - if (buffIndex >= buf.Length) - { - wsrr = new WebSocketReceiveResult(count, WebSocketMessageType.Text, true); - break; - } - } - a = new ArraySegment(a.Array, 0, count); - - return Task.FromResult(wsrr); - }); - return mockWsClient; - } - - } -} diff --git a/MoralisDotNet/Moralis.AuthApi/Api/AuthenticationEndpoint.cs b/MoralisDotNet/Moralis.AuthApi/Api/AuthenticationApi.cs similarity index 95% rename from MoralisDotNet/Moralis.AuthApi/Api/AuthenticationEndpoint.cs rename to MoralisDotNet/Moralis.AuthApi/Api/AuthenticationApi.cs index 3844021..2a1ea7e 100644 --- a/MoralisDotNet/Moralis.AuthApi/Api/AuthenticationEndpoint.cs +++ b/MoralisDotNet/Moralis.AuthApi/Api/AuthenticationApi.cs @@ -11,15 +11,15 @@ namespace Moralis.AuthApi.Api { - public class AuthenticationEndpoint : IAuthEndpoint + public class AuthenticationApi : IAuthenticationApi { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// an instance of ApiClient (optional) /// - public AuthenticationEndpoint(ApiClient apiClient = null) + public AuthenticationApi(ApiClient apiClient = null) { if (apiClient == null) // use the default one in Configuration this.ApiClient = Configuration.DefaultApiClient; @@ -28,10 +28,10 @@ public AuthenticationEndpoint(ApiClient apiClient = null) } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// - public AuthenticationEndpoint(String basePath) + public AuthenticationApi(String basePath) { this.ApiClient = new ApiClient(basePath); } diff --git a/MoralisDotNet/Moralis.AuthApi/Client/AuthApiClient.cs b/MoralisDotNet/Moralis.AuthApi/Client/AuthApiClient.cs index 5b5b26c..4bd0f1c 100644 --- a/MoralisDotNet/Moralis.AuthApi/Client/AuthApiClient.cs +++ b/MoralisDotNet/Moralis.AuthApi/Client/AuthApiClient.cs @@ -12,7 +12,7 @@ public class AuthApiClient : IAuthClientApi /// /// Target Authentication Endpoint. /// - public IAuthEndpoint AuthEndpoint { get; private set; } + public IAuthenticationApi AuthEndpoint { get; private set; } /// /// Indicates that the client has been initialized. @@ -43,7 +43,7 @@ public void Initialize(string serverUrl = null) // Initialize client ApiClient client = new ApiClient(serverUrl is { } ? serverUrl : defaultServerUrl); - AuthEndpoint = new AuthenticationEndpoint(client); + AuthEndpoint = new AuthenticationApi(client); // Indicate that the client is initialized. this.IsInitialized = true; diff --git a/MoralisDotNet/Moralis.AuthApi/Interfaces/IAuthClientApi.cs b/MoralisDotNet/Moralis.AuthApi/Interfaces/IAuthClientApi.cs index 7448389..122521b 100644 --- a/MoralisDotNet/Moralis.AuthApi/Interfaces/IAuthClientApi.cs +++ b/MoralisDotNet/Moralis.AuthApi/Interfaces/IAuthClientApi.cs @@ -9,7 +9,7 @@ public interface IAuthClientApi /// /// Target Authentication Endpoint. /// - IAuthEndpoint AuthEndpoint { get; } + IAuthenticationApi AuthEndpoint { get; } /// /// Indicates that the client has been initialized. diff --git a/MoralisDotNet/Moralis.AuthApi/Interfaces/IAuthEndpoint.cs b/MoralisDotNet/Moralis.AuthApi/Interfaces/IAuthenticationApi.cs similarity index 90% rename from MoralisDotNet/Moralis.AuthApi/Interfaces/IAuthEndpoint.cs rename to MoralisDotNet/Moralis.AuthApi/Interfaces/IAuthenticationApi.cs index 8067a9f..8ffb7da 100644 --- a/MoralisDotNet/Moralis.AuthApi/Interfaces/IAuthEndpoint.cs +++ b/MoralisDotNet/Moralis.AuthApi/Interfaces/IAuthenticationApi.cs @@ -3,7 +3,7 @@ namespace Moralis.AuthApi.Interfaces { - public interface IAuthEndpoint + public interface IAuthenticationApi { public Task Challenge(ChallengeRequestDto request); diff --git a/MoralisDotNet/Moralis.AuthApi/MoralisClient.cs b/MoralisDotNet/Moralis.AuthApi/MoralisAuthApiClient.cs similarity index 62% rename from MoralisDotNet/Moralis.AuthApi/MoralisClient.cs rename to MoralisDotNet/Moralis.AuthApi/MoralisAuthApiClient.cs index a83c05c..64a1f26 100644 --- a/MoralisDotNet/Moralis.AuthApi/MoralisClient.cs +++ b/MoralisDotNet/Moralis.AuthApi/MoralisAuthApiClient.cs @@ -7,20 +7,13 @@ namespace Moralis.AuthApi /// /// Provides an easy to wrapper around the Moralis Web3Api REST services. /// - public class MoralisClient + public class MoralisAuthApiClient { AuthApiClient client = new AuthApiClient(); - static MoralisClient instance = new MoralisClient(); + static MoralisAuthApiClient instance = new MoralisAuthApiClient(); - private MoralisClient() { } - - /// - /// Initialize Moralis Web3API. Use this to initialize to your personal - /// Moralis server. Major advantage is api key is supplied - /// - /// - public static void Initialize(string url) => instance.client.Initialize(url); + private MoralisAuthApiClient() { } /// /// Initialize Moralis Web3API. @@ -28,11 +21,10 @@ private MoralisClient() { } /// If true enforces use of the standard REST server /// Required if useStandardServer is true /// Optional server url. If not provided default standard server Url is used. - public static void Initialize(bool useStandardServer, string apiKey = null, string url = null) + public static void Initialize(string url, string apiKey) { - if (useStandardServer && !(apiKey is { })) throw new ArgumentException("API Key is required for Standard REST server."); + Configuration.ApiKey["X-API-Key"] = apiKey; - if (apiKey is { }) Configuration.ApiKey["X-API-Key"] = apiKey; instance.client.Initialize(url); } diff --git a/MoralisDotNet/Moralis.SolanaApi/Client/SolanaApiClient.cs b/MoralisDotNet/Moralis.SolanaApi/Client/SolanaApiClient.cs index 64a04c9..ac3655d 100644 --- a/MoralisDotNet/Moralis.SolanaApi/Client/SolanaApiClient.cs +++ b/MoralisDotNet/Moralis.SolanaApi/Client/SolanaApiClient.cs @@ -50,20 +50,8 @@ public void Initialize(string serverUrl=null) // Initialize client ApiClient client = new ApiClient(serverUrl is { } ? serverUrl : defaultServerUrl); - // Set endpoints based on api key. If apikey is set - // use the direct Web3Api server. - if (Configuration.ApiKey.ContainsKey("X-API-Key")) - { - this.Account = new AccountApi(client); - this.Nft = new NftApi(client); - } - // Api key not set assume the url is for moralis personal server - // and Cloud Function API should be used. - else - { - this.Account = new CloudApi.AccountApi(client); - this.Nft = new CloudApi.NftApi(client); - } + this.Account = new AccountApi(client); + this.Nft = new NftApi(client); // Indicate that the client is initialized. this.IsInitialized = true; diff --git a/MoralisDotNet/Moralis.SolanaApi/CloudApi/AccountApi.cs b/MoralisDotNet/Moralis.SolanaApi/CloudApi/AccountApi.cs deleted file mode 100644 index 4fe5616..0000000 --- a/MoralisDotNet/Moralis.SolanaApi/CloudApi/AccountApi.cs +++ /dev/null @@ -1,195 +0,0 @@ -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using System.Net; -using Moralis.Network; -using Moralis.SolanaApi.Interfaces; -using Moralis.SolanaApi.Models; -using System.Net.Http; - -namespace Moralis.SolanaApi.CloudApi -{ - public class AccountApi : IAccountApi - { - /// - /// Initializes a new instance of the class. - /// - /// an instance of ApiClient (optional) - /// - public AccountApi(ApiClient apiClient = null) - { - if (apiClient == null) // use the default one in Configuration - this.ApiClient = Configuration.DefaultApiClient; - else - this.ApiClient = apiClient; - } - - /// - /// Initializes a new instance of the class. - /// - /// - public AccountApi(String basePath) - { - this.ApiClient = new ApiClient(basePath); - } - - /// - /// Sets the base path of the API client. - /// - /// The base path - /// The base path - public void SetBasePath(String basePath) - { - this.ApiClient.BasePath = basePath; - } - - /// - /// Gets the base path of the API client. - /// - /// The base path - /// The base path - public String GetBasePath(String basePath) - { - return this.ApiClient.BasePath; - } - - /// - /// Gets or sets the API client. - /// - /// An instance of the ApiClient - public ApiClient ApiClient { get; set; } - - public async Task Balance(NetworkTypes network, string address) - { - // Verify the required parameter 'pairAddress' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetNFTMetadata"); - - var postBody = new Dictionary(); - var headerParams = new Dictionary(); - - var path = "/functions/sol-balance"; - postBody.Add("network", ApiClient.ParameterToString(network.ToString())); - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, null, bodyData, headerParams, null, null, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling Balance: {response.ReasonPhrase}"); - } - } - - public async Task> GetSplTokens(NetworkTypes network, string address) - { - // Verify the required parameter 'pairAddress' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetNFTMetadata"); - - var postBody = new Dictionary(); - var headerParams = new Dictionary(); - - var path = "/functions/sol-getSPL"; - postBody.Add("network", ApiClient.ParameterToString(network.ToString())); - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, null, bodyData, headerParams, null, null, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult>)ApiClient.Deserialize(data, typeof(CloudFunctionResult>), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetSplTokens: {response.ReasonPhrase}"); - } - } - - public async Task> GetNFTs(NetworkTypes network, string address) - { - // Verify the required parameter 'pairAddress' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetNFTMetadata"); - - var postBody = new Dictionary(); - var headerParams = new Dictionary(); - - var path = "/functions/sol-getNFTs"; - postBody.Add("network", ApiClient.ParameterToString(network.ToString())); - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, null, bodyData, headerParams, null, null, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult>)ApiClient.Deserialize(data, typeof(CloudFunctionResult>), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetNFTs: {response.ReasonPhrase}"); - } - } - - public async Task GetPortfolio(NetworkTypes network, string address) - { - // Verify the required parameter 'pairAddress' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetNFTMetadata"); - - var postBody = new Dictionary(); - var headerParams = new Dictionary(); - - var path = "/functions/sol-getPortfolio"; - postBody.Add("network", ApiClient.ParameterToString(network.ToString())); - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, null, bodyData, headerParams, null, null, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetPortfolio: {response.ReasonPhrase}"); - } - } - } -} diff --git a/MoralisDotNet/Moralis.SolanaApi/CloudApi/NftApi.cs b/MoralisDotNet/Moralis.SolanaApi/CloudApi/NftApi.cs deleted file mode 100644 index 83aa2cb..0000000 --- a/MoralisDotNet/Moralis.SolanaApi/CloudApi/NftApi.cs +++ /dev/null @@ -1,97 +0,0 @@ -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using System.Net; -using Moralis.Network; -using Moralis.SolanaApi.Interfaces; -using Moralis.SolanaApi.Models; -using System.Net.Http; - -namespace Moralis.SolanaApi.CloudApi -{ - public class NftApi : INftApi - { - /// - /// Initializes a new instance of the class. - /// - /// an instance of ApiClient (optional) - /// - public NftApi(ApiClient apiClient = null) - { - if (apiClient == null) // use the default one in Configuration - this.ApiClient = Configuration.DefaultApiClient; - else - this.ApiClient = apiClient; - } - - /// - /// Initializes a new instance of the class. - /// - /// - public NftApi(String basePath) - { - this.ApiClient = new ApiClient(basePath); - } - - /// - /// Sets the base path of the API client. - /// - /// The base path - /// The base path - public void SetBasePath(String basePath) - { - this.ApiClient.BasePath = basePath; - } - - /// - /// Gets the base path of the API client. - /// - /// The base path - /// The base path - public String GetBasePath(String basePath) - { - return this.ApiClient.BasePath; - } - - /// - /// Gets or sets the API client. - /// - /// An instance of the ApiClient - public ApiClient ApiClient { get; set; } - - - public async Task GetNFTMetadata(NetworkTypes network, string address) - { - // Verify the required parameter 'pairAddress' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetNFTMetadata"); - - var postBody = new Dictionary(); - var headerParams = new Dictionary(); - - var path = "/functions/sol-getNFTMetadata"; - postBody.Add("network", ApiClient.ParameterToString(network.ToString())); - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, null, bodyData, headerParams, null, null, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetNFTMetadata: {response.ReasonPhrase}"); - } - } - } -} diff --git a/MoralisDotNet/Moralis.SolanaApi/MoralisSolanaClient.cs b/MoralisDotNet/Moralis.SolanaApi/MoralisSolanaApiClient.cs similarity index 52% rename from MoralisDotNet/Moralis.SolanaApi/MoralisSolanaClient.cs rename to MoralisDotNet/Moralis.SolanaApi/MoralisSolanaApiClient.cs index 84a3589..725d721 100644 --- a/MoralisDotNet/Moralis.SolanaApi/MoralisSolanaClient.cs +++ b/MoralisDotNet/Moralis.SolanaApi/MoralisSolanaApiClient.cs @@ -4,34 +4,23 @@ namespace Moralis.SolanaApi { - public class MoralisSolanaClient + public class MoralisSolanaApiClient { SolanaApiClient client = new SolanaApiClient(); - static MoralisSolanaClient instance = new MoralisSolanaClient(); + static MoralisSolanaApiClient instance = new MoralisSolanaApiClient(); - private MoralisSolanaClient() { } - - /// - /// Initialize Moralis Web3API. Use this to initialize to your personal - /// Moralis server. Major advantage is api key is supplied - /// - /// - public static void Initialize(string url) => instance.client.Initialize(url); + private MoralisSolanaApiClient() { } /// /// Initialize Moralis Web3API. /// - /// If true enforces use of the standard REST server - /// Required if useStandardServer is true /// Optional server url. If not provided default standard server Url is used. - public static void Initialize(bool useStandardServer, string apiKey = null, string url = null) + /// Required if useStandardServer is true + public static void Initialize(string url, string apiKey) { - if (useStandardServer && !(apiKey is { })) throw new ArgumentException("API Key is required for Standard REST server."); - - Configuration.ApiKey.Clear(); + Configuration.ApiKey["X-API-Key"] = apiKey; - if (apiKey is { }) Configuration.ApiKey["X-API-Key"] = apiKey; instance.client.Initialize(url); } diff --git a/MoralisDotNet/Moralis.Web3Api/Client/Web3ApiClient.cs b/MoralisDotNet/Moralis.Web3Api/Client/Web3ApiClient.cs index 26dae6a..0e0c8e3 100644 --- a/MoralisDotNet/Moralis.Web3Api/Client/Web3ApiClient.cs +++ b/MoralisDotNet/Moralis.Web3Api/Client/Web3ApiClient.cs @@ -75,30 +75,13 @@ public void Initialize(string serverUrl=null) // Initialize client ApiClient client = new ApiClient(serverUrl is { } ? serverUrl : defaultServerUrl); - // Set endpoints based on api key. If apikey is set - // use the direct Web3Api server. - if (Configuration.ApiKey.ContainsKey("X-API-Key")) - { - this.Account = new AccountApi(client); - this.Defi = new DefiApi(client); - this.Info = new InfoApi(client); - this.Native = new NativeApi(client); - this.Resolve = new ResolveApi(client); - this.Storage = new StorageApi(client); - this.Token = new TokenApi(client); - } - // Api key not set assume the url is for moralis personal server - // and Cloud Function API should be used. - else - { - this.Account = new CloudApi.AccountApi(client); - this.Defi = new CloudApi.DefiApi(client); - this.Info = new CloudApi.InfoApi(client); - this.Native = new CloudApi.NativeApi(client); - this.Resolve = new CloudApi.ResolveApi(client); - this.Storage = new CloudApi.StorageApi(client); - this.Token = new CloudApi.TokenApi(client); - } + this.Account = new AccountApi(client); + this.Defi = new DefiApi(client); + this.Info = new InfoApi(client); + this.Native = new NativeApi(client); + this.Resolve = new ResolveApi(client); + this.Storage = new StorageApi(client); + this.Token = new TokenApi(client); // Indicate that the client is initialized. this.IsInitialized = true; diff --git a/MoralisDotNet/Moralis.Web3Api/CloudApi/AccountApi.cs b/MoralisDotNet/Moralis.Web3Api/CloudApi/AccountApi.cs deleted file mode 100644 index 5d67a96..0000000 --- a/MoralisDotNet/Moralis.Web3Api/CloudApi/AccountApi.cs +++ /dev/null @@ -1,488 +0,0 @@ -/** -* Module: AccountApi.cs -* Description: Represents a collection of functions to interact with the API endpoints -* Author: Moralis Web3 Technology AB, 559307-5988 - David B. Goodrich -* -* NOTE: THIS FILE HAS BEEN AUTOMATICALLY GENERATED. ANY CHANGES MADE TO THIS -* FILE WILL BE LOST -* -* MIT License -* -* Copyright (c) 2022 Moralis Web3 Technology AB, 559307-5988 -* -* Permission is hereby granted, free of charge, to any person obtaining a copy -* of this software and associated documentation files (the 'Software'), to deal -* in the Software without restriction, including without limitation the rights -* to use, copy, modify, merge, publish, distribute, sublicense, and / or sell -* copies of the Software, and to permit persons to whom the Software is -* furnished to do so, subject to the following conditions: -* -* The above copyright notice and this permission notice shall be included in all -* copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -* SOFTWARE. -*/ -using System; -using System.Collections.Generic; -using Newtonsoft.Json; -using System.Net; -using System.Threading.Tasks; -using Moralis.Network; -using Moralis.Web3Api.Interfaces; -using Moralis.Web3Api.Models; -using System.Net.Http; - -namespace Moralis.Web3Api.CloudApi -{ - /// - /// Represents a collection of functions to interact with the API endpoints - /// - public class AccountApi : IAccountApi - { - /// - /// Initializes a new instance of the class. - /// - /// an instance of ApiClient (optional) - /// - public AccountApi(ApiClient apiClient = null) - { - if (apiClient == null) // use the default one in Configuration - this.ApiClient = Configuration.DefaultApiClient; - else - this.ApiClient = apiClient; - } - - /// - /// Initializes a new instance of the class. - /// - /// - public AccountApi(String basePath) - { - this.ApiClient = new ApiClient(basePath); - } - - /// - /// Sets the base path of the API client. - /// - /// The base path - /// The base path - public void SetBasePath(String basePath) - { - this.ApiClient.BasePath = basePath; - } - - /// - /// Gets the base path of the API client. - /// - /// The base path - /// The base path - public String GetBasePath(String basePath) - { - return this.ApiClient.BasePath; - } - - /// - /// Gets or sets the API client. - /// - /// An instance of the ApiClient - public ApiClient ApiClient {get; set;} - - - /// - /// Gets native transactions in descending order based on block number - /// - /// address - /// The chain to query - /// The subdomain of the moralis server to use (Only use when selecting local devchain as chain) - /// The minimum block number from where to get the transactions - /// * Provide the param 'from_block' or 'from_date' - /// * If 'from_date' and 'from_block' are provided, 'from_block' will be used. - /// - /// The maximum block number from where to get the transactions. - /// * Provide the param 'to_block' or 'to_date' - /// * If 'to_date' and 'to_block' are provided, 'to_block' will be used. - /// - /// The date from where to get the transactions (any format that is accepted by momentjs) - /// * Provide the param 'from_block' or 'from_date' - /// * If 'from_date' and 'from_block' are provided, 'from_block' will be used. - /// - /// Get the transactions to this date (any format that is accepted by momentjs) - /// * Provide the param 'to_block' or 'to_date' - /// * If 'to_date' and 'to_block' are provided, 'to_block' will be used. - /// - /// offset - /// limit - /// Returns a collection of native transactions. - public async Task GetTransactions (string address, ChainList chain, string cursor="", string subdomain=null, int? fromBlock=null, int? toBlock=null, string fromDate=null, string toDate=null, int? limit=null) - { - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetTransactions"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getTransactions"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (subdomain != null) postBody.Add("subdomain", ApiClient.ParameterToString(subdomain)); - if (fromBlock != null) postBody.Add("from_block", ApiClient.ParameterToString(fromBlock)); - if (toBlock != null) postBody.Add("to_block", ApiClient.ParameterToString(toBlock)); - if (fromDate != null) postBody.Add("from_date", ApiClient.ParameterToString(fromDate)); - if (toDate != null) postBody.Add("to_date", ApiClient.ParameterToString(toDate)); - if (cursor != null) postBody.Add("cursor", ApiClient.ParameterToString(cursor)); - if (limit != null) postBody.Add("limit", ApiClient.ParameterToString(limit)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetTransactions: {response.ReasonPhrase}"); - } - } - - /// - /// Gets native balance for a specific address - /// - /// The address for which the native balance will be checked - /// The chain to query - /// web3 provider url to user when using local dev chain - /// The block number on which the balances should be checked - /// Returns native balance for a specific address - public async Task GetNativeBalance (string address, ChainList chain, string providerUrl=null, decimal? toBlock=null) - { - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetNativeBalance"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getNativeBalance"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (providerUrl != null) postBody.Add("providerUrl", ApiClient.ParameterToString(providerUrl)); - if (toBlock != null) postBody.Add("to_block", ApiClient.ParameterToString(toBlock)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetNativeBalance: {response.ReasonPhrase}"); - } - } - - /// - /// Gets token balances for a specific address - /// - /// The address for which token balances will be checked - /// The chain to query - /// The subdomain of the moralis server to use (Only use when selecting local devchain as chain) - /// The block number on which the balances should be checked - /// Returns token balances for a specific address - public async Task> GetTokenBalances (string address, ChainList chain, string subdomain=null, decimal? toBlock=null) - { - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetTokenBalances"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getTokenBalances"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (subdomain != null) postBody.Add("subdomain", ApiClient.ParameterToString(subdomain)); - if (toBlock != null) postBody.Add("to_block", ApiClient.ParameterToString(toBlock)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult>)ApiClient.Deserialize(data, typeof(CloudFunctionResult>), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetTokenBalances: {response.ReasonPhrase}"); - } - } - - /// - /// Gets ERC20 token transactions in descending order based on block number - /// - /// address - /// The chain to query - /// The subdomain of the moralis server to use (Only use when selecting local devchain as chain) - /// The minimum block number from where to get the transactions - /// * Provide the param 'from_block' or 'from_date' - /// * If 'from_date' and 'from_block' are provided, 'from_block' will be used. - /// - /// The maximum block number from where to get the transactions. - /// * Provide the param 'to_block' or 'to_date' - /// * If 'to_date' and 'to_block' are provided, 'to_block' will be used. - /// - /// The date from where to get the transactions (any format that is accepted by momentjs) - /// * Provide the param 'from_block' or 'from_date' - /// * If 'from_date' and 'from_block' are provided, 'from_block' will be used. - /// - /// Get the transactions to this date (any format that is accepted by momentjs) - /// * Provide the param 'to_block' or 'to_date' - /// * If 'to_date' and 'to_block' are provided, 'to_block' will be used. - /// - /// offset - /// limit - /// Returns a collection of token transactions. - public async Task GetTokenTransfers (string address, ChainList chain, string cursor="", string subdomain=null, int? fromBlock=null, int? toBlock=null, string fromDate=null, string toDate=null, int? limit=null) - { - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetTokenTransfers"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getTokenTransfers"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (subdomain != null) postBody.Add("subdomain", ApiClient.ParameterToString(subdomain)); - if (fromBlock != null) postBody.Add("from_block", ApiClient.ParameterToString(fromBlock)); - if (toBlock != null) postBody.Add("to_block", ApiClient.ParameterToString(toBlock)); - if (fromDate != null) postBody.Add("from_date", ApiClient.ParameterToString(fromDate)); - if (toDate != null) postBody.Add("to_date", ApiClient.ParameterToString(toDate)); - if (cursor != null) postBody.Add("cursor", ApiClient.ParameterToString(cursor)); - if (limit != null) postBody.Add("limit", ApiClient.ParameterToString(limit)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetTokenTransfers: {response.ReasonPhrase}"); - } - } - - /// - /// Gets NFTs owned by the given address - /// * The response will include status [SYNCED/SYNCING] based on the contracts being indexed. - /// * Use the token_address param to get results for a specific contract only - /// * Note results will include all indexed NFTs - /// * Any request which includes the token_address param will start the indexing process for that NFT collection the very first time it is requested - /// - /// - /// The owner of a given token - /// The chain to query - /// The format of the token id - /// offset - /// limit - /// Returns a collection of nft owners - public async Task GetNFTs (string address, ChainList chain, string cursor="", string format=null, int? limit=null) - { - - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetNFTs"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getNFTs"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (format != null) postBody.Add("format", ApiClient.ParameterToString(format)); - if (cursor != null) postBody.Add("cursor", ApiClient.ParameterToString(cursor)); - if (limit != null) postBody.Add("limit", ApiClient.ParameterToString(limit)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetNFTs: {response.ReasonPhrase}"); - } - } - - /// - /// Gets the transfers of the tokens matching the given parameters - /// - /// The sender or recepient of the transfer - /// The chain to query - /// The format of the token id - /// The transfer direction - /// offset - /// limit - /// Returns a collection of NFT transfer - public async Task GetNFTTransfers (string address, ChainList chain, string cursor="", string format=null, string direction=null, int? limit=null) - { - - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetNFTTransfers"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getNFTTransfers"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (format != null) postBody.Add("format", ApiClient.ParameterToString(format)); - if (direction != null) postBody.Add("direction", ApiClient.ParameterToString(direction)); - if (cursor != null) postBody.Add("cursor", ApiClient.ParameterToString(cursor)); - if (limit != null) postBody.Add("limit", ApiClient.ParameterToString(limit)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetNFTTransfers: {response.ReasonPhrase}"); - } - } - - /// - /// Gets NFTs owned by the given address - /// * Use the token_address param to get results for a specific contract only - /// * Note results will include all indexed NFTs - /// * Any request which includes the token_address param will start the indexing process for that NFT collection the very first time it is requested - /// - /// - /// The owner of a given token - /// Address of the contract - /// The chain to query - /// The format of the token id - /// offset - /// limit - /// Returns a collection of nft owners - public async Task GetNFTsForContract (string address, string tokenAddress, ChainList chain, string cursor="", string format=null, int? limit=null) - { - - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetNFTsForContract"); - - // Verify the required parameter 'tokenAddress' is set - if (tokenAddress == null) throw new ApiException(400, "Missing required parameter 'tokenAddress' when calling GetNFTsForContract"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getNFTsForContract"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (tokenAddress != null) postBody.Add("token_address", ApiClient.ParameterToString(tokenAddress)); - if (format != null) postBody.Add("format", ApiClient.ParameterToString(format)); - if (cursor != null) postBody.Add("cursor", ApiClient.ParameterToString(cursor)); - if (limit != null) postBody.Add("limit", ApiClient.ParameterToString(limit)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetNFTsForContract: {response.ReasonPhrase}"); - } - } - } -} diff --git a/MoralisDotNet/Moralis.Web3Api/CloudApi/DefiApi.cs b/MoralisDotNet/Moralis.Web3Api/CloudApi/DefiApi.cs deleted file mode 100644 index e979e14..0000000 --- a/MoralisDotNet/Moralis.Web3Api/CloudApi/DefiApi.cs +++ /dev/null @@ -1,210 +0,0 @@ -/** -* Module: DefiApi.cs -* Description: Represents a collection of functions to interact with the API endpoints -* Author: Moralis Web3 Technology AB, 559307-5988 - David B. Goodrich -* -* NOTE: THIS FILE HAS BEEN AUTOMATICALLY GENERATED. ANY CHANGES MADE TO THIS -* FILE WILL BE LOST -* -* MIT License -* -* Copyright (c) 2022 Moralis Web3 Technology AB, 559307-5988 -* -* Permission is hereby granted, free of charge, to any person obtaining a copy -* of this software and associated documentation files (the 'Software'), to deal -* in the Software without restriction, including without limitation the rights -* to use, copy, modify, merge, publish, distribute, sublicense, and / or sell -* copies of the Software, and to permit persons to whom the Software is -* furnished to do so, subject to the following conditions: -* -* The above copyright notice and this permission notice shall be included in all -* copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -* SOFTWARE. -*/ -using System; -using System.Collections.Generic; -using Newtonsoft.Json; -using System.Net; -using System.Threading.Tasks; -using Moralis.Network; -using Moralis.Web3Api.Interfaces; -using Moralis.Web3Api.Models; -using System.Linq; -using System.Net.Http; - -namespace Moralis.Web3Api.CloudApi -{ - /// - /// Represents a collection of functions to interact with the API endpoints - /// - public class DefiApi : IDefiApi - { - /// - /// Initializes a new instance of the class. - /// - /// an instance of ApiClient (optional) - /// - public DefiApi(ApiClient apiClient = null) - { - if (apiClient == null) // use the default one in Configuration - this.ApiClient = Configuration.DefaultApiClient; - else - this.ApiClient = apiClient; - } - - /// - /// Initializes a new instance of the class. - /// - /// - public DefiApi(String basePath) - { - this.ApiClient = new ApiClient(basePath); - } - - /// - /// Sets the base path of the API client. - /// - /// The base path - /// The base path - public void SetBasePath(String basePath) - { - this.ApiClient.BasePath = basePath; - } - - /// - /// Gets the base path of the API client. - /// - /// The base path - /// The base path - public String GetBasePath(String basePath) - { - return this.ApiClient.BasePath; - } - - /// - /// Gets or sets the API client. - /// - /// An instance of the ApiClient - public ApiClient ApiClient {get; set;} - - - /// - /// Get the liquidity reserves for a given pair address - /// - /// Liquidity pair address - /// The chain to query - /// To get the reserves at this block number - /// Get the reserves to this date (any format that is accepted by momentjs) - /// * Provide the param 'to_block' or 'to_date' - /// * If 'to_date' and 'to_block' are provided, 'to_block' will be used. - /// - /// web3 provider url to user when using local dev chain - /// Returns the pair reserves - public async Task GetPairReserves (string pairAddress, ChainList chain, string toBlock=null, string toDate=null, string providerUrl=null) - { - // Verify the required parameter 'pairAddress' is set - if (pairAddress == null) throw new ApiException(400, "Missing required parameter 'pairAddress' when calling GetPairReserves"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getPairReserves"; - if (pairAddress != null) postBody.Add("pair_address", ApiClient.ParameterToString(pairAddress)); - if (toBlock != null) postBody.Add("to_block", ApiClient.ParameterToString(toBlock)); - if (toDate != null) postBody.Add("to_date", ApiClient.ParameterToString(toDate)); - if (providerUrl != null) postBody.Add("provider_url", ApiClient.ParameterToString(providerUrl)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetPairReserves: {response.ReasonPhrase}"); - } - } - - /// - /// Fetches and returns pair data of the provided token0+token1 combination. - /// The token0 and token1 options are interchangable (ie. there is no different outcome in "token0=WETH and token1=USDT" or "token0=USDT and token1=WETH") - /// - /// - /// The factory name or address of the token exchange - /// Token0 address - /// Token1 address - /// The chain to query - /// To get the reserves at this block number - /// Get the reserves to this date (any format that is accepted by momentjs) - /// * Provide the param 'to_block' or 'to_date' - /// * If 'to_date' and 'to_block' are provided, 'to_block' will be used. - /// - /// Returns the pair address of the two tokens - public async Task GetPairAddress (string exchange, string token0Address, string token1Address, ChainList chain, string toBlock=null, string toDate=null) - { - // Verify the required parameter 'exchange' is set - if (exchange == null) throw new ApiException(400, "Missing required parameter 'exchange' when calling GetPairAddress"); - - // Verify the required parameter 'token0Address' is set - if (token0Address == null) throw new ApiException(400, "Missing required parameter 'token0Address' when calling GetPairAddress"); - - // Verify the required parameter 'token1Address' is set - if (token1Address == null) throw new ApiException(400, "Missing required parameter 'token1Address' when calling GetPairAddress"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getPairAddress"; - if (exchange != null) postBody.Add("exchange", ApiClient.ParameterToString(exchange)); - if (token0Address != null) postBody.Add("token0_address", ApiClient.ParameterToString(token0Address)); - if (token1Address != null) postBody.Add("token1_address", ApiClient.ParameterToString(token1Address)); - if (toBlock != null) postBody.Add("to_block", ApiClient.ParameterToString(toBlock)); - if (toDate != null) postBody.Add("to_date", ApiClient.ParameterToString(toDate)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetPairAddress: {response.ReasonPhrase}"); - } - } - } -} diff --git a/MoralisDotNet/Moralis.Web3Api/CloudApi/InfoApi.cs b/MoralisDotNet/Moralis.Web3Api/CloudApi/InfoApi.cs deleted file mode 100644 index d57bb1f..0000000 --- a/MoralisDotNet/Moralis.Web3Api/CloudApi/InfoApi.cs +++ /dev/null @@ -1,135 +0,0 @@ -using System; -using System.Collections.Generic; -using Newtonsoft.Json; -using System.Net; -using System.Threading.Tasks; -using Moralis.Network; -using Moralis.Web3Api.Interfaces; -using Moralis.Web3Api.Models; -using System.Net.Http; - -namespace Moralis.Web3Api.CloudApi -{ - public class InfoApi : IInfoApi - { - /// - /// Initializes a new instance of the class. - /// - /// an instance of ApiClient (optional) - /// - public InfoApi(ApiClient apiClient = null) - { - if (apiClient == null) // use the default one in Configuration - this.ApiClient = Configuration.DefaultApiClient; - else - this.ApiClient = apiClient; - } - - /// - /// Initializes a new instance of the class. - /// - /// - public InfoApi(String basePath) - { - this.ApiClient = new ApiClient(basePath); - } - - /// - /// Sets the base path of the API client. - /// - /// The base path - /// The base path - public void SetBasePath(String basePath) - { - this.ApiClient.BasePath = basePath; - } - - /// - /// Gets the base path of the API client. - /// - /// The base path - /// The base path - public String GetBasePath(String basePath) - { - return this.ApiClient.BasePath; - } - - /// - /// Gets or sets the API client. - /// - /// An instance of the ApiClient - public ApiClient ApiClient { get; set; } - - /// - /// Returns the current version of the Web3 API - /// - /// - /// - public async Task GetWeb3ApiVersion() - { - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/web3ApiVersion"; - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : "{}"; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling getVersion: {response.ReasonPhrase}"); - } - } - - /// - /// Returns the endpoint price list for rate limits and costs. - /// - /// - /// - public async Task> GetEndpointWeights() - { - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/endpointWeights"; - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : "{}"; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult>)ApiClient.Deserialize(data, typeof(CloudFunctionResult>), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling getEndpointWeights: {response.ReasonPhrase}"); - } - } - } -} diff --git a/MoralisDotNet/Moralis.Web3Api/CloudApi/NativeApi.cs b/MoralisDotNet/Moralis.Web3Api/CloudApi/NativeApi.cs deleted file mode 100644 index 00c5ba9..0000000 --- a/MoralisDotNet/Moralis.Web3Api/CloudApi/NativeApi.cs +++ /dev/null @@ -1,531 +0,0 @@ -/** -* Module: NativeApi.cs -* Description: Represents a collection of functions to interact with the API endpoints -* Author: Moralis Web3 Technology AB, 559307-5988 - David B. Goodrich -* -* NOTE: THIS FILE HAS BEEN AUTOMATICALLY GENERATED. ANY CHANGES MADE TO THIS -* FILE WILL BE LOST -* -* MIT License -* -* Copyright (c) 2022 Moralis Web3 Technology AB, 559307-5988 -* -* Permission is hereby granted, free of charge, to any person obtaining a copy -* of this software and associated documentation files (the 'Software'), to deal -* in the Software without restriction, including without limitation the rights -* to use, copy, modify, merge, publish, distribute, sublicense, and / or sell -* copies of the Software, and to permit persons to whom the Software is -* furnished to do so, subject to the following conditions: -* -* The above copyright notice and this permission notice shall be included in all -* copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -* SOFTWARE. -*/ -using System; -using System.Collections.Generic; -using Newtonsoft.Json; -using System.Net; -using System.Threading.Tasks; -using Moralis.Network; -using Moralis.Web3Api.Interfaces; -using Moralis.Web3Api.Models; -using System.Net.Http; - -namespace Moralis.Web3Api.CloudApi -{ - /// - /// Represents a collection of functions to interact with the API endpoints - /// - public class NativeApi : INativeApi - { - /// - /// Initializes a new instance of the class. - /// - /// an instance of ApiClient (optional) - /// - public NativeApi(ApiClient apiClient = null) - { - if (apiClient == null) // use the default one in Configuration - this.ApiClient = Configuration.DefaultApiClient; - else - this.ApiClient = apiClient; - } - - /// - /// Initializes a new instance of the class. - /// - /// - public NativeApi(String basePath) - { - this.ApiClient = new ApiClient(basePath); - } - - /// - /// Sets the base path of the API client. - /// - /// The base path - /// The base path - public void SetBasePath(String basePath) - { - this.ApiClient.BasePath = basePath; - } - - /// - /// Gets the base path of the API client. - /// - /// The base path - /// The base path - public String GetBasePath(String basePath) - { - return this.ApiClient.BasePath; - } - - /// - /// Gets or sets the API client. - /// - /// An instance of the ApiClient - public ApiClient ApiClient {get; set;} - - - /// - /// Gets the contents of a block by block hash - /// - /// The block hash or block number - /// The chain to query - /// The subdomain of the moralis server to use (Only use when selecting local devchain as chain) - /// Returns the contents of a block - public async Task GetBlock (string blockNumberOrHash, ChainList chain, string subdomain=null) - { - - // Verify the required parameter 'blockNumberOrHash' is set - if (blockNumberOrHash == null) throw new ApiException(400, "Missing required parameter 'blockNumberOrHash' when calling GetBlock"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getBlock"; - if (blockNumberOrHash != null) postBody.Add("block_number_or_hash", ApiClient.ParameterToString(blockNumberOrHash)); - if (subdomain != null) postBody.Add("subdomain", ApiClient.ParameterToString(subdomain)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetBlock: {response.ReasonPhrase}"); - } - - //Tuple, string> response = new Tuple, string>(HttpStatusCode.Unauthorized, new Dictionary(), "oopack"); - //// await ApiClient.CallApi(path, Method.POST, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - //if (((int)response.Item1) >= 400) - // throw new ApiException((int)response.Item1, "Error calling GetBlock: " + response.Item3, response.Item3); - //else if (((int)response.Item1) == 0) - // throw new ApiException((int)response.Item1, "Error calling GetBlock: " + response.Item3, response.Item3); - - //return ((CloudFunctionResult)ApiClient.Deserialize(response.Item3, typeof(CloudFunctionResult), null)).Result; - } - /// - /// Gets the closest block of the provided date - /// - /// Unix date in miliseconds or a datestring (any format that is accepted by momentjs) - /// The chain to query - /// web3 provider url to user when using local dev chain - /// Returns the blocknumber and corresponding date and timestamp - public async Task GetDateToBlock (string date, ChainList chain, string providerUrl=null) - { - - // Verify the required parameter 'date' is set - if (date == null) throw new ApiException(400, "Missing required parameter 'date' when calling GetDateToBlock"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getDateToBlock"; - if (date != null) postBody.Add("date", ApiClient.ParameterToString(date)); - if (providerUrl != null) postBody.Add("providerUrl", ApiClient.ParameterToString(providerUrl)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetDateToBlock: {response.ReasonPhrase}"); - } - //Tuple, string> response = new Tuple, string>(HttpStatusCode.Unauthorized, new Dictionary(), "oopack"); - //// await ApiClient.CallApi(path, Method.POST, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - //if (((int)response.Item1) >= 400) - // throw new ApiException((int)response.Item1, "Error calling GetDateToBlock: " + response.Item3, response.Item3); - //else if (((int)response.Item1) == 0) - // throw new ApiException((int)response.Item1, "Error calling GetDateToBlock: " + response.Item3, response.Item3); - - //return ((CloudFunctionResult)ApiClient.Deserialize(response.Item3, typeof(CloudFunctionResult), null)).Result; - } - /// - /// Gets the logs from an address - /// - /// address - /// The chain to query - /// The subdomain of the moralis server to use (Only use when selecting local devchain as chain) - /// The block number - /// * Provide the param 'block_numer' or ('from_block' and / or 'to_block') - /// * If 'block_numer' is provided in conbinaison with 'from_block' and / or 'to_block', 'block_number' will will be used - /// - /// The minimum block number from where to get the logs - /// * Provide the param 'block_numer' or ('from_block' and / or 'to_block') - /// * If 'block_numer' is provided in conbinaison with 'from_block' and / or 'to_block', 'block_number' will will be used - /// - /// The maximum block number from where to get the logs - /// * Provide the param 'block_numer' or ('from_block' and / or 'to_block') - /// * If 'block_numer' is provided in conbinaison with 'from_block' and / or 'to_block', 'block_number' will will be used - /// - /// The date from where to get the logs (any format that is accepted by momentjs) - /// * Provide the param 'from_block' or 'from_date' - /// * If 'from_date' and 'from_block' are provided, 'from_block' will be used. - /// * If 'from_date' and the block params are provided, the block params will be used. Please refer to the blocks params sections (block_number,from_block and to_block) on how to use them - /// - /// Get the logs to this date (any format that is accepted by momentjs) - /// * Provide the param 'to_block' or 'to_date' - /// * If 'to_date' and 'to_block' are provided, 'to_block' will be used. - /// * If 'to_date' and the block params are provided, the block params will be used. Please refer to the blocks params sections (block_number,from_block and to_block) on how to use them - /// - /// topic0 - /// topic1 - /// topic2 - /// topic3 - /// Returns the logs of an address - public async Task GetLogsByAddress (string address, ChainList chain, string cursor="", string subdomain=null, string blockNumber=null, string fromBlock=null, string toBlock=null, string fromDate=null, string toDate=null, string topic0=null, string topic1=null, string topic2=null, string topic3=null, int? limit = null) - { - - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetLogsByAddress"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getLogsByAddress"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (subdomain != null) postBody.Add("subdomain", ApiClient.ParameterToString(subdomain)); - if (blockNumber != null) postBody.Add("block_number", ApiClient.ParameterToString(blockNumber)); - if (fromBlock != null) postBody.Add("from_block", ApiClient.ParameterToString(fromBlock)); - if (toBlock != null) postBody.Add("to_block", ApiClient.ParameterToString(toBlock)); - if (fromDate != null) postBody.Add("from_date", ApiClient.ParameterToString(fromDate)); - if (toDate != null) postBody.Add("to_date", ApiClient.ParameterToString(toDate)); - if (topic0 != null) postBody.Add("topic0", ApiClient.ParameterToString(topic0)); - if (topic1 != null) postBody.Add("topic1", ApiClient.ParameterToString(topic1)); - if (topic2 != null) postBody.Add("topic2", ApiClient.ParameterToString(topic2)); - if (topic3 != null) postBody.Add("topic3", ApiClient.ParameterToString(topic3)); - if (cursor != null) postBody.Add("cursor", ApiClient.ParameterToString(cursor)); - if (limit != null) postBody.Add("limit", ApiClient.ParameterToString(limit)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetLogsByAddress: {response.ReasonPhrase}"); - } - } - - /// - /// Gets NFT transfers by block number or block hash - /// - /// The block hash or block number - /// The chain to query - /// The subdomain of the moralis server to use (Only use when selecting local devchain as chain) - /// offset - /// limit - /// Returns the contents of a block - public async Task GetNFTTransfersByBlock (string blockNumberOrHash, ChainList chain, string cursor="", string subdomain=null, int? limit=null) - { - - // Verify the required parameter 'blockNumberOrHash' is set - if (blockNumberOrHash == null) throw new ApiException(400, "Missing required parameter 'blockNumberOrHash' when calling GetNFTTransfersByBlock"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getNFTTransfersByBlock"; - if (blockNumberOrHash != null) postBody.Add("block_number_or_hash", ApiClient.ParameterToString(blockNumberOrHash)); - if (subdomain != null) postBody.Add("subdomain", ApiClient.ParameterToString(subdomain)); - if (cursor != null) postBody.Add("cursor", ApiClient.ParameterToString(cursor)); - if (limit != null) postBody.Add("limit", ApiClient.ParameterToString(limit)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetNFTTransfersByBlock: {response.ReasonPhrase}"); - } - } - - /// - /// Gets the contents of a block transaction by hash - /// - /// The transaction hash - /// The chain to query - /// The subdomain of the moralis server to use (Only use when selecting local devchain as chain) - /// Returns the contents of a block transaction - public async Task GetTransaction (string transactionHash, ChainList chain, string subdomain=null) - { - - // Verify the required parameter 'transactionHash' is set - if (transactionHash == null) throw new ApiException(400, "Missing required parameter 'transactionHash' when calling GetTransaction"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getTransaction"; - if (transactionHash != null) postBody.Add("transaction_hash", ApiClient.ParameterToString(transactionHash)); - if (subdomain != null) postBody.Add("subdomain", ApiClient.ParameterToString(subdomain)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetTransaction: {response.ReasonPhrase}"); - } - } - - /// - /// Gets events in descending order based on block number - /// - /// address - /// The topic of the event - /// ABI of the specific event - /// The chain to query - /// The subdomain of the moralis server to use (Only use when selecting local devchain as chain) - /// web3 provider url to user when using local dev chain - /// The minimum block number from where to get the logs - /// * Provide the param 'from_block' or 'from_date' - /// * If 'from_date' and 'from_block' are provided, 'from_block' will be used. - /// - /// The maximum block number from where to get the logs. - /// * Provide the param 'to_block' or 'to_date' - /// * If 'to_date' and 'to_block' are provided, 'to_block' will be used. - /// - /// The date from where to get the logs (any format that is accepted by momentjs) - /// * Provide the param 'from_block' or 'from_date' - /// * If 'from_date' and 'from_block' are provided, 'from_block' will be used. - /// - /// Get the logs to this date (any format that is accepted by momentjs) - /// * Provide the param 'to_block' or 'to_date' - /// * If 'to_date' and 'to_block' are provided, 'to_block' will be used. - /// - /// offset - /// limit - /// Returns a collection of events by topic - public async Task> GetContractEvents (string address, string topic, object abi, ChainList chain, string subdomain=null, string providerUrl=null, int? fromBlock=null, int? toBlock=null, string fromDate=null, string toDate=null, int? offset=null, int? limit=null) - { - - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetContractEvents"); - - // Verify the required parameter 'topic' is set - if (topic == null) throw new ApiException(400, "Missing required parameter 'topic' when calling GetContractEvents"); - - // Verify the required parameter 'abi' is set - if (abi == null) throw new ApiException(400, "Missing required parameter 'abi' when calling GetContractEvents"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getContractEvents"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (topic != null) postBody.Add("topic", ApiClient.ParameterToString(topic)); - if (abi != null) postBody.Add("abi", abi); - if (subdomain != null) postBody.Add("subdomain", ApiClient.ParameterToString(subdomain)); - if (providerUrl != null) postBody.Add("providerUrl", ApiClient.ParameterToString(providerUrl)); - if (fromBlock != null) postBody.Add("from_block", ApiClient.ParameterToString(fromBlock)); - if (toBlock != null) postBody.Add("to_block", ApiClient.ParameterToString(toBlock)); - if (fromDate != null) postBody.Add("from_date", ApiClient.ParameterToString(fromDate)); - if (toDate != null) postBody.Add("to_date", ApiClient.ParameterToString(toDate)); - if (offset != null) postBody.Add("offset", ApiClient.ParameterToString(offset)); - if (limit != null) postBody.Add("limit", ApiClient.ParameterToString(limit)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - LogEventResponse resp = ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - return resp.Events; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetContractEvents: {response.ReasonPhrase}"); - } - } - - /// - /// Runs a given function of a contract abi and returns readonly data - /// - /// address - /// function_name - /// Body - /// The chain to query - /// The subdomain of the moralis server to use (Only use when selecting local devchain as chain) - /// web3 provider url to user when using local dev chain - /// Returns response of the function executed - public async Task RunContractFunction (string address, string functionName, RunContractDto abi, ChainList chain, string subdomain=null, string providerUrl=null) - { - - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling RunContractFunction"); - - // Verify the required parameter 'functionName' is set - if (functionName == null) throw new ApiException(400, "Missing required parameter 'functionName' when calling RunContractFunction"); - - // Verify the required parameter 'abi' is set - if (abi == null) throw new ApiException(400, "Missing required parameter 'abi' when calling RunContractFunction"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/runContractFunction"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (functionName != null) postBody.Add("function_name", ApiClient.ParameterToString(functionName)); - if (abi != null) postBody.Add("abi", abi.Abi); - if (abi != null) postBody.Add("params", abi.Params); - if (subdomain != null) postBody.Add("subdomain", ApiClient.ParameterToString(subdomain)); - if (providerUrl != null) postBody.Add("providerUrl", ApiClient.ParameterToString(providerUrl)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - - if (data.Substring(0,10).Equals("{\"result\":")) - { - data = data.Substring(10); - // Strip off ending '}' - data = data.Substring(0, data.Length - 1); - // If data is a string, strip of leading and ending quotes - if (data.Substring(0, 1).Equals("\"")) - { - data = data.Substring(1, data.Length - 2); - } - } - - return data; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling RunContractFunction: {response.ReasonPhrase}"); - } - } - } -} diff --git a/MoralisDotNet/Moralis.Web3Api/CloudApi/ResolveApi.cs b/MoralisDotNet/Moralis.Web3Api/CloudApi/ResolveApi.cs deleted file mode 100644 index 245b8dc..0000000 --- a/MoralisDotNet/Moralis.Web3Api/CloudApi/ResolveApi.cs +++ /dev/null @@ -1,181 +0,0 @@ -/** -* Module: ResolveApi.cs -* Description: Represents a collection of functions to interact with the API endpoints -* Author: Moralis Web3 Technology AB, 559307-5988 - David B. Goodrich -* -* NOTE: THIS FILE HAS BEEN AUTOMATICALLY GENERATED. ANY CHANGES MADE TO THIS -* FILE WILL BE LOST -* -* MIT License -* -* Copyright (c) 2022 Moralis Web3 Technology AB, 559307-5988 -* -* Permission is hereby granted, free of charge, to any person obtaining a copy -* of this software and associated documentation files (the 'Software'), to deal -* in the Software without restriction, including without limitation the rights -* to use, copy, modify, merge, publish, distribute, sublicense, and / or sell -* copies of the Software, and to permit persons to whom the Software is -* furnished to do so, subject to the following conditions: -* -* The above copyright notice and this permission notice shall be included in all -* copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -* SOFTWARE. -*/ -using System; -using System.Collections.Generic; -using Newtonsoft.Json; -using System.Net; -using System.Threading.Tasks; -using Moralis.Network; -using Moralis.Web3Api.Interfaces; -using Moralis.Web3Api.Models; -using System.Net.Http; - -namespace Moralis.Web3Api.CloudApi -{ - /// - /// Represents a collection of functions to interact with the API endpoints - /// - public class ResolveApi : IResolveApi - { - /// - /// Initializes a new instance of the class. - /// - /// an instance of ApiClient (optional) - /// - public ResolveApi(ApiClient apiClient = null) - { - if (apiClient == null) // use the default one in Configuration - this.ApiClient = Configuration.DefaultApiClient; - else - this.ApiClient = apiClient; - } - - /// - /// Initializes a new instance of the class. - /// - /// - public ResolveApi(String basePath) - { - this.ApiClient = new ApiClient(basePath); - } - - /// - /// Sets the base path of the API client. - /// - /// The base path - /// The base path - public void SetBasePath(String basePath) - { - this.ApiClient.BasePath = basePath; - } - - /// - /// Gets the base path of the API client. - /// - /// The base path - /// The base path - public String GetBasePath(String basePath) - { - return this.ApiClient.BasePath; - } - - /// - /// Gets or sets the API client. - /// - /// An instance of the ApiClient - public ApiClient ApiClient {get; set;} - - - /// - /// Resolves an Unstoppable domain and returns the address - /// - /// - /// Domain to be resolved - /// The currency to query - /// Returns an address - public async Task ResolveDomain (string domain, string currency=null) - { - // Verify the required parameter 'domain' is set - if (domain == null) throw new ApiException(400, "Missing required parameter 'domain' when calling ResolveDomain"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/resolveDomain"; - if (domain != null) postBody.Add("domain", ApiClient.ParameterToString(domain)); - if (currency != null) postBody.Add("currency", ApiClient.ParameterToString(currency)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling ResolveDomain: {response.ReasonPhrase}"); - } - } - - /// - /// Resolves an ETH address and find the ENS name - /// - /// - /// The address to be resolved - /// Returns an ENS - public async Task ResolveAddress (string address) - { - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling ResolveAddress"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/resolveAddress"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling ResolveAddress: {response.ReasonPhrase}"); - } - } - } -} diff --git a/MoralisDotNet/Moralis.Web3Api/CloudApi/StorageApi.cs b/MoralisDotNet/Moralis.Web3Api/CloudApi/StorageApi.cs deleted file mode 100644 index 803c398..0000000 --- a/MoralisDotNet/Moralis.Web3Api/CloudApi/StorageApi.cs +++ /dev/null @@ -1,138 +0,0 @@ -/** -* Module: StorageApi.cs -* Description: Represents a collection of functions to interact with the API endpoints -* Author: Moralis Web3 Technology AB, 559307-5988 - David B. Goodrich -* -* NOTE: THIS FILE HAS BEEN AUTOMATICALLY GENERATED. ANY CHANGES MADE TO THIS -* FILE WILL BE LOST -* -* MIT License -* -* Copyright (c) 2022 Moralis Web3 Technology AB, 559307-5988 -* -* Permission is hereby granted, free of charge, to any person obtaining a copy -* of this software and associated documentation files (the 'Software'), to deal -* in the Software without restriction, including without limitation the rights -* to use, copy, modify, merge, publish, distribute, sublicense, and / or sell -* copies of the Software, and to permit persons to whom the Software is -* furnished to do so, subject to the following conditions: -* -* The above copyright notice and this permission notice shall be included in all -* copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -* SOFTWARE. -*/ -using System; -using System.Collections.Generic; -using Newtonsoft.Json; -using System.Net; -using System.Threading.Tasks; -using Moralis.Network; -using Moralis.Web3Api.Interfaces; -using Moralis.Web3Api.Models; -using System.Net.Http; - -namespace Moralis.Web3Api.CloudApi -{ - /// - /// Represents a collection of functions to interact with the API endpoints - /// - public class StorageApi : IStorageApi - { - /// - /// Initializes a new instance of the class. - /// - /// an instance of ApiClient (optional) - /// - public StorageApi(ApiClient apiClient = null) - { - if (apiClient == null) // use the default one in Configuration - this.ApiClient = Configuration.DefaultApiClient; - else - this.ApiClient = apiClient; - } - - /// - /// Initializes a new instance of the class. - /// - /// - public StorageApi(String basePath) - { - this.ApiClient = new ApiClient(basePath); - } - - /// - /// Sets the base path of the API client. - /// - /// The base path - /// The base path - public void SetBasePath(String basePath) - { - this.ApiClient.BasePath = basePath; - } - - /// - /// Gets the base path of the API client. - /// - /// The base path - /// The base path - public String GetBasePath(String basePath) - { - return this.ApiClient.BasePath; - } - - /// - /// Gets or sets the API client. - /// - /// An instance of the ApiClient - public ApiClient ApiClient {get; set;} - - - /// - /// Uploads multiple files and place them in a folder directory - /// - /// - /// Array of JSON and Base64 Supported - /// Returns the path to the uploaded files - public async Task> UploadFolder (List abi) - { - // Verify the required parameter 'abi' is set - if (abi == null) throw new ApiException(400, "Missing required parameter 'abi' when calling UploadFolder"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/uploadFolder"; - if (abi != null) postBody.Add("abi", ApiClient.ParameterToString(abi)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult>)ApiClient.Deserialize(data, typeof(CloudFunctionResult>), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling UploadFolder: {response.ReasonPhrase}"); - } - } - } -} diff --git a/MoralisDotNet/Moralis.Web3Api/CloudApi/TokenApi.cs b/MoralisDotNet/Moralis.Web3Api/CloudApi/TokenApi.cs deleted file mode 100644 index 2944e5f..0000000 --- a/MoralisDotNet/Moralis.Web3Api/CloudApi/TokenApi.cs +++ /dev/null @@ -1,1051 +0,0 @@ -/** -* Module: TokenApi.cs -* Description: Represents a collection of functions to interact with the API endpoints -* Author: Moralis Web3 Technology AB, 559307-5988 - David B. Goodrich -* -* NOTE: THIS FILE HAS BEEN AUTOMATICALLY GENERATED. ANY CHANGES MADE TO THIS -* FILE WILL BE LOST -* -* MIT License -* -* Copyright (c) 2022 Moralis Web3 Technology AB, 559307-5988 -* -* Permission is hereby granted, free of charge, to any person obtaining a copy -* of this software and associated documentation files (the 'Software'), to deal -* in the Software without restriction, including without limitation the rights -* to use, copy, modify, merge, publish, distribute, sublicense, and / or sell -* copies of the Software, and to permit persons to whom the Software is -* furnished to do so, subject to the following conditions: -* -* The above copyright notice and this permission notice shall be included in all -* copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -* SOFTWARE. -*/ -using System; -using System.Collections.Generic; -using Newtonsoft.Json; -using System.Net; -using System.Threading.Tasks; -using Moralis.Network; -using Moralis.Web3Api.Interfaces; -using Moralis.Web3Api.Models; -using System.Net.Http; - -namespace Moralis.Web3Api.CloudApi -{ - /// - /// Represents a collection of functions to interact with the API endpoints - /// - public class TokenApi : ITokenApi - { - /// - /// Initializes a new instance of the class. - /// - /// an instance of ApiClient (optional) - /// - public TokenApi(ApiClient apiClient = null) - { - if (apiClient == null) // use the default one in Configuration - this.ApiClient = Configuration.DefaultApiClient; - else - this.ApiClient = apiClient; - } - - /// - /// Initializes a new instance of the class. - /// - /// - public TokenApi(String basePath) - { - this.ApiClient = new ApiClient(basePath); - } - - /// - /// Sets the base path of the API client. - /// - /// The base path - /// The base path - public void SetBasePath(String basePath) - { - this.ApiClient.BasePath = basePath; - } - - /// - /// Gets the base path of the API client. - /// - /// The base path - /// The base path - public String GetBasePath(String basePath) - { - return this.ApiClient.BasePath; - } - - /// - /// Gets or sets the API client. - /// - /// An instance of the ApiClient - public ApiClient ApiClient {get; set;} - - - /// - /// Returns metadata (name, symbol, decimals, logo) for a given token contract address. - /// - /// The addresses to get metadata for - /// The chain to query - /// The subdomain of the moralis server to use (Only use when selecting local devchain as chain) - /// web3 provider url to user when using local dev chain - /// Returns metadata (name, symbol, decimals, logo) for a given token contract address. - public async Task> GetTokenMetadata (List addresses, ChainList chain, string subdomain=null, string providerUrl=null) - { - // Verify the required parameter 'addresses' is set - if (addresses == null) throw new ApiException(400, "Missing required parameter 'addresses' when calling GetTokenMetadata"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getTokenMetadata"; - if (addresses != null) postBody.Add("addresses", ApiClient.ParameterToString(addresses)); - if (subdomain != null) postBody.Add("subdomain", ApiClient.ParameterToString(subdomain)); - if (providerUrl != null) postBody.Add("providerUrl", ApiClient.ParameterToString(providerUrl)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult>)ApiClient.Deserialize(data, typeof(CloudFunctionResult>), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetTokenMetadata: {response.ReasonPhrase}"); - } - } - - /// - /// Get the nft trades for a given contracts and marketplace - /// - /// Address of the contract - /// The chain to query - /// The minimum block number from where to get the transfers - /// * Provide the param 'from_block' or 'from_date' - /// * If 'from_date' and 'from_block' are provided, 'from_block' will be used. - /// - /// To get the reserves at this block number - /// The date from where to get the transfers (any format that is accepted by momentjs) - /// * Provide the param 'from_block' or 'from_date' - /// * If 'from_date' and 'from_block' are provided, 'from_block' will be used. - /// - /// Get the reserves to this date (any format that is accepted by momentjs) - /// * Provide the param 'to_block' or 'to_date' - /// * If 'to_date' and 'to_block' are provided, 'to_block' will be used. - /// - /// web3 provider url to user when using local dev chain - /// marketplace from where to get the trades (only opensea is supported at the moment) - /// offset - /// limit - /// Returns the trades - public async Task GetNFTTrades (string address, ChainList chain, string cursor="", int? fromBlock=null, string toBlock=null, string fromDate=null, string toDate=null, string providerUrl=null, string marketplace=null, int? limit=null) - { - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetNFTTrades"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getNFTTrades"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (fromBlock != null) postBody.Add("from_block", ApiClient.ParameterToString(fromBlock)); - if (toBlock != null) postBody.Add("to_block", ApiClient.ParameterToString(toBlock)); - if (fromDate != null) postBody.Add("from_date", ApiClient.ParameterToString(fromDate)); - if (toDate != null) postBody.Add("to_date", ApiClient.ParameterToString(toDate)); - if (providerUrl != null) postBody.Add("provider_url", ApiClient.ParameterToString(providerUrl)); - if (marketplace != null) postBody.Add("marketplace", ApiClient.ParameterToString(marketplace)); - if (cursor != null) postBody.Add("offset", ApiClient.ParameterToString(cursor)); - if (limit != null) postBody.Add("limit", ApiClient.ParameterToString(limit)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetNFTTrades: {response.ReasonPhrase}"); - } - } - - /// - /// Get the lowest price found for a nft token contract for the last x days (only trades paid in ETH) - /// - /// Address of the contract - /// The chain to query - /// The number of days to look back to find the lowest price - /// If not provided 7 days will be the default - /// - /// web3 provider url to user when using local dev chain - /// marketplace from where to get the trades (only opensea is supported at the moment) - /// Returns the trade with the lowest price - public async Task GetNFTLowestPrice (string address, ChainList chain, int? days=null, string providerUrl=null, string marketplace=null) - { - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetNFTLowestPrice"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getNFTLowestPrice"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (days != null) postBody.Add("days", ApiClient.ParameterToString(days)); - if (providerUrl != null) postBody.Add("provider_url", ApiClient.ParameterToString(providerUrl)); - if (marketplace != null) postBody.Add("marketplace", ApiClient.ParameterToString(marketplace)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetNFTLowestPrice: {response.ReasonPhrase}"); - } - } - - /// - /// Returns metadata (name, symbol, decimals, logo) for a given token contract address. - /// - /// The symbols to get metadata for - /// The chain to query - /// The subdomain of the moralis server to use (Only use when selecting local devchain as chain) - /// Returns metadata (name, symbol, decimals, logo) for a given token contract address. - public async Task> GetTokenMetadataBySymbol (List symbols, ChainList chain, string subdomain=null) - { - // Verify the required parameter 'symbols' is set - if (symbols == null) throw new ApiException(400, "Missing required parameter 'symbols' when calling GetTokenMetadataBySymbol"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getTokenMetadataBySymbol"; - if (symbols != null) postBody.Add("symbols", ApiClient.ParameterToString(symbols)); - if (subdomain != null) postBody.Add("subdomain", ApiClient.ParameterToString(subdomain)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult>)ApiClient.Deserialize(data, typeof(CloudFunctionResult>), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetTokenMetadataBySymbol: {response.ReasonPhrase}"); - } - } - - /// - /// Returns the price nominated in the native token and usd for a given token contract address. - /// - /// The address of the token contract - /// The chain to query - /// web3 provider url to user when using local dev chain - /// The factory name or address of the token exchange - /// to_block - /// Returns the price nominated in the native token and usd for a given token contract address - public async Task GetTokenPrice (string address, ChainList chain, string providerUrl=null, string exchange=null, int? toBlock=null) - { - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetTokenPrice"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getTokenPrice"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (providerUrl != null) postBody.Add("providerUrl", ApiClient.ParameterToString(providerUrl)); - if (exchange != null) postBody.Add("exchange", ApiClient.ParameterToString(exchange)); - if (toBlock != null) postBody.Add("to_block", ApiClient.ParameterToString(toBlock)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetTokenPrice: {response.ReasonPhrase}"); - } - } - - /// - /// Gets ERC20 token contract transactions in descending order based on block number - /// - /// The address of the token contract - /// The chain to query - /// The subdomain of the moralis server to use (Only use when selecting local devchain as chain) - /// The minimum block number from where to get the transfers - /// * Provide the param 'from_block' or 'from_date' - /// * If 'from_date' and 'from_block' are provided, 'from_block' will be used. - /// - /// The maximum block number from where to get the transfers. - /// * Provide the param 'to_block' or 'to_date' - /// * If 'to_date' and 'to_block' are provided, 'to_block' will be used. - /// - /// The date from where to get the transfers (any format that is accepted by momentjs) - /// * Provide the param 'from_block' or 'from_date' - /// * If 'from_date' and 'from_block' are provided, 'from_block' will be used. - /// - /// Get the transfers to this date (any format that is accepted by momentjs) - /// * Provide the param 'to_block' or 'to_date' - /// * If 'to_date' and 'to_block' are provided, 'to_block' will be used. - /// - /// offset - /// limit - /// Returns a collection of token contract transactions. - public async Task GetTokenAddressTransfers (string address, ChainList chain, string subdomain=null, int? fromBlock=null, int? toBlock=null, string fromDate=null, string toDate=null, int? offset=null, int? limit=null) - { - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetTokenAddressTransfers"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getTokenAddressTransfers"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (subdomain != null) postBody.Add("subdomain", ApiClient.ParameterToString(subdomain)); - if (fromBlock != null) postBody.Add("from_block", ApiClient.ParameterToString(fromBlock)); - if (toBlock != null) postBody.Add("to_block", ApiClient.ParameterToString(toBlock)); - if (fromDate != null) postBody.Add("from_date", ApiClient.ParameterToString(fromDate)); - if (toDate != null) postBody.Add("to_date", ApiClient.ParameterToString(toDate)); - if (offset != null) postBody.Add("offset", ApiClient.ParameterToString(offset)); - if (limit != null) postBody.Add("limit", ApiClient.ParameterToString(limit)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetTokenAddressTransfers: {response.ReasonPhrase}"); - } - } - - /// - /// Gets the amount which the spender is allowed to withdraw from the spender - /// - /// The address of the token contract - /// The address of the token owner - /// The address of the token spender - /// The chain to query - /// web3 provider url to user when using local dev chain - /// Returns the amount which the spender is allowed to withdraw from the owner.. - public async Task GetTokenAllowance (string address, string ownerAddress, string spenderAddress, ChainList chain, string providerUrl=null) - { - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetTokenAllowance"); - - // Verify the required parameter 'ownerAddress' is set - if (ownerAddress == null) throw new ApiException(400, "Missing required parameter 'ownerAddress' when calling GetTokenAllowance"); - - // Verify the required parameter 'spenderAddress' is set - if (spenderAddress == null) throw new ApiException(400, "Missing required parameter 'spenderAddress' when calling GetTokenAllowance"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getTokenAllowance"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (ownerAddress != null) postBody.Add("owner_address", ApiClient.ParameterToString(ownerAddress)); - if (spenderAddress != null) postBody.Add("spender_address", ApiClient.ParameterToString(spenderAddress)); - if (providerUrl != null) postBody.Add("providerUrl", ApiClient.ParameterToString(providerUrl)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetTokenAllowance: {response.ReasonPhrase}"); - } - } - - /// - /// Gets NFTs that match a given metadata search. - /// - /// The search string - /// The chain to query - /// The format of the token id - /// What fields the search should match on. To look into the entire metadata set the value to 'global'. To have a better response time you can look into a specific field like name - /// The minimum block number from where to start the search - /// * Provide the param 'from_block' or 'from_date' - /// * If 'from_date' and 'from_block' are provided, 'from_block' will be used. - /// - /// The maximum block number from where to end the search - /// * Provide the param 'to_block' or 'to_date' - /// * If 'to_date' and 'to_block' are provided, 'to_block' will be used. - /// - /// The date from where to start the search (any format that is accepted by momentjs) - /// * Provide the param 'from_block' or 'from_date' - /// * If 'from_date' and 'from_block' are provided, 'from_block' will be used. - /// - /// Get search results up until this date (any format that is accepted by momentjs) - /// * Provide the param 'to_block' or 'to_date' - /// * If 'to_date' and 'to_block' are provided, 'to_block' will be used. - /// - /// offset - /// limit - /// Returns the matching NFTs - public async Task SearchNFTs (string q, ChainList chain, string cursor="", string format=null, string filter=null, int? fromBlock=null, int? toBlock=null, string fromDate=null, string toDate=null, int? limit=null) - { - // Verify the required parameter 'q' is set - if (q == null) throw new ApiException(400, "Missing required parameter 'q' when calling SearchNFTs"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/searchNFTs"; - if (q != null) postBody.Add("q", ApiClient.ParameterToString(q)); - if (format != null) postBody.Add("format", ApiClient.ParameterToString(format)); - if (filter != null) postBody.Add("filter", ApiClient.ParameterToString(filter)); - if (fromBlock != null) postBody.Add("from_block", ApiClient.ParameterToString(fromBlock)); - if (toBlock != null) postBody.Add("to_block", ApiClient.ParameterToString(toBlock)); - if (fromDate != null) postBody.Add("from_date", ApiClient.ParameterToString(fromDate)); - if (toDate != null) postBody.Add("to_date", ApiClient.ParameterToString(toDate)); - if (cursor != null) postBody.Add("offset", ApiClient.ParameterToString(cursor)); - if (limit != null) postBody.Add("limit", ApiClient.ParameterToString(limit)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling SearchNFTs: {response.ReasonPhrase}"); - } - } - - /// - /// Gets the transfers of the tokens from a block number to a block number - /// - /// The chain to query - /// The minimum block number from where to get the transfers - /// * Provide the param 'from_block' or 'from_date' - /// * If 'from_date' and 'from_block' are provided, 'from_block' will be used. - /// - /// The maximum block number from where to get the transfers. - /// * Provide the param 'to_block' or 'to_date' - /// * If 'to_date' and 'to_block' are provided, 'to_block' will be used. - /// - /// The date from where to get the transfers (any format that is accepted by momentjs) - /// * Provide the param 'from_block' or 'from_date' - /// * If 'from_date' and 'from_block' are provided, 'from_block' will be used. - /// - /// Get transfers up until this date (any format that is accepted by momentjs) - /// * Provide the param 'to_block' or 'to_date' - /// * If 'to_date' and 'to_block' are provided, 'to_block' will be used. - /// - /// The format of the token id - /// offset - /// limit - /// Returns a collection of NFT transfers - public async Task GetNftTransfersFromToBlock (ChainList chain, string cursor="", int? fromBlock=null, int? toBlock=null, string fromDate=null, string toDate=null, string format=null, int? limit=null) - { - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getNftTransfersFromToBlock"; - if (fromBlock != null) postBody.Add("from_block", ApiClient.ParameterToString(fromBlock)); - if (toBlock != null) postBody.Add("to_block", ApiClient.ParameterToString(toBlock)); - if (fromDate != null) postBody.Add("from_date", ApiClient.ParameterToString(fromDate)); - if (toDate != null) postBody.Add("to_date", ApiClient.ParameterToString(toDate)); - if (format != null) postBody.Add("format", ApiClient.ParameterToString(format)); - if (cursor != null) postBody.Add("offset", ApiClient.ParameterToString(cursor)); - if (limit != null) postBody.Add("limit", ApiClient.ParameterToString(limit)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetNftTransfersFromToBlock: {response.ReasonPhrase}"); - } - } - - /// - /// Gets data, including metadata (where available), for all token ids for the given contract address. - /// * Results are sorted by the block the token id was minted (descending) and limited to 100 per page by default - /// * Requests for contract addresses not yet indexed will automatically start the indexing process for that NFT collection - /// - /// - /// Address of the contract - /// The chain to query - /// The format of the token id - /// offset - /// limit - /// Returns a collection of nfts - public async Task GetAllTokenIds (string address, ChainList chain, string format=null, string cursor = "", int? limit=null) - { - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetAllTokenIds"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getAllTokenIds"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (format != null) postBody.Add("format", ApiClient.ParameterToString(format)); - if (cursor != null) postBody.Add("offset", ApiClient.ParameterToString(cursor)); - if (limit != null) postBody.Add("limit", ApiClient.ParameterToString(limit)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetAllTokenIds: {response.ReasonPhrase}"); - } - } - - /// - /// Gets the transfers of the tokens matching the given parameters - /// - /// Address of the contract - /// The chain to query - /// The format of the token id - /// offset - /// limit - /// Returns a collection of NFT transfers - public async Task GetContractNFTTransfers (string address, ChainList chain, string format=null, string cursor = "", int? limit=null) - { - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetContractNFTTransfers"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getContractNFTTransfers"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (format != null) postBody.Add("format", ApiClient.ParameterToString(format)); - if (cursor != null) postBody.Add("offset", ApiClient.ParameterToString(cursor)); - if (limit != null) postBody.Add("limit", ApiClient.ParameterToString(limit)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetContractNFTTransfers: {response.ReasonPhrase}"); - } - } - - /// - /// Gets all owners of NFT items within a given contract collection - /// * Use after /nft/contract/{token_address} to find out who owns each token id in a collection - /// * Make sure to include a sort parm on a column like block_number_minted for consistent pagination results - /// * Requests for contract addresses not yet indexed will automatically start the indexing process for that NFT collection - /// - /// - /// Address of the contract - /// The chain to query - /// The format of the token id - /// offset - /// limit - /// Returns a collection of nft owners - public async Task GetNFTOwners (string address, ChainList chain, string format=null, string cursor = "", int? limit=null) - { - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetNFTOwners"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getNFTOwners"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (format != null) postBody.Add("format", ApiClient.ParameterToString(format)); - if (cursor != null) postBody.Add("offset", ApiClient.ParameterToString(cursor)); - if (limit != null) postBody.Add("limit", ApiClient.ParameterToString(limit)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetNFTOwners: {response.ReasonPhrase}"); - } - } - - /// - /// Gets the contract level metadata (name, symbol, base token uri) for the given contract - /// * Requests for contract addresses not yet indexed will automatically start the indexing process for that NFT collection - /// - /// - /// Address of the contract - /// The chain to query - /// Returns a collection NFT collections. - public async Task GetNFTMetadata (string address, ChainList chain) - { - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetNFTMetadata"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getNFTMetadata"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetNFTMetadata: {response.ReasonPhrase}"); - } - } - - /// - /// Gets data, including metadata (where available), for the given token id of the given contract address. - /// * Requests for contract addresses not yet indexed will automatically start the indexing process for that NFT collection - /// - /// - /// Address of the contract - /// The id of the token - /// The chain to query - /// The format of the token id - /// Returns the specified NFT - public async Task GetTokenIdMetadata (string address, string tokenId, ChainList chain, string format=null) - { - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetTokenIdMetadata"); - - // Verify the required parameter 'tokenId' is set - if (tokenId == null) throw new ApiException(400, "Missing required parameter 'tokenId' when calling GetTokenIdMetadata"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getTokenIdMetadata"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (tokenId != null) postBody.Add("token_id", ApiClient.ParameterToString(tokenId)); - if (format != null) postBody.Add("format", ApiClient.ParameterToString(format)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetTokenIdMetadata: {response.ReasonPhrase}"); - } - } - - /// - /// Gets all owners of NFT items within a given contract collection - /// * Use after /nft/contract/{token_address} to find out who owns each token id in a collection - /// * Make sure to include a sort parm on a column like block_number_minted for consistent pagination results - /// * Requests for contract addresses not yet indexed will automatically start the indexing process for that NFT collection - /// - /// - /// Address of the contract - /// The id of the token - /// The chain to query - /// The format of the token id - /// offset - /// limit - /// Returns a collection of NFTs with their respective owners - public async Task GetTokenIdOwners (string address, string tokenId, ChainList chain, string format=null, string cursor = "", int? limit=null) - { - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetTokenIdOwners"); - - // Verify the required parameter 'tokenId' is set - if (tokenId == null) throw new ApiException(400, "Missing required parameter 'tokenId' when calling GetTokenIdOwners"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getTokenIdOwners"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (tokenId != null) postBody.Add("token_id", ApiClient.ParameterToString(tokenId)); - if (format != null) postBody.Add("format", ApiClient.ParameterToString(format)); - if (cursor != null) postBody.Add("offset", ApiClient.ParameterToString(cursor)); - if (limit != null) postBody.Add("limit", ApiClient.ParameterToString(limit)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetTokenIdOwners: {response.ReasonPhrase}"); - } - } - - /// - /// Gets the transfers of the tokens matching the given parameters - /// - /// Address of the contract - /// The id of the token - /// The chain to query - /// The format of the token id - /// offset - /// limit - /// The field(s) to order on and if it should be ordered in ascending or descending order. Specified by: fieldName1.order,fieldName2.order. Example 1: "block_number", "block_number.ASC", "block_number.DESC", Example 2: "block_number and contract_type", "block_number.ASC,contract_type.DESC" - /// Returns a collection of NFT transfers - public async Task GetWalletTokenIdTransfers (string address, string tokenId, ChainList chain, string format = null, string cursor = "", int? limit = null, string order = null) - { - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling GetWalletTokenIdTransfers"); - - // Verify the required parameter 'tokenId' is set - if (tokenId == null) throw new ApiException(400, "Missing required parameter 'tokenId' when calling GetWalletTokenIdTransfers"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/getWalletTokenIdTransfers"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (tokenId != null) postBody.Add("token_id", ApiClient.ParameterToString(tokenId)); - if (format != null) postBody.Add("format", ApiClient.ParameterToString(format)); - if (cursor != null) postBody.Add("offset", ApiClient.ParameterToString(cursor)); - if (limit != null) postBody.Add("limit", ApiClient.ParameterToString(limit)); - if (order != null) postBody.Add("order", ApiClient.ParameterToString(order)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - string data = await response.Content.ReadAsStringAsync(); - List headers = ApiClient.ResponHeadersToParameterList(response.Headers); - - return ((CloudFunctionResult)ApiClient.Deserialize(data, typeof(CloudFunctionResult), headers)).Result; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling GetWalletTokenIdTransfers: {response.ReasonPhrase}"); - } - } - - /// - /// ReSync the metadata for an NFT - /// * The metadata flag will request a resync of the metadata for an nft - /// * The uri flag will request fetch the token_uri for an NFT and then fetch it's metadata. To be used when the token uri get updated - /// - /// - /// Address of the contract - /// The id of the token - /// The chain to query - /// the type of resync to operate - public async Task ReSyncMetadata(string address, string tokenId, ChainList chain) - { - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling ReSyncMetadata"); - - // Verify the required parameter 'tokenId' is set - if (tokenId == null) throw new ApiException(400, "Missing required parameter 'tokenId' when calling ReSyncMetadata"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/reSyncMetadata"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - if (tokenId != null) postBody.Add("token_id", ApiClient.ParameterToString(tokenId)); - //if (flag != null) postBody.Add("flag", ApiClient.ParameterToString(flag)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - return true; } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling ReSyncMetadata: {response.ReasonPhrase}"); - } - } - - /// - /// Sync a Contract for NFT Index - /// - /// - /// Address of the contract - /// The chain to query - public async Task SyncNFTContract(string address, ChainList chain) - { - // Verify the required parameter 'address' is set - if (address == null) throw new ApiException(400, "Missing required parameter 'address' when calling SyncNFTContract"); - - var postBody = new Dictionary(); - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); - var fileParams = new Dictionary(); - - var path = "/functions/syncNFTContract"; - if (address != null) postBody.Add("address", ApiClient.ParameterToString(address)); - postBody.Add("chain", ApiClient.ParameterToHex((long)chain)); - - // Authentication setting, if any - String[] authSettings = new String[] { "ApiKeyAuth" }; - - string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null; - - HttpResponseMessage response = - await ApiClient.CallApi(path, HttpMethod.Post, queryParams, bodyData, headerParams, formParams, fileParams, authSettings); - - if (HttpStatusCode.OK.Equals(response.StatusCode)) - { - return true; - } - else - { - throw new ApiException((int)response.StatusCode, $"Error calling SyncNFTContract: {response.ReasonPhrase}"); - } - } - } -} diff --git a/MoralisDotNet/Moralis.Web3Api/MoralisClient.cs b/MoralisDotNet/Moralis.Web3Api/MoralisWeb3ApiClient.cs similarity index 57% rename from MoralisDotNet/Moralis.Web3Api/MoralisClient.cs rename to MoralisDotNet/Moralis.Web3Api/MoralisWeb3ApiClient.cs index 5d583f6..4a0833f 100644 --- a/MoralisDotNet/Moralis.Web3Api/MoralisClient.cs +++ b/MoralisDotNet/Moralis.Web3Api/MoralisWeb3ApiClient.cs @@ -7,32 +7,23 @@ namespace Moralis.Web3Api /// /// Provides an easy to wrapper around the Moralis Web3Api REST services. /// - public class MoralisClient + public class MoralisWeb3ApiClient { Web3ApiClient client = new Web3ApiClient(); - static MoralisClient instance = new MoralisClient(); + static MoralisWeb3ApiClient instance = new MoralisWeb3ApiClient(); - private MoralisClient() { } - - /// - /// Initialize Moralis Web3API. Use this to initialize to your personal - /// Moralis server. Major advantage is api key is supplied - /// - /// - public static void Initialize(string url) => instance.client.Initialize(url); + private MoralisWeb3ApiClient() { } /// /// Initialize Moralis Web3API. /// - /// If true enforces use of the standard REST server - /// Required if useStandardServer is true /// Optional server url. If not provided default standard server Url is used. - public static void Initialize(bool useStandardServer, string apiKey = null, string url = null) + /// Required if useStandardServer is true + public static void Initialize(string url, string apiKey) { - if (useStandardServer && !(apiKey is { })) throw new ArgumentException("API Key is required for Standard REST server."); + Configuration.ApiKey["X-API-Key"] = apiKey; - if (apiKey is { }) Configuration.ApiKey["X-API-Key"] = apiKey; instance.client.Initialize(url); } diff --git a/MoralisDotNet/Moralis/Core/Expections/MoralisSaveException.cs b/MoralisDotNet/Moralis/Core/Expections/MoralisSaveException.cs deleted file mode 100644 index c741115..0000000 --- a/MoralisDotNet/Moralis/Core/Expections/MoralisSaveException.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; - -namespace Moralis.Core.Exceptions -{ - public class MoralisSaveException : Exception - { - public MoralisSaveException() { } - - public MoralisSaveException(string message) : base(message) { } - } -} \ No newline at end of file diff --git a/MoralisDotNet/Moralis/Core/Expections/MoralisSignupException.cs b/MoralisDotNet/Moralis/Core/Expections/MoralisSignupException.cs deleted file mode 100644 index d597757..0000000 --- a/MoralisDotNet/Moralis/Core/Expections/MoralisSignupException.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; - -namespace Moralis.Core.Exceptions -{ - public class MoralisSignupException : Exception - { - public MoralisSignupException() { } - - public MoralisSignupException(string message) : base(message) { } - } -} \ No newline at end of file diff --git a/MoralisDotNet/Moralis/Platform/ServerConnectionData.cs b/MoralisDotNet/Moralis/Models/ServerConnectionData.cs similarity index 63% rename from MoralisDotNet/Moralis/Platform/ServerConnectionData.cs rename to MoralisDotNet/Moralis/Models/ServerConnectionData.cs index 993a4c9..a4beb5a 100644 --- a/MoralisDotNet/Moralis/Platform/ServerConnectionData.cs +++ b/MoralisDotNet/Moralis/Models/ServerConnectionData.cs @@ -1,15 +1,16 @@ -using System; -using System.Collections.Generic; -using Moralis.Platform.Abstractions; +using System.Collections.Generic; -namespace Moralis.Platform +namespace Moralis.Models { /// - /// Represents the configuration of the Moralis SDK. + /// /// - public struct ServerConnectionData : IServerConnectionData + public class ServerConnectionData { - public bool Test { get; set; } + public ServerConnectionData() + { + Web3ApiUrl = "https://deep-index.moralis.io/api/v2"; + } /// /// The App ID of your app. @@ -19,12 +20,7 @@ public struct ServerConnectionData : IServerConnectionData /// /// A URI pointing to the target Moralis Server instance hosting the app targeted by . /// - public string ServerURI { get; set; } - - /// - /// A URI pointing to the target Moralis WS/WSS server. - /// - public string LiveQueryServerURI { get; set; } + public string DappUrl { get; set; } /// /// The Web3Api key, must be supplied to initialize Web3Api to use @@ -33,29 +29,28 @@ public struct ServerConnectionData : IServerConnectionData public string ApiKey { get; set; } /// - /// The .NET Key for the Moralis app targeted by . + /// The Master Key for the Moralis app targeted by . /// - public string Key { get; set; } + public string MasterKey { get; set; } /// - /// The Master Key for the Moralis app targeted by . + /// URL for the Authentication 2.0 API /// - public string MasterKey { get; set; } + public string AuthenticationApiUrl { get; set; } /// - /// Used to + /// URL for Web3 Api and Solana Api /// - public string LocalStoragePath { get; set; } + public string Web3ApiUrl { get; set; } /// - /// URL for the Authentication 2.0 API + /// API version to use for Web3 API and Solana API. /// - public string AuthenticationApiUrl { get; set; } + public string Web3ApiVersionIndicator { get; set; } /// /// Additional HTTP headers to be sent with network requests from the SDK. /// public IDictionary Headers { get; set; } } - } diff --git a/MoralisDotNet/Moralis/MoralisClient.cs b/MoralisDotNet/Moralis/MoralisClient.cs index 12049be..96c4c6c 100644 --- a/MoralisDotNet/Moralis/MoralisClient.cs +++ b/MoralisDotNet/Moralis/MoralisClient.cs @@ -1,358 +1,202 @@ using System; -using System.Threading.Tasks; -using Moralis.Platform; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Queries; -using Moralis.Platform.Services.ClientServices; -using Moralis.Platform.Utilities; -using System.Collections.Generic; -using System.Threading; +using Moralis.AuthApi.Interfaces; using Moralis.Web3Api.Interfaces; using Moralis.SolanaApi.Interfaces; -using Moralis.AuthApi.Interfaces; -using Moralis.Platform.Services.Infrastructure; +using Moralis.Models; +using Moralis.SolanaApi; +using Moralis.Web3Api; +using Moralis.AuthApi; namespace Moralis { - public class MoralisClient : IDisposable + /// + /// Main object used to access Moralis APIs and other functioinality. + /// + public class MoralisClient { - string serverAuthToken = ""; - string serverAuthType = ""; - - public MoralisClient(ServerConnectionData connectionData, IWeb3Api web3Api = null, ISolanaApi solanaApi = null, IJsonSerializer jsonSerializer = null, IAuthClientApi authApi = null) - { - if (jsonSerializer == null) - { - throw new ArgumentException("jsonSerializer cannot be null."); - } - - connectionData.Key = connectionData.Key ?? ""; - - moralisService = new MoralisService(connectionData.ApplicationID, connectionData.ServerURI, connectionData.Key, jsonSerializer); - moralisService.ServerConnectionData.Key = connectionData.Key; - moralisService.ServerConnectionData.ServerURI = connectionData.ServerURI; - moralisService.ServerConnectionData.ApplicationID = connectionData.ApplicationID; - moralisService.ServerConnectionData.LocalStoragePath = connectionData.LocalStoragePath; - - // Make sure local folder for Unity apps is used if defined. - MoralisCacheService.BaseFilePath = connectionData.LocalStoragePath; - - // Make sure singleton instance is available. - moralisService.Publicize(); - - // Default to always save. - ServiceHub.AlwaysSave = true; - - this.Web3Api = web3Api; - - if (this.Web3Api is { }) - { - if (connectionData.ApiKey is { }) - { - this.Web3Api.Initialize(); - } - else - { - this.Web3Api.Initialize(connectionData.ServerURI); - } - } + #region Instance variables + private IAuthClientApi AuthenticationApiClient { get; set; } + private ISolanaApi SolanaApiClient { get; set; } + private IWeb3Api Web3ApiClient { get; set; } + #endregion - this.SolanaApi = solanaApi; + #region Class level variables + private static MoralisClient instance; - if (this.SolanaApi is { }) + /// + /// Instance of the Authentication API + /// + public static IAuthClientApi AuthenticationApi + { + get { - if (connectionData.ApiKey is { }) + // Initialize Moralis using default values if it has not been initialized. + if (!IsInitialized) { - this.SolanaApi.Initialize(); + Start(); } - else - { - this.SolanaApi.Initialize(connectionData.ServerURI); - } - } - this.AuthenticationApi = authApi; - - if (this.AuthenticationApi is { }) - { - if (connectionData.AuthenticationApiUrl is { }) - { - this.AuthenticationApi.Initialize(connectionData.AuthenticationApiUrl); - } + return instance.AuthenticationApiClient; } } + /// + /// The information used to connect to Moralis Services + /// + public static ServerConnectionData ConnectionData { get; set; } - public string EthAddress { get; } - - public IServiceHub ServiceHub => moralisService.Services; - - MoralisService moralisService; - - public void SetLocalDatastoreController() - { - throw new NotImplementedException(); - } - - public string ApplicationId + /// + /// Indicates if the Moralis Client has been initialized. + /// + public static bool IsInitialized { - get => moralisService.ServerConnectionData.ApplicationID; - set - { - moralisService.ServerConnectionData.ApplicationID = value; - } + get { return instance != null; } } - public string Key + /// + /// Instance of the Solana API + /// + public static ISolanaApi SolanaApi { - get => moralisService.ServerConnectionData.Key; - set + get { - moralisService.ServerConnectionData.Key = value; - } - } + // Initialize Moralis using default values if it has not been initialized. + if (!IsInitialized) + { + Start(); + } - public string MasterKey - { - get => moralisService.ServerConnectionData.MasterKey; - set - { - moralisService.ServerConnectionData.MasterKey = value; + return instance.SolanaApiClient; } } - public string ServerUrl + /// + /// Instance of the Web3 Api + /// + public static IWeb3Api Web3Api { - get => moralisService.ServerConnectionData.ServerURI; - set + get { - moralisService.ServerConnectionData.ServerURI = value; - - if (string.IsNullOrWhiteSpace(moralisService.ServerConnectionData.LiveQueryServerURI)) + // Initialize Moralis using default values if it has not been initialized. + if (!IsInitialized) { - LiveQueryServerUrl = Conversion.WebUriToWsURi(moralisService.ServerConnectionData.ServerURI); + Start(); } - } - } - - public string LiveQueryServerUrl - { - get => moralisService.ServerConnectionData.LiveQueryServerURI; - set => moralisService.ServerConnectionData.LiveQueryServerURI = value; - } - - public void SetServerAuthToken(string value) - { - serverAuthToken = value; - } - - public string GetServerAuthToken() - { - return serverAuthToken; - } - - public void SetServerAuthType(string value) - { - serverAuthToken = value; - } - - public string GetServerAuthType() - { - return serverAuthToken; - } - public IFileService File => moralisService.FileService; - public IInstallationService InstallationService => moralisService.InstallationService; - public IQueryService QueryService => moralisService.QueryService; - public ISessionService Session => moralisService.SessionService; - public IUserService UserService => moralisService.UserService; - - public MoralisCloud Cloud => moralisService.Cloud; - - public async Task GetInstallationIdAsync() => await InstallationService.GetAsync(); - - public async Task> Query() where T : MoralisObject - { - MoralisUser user = await GetCurrentUser(); - - return new MoralisQuery(this.QueryService, InstallationService, moralisService.ServerConnectionData, moralisService.JsonSerializer, user != null ? user.sessionToken : null); //, logger); - } - - public T Create(object[] parameters = null) where T : MoralisObject - { - return this.ServiceHub.Create(parameters); - } - - public Task GetCurrentUser() => this.ServiceHub.GetCurrentUser(); - - - public void Dispose() - { - MoralisLiveQueryManager.DisposeService(); + return instance.Web3ApiClient; + } } /// - /// Retrieve user object by sesion token. + /// Default initializer of the Moralis Client /// - /// - /// Task - public Task UserFromSession(string sessionToken) + /// ConnectionData must be supplied. + public static void Start() { - return this.ServiceHub.BecomeAsync(sessionToken); + if (ConnectionData is { }) + { + Start(ConnectionData); + } + else + { + throw new ArgumentNullException(nameof(ConnectionData)); + } } + #endregion /// - /// Provid async user login. - /// data: - /// id: Address - /// signature: Signature from wallet - /// data: Message that was signed + /// Initialize Moralis Client using Connection Data to derive all API clients /// - /// Authentication data - /// Task - public Task LogInAsync(IDictionary data) - { - return this.LogInAsync(data, CancellationToken.None); - } - - - /// Provid async user login. - /// data: - /// id: Address - /// signature: Signature from wallet - /// data: Message that was signed - /// - /// Authentication data - /// - /// Task - public Task LogInAsync(IDictionary data, CancellationToken cancellationToken) - { - return this.ServiceHub.LogInWithAsync("moralisEth", data, cancellationToken); + /// + public static void Start(ServerConnectionData connectionData) + { + Start(connectionData, null, null, null); } /// - /// Logs out the current user. + /// Initialize Moralis Client by providing connection data and pre-initialized Api Clients /// - /// - public Task LogOutAsync() - { - return this.ServiceHub.LogOutAsync(); + /// + /// + /// + /// + public static void Start(ServerConnectionData connectionData, IAuthClientApi authApi = null, ISolanaApi solanaApi = null, IWeb3Api web3Api = null) + { + instance = new MoralisClient(connectionData, authApi, solanaApi, web3Api); } /// - /// Constructs a query that is the and of the given queries. + /// Creates an instance of the Moralis Client. /// - /// The type of MoralisObject being queried. - /// - /// An initial query to 'and' with additional queries. - /// The list of MoralisQueries to 'and' together. - /// A query that is the and of the given queries. - public MoralisQuery BuildAndQuery(MoralisQuery source, params MoralisQuery[] queries) where T : MoralisObject - { - return ServiceHub.ConstructAndQuery(source, queries); - } + /// + /// + /// + /// + /// + private MoralisClient(ServerConnectionData connectionData, IAuthClientApi authApi = null, ISolanaApi solanaApi = null, IWeb3Api web3Api = null) + { + // Api Key is required + if (string.IsNullOrEmpty(connectionData.ApiKey)) throw new ArgumentNullException(nameof(connectionData.ApiKey)); + // Master Key is required. + if (string.IsNullOrEmpty(connectionData.MasterKey)) throw new ArgumentNullException(nameof(connectionData.MasterKey)); + // Auth 2.0 Api URI is required. + if (string.IsNullOrEmpty(connectionData.AuthenticationApiUrl)) throw new ArgumentNullException(nameof(connectionData.AuthenticationApiUrl)); + + ConnectionData = connectionData; + + // -------------------------------------------------------------------------------- + // Setp Authentication Api + // -------------------------------------------------------------------------------- + AuthenticationApiClient = authApi; + + if (AuthenticationApiClient is { }) + { + AuthenticationApiClient.Initialize(connectionData.AuthenticationApiUrl); + } + else + { + MoralisAuthApiClient.Initialize(connectionData.AuthenticationApiUrl, connectionData.ApiKey); - /// - /// Construct a query that is the and of two or more queries. - /// - /// - /// - /// The list of MoralisQueries to 'and' together. - /// A MoralisQquery that is the 'and' of the passed in queries. - public MoralisQuery BuildAndQuery(IEnumerable> queries) where T : MoralisObject - { - return ServiceHub.ConstructAndQuery(queries); - } - - /// - /// Constructs a query that is the or of the given queries. - /// - /// The type of MoralisObject being queried. - /// An initial query to 'or' with additional queries. - /// The list of MoralisQueries to 'or' together. - /// A query that is the or of the given queries. - public MoralisQuery BuildOrQuery(MoralisQuery source, params MoralisQuery[] queries) where T : MoralisObject - { - return ServiceHub.ConstructOrQuery(source, queries); - } + AuthenticationApiClient = MoralisAuthApiClient.AuthenticationApi; + } - /// - /// Construct a query that is the 'or' of two or more queries. - /// - /// - /// - /// The list of MoralisQueries to 'and' together. - /// A MoralisQquery that is the 'or' of the passed in queries. - public MoralisQuery BuildOrQuery(IEnumerable> queries) where T : MoralisObject - { - return ServiceHub.ConstructOrQuery(queries); - } + // -------------------------------------------------------------------------------- + // Setup Solana Api + // -------------------------------------------------------------------------------- + SolanaApiClient = solanaApi; - /// - /// Constructs a query that is the nor of the given queries. - /// - /// The type of MoralisObject being queried. - /// An initial query to 'or' with additional queries. - /// The list of MoralisQueries to 'or' together. - /// A query that is the nor of the given queries. - public MoralisQuery BuildNorQuery(MoralisQuery source, params MoralisQuery[] queries) where T : MoralisObject - { - return ServiceHub.ConstructNorQuery(source, queries); - } + if (SolanaApiClient is { }) + { + SolanaApiClient.Initialize(); + } + else + { + // Api URI is required. + if (string.IsNullOrEmpty(connectionData.Web3ApiUrl)) throw new ArgumentNullException(nameof(connectionData.Web3ApiUrl)); - /// - /// Construct a query that is the 'nor' of two or more queries. - /// - /// - /// - /// The list of MoralisQueries to 'and' together. - /// A MoralisQquery that is the 'nor' of the passed in queries. - public MoralisQuery BuildNorQuery(IEnumerable> queries) where T : MoralisObject - { - return ServiceHub.ConstructNorQuery(queries); - } + MoralisSolanaApiClient.Initialize(connectionData.Web3ApiUrl, connectionData.ApiKey); - /// - /// Deletes target object from the Moralis database. - /// - /// - /// - /// - public Task DeleteAsync(T target) where T : MoralisObject - { - return target.DeleteAsync(); - } + SolanaApiClient = MoralisSolanaApiClient.SolanaApi; + } - /// - /// Provide an object hook for Web3Api incase developer supplies a - /// web3api client at initialize - /// - public IWeb3Api Web3Api { get; private set; } + // -------------------------------------------------------------------------------- + // Setp Web3 Api + // -------------------------------------------------------------------------------- + Web3ApiClient = web3Api; - /// - /// Provide an object hook for SolanaApi - /// - public ISolanaApi SolanaApi { get; private set; } + if (Web3ApiClient is { }) + { + Web3ApiClient.Initialize(); + } + else + { + // Api URI is required. + if (string.IsNullOrEmpty(connectionData.Web3ApiUrl)) throw new ArgumentNullException(nameof(connectionData.Web3ApiUrl)); - /// - /// Provide an object hook for AuthAppi - /// - public IAuthClientApi AuthenticationApi { get; private set; } + MoralisWeb3ApiClient.Initialize(connectionData.Web3ApiUrl, connectionData.ApiKey); - /// - /// Included so that this can be set prior to initialization for systems - /// (Unity, Xamarin, etc.) that may not have Assembly Attributes available. - /// - public static HostManifestData ManifestData - { - get => Platform.Services.ServiceHub.ManifestData; - set - { - Platform.Services.ServiceHub.ManifestData = value; - Platform.Services.MutableServiceHub.ManifestData = value; + Web3ApiClient = MoralisWeb3ApiClient.Web3Api; } } } } - diff --git a/MoralisDotNet/Moralis/MoralisDynamic.cs b/MoralisDotNet/Moralis/MoralisDynamic.cs deleted file mode 100644 index 3e6bae1..0000000 --- a/MoralisDotNet/Moralis/MoralisDynamic.cs +++ /dev/null @@ -1,372 +0,0 @@ -using System; -using System.Threading.Tasks; -using Moralis.Platform; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Queries; -using Moralis.Platform.Services.ClientServices; -using System.Collections.Generic; -using System.Threading; -using Moralis.Web3Api.Interfaces; -using Moralis.Platform.Services.Infrastructure; -using Moralis.SolanaApi.Interfaces; -using System.Threading.Tasks; - -namespace Moralis -{ - public class MoralisClient where TUser : MoralisUser - { - string serverAuthToken = ""; - string serverAuthType = ""; - - public MoralisClient(ServerConnectionData connectionData, IWeb3Api web3Api = null, ISolanaApi solanaApi = null, IJsonSerializer jsonSerializer = null) - { - if (jsonSerializer == null) - { - throw new ArgumentException("jsonSerializer cannot be null."); - } - - connectionData.Key = connectionData.Key ?? ""; - - moralisService = new MoralisService(connectionData.ApplicationID, connectionData.ServerURI, connectionData.Key, jsonSerializer); - moralisService.ServerConnectionData.Key = connectionData.Key; - moralisService.ServerConnectionData.ServerURI = connectionData.ServerURI; - moralisService.ServerConnectionData.ApplicationID = connectionData.ApplicationID; moralisService.ServerConnectionData.LocalStoragePath = connectionData.LocalStoragePath; - - // Make sure local folder for Unity apps is used if defined. - MoralisCacheService.BaseFilePath = connectionData.LocalStoragePath; - - // Make sure singleton instance is available. - moralisService.Publicize(); - - this.Web3Api = web3Api; - - if (this.Web3Api is { }) - { - if (connectionData.ApiKey is { }) - { - this.Web3Api.Initialize(); - } - else - { - this.Web3Api.Initialize(connectionData.ServerURI); - } - } - - this.SolanaApi = solanaApi; - - if (this.SolanaApi is { }) - { - if (connectionData.ApiKey is { }) - { - this.SolanaApi.Initialize(); - } - else - { - this.SolanaApi.Initialize(connectionData.ServerURI); - } - } - } - - - public string EthAddress { get; } - - public IServiceHub ServiceHub => moralisService.Services; - - MoralisService moralisService; - - public void SetLocalDatastoreController() - { - throw new NotImplementedException(); - } - - public string ApplicationId - { - get => moralisService.ServerConnectionData.ApplicationID; - set - { - moralisService.ServerConnectionData.ApplicationID = value; - } - } - - public string Key - { - get => moralisService.ServerConnectionData.Key; - set - { - moralisService.ServerConnectionData.Key = value; - } - } - - public string MasterKey - { - get => moralisService.ServerConnectionData.MasterKey; - set - { - moralisService.ServerConnectionData.MasterKey = value; - } - } - - public string ServerUrl - { - get => moralisService.ServerConnectionData.ServerURI; - set - { - moralisService.ServerConnectionData.ServerURI = value; - } - } - - public void SetServerAuthToken(string value) - { - serverAuthToken = value; - } - - public string GetServerAuthToken() - { - return serverAuthToken; - } - - public void SetServerAuthType(string value) - { - serverAuthToken = value; - } - - public string GetServerAuthType() - { - return serverAuthToken; - } - - public void SetLiveQueryServerURL(string value) - { - throw new NotImplementedException(); - } - - public string GetLiveQueryServerURL() - { - throw new NotImplementedException(); - } - - public void SetEncryptedUser(string value) - { - throw new NotImplementedException(); - } - - public string GetEncryptedUser() - { - throw new NotImplementedException(); - } - - public void SetSecret(string value) - { - throw new NotImplementedException(); - } - - public string GetSecret() - { - throw new NotImplementedException(); - } - - public void SetIdempotency(string value) - { - throw new NotImplementedException(); - } - - public string GetIdempotency() - { - throw new NotImplementedException(); - } - - public IFileService File => moralisService.FileService; - - public IInstallationService InstallationService => moralisService.InstallationService; - public IQueryService QueryService => moralisService.QueryService; - public ISessionService Session => moralisService.SessionService; - public IUserService UserService => moralisService.UserService; - - public MoralisCloud Cloud => moralisService.Cloud; - - - public async Task GetInstallationIdAsync() => await InstallationService.GetAsync(); - - //public MoralisQuery Query() where T : MoralisObject - //{ - // return new MoralisQuery(this.ServiceHub.QueryService, InstallationService, moralisService.ServerConnectionData, moralisService.JsonSerializer, this.ServiceHub.CurrentUserService.CurrentUser.sessionToken); - //} - public async Task> Query() where T : MoralisObject - { - MoralisUser user = await GetCurrentUser(); - - return new MoralisQuery(this.QueryService, InstallationService, moralisService.ServerConnectionData, moralisService.JsonSerializer, user.sessionToken); //, logger); - } - public T Create(object[] parameters = null) where T : MoralisObject - { - return this.ServiceHub.Create(parameters); - } - - public Task GetCurrentUser() => this.ServiceHub.GetCurrentUser(); - - - public void Dispose() - { - MoralisLiveQueryManager.DisposeService(); - - } - - /// - /// Retrieve user object by sesion token. - /// - /// - /// Task - public Task UserFromSession(string sessionToken) - { - return this.ServiceHub.BecomeAsync(sessionToken); - } - - /// - /// Provid async user login. - /// data: - /// id: Address - /// signature: Signature from wallet - /// data: Message that was signed - /// - /// Authentication data - /// Task - public Task LogInAsync(IDictionary data) - { - return this.LogInAsync(data, CancellationToken.None); - } - - /// Provid async user login. - /// data: - /// id: Address - /// signature: Signature from wallet - /// data: Message that was signed - /// - /// Authentication data - /// - /// Task - public Task LogInAsync(IDictionary data, CancellationToken cancellationToken) - { - return this.ServiceHub.LogInWithAsync("moralisEth", data, cancellationToken); - } - - /// - /// Logs out the current user. - /// - /// - public Task LogOutAsync() - { - return this.ServiceHub.LogOutAsync(); - } - /// - /// Constructs a query that is the and of the given queries. - /// - /// The type of MoralisObject being queried. - /// - /// An initial query to 'and' with additional queries. - /// The list of MoralisQueries to 'and' together. - /// A query that is the and of the given queries. - public MoralisQuery BuildAndQuery(MoralisQuery source, params MoralisQuery[] queries) where T : MoralisObject - { - return ServiceHub.ConstructAndQuery(source, queries); - } - - /// - /// Construct a query that is the and of two or more queries. - /// - /// - /// - /// The list of MoralisQueries to 'and' together. - /// A MoralisQquery that is the 'and' of the passed in queries. - public MoralisQuery BuildAndQuery(IEnumerable> queries) where T : MoralisObject - { - return ServiceHub.ConstructAndQuery(queries); - } - - /// - /// Constructs a query that is the or of the given queries. - /// - /// The type of MoralisObject being queried. - /// An initial query to 'or' with additional queries. - /// The list of MoralisQueries to 'or' together. - /// A query that is the or of the given queries. - public MoralisQuery BuildOrQuery(MoralisQuery source, params MoralisQuery[] queries) where T : MoralisObject - { - return ServiceHub.ConstructOrQuery(source, queries); - } - - /// - /// Construct a query that is the 'or' of two or more queries. - /// - /// - /// - /// The list of MoralisQueries to 'and' together. - /// A MoralisQquery that is the 'or' of the passed in queries. - public MoralisQuery BuildOrQuery(IEnumerable> queries) where T : MoralisObject - { - return ServiceHub.ConstructOrQuery(queries); - } - - /// - /// Constructs a query that is the nor of the given queries. - /// - /// The type of MoralisObject being queried. - /// An initial query to 'or' with additional queries. - /// The list of MoralisQueries to 'or' together. - /// A query that is the nor of the given queries. - public MoralisQuery BuildNorQuery(MoralisQuery source, params MoralisQuery[] queries) where T : MoralisObject - { - return ServiceHub.ConstructNorQuery(source, queries); - } - - /// - /// Construct a query that is the 'nor' of two or more queries. - /// - /// - /// - /// The list of MoralisQueries to 'and' together. - /// A MoralisQquery that is the 'nor' of the passed in queries. - public MoralisQuery BuildNorQuery(IEnumerable> queries) where T : MoralisObject - { - return ServiceHub.ConstructNorQuery(queries); - } - - /// - /// Deletes target object from the Moralis database. - /// - /// - /// - /// - public Task DeleteAsync(T target) where T : MoralisObject - { - return target.DeleteAsync(); - } - - /// - /// Provide an object hook for Web3Api incase developer supplies a - /// web3api client at initialize - /// - public IWeb3Api Web3Api { get; private set; } - - /// - /// Provide an object hook for SolanaApi - /// - public ISolanaApi SolanaApi { get; private set; } - - /// - /// Included so that this can be set prior to initialization for systems - /// (Unity, Xamarin, etc.) that may not have Assembly Attributes available. - /// - public static HostManifestData ManifestData - { - get => Platform.Services.ServiceHub.ManifestData; - set - { - Platform.Services.ServiceHub.ManifestData = value; - Platform.Services.MutableServiceHub.ManifestData = value; - } - } - } - - -} diff --git a/MoralisDotNet/Moralis/MoralisLiveQueryCallbacks.cs b/MoralisDotNet/Moralis/MoralisLiveQueryCallbacks.cs deleted file mode 100644 index 16ef0a2..0000000 --- a/MoralisDotNet/Moralis/MoralisLiveQueryCallbacks.cs +++ /dev/null @@ -1,140 +0,0 @@ -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Queries.Live; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Moralis -{ - public class MoralisLiveQueryCallbacks : ILiveQueryCallbacks where T : MoralisObject - { - - /// - /// Called when a connected event is returned from the server. - /// - public event LiveQueryConnectedHandler OnConnectedEvent; - - /// - /// Called when a subscribed event is returned from the server. - /// - public event LiveQuerySubscribedHandler OnSubscribedEvent; - - /// - /// Called when a create event is returned from the server. - /// - public event LiveQueryActionHandler OnCreateEvent; - - /// - /// Called when a delete event is returned from the server. - /// - public event LiveQueryActionHandler OnDeleteEvent; - - /// - /// Called when a enter event is returned from the server. - /// - public event LiveQueryActionHandler OnEnterEvent; - - /// - /// Called when a leave event is returned from the server. - /// - public event LiveQueryActionHandler OnLeaveEvent; - - /// - /// Called when a update event is returned from the server. - /// - public event LiveQueryActionHandler OnUpdateEvent; - - /// - /// Called when a ubsubscribed event is received. - /// - public event LiveQueryUnsubscribedHandler OnUnsubscribedEvent; - - /// - /// Called when an ErrorMEssage is received. - /// - public event LiveQueryErrorHandler OnErrorEvent; - - public event LiveQueryGeneralMessageHandler OnGeneralMessageEvent; - - public void OnConnected() - { - if (OnConnectedEvent != null) - { - OnConnectedEvent(); - } - } - - public void OnCreate(T item, int requestId) - { - if (OnCreateEvent != null) - { - OnCreateEvent(item, requestId); - } - } - - public void OnDelete(T item, int requestId) - { - if (OnDeleteEvent != null) - { - OnDeleteEvent(item, requestId); - } - } - - public void OnEnter(T item, int requestId) - { - if (OnEnterEvent != null) - { - OnEnterEvent(item, requestId); - } - } - - public void OnError(ErrorMessage em) - { - if (OnErrorEvent != null) - { - OnErrorEvent(em); - } - } - - public void OnLeave(T item, int requestId) - { - if (OnLeaveEvent != null) - { - OnLeaveEvent(item, requestId); - } - } - - public void OnSubscribed(int requestId) - { - if (OnSubscribedEvent != null) - { - OnSubscribedEvent(requestId); - } - } - - public void OnUnsubscribed(int requestId) - { - if (OnUnsubscribedEvent != null) - { - OnUnsubscribedEvent(requestId); - } - } - - public void OnUpdate(T item, int requestId) - { - if (OnUpdateEvent != null) - { - OnUpdateEvent(item, requestId); - } - } - - public void OnGeneralMessage(string text) - { - if (OnGeneralMessageEvent != null) - { - OnGeneralMessageEvent(text); - } - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/CustomServiceHub.cs b/MoralisDotNet/Moralis/Platform/Abstractions/CustomServiceHub.cs deleted file mode 100644 index 1cee111..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/CustomServiceHub.cs +++ /dev/null @@ -1,80 +0,0 @@ - -using System; -using System.Reflection; -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Abstractions -{ - public abstract class CustomServiceHub : ICustomServiceHub where TUser : MoralisUser - { - public bool AlwaysSave { get; set; } - - public virtual IServiceHub Services { get; internal set; } - - //public virtual IServiceHubCloner Cloner => Services.Cloner; - - public virtual IMetadataService MetadataService => Services.MetadataService; - - /// - /// Provides Serialization / Deserialization services. - /// - public virtual IJsonSerializer JsonSerializer => Services.JsonSerializer; - - public virtual IWebClient WebClient => Services.WebClient; - - public virtual ICacheService CacheService => Services.CacheService; - - //public virtual IParseObjectClassController ClassController => Services.ClassController; - - public IInstallationService InstallationService => Services.InstallationService; - - public virtual IMoralisCommandRunner CommandRunner => Services.CommandRunner; - - public virtual ICloudFunctionService CloudFunctionService => Services.CloudFunctionService; - - //public virtual IParseConfigurationController ConfigurationController => Services.ConfigurationController; - - public virtual IFileService FileService => Services.FileService; - - public virtual IObjectService ObjectService => Services.ObjectService; - - public virtual IQueryService QueryService => Services.QueryService; - - public virtual ISessionService SessionService => Services.SessionService; - - public virtual IUserService UserService => Services.UserService; - - public virtual ICurrentUserService CurrentUserService => Services.CurrentUserService; - - //public virtual IParseAnalyticsController AnalyticsController => Services.AnalyticsController; - - //public virtual IParseInstallationCoder InstallationCoder => Services.InstallationCoder; - - //public virtual IParsePushChannelsController PushChannelsController => Services.PushChannelsController; - - //public virtual IParsePushController PushController => Services.PushController; - - //public virtual IParseCurrentInstallationController CurrentInstallationController => Services.CurrentInstallationController; - - public virtual IServerConnectionData ServerConnectionData => Services.ServerConnectionData; - - //public virtual IParseDataDecoder Decoder => Services.Decoder; - - //public virtual IParseInstallationDataFinalizer InstallationDataFinalizer => Services.InstallationDataFinalizer; - public T Create(object[] parameters) where T : MoralisObject - { - T thing; - - if (parameters is { } && parameters.Length > 0) - thing = (T)Activator.CreateInstance(typeof(T), parameters); - else - thing = (T)Activator.CreateInstance(typeof(T)); - - thing.sessionToken = this.CurrentUserService.CurrentUser.sessionToken; - thing.ObjectService = this.ObjectService; - - return thing; - } - } - -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IAuthenticationProvider.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IAuthenticationProvider.cs deleted file mode 100644 index 39bf26f..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IAuthenticationProvider.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; - -namespace Moralis.Platform.Abstractions -{ - public interface IAuthenticationProvider - { - /// - /// Authenticates with the service. - /// - /// The cancellation token. - Task> AuthenticateAsync(CancellationToken cancellationToken); - - /// - /// Deauthenticates (logs out) the user associated with this provider. This - /// call may block. - /// - void Deauthenticate(); - - /// - /// Restores authentication that has been serialized, such as session keys, - /// etc. - /// - /// The auth data for the provider. This value may be null - /// when unlinking an account. - /// true iff the authData was successfully synchronized. A false return - /// value indicates that the user should no longer be associated because of bad auth - /// data. - bool RestoreAuthentication(IDictionary authData); - - /// - /// Provides a unique name for the type of authentication the provider does. - /// For example, the FacebookAuthenticationProvider would return "facebook". - /// - string AuthType { get; } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/ICacheService.cs b/MoralisDotNet/Moralis/Platform/Abstractions/ICacheService.cs deleted file mode 100644 index 9732450..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/ICacheService.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; - -namespace Moralis.Platform.Abstractions -{ - /// - /// An abstraction for accessing persistent storage in the Moralis SDK. - /// - public interface ICacheService - { - /// - /// Cleans up any temporary files and/or directories created during SDK operation. - /// - public void Clear(); - - /// - /// Gets the file wrapper for the specified . - /// - /// The relative path to the target file - /// An instance of wrapping the the value - FileInfo GetRelativeFile(string path); - - /// - /// Transfers a file from to . - /// - /// - /// - /// A task that completes once the file move operation form to completes. - Task TransferAsync(string originFilePath, string targetFilePath); - - /// - /// Load the contents of this storage controller asynchronously. - /// - /// - Task> LoadAsync(); - - /// - /// Overwrites the contents of this storage controller asynchronously. - /// - /// - /// - Task> SaveAsync(IDictionary contents); - } - -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IClientWebSocket.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IClientWebSocket.cs deleted file mode 100644 index 8392d06..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IClientWebSocket.cs +++ /dev/null @@ -1,155 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net.WebSockets; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace Moralis.Platform.Abstractions -{ - public interface IClientWebSocket : IDisposable - { - // - // Summary: - // Gets the reason why the close handshake was initiated on System.Net.WebSockets.ClientWebSocket - // instance. - // - // Returns: - // Returns System.Net.WebSockets.WebSocketCloseStatus. The reason why the close - // handshake was initiated. - WebSocketCloseStatus? CloseStatus { get; } - // - // Summary: - // Gets a description of the reason why the System.Net.WebSockets.ClientWebSocket - // instance was closed. - // - // Returns: - // Returns System.String. The description of the reason why the System.Net.WebSockets.ClientWebSocket - // instance was closed. - string CloseStatusDescription { get; } - // - // Summary: - // Gets the WebSocket options for the System.Net.WebSockets.ClientWebSocket instance. - // - // Returns: - // Returns System.Net.WebSockets.ClientWebSocketOptions. The WebSocket options for - // the System.Net.WebSockets.ClientWebSocket instance. - ClientWebSocketOptions Options { get; } - // - // Summary: - // Get the WebSocket state of the System.Net.WebSockets.ClientWebSocket instance. - // - // Returns: - // Returns System.Net.WebSockets.WebSocketState. The WebSocket state of the System.Net.WebSockets.ClientWebSocket - // instance. - WebSocketState State { get; } - // - // Summary: - // Gets the supported WebSocket sub-protocol for the System.Net.WebSockets.ClientWebSocket - // instance. - // - // Returns: - // Returns System.String. The supported WebSocket sub-protocol. - string SubProtocol { get; } - - // - // Summary: - // Aborts the connection and cancels any pending IO operations. - void Abort(); - // - // Summary: - // Close the System.Net.WebSockets.ClientWebSocket instance as an asynchronous operation. - // - // Parameters: - // closeStatus: - // The WebSocket close status. - // - // statusDescription: - // A description of the close status. - // - // cancellationToken: - // A cancellation token used to propagate notification that this operation should - // be canceled. - // - // Returns: - // Returns System.Threading.Tasks.Task. The task object representing the asynchronous - // operation. - Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken); - // - // Summary: - // Close the output for the System.Net.WebSockets.ClientWebSocket instance as an - // asynchronous operation. - // - // Parameters: - // closeStatus: - // The WebSocket close status. - // - // statusDescription: - // A description of the close status. - // - // cancellationToken: - // A cancellation token used to propagate notification that this operation should - // be canceled. - // - // Returns: - // Returns System.Threading.Tasks.Task. The task object representing the asynchronous - // operation. - Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken); - // - // Summary: - // Connect to a WebSocket server as an asynchronous operation. - // - // Parameters: - // uri: - // The URI of the WebSocket server to connect to. - // - // cancellationToken: - // A cancellation token used to propagate notification that the operation should - // be canceled. - // - // Returns: - // Returns System.Threading.Tasks.Task. The task object representing the asynchronous - // operation. - Task ConnectAsync(Uri uri, CancellationToken cancellationToken); - - // - // Summary: - // Receive data on System.Net.WebSockets.ClientWebSocket as an asynchronous operation. - // - // Parameters: - // buffer: - // The buffer to receive the response. - // - // cancellationToken: - // A cancellation token used to propagate notification that this operation should - // be canceled. - // - // Returns: - // Returns System.Threading.Tasks.Task`1. The task object representing the asynchronous - // operation. - Task ReceiveAsync(ArraySegment buffer, CancellationToken cancellationToken); - // - // Summary: - // Send data on System.Net.WebSockets.ClientWebSocket as an asynchronous operation. - // - // Parameters: - // buffer: - // The buffer containing the message to be sent. - // - // messageType: - // Specifies whether the buffer is clear text or in a binary format. - // - // endOfMessage: - // Specifies whether this is the final asynchronous send. Set to true if this is - // the final send; false otherwise. - // - // cancellationToken: - // A cancellation token used to propagate notification that this operation should - // be canceled. - // - // Returns: - // The task object representing the asynchronous operation. - Task SendAsync(ArraySegment buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken); - - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/ICloudFunctionService.cs b/MoralisDotNet/Moralis/Platform/Abstractions/ICloudFunctionService.cs deleted file mode 100644 index fc1c39d..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/ICloudFunctionService.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; - -namespace Moralis.Platform.Abstractions -{ - public interface ICloudFunctionService - { - Task CallFunctionAsync(string name, IDictionary parameters, string sessionToken, CancellationToken cancellationToken = default); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/ICurrentObjectService.cs b/MoralisDotNet/Moralis/Platform/Abstractions/ICurrentObjectService.cs deleted file mode 100644 index 031bd8a..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/ICurrentObjectService.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Abstractions -{ - public interface ICurrentObjectService where T : MoralisObject where TUser : MoralisUser - { - /// - /// Persists current . - /// - /// to be persisted. - /// The cancellation token. - Task SetAsync(T obj, CancellationToken cancellationToken = default); - - /// - /// Gets the persisted current . - /// - /// The cancellation token. - Task GetAsync(IServiceHub serviceHub, CancellationToken cancellationToken = default); - - /// - /// Returns a that resolves to true if current - /// exists. - /// - /// The cancellation token. - Task ExistsAsync(CancellationToken cancellationToken = default); - - /// - /// Returns true if the given is the persisted current - /// . - /// - /// The object to check. - /// true if obj is the current persisted . - bool IsCurrent(T obj); - - /// - /// Nullifies the current from memory. - /// - void ClearFromMemory(); - - /// - /// Clears current from disk. - /// - Task ClearFromDiskAsync(); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/ICurrentUserService.cs b/MoralisDotNet/Moralis/Platform/Abstractions/ICurrentUserService.cs deleted file mode 100644 index a90156a..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/ICurrentUserService.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Abstractions -{ - public interface ICurrentUserService : ICurrentObjectService where TUser : MoralisUser - { - TUser CurrentUser { get; set; } - - Task GetCurrentSessionTokenAsync(IServiceHub serviceHub, CancellationToken cancellationToken = default); - - Task LogOutAsync(IServiceHub serviceHub, CancellationToken cancellationToken = default); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/ICustomServiceHub.cs b/MoralisDotNet/Moralis/Platform/Abstractions/ICustomServiceHub.cs deleted file mode 100644 index 05e46c3..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/ICustomServiceHub.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Abstractions -{ - public interface ICustomServiceHub : IServiceHub where TUser : MoralisUser - { - IServiceHub Services { get; } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IDataCache.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IDataCache.cs deleted file mode 100644 index cba733d..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IDataCache.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; - -namespace Moralis.Platform.Abstractions -{ - /// - /// An interface for a dictionary that is persisted to disk asynchronously. - /// - /// They key type of the dictionary. - /// The value type of the dictionary. - public interface IDataCache : IDictionary - { - /// - /// Adds a key to this dictionary, and saves it asynchronously. - /// - /// The key to insert. - /// The value to insert. - /// - Task AddAsync(TKey key, TValue value); - - /// - /// Removes a key from this dictionary, and saves it asynchronously. - /// - /// - /// - Task RemoveAsync(TKey key); - } - -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IDataTransferLevel.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IDataTransferLevel.cs deleted file mode 100644 index 8396551..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IDataTransferLevel.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Moralis.Platform.Abstractions -{ - public interface IDataTransferLevel - { - double Amount { get; set; } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IDiskFileCacheService.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IDiskFileCacheService.cs deleted file mode 100644 index 76ee2bc..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IDiskFileCacheService.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; - -namespace Moralis.Platform.Abstractions -{ - /// - /// An which stores the cache on disk via a file. - /// - public interface IDiskFileCacheService : ICacheService - { - /// - /// The path to a persistent user-specific storage location specific to the final client assembly of the Moralis library. - /// - public string AbsoluteCacheFilePath { get; set; } - - /// - /// The relative path from the on the device an to application-specific persistent storage folder. - /// - public string RelativeCacheFilePath { get; set; } - - /// - /// Refreshes this cache controller's internal tracked cache file to reflect the and/or . - /// - /// This will not delete the active tracked cache file that will be un-tracked after a call to this method. To do so, call . - void RefreshPaths(); - } - -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IEnvironmentData.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IEnvironmentData.cs deleted file mode 100644 index 1567bf9..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IEnvironmentData.cs +++ /dev/null @@ -1,25 +0,0 @@ - -namespace Moralis.Platform.Abstractions -{ - /// - /// Information about the environment in which the library will be operating. - /// - public interface IEnvironmentData - { - /// - /// The currently active time zone when the library will be used. - /// - string TimeZone { get; } - - /// - /// The operating system version of the platform the SDK is operating in. - /// - string OSVersion { get; } - - /// - /// An identifier of the platform. - /// - /// Expected to be one of ios, android, winrt, winphone, or dotnet. - public string Platform { get; set; } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IFileService.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IFileService.cs deleted file mode 100644 index c9e3238..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IFileService.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Abstractions -{ - public interface IFileService - { - Task SaveAsync(MoralisFileState state, Stream dataStream, string sessionToken, IProgress progress, CancellationToken cancellationToken); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IHostManifestData.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IHostManifestData.cs deleted file mode 100644 index 7719ac5..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IHostManifestData.cs +++ /dev/null @@ -1,31 +0,0 @@ - - -namespace Moralis.Platform.Abstractions -{ - /// - /// Information about the application using the Parse SDK. - /// - public interface IHostManifestData - { - /// - /// The build number of your app. - /// - string Version { get; } - - /// - /// The human friendly version number of your app. - /// - string ShortVersion { get; } - - /// - /// A unique string representing your app. - /// - string Identifier { get; } - - /// - /// The name of your app. - /// - string Name { get; } - } - -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IInstallationService.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IInstallationService.cs deleted file mode 100644 index 7f832a1..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IInstallationService.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Threading.Tasks; - -namespace Moralis.Platform.Abstractions -{ - public interface IInstallationService - { - /// - /// The current installation Id. - /// - Guid? InstallationId { get; } - - /// - /// Sets current installationId and saves it to local storage. - /// - /// The installationId to be saved. - Task SetAsync(Guid? installationId); - - /// - /// Gets current installationId from local storage. Generates a none exists. - /// - /// Current installationId. - Task GetAsync(); - - /// - /// Clears current installationId from memory and local storage. - /// - Task ClearAsync(); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IJsonConvertible.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IJsonConvertible.cs deleted file mode 100644 index 1b3cebf..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IJsonConvertible.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Moralis.Platform.Abstractions -{ - /// - /// Represents an object that can be converted into JSON. - /// - public interface IJsonConvertible - { - /// - /// Converts the object to a data structure that can be converted to JSON. - /// - /// An object to be JSONified. - IDictionary ConvertToJSON(); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IJsonSerializer.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IJsonSerializer.cs deleted file mode 100644 index e4164c3..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IJsonSerializer.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Collections.Generic; - - -namespace Moralis.Platform.Abstractions -{ - /// - /// Defines an interface for common json serialization functions. - /// - public interface IJsonSerializer - { - IDictionary DefaultOptions { get; set; } - - /// - /// Performs deserialization of json into object of type T - /// - /// Type of opbject - /// Json serialized object - /// Serialization objects. Implementation must map relevant options type. - /// Type - T Deserialize(string json, IDictionary options = null); - - /// - /// Json serializes target using provided options. - /// - /// Object to serialize - /// Serialization objects. Implementation must map relevant options type. - /// Json string - string Serialize(object target, IDictionary options = null); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/ILiveQueryCallbacks.cs b/MoralisDotNet/Moralis/Platform/Abstractions/ILiveQueryCallbacks.cs deleted file mode 100644 index c691226..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/ILiveQueryCallbacks.cs +++ /dev/null @@ -1,60 +0,0 @@ -using Moralis.Platform.Objects; -using Moralis.Platform.Queries.Live; - -namespace Moralis.Platform.Abstractions -{ - public interface ILiveQueryCallbacks where T : MoralisObject - { - /// - /// Called when a connected event is returned from the server. - /// - void OnConnected (); - - /// - /// Called when a subscribed event is returned from the server. - /// - void OnSubscribed (int requestId); - - /// - /// Called when a create event is returned from the server. - /// - void OnCreate(T item, int requestId); - - /// - /// Called when a delete event is returned from the server. - /// - void OnDelete(T item, int requestId); - - /// - /// Called when a enter event is returned from the server. - /// - void OnEnter(T item, int requestId); - - /// - /// Called when a leave event is returned from the server. - /// - void OnLeave(T item, int requestId); - - /// - /// Called when a update event is returned from the server. - /// - void OnUpdate(T item, int requestId); - - /// - /// Called when a ubsubscribed event is received. - /// - void OnUnsubscribed (int requestId); - - /// - /// Called when an error message is recevied. - /// - /// - void OnError(ErrorMessage em); - - /// - /// Called when a general message is reported by the client. - /// - /// - void OnGeneralMessage(string text); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/ILiveQueryClient.cs b/MoralisDotNet/Moralis/Platform/Abstractions/ILiveQueryClient.cs deleted file mode 100644 index 11537b6..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/ILiveQueryClient.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using Moralis.Platform.Objects; -using Moralis.Platform.Queries.Live; - -namespace Moralis.Platform.Abstractions -{ - public interface ILiveQueryClient : IDisposable - { - /// - /// Called when a connected event is returned from the server. - /// - event LiveQueryConnectedHandler OnConnected; - - /// - /// Called when a subscribed event is returned from the server. - /// - event LiveQuerySubscribedHandler OnSubscribed; - - /// - /// Called when a ubsubscribed event is received. - /// - event LiveQueryUnsubscribedHandler OnUnsubscribed; - - /// - /// Called when an ErrorMEssage is received. - /// - event LiveQueryErrorHandler OnError; - - /// - /// Indicates the current status of this client. - /// - LiveQueryClientStatusTypes ClientStatus { get; set; } - - /// - /// Server connection settings. - /// - IServerConnectionData ConncetionData { get; set; } - - string InstallationId { get; set; } - /// - /// Request Id used for this subscription - /// - int RequestId { get; } - /// - /// User session token. - /// - string SessionToken { get; set; } - - /// - /// Unsubscribe from the live query server. - /// - void Unsubscribe(); - - /// - /// Create a query subscription to the Live Query server. - /// - void Subscribe(); - -#if UNITY_WEBGL - /// - /// For WebGL Only should be called on Unity Update. - /// - void HandleUpdateEvent(); -#endif - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/ILiveQueryService.cs b/MoralisDotNet/Moralis/Platform/Abstractions/ILiveQueryService.cs deleted file mode 100644 index fca3821..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/ILiveQueryService.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Moralis.Platform.Abstractions -{ - public interface ILiveQueryService : IDisposable - { - /// - /// Adds a live query subscription to the service - /// - /// - void AddSubscription(ILiveQueryClient client); - - /// - /// Returns all active subscriptions. - /// - /// IEnumerable - IEnumerable Subscriptions(); - - /// - /// Issues unsubscribe message to all subscriptions that are currently subscribed. - /// - /// Task - void UnsubscribeAll(); - -#if UNITY_WEBGL - /// - /// For WebGL Only should be called on Unity Update. - /// - void HandleUpdateEvent(); -#endif - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IMetadataService.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IMetadataService.cs deleted file mode 100644 index f2af7fa..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IMetadataService.cs +++ /dev/null @@ -1,20 +0,0 @@ - -namespace Moralis.Platform.Abstractions -{ - /// - /// A controller for metadata. This is provided in a dependency injection container because if a beta feature is activated for a client managing a specific aspect of application operation, then this might need to be reflected in the application versioning information as it is used to determine the data cache location. - /// - /// This container could have been implemented as a or , due to it's simplicity but, more information may be added in the future so it is kept general. - public interface IMetadataService - { - /// - /// Information about the application using the Parse SDK. - /// - public IHostManifestData HostManifestData { get; } - - /// - /// Environment data specific to the application hosting the Parse SDK. - /// - public IEnvironmentData EnvironmentData { get; } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IMoralisCommandRunner.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IMoralisCommandRunner.cs deleted file mode 100644 index cb9b328..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IMoralisCommandRunner.cs +++ /dev/null @@ -1,23 +0,0 @@ - -using System; -using System.Collections.Generic; -using System.Net; -using System.Threading; -using System.Threading.Tasks; -using Moralis.Platform.Services.Models; - -namespace Moralis.Platform.Abstractions -{ - public interface IMoralisCommandRunner - { - /// - /// Executes and convert the result into Dictionary. - /// - /// The command to be run. - /// Upload progress callback. - /// Download progress callback. - /// The cancellation token for the request. - /// - Task> RunCommandAsync(MoralisCommand command, IProgress uploadProgress = null, IProgress downloadProgress = null, CancellationToken cancellationToken = default); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IMoralisFieldOperation.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IMoralisFieldOperation.cs deleted file mode 100644 index cb2ffc9..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IMoralisFieldOperation.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Moralis.Platform.Abstractions; - -namespace Moralis.Platform.Abstractions -{ - /// - /// A MoralisFieldOperation represents a modification to a value in a MoralisObject. - /// For example, setting, deleting, or incrementing a value are all different kinds of - /// MoralisFieldOperations. MoralisFieldOperations themselves can be considered to be - /// immutable. - /// - public interface IMoralisFieldOperation - { - /// - /// Converts the MoralisFieldOperation to a data structure that can be converted to JSON and sent to - /// Moralis as part of a save operation. - /// - /// An object to be JSONified. - //object Encode(IServiceHub serviceHub); - - /// - /// Returns a field operation that is composed of a previous operation followed by - /// this operation. This will not mutate either operation. However, it may return - /// this if the current operation is not affected by previous changes. - /// For example: - /// {increment by 2}.MergeWithPrevious({set to 5}) -> {set to 7} - /// {set to 5}.MergeWithPrevious({increment by 2}) -> {set to 5} - /// {add "foo"}.MergeWithPrevious({delete}) -> {set to ["foo"]} - /// {delete}.MergeWithPrevious({add "foo"}) -> {delete} /// - /// The most recent operation on the field, or null if none. - /// A new MoralisFieldOperation or this. - IMoralisFieldOperation MergeWithPrevious(IMoralisFieldOperation previous); - - /// - /// Returns a new estimated value based on a previous value and this operation. This - /// value is not intended to be sent to Moralis, but it is used locally on the client to - /// inspect the most likely current value for a field. - /// - /// The key and object are used solely for MoralisRelation to be able to construct objects - /// that refer back to their parents. - /// - /// The previous value for the field. - /// The key that this value is for. - /// The new value for the field. - object Apply(object oldValue, string key); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IMutableServiceHub.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IMutableServiceHub.cs deleted file mode 100644 index 9fa0bb0..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IMutableServiceHub.cs +++ /dev/null @@ -1,39 +0,0 @@ -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Abstractions -{ - public interface IMutableServiceHub : IServiceHub where TUser : MoralisUser - { - new IServerConnectionData ServerConnectionData { set; } - new IMetadataService MetadataService { set; } - new IJsonSerializer JsonSerializer { set; } - //IServiceHubCloner Cloner { set; } - - new IWebClient WebClient { set; } - new ICacheService CacheService { set; } - //IParseObjectClassController ClassController { set; } - - //IParseDataDecoder Decoder { set; } - - //IParseInstallationController InstallationController { set; } - new IMoralisCommandRunner CommandRunner { set; } - - //IParseCloudCodeController CloudCodeController { set; } - //IParseConfigurationController ConfigurationController { set; } - //IParseFileController FileController { set; } - //IParseObjectController ObjectController { set; } - //IParseQueryController QueryController { set; } - //IParseSessionController SessionController { set; } - new IUserService UserService { set; } - new ICurrentUserService CurrentUserService { get; } - - //IParseAnalyticsController AnalyticsController { set; } - - //IParseInstallationCoder InstallationCoder { set; } - - //IParsePushChannelsController PushChannelsController { set; } - //IParsePushController PushController { set; } - //IParseCurrentInstallationController CurrentInstallationController { set; } - //IParseInstallationDataFinalizer InstallationDataFinalizer { set; } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IObjectService.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IObjectService.cs deleted file mode 100644 index 0f44af1..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IObjectService.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading; -using Moralis.Platform.Abstractions; -using System.Threading.Tasks; -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Abstractions -{ - public interface IObjectService - { - Task FetchAsync(T item, string sessionToken, CancellationToken cancellationToken = default) where T : MoralisObject; - - Task SaveAsync(MoralisObject item, IDictionary operations, string sessionToken, CancellationToken cancellationToken = default); - - //IList> SaveAllAsync(IList states, IList serviceHub, CancellationToken cancellationToken = default) where T : MoralisObject; - - Task DeleteAsync(MoralisObject item, string sessionToken, CancellationToken cancellationToken = default); - - //IList DeleteAllAsync(IList items, string sessionToken, CancellationToken cancellationToken = default) where T : MoralisObject; - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IObjectState.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IObjectState.cs deleted file mode 100644 index 007b8cd..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IObjectState.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Moralis.Platform.Queries; - -namespace Moralis.Platform.Abstractions -{ - public interface IObjectState : IEnumerable> - { - bool IsNew { get; } - object this[string key] { get; } - - bool ContainsKey(string key); - - IObjectState MutatedClone(Action func); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IQueryService.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IQueryService.cs deleted file mode 100644 index 95a5426..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IQueryService.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Moralis.Platform.Objects; -using Moralis.Platform.Queries; - -namespace Moralis.Platform.Abstractions -{ - public interface IQueryService - { - IObjectService ObjectService { get; } - //Task> FindAsync(MoralisQuery query, MoralisUser user, CancellationToken cancellationToken = default) where T : MoralisObject; - - //Task> AggregateAsync(MoralisQuery query, MoralisUser user, CancellationToken cancellationToken = default) where T : MoralisObject; - - //Task CountAsync(MoralisQuery query, MoralisUser user, CancellationToken cancellationToken = default) where T : MoralisObject; - - //Task FirstAsync(MoralisQuery query, MoralisUser user, CancellationToken cancellationToken = default) where T : MoralisObject; - - //Task> DistinctAsync(MoralisQuery query, MoralisUser user, CancellationToken cancellationToken = default) where T : MoralisObject; - Task> FindAsync(MoralisQuery query, string sessionToken, CancellationToken cancellationToken = default) where T : MoralisObject; - - Task> AggregateAsync(MoralisQuery query, string sessionToken, CancellationToken cancellationToken = default) where T : MoralisObject; - - Task CountAsync(MoralisQuery query, string sessionToken, CancellationToken cancellationToken = default) where T : MoralisObject; - - Task FirstAsync(MoralisQuery query, string sessionToken, CancellationToken cancellationToken = default) where T : MoralisObject; - - Task> DistinctAsync(MoralisQuery query, string sessionToken, CancellationToken cancellationToken = default) where T : MoralisObject; - - - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IRelativeCacheLocationGenerator.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IRelativeCacheLocationGenerator.cs deleted file mode 100644 index 29c1056..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IRelativeCacheLocationGenerator.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Abstractions -{ - /// - /// A unit that can generate a relative path to a persistent storage file. - /// - public interface IRelativeCacheLocationGenerator - { - /// - /// The corresponding relative path generated by this . - /// - string GetRelativeCacheFilePath(IServiceHub serviceHub) where TUser : MoralisUser; - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IServerConnectionData.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IServerConnectionData.cs deleted file mode 100644 index 785a48b..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IServerConnectionData.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System.Collections.Generic; - -namespace Moralis.Platform.Abstractions -{ - public interface IServerConnectionData - { - /// - /// The App ID of your app. - /// - string ApplicationID { get; set; } - - /// - /// A URI pointing to the target Moralis Server instance hosting the app targeted by . - /// - string ServerURI { get; set; } - - /// - /// A URI pointing to the target Moralis WS/WSS server. - /// - string LiveQueryServerURI { get; set; } - - /// - /// The Web3Api key, must be supplied to initialize Web3Api to use - /// standard REST server. - /// - string ApiKey { get; set; } - - /// - /// The .NET Key for the Moralis app targeted by . - /// - string Key { get; set; } - - /// - /// The Master Key for the Moralis app targeted by . - /// - string MasterKey { get; set; } - - /// - /// Used to - /// - public string LocalStoragePath { get; set; } - - /// - /// Additional HTTP headers to be sent with network requests from the SDK. - /// - IDictionary Headers { get; set; } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IServiceHub.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IServiceHub.cs deleted file mode 100644 index 900502e..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IServiceHub.cs +++ /dev/null @@ -1,47 +0,0 @@ -#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member - -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Abstractions -{ - /// - /// The dependency injection container for all internal .NET Moralis SDK services. - /// - public interface IServiceHub where TUser : MoralisUser - { - /// - /// If true when an object is requested to be saved it is always saved regardless of if it was - /// updated or not. If false, the object is only saved if the IsDirty flag has been set. - /// - bool AlwaysSave { get; set; } - - /// - /// The current server connection data that the the Moralis SDK has been initialized with. - /// - IServerConnectionData ServerConnectionData { get; } - IMetadataService MetadataService { get; } - - /// - /// Provides Serialization / Deserialization services. - /// - IJsonSerializer JsonSerializer { get; } - - IWebClient WebClient { get; } - ICacheService CacheService { get; } - - IInstallationService InstallationService{ get; } - IMoralisCommandRunner CommandRunner { get; } - - ICloudFunctionService CloudFunctionService { get; } - - IFileService FileService { get; } - IObjectService ObjectService { get; } - IQueryService QueryService { get; } - ISessionService SessionService { get; } - IUserService UserService { get; } - ICurrentUserService CurrentUserService { get; } - - T Create(object[] parameters) where T : MoralisObject; - - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IServiceHubComposer.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IServiceHubComposer.cs deleted file mode 100644 index 0e1b3e3..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IServiceHubComposer.cs +++ /dev/null @@ -1,9 +0,0 @@ -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Abstractions -{ - public interface IServiceHubComposer where TUser : MoralisUser - { - public IServiceHub BuildHub(IMutableServiceHub serviceHub = default, IServiceHub extension = default, params IServiceHubMutator[] configurators) ; - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IServiceHubMutator.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IServiceHubMutator.cs deleted file mode 100644 index 0ea36f8..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IServiceHubMutator.cs +++ /dev/null @@ -1,22 +0,0 @@ -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Abstractions -{ - /// - /// A class which makes a deliberate mutation to a service. - /// - public interface IServiceHubMutator - { - /// - /// A value which dictates whether or not the should be considered in a valid state. - /// - bool Valid { get; } - - /// - /// A method which mutates an implementation instance. - /// - /// The target implementation instance - /// A hub which the is composed onto that should be used when needs to access services. - void Mutate(ref IMutableServiceHub target, in IServiceHub composedHub) where TUser : MoralisUser; - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/ISessionService.cs b/MoralisDotNet/Moralis/Platform/Abstractions/ISessionService.cs deleted file mode 100644 index a0e4490..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/ISessionService.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Threading; -using Moralis.Platform.Objects; -using System.Threading.Tasks; - -namespace Moralis.Platform.Abstractions -{ - public interface ISessionService where TUser : MoralisUser - { - Task GetSessionAsync(string sessionToken, IServiceHub serviceHub, CancellationToken cancellationToken = default); - - Task RevokeAsync(string sessionToken, CancellationToken cancellationToken = default); - - Task UpgradeToRevocableSessionAsync(string sessionToken, IServiceHub serviceHub, CancellationToken cancellationToken = default); - - bool IsRevocableSessionToken(string sessionToken); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IUser.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IUser.cs deleted file mode 100644 index fc8c988..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IUser.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; - -namespace Moralis.Platform.Abstractions -{ - public interface IUser - { - /// - /// Get or set the user name - /// - //[JsonProperty("username")] - string username { get; set; } - - /// - /// Get or set the user password - /// - //[JsonProperty("password")] - string password { get; set; } - - /// - /// Get or set user email address. - /// - //[JsonProperty("email")] - string email { get; set; } - - //[JsonProperty("sessionToken")] - string sessionToken { get;} - - /// - /// Gets the authData for this user. - /// - IDictionary> AuthData { get; internal set; } - - - /// - /// Signs up a new user. This will create a new ParseUser on the server and will also persist the - /// session on disk so that you can access the user using . A username and - /// password must be set before calling SignUpAsync. - /// - Task SignUpAsync(); - - /// - /// Signs up a new user. This will create a new ParseUser on the server and will also persist the - /// session on disk so that you can access the user using . A username and - /// password must be set before calling SignUpAsync. - /// - /// The cancellation token. - Task SignUpAsync(CancellationToken cancellationToken); - - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IUserService.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IUserService.cs deleted file mode 100644 index 7bc45c7..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IUserService.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Abstractions -{ - public interface IUserService where TUser : MoralisUser - { - Task SignUpAsync(IObjectState state, IDictionary operations, CancellationToken cancellationToken = default); - - Task LogInAsync(string username, string password, IServiceHub serviceHub, CancellationToken cancellationToken = default); - - Task LogInAsync(string authType, IDictionary data, IServiceHub serviceHub, CancellationToken cancellationToken = default); - - Task GetUserAsync(string sessionToken, IServiceHub serviceHub, CancellationToken cancellationToken = default); - - Task RequestPasswordResetAsync(string email, CancellationToken cancellationToken = default); - - bool RevocableSessionEnabled { get; set; } - - object RevocableSessionEnabledMutex { get; } - } - -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/IWebClient.cs b/MoralisDotNet/Moralis/Platform/Abstractions/IWebClient.cs deleted file mode 100644 index 1e5e926..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/IWebClient.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Threading; -using Status = System.Net.HttpStatusCode; -using System.Threading.Tasks; -using Moralis.Platform.Services.Models; - -namespace Moralis.Platform.Abstractions -{ - public interface IWebClient - { - /// - /// Executes HTTP request to a with HTTP verb - /// and . - /// - /// The HTTP request to be executed. - /// A task that resolves to Htt - Task> ExecuteAsync(WebRequest httpRequest, IProgress uploadProgress, IProgress downloadProgress, CancellationToken cancellationToken = default); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/LiveQueryCallbacks.cs b/MoralisDotNet/Moralis/Platform/Abstractions/LiveQueryCallbacks.cs deleted file mode 100644 index 64513f1..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/LiveQueryCallbacks.cs +++ /dev/null @@ -1,56 +0,0 @@ -using Moralis.Platform.Objects; -using Moralis.Platform.Queries.Live; - -namespace Moralis.Platform.Abstractions -{ - public class LiveQueryCallbacks : ILiveQueryCallbacks where T : MoralisObject - { - /// - /// Called when a connected event is returned from the server. - /// - public virtual void OnConnected() { } - - /// - /// Called when a subscribed event is returned from the server. - /// - public virtual void OnSubscribed(int requestId) { } - - /// - /// Called when a create event is returned from the server. - /// - public virtual void OnCreate(T item, int requestId) { } - - /// - /// Called when a delete event is returned from the server. - /// - public virtual void OnDelete(T item, int requestId) { } - - /// - /// Called when a enter event is returned from the server. - /// - public virtual void OnEnter(T item, int requestId) { } - - /// - /// Called when a leave event is returned from the server. - /// - public virtual void OnLeave(T item, int requestId) { } - - /// - /// Called when a update event is returned from the server. - /// - public virtual void OnUpdate(T item, int requestId) { } - - /// - /// Called when a ubsubscribed event is received. - /// - public virtual void OnUnsubscribed(int requestId) { } - - /// - /// Called when an error message is recevied. - /// - /// - public virtual void OnError(ErrorMessage em) { } - - public virtual void OnGeneralMessage(string text) { } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Abstractions/RelationBase.cs b/MoralisDotNet/Moralis/Platform/Abstractions/RelationBase.cs deleted file mode 100644 index 1d2fc8a..0000000 --- a/MoralisDotNet/Moralis/Platform/Abstractions/RelationBase.cs +++ /dev/null @@ -1,54 +0,0 @@ -//using Moralis.Platform.Objects; -//using System; -//using System.Collections.Generic; -//using System.Text; - -//namespace Moralis.Platform.Abstractions -//{ -// [EditorBrowsable(EditorBrowsableState.Never)] -// public abstract class RelationBase : IJsonConvertible -// { -// MoralisObject Parent { get; set; } - -// string Key { get; set; } - -// internal ParseRelationBase(MoralisObject parent, string key) => EnsureParentAndKey(parent, key); - -// internal ParseRelationBase(MoralisObject parent, string key, string targetClassName) : this(parent, key) => TargetClassName = targetClassName; - -// internal void EnsureParentAndKey(MoralisObject parent, string key) -// { -// Parent ??= parent; -// Key ??= key; - -// Debug.Assert(Parent == parent, "Relation retrieved from two different objects"); -// Debug.Assert(Key == key, "Relation retrieved from two different keys"); -// } - -// internal void Add(MoralisObject entity) -// { -// ParseRelationOperation change = new ParseRelationOperation(Parent.Services.ClassController, new[] { entity }, default); - -// Parent.PerformOperation(Key, change); -// TargetClassName = change.TargetClassName; -// } - -// internal void Remove(ParseObject entity) -// { -// ParseRelationOperation change = new ParseRelationOperation(Parent.Services.ClassController, default, new[] { entity }); - -// Parent.PerformOperation(Key, change); -// TargetClassName = change.TargetClassName; -// } - -// IDictionary IJsonConvertible.ConvertToJSON() => new Dictionary -// { -// ["__type"] = "Relation", -// ["className"] = TargetClassName -// }; - -// internal MoralisQuery GetQuery() where T : MoralisQuery => TargetClassName is { } ? new MoralisQuery(Parent.Services, TargetClassName).WhereRelatedTo(Parent, Key) : new ParseQuery(Parent.Services, Parent.ClassName).RedirectClassName(Key).WhereRelatedTo(Parent, Key); - -// internal string TargetClassName { get; set; } -// } -//} diff --git a/MoralisDotNet/Moralis/Platform/EnvironmentData.cs b/MoralisDotNet/Moralis/Platform/EnvironmentData.cs deleted file mode 100644 index 30cf304..0000000 --- a/MoralisDotNet/Moralis/Platform/EnvironmentData.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using Moralis.Platform.Abstractions; - -namespace Moralis.Platform -{ - /// - /// Inferred data about the environment in which Moralis is operating. - /// - public class EnvironmentData : IEnvironmentData - { - /// - /// A instance that the Moralis SDK will attempt to generate from environment metadata it should be able to access. - /// - public static EnvironmentData Inferred => new EnvironmentData - { - TimeZone = TimeZoneInfo.Local.StandardName, - #if UNITY_WEBGL - OSVersion = "unknown", // WebGL doesn't know the OS - Platform = ".NET" - #else - OSVersion = RuntimeInformation.OSDescription ?? Environment.OSVersion.ToString(), - Platform = RuntimeInformation.FrameworkDescription ?? ".NET" - #endif - }; - - /// - /// The active time zone for the app and/or system. - /// - public string TimeZone { get; set; } - - /// - /// The host operating system version of the platform the host application is operating in. - /// - public string OSVersion { get; set; } - - /// - /// The target platform the app is running on. Defaults to .NET. - /// - public string Platform { get; set; } - } - -} diff --git a/MoralisDotNet/Moralis/Platform/Exceptions/MoralisFailureException.cs b/MoralisDotNet/Moralis/Platform/Exceptions/MoralisFailureException.cs deleted file mode 100644 index 09cd407..0000000 --- a/MoralisDotNet/Moralis/Platform/Exceptions/MoralisFailureException.cs +++ /dev/null @@ -1,277 +0,0 @@ -using System; - -namespace Moralis.Platform.Exceptions -{ - /// - /// Exceptions that may occur when sending requests to Moralis. - /// - public class MoralisFailureException : Exception - { - /// - /// Error codes that may be delivered in response to requests to Moralis. - /// - public enum ErrorCode - { - /// - /// Error code indicating that an unknown error or an error unrelated to server - /// occurred. - /// - OtherCause = -1, - - /// - /// Error code indicating that something has gone wrong with the server. - /// If you get this error code, it is Moralis' fault. Please report the bug. - /// - InternalServerError = 1, - - /// - /// Error code indicating the connection to the servers failed. - /// - ConnectionFailed = 100, - - /// - /// Error code indicating the specified object doesn't exist. - /// - ObjectNotFound = 101, - - /// - /// Error code indicating you tried to query with a datatype that doesn't - /// support it, like exact matching an array or object. - /// - InvalidQuery = 102, - - /// - /// Error code indicating a missing or invalid classname. Classnames are - /// case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the - /// only valid characters. - /// - InvalidClassName = 103, - - /// - /// Error code indicating an unspecified object id. - /// - MissingObjectId = 104, - - /// - /// Error code indicating an invalid key name. Keys are case-sensitive. They - /// must start with a letter, and a-zA-Z0-9_ are the only valid characters. - /// - InvalidKeyName = 105, - - /// - /// Error code indicating a malformed pointer. You should not see this unless - /// you have been mucking about changing internal code. - /// - InvalidPointer = 106, - - /// - /// Error code indicating that badly formed JSON was received upstream. This - /// either indicates you have done something unusual with modifying how - /// things encode to JSON, or the network is failing badly. - /// - InvalidJSON = 107, - - /// - /// Error code indicating that the feature you tried to access is only - /// available internally for testing purposes. - /// - CommandUnavailable = 108, - - /// - /// You must call Moralis.initialize before using the Moralis library. - /// - NotInitialized = 109, - - /// - /// Error code indicating that a field was set to an inconsistent type. - /// - IncorrectType = 111, - - /// - /// Error code indicating an invalid channel name. A channel name is either - /// an empty string (the broadcast channel) or contains only a-zA-Z0-9_ - /// characters and starts with a letter. - /// - InvalidChannelName = 112, - - /// - /// Error code indicating that push is misconfigured. - /// - PushMisconfigured = 115, - - /// - /// Error code indicating that the object is too large. - /// - ObjectTooLarge = 116, - - /// - /// Error code indicating that the operation isn't allowed for clients. - /// - OperationForbidden = 119, - - /// - /// Error code indicating the result was not found in the cache. - /// - CacheMiss = 120, - - /// - /// Error code indicating that an invalid key was used in a nested - /// JSONObject. - /// - InvalidNestedKey = 121, - - /// - /// Error code indicating that an invalid filename was used for File. - /// A valid file name contains only a-zA-Z0-9_. characters and is between 1 - /// and 128 characters. - /// - InvalidFileName = 122, - - /// - /// Error code indicating an invalid ACL was provided. - /// - InvalidACL = 123, - - /// - /// Error code indicating that the request timed out on the server. Typically - /// this indicates that the request is too expensive to run. - /// - Timeout = 124, - - /// - /// Error code indicating that the email address was invalid. - /// - InvalidEmailAddress = 125, - - /// - /// Error code indicating that a unique field was given a value that is - /// already taken. - /// - DuplicateValue = 137, - - /// - /// Error code indicating that a role's name is invalid. - /// - InvalidRoleName = 139, - - /// - /// Error code indicating that an application quota was exceeded. Upgrade to - /// resolve. - /// - ExceededQuota = 140, - - /// - /// Error code indicating that a Cloud Code script failed. - /// - ScriptFailed = 141, - - /// - /// Error code indicating that a Cloud Code validation failed. - /// - ValidationFailed = 142, - - /// - /// Error code indicating that deleting a file failed. - /// - FileDeleteFailed = 153, - - /// - /// Error code indicating that the application has exceeded its request limit. - /// - RequestLimitExceeded = 155, - - /// - /// Error code indicating that the provided event name is invalid. - /// - InvalidEventName = 160, - - /// - /// Error code indicating that the username is missing or empty. - /// - UsernameMissing = 200, - - /// - /// Error code indicating that the password is missing or empty. - /// - PasswordMissing = 201, - - /// - /// Error code indicating that the username has already been taken. - /// - UsernameTaken = 202, - - /// - /// Error code indicating that the email has already been taken. - /// - EmailTaken = 203, - - /// - /// Error code indicating that the email is missing, but must be specified. - /// - EmailMissing = 204, - - /// - /// Error code indicating that a user with the specified email was not found. - /// - EmailNotFound = 205, - - /// - /// Error code indicating that a user object without a valid session could - /// not be altered. - /// - SessionMissing = 206, - - /// - /// Error code indicating that a user can only be created through signup. - /// - MustCreateUserThroughSignup = 207, - - /// - /// Error code indicating that an an account being linked is already linked - /// to another user. - /// - AccountAlreadyLinked = 208, - - /// - /// Error code indicating that the current session token is invalid. - /// - InvalidSessionToken = 209, - - /// - /// Error code indicating that a user cannot be linked to an account because - /// that account's id could not be found. - /// - LinkedIdMissing = 250, - - /// - /// Error code indicating that a user with a linked (e.g. Facebook) account - /// has an invalid session. - /// - InvalidLinkedSession = 251, - - /// - /// Error code indicating that a service being linked (e.g. Facebook or - /// Twitter) is unsupported. - /// - UnsupportedService = 252, - - /// - /// Error code indicating that handling of a live query event failed. - /// - LiveQueryEventHandlingFailed = 300, - - /// - /// Error code that inidicates that the server URL provided is null or empty. - /// - ServerUrlNullOrEmtpy = 301 - } - - internal MoralisFailureException(ErrorCode code, string message, Exception cause = null) : base(message, cause) => Code = code; - - /// - /// The error code associated with the exception. - /// - public ErrorCode Code { get; private set; } - } - -} diff --git a/MoralisDotNet/Moralis/Platform/HostManifestData.cs b/MoralisDotNet/Moralis/Platform/HostManifestData.cs deleted file mode 100644 index a912c0e..0000000 --- a/MoralisDotNet/Moralis/Platform/HostManifestData.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System; -using System.Reflection; -using Moralis.Platform.Abstractions; - -namespace Moralis.Platform -{ - /// - /// In the event that you would like to use the Moralis SDK - /// from a completely portable project, with no platform-specific library required, - /// to get full access to all of our features available on Parse Dashboard - /// (A/B testing, slow queries, etc.), you must set the values of this struct - /// to be appropriate for your platform. - /// - /// Any values set here will overwrite those that are automatically configured by - /// any platform-specific migration library your app includes. - /// - public class HostManifestData : IHostManifestData - { - /// - /// An instance of with inferred values based on the entry assembly. - /// - /// Should not be used with Unity. - public static HostManifestData Inferred => new HostManifestData - { - Version = Assembly.GetEntryAssembly().GetCustomAttribute()?.InformationalVersion, - Name = Assembly.GetEntryAssembly().GetCustomAttribute()?.Title != null ? Assembly.GetEntryAssembly().GetCustomAttribute()?.Title : - Assembly.GetEntryAssembly().GetCustomAttribute()?.Product != null ? Assembly.GetEntryAssembly().GetCustomAttribute()?.Product : - Assembly.GetEntryAssembly().GetName().Name, - ShortVersion = Assembly.GetEntryAssembly().GetName().Version.ToString(), - - Identifier = AppDomain.CurrentDomain.FriendlyName - }; - - /// - /// The build version of your app. - /// - public string Version { get; set; } - - /// - /// The human-friendly display version number of your app. - /// - public string ShortVersion { get; set; } - - /// - /// The identifier of the application - /// - public string Identifier { get; set; } - - /// - /// The friendly name of your app. - /// - public string Name { get; set; } - - /// - /// Gets a value for whether or not this instance of is populated with default values. - /// - public bool IsDefault => Version is null && ShortVersion is null && Identifier is null && Name is null; - - /// - /// Gets a value for whether or not this instance of can currently be used for the generation of . - /// - public bool CanBeUsedForInference => !(IsDefault || String.IsNullOrWhiteSpace(ShortVersion)); - } - -} diff --git a/MoralisDotNet/Moralis/Platform/IdentifierBasedRelativeCacheLocationGenerator.cs b/MoralisDotNet/Moralis/Platform/IdentifierBasedRelativeCacheLocationGenerator.cs deleted file mode 100644 index 7f0bc0a..0000000 --- a/MoralisDotNet/Moralis/Platform/IdentifierBasedRelativeCacheLocationGenerator.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using System.IO; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; - -namespace Moralis.Platform -{ - /// - /// A configuration of the Parse SDK persistent storage location based on an identifier. - /// - public struct IdentifierBasedRelativeCacheLocationGenerator : IRelativeCacheLocationGenerator - { - internal static IdentifierBasedRelativeCacheLocationGenerator Fallback { get; } = new IdentifierBasedRelativeCacheLocationGenerator { IsFallback = true }; - - /// - /// Dictates whether or not this instance should act as a fallback for when has not yet been initialized but the storage path is needed. - /// - internal bool IsFallback { get; set; } - - /// - /// The identifier that all Parse SDK cache files should be labelled with. - /// - public string Identifier { get; set; } - - /// - /// The corresponding relative path generated by this . - /// - /// This will cause a .cachefile file extension to be added to the cache file in order to prevent the creation of files with unwanted extensions due to the value of containing periods. - public string GetRelativeCacheFilePath(IServiceHub serviceHub) where TUser : MoralisUser - { - FileInfo file; - - while ((file = serviceHub.CacheService.GetRelativeFile(GeneratePath())).Exists && IsFallback) - ; - - return file.FullName; - } - - /// - /// Generates a path for use in the method. - /// - /// A potential path to the cachefile - string GeneratePath() => Path.Combine(nameof(Moralis), IsFallback ? "_fallback" : "_global", $"{(IsFallback ? new Random { }.Next().ToString() : Identifier)}.cachefile"); - } -} diff --git a/MoralisDotNet/Moralis/Platform/MoralisCloud.cs b/MoralisDotNet/Moralis/Platform/MoralisCloud.cs deleted file mode 100644 index 11526bc..0000000 --- a/MoralisDotNet/Moralis/Platform/MoralisCloud.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Moralis.Platform; -using Moralis.Platform.Exceptions; -using Moralis.Platform.Queries; -using Moralis.Platform.Services; -using Moralis.Platform.Services.ClientServices; -using Moralis.Platform.Utilities; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; - -namespace Moralis.Platform -{ - public class MoralisCloud where TUser : MoralisUser - { - public IServiceHub ServiceHub; - - public MoralisCloud(IServiceHub serviceHub) => (ServiceHub) = (serviceHub); - public async Task RunAsync(string name, IDictionary parameters) - { - MoralisUser user = await this.ServiceHub.GetCurrentUserAsync(); - - T result = await this.ServiceHub.CloudFunctionService.CallFunctionAsync(name, parameters, user is { } ? user.sessionToken : ""); - - return result; - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/MoralisServiceHub.cs b/MoralisDotNet/Moralis/Platform/MoralisServiceHub.cs deleted file mode 100644 index 7687022..0000000 --- a/MoralisDotNet/Moralis/Platform/MoralisServiceHub.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Moralis.Platform; -using Moralis.Platform.Utilities; -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Text; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Services; - -namespace Moralis.Platform -{ - public class MoralisServiceHub : ServiceHub - { - public MoralisServiceHub (HttpClient httpClient, IServerConnectionData connectionData, IJsonSerializer jsonSerializer) : base(connectionData, jsonSerializer, httpClient) { } - } -} diff --git a/MoralisDotNet/Moralis/Platform/NewtonsoftJsonSerializer.cs b/MoralisDotNet/Moralis/Platform/NewtonsoftJsonSerializer.cs deleted file mode 100644 index 083a3aa..0000000 --- a/MoralisDotNet/Moralis/Platform/NewtonsoftJsonSerializer.cs +++ /dev/null @@ -1,84 +0,0 @@ -using Moralis.Platform.Abstractions; -using System; -using System.Collections.Generic; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using System.Runtime.Serialization; -using System.Globalization; - -namespace Moralis.Platform -{ - public class NewtonsoftJsonSerializer : IJsonSerializer - { - public IDictionary DefaultOptions { get; set; } - - public NewtonsoftJsonSerializer() - { - DefaultOptions = new Dictionary(); - DefaultOptions.Add("NullValueHandling", NullValueHandling.Ignore); - DefaultOptions.Add("ReferenceLoopHandling", ReferenceLoopHandling.Serialize); - DefaultOptions.Add("DateFormatString", "yyyy-MM-ddTHH:mm:ss.fffZ"); - } - - public T Deserialize(string json, IDictionary options=null) - { - if (options != null) - { - return JsonConvert.DeserializeObject(json, OptionsToSettings(options)); - } - else - { - return JsonConvert.DeserializeObject(json); - } - } - - public string Serialize(object target, IDictionary options=null) - { - if (options != null) - { - return JsonConvert.SerializeObject(target, OptionsToSettings(options)); - } - else - { - return JsonConvert.SerializeObject(target); - } - } - - private JsonSerializerSettings OptionsToSettings(IDictionary options) - { - JsonSerializerSettings settings = new JsonSerializerSettings() - { - //CheckAdditionalContent = options.ContainsKey("CheckAdditionalContent") ? (bool)options["CheckAdditionalContent"] : false, - //ConstructorHandling = options.ContainsKey("ConstructorHandling") ? (ConstructorHandling)options["ConstructorHandling"] : ConstructorHandling.Default, - //Context = options.ContainsKey("Context") ? (StreamingContext)options["Context"] : new StreamingContext(), - //ContractResolver = options.ContainsKey("ContractResolver") ? (IContractResolver)options["ContractResolver"] : null, - //Converters = options.ContainsKey("Converters") ? (List)options["Converters"] : null, - //Culture = options.ContainsKey("Culture") ? (CultureInfo)options["Culture"] : null, - //DateFormatHandling = options.ContainsKey("DateFormatHandling") ? (DateFormatHandling)options["DateFormatHandling"] : DateFormatHandling.IsoDateFormat, - DateFormatString = options.ContainsKey("DateFormatString") ? (string)options["DateFormatString"] : null, - //DateParseHandling = options.ContainsKey("DateParseHandling") ? (DateParseHandling)options["DateParseHandling"] : DateParseHandling.DateTime, - //DateTimeZoneHandling = options.ContainsKey("DateTimeZoneHandling") ? (DateTimeZoneHandling)options["DateTimeZoneHandling"] : DateTimeZoneHandling.Utc, - //DefaultValueHandling = options.ContainsKey("DefaultValueHandling") ? (DefaultValueHandling)options["DefaultValueHandling"] : DefaultValueHandling.Ignore, - //Error = options.ContainsKey("Error") ? (EventHandler)options["Error"] : null, - //FloatFormatHandling = options.ContainsKey("FloatFormatHandling") ? (FloatFormatHandling)options["FloatFormatHandling"] : FloatFormatHandling.DefaultValue, - //FloatParseHandling = options.ContainsKey("FloatParseHandling") ? (FloatParseHandling)options["FloatParseHandling"] : FloatParseHandling.Double, - //Formatting = options.ContainsKey("Formatting") ? (Formatting)options["Formatting"] : Formatting.None, - //MaxDepth = options.ContainsKey("MaxDepth") ? (int?)options["MaxDepth"] : null, - //MetadataPropertyHandling = options.ContainsKey("MetadataPropertyHandling") ? (MetadataPropertyHandling)options["MetadataPropertyHandling"] : MetadataPropertyHandling.Default, - //MissingMemberHandling = options.ContainsKey("MissingMemberHandling") ? (MissingMemberHandling)options["MissingMemberHandling"] : MissingMemberHandling.Ignore, - NullValueHandling = options.ContainsKey("NullValueHandling") ? (NullValueHandling)options["NullValueHandling"] : NullValueHandling.Ignore, - //ObjectCreationHandling = options.ContainsKey("ObjectCreationHandling") ? (ObjectCreationHandling)options["ObjectCreationHandling"] : ObjectCreationHandling.Auto, - //PreserveReferencesHandling = options.ContainsKey("PreserveReferencesHandling") ? (PreserveReferencesHandling)options["PreserveReferencesHandling"] : PreserveReferencesHandling.None, - ReferenceLoopHandling = options.ContainsKey("ReferenceLoopHandling") ? (ReferenceLoopHandling)options["ReferenceLoopHandling"] : ReferenceLoopHandling.Ignore, - //ReferenceResolverProvider = options.ContainsKey("ReferenceResolverProvider") ? (Func)options["ReferenceResolverProvider"] : null, - //SerializationBinder = options.ContainsKey("SerializationBinder") ? (ISerializationBinder)options["SerializationBinder"] : null, - //StringEscapeHandling = options.ContainsKey("StringEscapeHandling") ? (StringEscapeHandling)options["StringEscapeHandling"] : StringEscapeHandling.Default, - //TraceWriter = options.ContainsKey("TraceWriter") ? (ITraceWriter)options["TraceWriter"] : null, - //TypeNameAssemblyFormatHandling = options.ContainsKey("TypeNameAssemblyFormatHandling") ? (TypeNameAssemblyFormatHandling)options["TypeNameAssemblyFormatHandling"] : TypeNameAssemblyFormatHandling.Full, - //TypeNameHandling = options.ContainsKey("TypeNameHandling") ? (TypeNameHandling)options["TypeNameHandling"] : TypeNameHandling.None - }; - - return settings; - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Objects/MoralisAcl.cs b/MoralisDotNet/Moralis/Platform/Objects/MoralisAcl.cs deleted file mode 100644 index d0c67af..0000000 --- a/MoralisDotNet/Moralis/Platform/Objects/MoralisAcl.cs +++ /dev/null @@ -1,327 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Moralis.Platform.Abstractions; -using Newtonsoft.Json; - -namespace Moralis.Platform.Objects -{ - class MoralisAclJsonConvertor : JsonConverter - { - public override bool CanConvert(Type objectType) - { - return true; - } - - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - //MyCustomType myCustomType = new MyCustomType();//for null values - Dictionary acl = new Dictionary(); - string key = String.Empty; - - while (reader.Read()) - { - var tokenType = reader.TokenType; - if (reader.TokenType == JsonToken.PropertyName) - { - key = (reader.Value as string) ?? string.Empty; - } - else if (reader.TokenType == JsonToken.StartObject) - { - Dictionary cntlDict = new Dictionary(); - var cntlKey = string.Empty; - - while (reader.Read()) - { - if (reader.TokenType == JsonToken.PropertyName) - { - cntlKey = (reader.Value as string) ?? string.Empty; - } - else if (reader.TokenType == JsonToken.Boolean) - { - bool? b = reader.Value as bool?; - cntlDict.Add(cntlKey, b.Value); - } - if (reader.TokenType == JsonToken.EndObject) - { - acl.Add(key, cntlDict); - break; - } - } - } - else if (reader.TokenType == JsonToken.EndObject) - { - break; - } - } - - return new MoralisAcl(acl); - } - - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - if (value == null || !(value is MoralisAcl)) - { - serializer.Serialize(writer, null); - return; - } - - Dictionary acl = ((MoralisAcl)value).ToParameterDictionary(); - - serializer.Serialize(writer, acl); - } - } - - - [JsonConverter(typeof(MoralisAclJsonConvertor))] - public class MoralisAcl - { - private enum AccessKind - { - Read, - Write - } - private const string publicName = "*"; - private readonly ICollection readers = new HashSet(); - private readonly ICollection writers = new HashSet(); - - internal MoralisAcl(IDictionary jsonObject) - { - readers = new HashSet(from pair in jsonObject - where ((IDictionary)pair.Value).ContainsKey("read") - select pair.Key); - writers = new HashSet(from pair in jsonObject - where ((IDictionary)pair.Value).ContainsKey("write") - select pair.Key); - } - - /// - /// Creates an ACL with no permissions granted. - /// - public MoralisAcl() - { - } - - /// - /// Creates an ACL where only the provided user has access. - /// - /// The only user that can read or write objects governed by this ACL. - public MoralisAcl(MoralisUser owner) - { - SetReadAccess(owner, true); - SetWriteAccess(owner, true); - } - - public Dictionary ToParameterDictionary() - { - Dictionary result = new Dictionary(); - foreach (string user in readers.Union(writers)) - { - Dictionary userPermissions = new Dictionary(); - if (readers.Contains(user)) - { - userPermissions["read"] = true; - } - if (writers.Contains(user)) - { - userPermissions["write"] = true; - } - result[user] = userPermissions; - } - return result; - } - - private void SetAccess(AccessKind kind, string userId, bool allowed) - { - if (userId == null) - { - throw new ArgumentException("Cannot set access for an unsaved user or role."); - } - ICollection target = null; - switch (kind) - { - case AccessKind.Read: - target = readers; - break; - case AccessKind.Write: - target = writers; - break; - default: - throw new NotImplementedException("Unknown AccessKind"); - } - if (allowed) - { - target.Add(userId); - } - else - { - target.Remove(userId); - } - } - - private bool GetAccess(AccessKind kind, string userId) - { - if (userId == null) - { - throw new ArgumentException("Cannot get access for an unsaved user or role."); - } - switch (kind) - { - case AccessKind.Read: - return readers.Contains(userId); - case AccessKind.Write: - return writers.Contains(userId); - default: - throw new NotImplementedException("Unknown AccessKind"); - } - } - - /// - /// Gets or sets whether the public is allowed to read this object. - /// - public bool PublicReadAccess - { - get => GetAccess(AccessKind.Read, publicName); - set => SetAccess(AccessKind.Read, publicName, value); - } - - /// - /// Gets or sets whether the public is allowed to write this object. - /// - public bool PublicWriteAccess - { - get => GetAccess(AccessKind.Write, publicName); - set => SetAccess(AccessKind.Write, publicName, value); - } - - /// - /// Sets whether the given user id is allowed to read this object. - /// - /// The objectId of the user. - /// Whether the user has permission. - public void SetReadAccess(string userId, bool allowed) => SetAccess(AccessKind.Read, userId, allowed); - - /// - /// Sets whether the given user is allowed to read this object. - /// - /// The user. - /// Whether the user has permission. - public void SetReadAccess(MoralisUser user, bool allowed) => SetReadAccess(user.objectId, allowed); - - /// - /// Sets whether the given user id is allowed to write this object. - /// - /// The objectId of the user. - /// Whether the user has permission. - public void SetWriteAccess(string userId, bool allowed) => SetAccess(AccessKind.Write, userId, allowed); - - /// - /// Sets whether the given user is allowed to write this object. - /// - /// The user. - /// Whether the user has permission. - public void SetWriteAccess(MoralisUser user, bool allowed) => SetWriteAccess(user.objectId, allowed); - - /// - /// Gets whether the given user id is *explicitly* allowed to read this object. - /// Even if this returns false, the user may still be able to read it if - /// PublicReadAccess is true or a role that the user belongs to has read access. - /// - /// The user objectId to check. - /// Whether the user has access. - public bool GetReadAccess(string userId) => GetAccess(AccessKind.Read, userId); - - /// - /// Gets whether the given user is *explicitly* allowed to read this object. - /// Even if this returns false, the user may still be able to read it if - /// PublicReadAccess is true or a role that the user belongs to has read access. - /// - /// The user to check. - /// Whether the user has access. - public bool GetReadAccess(MoralisUser user) => GetReadAccess(user.objectId); - - /// - /// Gets whether the given user id is *explicitly* allowed to write this object. - /// Even if this returns false, the user may still be able to write it if - /// PublicReadAccess is true or a role that the user belongs to has write access. - /// - /// The user objectId to check. - /// Whether the user has access. - public bool GetWriteAccess(string userId) => GetAccess(AccessKind.Write, userId); - - /// - /// Gets whether the given user is *explicitly* allowed to write this object. - /// Even if this returns false, the user may still be able to write it if - /// PublicReadAccess is true or a role that the user belongs to has write access. - /// - /// The user to check. - /// Whether the user has access. - public bool GetWriteAccess(MoralisUser user) => GetWriteAccess(user.objectId); - - /// - /// Sets whether users belonging to the role with the given - /// are allowed to read this object. - /// - /// The name of the role. - /// Whether the role has access. - public void SetRoleReadAccess(string roleName, bool allowed) => SetAccess(AccessKind.Read, "role:" + roleName, allowed); - - /// - /// Sets whether users belonging to the given role are allowed to read this object. - /// - /// The role. - /// Whether the role has access. - public void SetRoleReadAccess(MoralisRole role, bool allowed) => SetRoleReadAccess(role.name, allowed); - - /// - /// Gets whether users belonging to the role with the given - /// are allowed to read this object. Even if this returns false, the role may still be - /// able to read it if a parent role has read access. - /// - /// The name of the role. - /// Whether the role has access. - public bool GetRoleReadAccess(string roleName) => GetAccess(AccessKind.Read, "role:" + roleName); - - /// - /// Gets whether users belonging to the role are allowed to read this object. - /// Even if this returns false, the role may still be able to read it if a - /// parent role has read access. - /// - /// The name of the role. - /// Whether the role has access. - public bool GetRoleReadAccess(MoralisRole role) => GetRoleReadAccess(role.name); - - /// - /// Sets whether users belonging to the role with the given - /// are allowed to write this object. - /// - /// The name of the role. - /// Whether the role has access. - public void SetRoleWriteAccess(string roleName, bool allowed) => SetAccess(AccessKind.Write, "role:" + roleName, allowed); - - /// - /// Sets whether users belonging to the given role are allowed to write this object. - /// - /// The role. - /// Whether the role has access. - public void SetRoleWriteAccess(MoralisRole role, bool allowed) => SetRoleWriteAccess(role.name, allowed); - - /// - /// Gets whether users belonging to the role with the given - /// are allowed to write this object. Even if this returns false, the role may still be - /// able to write it if a parent role has write access. - /// - /// The name of the role. - /// Whether the role has access. - public bool GetRoleWriteAccess(string roleName) => GetAccess(AccessKind.Write, "role:" + roleName); - - /// - /// Gets whether users belonging to the role are allowed to write this object. - /// Even if this returns false, the role may still be able to write it if a - /// parent role has write access. - /// - /// The name of the role. - /// Whether the role has access. - public bool GetRoleWriteAccess(MoralisRole role) => GetRoleWriteAccess(role.name); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Objects/MoralisFile.cs b/MoralisDotNet/Moralis/Platform/Objects/MoralisFile.cs deleted file mode 100644 index 5838130..0000000 --- a/MoralisDotNet/Moralis/Platform/Objects/MoralisFile.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System; -using System.IO; -using Moralis.Platform.Utilities; - -namespace Moralis.Platform.Objects -{ - public class MoralisFile - { - internal MoralisFileState State { get; set; } - - internal Stream DataStream { get; } - - #region Constructor - - internal MoralisFile(string name, Uri uri, string mimeType = null) => State = new MoralisFileState - { - name = name, - url = uri, - mediatype = mimeType - }; - - /// - /// Creates a new file from a byte array and a name. - /// - /// The file's name, ideally with an extension. The file name - /// must begin with an alphanumeric character, and consist of alphanumeric - /// characters, periods, spaces, underscores, or dashes. - /// The file's data. - /// To specify the content-type used when uploading the - /// file, provide this parameter. - public MoralisFile(string name, byte[] data, string mimeType = null) : this(name, new MemoryStream(data), mimeType) { } - - /// - /// Creates a new file from a stream and a name. - /// - /// The file's name, ideally with an extension. The file name - /// must begin with an alphanumeric character, and consist of alphanumeric - /// characters, periods, spaces, underscores, or dashes. - /// The file's data. - /// To specify the content-type used when uploading the - /// file, provide this parameter. - public MoralisFile(string name, Stream data, string mimeType = null) - { - State = new MoralisFileState - { - name = name, - mediatype = mimeType - }; - - DataStream = data; - } - - #endregion - - #region Properties - - /// - /// Gets whether the file still needs to be saved. - /// - public bool IsDirty => State.url == null; - - /// - /// Gets the name of the file. Before save is called, this is the filename given by - /// the user. After save is called, that name gets prefixed with a unique identifier. - /// - //[JsonProperty("name")] - public string name => State.name; - - /// - /// Gets the MIME type of the file. This is either passed in to the constructor or - /// inferred from the file extension. "unknown/unknown" will be used if neither is - /// available. - /// - public string MimeType => State.mediatype; - - /// - /// Gets the url of the file. It is only available after you save the file or after - /// you get the file from a . - /// - //[JsonProperty("url")] - public Uri url => State.SecureLocation; - - #endregion - } -} diff --git a/MoralisDotNet/Moralis/Platform/Objects/MoralisFileState.cs b/MoralisDotNet/Moralis/Platform/Objects/MoralisFileState.cs deleted file mode 100644 index 934f741..0000000 --- a/MoralisDotNet/Moralis/Platform/Objects/MoralisFileState.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; - -namespace Moralis.Platform.Objects -{ - public class MoralisFileState - { - static string SecureHyperTextTransferScheme { get; } = "https"; - - public string name { get; set; } - public string mediatype { get; set; } - public Uri url { get; set; } - - public MoralisFileState() { } - - public Uri SecureLocation => url switch - { - { Host: "files.parsetfss.com" } location => new UriBuilder(location) - { - Scheme = SecureHyperTextTransferScheme, - - // This makes URIBuilder assign the default port for the URL scheme. - - Port = -1, - }.Uri, - _ => url - }; - } -} diff --git a/MoralisDotNet/Moralis/Platform/Objects/MoralisGeoDistance.cs b/MoralisDotNet/Moralis/Platform/Objects/MoralisGeoDistance.cs deleted file mode 100644 index e1b1986..0000000 --- a/MoralisDotNet/Moralis/Platform/Objects/MoralisGeoDistance.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Moralis.Platform.Objects -{ - /// - /// Represents a distance between two MoralisGeoPoints. - /// - public struct MoralisGeoDistance - { - private const double EarthMeanRadiusKilometers = 6371.0; - private const double EarthMeanRadiusMiles = 3958.8; - - /// - /// Creates a ParseGeoDistance. - /// - /// The distance in radians. - public MoralisGeoDistance(double radians) - : this() => Radians = radians; - - /// - /// Gets the distance in radians. - /// - public double Radians { get; private set; } - - /// - /// Gets the distance in miles. - /// - public double Miles => Radians * EarthMeanRadiusMiles; - - /// - /// Gets the distance in kilometers. - /// - public double Kilometers => Radians * EarthMeanRadiusKilometers; - - /// - /// Gets a MoralisGeoDistance from a number of miles. - /// - /// The number of miles. - /// A MoralisGeoDistance for the given number of miles. - public static MoralisGeoDistance FromMiles(double miles) => new MoralisGeoDistance(miles / EarthMeanRadiusMiles); - - /// - /// Gets a MoralisGeoDistance from a number of kilometers. - /// - /// The number of kilometers. - /// A MoralisGeoDistance for the given number of kilometers. - public static MoralisGeoDistance FromKilometers(double kilometers) => new MoralisGeoDistance(kilometers / EarthMeanRadiusKilometers); - - /// - /// Gets a MoralisGeoDistance from a number of radians. - /// - /// The number of radians. - /// A MoralisGeoDistance for the given number of radians. - public static MoralisGeoDistance FromRadians(double radians) => new MoralisGeoDistance(radians); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Objects/MoralisGeoPoint.cs b/MoralisDotNet/Moralis/Platform/Objects/MoralisGeoPoint.cs deleted file mode 100644 index f773ceb..0000000 --- a/MoralisDotNet/Moralis/Platform/Objects/MoralisGeoPoint.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Moralis.Platform.Objects -{ - public class MoralisGeoPoint - { - /// - /// Constructs a MoralisGeoPoint with the specified latitude and longitude. - /// - /// The point's latitude. - /// The point's longitude. - public MoralisGeoPoint(double latitude, double longitude) - // : this() - { - Latitude = latitude; - Longitude = longitude; - } - - private double latitude; - /// - /// Gets or sets the latitude of the GeoPoint. Valid range is [-90, 90]. - /// Extremes should not be used. - /// - public double Latitude - { - get => latitude; - set - { - if (value > 90 || value < -90) - { - throw new ArgumentOutOfRangeException("value", - "Latitude must be within the range [-90, 90]"); - } - latitude = value; - } - } - - private double longitude; - /// - /// Gets or sets the longitude. Valid range is [-180, 180]. - /// Extremes should not be used. - /// - public double Longitude - { - get => longitude; - set - { - if (value > 180 || value < -180) - { - throw new ArgumentOutOfRangeException("value", - "Longitude must be within the range [-180, 180]"); - } - longitude = value; - } - } - - /// - /// Get the distance in radians between this point and another GeoPoint. This is the smallest angular - /// distance between the two points. - /// - /// GeoPoint describing the other point being measured against. - /// The distance in between the two points. - public MoralisGeoDistance DistanceTo(MoralisGeoPoint point) - { - double d2r = Math.PI / 180; // radian conversion factor - double lat1rad = Latitude * d2r; - double long1rad = longitude * d2r; - double lat2rad = point.Latitude * d2r; - double long2rad = point.Longitude * d2r; - double deltaLat = lat1rad - lat2rad; - double deltaLong = long1rad - long2rad; - double sinDeltaLatDiv2 = Math.Sin(deltaLat / 2); - double sinDeltaLongDiv2 = Math.Sin(deltaLong / 2); - // Square of half the straight line chord distance between both points. - // [0.0, 1.0] - double a = sinDeltaLatDiv2 * sinDeltaLatDiv2 + - Math.Cos(lat1rad) * Math.Cos(lat2rad) * sinDeltaLongDiv2 * sinDeltaLongDiv2; - a = Math.Min(1.0, a); - return new MoralisGeoDistance(2 * Math.Asin(Math.Sqrt(a))); - } - - //IDictionary IJsonConvertible.ConvertToJSON() => new Dictionary { - // {"__type", "GeoPoint"}, - // {nameof(latitude), Latitude}, - // {nameof(longitude), Longitude} - // }; - } -} diff --git a/MoralisDotNet/Moralis/Platform/Objects/MoralisObject.cs b/MoralisDotNet/Moralis/Platform/Objects/MoralisObject.cs deleted file mode 100644 index 1fce624..0000000 --- a/MoralisDotNet/Moralis/Platform/Objects/MoralisObject.cs +++ /dev/null @@ -1,232 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Threading; -using System.Threading.Tasks; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Operations; -using Moralis.Platform.Utilities; - -namespace Moralis.Platform.Objects -{ - /// - /// Base class for any objects that can be processed via Moralis. - /// Note: JsonIgnore internals just incase someone changes JsonSerializerSettings - /// - public class MoralisObject - { - private IObjectService objectService = null; - - public MoralisObject() - { - this.ClassName = this.GetType().Name; - this.objectId = null; - this.createdAt = DateTime.Now; - this.updatedAt = DateTime.Now; - this.ACL = new MoralisAcl(); - this.IsDirty = false; - this.sessionToken = string.Empty; - } - - public MoralisObject(string className, - string objectId = null, - string sessionToken = null, - DateTime? createdAt = null, - DateTime? updatedAt = null, - MoralisAcl ACL = null) - { - this.ClassName = className; - this.objectId = objectId; - this.sessionToken = sessionToken; - this.createdAt = createdAt; - this.updatedAt = updatedAt; - this.ACL = ACL; - this.IsDirty = true; - } - - public string objectId; - public string sessionToken; - public DateTime? createdAt; - public DateTime? updatedAt; - public MoralisAcl ACL; - public string ClassName { get; set; } - internal bool IsDirty { get; set; } - internal IObjectService ObjectService - { - get - { - return objectService; - } - - set - { - objectService = value; - } - } - - internal object Mutex { get; } = new object { }; - internal IDictionary CurrentOperations - { - get - { - lock (Mutex) - { - return OperationSetQueue.Count > 0 ? OperationSetQueue.Last.Value : new Dictionary(); - } - } - } - - LinkedList> OperationSetQueue { get; } = new LinkedList>(); - - /// - /// Deletes this object on the server. - /// - /// The cancellation token. - public Task DeleteAsync(CancellationToken cancellationToken = default) - { - return this.ObjectService.DeleteAsync(this, sessionToken, cancellationToken); - } - - public virtual async Task SaveAsync(CancellationToken cancellationToken = default) - { - // MoralisUser is a special case not all properties can be passed to save. - if (this is MoralisUser) ((MoralisUser)this).SetSaving(true); - - IDictionary operations = this.StartSave(); - string resp = await this.ObjectService.SaveAsync(this, operations, sessionToken, cancellationToken); - - Dictionary obj = JsonUtilities.Parse(resp) as Dictionary; - - if (obj.ContainsKey("objectId")) - { - this.objectId = (string)obj["objectId"]; - } - - if (obj.ContainsKey("createdAt")) - { - DateTime dt = DateTime.Now; - if (DateTime.TryParse(obj["createdAt"].ToString(), out dt)) - { - this.createdAt = dt; - } - } - - if (obj.ContainsKey("updatedAt")) - { - DateTime dt = DateTime.Now; - if (DateTime.TryParse(obj["updatedAt"].ToString(), out dt)) - { - this.updatedAt = dt; - } - } - - // Set user saving false so that local persistence has full object. - if (this is MoralisUser) ((MoralisUser)this).SetSaving(false); - - Console.WriteLine($"Save response: {resp}"); - - OperationSetQueue.Clear(); - - return true; - } - - /// - /// Atomically increments the given key by 1. - /// - /// The key to increment. - public void Increment(string key) => Increment(key, 1); - - /// - /// Atomically increments the given key by the given number. - /// - /// The key to increment. - /// The amount to increment by. - public void Increment(string key, byte amount) - { - lock (Mutex) - { - PerformOperation(key, new MoralisIncrementOperation(amount)); - } - } - public void Increment(string key, int amount) - { - lock (Mutex) - { - PerformOperation(key, new MoralisIncrementOperation(amount)); - } - } - public void Increment(string key, long amount) - { - lock (Mutex) - { - PerformOperation(key, new MoralisIncrementOperation(amount)); - } - } - /// - /// Atomically increments the given key by the given number. - /// - /// The key to increment. - /// The amount to increment by. - public void Increment(string key, double amount) - { - lock (Mutex) - { - PerformOperation(key, new MoralisIncrementOperation(amount)); - } - } - public void Increment(string key, decimal amount) - { - lock (Mutex) - { - PerformOperation(key, new MoralisIncrementOperation(amount)); - } - } - public void Increment(string key, float amount) - { - lock (Mutex) - { - PerformOperation(key, new MoralisIncrementOperation(amount)); - } - } - /// - /// Pushes new operations onto the queue and returns the current set of operations. - /// - internal IDictionary StartSave() - { - lock (Mutex) - { - IDictionary currentOperations = CurrentOperations; - OperationSetQueue.AddLast(new Dictionary()); - return currentOperations; - } - } - - internal string GetCurrentSessionToken() => this.sessionToken; - - /// - /// PerformOperation is like setting a value at an index, but instead of - /// just taking a new value, it takes a MoralisFieldOperation that modifies the value. - /// - internal void PerformOperation(string key, IMoralisFieldOperation operation) - { - lock (Mutex) - { - - PropertyInfo prop = this.GetType().GetProperty(key, BindingFlags.Public | BindingFlags.Instance); - - if (null != prop && prop.CanWrite) - { - object oldValue = prop.GetValue(this); - object newValue = operation.Apply(oldValue, key); - prop.SetValue(this, newValue); - } - - bool wasDirty = CurrentOperations.Count > 0; - CurrentOperations.TryGetValue(key, out IMoralisFieldOperation oldOperation); - IMoralisFieldOperation newOperation = operation.MergeWithPrevious(oldOperation); - CurrentOperations[key] = newOperation; - - } - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Objects/MoralisRole.cs b/MoralisDotNet/Moralis/Platform/Objects/MoralisRole.cs deleted file mode 100644 index c69ab78..0000000 --- a/MoralisDotNet/Moralis/Platform/Objects/MoralisRole.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System; -using System.Text.RegularExpressions; - -namespace Moralis.Platform.Objects -{ - public class MoralisRole : MoralisObject - { - private static readonly Regex namePattern = new Regex("^[0-9a-zA-Z_\\- ]+$"); - private string roleName; - - /// - /// Default constructor - /// - public MoralisRole() : base("_Role") { } - /// - /// Constructs a new MoralisRole with the given name. - /// - /// The name of the role to create. - /// The ACL for this role. Roles must have an ACL. - public MoralisRole(string rolName, MoralisAcl acl) : this() - { - name = roleName; - ACL = acl; - } - - public string name - { - get { return roleName; } - - set - { - if (objectId != null) - { - throw new InvalidOperationException( - "A role's name can only be set before it has been saved."); - } - if (!namePattern.IsMatch((string)value)) - { - throw new ArgumentException("A role's name can only contain alphanumeric characters, _, -, and spaces.", nameof(value)); - } - - roleName = value; - } - } - - - - /// - /// Gets the for the s that are - /// direct children of this role. These users are granted any privileges that - /// this role has been granted (e.g. read or write access through ACLs). You can - /// add or remove child users from the role through this relation. - /// - //[JsonProperty("users")] - //public Moralis Users => GetRelationProperty("Users"); - - /// - /// Gets the for the s that are - /// direct children of this role. These roles' users are granted any privileges that - /// this role has been granted (e.g. read or write access through ACLs). You can - /// add or remove child roles from the role through this relation. - /// - //[JsonProperty("roles")] - //public Moralis Roles => GetRelationProperty("Roles"); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Objects/MoralisSession.cs b/MoralisDotNet/Moralis/Platform/Objects/MoralisSession.cs deleted file mode 100644 index 7769012..0000000 --- a/MoralisDotNet/Moralis/Platform/Objects/MoralisSession.cs +++ /dev/null @@ -1,12 +0,0 @@ - - -namespace Moralis.Platform.Objects -{ - public class MoralisSession : MoralisObject - { - public MoralisSession() : base("_Session") { } - - // [JsonProperty("sessionToken")] - public new string sessionToken { get; set; } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Objects/MoralisUser.cs b/MoralisDotNet/Moralis/Platform/Objects/MoralisUser.cs deleted file mode 100644 index f849d53..0000000 --- a/MoralisDotNet/Moralis/Platform/Objects/MoralisUser.cs +++ /dev/null @@ -1,265 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Threading; -using Moralis.Platform.Utilities; -using System.Threading.Tasks; -using Moralis.Platform.Abstractions; -using Newtonsoft.Json; -using Moralis.Core.Exceptions; - -namespace Moralis.Platform.Objects -{ - - class MoralisUserJsonConvertor : JsonConverter - { - public override bool CanConvert(Type objectType) - { - return true; - } - public override bool CanRead - { - get { return false; } - } - - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) - { - throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter."); - } - - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) - { - if (value == null || !(value is MoralisUser)) - { - serializer.Serialize(writer, null); - return; - } - - Dictionary user = ((MoralisUser)value).ToParameterDictionary(); - - serializer.Serialize(writer, user); - } - } - - [JsonConverter(typeof(MoralisUserJsonConvertor))] - public class MoralisUser : MoralisObject - { - private bool isSaving = false; - - public MoralisUser() - { - this.ClassName = "_User"; - } - - public MoralisUser(string objectId = null, - string userName = null, - IDictionary> authData = null, - DateTime? createdAt = null, - DateTime? updatedAt = null, - MoralisAcl ACL = null, - string sessionToken = null, - string ethAddress = null - ) : base("_User", objectId, sessionToken, createdAt, updatedAt, ACL) - { - this.username = userName; - this.authData = authData != null ? authData : new Dictionary>(); - - if (!String.IsNullOrEmpty(ethAddress)) - { - this.ethAddress = ethAddress; - this.accounts = new string[1]; - this.accounts[0] = ethAddress; - } - else - { - accounts = new string[0]; - } - } - - public string username; - - public IDictionary> authData; - - public string password; - public string email; - public string ethAddress; - public string[] accounts; - - internal static IDictionary Authenticators { get; } = new Dictionary { }; - - internal static HashSet ImmutableKeys { get; } = new HashSet { "classname", "sessionToken", "isNew" }; - - internal ICurrentUserService CurrentUserService { get; set; } - - internal async Task SignUpAsync(Task toAwait, CancellationToken cancellationToken) - { - if (String.IsNullOrEmpty(this.objectId)) - { - if (String.IsNullOrEmpty(this.username)) throw new ArgumentException("User username required for this action."); - if (String.IsNullOrEmpty(this.password)) throw new ArgumentException("User password required for this action."); - - await this.SaveAsync(); - } - } - - public Dictionary ToParameterDictionary() - { - List propertiesToSkip = new List(new string[] { "classname", "createdat", "sessiontoken" }); - Dictionary result = new Dictionary(); - - // Use reflection to get all string properties - // that have getters and setters - IEnumerable properties = from p in this.GetType().GetProperties() - where p.CanRead && - p.CanWrite - select p; - - foreach (PropertyInfo property in properties) - { - // Not all properties should be included on save - if (isSaving && propertiesToSkip.Contains(property.Name.ToLower())) continue; - - var value = property.GetValue(this); - - if (value != null) - { - result.Add(property.Name, value); - } - } - - IEnumerable fields = from f in this.GetType().GetFields() - where f.IsPublic - select f; - - foreach (FieldInfo field in fields) - { - // Not all properties should be included on save - if (isSaving && propertiesToSkip.Contains(field.Name.ToLower())) continue; - - var value = field.GetValue(this); - - if (value != null) - { - result.Add(field.Name, value); - } - } - - return result; - } - - /// - /// Signs up a new user. This will create a new ParseUser on the server and will also persist the - /// session on disk so that you can access the user using . A username and - /// password must be set before calling SignUpAsync. - /// - public Task SignUpAsync() => SignUpAsync(CancellationToken.None); - - public void SetSaving(bool val) - { - isSaving = val; - } - - /// - /// Signs up a new user. This will create a new ParseUser on the server and will also persist the - /// session on disk so that you can access the user using . A username and - /// password must be set before calling SignUpAsync. - /// - /// The cancellation token. - public async Task SignUpAsync(CancellationToken cancellationToken) //=> TaskQueue.Enqueue(toAwait => SignUpAsync(toAwait, cancellationToken), cancellationToken); - { - if (String.IsNullOrEmpty(this.objectId)) - { - if (String.IsNullOrEmpty(this.username)) throw new ArgumentException("User username required for this action."); - if (String.IsNullOrEmpty(this.password)) throw new ArgumentException("User password required for this action."); - - try - { - await this.SaveAsync(); - } - catch (MoralisSaveException msexp) - { - throw new MoralisSignupException(msexp.Message); - } - } - } - - /// - /// Removes null values from authData (which exist temporarily for unlinking) - /// - void CleanupAuthData() - { - lock (Mutex) - { - IDictionary> _authData = authData; - - if (_authData == null) - { - return; - } - - foreach (KeyValuePair> pair in new Dictionary>(_authData)) - { - if (pair.Value == null) - { - _authData.Remove(pair.Key); - } - } - } - } - - internal static IAuthenticationProvider GetProvider(string providerName) => Authenticators.TryGetValue(providerName, out IAuthenticationProvider provider) ? provider : null; - - /// - /// Synchronizes authData for all providers. - /// - internal void SynchronizeAllAuthData() - { - lock (Mutex) - { - IDictionary> _authData = authData; - - if (_authData == null) - { - return; - } - - foreach (KeyValuePair> pair in _authData) - { - SynchronizeAuthData(GetProvider(pair.Key)); - } - } - } - - internal void SynchronizeAuthData(IAuthenticationProvider provider) - { - bool restorationSuccess = false; - - lock (Mutex) - { - IDictionary> _authData = authData; - - if (_authData == null || provider == null) - { - return; - } - - if (_authData.TryGetValue(provider.AuthType, out IDictionary data)) - { - restorationSuccess = provider.RestoreAuthentication(data); - } - } - } - - /// - /// Checks whether a user is linked to a service. - /// - internal bool IsLinked(string authType) - { - lock (Mutex) - { - return authData != null && authData.ContainsKey(authType) && authData[authType] != null; - } - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Operations/MoralisAddOperation.cs b/MoralisDotNet/Moralis/Platform/Operations/MoralisAddOperation.cs deleted file mode 100644 index 1c2d3ae..0000000 --- a/MoralisDotNet/Moralis/Platform/Operations/MoralisAddOperation.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Utilities; - -namespace Moralis.Platform.Operations -{ - class MoralisAddOperation : IMoralisFieldOperation - { - ReadOnlyCollection Data { get; } - - public string __op { get { return "Add"; } } - - public IEnumerable objects => Data; - - public MoralisAddOperation(IEnumerable objects) => Data = new ReadOnlyCollection(objects.ToList()); - - public IMoralisFieldOperation MergeWithPrevious(IMoralisFieldOperation previous) => previous switch - { - null => this, - MoralisDeleteOperation { } => new MoralisSetOperation(Data.ToList()), - MoralisSetOperation { } setOp => new MoralisSetOperation(Conversion.To>(setOp.Value).Concat(Data).ToList()), - MoralisAddOperation { } addition => new MoralisAddOperation(addition.objects.Concat(Data)), - _ => throw new InvalidOperationException("Operation is invalid after previous operation.") - }; - - public object Apply(object oldValue, string key) => oldValue is { } ? Conversion.To>(oldValue).Concat(Data).ToList() : Data.ToList(); - - - } -} diff --git a/MoralisDotNet/Moralis/Platform/Operations/MoralisDeleteOperation.cs b/MoralisDotNet/Moralis/Platform/Operations/MoralisDeleteOperation.cs deleted file mode 100644 index c1f2b4d..0000000 --- a/MoralisDotNet/Moralis/Platform/Operations/MoralisDeleteOperation.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Moralis.Platform.Abstractions; - -namespace Moralis.Platform.Operations -{ - public class MoralisDeleteOperation : IMoralisFieldOperation - { - public string __op { get { return "Delete"; } } - internal static object Token { get; } = new object { }; - - public static MoralisDeleteOperation Instance { get; } = new MoralisDeleteOperation { }; - - private MoralisDeleteOperation() { } - - public IMoralisFieldOperation MergeWithPrevious(IMoralisFieldOperation previous) => this; - - public object Apply(object oldValue, string key) => Token; - } -} diff --git a/MoralisDotNet/Moralis/Platform/Operations/MoralisFieldOperations.cs b/MoralisDotNet/Moralis/Platform/Operations/MoralisFieldOperations.cs deleted file mode 100644 index a75fe6e..0000000 --- a/MoralisDotNet/Moralis/Platform/Operations/MoralisFieldOperations.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using System.Collections.Generic; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Operations -{ - public class MoralisObjectIdComparer : IEqualityComparer - { - bool IEqualityComparer.Equals(object p1, object p2) - { - MoralisObject moralisObj1 = p1 as MoralisObject; - MoralisObject moralisObj2 = p2 as MoralisObject; - if (moralisObj1 != null && moralisObj1 != null) - { - return Equals(moralisObj1.objectId, moralisObj1.objectId); - } - return Equals(p1, p2); - } - - public int GetHashCode(object p) - { - MoralisObject moralisObject = p as MoralisObject; - if (moralisObject != null) - { - return moralisObject.objectId.GetHashCode(); - } - return p.GetHashCode(); - } - } - - static class MoralisFieldOperations - { - private static MoralisObjectIdComparer comparer; - - public static IMoralisFieldOperation Decode(IDictionary json) => throw new NotImplementedException(); - - public static IEqualityComparer MoralisObjectComparer - { - get - { - if (comparer == null) - { - comparer = new MoralisObjectIdComparer(); - } - return comparer; - } - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Operations/MoralisIncrementOperation.cs b/MoralisDotNet/Moralis/Platform/Operations/MoralisIncrementOperation.cs deleted file mode 100644 index 30926dd..0000000 --- a/MoralisDotNet/Moralis/Platform/Operations/MoralisIncrementOperation.cs +++ /dev/null @@ -1,115 +0,0 @@ -using System; -using System.Collections.Generic; -using Moralis.Platform.Abstractions; - -namespace Moralis.Platform.Operations -{ - class MoralisIncrementOperation : IMoralisFieldOperation - { - - static IDictionary, Func> Adders { get; } = new Dictionary, Func> - { - [new Tuple(typeof(sbyte), typeof(sbyte))] = (left, right) => (sbyte)left + (sbyte)right, - [new Tuple(typeof(sbyte), typeof(short))] = (left, right) => (sbyte)left + (short)right, - [new Tuple(typeof(sbyte), typeof(int))] = (left, right) => (sbyte)left + (int)right, - [new Tuple(typeof(sbyte), typeof(long))] = (left, right) => (sbyte)left + (long)right, - [new Tuple(typeof(sbyte), typeof(float))] = (left, right) => (sbyte)left + (float)right, - [new Tuple(typeof(sbyte), typeof(double))] = (left, right) => (sbyte)left + (double)right, - [new Tuple(typeof(sbyte), typeof(decimal))] = (left, right) => (sbyte)left + (decimal)right, - [new Tuple(typeof(byte), typeof(byte))] = (left, right) => (byte)left + (byte)right, - [new Tuple(typeof(byte), typeof(short))] = (left, right) => (byte)left + (short)right, - [new Tuple(typeof(byte), typeof(ushort))] = (left, right) => (byte)left + (ushort)right, - [new Tuple(typeof(byte), typeof(int))] = (left, right) => (byte)left + (int)right, - [new Tuple(typeof(byte), typeof(uint))] = (left, right) => (byte)left + (uint)right, - [new Tuple(typeof(byte), typeof(long))] = (left, right) => (byte)left + (long)right, - [new Tuple(typeof(byte), typeof(ulong))] = (left, right) => (byte)left + (ulong)right, - [new Tuple(typeof(byte), typeof(float))] = (left, right) => (byte)left + (float)right, - [new Tuple(typeof(byte), typeof(double))] = (left, right) => (byte)left + (double)right, - [new Tuple(typeof(byte), typeof(decimal))] = (left, right) => (byte)left + (decimal)right, - [new Tuple(typeof(short), typeof(short))] = (left, right) => (short)left + (short)right, - [new Tuple(typeof(short), typeof(int))] = (left, right) => (short)left + (int)right, - [new Tuple(typeof(short), typeof(long))] = (left, right) => (short)left + (long)right, - [new Tuple(typeof(short), typeof(float))] = (left, right) => (short)left + (float)right, - [new Tuple(typeof(short), typeof(double))] = (left, right) => (short)left + (double)right, - [new Tuple(typeof(short), typeof(decimal))] = (left, right) => (short)left + (decimal)right, - [new Tuple(typeof(ushort), typeof(ushort))] = (left, right) => (ushort)left + (ushort)right, - [new Tuple(typeof(ushort), typeof(int))] = (left, right) => (ushort)left + (int)right, - [new Tuple(typeof(ushort), typeof(uint))] = (left, right) => (ushort)left + (uint)right, - [new Tuple(typeof(ushort), typeof(long))] = (left, right) => (ushort)left + (long)right, - [new Tuple(typeof(ushort), typeof(ulong))] = (left, right) => (ushort)left + (ulong)right, - [new Tuple(typeof(ushort), typeof(float))] = (left, right) => (ushort)left + (float)right, - [new Tuple(typeof(ushort), typeof(double))] = (left, right) => (ushort)left + (double)right, - [new Tuple(typeof(ushort), typeof(decimal))] = (left, right) => (ushort)left + (decimal)right, - [new Tuple(typeof(int), typeof(int))] = (left, right) => (int)left + (int)right, - [new Tuple(typeof(int), typeof(long))] = (left, right) => (int)left + (long)right, - [new Tuple(typeof(int), typeof(float))] = (left, right) => (int)left + (float)right, - [new Tuple(typeof(int), typeof(double))] = (left, right) => (int)left + (double)right, - [new Tuple(typeof(int), typeof(decimal))] = (left, right) => (int)left + (decimal)right, - [new Tuple(typeof(uint), typeof(uint))] = (left, right) => (uint)left + (uint)right, - [new Tuple(typeof(uint), typeof(long))] = (left, right) => (uint)left + (long)right, - [new Tuple(typeof(uint), typeof(ulong))] = (left, right) => (uint)left + (ulong)right, - [new Tuple(typeof(uint), typeof(float))] = (left, right) => (uint)left + (float)right, - [new Tuple(typeof(uint), typeof(double))] = (left, right) => (uint)left + (double)right, - [new Tuple(typeof(uint), typeof(decimal))] = (left, right) => (uint)left + (decimal)right, - [new Tuple(typeof(long), typeof(long))] = (left, right) => (long)left + (long)right, - [new Tuple(typeof(long), typeof(float))] = (left, right) => (long)left + (float)right, - [new Tuple(typeof(long), typeof(double))] = (left, right) => (long)left + (double)right, - [new Tuple(typeof(long), typeof(decimal))] = (left, right) => (long)left + (decimal)right, - [new Tuple(typeof(char), typeof(char))] = (left, right) => (char)left + (char)right, - [new Tuple(typeof(char), typeof(ushort))] = (left, right) => (char)left + (ushort)right, - [new Tuple(typeof(char), typeof(int))] = (left, right) => (char)left + (int)right, - [new Tuple(typeof(char), typeof(uint))] = (left, right) => (char)left + (uint)right, - [new Tuple(typeof(char), typeof(long))] = (left, right) => (char)left + (long)right, - [new Tuple(typeof(char), typeof(ulong))] = (left, right) => (char)left + (ulong)right, - [new Tuple(typeof(char), typeof(float))] = (left, right) => (char)left + (float)right, - [new Tuple(typeof(char), typeof(double))] = (left, right) => (char)left + (double)right, - [new Tuple(typeof(char), typeof(decimal))] = (left, right) => (char)left + (decimal)right, - [new Tuple(typeof(float), typeof(float))] = (left, right) => (float)left + (float)right, - [new Tuple(typeof(float), typeof(double))] = (left, right) => (float)left + (double)right, - [new Tuple(typeof(ulong), typeof(ulong))] = (left, right) => (ulong)left + (ulong)right, - [new Tuple(typeof(ulong), typeof(float))] = (left, right) => (ulong)left + (float)right, - [new Tuple(typeof(ulong), typeof(double))] = (left, right) => (ulong)left + (double)right, - [new Tuple(typeof(ulong), typeof(decimal))] = (left, right) => (ulong)left + (decimal)right, - [new Tuple(typeof(double), typeof(double))] = (left, right) => (double)left + (double)right, - [new Tuple(typeof(decimal), typeof(decimal))] = (left, right) => (decimal)left + (decimal)right - }; - - static object Add(object first, object second) => Adders.TryGetValue(new Tuple(first.GetType(), second.GetType()), out Func adder) ? adder(first, second) : throw new InvalidCastException($"Could not add objects of type {first.GetType()} and {second.GetType()} to each other."); - - - // [JsonProperty("__op")] - public string __op { get { return "Increment"; } } - - //[JsonProperty("amount")] - public object amount { get; } - - public MoralisIncrementOperation(object amt) => amount = amt; - - - - public IMoralisFieldOperation MergeWithPrevious(IMoralisFieldOperation previous) => previous switch - { - null => this, - MoralisDeleteOperation _ => new MoralisSetOperation(amount), - - // This may be a bug, but it was in the original logic. - - MoralisSetOperation { Value: string { } } => throw new InvalidOperationException("Cannot increment a non-number type."), - MoralisSetOperation { Value: var value } => new MoralisSetOperation(Add(value, amount)), - MoralisIncrementOperation { amount: var amt } => new MoralisIncrementOperation(Add(amt, amount)), - _ => throw new InvalidOperationException("Operation is invalid after previous operation.") - }; - - public object Apply(object oldValue, string key) - { - if (oldValue is string) throw new InvalidOperationException("Cannot increment a non-number type."); - - if (oldValue == null) oldValue = 0; - - return Add(oldValue, amount); - } - - - - } -} diff --git a/MoralisDotNet/Moralis/Platform/Operations/MoralisSetOperation.cs b/MoralisDotNet/Moralis/Platform/Operations/MoralisSetOperation.cs deleted file mode 100644 index a140dc5..0000000 --- a/MoralisDotNet/Moralis/Platform/Operations/MoralisSetOperation.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Moralis.Platform.Abstractions; - -namespace Moralis.Platform.Operations -{ - class MoralisSetOperation : IMoralisFieldOperation - { - public object Value { get; private set; } - - public MoralisSetOperation(object value) => Value = value; - - public IMoralisFieldOperation MergeWithPrevious(IMoralisFieldOperation previous) => this; - - public object Apply(object oldValue, string key) => Value; - - - } -} diff --git a/MoralisDotNet/Moralis/Platform/Operations/MoralisUniqueAddOperation.cs b/MoralisDotNet/Moralis/Platform/Operations/MoralisUniqueAddOperation.cs deleted file mode 100644 index c38175b..0000000 --- a/MoralisDotNet/Moralis/Platform/Operations/MoralisUniqueAddOperation.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Utilities; - -namespace Moralis.Platform.Operations -{ - class MoralisUniqueAddOperation : IMoralisFieldOperation - { - ReadOnlyCollection Data { get; } - - public string __op { get { return "AddUnique"; } } - - public IEnumerable objects => Data; - public MoralisUniqueAddOperation(IEnumerable objects) => Data = new ReadOnlyCollection(objects.ToList()); - - public IMoralisFieldOperation MergeWithPrevious(IMoralisFieldOperation previous) => previous switch - { - null => this, - MoralisDeleteOperation { } => new MoralisSetOperation(Data.ToList()), - MoralisSetOperation { } setOp => new MoralisSetOperation(Conversion.To>(setOp.Value).Concat(Data).ToList()), - MoralisAddOperation { } addition => new MoralisAddOperation(addition.objects.Concat(Data)), - _ => throw new InvalidOperationException("Operation is invalid after previous operation.") - }; - - public object Apply(object oldValue, string key) - { - if (oldValue == null) - { - return Data.ToList(); - } - - List result = Conversion.To>(oldValue).ToList(); - IEqualityComparer comparer = MoralisFieldOperations.MoralisObjectComparer; - - foreach (object target in Data) - { - if (target is MoralisObject) - { - if (!(result.FirstOrDefault(reference => comparer.Equals(target, reference)) is { } matched)) - { - result.Add(target); - } - else - { - result[result.IndexOf(matched)] = target; - } - } - else if (!result.Contains(target, comparer)) - { - result.Add(target); - } - } - - return result; - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Queries/Live/ActionEvent.cs b/MoralisDotNet/Moralis/Platform/Queries/Live/ActionEvent.cs deleted file mode 100644 index 3d00e65..0000000 --- a/MoralisDotNet/Moralis/Platform/Queries/Live/ActionEvent.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Queries.Live -{ - /// - /// This action object is used for Connected, Create, Update, Enter, Delete, - /// Leave, Subscribed, and Unsubscribed events. - /// Note: For subscribed and unscubscribed events, Object will always be null or default - /// - /// Response object - public class ActionEvent : QueryEventMessage where T : MoralisObject - { - /// - /// REQUIRED: Client generated - /// - public int requestId { get; set; } - - /// - /// OPTIONAL: Moralis current user session token. - /// - public T Object { get; set; } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Queries/Live/ConnectRequest.cs b/MoralisDotNet/Moralis/Platform/Queries/Live/ConnectRequest.cs deleted file mode 100644 index ff8ccd5..0000000 --- a/MoralisDotNet/Moralis/Platform/Queries/Live/ConnectRequest.cs +++ /dev/null @@ -1,58 +0,0 @@ - -namespace Moralis.Platform.Queries.Live -{ - /// - /// The connect request is sent from a client to the LiveQuery server. It - /// should be the first message sent from a client after the WebSocket - /// connection is established - /// - public class ConnectRequest : QueryEventMessage - { - /// - /// REQUIRED: Moralis Application Id - /// - public string applicationId { get; set; } - - /// - /// OPTIONAL: For future use. - /// - public string restApiKey { get; set; } - - /// - /// OPTIONAL: For future use. - /// - public string javascriptKey { get; set; } - - /// - /// OPTIONAL: For future use. - /// - public string clientKey { get; set; } - - /// - /// OPTIONAL: For future use. - /// - public string windowsKey { get; set; } - - /// - /// OPTIONAL: Moralis Master Key - CAUTION should not be used from client - /// application. If an operation requires a master key it is recommended - /// that that operation be called via a Cloud Function. - /// - public string masterKey { get; set; } - - /// - /// OPTIONAL: Moralis current user session token. - /// - public string sessionToken { get; set; } - - /// - /// OPTIONAL: Moralis Instanllation Id. - /// - public string installationId { get; set; } - - public ConnectRequest() - { - op = OperationTypes.connect.ToString(); - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Queries/Live/Enums.cs b/MoralisDotNet/Moralis/Platform/Queries/Live/Enums.cs deleted file mode 100644 index a1240ea..0000000 --- a/MoralisDotNet/Moralis/Platform/Queries/Live/Enums.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Moralis.Platform.Queries.Live -{ - public enum WebSocketStateType { - Connecting = 0, - Open = 1, - Closing = 2, - Closed = 3 - } -} \ No newline at end of file diff --git a/MoralisDotNet/Moralis/Platform/Queries/Live/ErrorMessage.cs b/MoralisDotNet/Moralis/Platform/Queries/Live/ErrorMessage.cs deleted file mode 100644 index f9a1f7d..0000000 --- a/MoralisDotNet/Moralis/Platform/Queries/Live/ErrorMessage.cs +++ /dev/null @@ -1,28 +0,0 @@ - -namespace Moralis.Platform.Queries.Live -{ - public class ErrorMessage : QueryEventMessage - { - public ErrorMessage() => op = OperationTypes.error.ToString(); - - /// - /// REQUIRED: Client generated - /// - public int? requestId { get; set; } - - /// - /// A number which represents the type of the error. - /// - public int code { get; set; } - - /// - /// The error message. - /// - public string error { get; set; } - - /// - /// Indicates whether a client can reconnect to the LiveQuery server after this error. - /// - public bool reconnect { get; set; } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Queries/Live/LiveQueryClientStatus.cs b/MoralisDotNet/Moralis/Platform/Queries/Live/LiveQueryClientStatus.cs deleted file mode 100644 index 5a78290..0000000 --- a/MoralisDotNet/Moralis/Platform/Queries/Live/LiveQueryClientStatus.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Moralis.Platform.Queries.Live -{ - public enum LiveQueryClientStatusTypes - { - /// - /// The client is new and not running - /// - New, - /// - /// A subscribe request was sent - /// - Opening, - /// - /// The client is subscribed and listening for server events. - /// - Open, - /// - /// An unscubscribe message has bee sent to the server. - /// - Closing, - /// - /// The client has been successfully unscubscribed from the server and can be disposed of. - /// - Closed, - /// - /// The client is waiting on a request result to finish processing. - /// - Waiting - } -} diff --git a/MoralisDotNet/Moralis/Platform/Queries/Live/MoralisClientWebSocket.cs b/MoralisDotNet/Moralis/Platform/Queries/Live/MoralisClientWebSocket.cs deleted file mode 100644 index 3fa407b..0000000 --- a/MoralisDotNet/Moralis/Platform/Queries/Live/MoralisClientWebSocket.cs +++ /dev/null @@ -1,164 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net.WebSockets; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Moralis.Platform.Abstractions; - -namespace Moralis.Platform.Queries.Live -{ - public class MoralisClientWebSocket : IClientWebSocket - { - private ClientWebSocket webSocket = new ClientWebSocket(); - - // - // Summary: - // Gets the reason why the close handshake was initiated on System.Net.WebSockets.ClientWebSocket - // instance. - // - // Returns: - // Returns System.Net.WebSockets.WebSocketCloseStatus. The reason why the close - // handshake was initiated. - public WebSocketCloseStatus? CloseStatus => webSocket.CloseStatus; - // - // Summary: - // Gets a description of the reason why the System.Net.WebSockets.ClientWebSocket - // instance was closed. - // - // Returns: - // Returns System.String. The description of the reason why the System.Net.WebSockets.ClientWebSocket - // instance was closed. - public string CloseStatusDescription => webSocket.CloseStatusDescription; - // - // Summary: - // Gets the WebSocket options for the System.Net.WebSockets.ClientWebSocket instance. - // - // Returns: - // Returns System.Net.WebSockets.ClientWebSocketOptions. The WebSocket options for - // the System.Net.WebSockets.ClientWebSocket instance. - public ClientWebSocketOptions Options => webSocket.Options; - // - // Summary: - // Get the WebSocket state of the System.Net.WebSockets.ClientWebSocket instance. - // - // Returns: - // Returns System.Net.WebSockets.WebSocketState. The WebSocket state of the System.Net.WebSockets.ClientWebSocket - // instance. - public WebSocketState State => webSocket.State; - // - // Summary: - // Gets the supported WebSocket sub-protocol for the System.Net.WebSockets.ClientWebSocket - // instance. - // - // Returns: - // Returns System.String. The supported WebSocket sub-protocol. - public string SubProtocol => webSocket.SubProtocol; - - // - // Summary: - // Aborts the connection and cancels any pending IO operations. - public void Abort() => webSocket.Abort(); - // - // Summary: - // Close the System.Net.WebSockets.ClientWebSocket instance as an asynchronous operation. - // - // Parameters: - // closeStatus: - // The WebSocket close status. - // - // statusDescription: - // A description of the close status. - // - // cancellationToken: - // A cancellation token used to propagate notification that this operation should - // be canceled. - // - // Returns: - // Returns System.Threading.Tasks.Task. The task object representing the asynchronous - // operation. - public Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) - => webSocket.CloseAsync(closeStatus, statusDescription, cancellationToken); - // - // Summary: - // Close the output for the System.Net.WebSockets.ClientWebSocket instance as an - // asynchronous operation. - // - // Parameters: - // closeStatus: - // The WebSocket close status. - // - // statusDescription: - // A description of the close status. - // - // cancellationToken: - // A cancellation token used to propagate notification that this operation should - // be canceled. - // - // Returns: - // Returns System.Threading.Tasks.Task. The task object representing the asynchronous - // operation. - public Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) - => webSocket.CloseOutputAsync(closeStatus, statusDescription, cancellationToken); - // - // Summary: - // Connect to a WebSocket server as an asynchronous operation. - // - // Parameters: - // uri: - // The URI of the WebSocket server to connect to. - // - // cancellationToken: - // A cancellation token used to propagate notification that the operation should - // be canceled. - // - // Returns: - // Returns System.Threading.Tasks.Task. The task object representing the asynchronous - // operation. - public Task ConnectAsync(Uri uri, CancellationToken cancellationToken) - => webSocket.ConnectAsync(uri, cancellationToken); - - // - // Summary: - // Receive data on System.Net.WebSockets.ClientWebSocket as an asynchronous operation. - // - // Parameters: - // buffer: - // The buffer to receive the response. - // - // cancellationToken: - // A cancellation token used to propagate notification that this operation should - // be canceled. - // - // Returns: - // Returns System.Threading.Tasks.Task`1. The task object representing the asynchronous - // operation. - public Task ReceiveAsync(ArraySegment buffer, CancellationToken cancellationToken) - => webSocket.ReceiveAsync(buffer, cancellationToken); - // - // Summary: - // Send data on System.Net.WebSockets.ClientWebSocket as an asynchronous operation. - // - // Parameters: - // buffer: - // The buffer containing the message to be sent. - // - // messageType: - // Specifies whether the buffer is clear text or in a binary format. - // - // endOfMessage: - // Specifies whether this is the final asynchronous send. Set to true if this is - // the final send; false otherwise. - // - // cancellationToken: - // A cancellation token used to propagate notification that this operation should - // be canceled. - // - // Returns: - // The task object representing the asynchronous operation. - public Task SendAsync(ArraySegment buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) - => webSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken); - - public void Dispose() => webSocket.Dispose(); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Queries/Live/MoralisLiveQueryDelegates.cs b/MoralisDotNet/Moralis/Platform/Queries/Live/MoralisLiveQueryDelegates.cs deleted file mode 100644 index 70fb3a0..0000000 --- a/MoralisDotNet/Moralis/Platform/Queries/Live/MoralisLiveQueryDelegates.cs +++ /dev/null @@ -1,49 +0,0 @@ -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Queries.Live -{ - /// - /// Delegate to define a event to fire when a connection to the live query - /// server has been established. - /// - public delegate void LiveQueryConnectedHandler(); - - /// - /// Delegate to define a event to fire when a substribtion to the live - /// query server has been established. - /// - /// - public delegate void LiveQuerySubscribedHandler(int requestId); - - /// - /// Delegate to define an event to fire when a live query action has - /// occurred. - /// - /// - /// - /// - public delegate void LiveQueryActionHandler(T item, int requestId) where T : MoralisObject; - - /// - /// A delgate to define an event to fire when a client has successfully - /// unsubscribed from the live query server. - /// - /// - public delegate void LiveQueryUnsubscribedHandler(int requestId); - - /// - /// Provides a delegate for Moralis Live Query error messages. - /// - /// - public delegate void LiveQueryErrorHandler(ErrorMessage evt); - - /// - /// A delegate the client uses to handle an event when a message is received - /// from the live query server. - /// - /// - /// - public delegate void LiveQueryMessageHandler(byte[] buffer, int bufferSize); - - public delegate void LiveQueryGeneralMessageHandler(string text); -} diff --git a/MoralisDotNet/Moralis/Platform/Queries/Live/OperationTypes.cs b/MoralisDotNet/Moralis/Platform/Queries/Live/OperationTypes.cs deleted file mode 100644 index 45aa67e..0000000 --- a/MoralisDotNet/Moralis/Platform/Queries/Live/OperationTypes.cs +++ /dev/null @@ -1,68 +0,0 @@ - -namespace Moralis.Platform.Queries.Live -{ - /// - /// Define valid Live Query operations. - /// - public enum OperationTypes - { - /// - /// Request Operation: The connect message is sent from a client to the LiveQuery - /// server. It should be the first message sent from a client after the WebSocket - /// connection is established. - /// - connect, - /// - /// Event Operation: Received when a connection to the Live Query server is successful. - /// - connected, - /// - /// Request Operation: Used to subscribe to updates based on a query. - /// - subscribe, - /// - /// Event Operation: If a subscription is successful the server will respond - /// with subscribed. - /// - subscribed, - /// - /// Event Operation: A new object that meets the requirements of the query has - /// been created. - /// - create, - /// - /// Event Operation: Enter is returned by the server when a previous object that - /// did not meet requirements of the query now does. - /// - enter, - /// - /// Event Operation: Sent when an object that meets the requirements of the query - /// is updated. - /// - update, - /// - /// Event Operation: Sent when an object changes so that it no longer meets the - /// requirements of the query. - /// - leave, - /// - /// Event Operation: Sent when an object that meets the requirements of the query - /// is deleted. - /// - delete, - /// - /// Request Operation: Client should send this request to server when the client no - /// longer wants to receive events related to query. - /// - unsubscribe, - /// - /// Event operation: Sent to a client when unsubcribe is successful. - /// - unsubscribed, - /// - /// Event operation: Sent when a client request cannot be handled by the server - /// - error - }; -} - diff --git a/MoralisDotNet/Moralis/Platform/Queries/Live/QueryEventMessage.cs b/MoralisDotNet/Moralis/Platform/Queries/Live/QueryEventMessage.cs deleted file mode 100644 index 1c7e61f..0000000 --- a/MoralisDotNet/Moralis/Platform/Queries/Live/QueryEventMessage.cs +++ /dev/null @@ -1,14 +0,0 @@ - -namespace Moralis.Platform.Queries.Live -{ - /// - /// Defines the base live query request / event message object. - /// - public class QueryEventMessage - { - /// - /// REQUIRED: The operation being requested or event reported. - /// - public string op { get; set; } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Queries/Live/SubscribableWebSocket.cs b/MoralisDotNet/Moralis/Platform/Queries/Live/SubscribableWebSocket.cs deleted file mode 100644 index 1bee772..0000000 --- a/MoralisDotNet/Moralis/Platform/Queries/Live/SubscribableWebSocket.cs +++ /dev/null @@ -1,231 +0,0 @@ - -using System; -using System.Net.WebSockets; -using System.Text; -using System.Threading; -using Moralis.Platform.Exceptions; -using static Moralis.Platform.Exceptions.MoralisFailureException; -using System.Collections.Generic; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Queries.Live; - -namespace Moralis.Platform.Queries.Live -{ - public class SubscribableWebSocket - { - private byte[] subscriptionRequest = null; - private bool cocnectionSent = false; - private bool subscriptionSent = false; - private bool unsubscribeSent = false; - - /// - /// Event raised when a message is received from the server. - /// - public event LiveQueryMessageHandler OnEventMessage; - - public event LiveQueryGeneralMessageHandler OnGeneralMessage; - - /// - /// Indicates the current status of this client. - /// - public LiveQueryClientStatusTypes ClientStatus { get; set; } - - /// - /// Server connection settings. - /// - public IServerConnectionData ConncetionData { get; set; } - - /// - /// Provides Serialization / Deserialization services. - /// - public IJsonSerializer JsonSerializer { get; set; } - - public string InstallationId { get; set; } - - /// - /// Request Id used for this subscription - /// - public int RequestId { get; private set; } - - /// - /// User session token. - /// - public string SessionToken { get; set; } - - private IClientWebSocket webSocket; - - public SubscribableWebSocket(byte[] subRequest, IServerConnectionData connectionData, int requestId, string installationId, string sessionToken, IJsonSerializer jsonSerializer) - { - subscriptionRequest = subRequest; - ConncetionData = connectionData; - InstallationId = installationId; - RequestId = requestId; - SessionToken = sessionToken; - JsonSerializer = jsonSerializer; - } - - /// - /// Creates a live query subscription. If established, listens until either - /// the app or the server closes the connection. - /// - public async void Subscribe() - { - if (String.IsNullOrWhiteSpace(ConncetionData.LiveQueryServerURI)) - { - throw new MoralisFailureException(ErrorCode.ServerUrlNullOrEmtpy, ""); - } - - ClientStatus = LiveQueryClientStatusTypes.New; - bool receiving = false; - List messageBytes = new List(); - - using (IClientWebSocket ws = webSocket switch - { - { } => webSocket, - _ => new MoralisClientWebSocket() - }) - { - await ws.ConnectAsync(new Uri(ConncetionData.LiveQueryServerURI), CancellationToken.None); - byte[] buffer = new byte[256]; - bool msgSent = false; - - // Establish a connection and listen and process messages until closed. - while (ws.State == WebSocketState.Open && ClientStatus != LiveQueryClientStatusTypes.Closed) - { - if (!receiving) - { - // If in new status create and send a connection request. - if (!cocnectionSent && LiveQueryClientStatusTypes.New.Equals(ClientStatus)) - { - SendGeneralMessage("Sending connection request."); - byte[] bytes = CreateConnectRequest(); - ArraySegment seg = new ArraySegment(bytes); - await ws.SendAsync(seg, WebSocketMessageType.Text, true, CancellationToken.None); - cocnectionSent = true; - msgSent = true; - } - // If in openning status, create and send a subscription request. - else if (!subscriptionSent && LiveQueryClientStatusTypes.Opening.Equals(ClientStatus)) - { - SendGeneralMessage("Sending subscription request."); - ArraySegment seg = new ArraySegment(subscriptionRequest); - await ws.SendAsync(seg, WebSocketMessageType.Text, true, CancellationToken.None); - subscriptionSent = true; - msgSent = true; - } - // If in closing status, create and send an unsubscribe request. - else if (!unsubscribeSent && LiveQueryClientStatusTypes.Closing.Equals(ClientStatus)) - { - SendGeneralMessage("Sending unsubscribe request."); - byte[] bytes = CreateUnsubscribeRequest(); - ArraySegment seg = new ArraySegment(bytes); - await ws.SendAsync(seg, WebSocketMessageType.Text, true, CancellationToken.None); - unsubscribeSent = true; - msgSent = true; - } - } - - // Only listen if the client is not processing the response for - // a request (such as connect, subscribe, unsubscribe). - if (receiving || msgSent || LiveQueryClientStatusTypes.Open.Equals(ClientStatus)) - { - SendGeneralMessage($"Listening, status: {ClientStatus}"); - // Listen for next response from server. - var result = await ws.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None); - SendGeneralMessage("Result received."); - if (result.MessageType == WebSocketMessageType.Close) - { - await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); - ClientStatus = LiveQueryClientStatusTypes.Closed; - receiving = false; - msgSent = false; - } - else - { - if (!receiving) - { - messageBytes.Clear(); - receiving = true; - } - - messageBytes.AddRange(PackBuffer(buffer, result.Count)); - - if (result.EndOfMessage) - { - receiving = false; - msgSent = false; - // Handle normal processing message. - OnEventMessage(messageBytes.ToArray(), messageBytes.Count); - } - } - } - } - - Console.WriteLine("Left subscription loop."); - } - } - - internal void SetState(LiveQueryClientStatusTypes newState) => ClientStatus = newState; - - /// - /// Should only be set for testing scenarios. - /// - /// - public void SetWebsocket(IClientWebSocket ws) => webSocket = ws; - - private byte[] CreateConnectRequest() - { - ConnectRequest msg = new ConnectRequest() - { - applicationId = ConncetionData.ApplicationID, - //InstallationId = InstallationId, - //SessionToken = SessionToken - }; - - string json = JsonSerializer.Serialize(msg, JsonSerializer.DefaultOptions); - - byte[] bytes = Encoding.UTF8.GetBytes(json); - - return bytes; - } - - private byte[] CreateUnsubscribeRequest() - { - UnscubscribeRequest msg = new UnscubscribeRequest(RequestId); - - string json = JsonSerializer.Serialize(msg, JsonSerializer.DefaultOptions); - - byte[] bytes = Encoding.UTF8.GetBytes(json); - - return bytes; - } - - private byte[] PackBuffer(byte[] buffer, int size) - { - List resp = new List(); - int index = 0; - foreach (byte b in buffer) - { - - if (b == 0) - break; - - resp.Add(b); - index++; - - if (index >= size) - break; - } - - return resp.ToArray(); - } - - private void SendGeneralMessage(string msg) - { - if (OnGeneralMessage != null) - { - OnGeneralMessage(msg); - } - } - } -} \ No newline at end of file diff --git a/MoralisDotNet/Moralis/Platform/Queries/Live/SubscribeRequest.cs b/MoralisDotNet/Moralis/Platform/Queries/Live/SubscribeRequest.cs deleted file mode 100644 index 3b633fa..0000000 --- a/MoralisDotNet/Moralis/Platform/Queries/Live/SubscribeRequest.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System.Collections.Generic; -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Queries.Live -{ - public class SubscribeRequest : QueryEventMessage where T : MoralisObject - { - private MoralisQuery _query; - - /// - /// REQUIRED: Moralis Application Id - /// - public string applicationId { get; set; } - - /// - /// REQUIRED: Client generated - /// - public int requestId { get; set; } - - /// - /// OPTIONAL: Moralis current user session token. - /// - public string sessionToken { get; set; } - - /// - /// Query parameter values sent to - /// - public IDictionary query { get; private set; } - - internal MoralisQuery OriginalQuery - { - get { return _query; } - set - { - _query = value; - - query = _query.BuildParameters(true); - } - } - - public SubscribeRequest() => op = OperationTypes.subscribe.ToString(); - - public SubscribeRequest(MoralisQuery targetQuery, string applicationId, int requestId, string sessionToken = null) => - (this.OriginalQuery, this.applicationId, this.requestId, op, this.sessionToken) = - (targetQuery, applicationId, requestId, OperationTypes.subscribe.ToString(), sessionToken); - - } -} diff --git a/MoralisDotNet/Moralis/Platform/Queries/Live/UnscubscribeRequest.cs b/MoralisDotNet/Moralis/Platform/Queries/Live/UnscubscribeRequest.cs deleted file mode 100644 index d103fbc..0000000 --- a/MoralisDotNet/Moralis/Platform/Queries/Live/UnscubscribeRequest.cs +++ /dev/null @@ -1,15 +0,0 @@ - -namespace Moralis.Platform.Queries.Live -{ - public class UnscubscribeRequest : QueryEventMessage - { - public UnscubscribeRequest() => (op, requestId) = (OperationTypes.unsubscribe.ToString(), 0); - - public UnscubscribeRequest(int requestId) => (op, this.requestId) = (OperationTypes.unsubscribe.ToString(), requestId); - - /// - /// REQUIRED: Client generated - /// - public int requestId { get; set; } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Queries/MoralisQuery.cs b/MoralisDotNet/Moralis/Platform/Queries/MoralisQuery.cs deleted file mode 100644 index 531174c..0000000 --- a/MoralisDotNet/Moralis/Platform/Queries/MoralisQuery.cs +++ /dev/null @@ -1,826 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.Text.RegularExpressions; -using System.Threading; -using Moralis.Platform.Utilities; -using System.Threading.Tasks; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Exceptions; -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Queries -{ - public class MoralisQuery where T : MoralisObject - { - /// - /// Serialized clauses. - /// - Dictionary Filters { get; } - - /// - /// Serialized clauses. - /// - ReadOnlyCollection Orderings { get; } - - /// - /// Serialized related data query merging request (data inclusion) clauses. - /// - ReadOnlyCollection Includes { get; } - - /// - /// Serialized key selections. - /// - ReadOnlyCollection KeySelections { get; } - - string RedirectClassNameForKey { get; } - - int? SkipAmount { get; } - - int? LimitAmount { get; } - - internal string ClassName { get; } - - internal string SessionToken { get; } - - internal IQueryService QueryService { get; } - - internal IInstallationService InstallationService { get; } - - internal IServerConnectionData ServerConnectionData { get; } - - internal IJsonSerializer JsonSerializer { get; } - - /// - /// Private constructor for composition of queries. A source query is required, - /// but the remaining values can be null if they won't be changed in this - /// composition. - /// - internal MoralisQuery(MoralisQuery source, IDictionary where = null, IEnumerable replacementOrderBy = null, IEnumerable thenBy = null, int? skip = null, int? limit = null, IEnumerable includes = null, IEnumerable selectedKeys = null, string redirectClassNameForKey = null) - { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - - QueryService = source.QueryService; - SessionToken = source.SessionToken; - ClassName = source.ClassName; - Filters = source.Filters; - Orderings = replacementOrderBy is null ? source.Orderings : new ReadOnlyCollection(replacementOrderBy.ToList()); - InstallationService = source.InstallationService; - ServerConnectionData = source.ServerConnectionData; - JsonSerializer = source.JsonSerializer; - - SkipAmount = skip is null ? source.SkipAmount : (source.SkipAmount != null ? source.SkipAmount : 0) + skip; - LimitAmount = limit != null ? limit : source.LimitAmount; - Includes = source.Includes; - KeySelections = source.KeySelections; - RedirectClassNameForKey = redirectClassNameForKey != null ? redirectClassNameForKey : source.RedirectClassNameForKey; - - if (thenBy is { }) - { - List newOrderBy = new List(Orderings != null ? Orderings : throw new ArgumentException("You must call OrderBy before calling ThenBy.")); - - newOrderBy.AddRange(thenBy); - Orderings = new ReadOnlyCollection(newOrderBy); - } - - // Remove duplicates. - - if (Orderings is { }) - { - Orderings = new ReadOnlyCollection(new HashSet(Orderings).ToList()); - } - - if (where is { }) - { - Filters = new Dictionary(MergeWhereClauses(where)); - } - else - { - Filters = new Dictionary(); - } - - if (includes is { }) - { - Includes = new ReadOnlyCollection(MergeIncludes(includes).ToList()); - } - - if (selectedKeys is { }) - { - KeySelections = new ReadOnlyCollection(MergeSelectedKeys(selectedKeys).ToList()); - } - } - - HashSet MergeIncludes(IEnumerable includes) - { - if (Includes is null) - { - return new HashSet(includes); - } - - HashSet newIncludes = new HashSet(Includes); - - foreach (string item in includes) - { - newIncludes.Add(item); - } - - return newIncludes; - } - - HashSet MergeSelectedKeys(IEnumerable selectedKeys) - { - return new HashSet((KeySelections != null ? KeySelections : Enumerable.Empty()).Concat(selectedKeys)); - } - - IDictionary MergeWhereClauses(IDictionary where) - { - if (Filters is null) - { - return where; - } - - Dictionary newWhere = new Dictionary(Filters); - foreach (KeyValuePair pair in where) - { - if (newWhere.ContainsKey(pair.Key)) - { - if (!(newWhere[pair.Key] is IDictionary oldCondition) || !(pair.Value is IDictionary condition)) - { - throw new ArgumentException("More than one where clause for the given key provided."); - } - - Dictionary newCondition = new Dictionary(oldCondition); - foreach (KeyValuePair conditionPair in condition) - { - if (newCondition.ContainsKey(conditionPair.Key)) - { - throw new ArgumentException("More than one condition for the given key provided."); - } - - newCondition[conditionPair.Key] = conditionPair.Value; - } - - newWhere[pair.Key] = newCondition; - } - else - { - newWhere[pair.Key] = pair.Value; - } - } - return newWhere; - } - - /// - /// Constructs a query based upon the MoralisObject subclass used as the generic parameter for the MoralisQuery. - /// - public MoralisQuery(IQueryService queryService, IInstallationService installationService, IServerConnectionData connectionData, IJsonSerializer jsonSerializer, string sessionToken) : this(queryService, installationService, connectionData, jsonSerializer, sessionToken, typeof(T).Name) { } - - /// - /// Constructs a query. A default query with no further parameters will retrieve - /// all s of the provided class. - /// - /// The name of the class to retrieve MoralisObjects for. - public MoralisQuery(IQueryService queryService, IInstallationService installationService, IServerConnectionData connectionData, IJsonSerializer jsonSerializer, string sessionToken, string className) => (ClassName, QueryService, InstallationService, ServerConnectionData, SessionToken, JsonSerializer) = (className != null ? className : throw new ArgumentNullException(nameof(className), "Must specify a MoralisObject class name when creating a MoralisQuery."), queryService, installationService, connectionData, sessionToken, jsonSerializer); - - #region Order By - - /// - /// Sorts the results in ascending order by the given key. - /// This will override any existing ordering for the query. - /// - /// The key to order by. - /// A new query with the additional constraint. - public MoralisQuery OrderBy(string key) => new MoralisQuery(this, replacementOrderBy: new List { key }); - - /// - /// Sorts the results in descending order by the given key. - /// This will override any existing ordering for the query. - /// - /// The key to order by. - /// A new query with the additional constraint. - public MoralisQuery OrderByDescending(string key) => new MoralisQuery(this, replacementOrderBy: new List { "-" + key }); - - /// - /// Sorts the results in ascending order by the given key, after previous - /// ordering has been applied. - /// - /// This method can only be called if there is already an - /// or - /// on this query. - /// - /// The key to order by. - /// A new query with the additional constraint. - public MoralisQuery ThenBy(string key) => new MoralisQuery(this, thenBy: new List { key }); - - /// - /// Sorts the results in descending order by the given key, after previous - /// ordering has been applied. - /// - /// This method can only be called if there is already an - /// or on this query. - /// - /// The key to order by. - /// A new query with the additional constraint. - public MoralisQuery ThenByDescending(string key) => new MoralisQuery(this, thenBy: new List { "-" + key }); - - #endregion - - /// - /// Include nested MoralisObjects for the provided key. You can use dot notation - /// to specify which fields in the included objects should also be fetched. - /// - /// The key that should be included. - /// A new query with the additional constraint. - public MoralisQuery Include(string key) => new MoralisQuery(this, includes: new List { key }); - - /// - /// Restrict the fields of returned MoralisObjects to only include the provided key. - /// If this is called multiple times, then all of the keys specified in each of - /// the calls will be included. - /// - /// The key that should be included. - /// A new query with the additional constraint. - public MoralisQuery Select(string key) => new MoralisQuery(this, selectedKeys: new List { key }); - - /// - /// Skips a number of results before returning. This is useful for pagination - /// of large queries. Chaining multiple skips together will cause more results - /// to be skipped. - /// - /// The number of results to skip. - /// A new query with the additional constraint. - public MoralisQuery Skip(int count) => new MoralisQuery(this, skip: count); - - /// - /// Controls the maximum number of results that are returned. Setting a negative - /// limit denotes retrieval without a limit. Chaining multiple limits - /// results in the last limit specified being used. The default limit is - /// 100, with a maximum of 1000 results being returned at a time. - /// - /// The maximum number of results to return. - /// A new query with the additional constraint. - public MoralisQuery Limit(int count) => new MoralisQuery(this, limit: count); - - internal MoralisQuery RedirectClassName(string key) => new MoralisQuery(this, redirectClassNameForKey: key); - - #region Where - - /// - /// Adds a constraint to the query that requires a particular key's value to be - /// contained in the provided list of values. - /// - /// The key to check. - /// The values that will match. - /// A new query with the additional constraint. - public MoralisQuery WhereContainedIn(string key, IEnumerable values) => new MoralisQuery(this, where: new Dictionary { { key, new Dictionary { { "$in", values.ToList() } } } }); - - /// - /// Add a constraint to the querey that requires a particular key's value to be - /// a list containing all of the elements in the provided list of values. - /// - /// The key to check. - /// The values that will match. - /// A new query with the additional constraint. - public MoralisQuery WhereContainsAll(string key, IEnumerable values) => new MoralisQuery(this, where: new Dictionary { { key, new Dictionary { { "$all", values.ToList() } } } }); - - /// - /// Adds a constraint for finding string values that contain a provided string. - /// This will be slow for large data sets. - /// - /// The key that the string to match is stored in. - /// The substring that the value must contain. - /// A new query with the additional constraint. - public MoralisQuery WhereContains(string key, string substring) => new MoralisQuery(this, where: new Dictionary { { key, new Dictionary { { "$regex", RegexQuote(substring) } } } }); - - /// - /// Adds a constraint for finding objects that do not contain a given key. - /// - /// The key that should not exist. - /// A new query with the additional constraint. - public MoralisQuery WhereDoesNotExist(string key) => new MoralisQuery(this, where: new Dictionary { { key, new Dictionary { { "$exists", false } } } }); - - /// - /// Adds a constraint to the query that requires that a particular key's value - /// does not match another MoralisQuery. This only works on keys whose values are - /// MoralisObjects or lists of MoralisObjects. - /// - /// The key to check. - /// The query that the value should not match. - /// A new query with the additional constraint. - public MoralisQuery WhereDoesNotMatchQuery(string key, MoralisQuery query) where TOther : MoralisObject => new MoralisQuery(this, where: new Dictionary { { key, new Dictionary { { "$notInQuery", query.BuildParameters(true) } } } }); - - /// - /// Adds a constraint for finding string values that end with a provided string. - /// This will be slow for large data sets. - /// - /// The key that the string to match is stored in. - /// The substring that the value must end with. - /// A new query with the additional constraint. - public MoralisQuery WhereEndsWith(string key, string suffix) => new MoralisQuery(this, where: new Dictionary { { key, new Dictionary { { "$regex", RegexQuote(suffix) + "$" } } } }); - - /// - /// Adds a constraint to the query that requires a particular key's value to be - /// equal to the provided value. - /// - /// The key to check. - /// The value that the MoralisObject must contain. - /// A new query with the additional constraint. - public MoralisQuery WhereEqualTo(string key, object value) => new MoralisQuery(this, where: new Dictionary { { key, value } }); - - /// - /// Adds a constraint for finding objects that contain a given key. - /// - /// The key that should exist. - /// A new query with the additional constraint. - public MoralisQuery WhereExists(string key) => new MoralisQuery(this, where: new Dictionary { { key, new Dictionary { { "$exists", true } } } }); - - /// - /// Adds a constraint to the query that requires a particular key's value to be - /// greater than the provided value. - /// - /// The key to check. - /// The value that provides a lower bound. - /// A new query with the additional constraint. - public MoralisQuery WhereGreaterThan(string key, object value) => new MoralisQuery(this, where: new Dictionary { { key, new Dictionary { { "$gt", value } } } }); - - /// - /// Adds a constraint to the query that requires a particular key's value to be - /// greater or equal to than the provided value. - /// - /// The key to check. - /// The value that provides a lower bound. - /// A new query with the additional constraint. - public MoralisQuery WhereGreaterThanOrEqualTo(string key, object value) => new MoralisQuery(this, where: new Dictionary { { key, new Dictionary { { "$gte", value } } } }); - - /// - /// Adds a constraint to the query that requires a particular key's value to be - /// less than the provided value. - /// - /// The key to check. - /// The value that provides an upper bound. - /// A new query with the additional constraint. - public MoralisQuery WhereLessThan(string key, object value) => new MoralisQuery(this, where: new Dictionary { { key, new Dictionary { { "$lt", value } } } }); - - /// - /// Adds a constraint to the query that requires a particular key's value to be - /// less than or equal to the provided value. - /// - /// The key to check. - /// The value that provides a lower bound. - /// A new query with the additional constraint. - public MoralisQuery WhereLessThanOrEqualTo(string key, object value) => new MoralisQuery(this, where: new Dictionary { { key, new Dictionary { { "$lte", value } } } }); - - /// - /// Adds a regular expression constraint for finding string values that match the provided - /// regular expression. This may be slow for large data sets. - /// - /// The key that the string to match is stored in. - /// The regular expression pattern to match. The Regex must - /// have the options flag set. - /// Any of the following supported PCRE modifiers: - /// i - Case insensitive search - /// m Search across multiple lines of input - /// A new query with the additional constraint. - public MoralisQuery WhereMatches(string key, Regex regex, string modifiers) => !regex.Options.HasFlag(RegexOptions.ECMAScript) ? throw new ArgumentException("Only ECMAScript-compatible regexes are supported. Please use the ECMAScript RegexOptions flag when creating your regex.") : new MoralisQuery(this, where: new Dictionary { { key, EncodeRegex(regex, modifiers) } }); - - /// - /// Adds a regular expression constraint for finding string values that match the provided - /// regular expression. This may be slow for large data sets. - /// - /// The key that the string to match is stored in. - /// The regular expression pattern to match. The Regex must - /// have the options flag set. - /// A new query with the additional constraint. - public MoralisQuery WhereMatches(string key, Regex regex) => WhereMatches(key, regex, null); - - /// - /// Adds a regular expression constraint for finding string values that match the provided - /// regular expression. This may be slow for large data sets. - /// - /// The key that the string to match is stored in. - /// The PCRE regular expression pattern to match. - /// Any of the following supported PCRE modifiers: - /// i - Case insensitive search - /// m Search across multiple lines of input - /// A new query with the additional constraint. - public MoralisQuery WhereMatches(string key, string pattern, string modifiers = null) => WhereMatches(key, new Regex(pattern, RegexOptions.ECMAScript), modifiers); - - /// - /// Adds a regular expression constraint for finding string values that match the provided - /// regular expression. This may be slow for large data sets. - /// - /// The key that the string to match is stored in. - /// The PCRE regular expression pattern to match. - /// A new query with the additional constraint. - public MoralisQuery WhereMatches(string key, string pattern) => WhereMatches(key, pattern, null); - - /// - /// Adds a constraint to the query that requires a particular key's value - /// to match a value for a key in the results of another MoralisQuery. - /// - /// The key whose value is being checked. - /// The key in the objects from the subquery to look in. - /// The subquery to run - /// A new query with the additional constraint. - public MoralisQuery WhereMatchesKeyInQuery(string key, string keyInQuery, MoralisQuery query) where TOther : MoralisObject => new MoralisQuery(this, where: new Dictionary - { - [key] = new Dictionary - { - ["$select"] = new Dictionary - { - [nameof(query)] = query.BuildParameters(true), - [nameof(key)] = keyInQuery - } - } - }); - - /// - /// Adds a constraint to the query that requires a particular key's value - /// does not match any value for a key in the results of another MoralisQuery. - /// - /// The key whose value is being checked. - /// The key in the objects from the subquery to look in. - /// The subquery to run - /// A new query with the additional constraint. - public MoralisQuery WhereDoesNotMatchesKeyInQuery(string key, string keyInQuery, MoralisQuery query) where TOther : MoralisObject => new MoralisQuery(this, where: new Dictionary - { - [key] = new Dictionary - { - ["$dontSelect"] = new Dictionary - { - [nameof(query)] = query.BuildParameters(true), - [nameof(key)] = keyInQuery - } - } - }); - - /// - /// Adds a constraint to the query that requires that a particular key's value - /// matches another MoralisQuery. This only works on keys whose values are - /// MoralisObjects or lists of MoralisObjects. - /// - /// The key to check. - /// The query that the value should match. - /// A new query with the additional constraint. - public MoralisQuery WhereMatchesQuery(string key, MoralisQuery query) where TOther : MoralisObject => new MoralisQuery(this, where: new Dictionary - { - [key] = new Dictionary - { - ["$inQuery"] = query.BuildParameters(true) - } - }); - - /// - /// Adds a proximity-based constraint for finding objects with keys whose GeoPoint - /// values are near the given point. - /// - /// The key that the MoralisGeoPoint is stored in. - /// The reference MoralisGeoPoint. - /// A new query with the additional constraint. - public MoralisQuery WhereNear(string key, MoralisGeoPoint point) => new MoralisQuery(this, where: new Dictionary - { - [key] = new Dictionary - { - ["$nearSphere"] = point - } - }); - - /// - /// Adds a constraint to the query that requires a particular key's value to be - /// contained in the provided list of values. - /// - /// The key to check. - /// The values that will match. - /// A new query with the additional constraint. - public MoralisQuery WhereNotContainedIn(string key, IEnumerable values) => new MoralisQuery(this, where: new Dictionary - { - [key] = new Dictionary - { - ["$nin"] = values.ToList() - } - }); - - /// - /// Adds a constraint to the query that requires a particular key's value not - /// to be equal to the provided value. - /// - /// The key to check. - /// The value that that must not be equalled. - /// A new query with the additional constraint. - public MoralisQuery WhereNotEqualTo(string key, object value) => new MoralisQuery(this, where: new Dictionary - { - [key] = new Dictionary - { - ["$ne"] = value - } - }); - - /// - /// Adds a constraint for finding string values that start with the provided string. - /// This query will use the backend index, so it will be fast even with large data sets. - /// - /// The key that the string to match is stored in. - /// The substring that the value must start with. - /// A new query with the additional constraint. - public MoralisQuery WhereStartsWith(string key, string suffix) => new MoralisQuery(this, where: new Dictionary - { - [key] = new Dictionary - { - ["$regex"] = $"^{RegexQuote(suffix)}" - } - }); - - /// - /// Add a constraint to the query that requires a particular key's coordinates to be - /// contained within a given rectangular geographic bounding box. - /// - /// The key to be constrained. - /// The lower-left inclusive corner of the box. - /// The upper-right inclusive corner of the box. - /// A new query with the additional constraint. - public MoralisQuery WhereWithinGeoBox(string key, MoralisGeoPoint southwest, MoralisGeoPoint northeast) => new MoralisQuery(this, where: new Dictionary - { - [key] = new Dictionary - { - ["$within"] = new Dictionary - { - ["$box"] = new[] - { - southwest, - northeast - } - } - } - }); - - /// - /// Adds a proximity-based constraint for finding objects with keys whose GeoPoint - /// values are near the given point and within the maximum distance given. - /// - /// The key that the MoralisGeoPoint is stored in. - /// The reference MoralisGeoPoint. - /// The maximum distance (in radians) of results to return. - /// A new query with the additional constraint. - public MoralisQuery WhereWithinDistance(string key, MoralisGeoPoint point, MoralisGeoDistance maxDistance) => new MoralisQuery(WhereNear(key, point), where: new Dictionary - { - [key] = new Dictionary - { - ["$maxDistance"] = maxDistance.Radians - } - }); - - internal MoralisQuery WhereRelatedTo(MoralisObject parent, string key) => new MoralisQuery(this, where: new Dictionary - { - ["$relatedTo"] = new Dictionary - { - ["object"] = parent, - [nameof(key)] = key - } - }); - - #endregion - - /// - /// Executes an aggregate query and returns aggregate results - /// - /// The list of MoralisObjects that match this query. - public Task> AggregateAsync() => AggregateAsync(CancellationToken.None); - - /// - /// Executes an aggregate query and returns aggregate results - /// - /// The cancellation token. - /// The list of MoralisObjects that match this query. - public async Task> AggregateAsync(CancellationToken cancellationToken) - { - EnsureNotInstallationQuery(); - IEnumerable aggResp = await QueryService.AggregateAsync(this, SessionToken, cancellationToken); - - foreach (T i in aggResp) - { - i.ObjectService = this.QueryService.ObjectService; - i.sessionToken = this.SessionToken; - } - - return aggResp; - } - - /// - /// Retrieves a list of MoralisObjects that satisfy this query from Moralis. - /// - /// The list of MoralisObjects that match this query. - public Task> FindAsync() => FindAsync(CancellationToken.None); - - /// - /// Retrieves a list of MoralisObjects that satisfy this query from Moralis. - /// - /// The cancellation token. - /// The list of MoralisObjects that match this query. - public async Task> FindAsync(CancellationToken cancellationToken) - { - EnsureNotInstallationQuery(); - IEnumerable items = await QueryService.FindAsync(this, SessionToken, cancellationToken); - - foreach (T i in items) - { - i.ObjectService = this.QueryService.ObjectService; - i.sessionToken = this.SessionToken; - } - - return items; - } - - /// - /// Retrieves a list of distinct MoralisObjects that satisfy this query from Moralis. - /// - /// The list of MoralisObjects that match this query. - public async Task> DistinctAsync() => await DistinctAsync(CancellationToken.None); - - /// - /// Retrieves a list of distinct MoralisObjects that satisfy this query from Moralis. - /// - /// The cancellation token. - /// The list of MoralisObjects that match this query. - public async Task> DistinctAsync(CancellationToken cancellationToken) - { - EnsureNotInstallationQuery(); - IEnumerable items = await QueryService.DistinctAsync(this, SessionToken, cancellationToken); - - foreach (T i in items) - { - i.ObjectService = this.QueryService.ObjectService; - i.sessionToken = this.SessionToken; - } - - return items; - } - - /// - /// Retrieves at most one MoralisObject that satisfies this query. - /// - /// A single MoralisObject that satisfies this query, or else null. - public async Task FirstOrDefaultAsync() => await FirstOrDefaultAsync(CancellationToken.None); - - /// - /// Retrieves at most one MoralisObject that satisfies this query. - /// - /// The cancellation token. - /// A single MoralisObject that satisfies this query, or else null. - public async Task FirstOrDefaultAsync(CancellationToken cancellationToken) - { - EnsureNotInstallationQuery(); - T item = await QueryService.FirstAsync(this, SessionToken, cancellationToken); - - item.ObjectService = this.QueryService.ObjectService; - item.sessionToken = this.SessionToken; - - return item; - } - - /// - /// Retrieves at most one MoralisObject that satisfies this query. - /// - /// A single MoralisObject that satisfies this query. - /// If no results match the query. - public async Task FirstAsync() => await FirstAsync(CancellationToken.None); - - /// - /// Retrieves at most one MoralisObject that satisfies this query. - /// - /// The cancellation token. - /// A single MoralisObject that satisfies this query. - /// If no results match the query. - public async Task FirstAsync(CancellationToken cancellationToken) => await FirstOrDefaultAsync(cancellationToken); - - /// - /// Counts the number of objects that match this query. - /// - /// The number of objects that match this query. - public async Task CountAsync() => await CountAsync(CancellationToken.None); - - /// - /// Counts the number of objects that match this query. - /// - /// The cancellation token. - /// The number of objects that match this query. - public async Task CountAsync(CancellationToken cancellationToken) - { - EnsureNotInstallationQuery(); - return await QueryService.CountAsync(this, SessionToken, cancellationToken); - } - - /// - /// Constructs a MoralisObject whose id is already known by fetching data - /// from the server. - /// - /// ObjectId of the MoralisObject to fetch. - /// The MoralisObject for the given objectId. - public async Task GetAsync(string objectId) => await GetAsync(objectId, CancellationToken.None); - - /// - /// Constructs a MoralisObject whose id is already known by fetching data - /// from the server. - /// - /// ObjectId of the MoralisObject to fetch. - /// The cancellation token. - /// The MoralisObject for the given objectId. - public async Task GetAsync(string objectId, CancellationToken cancellationToken) - { - MoralisQuery singleItemQuery = new MoralisQuery(QueryService, InstallationService, ServerConnectionData, JsonSerializer, SessionToken, ClassName).WhereEqualTo(nameof(objectId), objectId); - singleItemQuery = new MoralisQuery(singleItemQuery, includes: Includes, selectedKeys: KeySelections, limit: 1); - IEnumerable findResp = await singleItemQuery.FindAsync(cancellationToken); - T result = findResp.FirstOrDefault(); - - if (result == null) - { - throw new MoralisFailureException(MoralisFailureException.ErrorCode.ObjectNotFound, "Object with the given objectId not found."); - } - - result.ObjectService = this.QueryService.ObjectService; - result.sessionToken = this.SessionToken; - - return result; - } - - internal object GetConstraint(string key) => Filters?.GetOrDefault(key, null); - - internal IDictionary BuildParameters(bool includeClassName = false) - { - Dictionary result = new Dictionary(); - - if (Filters != null) - result["where"] = JsonSerializer.Serialize(Filters); - else - result["where"] = new Dictionary(); - - if (Orderings != null) - result["order"] = String.Join(",", Orderings.ToArray()); - if (SkipAmount != null) - result["skip"] = SkipAmount.Value; - if (LimitAmount != null) - result["limit"] = LimitAmount.Value; - if (Includes != null) - result["include"] = String.Join(",", Includes.ToArray()); - if (KeySelections != null) - result["keys"] = String.Join(",", KeySelections.ToArray()); - if (includeClassName) - result["className"] = ClassName; - if (RedirectClassNameForKey != null) - result["redirectClassNameForKey"] = RedirectClassNameForKey; - return result; - } - - string RegexQuote(string input) => "\\Q" + input.Replace("\\E", "\\E\\\\E\\Q") + "\\E"; - - string GetRegexOptions(Regex regex, string modifiers) - { - string result = modifiers != null ? modifiers : ""; - if (regex.Options.HasFlag(RegexOptions.IgnoreCase) && !modifiers.Contains("i")) - result += "i"; - if (regex.Options.HasFlag(RegexOptions.Multiline) && !modifiers.Contains("m")) - result += "m"; - return result; - } - - IDictionary EncodeRegex(Regex regex, string modifiers) - { - string options = GetRegexOptions(regex, modifiers); - Dictionary dict = new Dictionary { ["$regex"] = regex.ToString() }; - - if (!String.IsNullOrEmpty(options)) - { - dict["$options"] = options; - } - - return dict; - } - - void EnsureNotInstallationQuery() - { - // The MoralisInstallation class is not accessible from this project; using string literal. - - if (ClassName.Equals("_Installation")) - { - throw new InvalidOperationException("Cannot directly query the Installation class."); - } - } - - /// - /// Determines whether the specified object is equal to the current object. - /// - /// The object to compare with the current object. - /// true if the specified object is equal to the current object; otherwise, false - public override bool Equals(object obj) => obj == null || !(obj is MoralisQuery other) ? false : Equals(ClassName, other.ClassName) && Filters.CollectionsEqual(other.Filters) && Orderings.CollectionsEqual(other.Orderings) && Includes.CollectionsEqual(other.Includes) && KeySelections.CollectionsEqual(other.KeySelections) && Equals(SkipAmount, other.SkipAmount) && Equals(LimitAmount, other.LimitAmount); - - /// - /// Serves as the default hash function. - /// - /// A hash code for the current object. - public override int GetHashCode() => - this.GetHashCode(); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Queries/MutableObjectState.cs b/MoralisDotNet/Moralis/Platform/Queries/MutableObjectState.cs deleted file mode 100644 index cb34ac0..0000000 --- a/MoralisDotNet/Moralis/Platform/Queries/MutableObjectState.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Operations; - -namespace Moralis.Platform.Queries -{ - public class MutableObjectState : IObjectState - { - public bool IsNew { get; set; } - public IDictionary ServerData { get; set; } = new Dictionary { }; - - public object this[string key] => ServerData[key]; - - public bool ContainsKey(string key) => ServerData.ContainsKey(key); - - public void Apply(IDictionary operationSet) - { - // Apply operationSet - foreach (KeyValuePair pair in operationSet) - { - ServerData.TryGetValue(pair.Key, out object oldValue); - object newValue = pair.Value.Apply(oldValue, pair.Key); - if (newValue != MoralisDeleteOperation.Token) - ServerData[pair.Key] = newValue; - else - ServerData.Remove(pair.Key); - } - } - - public void Apply(IObjectState other) - { - IsNew = other.IsNew; - - foreach (KeyValuePair pair in other) - ServerData[pair.Key] = pair.Value; - } - - public IObjectState MutatedClone(Action func) - { - MutableObjectState clone = MutableClone(); - func(clone); - return clone; - } - - protected virtual MutableObjectState MutableClone() => new MutableObjectState - { - IsNew = IsNew, - ServerData = this.ToDictionary(t => t.Key, t => t.Value) - }; - - IEnumerator> IEnumerable>.GetEnumerator() => ServerData.GetEnumerator(); - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => ((IEnumerable>)this).GetEnumerator(); - - } -} diff --git a/MoralisDotNet/Moralis/Platform/Queries/QueryExtensions.cs b/MoralisDotNet/Moralis/Platform/Queries/QueryExtensions.cs deleted file mode 100644 index 70d3236..0000000 --- a/MoralisDotNet/Moralis/Platform/Queries/QueryExtensions.cs +++ /dev/null @@ -1,25 +0,0 @@ -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Services.ClientServices; - -namespace Moralis.Platform.Queries -{ - public static class QueryExtensions - { - public static MoralisLiveQueryClient Subscribe(this MoralisQuery query, ILiveQueryCallbacks callbacks = null) where T : MoralisObject - { - if (!(callbacks is { })) - { - callbacks = new LiveQueryCallbacks(); - } - - string sessionToken = query.SessionToken; - string installationId = query.InstallationService.InstallationId?.ToString(); - - MoralisLiveQueryClient subscription = - MoralisLiveQueryManager.CreateSubscription(query, query.ServerConnectionData, callbacks, query.JsonSerializer, sessionToken, installationId); - - return subscription; - } - } -} \ No newline at end of file diff --git a/MoralisDotNet/Moralis/Platform/Queries/QueryServiceExtensions.cs b/MoralisDotNet/Moralis/Platform/Queries/QueryServiceExtensions.cs deleted file mode 100644 index 2912282..0000000 --- a/MoralisDotNet/Moralis/Platform/Queries/QueryServiceExtensions.cs +++ /dev/null @@ -1,169 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Queries -{ - public static class QueryServiceExtensions - { - public static MoralisQuery GetQuery(this IServiceHub serviceHub) where T : MoralisObject where TUser : MoralisUser => new MoralisQuery(serviceHub.QueryService, serviceHub.InstallationService, serviceHub.ServerConnectionData, serviceHub.JsonSerializer, serviceHub.CurrentUserService.CurrentUser.sessionToken); - - /// - /// Constructs a query that is the and of the given queries. - /// - /// The type of MoralisObject being queried. - /// - /// An initial query to 'and' with additional queries. - /// The list of MoralisQueries to 'and' together. - /// A query that is the and of the given queries. - public static MoralisQuery ConstructAndQuery(this IServiceHub serviceHub, MoralisQuery source, params MoralisQuery[] queries) where T : MoralisObject where TUser : MoralisUser => serviceHub.ConstructAndQuery(queries.Concat(new[] { source })); - - // ALTERNATE NAME: BuildOrQuery - - /// - /// Constructs a query that is the or of the given queries. - /// - /// The type of MoralisObject being queried. - /// An initial query to 'or' with additional queries. - /// The list of MoralisQueries to 'or' together. - /// A query that is the or of the given queries. - public static MoralisQuery ConstructOrQuery(this IServiceHub serviceHub, MoralisQuery source, params MoralisQuery[] queries) where T : MoralisObject where TUser : MoralisUser => serviceHub.ConstructOrQuery(queries.Concat(new[] { source })); - public static MoralisQuery ConstructNorQuery(this IServiceHub serviceHub, MoralisQuery source, params MoralisQuery[] queries) where T : MoralisObject where TUser : MoralisUser => serviceHub.ConstructNorQuery(queries.Concat(new[] { source })); - - /// - /// Construct a query that is the and of two or more queries. - /// - /// - /// - /// The list of MoralisQueries to 'and' together. - /// A MoralisQquery that is the 'and' of the passed in queries. - public static MoralisQuery ConstructAndQuery(this IServiceHub serviceHub, IEnumerable> queries) where T : MoralisObject where TUser : MoralisUser - { - string className = default; - List> andValue = new List> { }; - - // We need to cast it to non-generic IEnumerable because of AOT-limitation - - IEnumerable nonGenericQueries = queries; - foreach (object obj in nonGenericQueries) - { - MoralisQuery query = obj as MoralisQuery; - - if (className is { } && query.ClassName != className) - { - throw new ArgumentException("All of the queries in an and query must be on the same class."); - } - - className = query.ClassName; - IDictionary parameters = query.BuildParameters(); - - if (parameters.Count == 0) - { - continue; - } - - if (!parameters.TryGetValue("where", out object where) || parameters.Count > 1) - { - throw new ArgumentException("None of the queries in an and query can have non-filtering clauses"); - } - - //orValue.Add(where as IDictionary); - - andValue.Add(serviceHub.JsonSerializer.Deserialize>(where.ToString())); - //andValue.Add(JsonConvert.DeserializeObject>(where.ToString())); - } - - return new MoralisQuery(new MoralisQuery(serviceHub.QueryService, serviceHub.InstallationService, serviceHub.ServerConnectionData, serviceHub.JsonSerializer, serviceHub.CurrentUserService.CurrentUser?.sessionToken, className), where: new Dictionary { ["$and"] = andValue }); - } - - /// - /// Constructs a query that is the or of the given queries. - /// - /// The list of MoralisQueries to 'or' together. - /// A MoralisQquery that is the 'or' of the passed in queries. - public static MoralisQuery ConstructOrQuery(this IServiceHub serviceHub, IEnumerable> queries) where T : MoralisObject where TUser : MoralisUser - { - string className = default; - List> orValue = new List> { }; - - // We need to cast it to non-generic IEnumerable because of AOT-limitation - - IEnumerable nonGenericQueries = queries; - foreach (object obj in nonGenericQueries) - { - MoralisQuery query = obj as MoralisQuery; - - if (className is { } && query.ClassName != className) - { - throw new ArgumentException("All of the queries in an or query must be on the same class."); - } - - className = query.ClassName; - IDictionary parameters = query.BuildParameters(); - - if (parameters.Count == 0) - { - continue; - } - - if (!parameters.TryGetValue("where", out object where) || parameters.Count > 1) - { - throw new ArgumentException("None of the queries in an or query can have non-filtering clauses"); - } - - //orValue.Add(where as IDictionary); - orValue.Add(serviceHub.JsonSerializer.Deserialize>(where.ToString())); - //orValue.Add(JsonConvert.DeserializeObject>(where.ToString())); - } - - return new MoralisQuery(new MoralisQuery(serviceHub.QueryService, serviceHub.InstallationService, serviceHub.ServerConnectionData, serviceHub.JsonSerializer, serviceHub.CurrentUserService.CurrentUser.sessionToken, className), where: new Dictionary { ["$or"] = orValue }); - } - - /// - /// Construct a query that is the nor of two queries. - /// - /// - /// - /// The list of MoralisQueries to 'nor' together. - /// A MoralisQquery that is the 'nor' of the passed in queries. - public static MoralisQuery ConstructNorQuery(this IServiceHub serviceHub, IEnumerable> queries) where T : MoralisObject where TUser : MoralisUser - { - string className = default; - List> norValue = new List> { }; - - // We need to cast it to non-generic IEnumerable because of AOT-limitation - - IEnumerable nonGenericQueries = queries; - foreach (object obj in nonGenericQueries) - { - MoralisQuery query = obj as MoralisQuery; - - if (className is { } && query.ClassName != className) - { - throw new ArgumentException("All of the queries in an nor query must be on the same class."); - } - - className = query.ClassName; - IDictionary parameters = query.BuildParameters(); - - if (parameters.Count == 0) - { - continue; - } - - if (!parameters.TryGetValue("where", out object where) || parameters.Count > 1) - { - throw new ArgumentException("None of the queries in an or query can have non-filtering clauses"); - } - - norValue.Add(serviceHub.JsonSerializer.Deserialize>(where.ToString())); - } - - return new MoralisQuery(new MoralisQuery(serviceHub.QueryService, serviceHub.InstallationService, serviceHub.ServerConnectionData, serviceHub.JsonSerializer, serviceHub.CurrentUserService.CurrentUser.sessionToken, className), where: new Dictionary { ["$nor"] = norValue }); - } - } - -} diff --git a/MoralisDotNet/Moralis/Platform/ResourceWrapper.cs b/MoralisDotNet/Moralis/Platform/ResourceWrapper.cs deleted file mode 100644 index 95a1342..0000000 --- a/MoralisDotNet/Moralis/Platform/ResourceWrapper.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Moralis.Platform -{ - public class ResourceWrapper - { - - /// - /// Looks up a localized string similar to Mutation of a file-backed cache is an asynchronous operation as the tracked file needs to be modified.. - /// - public static string FileBackedCacheSynchronousMutationNotSupportedMessage - { - get - { - return Resources.ResourceManager.GetString("FileBackedCacheSynchronousMutationNotSupportedMessage", Resources.Culture); - } - } - - /// - /// Looks up a localized string similar to Cannot perform file operations with in-memory cache controller.. - /// - public static string TransientCacheControllerDiskFileOperationNotSupportedMessage - { - get - { - return Resources.ResourceManager.GetString("TransientCacheControllerDiskFileOperationNotSupportedMessage", Resources.Culture); - } - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Resources.Designer.cs b/MoralisDotNet/Moralis/Platform/Resources.Designer.cs deleted file mode 100644 index 2bbbe22..0000000 --- a/MoralisDotNet/Moralis/Platform/Resources.Designer.cs +++ /dev/null @@ -1,81 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Moralis.Platform { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Moralis.Platform.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Mutation of a file-backed cache is an asynchronous operation as the tracked file needs to be modified.. - /// - internal static string FileBackedCacheSynchronousMutationNotSupportedMessage { - get { - return ResourceManager.GetString("FileBackedCacheSynchronousMutationNotSupportedMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Cannot perform file operations with in-memory cache controller.. - /// - internal static string TransientCacheControllerDiskFileOperationNotSupportedMessage { - get { - return ResourceManager.GetString("TransientCacheControllerDiskFileOperationNotSupportedMessage", resourceCulture); - } - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Resources.resx b/MoralisDotNet/Moralis/Platform/Resources.resx deleted file mode 100644 index 69ace47..0000000 --- a/MoralisDotNet/Moralis/Platform/Resources.resx +++ /dev/null @@ -1,126 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Mutation of a file-backed cache is an asynchronous operation as the tracked file needs to be modified. - - - Cannot perform file operations with in-memory cache controller. - - \ No newline at end of file diff --git a/MoralisDotNet/Moralis/Platform/Services/AbsoluteCacheLocationMutator.cs b/MoralisDotNet/Moralis/Platform/Services/AbsoluteCacheLocationMutator.cs deleted file mode 100644 index 1a03a07..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/AbsoluteCacheLocationMutator.cs +++ /dev/null @@ -1,37 +0,0 @@ -using Moralis.Platform.Services.Infrastructure; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Services -{ - /// - /// An implementation which changes the 's if available. - /// - public class AbsoluteCacheLocationMutator : IServiceHubMutator - { - /// - /// A custom absolute cache file path to be set on the active if it implements . - /// - public string CustomAbsoluteCacheFilePath { get; set; } - - /// - /// - /// - public bool Valid => CustomAbsoluteCacheFilePath is { }; - - /// - /// - /// - /// - /// - public void Mutate(ref IMutableServiceHub target, in IServiceHub composedHub) where TUser : MoralisUser - { - if ((target as IServiceHub).CacheService is IDiskFileCacheService { } diskFileCacheController) - { - diskFileCacheController.AbsoluteCacheFilePath = CustomAbsoluteCacheFilePath; - diskFileCacheController.RefreshPaths(); - } - } - } - -} diff --git a/MoralisDotNet/Moralis/Platform/Services/ClientServices/CommandRunnerExtensions.cs b/MoralisDotNet/Moralis/Platform/Services/ClientServices/CommandRunnerExtensions.cs deleted file mode 100644 index 2e9e833..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/ClientServices/CommandRunnerExtensions.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Text; -using System.Text.RegularExpressions; - -namespace Moralis.Platform.Services.ClientServices -{ - public static class CommandRunnerExtensions - { - public static string AdjustJsonForParseDate(this string json) - { - string adjusted = json; - - Regex r = new Regex("{\"__type\":\"Date\",\"iso\":(\"\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d\\.\\d+([+-][0-2]\\d:[0-5]\\d|Z)\")}"); - MatchCollection matches = r.Matches(json); - - // Use foreach-loop. - foreach (Match match in matches) - { - if (match.Groups.Count >= 2) - { - adjusted = adjusted.Replace(match.Groups[0].Value, match.Groups[1].Value); - } - } - - return adjusted; - } - - - public static string JsonInsertParseDate(this string json) - { - string adjusted = json; - - Regex r = new Regex("(\"\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d\\.\\d+([+-][0-2]\\d:[0-5]\\d|Z)\")"); - MatchCollection matches = r.Matches(json); - - // Use foreach-loop. - foreach (Match match in matches) - { - if (match.Groups.Count >= 1) - { - StringBuilder sb = new StringBuilder(); - sb.Append("{\"__type\":\"Date\",\"iso\":"); - sb.Append(match.Groups[0].Value); - sb.Append("}"); - - adjusted = adjusted.Replace(match.Groups[0].Value, sb.ToString()); - } - } - - return adjusted; - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Services/ClientServices/FileServiceExtensions.cs b/MoralisDotNet/Moralis/Platform/Services/ClientServices/FileServiceExtensions.cs deleted file mode 100644 index 0dc8066..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/ClientServices/FileServiceExtensions.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Threading; -using Moralis.Platform.Utilities; -using System.Threading.Tasks; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Services.ClientServices -{ - public static class FileServiceExtensions - { - /// - /// Saves the file to the Parse cloud. - /// - /// The cancellation token. - public static async Task SaveFileAsync(this IServiceHub serviceHub, MoralisFile file, CancellationToken cancellationToken = default) - { - await serviceHub.SaveFileAsync(file, default, cancellationToken); - } - - /// - /// Saves the file to the Parse cloud. - /// - /// The progress callback. - /// The cancellation token. - //public static Task SaveFileAsync(this IServiceHub serviceHub, MoralisFile file, IProgress progress, CancellationToken cancellationToken = default) => (file.TaskQueue.Enqueue(toAwait => serviceHub.FileService.SaveAsync(file.State, file.DataStream, serviceHub.GetCurrentSessionTokenAsync(), progress, cancellationToken), cancellationToken).OnSuccess(task => file.State = task.Result)); - public static async Task SaveFileAsync(this IServiceHub serviceHub, MoralisFile file, IProgress progress, CancellationToken cancellationToken = default) - { - string sessionToken = await serviceHub.GetCurrentSessionTokenAsync(); - - - MoralisFileState state = await serviceHub.FileService.SaveAsync(file.State, file.DataStream, sessionToken, progress, cancellationToken); - - file.State = state; - } - - /// - /// Saves the file to the Parse cloud. - /// - /// The cancellation token. - public static async Task SaveAsync(this MoralisFile file, IServiceHub serviceHub, CancellationToken cancellationToken = default) - { - await serviceHub.SaveFileAsync(file, cancellationToken); - } - - /// - /// Saves the file to the Parse cloud. - /// - /// The progress callback. - /// The cancellation token. - public static async Task SaveAsync(this MoralisFile file, IServiceHub serviceHub, IProgress progress, CancellationToken cancellationToken = default) - { - await serviceHub.SaveFileAsync(file, progress, cancellationToken); - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisCloudFunctionService.cs b/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisCloudFunctionService.cs deleted file mode 100644 index 5e7e021..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisCloudFunctionService.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading; -using Moralis.Platform.Utilities; -using System.Threading.Tasks; -using System.Net; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Services.Models; - -namespace Moralis.Platform.Services.ClientServices -{ - /// - /// This service enables an application to call Moralis Cloud Functions. - /// - public class MoralisCloudFunctionService : ICloudFunctionService - { - IMoralisCommandRunner CommandRunner { get; } - - IServerConnectionData ServerConnectionData { get; } - - IJsonSerializer JsonSerializer { get; } - - public MoralisCloudFunctionService(IMoralisCommandRunner commandRunner, IServerConnectionData serverConnectionData, IJsonSerializer jsonSerializer) => (CommandRunner, ServerConnectionData, JsonSerializer) = (commandRunner, serverConnectionData, jsonSerializer); - - /// - /// Calls Moralis cloud function specified by 'name'. - /// - /// Expected result type - /// Name of cloud function - /// Parameters that will be passed to the cloud function - /// current user's session token - /// Threading cancellation token - /// T - result of cloud function call. - public async Task CallFunctionAsync(string name, IDictionary parameters, string sessionToken, System.Threading.CancellationToken cancellationToken = default) - { - MoralisCommand command = new MoralisCommand($"server/functions/{Uri.EscapeDataString(name)}", method: "POST", sessionToken: sessionToken, data: parameters is { } && parameters.Count > 0 ? JsonSerializer.Serialize(parameters) : "{}"); - - Tuple cmdResult = await CommandRunner.RunCommandAsync(command, cancellationToken: cancellationToken); - - T resp = default; - - if ((int)cmdResult.Item1 < 400) - { - resp = (T)JsonSerializer.Deserialize(cmdResult.Item2); - } - - return resp; - - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisCommandRunner.cs b/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisCommandRunner.cs deleted file mode 100644 index 0a76805..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisCommandRunner.cs +++ /dev/null @@ -1,161 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net; -using System.Threading; -using Status = System.Net.HttpStatusCode; -using Moralis.Platform.Utilities; -using System.Threading.Tasks; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Exceptions; -using Moralis.Platform.Objects; -using Moralis.Platform.Services.Models; - -namespace Moralis.Platform.Services.ClientServices -{ - /// - /// The command runner for all SDK operations that need to interact with the targeted deployment of Moralis Server. - /// - public class MoralisCommandRunner : IMoralisCommandRunner where TUser : MoralisUser - { - IWebClient WebClient { get; } - - IInstallationService InstallationService { get; } - - IMetadataService MetadataService { get; } - - IServerConnectionData ServerConnectionData { get; } - - Lazy> UserService { get; } - - IWebClient GetWebClient() => WebClient; - - /// - /// Creates a new Moralis SDK command runner. - /// - /// The implementation instance to use. - /// The implementation instance to use. - public MoralisCommandRunner(IWebClient webClient, IInstallationService installationController, IMetadataService metadataController, IServerConnectionData serverConnectionData, Lazy> userController) - { - WebClient = webClient; - InstallationService = installationController; - MetadataService = metadataController; - ServerConnectionData = serverConnectionData; - UserService = userController; - - - } - - /// - /// Runs a specified . - /// - /// The to run. - /// An instance to push upload progress data to. - /// An instance to push download progress data to. - /// An asynchronous operation cancellation token that dictates if and when the operation should be cancelled. - /// Tuple - public async Task> RunCommandAsync(MoralisCommand command, IProgress uploadProgress = null, IProgress downloadProgress = null, CancellationToken cancellationToken = default) - { - MoralisCommand cmd = await PrepareCommand(command); - - Tuple cmdResult = await GetWebClient().ExecuteAsync(cmd, uploadProgress, downloadProgress, cancellationToken); - - cancellationToken.ThrowIfCancellationRequested(); - - string content = cmdResult.Item2; - int responseCode = (int)cmdResult.Item1; - - if (responseCode >= 500) - { - throw new MoralisFailureException(MoralisFailureException.ErrorCode.InternalServerError, cmdResult.Item2); - } - - // The Moralis server returns POCO saved dates as an object. Convert to ISO datetime string. - string adjustedData = cmdResult.Item2.AdjustJsonForParseDate(); - - // Remove Results wrapper. - if (adjustedData.StartsWith("{\"results\":")) - { - adjustedData = adjustedData.Substring(11, adjustedData.Length - 12); - } - else if (adjustedData.StartsWith("{\"result\":")) - { - adjustedData = adjustedData.Substring(10, adjustedData.Length - 11); - } - - Tuple newResponse = new Tuple(cmdResult.Item1, adjustedData); - - return newResponse; - } - - async Task PrepareCommand(MoralisCommand command) - { - MoralisCommand newCommand = new MoralisCommand(command) - { - Resource = ServerConnectionData.ServerURI - }; - - Guid? guid = await InstallationService.GetAsync(); - - lock (newCommand.Headers) - { - newCommand.Headers.Add(new KeyValuePair("X-Parse-Installation-Id", guid?.ToString())); - } - - lock (newCommand.Headers) - { - KeyValuePair appId = new KeyValuePair("X-Parse-Application-Id", ServerConnectionData.ApplicationID); - - if (!newCommand.Headers.Contains(appId)) - { - newCommand.Headers.Add(appId); - } - - KeyValuePair clientVersion = new KeyValuePair("X-Parse-Client-Version", MoralisService.Version.ToString()); - - if (!newCommand.Headers.Contains(clientVersion)) - { - newCommand.Headers.Add(clientVersion); - } - - if (ServerConnectionData.Headers != null) - { - foreach (KeyValuePair header in ServerConnectionData.Headers) - { - newCommand.Headers.Add(header); - } - } - - if (!String.IsNullOrEmpty(MetadataService.HostManifestData.Version)) - { - newCommand.Headers.Add(new KeyValuePair("X-Parse-App-Build-Version", MetadataService.HostManifestData.Version)); - } - - if (!String.IsNullOrEmpty(MetadataService.HostManifestData.ShortVersion)) - { - newCommand.Headers.Add(new KeyValuePair("X-Parse-App-Display-Version", MetadataService.HostManifestData.ShortVersion)); - } - - if (!String.IsNullOrEmpty(MetadataService.EnvironmentData.OSVersion)) - { - newCommand.Headers.Add(new KeyValuePair("X-Parse-OS-Version", MetadataService.EnvironmentData.OSVersion)); - } - - if (!String.IsNullOrEmpty(ServerConnectionData.MasterKey)) - { - newCommand.Headers.Add(new KeyValuePair("X-Parse-Master-Key", ServerConnectionData.MasterKey)); - } - else - { - newCommand.Headers.Add(new KeyValuePair("X-Parse-Windows-Key", ServerConnectionData.Key)); - } - - if (UserService.Value.RevocableSessionEnabled) - { - newCommand.Headers.Add(new KeyValuePair("X-Parse-Revocable-Session", "1")); - } - } - - return newCommand; - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisFileService.cs b/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisFileService.cs deleted file mode 100644 index 3d72c8d..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisFileService.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Threading; -using Moralis.Platform.Services.ClientServices; -using Moralis.Platform.Utilities; -using System.Threading.Tasks; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Exceptions; -using Moralis.Platform.Objects; -using Moralis.Platform.Services.Models; - -namespace Moralis.Platform.Services.ClientServices -{ - public class MoralisFileService : IFileService - { - IMoralisCommandRunner CommandRunner { get; } - - IJsonSerializer JsonSerializer { get; } - - public MoralisFileService(IMoralisCommandRunner commandRunner, IJsonSerializer jsonSerializer) => (CommandRunner, JsonSerializer) = (commandRunner, jsonSerializer); - - public async Task SaveAsync(MoralisFileState state, Stream dataStream, string sessionToken, IProgress progress, CancellationToken cancellationToken = default) - { - if (state.url != null) - return state; - - if (cancellationToken.IsCancellationRequested) - return await Task.FromCanceled(cancellationToken); - - long oldPosition = dataStream.Position; - - Tuple cmdResult = await CommandRunner.RunCommandAsync(new MoralisCommand($"server/files/{state.name}", method: "POST", sessionToken: sessionToken, contentType: state.mediatype, stream: dataStream), uploadProgress: progress, cancellationToken: cancellationToken); - - cancellationToken.ThrowIfCancellationRequested(); - MoralisFileState fileState = default; - - if (cmdResult.Item2 is { }) - { - fileState = JsonSerializer.Deserialize(cmdResult.Item2); - - if (String.IsNullOrWhiteSpace(fileState.name) || !(fileState.url is { })) - throw new MoralisFailureException(MoralisFailureException.ErrorCode.ScriptFailed, ""); - - fileState.mediatype = state.mediatype; - } - else - throw new MoralisFailureException(MoralisFailureException.ErrorCode.ScriptFailed, ""); - - // Rewind the stream on failure or cancellation (if possible). - if (dataStream.CanSeek) - dataStream.Seek(oldPosition, SeekOrigin.Begin); - - return fileState; - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisLiveQueryClient.cs b/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisLiveQueryClient.cs deleted file mode 100644 index ddd9350..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisLiveQueryClient.cs +++ /dev/null @@ -1,806 +0,0 @@ -#if UNITY_WEBGL -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using Moralis.Platform.Utilities; -using static Moralis.Platform.Exceptions.MoralisFailureException; -using System.Threading.Tasks; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Exceptions; -using Moralis.Platform.Objects; -using Moralis.Platform.Queries; -using Moralis.Platform.Queries.Live; - -namespace Moralis.Platform.Services.ClientServices -{ - /// - /// Represents a single Live Query subscription. - /// - /// - public class MoralisLiveQueryClient : ILiveQueryClient where T : MoralisObject - { - private bool disposedValue; - private Task subscriptTask; - - private CancellationTokenSource cancelSource = new CancellationTokenSource(); - private CancellationToken cancellationToken = CancellationToken.None; - private MoralisQuery targetQuery; - private SubscribableWebSocket liveQueryServerClient = default; - - /// - /// Standard constructor - /// - /// - /// - /// - /// - /// - public MoralisLiveQueryClient(MoralisQuery query, IServerConnectionData conncetionData, ILiveQueryCallbacks callbacks, string sessionToken = null, string installationId = null) - { - Initialize(query, conncetionData, callbacks, sessionToken, installationId); - - liveQueryServerClient = new SubscribableWebSocket(CreateSubscribeRequest(), ConncetionData, RequestId, InstallationId, sessionToken, query.JsonSerializer); - liveQueryServerClient.OnEventMessage += HandleEventMessage; - liveQueryServerClient.OnGeneralMessage += HandleGeneralMessage; - - ClientStatus = LiveQueryClientStatusTypes.New; - } - - /// - /// Constructor accepting SubscribableWebSocket to facilitate testing. - /// - /// - /// - /// - /// - /// - public MoralisLiveQueryClient(MoralisQuery query, IServerConnectionData conncetionData, ILiveQueryCallbacks callbacks, SubscribableWebSocket webSocket, string sessionToken = null, string installationId = null) - { - Initialize(query, conncetionData, callbacks, sessionToken, installationId); - - liveQueryServerClient = webSocket; - liveQueryServerClient.OnEventMessage += HandleEventMessage; - - ClientStatus = LiveQueryClientStatusTypes.New; - } - - /// - /// For WebGL Only should be called on Unity Update. - /// - public void HandleUpdateEvent() - { - if (liveQueryServerClient != null) - { - LiveQueryClientStatusTypes state = liveQueryServerClient.ClientStatus; // .GetWebSocketStatus(); - - if (!WebSocketStateType.Closed.Equals(state)) - { - liveQueryServerClient.PingWebsocket(); - } - } - } - - /// - /// Called when a connected event is returned from the server. - /// - public event LiveQueryConnectedHandler OnConnected; - - /// - /// Called when a subscribed event is returned from the server. - /// - public event LiveQuerySubscribedHandler OnSubscribed; - - /// - /// Called when a create event is returned from the server. - /// - public event LiveQueryActionHandler OnCreate; - - /// - /// Called when a delete event is returned from the server. - /// - public event LiveQueryActionHandler OnDelete; - - /// - /// Called when a enter event is returned from the server. - /// - public event LiveQueryActionHandler OnEnter; - - /// - /// Called when a leave event is returned from the server. - /// - public event LiveQueryActionHandler OnLeave; - - /// - /// Called when a update event is returned from the server. - /// - public event LiveQueryActionHandler OnUpdate; - - /// - /// Called when a ubsubscribed event is received. - /// - public event LiveQueryUnsubscribedHandler OnUnsubscribed; - - /// - /// Called when an ErrorMEssage is received. - /// - public event LiveQueryErrorHandler OnError; - - public event LiveQueryGeneralMessageHandler OnGeneralMessage; - - /// - /// Indicates the current status of this client. - /// - public LiveQueryClientStatusTypes ClientStatus - { - get => liveQueryServerClient.ClientStatus; - set => liveQueryServerClient.ClientStatus = value; - } - - /// - /// Server connection settings. - /// - public IServerConnectionData ConncetionData { get; set; } - - public string InstallationId { get; set; } - - /// - /// Used to lock object resources. - /// - public object Mutex { get; set; } = new object { }; - - /// - /// Request Id used for this subscription - /// - public int RequestId { get; private set; } - - /// - /// User session token. - /// - public string SessionToken { get; set; } - - public IJsonSerializer JsonSerializer { get; set; } - - public void Unsubscribe() - { - this.ClientStatus = LiveQueryClientStatusTypes.Closing; - } - - public void Dispose() - { - // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method - Dispose(disposing: true); - GC.SuppressFinalize(this); - } - - public void Subscribe() - { - lock (Mutex) - { - if (!(cancellationToken is { })) - { - cancellationToken = cancelSource.Token; - } - - this.liveQueryServerClient.Subscribe(); - } - } - - protected virtual void Dispose(bool disposing) - { - if (!disposedValue) - { - if (disposing) - { - lock (Mutex) - { - cancelSource.Cancel(); - - if (subscriptTask is { }) - { - subscriptTask.Forget(); - } - } - } - - disposedValue = true; - } - } - - private void HandleGeneralMessage(string text) - { - if (this.OnGeneralMessage != null) - { - OnGeneralMessage(text); - } - } - - private void HandleEventMessage(byte[] buffer, int bufferSize) - { - // Lock mutex to enforce thread safty. - lock (Mutex) - { - if (cancellationToken == CancellationToken.None) - { - cancellationToken = cancelSource.Token; - } - - // Convert buffer to string - hopefully this is well formed JSON. - string json = Encoding.UTF8.GetString(buffer); - - // First convert to a basic event message so that - QueryEventMessage opMsg = (QueryEventMessage)JsonSerializer.Deserialize(json); - - OperationTypes op = (OperationTypes)Enum.Parse(typeof(OperationTypes), opMsg.op); - - // If response is a response to a command request, set - // client status to Waiting. - if (OperationTypes.connected.Equals(op) || - OperationTypes.subscribed.Equals(op) || - OperationTypes.unsubscribed.Equals(op)) - { - ClientStatus = LiveQueryClientStatusTypes.Waiting; - } - - json = json.AdjustJsonForParseDate(); - - try - { - HandleGeneralMessage($"Received message ${op}"); - // Based on operation indicated by the event, handle message - switch (op) - { - case OperationTypes.connected: - this.ClientStatus = LiveQueryClientStatusTypes.Opening; - if (OnConnected != null) - { - ActionEvent ae = (ActionEvent)JsonSerializer.Deserialize>(json); - OnConnected(); - } - HandleGeneralMessage("Processed connected."); - - break; - case OperationTypes.create: - if (OnCreate != null) - { - ActionEvent ae = (ActionEvent)JsonSerializer.Deserialize>(json); - OnCreate(ae.Object, ae.requestId); - } - - break; - case OperationTypes.delete: - if (OnDelete != null) - { - ActionEvent ae = (ActionEvent)JsonSerializer.Deserialize>(json); - OnDelete(ae.Object, ae.requestId); - } - - break; - case OperationTypes.enter: - if (OnEnter != null) - { - ActionEvent ae = (ActionEvent)JsonSerializer.Deserialize>(json); - OnEnter(ae.Object, ae.requestId); - } - - break; - case OperationTypes.error: - if (OnError != null) - { - ErrorMessage em = (ErrorMessage)JsonSerializer.Deserialize(json); - OnError(em); - } - - break; - case OperationTypes.leave: - if (OnLeave != null) - { - ActionEvent ae = (ActionEvent)JsonSerializer.Deserialize>(json); - OnLeave(ae.Object, ae.requestId); - } - - break; - case OperationTypes.subscribed: - this.ClientStatus = LiveQueryClientStatusTypes.Open; - if (OnSubscribed != null) - { - ActionEvent ae = (ActionEvent)JsonSerializer.Deserialize>(json); - OnSubscribed(ae.requestId); - } - HandleGeneralMessage("Processed subscribed."); - - break; - case OperationTypes.unsubscribed: - this.ClientStatus = LiveQueryClientStatusTypes.Closed; - if (OnUnsubscribed != null) - { - ActionEvent ae = (ActionEvent)JsonSerializer.Deserialize>(json); - OnUnsubscribed(ae.requestId); - } - HandleGeneralMessage("Processed unsubscribed."); - - break; - case OperationTypes.update: - if (OnUpdate != null) - { - ActionEvent ae = (ActionEvent)JsonSerializer.Deserialize>(json); - OnUpdate(ae.Object, ae.requestId); - } - - break; - } - } - catch (Exception exp) - { - if (OnError != null) - { - ErrorMessage evt = new ErrorMessage() { - code = (int)MoralisFailureException.ErrorCode.LiveQueryEventHandlingFailed, - error = exp.Message - }; - - OnError(evt); - } - } - - } - } - - private void HandleConnectEvent() - { - this.ClientStatus = LiveQueryClientStatusTypes.Opening; - //HandleGeneralMessage($"Subscription Client status changed to: {this.ClientStatus}"); - } - - private void HandleSubscribedEvent(int requestId) - { - this.ClientStatus = LiveQueryClientStatusTypes.Open; - //HandleGeneralMessage($"Subscription Client status changed to: {this.ClientStatus}"); - } - - private void HandleUnsubscribedEvent(int requestId) - { - this.ClientStatus = LiveQueryClientStatusTypes.Closed; - //HandleGeneralMessage($"Subscription Client status changed to: {this.ClientStatus}"); - } - - - private void Initialize(MoralisQuery query, IServerConnectionData conncetionData, ILiveQueryCallbacks callbacks, string sessionToken, string installationId) - { - RequestId = query.ClassName.GetHashCode(); - - targetQuery = query; - ConncetionData = conncetionData; - SessionToken = sessionToken; - InstallationId = installationId; - JsonSerializer = query.JsonSerializer; - - this.OnConnected += callbacks.OnConnected; - this.OnCreate += callbacks.OnCreate; - this.OnDelete += callbacks.OnDelete; - this.OnEnter += callbacks.OnEnter; - this.OnError += callbacks.OnError; - this.OnLeave += callbacks.OnLeave; - this.OnSubscribed += callbacks.OnSubscribed; - this.OnUnsubscribed += callbacks.OnUnsubscribed; - this.OnUpdate += callbacks.OnUpdate; - this.OnGeneralMessage += callbacks.OnGeneralMessage; - - // Add internal handlers - this.OnConnected += this.HandleConnectEvent; - this.OnSubscribed += this.HandleSubscribedEvent; - this.OnUnsubscribed += this.HandleUnsubscribedEvent; - } - - private byte[] CreateSubscribeRequest() - { - SubscribeRequest msg = new SubscribeRequest(targetQuery, null, RequestId, null); - - string json = JsonSerializer.Serialize(msg, JsonSerializer.DefaultOptions); - - byte[] bytes = Encoding.UTF8.GetBytes(json); - - return bytes; - } - } -} -#else -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Queries; -using Moralis.Platform.Queries.Live; -using static Moralis.Platform.Exceptions.MoralisFailureException; - -namespace Moralis.Platform.Services.ClientServices -{ - /// - /// Represents a single Live Query subscription. - /// - /// - public class MoralisLiveQueryClient : ILiveQueryClient where T : MoralisObject - { - /// - /// Singleton value should beincremented whenever a client is created. - /// - public static int NextRequestId = 1; - private bool disposedValue; - private Task subscriptTask; - - private CancellationTokenSource cancelSource = new CancellationTokenSource(); - private CancellationToken cancellationToken = CancellationToken.None; - private Dictionary meassageHandlingTasks = new Dictionary(); - private MoralisQuery targetQuery; - private SubscribableWebSocket liveQueryServerClient = default; - - /// - /// Standard constructor - /// - /// - /// - /// - /// - /// - public MoralisLiveQueryClient(MoralisQuery query, IServerConnectionData conncetionData, ILiveQueryCallbacks callbacks, string sessionToken = null, string installationId = null) - { - Initialize(query, conncetionData, callbacks, sessionToken, installationId); - - liveQueryServerClient = new SubscribableWebSocket(CreateSubscribeRequest(), ConncetionData, RequestId, InstallationId, sessionToken, query.JsonSerializer); - liveQueryServerClient.OnEventMessage += HandleEventMessage; - liveQueryServerClient.OnGeneralMessage += HandleGeneralMessage; - - ClientStatus = LiveQueryClientStatusTypes.New; - } - - /// - /// Constructor accepting SubscribableWebSocket to facilitate testing. - /// - /// - /// - /// - /// - /// - public MoralisLiveQueryClient(MoralisQuery query, IServerConnectionData conncetionData, ILiveQueryCallbacks callbacks, SubscribableWebSocket webSocket, string sessionToken = null, string installationId = null) - { - Initialize(query, conncetionData, callbacks, sessionToken, installationId); - - liveQueryServerClient = webSocket; - liveQueryServerClient.OnEventMessage += HandleEventMessage; - - ClientStatus = LiveQueryClientStatusTypes.New; - } - - /// - /// Called when a connected event is returned from the server. - /// - public event LiveQueryConnectedHandler OnConnected; - - /// - /// Called when a subscribed event is returned from the server. - /// - public event LiveQuerySubscribedHandler OnSubscribed; - - /// - /// Called when a create event is returned from the server. - /// - public event LiveQueryActionHandler OnCreate; - - /// - /// Called when a delete event is returned from the server. - /// - public event LiveQueryActionHandler OnDelete; - - /// - /// Called when a enter event is returned from the server. - /// - public event LiveQueryActionHandler OnEnter; - - /// - /// Called when a leave event is returned from the server. - /// - public event LiveQueryActionHandler OnLeave; - - /// - /// Called when a update event is returned from the server. - /// - public event LiveQueryActionHandler OnUpdate; - - /// - /// Called when a ubsubscribed event is received. - /// - public event LiveQueryUnsubscribedHandler OnUnsubscribed; - - /// - /// Called when an ErrorMEssage is received. - /// - public event LiveQueryErrorHandler OnError; - - public event LiveQueryGeneralMessageHandler OnGeneralMessage; - - /// - /// Indicates the current status of this client. - /// - public LiveQueryClientStatusTypes ClientStatus - { - get => liveQueryServerClient.ClientStatus; - set => liveQueryServerClient.ClientStatus = value; - } - - /// - /// Server connection settings. - /// - public IServerConnectionData ConncetionData { get; set; } - - public string InstallationId { get; set; } - - /// - /// Used to lock object resources. - /// - public object Mutex { get; set; } = new object { }; - - /// - /// Request Id used for this subscription - /// - public int RequestId { get; private set; } - - /// - /// User session token. - /// - public string SessionToken { get; set; } - - public IJsonSerializer JsonSerializer { get; set; } - - public void Unsubscribe() - { - this.ClientStatus = LiveQueryClientStatusTypes.Closing; - } - - public void Dispose() - { - // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method - Dispose(disposing: true); - GC.SuppressFinalize(this); - } - - public void Subscribe() - { - lock (Mutex) - { - if (!(cancellationToken is { })) - { - cancellationToken = cancelSource.Token; - } - - subscriptTask = Task.Run(() => this.liveQueryServerClient.Subscribe(), cancellationToken); - } - } - - protected virtual void Dispose(bool disposing) - { - if (!disposedValue) - { - if (disposing) - { - lock (Mutex) - { - cancelSource.Cancel(); - - foreach (int k in meassageHandlingTasks.Keys) - { - meassageHandlingTasks[k].Dispose(); - meassageHandlingTasks.Remove(k); - } - - if (subscriptTask is { }) - { - subscriptTask.Dispose(); - } - } - } - - disposedValue = true; - } - } - - private void HandleGeneralMessage(string text) - { - if (this.OnGeneralMessage != null) - { - OnGeneralMessage(text); - } - } - private void HandleEventMessage(byte[] buffer, int bufferSize) - { - // Lock mutex to enforce thread safty. - lock (Mutex) - { - if (cancellationToken == CancellationToken.None) - { - cancellationToken = cancelSource.Token; - } - - // Convert buffer to string - hopefully this is well formed JSON. - string json = Encoding.UTF8.GetString(buffer); - - // First convert to a basic event message so that - QueryEventMessage opMsg = (QueryEventMessage)JsonSerializer.Deserialize(json); - - OperationTypes op = (OperationTypes)Enum.Parse(typeof(OperationTypes), opMsg.op); - - // If response is a response to a command request, set - // client status to Waiting. - if (OperationTypes.connected.Equals(op) || - OperationTypes.subscribed.Equals(op) || - OperationTypes.unsubscribed.Equals(op)) - { - ClientStatus = LiveQueryClientStatusTypes.Waiting; - } - - json = json.AdjustJsonForParseDate(); - - try - { - HandleGeneralMessage($"Received message ${op}"); - // Based on operation indicated by the event, handle message - switch (op) - { - case OperationTypes.connected: - this.ClientStatus = LiveQueryClientStatusTypes.Opening; - if (OnConnected != null) - { - ActionEvent ae = (ActionEvent)JsonSerializer.Deserialize>(json); - OnConnected(); - } - HandleGeneralMessage("Processed connected."); - - break; - case OperationTypes.create: - if (OnCreate != null) - { - ActionEvent ae = (ActionEvent)JsonSerializer.Deserialize>(json); - OnCreate(ae.Object, ae.requestId); - } - - break; - case OperationTypes.delete: - if (OnDelete != null) - { - ActionEvent ae = (ActionEvent)JsonSerializer.Deserialize>(json); - OnDelete(ae.Object, ae.requestId); - } - - break; - case OperationTypes.enter: - if (OnEnter != null) - { - ActionEvent ae = (ActionEvent)JsonSerializer.Deserialize>(json); - OnEnter(ae.Object, ae.requestId); - } - - break; - case OperationTypes.error: - if (OnError != null) - { - ErrorMessage em = (ErrorMessage)JsonSerializer.Deserialize(json); - OnError(em); - } - - break; - case OperationTypes.leave: - if (OnLeave != null) - { - ActionEvent ae = (ActionEvent)JsonSerializer.Deserialize>(json); - OnLeave(ae.Object, ae.requestId); - } - - break; - case OperationTypes.subscribed: - this.ClientStatus = LiveQueryClientStatusTypes.Open; - if (OnSubscribed != null) - { - ActionEvent ae = (ActionEvent)JsonSerializer.Deserialize>(json); - OnSubscribed(ae.requestId); - } - HandleGeneralMessage("Processed subscribed."); - - break; - case OperationTypes.unsubscribed: - this.ClientStatus = LiveQueryClientStatusTypes.Closed; - if (OnUnsubscribed != null) - { - ActionEvent ae = (ActionEvent)JsonSerializer.Deserialize>(json); - OnUnsubscribed(ae.requestId); - } - HandleGeneralMessage("Processed unsubscribed."); - - break; - case OperationTypes.update: - if (OnUpdate != null) - { - ActionEvent ae = (ActionEvent)JsonSerializer.Deserialize>(json); - OnUpdate(ae.Object, ae.requestId); - } - - break; - } - } - catch (Exception exp) - { - if (OnError != null) - { - ErrorMessage evt = new ErrorMessage() - { - code = (int)ErrorCode.LiveQueryEventHandlingFailed, - error = exp.Message - }; - - OnError(evt); - } - } - - } - } - - private void HandleConnectEvent() - { - //this.ClientStatus = LiveQueryClientStatusTypes.Opening; - //HandleGeneralMessage($"Subscription Client status changed to: {this.ClientStatus}"); - } - - private void HandleSubscribedEvent(int requestId) - { - //this.ClientStatus = LiveQueryClientStatusTypes.Open; - //HandleGeneralMessage($"Subscription Client status changed to: {this.ClientStatus}"); - } - - private void HandleUnsubscribedEvent(int requestId) - { - //this.ClientStatus = LiveQueryClientStatusTypes.Closed; - //HandleGeneralMessage($"Subscription Client status changed to: {this.ClientStatus}"); - } - - - private void Initialize(MoralisQuery query, IServerConnectionData conncetionData, ILiveQueryCallbacks callbacks, string sessionToken, string installationId) - { - RequestId = NextRequestId++; - targetQuery = query; - ConncetionData = conncetionData; - SessionToken = sessionToken; - InstallationId = installationId; - JsonSerializer = query.JsonSerializer; - - this.OnConnected += callbacks.OnConnected; - this.OnCreate += callbacks.OnCreate; - this.OnDelete += callbacks.OnDelete; - this.OnEnter += callbacks.OnEnter; - this.OnError += callbacks.OnError; - this.OnLeave += callbacks.OnLeave; - this.OnSubscribed += callbacks.OnSubscribed; - this.OnUnsubscribed += callbacks.OnUnsubscribed; - this.OnUpdate += callbacks.OnUpdate; - this.OnGeneralMessage += callbacks.OnGeneralMessage; - - // Add internal handlers - this.OnConnected += this.HandleConnectEvent; - this.OnSubscribed += this.HandleSubscribedEvent; - this.OnUnsubscribed += this.HandleUnsubscribedEvent; - } - - private byte[] CreateSubscribeRequest() - { - SubscribeRequest msg = new SubscribeRequest(targetQuery, null, RequestId, null); - - string json = JsonSerializer.Serialize(msg, JsonSerializer.DefaultOptions); - - byte[] bytes = Encoding.UTF8.GetBytes(json); - - return bytes; - } - } -} - -#endif \ No newline at end of file diff --git a/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisLiveQueryManager.cs b/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisLiveQueryManager.cs deleted file mode 100644 index 27a16c9..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisLiveQueryManager.cs +++ /dev/null @@ -1,115 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Queries; - -namespace Moralis.Platform.Services.ClientServices -{ - public class MoralisLiveQueryManager : ILiveQueryService - { - private List clients = new List(); - - private static MoralisLiveQueryManager instance = new MoralisLiveQueryManager(); - - private MoralisLiveQueryManager() { } - /// - /// Adds a live query subscription to the service - /// - /// - public void AddSubscription(ILiveQueryClient client) - { - client.Subscribe(); - clients.Add(client); - } - - public void Dispose() - { - UnsubscribeAll(); - - foreach (ILiveQueryClient c in clients) - { - c.Dispose(); - } - } - - /// - /// Returns all active subscriptions. - /// - /// IEnumerable - public IEnumerable Subscriptions() - { - return clients; - } - - /// - /// Issues unsubscribe message to all subscriptions that are currently subscribed. - /// - public void UnsubscribeAll() - { - List tasks = new List(); - - foreach (ILiveQueryClient c in clients) - { - tasks.Add(Task.Run(() => - { - long ticks = DateTime.Now.Ticks; - c.Unsubscribe(); - while ((DateTime.Now.Ticks - ticks) > 2000 || - c.ClientStatus != Queries.Live.LiveQueryClientStatusTypes.Closed); - })); - } - - Task.WhenAll(tasks.ToArray()); - } - - #if UNITY_WEBGL - /// - /// For WebGL Only should be called on Unity Update. - /// - public void HandleUpdateEvent() - { - foreach (ILiveQueryClient c in clients) - { - c.HandleUpdateEvent(); - } - } - #endif - - /// - /// Create and return a subscription to the specified query. - /// - /// - /// - /// - /// - /// - /// - /// MoralisLiveQueryClient - public static MoralisLiveQueryClient CreateSubscription(MoralisQuery query, IServerConnectionData connectionData, ILiveQueryCallbacks callbacks, IJsonSerializer jsonSerializer, string sessionToken = null, string installationId = null) where T : MoralisObject - { - MoralisLiveQueryClient client = new MoralisLiveQueryClient(query, connectionData, callbacks, sessionToken, installationId); - instance.AddSubscription(client); - - return client; - } - - public static void UnsubscribeToAllAsync() - { - instance.UnsubscribeAll(); - } - - public static void DisposeService() - { - instance.Dispose(); - } - - #if UNITY_WEBGL - public static void UpdateWebSockets() - { - instance.HandleUpdateEvent(); - } - #endif - } -} \ No newline at end of file diff --git a/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisObjectService.cs b/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisObjectService.cs deleted file mode 100644 index 3f78df4..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisObjectService.cs +++ /dev/null @@ -1,148 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using System.Net; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Exceptions; -using Moralis.Platform.Objects; -using Moralis.Platform.Services.Models; -using Moralis.Platform.Utilities; -using Moralis.Core.Exceptions; - -namespace Moralis.Platform.Services.ClientServices -{ - public class MoralisObjectService : IObjectService - { - IMoralisCommandRunner CommandRunner { get; } - - IServerConnectionData ServerConnectionData { get; } - - IJsonSerializer JsonSerializer { get; } - - public MoralisObjectService(IMoralisCommandRunner commandRunner, IServerConnectionData serverConnectionData, IJsonSerializer jsonSerializer) - { - CommandRunner = commandRunner; - ServerConnectionData = serverConnectionData; - JsonSerializer = jsonSerializer; - } - - public async Task FetchAsync(T item, string sessionToken, CancellationToken cancellationToken = default) where T : MoralisObject - { - MoralisCommand command = new MoralisCommand($"server/classes/{Uri.EscapeDataString(item.ClassName)}/{Uri.EscapeDataString(item.objectId)}", method: "GET", sessionToken: sessionToken, data: default); - Tuple cmdResp = await CommandRunner.RunCommandAsync(command, cancellationToken: cancellationToken); - - T resp = default; - - if ((int)cmdResp.Item1 < 400) - { - resp = (T)JsonSerializer.Deserialize(cmdResp.Item2); - - } - - return resp; - } - - public async Task SaveAsync(MoralisObject item, IDictionary operations, string sessionToken, CancellationToken cancellationToken = default) - { - MoralisCommand command = new MoralisCommand(item.objectId == null ? $"server/classes/{Uri.EscapeDataString(item.ClassName)}" : $"server/classes/{Uri.EscapeDataString(item.ClassName)}/{item.objectId}", method: item.objectId is null ? "POST" : "PUT", sessionToken: sessionToken, data: operations is { } && operations.Count > 0 ? JsonSerializer.Serialize(operations, JsonSerializer.DefaultOptions).JsonInsertParseDate() : JsonSerializer.Serialize(item, JsonSerializer.DefaultOptions).JsonInsertParseDate()); - Tuple cmdResp = await CommandRunner.RunCommandAsync(command, cancellationToken: cancellationToken); - - string resp = default; - - if ((int)cmdResp.Item1 < 400) - { - resp = cmdResp.Item2; - } - else - { - throw new MoralisSaveException(cmdResp.Item2); - } - - return resp; - } - - public async Task DeleteAsync(MoralisObject item, string sessionToken, CancellationToken cancellationToken = default) - { - Tuple cmdResp = await CommandRunner.RunCommandAsync(new MoralisCommand($"server/classes/{item.ClassName}/{item.objectId}", method: "DELETE", sessionToken: sessionToken, data: null), cancellationToken: cancellationToken); - } - - int MaximumBatchSize { get; } = 50; - - async Task>>> ExecuteBatchRequestAsync(IList requests, string sessionToken, CancellationToken cancellationToken = default) - { - int batchSize = requests.Count; - - List>> tasks = new List>> { }; - List>> completionSources = new List>> { }; - - for (int i = 0; i < batchSize; ++i) - { - TaskCompletionSource> tcs = new TaskCompletionSource>(); - - completionSources.Add(tcs); - tasks.Add(tcs.Task); - } - - List encodedRequests = requests.Select(request => - { - Dictionary results = new Dictionary - { - ["method"] = request.Method, - ["path"] = request is { Path: { }, Resource: { } } ? request.Target.AbsolutePath : new Uri(new Uri(ServerConnectionData.ServerURI), request.Path).AbsolutePath, - }; - - if (request.DataObject != null) - results["body"] = request.DataObject; - - return results; - }).Cast().ToList(); - - MoralisCommand command = new MoralisCommand("batch", method: "POST", sessionToken: sessionToken, data: JsonSerializer.Serialize(new Dictionary { [nameof(requests)] = encodedRequests }, JsonSerializer.DefaultOptions)); - - Tuple cmdResp = await CommandRunner.RunCommandAsync(command, cancellationToken: cancellationToken); - - if ((int)cmdResp.Item1 < 400) - { - foreach (TaskCompletionSource> tcs in completionSources) - { - if (TaskStatus.Faulted.Equals(tcs.Task.Status)) - tcs.TrySetException(new Exception("Update failed.")); - else if (TaskStatus.Canceled.Equals(tcs.Task.Status)) - tcs.TrySetCanceled(); - } - - - IList resultsArray = Conversion.As>(cmdResp.Item2); - int resultLength = resultsArray.Count; - - if (resultLength != batchSize) - { - foreach (TaskCompletionSource> completionSource in completionSources) - completionSource.TrySetException(new InvalidOperationException($"Batch command result count expected: {batchSize} but was: {resultLength}.")); - } - else - { - for (int i = 0; i < batchSize; ++i) - { - Dictionary result = resultsArray[i] as Dictionary; - TaskCompletionSource> target = completionSources[i]; - - if (result.ContainsKey("success")) - target.TrySetResult(result["success"] as IDictionary); - else if (result.ContainsKey("error")) - { - IDictionary error = result["error"] as IDictionary; - target.TrySetException(new MoralisFailureException((MoralisFailureException.ErrorCode)(long)error["code"], error[nameof(error)] as string)); - } - else - target.TrySetException(new InvalidOperationException("Invalid batch command response.")); - } - } - } - - return tasks; - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisService.cs b/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisService.cs deleted file mode 100644 index 247bbcd..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisService.cs +++ /dev/null @@ -1,159 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Utilities; - -namespace Moralis.Platform.Services.ClientServices -{ - public class MoralisService : CustomServiceHub, IServiceHubComposer where TUser : MoralisUser - { - - - /// - /// Contains, in order, the official ISO date and time format strings, and two modified versions that account for the possibility that the server-side string processing mechanism removed trailing zeroes. - /// - internal static string[] DateFormatStrings { get; } = - { - "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'", - "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ff'Z'", - "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'f'Z'", - }; - - /// - /// Gets whether or not the assembly using the Moralis SDK was compiled by IL2CPP. - /// - public static bool IL2CPPCompiled { get; set; } = AppDomain.CurrentDomain?.FriendlyName?.Equals("IL2CPP Root Domain") == true; - - /// - /// The configured default instance of to use. - /// - public static MoralisService Instance { get; private set; } - - internal static string Version => typeof(MoralisService)?.Assembly?.GetCustomAttribute()?.InformationalVersion ?? typeof(MoralisService)?.Assembly?.GetName()?.Version?.ToString(); - - /// - /// Services that provide essential functionality. - /// - public override IServiceHub Services { get; internal set; } - - /// - /// Creates a new and authenticates it as belonging to your application. This class is a hub for interacting with the SDK. The recommended way to use this class on client applications is to instantiate it, then call on it in your application entry point. This allows you to access . - /// - /// The Application ID provided in the Moralis dashboard. - /// The server URL provided in the Moralis dashboard. - /// The .NET Key provided in the Moralis dashboard. - /// A service hub to override internal services and thereby make the Moralis SDK operate in a custom manner. - /// A set of implementation instances to tweak the behaviour of the SDK. - public MoralisService(string applicationID, string serverURL, string key, IJsonSerializer jsonSerializer, IServiceHub serviceHub = default, params IServiceHubMutator[] configurators) : this(new ServerConnectionData { ApplicationID = applicationID, ServerURI = serverURL, Key = key }, jsonSerializer, serviceHub, configurators) { } - - /// - /// Creates a new and authenticates it as belonging to your application. This class is a hub for interacting with the SDK. The recommended way to use this class on client applications is to instantiate it, then call on it in your application entry point. This allows you to access . - /// - /// The configuration to initialize Moralis with. - /// A service hub to override internal services and thereby make the Moralis SDK operate in a custom manner. - /// A set of implementation instances to tweak the behaviour of the SDK. - public MoralisService(IServerConnectionData configuration, IJsonSerializer jsonSerializer, IServiceHub serviceHub = default, params IServiceHubMutator[] configurators) - { - Services = serviceHub is { } ? new OrchestrationServiceHub { Custom = serviceHub, Default = new ServiceHub { ServerConnectionData = GenerateServerConnectionData(), JsonSerializer = jsonSerializer } } : new ServiceHub { ServerConnectionData = GenerateServerConnectionData(), JsonSerializer = jsonSerializer } as IServiceHub; - - IServerConnectionData GenerateServerConnectionData() => configuration switch - { - null => throw new ArgumentNullException(nameof(configuration)), - ServerConnectionData { Test: true, ServerURI: { } } data => data, - ServerConnectionData { Test: true } data => new ServerConnectionData - { - ApplicationID = data.ApplicationID, - Headers = data.Headers, - MasterKey = data.MasterKey, - Test = data.Test, - Key = data.Key, - ServerURI = "https://api.Moralis.com/1/" - }, - { ServerURI: "https://api.Moralis.com/1/" } => throw new InvalidOperationException("Since the official Moralis server has shut down, you must specify a URI that points to a hosted instance."), - { ApplicationID: { }, ServerURI: { }, Key: { } } data => data, - _ => throw new InvalidOperationException("The IServerConnectionData implementation instance provided to the MoralisClient constructor must be populated with the information needed to connect to a Moralis server instance.") - }; - - // If a WS/WSS URI is not supplied create it from the server URL. - if (String.IsNullOrWhiteSpace(configuration.LiveQueryServerURI)) - { - configuration.LiveQueryServerURI = Conversion.WebUriToWsURi(configuration.ServerURI); - } - - if (configurators is { Length: int length } && length > 0) - { - Services = serviceHub switch - { - IMutableServiceHub { } mutableServiceHub => BuildHub((Hub: mutableServiceHub, mutableServiceHub.ServerConnectionData = serviceHub.ServerConnectionData != null ? serviceHub.ServerConnectionData : Services.ServerConnectionData).Hub, Services, configurators), - { } => BuildHub(default, Services, configurators) - }; - } - - Cloud = new MoralisCloud((IServiceHub)this.Services); - - //Services.ClassController.AddIntrinsic(); - } - - /// - /// Initializes a instance using the set on the 's implementation instance. - /// - //public MoralisClient() => Services = (Instance ?? throw new InvalidOperationException("A MoralisClient instance with an initializer service must first be publicized in order for the default constructor to be used.")).Services.Cloner.BuildHub(Instance.Services, this); - - /// - /// Sets this instance as the template to create new instances from. - /// - ///// Declares that the current instance should be the publicly-accesible . - public void Publicize() - { - lock (Mutex) - { - Instance = this; - } - } - - public MoralisCloud Cloud { get; private set; } - - - static object Mutex { get; } = new object { }; - - internal static string BuildQueryString(IDictionary parameters) => String.Join("&", (from pair in parameters let valueString = pair.Value as string select $"{Uri.EscapeDataString(pair.Key)}={Uri.EscapeDataString(String.IsNullOrEmpty(valueString) ? JsonUtilities.Encode(pair.Value) : valueString)}").ToArray()); - - internal static IDictionary DecodeQueryString(string queryString) - { - Dictionary query = new Dictionary { }; - - foreach (string pair in queryString.Split('&')) - { - string[] parts = pair.Split(new char[] { '=' }, 2); - query[parts[0]] = parts.Length == 2 ? Uri.UnescapeDataString(parts[1].Replace("+", " ")) : null; - } - - return query; - } - - //internal static IDictionary DeserializeJsonString(string jsonData) => JsonUtilities.Parse(jsonData) as IDictionary; - - //internal static string SerializeJsonString(IDictionary jsonData) => JsonUtilities.Encode(jsonData); - - public IServiceHub BuildHub(IMutableServiceHub target = default, IServiceHub extension = default, params IServiceHubMutator[] configurators) - { - OrchestrationServiceHub orchestrationServiceHub = new OrchestrationServiceHub - { - Custom = target != null ? target : new MutableServiceHub { }, - Default = extension != null ? extension : new ServiceHub { } - }; - - foreach (IServiceHubMutator mutator in configurators.Where(configurator => configurator.Valid)) - { - mutator.Mutate(ref target, orchestrationServiceHub); - orchestrationServiceHub.Custom = target; - } - - return orchestrationServiceHub; - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisSessionService.cs b/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisSessionService.cs deleted file mode 100644 index 77662d1..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisSessionService.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System.Threading; -using Moralis.Platform.Utilities; -using System.Threading.Tasks; -using System.Net; -using System; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Services.Models; - -namespace Moralis.Platform.Services.ClientServices -{ - public class MoralisSessionService : ISessionService where TUser : MoralisUser - { - IMoralisCommandRunner CommandRunner { get; } - - IJsonSerializer JsonSerializer { get; } - - public MoralisSessionService(IMoralisCommandRunner commandRunner, IJsonSerializer jsonSerializer) => (CommandRunner, JsonSerializer) = (commandRunner, jsonSerializer); - - public async Task GetSessionAsync(string sessionToken, IServiceHub serviceHub, CancellationToken cancellationToken = default) - { - Tuple cmdResp = await CommandRunner.RunCommandAsync(new MoralisCommand("sessions/me", method: "GET", sessionToken: sessionToken, data: null), cancellationToken: cancellationToken); - - MoralisSession session = default; - - if ((int)cmdResp.Item1 < 300) - { - session = JsonSerializer.Deserialize(cmdResp.Item2); - } - - return session; - } - - public async Task RevokeAsync(string sessionToken, CancellationToken cancellationToken = default) - { - await CommandRunner.RunCommandAsync(new MoralisCommand("logout", method: "POST", sessionToken: sessionToken, data: "{}"), cancellationToken: cancellationToken); - } - - public async Task UpgradeToRevocableSessionAsync(string sessionToken, IServiceHub serviceHub, CancellationToken cancellationToken = default) - { - Tuple cmdResp = await CommandRunner.RunCommandAsync(new MoralisCommand("upgradeToRevocableSession", method: "POST", sessionToken: sessionToken, data: "{}"), cancellationToken: cancellationToken); - - MoralisSession session = default; - - if ((int)cmdResp.Item1 < 300) - { - session = JsonSerializer.Deserialize(cmdResp.Item2); - } - - return session; - } - - public bool IsRevocableSessionToken(string sessionToken) => sessionToken.Contains("r:"); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisUserService.cs b/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisUserService.cs deleted file mode 100644 index fcf0999..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/ClientServices/MoralisUserService.cs +++ /dev/null @@ -1,107 +0,0 @@ -using System.Collections.Generic; -using System.Threading; -using Moralis.Platform.Utilities; -using System.Threading.Tasks; -using System.Net; -using System; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Services.Models; - -namespace Moralis.Platform.Services.ClientServices -{ - public class MoralisUserService : IUserService where TUser : MoralisUser - { - IMoralisCommandRunner CommandRunner { get; } - - IJsonSerializer JsonSerializer { get; } - - IObjectService ObjectService { get; } - - public bool RevocableSessionEnabled { get; set; } - - public object RevocableSessionEnabledMutex { get; } = new object { }; - - public MoralisUserService(IMoralisCommandRunner commandRunner, IObjectService objectService, IJsonSerializer jsonSerializer) => (CommandRunner, ObjectService, JsonSerializer) = (commandRunner, objectService, jsonSerializer); - - public async Task SignUpAsync(IObjectState state, IDictionary operations, CancellationToken cancellationToken = default) - { - Tuple cmdResp = await CommandRunner.RunCommandAsync(new MoralisCommand("server/classes/_User", method: "POST", data: JsonSerializer.Serialize(operations)), cancellationToken: cancellationToken); - - TUser resp = default; - - if ((int)cmdResp.Item1 < 300) - { - resp = (TUser)JsonSerializer.Deserialize(cmdResp.Item2); - - resp.ObjectService = this.ObjectService; - } - - return resp; - } - - public async Task LogInAsync(string username, string password, IServiceHub serviceHub, CancellationToken cancellationToken = default) - { - TUser result = default; - Tuple cmdResp = await CommandRunner.RunCommandAsync(new MoralisCommand($"server/login?{MoralisService.BuildQueryString(new Dictionary { [nameof(username)] = username, [nameof(password)] = password })}", method: "GET", data: null), cancellationToken: cancellationToken); - if ((int)cmdResp.Item1 < 300) - { - result = JsonSerializer.Deserialize(cmdResp.Item2.ToString()); - - result.ObjectService = this.ObjectService; - result.ACL = new MoralisAcl(result); - await result.SaveAsync(); - } - - return result; - } - - public async Task LogInAsync(string authType, IDictionary data, IServiceHub serviceHub, CancellationToken cancellationToken = default) - { - TUser user = default; - - Dictionary authData = new Dictionary - { - [authType] = data - }; - - MoralisCommand cmd = new MoralisCommand("server/users", method: "POST", data: JsonSerializer.Serialize(new Dictionary { [nameof(authData)] = authData })); - Tuple cmdResp = await CommandRunner.RunCommandAsync(cmd, cancellationToken: cancellationToken); - - if ((int)cmdResp.Item1 < 300) - { - user = JsonSerializer.Deserialize(cmdResp.Item2.ToString()); - - user.ObjectService = this.ObjectService; - - user.ACL = new MoralisAcl(user); - user.ethAddress = data["id"].ToString(); - user.accounts = new string[1]; - user.accounts[0] = user.ethAddress; - - await user.SaveAsync(); - } - - return user; - } - - public async Task GetUserAsync(string sessionToken, IServiceHub serviceHub, CancellationToken cancellationToken = default) - { - TUser user = default; - Tuple cmdResp = await CommandRunner.RunCommandAsync(new MoralisCommand("server/users/me", method: "GET", sessionToken: sessionToken, data: default), cancellationToken: cancellationToken); - if ((int)cmdResp.Item1 < 300) - { - user = JsonSerializer.Deserialize(cmdResp.Item2.ToString()); - - user.ObjectService = this.ObjectService; - } - - return user; - } - - public async Task RequestPasswordResetAsync(string email, CancellationToken cancellationToken = default) - { - Tuple cmdResp = await CommandRunner.RunCommandAsync(new MoralisCommand("server/requestPasswordReset", method: "POST", data: JsonSerializer.Serialize(new Dictionary { [nameof(email)] = email })), cancellationToken: cancellationToken); - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Services/ClientServices/SessionServiceExtensions.cs b/MoralisDotNet/Moralis/Platform/Services/ClientServices/SessionServiceExtensions.cs deleted file mode 100644 index e3e27d8..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/ClientServices/SessionServiceExtensions.cs +++ /dev/null @@ -1,61 +0,0 @@ - -using System.Threading; -using Moralis.Platform.Utilities; -using System.Threading.Tasks; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Queries; - -namespace Moralis.Platform.Services.ClientServices -{ - public static class SessionServiceExtensions - { - /// - /// Constructs a for ParseSession. - /// - public static MoralisQuery GetSessionQuery(this IServiceHub serviceHub) where TUser : MoralisUser => serviceHub.GetQuery(); - - /// - /// Gets the current object related to the current user. - /// - public static async Task GetCurrentSessionAsync(this IServiceHub serviceHub) where TUser : MoralisUser - { - return await GetCurrentSessionAsync(serviceHub, CancellationToken.None); - } - - /// - /// Gets the current object related to the current user. - /// - /// The cancellation token - public static async Task GetCurrentSessionAsync(this IServiceHub serviceHub, CancellationToken cancellationToken) where TUser : MoralisUser - { - MoralisSession ms = await serviceHub.GetCurrentSessionAsync(cancellationToken); - - if (ms == null) return default; - - string token = ms.GetCurrentSessionToken(); - - if (token == null) return default; - - return await serviceHub.SessionService.GetSessionAsync(token, serviceHub, cancellationToken); - } - - public static async Task RevokeSessionAsync(this IServiceHub serviceHub, string sessionToken, CancellationToken cancellationToken) where TUser : MoralisUser - { - if (sessionToken != null && serviceHub.SessionService.IsRevocableSessionToken(sessionToken)) - await serviceHub.SessionService.RevokeAsync(sessionToken, cancellationToken); - } - - public static async Task UpgradeToRevocableSessionAsync(this IServiceHub serviceHub, string sessionToken, CancellationToken cancellationToken) where TUser : MoralisUser - { - if (sessionToken is null || serviceHub.SessionService.IsRevocableSessionToken(sessionToken)) - return sessionToken; - else - { - MoralisSession ms = await serviceHub.SessionService.UpgradeToRevocableSessionAsync(sessionToken, serviceHub, cancellationToken); - - return ms.sessionToken; - } - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Services/ClientServices/UniversalWebClient.cs b/MoralisDotNet/Moralis/Platform/Services/ClientServices/UniversalWebClient.cs deleted file mode 100644 index 310f8ee..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/ClientServices/UniversalWebClient.cs +++ /dev/null @@ -1,135 +0,0 @@ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Net.Http; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using System.Threading.Tasks; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Services.Models; -using Moralis.Platform.Utilities; -using BCLWebClient = System.Net.Http.HttpClient; -using WebRequest = Moralis.Platform.Services.Models.WebRequest; - -namespace Moralis.Platform.Services -{ - /// - /// A universal implementation of . - /// - public class UniversalWebClient : IWebClient - { - static HashSet ContentHeaders { get; } = new HashSet - { - { "Allow" }, - { "Content-Disposition" }, - { "Content-Encoding" }, - { "Content-Language" }, - { "Content-Length" }, - { "Content-Location" }, - { "Content-MD5" }, - { "Content-Range" }, - { "Content-Type" }, - { "Expires" }, - { "Last-Modified" } - }; - - public UniversalWebClient() : this(new BCLWebClient { }) { } - - public UniversalWebClient(BCLWebClient client) => Client = client; - - BCLWebClient Client { get; set; } - - public async Task> ExecuteAsync(WebRequest httpRequest, IProgress uploadProgress, IProgress downloadProgress, CancellationToken cancellationToken) - { - uploadProgress ??= new Progress { }; - downloadProgress ??= new Progress { }; - - HttpRequestMessage message = new HttpRequestMessage(new HttpMethod(httpRequest.Method), httpRequest.Target); - - // Fill in zero-length data if method is post. - if ((httpRequest.Data is null && httpRequest.Method.ToLower().Equals("post") ? new MemoryStream(new byte[0]) : httpRequest.Data) is Stream { } data) - { - message.Content = new StreamContent(data); - } - - if (httpRequest.Headers != null) - { - foreach (KeyValuePair header in httpRequest.Headers) - { - if (ContentHeaders.Contains(header.Key)) - { - message.Content.Headers.Add(header.Key, header.Value); - } - else - { - message.Headers.Add(header.Key, header.Value); - } - } - } - - // Avoid aggressive caching on Windows Phone 8.1. - - message.Headers.Add("Cache-Control", "no-cache"); - message.Headers.IfModifiedSince = DateTimeOffset.UtcNow; - - // TODO: (richardross) investigate progress here, maybe there's something we're missing in order to support this. - - uploadProgress.Report(new DataTransferLevel { Amount = 0 }); - - HttpResponseMessage sendResp = await Client.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, cancellationToken); - //HttpResponseMessage response = httpMessageTask.Result; - uploadProgress.Report(new DataTransferLevel { Amount = 1 }); - - Stream readStream = await sendResp.Content.ReadAsStreamAsync(); - - MemoryStream resultStream = new MemoryStream { }; - //Stream responseStream = streamTask.Result; - - int bufferSize = 4096; - int bytesRead = 0; - byte[] buffer = new byte[bufferSize]; - long totalLength = -1; - long readSoFar = 0; - - try - { - totalLength = readStream.Length; - } - catch { }; - - bytesRead = await readStream.ReadAsync(buffer, 0, bufferSize, cancellationToken); - - while (bytesRead > 0) - { - cancellationToken.ThrowIfCancellationRequested(); - - await resultStream.WriteAsync(buffer, 0, bytesRead, cancellationToken); - - cancellationToken.ThrowIfCancellationRequested(); - readSoFar += bytesRead; - - if (totalLength > -1) - { - downloadProgress.Report(new DataTransferLevel { Amount = 1.0 * readSoFar / totalLength }); - } - - bytesRead = await readStream.ReadAsync(buffer, 0, bufferSize, cancellationToken); - } - - // If getting stream size is not supported, then report download only once. - if (totalLength == -1) - { - downloadProgress.Report(new DataTransferLevel { Amount = 1.0 }); - } - - byte[] resultAsArray = resultStream.ToArray(); - resultStream.Dispose(); - - // Assume UTF-8 encoding. - return new Tuple(sendResp.StatusCode, Encoding.UTF8.GetString(resultAsArray, 0, resultAsArray.Length)); - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Services/ClientServices/UserServiceExtensions.cs b/MoralisDotNet/Moralis/Platform/Services/ClientServices/UserServiceExtensions.cs deleted file mode 100644 index f9d9c6f..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/ClientServices/UserServiceExtensions.cs +++ /dev/null @@ -1,237 +0,0 @@ -using System.Collections.Generic; -using System.Threading; -using Moralis.Platform.Utilities; -using System.Threading.Tasks; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Queries; - -namespace Moralis.Platform.Services.ClientServices -{ - public static class UserServiceExtensions - { - internal async static Task GetCurrentSessionTokenAsync(this IServiceHub serviceHub, CancellationToken cancellationToken = default) where TUser : MoralisUser - { - return await serviceHub.CurrentUserService.GetCurrentSessionTokenAsync(serviceHub, cancellationToken); - } - - //public static Task LogInWithAsync(this IServiceHub serviceHub, string authType, IDictionary data, CancellationToken cancellationToken) where TUser : MoralisUser - //{ - // TUser user = null; - - // return serviceHub.UserService.LogInAsync(authType, data, serviceHub, cancellationToken).ContinueWith(task => SaveCurrentUserAsync((IServiceHub)serviceHub, task.Result).OnSuccess(_ => task.Result)).Unwrap(); - // //OnSuccess(task => task.Result ); - //} - - public static async Task LogInWithAsync(this IServiceHub serviceHub, string authType, CancellationToken cancellationToken) where TUser : MoralisUser - { - IAuthenticationProvider provider = MoralisUser.GetProvider(authType); - IDictionary authData = await provider.AuthenticateAsync(cancellationToken); - - return await LogInWithAsync(serviceHub, authType, authData, cancellationToken); - } - - /// - /// Logs in a user with a username and password. On success, this saves the session to disk or to memory so you can retrieve the currently logged in user using . - /// - /// The instance to target when logging in. - /// The username to log in with. - /// The password to log in with. - /// The cancellation token. - /// The newly logged-in user. - public static async Task LogInAsync(this IServiceHub serviceHub, string username, string password, CancellationToken cancellationToken = default) where TUser : MoralisUser - { - TUser user = await serviceHub.UserService.LogInAsync(username, password, serviceHub, cancellationToken); - - await SaveCurrentUserAsync(serviceHub, user); - - return user; - } - - /// - /// Logs in a user with a username and password. On success, this saves the session to disk so you - /// can retrieve the currently logged in user using . - /// - /// The session token to authorize with - /// The cancellation token. - /// The user if authorization was successful - public static async Task BecomeAsync(this IServiceHub serviceHub, string sessionToken, CancellationToken cancellationToken = default) where TUser : MoralisUser - { - TUser user = await serviceHub.UserService.GetUserAsync(sessionToken, serviceHub, cancellationToken); - - await SaveCurrentUserAsync(serviceHub, user); - - return user; - } - - /// - /// Logs out the currently logged in user session. This will remove the session from disk, log out of - /// linked services, and future calls to will return null. - /// - /// - /// Typically, you should use , unless you are managing your own threading. - /// - public static async void LogOut(this IServiceHub serviceHub) where TUser : MoralisUser - { - await LogOutAsync(serviceHub); - } - - /// - /// Logs out the currently logged in user session. This will remove the session from disk, log out of - /// linked services, and future calls to will return null. - /// - /// - /// This is preferable to using , unless your code is already running from a - /// background thread. - /// - public static Task LogOutAsync(this IServiceHub serviceHub) where TUser : MoralisUser => LogOutAsync(serviceHub, CancellationToken.None); - - /// - /// Logs out the currently logged in user session. This will remove the session from disk, log out of - /// linked services, and future calls to will return null. - /// - /// This is preferable to using , unless your code is already running from a - /// background thread. - /// - public static async Task LogOutAsync(this IServiceHub serviceHub, CancellationToken cancellationToken) where TUser : MoralisUser - { - TUser user = await GetCurrentUserAsync(serviceHub); - - if (user != null) - await serviceHub.CurrentUserService.LogOutAsync(serviceHub, cancellationToken); - } - - static void LogOutWithProviders() - { - foreach (IAuthenticationProvider provider in MoralisUser.Authenticators.Values) - { - provider.Deauthenticate(); - } - } - - /// - /// Gets the currently logged in MoralisUser with a valid session, either from memory or disk - /// if necessary. - /// - public static async Task GetCurrentUser(this IServiceHub serviceHub) where TUser : MoralisUser - { - return await GetCurrentUserAsync(serviceHub); - } - - /// - /// Gets the currently logged in MoralisUser with a valid session, either from memory or disk - /// if necessary, asynchronously. - /// - internal static async Task GetCurrentUserAsync(this IServiceHub serviceHub, CancellationToken cancellationToken = default) where TUser : MoralisUser - { - return await serviceHub.CurrentUserService.GetAsync(serviceHub, cancellationToken); - } - - internal static async Task SaveCurrentUserAsync(this IServiceHub serviceHub, TUser user, CancellationToken cancellationToken = default) where TUser : MoralisUser - { - await serviceHub.CurrentUserService.SetAsync(user, cancellationToken); - } - - internal static void ClearInMemoryUser(this IServiceHub serviceHub) where TUser : MoralisUser => serviceHub.CurrentUserService.ClearFromMemory(); - - /// - /// Constructs a for s. - /// - public static MoralisQuery GetUserQuery(this IServiceHub serviceHub) where TUser : MoralisUser => serviceHub.GetQuery(); - - #region Legacy / Revocable Session Tokens - - /// - /// Tells server to use revocable session on LogIn and SignUp, even when App's Settings - /// has "Require Revocable Session" turned off. Issues network request in background to - /// migrate the sessionToken on disk to revocable session. - /// - /// The Task that upgrades the session. - public static async Task EnableRevocableSessionAsync(this IServiceHub serviceHub, CancellationToken cancellationToken = default) - { - lock (serviceHub.UserService.RevocableSessionEnabledMutex) - { - serviceHub.UserService.RevocableSessionEnabled = true; - } - - await GetCurrentUserAsync(serviceHub, cancellationToken); - } - - internal static void DisableRevocableSession(this IServiceHub serviceHub) - { - lock (serviceHub.UserService.RevocableSessionEnabledMutex) - { - serviceHub.UserService.RevocableSessionEnabled = false; - } - } - - internal static bool GetIsRevocableSessionEnabled(this IServiceHub serviceHub) - { - lock (serviceHub.UserService.RevocableSessionEnabledMutex) - { - return serviceHub.UserService.RevocableSessionEnabled; - } - } - - #endregion - - /// - /// Requests a password reset email to be sent to the specified email address associated with the - /// user account. This email allows the user to securely reset their password on the Moralis site. - /// - /// The email address associated with the user that forgot their password. - public static async Task RequestPasswordResetAsync(this IServiceHub serviceHub, string email) where TUser : MoralisUser { - await RequestPasswordResetAsync(serviceHub, email, CancellationToken.None); - } - - /// - /// Requests a password reset email to be sent to the specified email address associated with the - /// user account. This email allows the user to securely reset their password on the Moralis site. - /// - /// The email address associated with the user that forgot their password. - /// The cancellation token. - public static async Task RequestPasswordResetAsync(this IServiceHub serviceHub, string email, CancellationToken cancellationToken) where TUser : MoralisUser - { - await serviceHub.UserService.RequestPasswordResetAsync(email, cancellationToken); - } - - public static async Task LogInWithAsync(this IServiceHub serviceHub, string authType, IDictionary data, CancellationToken cancellationToken) where TUser : MoralisUser - { - TUser user = await serviceHub.UserService.LogInAsync(authType, data, serviceHub, cancellationToken); - - lock (user.Mutex) - { - if (user.authData == null) - { - user.authData = new Dictionary>(); - } - - user.authData[authType] = data; - - user.SynchronizeAllAuthData(); - } - - await SaveCurrentUserAsync(serviceHub, user); - - return user; - } - - //public static Task LogInWithAsync(this IServiceHub serviceHub, string authType, CancellationToken cancellationToken) where TUser : MoralisUser - //{ - // IAuthenticationProvider provider = MoralisUser.GetProvider(authType); - // return provider.AuthenticateAsync(cancellationToken).OnSuccess(authData => LogInWithAsync(serviceHub, authType, authData.Result, cancellationToken)).Unwrap(); - //} - - internal static async void RegisterProvider(this IServiceHub serviceHub, IAuthenticationProvider provider) where TUser : MoralisUser - { - MoralisUser.Authenticators[provider.AuthType] = provider; - MoralisUser curUser = await GetCurrentUserAsync(serviceHub); - - if (curUser != null) - { - curUser.SynchronizeAuthData(provider); - } - } - - } -} diff --git a/MoralisDotNet/Moralis/Platform/Services/Infrastructure/InstallationService.cs b/MoralisDotNet/Moralis/Platform/Services/Infrastructure/InstallationService.cs deleted file mode 100644 index 014ca7a..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/Infrastructure/InstallationService.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System; -using Moralis.Platform.Utilities; -using System.Threading.Tasks; -using Moralis.Platform.Abstractions; - -namespace Moralis.Platform.Services.Infrastructure -{ - public class InstallationService : IInstallationService - { - - static string InstallationIdKey { get; } = "InstallationId"; - - object Mutex { get; } = new object { }; - - public Guid? InstallationId { get; private set; } - - ICacheService StorageController { get; } - - public InstallationService(ICacheService storageController) => StorageController = storageController; - - public async Task SetAsync(Guid? installationId) - { - //lock (Mutex) - //{ - - if (installationId != null) - { - IDataCache storage = await StorageController.LoadAsync(); - - await storage.AddAsync(InstallationIdKey, installationId.ToString()); - } - else - { - IDataCache storage = await StorageController.LoadAsync(); - - await storage.RemoveAsync(InstallationIdKey); - } - - InstallationId = installationId; - } - - public async Task GetAsync() - { - lock (Mutex) - if (InstallationId != null) - return InstallationId; - - IDataCache storage = await StorageController.LoadAsync(); - - storage.TryGetValue(InstallationIdKey, out object id); - - try - { - lock (Mutex) - return InstallationId = new Guid(id as string); - } - catch (Exception) - { - Guid newInstallationId = Guid.NewGuid(); - await SetAsync(newInstallationId); - return newInstallationId; - } - } - - public async Task ClearAsync() => await SetAsync(null); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Services/Infrastructure/MetadataService.cs b/MoralisDotNet/Moralis/Platform/Services/Infrastructure/MetadataService.cs deleted file mode 100644 index 5937183..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/Infrastructure/MetadataService.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Moralis.Platform.Abstractions; - -namespace Moralis.Platform.Services.Infrastructure -{ - public class MetadataService : IMetadataService - { - /// - /// Information about your app. - /// - public IHostManifestData HostManifestData { get; set; } - - /// - /// Information about the environment the library is operating in. - /// - public IEnvironmentData EnvironmentData { get; set; } - } -} - diff --git a/MoralisDotNet/Moralis/Platform/Services/Infrastructure/MoralisCacheService.cs b/MoralisDotNet/Moralis/Platform/Services/Infrastructure/MoralisCacheService.cs deleted file mode 100644 index 2c3923e..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/Infrastructure/MoralisCacheService.cs +++ /dev/null @@ -1,301 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Utilities; -using static Moralis.Platform.ResourceWrapper; - -#pragma warning disable CS1998 // This async method lacks 'await' operators and will run synchronously - -namespace Moralis.Platform.Services.Infrastructure -{ - /// - /// Implements `IStorageController` for PCL targets, based off of PCLStorage. - /// - public class MoralisCacheService : IDiskFileCacheService where TUser : MoralisUser - { - class FileBackedCache : IDataCache - { - public FileBackedCache(FileInfo file) => File = file; - - internal void Save() - { - File.WriteContent(JsonUtilities.Encode(Storage)); - } - - internal async Task LoadAsync() - { - Storage = new Dictionary { }; - -#if !UNITY_WEBGL - if (File.Exists) - { - string data = string.Empty; - - data = await File.ReadAllTextAsync(); - - lock (Mutex) - { - try - { - Storage = JsonUtilities.Parse(data) as Dictionary; - } - catch - { - Storage = new Dictionary { }; - } - } - } - else - { - Storage = new Dictionary { }; - using (File.Create()) - { - } - } -#endif - } - - internal void Update(IDictionary contents) => Lock(() => Storage = contents.ToDictionary(element => element.Key, element => element.Value)); - - public async Task AddAsync(string key, object value) - { - Storage[key] = value; - Save(); - } - - public async Task RemoveAsync(string key) - { - Storage.Remove(key); - Save(); - } - - public void Add(string key, object value) => throw new NotSupportedException(FileBackedCacheSynchronousMutationNotSupportedMessage); - - public bool Remove(string key) => throw new NotSupportedException(FileBackedCacheSynchronousMutationNotSupportedMessage); - - public void Add(KeyValuePair item) => throw new NotSupportedException(FileBackedCacheSynchronousMutationNotSupportedMessage); - - public bool Remove(KeyValuePair item) => throw new NotSupportedException(FileBackedCacheSynchronousMutationNotSupportedMessage); - - public bool ContainsKey(string key) => Lock(() => Storage.ContainsKey(key)); - - public bool TryGetValue(string key, out object value) - { - lock (Mutex) - { - return (Result: Storage.TryGetValue(key, out object found), value = found).Result; - } - } - - public void Clear() => Lock(() => Storage.Clear()); - - public bool Contains(KeyValuePair item) => Lock(() => Elements.Contains(item)); - - public void CopyTo(KeyValuePair[] array, int arrayIndex) => Lock(() => Elements.CopyTo(array, arrayIndex)); - - public IEnumerator> GetEnumerator() => Storage.GetEnumerator(); - - IEnumerator IEnumerable.GetEnumerator() => Storage.GetEnumerator(); - - public FileInfo File { get; set; } - - public object Mutex { get; set; } = new object { }; - - // ALTNAME: Operate - - TResult Lock(Func operation) - { - lock (Mutex) - { - return operation.Invoke(); - } - } - - void Lock(Action operation) - { - lock (Mutex) - { - operation.Invoke(); - } - } - - ICollection> Elements => Storage as ICollection>; - - Dictionary Storage { get; set; } = new Dictionary { }; - - public ICollection Keys => Storage.Keys; - - public ICollection Values => Storage.Values; - - public int Count => Storage.Count; - - public bool IsReadOnly => Elements.IsReadOnly; - - public object this[string key] - { - get => Storage[key]; - set => throw new NotSupportedException(FileBackedCacheSynchronousMutationNotSupportedMessage); - } - } - - /// - /// Set this for systems (Unity based Android, iOs, etc.) that may not - /// be able to access Environment.SpecialFolder.LocalApplicationData - /// - public static string BaseFilePath { get; set; } - - FileInfo File { get; set; } - FileBackedCache Cache { get; set; } - - /// - /// Creates a Moralis storage controller and attempts to extract a previously created settings storage file from the persistent storage location. - /// - public MoralisCacheService() { } - - /// - /// Creates a Moralis storage controller with the provided wrapper. - /// - /// The file wrapper that the storage controller instance should target - public MoralisCacheService(FileInfo file) => EnsureCacheExists(file); - - FileBackedCache EnsureCacheExists(FileInfo file = default) => Cache ??= new FileBackedCache(file ?? (File ??= PersistentCacheFile)); - - /// - /// Loads a settings dictionary from the file wrapped by . - /// - /// A storage dictionary containing the deserialized content of the storage file targeted by the instance - public async Task> LoadAsync() - { - // Check if storage dictionary is already created from the controllers file (create if not) - EnsureCacheExists(); - - // Load storage dictionary content async and return the resulting dictionary type - //return Queue.Enqueue(toAwait => toAwait.ContinueWith(_ => Cache.LoadAsync().OnSuccess(_ => Cache as IDataCache)).Unwrap(), CancellationToken.None); - await Cache.LoadAsync(); - - return Cache as IDataCache; - } - - /// - /// Saves the requested data. - /// - /// The data to be saved. - /// A data cache containing the saved data. - public async Task> SaveAsync(IDictionary contents) - { - EnsureCacheExists(); - Cache.Save(); - return Cache as IDataCache; - } - - /// - /// - /// - public void RefreshPaths() => Cache = new FileBackedCache(File = PersistentCacheFile); - - /// - /// Clears the data controlled by this class. - /// - public void Clear() - { - if (new FileInfo(FallbackRelativeCacheFilePath) is { Exists: true } file) - { - file.Delete(); - } - } - - /// - /// - /// - public string RelativeCacheFilePath { get; set; } - - /// - /// - /// - public string AbsoluteCacheFilePath - { - get => StoredAbsoluteCacheFilePath ?? Path.GetFullPath(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), RelativeCacheFilePath ?? FallbackRelativeCacheFilePath)); - set => StoredAbsoluteCacheFilePath = value; - } - - string StoredAbsoluteCacheFilePath { get; set; } - - /// - /// Gets the calculated persistent storage file fallback path for this app execution. - /// - public string FallbackRelativeCacheFilePath => StoredFallbackRelativeCacheFilePath ??= IdentifierBasedRelativeCacheLocationGenerator.Fallback.GetRelativeCacheFilePath(new MutableServiceHub { CacheService = this }); - - string StoredFallbackRelativeCacheFilePath { get; set; } - - /// - /// Gets or creates the file pointed to by and returns it's wrapper as a instance. - /// - public FileInfo PersistentCacheFile - { - get - { - Directory.CreateDirectory(AbsoluteCacheFilePath.Substring(0, AbsoluteCacheFilePath.LastIndexOf(Path.DirectorySeparatorChar))); - - FileInfo file = new FileInfo(AbsoluteCacheFilePath); - if (!file.Exists) - using (file.Create()) - { - } - - // Hopefully the JIT doesn't no-op this. The behaviour of the "using" clause should dictate how the stream is closed, to make sure it happens properly. - - return file; - } - } - - /// - /// Gets the file wrapper for the specified . - /// - /// The relative path to the target file - /// An instance of wrapping the the value - public FileInfo GetRelativeFile(string path) - { - return DefineRelativeFilePath(path); - } - - public static FileInfo DefineRelativeFilePath(string path) - { - string basePath = BaseFilePath ?? Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - Directory.CreateDirectory((path = Path.GetFullPath(Path.Combine(basePath, path))).Substring(0, path.LastIndexOf(Path.DirectorySeparatorChar))); - return new FileInfo(path); - } - // MoveAsync - - /// - /// Transfers a file from to . - /// - /// - /// - /// A task that completes once the file move operation form to completes. - public async Task TransferAsync(string originFilePath, string targetFilePath) - { - if (!String.IsNullOrWhiteSpace(originFilePath) && - !String.IsNullOrWhiteSpace(targetFilePath)) - { - FileInfo originFile = new FileInfo(originFilePath); - FileInfo targetFile = new FileInfo(targetFilePath); - - if (originFile.Exists && targetFile != null) - { - using StreamWriter writer = new StreamWriter(targetFile.OpenWrite(), Encoding.Unicode); - using StreamReader reader = new StreamReader(originFile.OpenRead(), Encoding.Unicode); - - await writer.WriteAsync(await reader.ReadToEndAsync()); - } - } - } - } - -} diff --git a/MoralisDotNet/Moralis/Platform/Services/Infrastructure/MoralisCurrentUserService.cs b/MoralisDotNet/Moralis/Platform/Services/Infrastructure/MoralisCurrentUserService.cs deleted file mode 100644 index 9c6d5c3..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/Infrastructure/MoralisCurrentUserService.cs +++ /dev/null @@ -1,128 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Utilities; - -namespace Moralis.Platform.Services.Infrastructure -{ - public class MoralisCurrentUserService : ICurrentUserService where TUser : MoralisUser - { - TUser currentUser; - - object Mutex { get; } = new object { }; - - ICacheService StorageController { get; } - - IJsonSerializer JsonSerializer { get; } - - public MoralisCurrentUserService(ICacheService storageController, IJsonSerializer jsonSerializer) => (StorageController, JsonSerializer) = (storageController, jsonSerializer); - - - public TUser CurrentUser - { - get - { - lock (Mutex) - return currentUser; - } - set - { - lock (Mutex) - currentUser = value; - } - } - - public async Task SetAsync(TUser user, CancellationToken cancellationToken) - { - if (user is null) - { - IDataCache loadResp = await StorageController.LoadAsync(); - await loadResp.RemoveAsync(nameof(CurrentUser)); - } - else - { - string data = JsonSerializer.Serialize(user); - - IDataCache loadResp = await StorageController.LoadAsync(); - await loadResp.AddAsync(nameof(CurrentUser), data); - } - - CurrentUser = user; - } - - public async Task GetAsync(IServiceHub serviceHub, CancellationToken cancellationToken = default) - { - TUser cachedCurrent = null; - - lock (Mutex) - cachedCurrent = CurrentUser; - - if (cachedCurrent == null) - { - object data = default; - IDataCache loadResp = await StorageController.LoadAsync(); - loadResp.TryGetValue(nameof(CurrentUser), out data); - TUser user = default; - - if (data is string) - { - user = (TUser)JsonSerializer.Deserialize(data.ToString()); - CurrentUser = user; - cachedCurrent = user; - } - } - - return cachedCurrent; - } - - public async Task ExistsAsync(CancellationToken cancellationToken) - { - bool result = true; - - if (CurrentUser == null) - { - IDataCache loadResp = await StorageController.LoadAsync(); - result = loadResp.ContainsKey(nameof(CurrentUser)); - } - - return result; - } - - public bool IsCurrent(TUser user) - { - lock (Mutex) - return CurrentUser == user; - } - - public void ClearFromMemory() => CurrentUser = default; - - public async Task ClearFromDiskAsync() - { - lock (Mutex) - { - ClearFromMemory(); - } - - IDataCache loadResp = await StorageController.LoadAsync(); - await loadResp.RemoveAsync(nameof(CurrentUser)); - } - - public async Task GetCurrentSessionTokenAsync(IServiceHub serviceHub, CancellationToken cancellationToken = default) - { - string result = null; - TUser user = await GetAsync(serviceHub, cancellationToken); - result = user?.sessionToken; - - return result; - } - - public async Task LogOutAsync(IServiceHub serviceHub, CancellationToken cancellationToken = default) - { - TUser user = await GetAsync(serviceHub, cancellationToken); - await ClearFromDiskAsync(); - } - - } -} diff --git a/MoralisDotNet/Moralis/Platform/Services/Infrastructure/MoralisQueryService.cs b/MoralisDotNet/Moralis/Platform/Services/Infrastructure/MoralisQueryService.cs deleted file mode 100644 index 0ce150a..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/Infrastructure/MoralisQueryService.cs +++ /dev/null @@ -1,94 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using Moralis.Platform.Utilities; -using System.Threading.Tasks; -using System.Net; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Queries; -using Moralis.Platform.Services.ClientServices; -using Moralis.Platform.Services.Models; - -namespace Moralis.Platform.Services.Infrastructure -{ - internal class MoralisQueryService : IQueryService - { - - IMoralisCommandRunner CommandRunner { get; } - - IJsonSerializer JsonSerializer { get; } - string SessionToken { get; } - //IMoralisDataDecoder Decoder { get; } - - public IObjectService ObjectService { get; } - - public MoralisQueryService(IMoralisCommandRunner commandRunner, string sessionToken, IJsonSerializer jsonSerializer, IObjectService objectService) => (CommandRunner, SessionToken, JsonSerializer, ObjectService) = (commandRunner, sessionToken, jsonSerializer, objectService); - - public async Task> FindAsync(MoralisQuery query, string sessionToken, CancellationToken cancellationToken = default) where T : MoralisObject - { - string result = await FindAsync(query.ClassName, query.BuildParameters(), sessionToken, cancellationToken); - - return JsonSerializer.Deserialize>(result) as IEnumerable; - } - - public async Task> AggregateAsync(MoralisQuery query, string sessionToken, CancellationToken cancellationToken = default) where T : MoralisObject - { - string aggResp = await AggregateAsync(query.ClassName, query.BuildParameters(), sessionToken, cancellationToken); - return JsonSerializer.Deserialize>(aggResp) as IEnumerable; - } - - public async Task CountAsync(MoralisQuery query, string sessionToken, CancellationToken cancellationToken = default) where T : MoralisObject - { - IDictionary parameters = query.BuildParameters(); - parameters["limit"] = 0; - parameters["count"] = 1; - - string findResp = await FindAsync(query.ClassName, parameters, sessionToken, cancellationToken); - - CountQueryResult result = JsonSerializer.Deserialize(findResp); - - return result.count; - } - - public async Task> DistinctAsync(MoralisQuery query, string sessionToken, CancellationToken cancellationToken = default) where T : MoralisObject - { - IDictionary parameters = query.BuildParameters(); - parameters["distinct"] = ""; // key - parameters["where"] = ""; // where ? - parameters["hint"] = ""; // hint - - string aggResp = await AggregateAsync(query.ClassName, parameters, sessionToken, cancellationToken); - - return JsonSerializer.Deserialize>(aggResp) as IEnumerable; - } - - public async Task FirstAsync(MoralisQuery query, string sessionToken, CancellationToken cancellationToken = default) where T : MoralisObject - { - IDictionary parameters = query.BuildParameters(); - parameters["limit"] = 1; - - string findResp = await FindAsync(query.ClassName, parameters, sessionToken, cancellationToken); - - IList l = JsonSerializer.Deserialize>(findResp); - - return l.FirstOrDefault(); - } - - async Task FindAsync(string className, IDictionary parameters, string sessionToken, CancellationToken cancellationToken = default) - { - Tuple cmdResult = await CommandRunner.RunCommandAsync(new MoralisCommand($"server/classes/{Uri.EscapeDataString(className)}?{MoralisService.BuildQueryString(parameters)}", method: "GET", sessionToken: sessionToken, data: null), cancellationToken: cancellationToken); - - return cmdResult.Item2; - } - - async Task AggregateAsync(string className, IDictionary parameters, string sessionToken, CancellationToken cancellationToken = default) - { - Tuple cmdResult = await CommandRunner.RunCommandAsync(new MoralisCommand($"server/aggregate/{Uri.EscapeDataString(className)}?{MoralisService.BuildQueryString(parameters)}", method: "GET", sessionToken: sessionToken, data: null), cancellationToken: cancellationToken); - - return cmdResult.Item2; - } - - } -} diff --git a/MoralisDotNet/Moralis/Platform/Services/Models/CountQueryResult.cs b/MoralisDotNet/Moralis/Platform/Services/Models/CountQueryResult.cs deleted file mode 100644 index 62c1426..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/Models/CountQueryResult.cs +++ /dev/null @@ -1,11 +0,0 @@ - -namespace Moralis.Platform.Services.Models -{ - internal class CountQueryResult - { - public CountQueryResult() { } - - // [JsonProperty("count")] - public int count { get; set; } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Services/Models/DataTransferLevel.cs b/MoralisDotNet/Moralis/Platform/Services/Models/DataTransferLevel.cs deleted file mode 100644 index d03f410..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/Models/DataTransferLevel.cs +++ /dev/null @@ -1,18 +0,0 @@ - -using System; -using Moralis.Platform.Abstractions; - -namespace Moralis.Platform.Services.Models -{ - /// - /// Represents upload progress. - /// - public class DataTransferLevel : EventArgs, IDataTransferLevel - { - public DataTransferLevel() { } - /// - /// Gets the progress (a number between 0.0 and 1.0) of an upload or download. - /// - public double Amount { get; set; } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Services/Models/MoralisCommand.cs b/MoralisDotNet/Moralis/Platform/Services/Models/MoralisCommand.cs deleted file mode 100644 index 348db3b..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/Models/MoralisCommand.cs +++ /dev/null @@ -1,58 +0,0 @@ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using Moralis.Platform.Utilities; - -namespace Moralis.Platform.Services.Models -{ - /// - /// ParseCommand is an with pre-populated - /// headers. - /// - public class MoralisCommand : WebRequest - { - //public IDictionary DataObject { get; private set; } - public string DataObject { get; private set; } - - public override Stream Data - { - //get => base.Data ??= DataObject is { } ? new MemoryStream(Encoding.UTF8.GetBytes(JsonUtilities.Encode(DataObject))) : default; - get => base.Data ??= DataObject is { } ? new MemoryStream(Encoding.UTF8.GetBytes(DataObject)) : default; - set => base.Data = value; - } - - //public MoralisCommand(string relativeUri, string method, string sessionToken = null, IList> headers = null, IDictionary data = null) : this(relativeUri: relativeUri, method: method, sessionToken: sessionToken, headers: headers, stream: null, contentType: data != null ? "application/json" : null) => DataObject = data; - public MoralisCommand(string relativeUri, string method, string sessionToken = null, IList> headers = null, string data = null) : this(relativeUri: relativeUri, method: method, sessionToken: sessionToken, headers: headers, stream: null, contentType: data != null ? "application/json" : null) => DataObject = data; - - public MoralisCommand(string relativeUri, string method, string sessionToken = null, IList> headers = null, Stream stream = null, string contentType = null) - { - Path = relativeUri; - Method = method; - Data = stream; - Headers = new List>(headers ?? Enumerable.Empty>()); - - if (!String.IsNullOrEmpty(sessionToken)) - { - Headers.Add(new KeyValuePair("X-Parse-Session-Token", sessionToken)); - } - - if (!String.IsNullOrEmpty(contentType)) - { - Headers.Add(new KeyValuePair("Content-Type", contentType)); - } - } - - public MoralisCommand(MoralisCommand other) - { - Resource = other.Resource; - Path = other.Path; - Method = other.Method; - DataObject = other.DataObject; - Headers = new List>(other.Headers); - Data = other.Data; - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Services/Models/WebRequest.cs b/MoralisDotNet/Moralis/Platform/Services/Models/WebRequest.cs deleted file mode 100644 index b46e1d9..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/Models/WebRequest.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; - -namespace Moralis.Platform.Services.Models -{ - /// - /// IHttpRequest is an interface that provides an API to execute HTTP request data. - /// - public class WebRequest - { - public Uri Target => new Uri(new Uri(Resource), Path); - - public string Resource { get; set; } - - public string Path { get; set; } - - public IList> Headers { get; set; } - - /// - /// Data stream to be uploaded. - /// - public virtual Stream Data { get; set; } - - /// - /// HTTP method. One of DELETE, GET, HEAD, POST or PUT - /// - public string Method { get; set; } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Services/MutableServiceHub.cs b/MoralisDotNet/Moralis/Platform/Services/MutableServiceHub.cs deleted file mode 100644 index c08b129..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/MutableServiceHub.cs +++ /dev/null @@ -1,102 +0,0 @@ -using System; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Services.ClientServices; -using Moralis.Platform.Services.Infrastructure; - -namespace Moralis.Platform.Services -{ - /// - /// A service hub that is mutable. - /// - /// This class is not thread safe; the mutability is allowed for the purposes of overriding values before it is used, as opposed to modifying it while it is in use. - public class MutableServiceHub : IMutableServiceHub where TUser : MoralisUser - { - /// - /// Included so that this can be set prior to initialization for systems - /// (Unity, Xamarin, etc.) that may not have Assembly Attributes available. - /// - public static HostManifestData ManifestData { get; set; } - - public MutableServiceHub() { AlwaysSave = true; } - - public bool AlwaysSave { get; set; } - - public IServerConnectionData ServerConnectionData { get; set; } - - public IMetadataService MetadataService { get; set; } - - public IJsonSerializer JsonSerializer { get; set; } - - public IWebClient WebClient { get; set; } - public ICacheService CacheService { get; set; } - - public IInstallationService InstallationService { get; set; } - - public IMoralisCommandRunner CommandRunner { get; set; } - - public ICloudFunctionService CloudFunctionService { get; set; } - //public IParseConfigurationController ConfigurationController { get; set; } - public IFileService FileService { get; set; } - public IObjectService ObjectService { get; set; } - public IQueryService QueryService { get; set; } - public ISessionService SessionService { get; set; } - - public IUserService UserService { get; set; } - - public ICurrentUserService CurrentUserService { get; set; } - - public T Create(object[] parameters) where T : MoralisObject - { - T thing; - - if (parameters is { } && parameters.Length > 0) - thing = (T)Activator.CreateInstance(typeof(T), parameters); - else - thing = (T)Activator.CreateInstance(typeof(T)); - - thing.sessionToken = this.CurrentUserService.CurrentUser.sessionToken; - thing.ObjectService = this.ObjectService; - - return thing; - } - - public MutableServiceHub SetDefaults(IServerConnectionData connectionData = default) - { - ServerConnectionData ??= connectionData; - MetadataService ??= new MetadataService - { - EnvironmentData = EnvironmentData.Inferred, - HostManifestData = ManifestData ?? HostManifestData.Inferred - }; - - - WebClient ??= new UniversalWebClient { }; - CacheService ??= new MoralisCacheService (MoralisCacheService.DefineRelativeFilePath("Moralis\\moralis.cachefile")); - - InstallationService ??= new InstallationService(CacheService); - CommandRunner ??= new MoralisCommandRunner(WebClient, InstallationService, MetadataService, ServerConnectionData, new Lazy>(() => UserService)); - - CloudFunctionService ??= new MoralisCloudFunctionService(CommandRunner, ServerConnectionData, JsonSerializer); - //ConfigurationController ??= new ParseConfigurationController(CommandRunner, CacheController, Decoder); - FileService ??= new MoralisFileService(CommandRunner, JsonSerializer); - ObjectService ??= new MoralisObjectService(CommandRunner, ServerConnectionData, JsonSerializer); - QueryService ??= new MoralisQueryService(CommandRunner, this.CurrentUserService.CurrentUser.sessionToken, JsonSerializer, ObjectService); - SessionService ??= new MoralisSessionService(CommandRunner, JsonSerializer); - UserService ??= new MoralisUserService(CommandRunner, ObjectService, JsonSerializer); - CurrentUserService ??= new MoralisCurrentUserService(CacheService, JsonSerializer); - - //AnalyticsController ??= new ParseAnalyticsController(CommandRunner); - - //InstallationCoder ??= new ParseInstallationCoder(Decoder, ClassController); - - //PushController ??= new ParsePushController(CommandRunner, CurrentUserController); - //CurrentInstallationController ??= new ParseCurrentInstallationController(InstallationController, CacheController, InstallationCoder, ClassController); - //PushChannelsController ??= new ParsePushChannelsController(CurrentInstallationController); - //InstallationDataFinalizer ??= new ParseInstallationDataFinalizer { }; - - return this; - } - } - -} diff --git a/MoralisDotNet/Moralis/Platform/Services/OrchestrationServiceHub.cs b/MoralisDotNet/Moralis/Platform/Services/OrchestrationServiceHub.cs deleted file mode 100644 index b2437f2..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/OrchestrationServiceHub.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Services -{ - public class OrchestrationServiceHub : IServiceHub where TUser : MoralisUser - { - public OrchestrationServiceHub() - { - AlwaysSave = true; - } - - public bool AlwaysSave { get; set; } - public IServiceHub Default { get; set; } - - public IServiceHub Custom { get; set; } - - //public IServiceHubCloner Cloner => Custom.Cloner ?? Default.Cloner; - - public IMetadataService MetadataService => Custom.MetadataService ?? Default.MetadataService; - - public IJsonSerializer JsonSerializer => Custom.JsonSerializer ?? Default.JsonSerializer; - - public IWebClient WebClient => Custom.WebClient ?? Default.WebClient; - - public ICacheService CacheService => Custom.CacheService ?? Default.CacheService; - - public IInstallationService InstallationService => Custom.InstallationService ?? Default.InstallationService; - - public IMoralisCommandRunner CommandRunner => Custom.CommandRunner ?? Default.CommandRunner; - - public ICloudFunctionService CloudFunctionService => Custom.CloudFunctionService ?? Default.CloudFunctionService; - - //public IParseConfigurationController ConfigurationController => Custom.ConfigurationController ?? Default.ConfigurationController; - - public IFileService FileService => Custom.FileService ?? Default.FileService; - - public IObjectService ObjectService => Custom.ObjectService ?? Default.ObjectService; - - public IQueryService QueryService => Custom.QueryService ?? Default.QueryService; - - public ISessionService SessionService => Custom.SessionService ?? Default.SessionService; - - public IUserService UserService => Custom.UserService ?? Default.UserService; - - public ICurrentUserService CurrentUserService => Custom.CurrentUserService ?? Default.CurrentUserService; - - //public IParseAnalyticsController AnalyticsController => Custom.AnalyticsController ?? Default.AnalyticsController; - - //public IParsePushChannelsController PushChannelsController => Custom.PushChannelsController ?? Default.PushChannelsController; - - //public IParsePushController PushController => Custom.PushController ?? Default.PushController; - - public IInstallationService InstallationController => Custom.InstallationService ?? Default.InstallationService; - - public IServerConnectionData ServerConnectionData => Custom.ServerConnectionData ?? Default.ServerConnectionData; - - - public T Create(object[] parameters) where T : MoralisObject - { - T thing; - - if (parameters is { } && parameters.Length > 0) - thing = (T)Activator.CreateInstance(typeof(T), parameters); - else - thing = (T)Activator.CreateInstance(typeof(T)); - - thing.sessionToken = this.CurrentUserService.CurrentUser.sessionToken; - thing.ObjectService = this.ObjectService; - - return thing; - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Services/RelativeCacheLocationMutator.cs b/MoralisDotNet/Moralis/Platform/Services/RelativeCacheLocationMutator.cs deleted file mode 100644 index 45764e9..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/RelativeCacheLocationMutator.cs +++ /dev/null @@ -1,35 +0,0 @@ -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Services.Infrastructure; - -namespace Moralis.Platform.Services -{ - /// - /// An for the relative cache file location. This should be used if the relative cache file location is not created correctly by the SDK, such as platforms on which it is not possible to gather metadata about the client assembly, or ones on which is inaccsessible. - /// - public class RelativeCacheLocationMutator : IServiceHubMutator - { - /// - /// An implementation instance which creates a path that should be used as the -relative cache location. - /// - public IRelativeCacheLocationGenerator RelativeCacheLocationGenerator { get; set; } - - /// - /// - /// - public bool Valid => RelativeCacheLocationGenerator is { }; - - /// - /// - /// - /// - /// - public void Mutate(ref IMutableServiceHub target, in IServiceHub referenceHub) where TUser : MoralisUser => target.CacheService = (target as IServiceHub).CacheService switch - { - null => new MoralisCacheService { RelativeCacheFilePath = RelativeCacheLocationGenerator.GetRelativeCacheFilePath(referenceHub) }, - IDiskFileCacheService { } controller => (Controller: controller, controller.RelativeCacheFilePath = RelativeCacheLocationGenerator.GetRelativeCacheFilePath(referenceHub)).Controller, - { } controller => controller - }; - } - -} diff --git a/MoralisDotNet/Moralis/Platform/Services/ServiceHub.cs b/MoralisDotNet/Moralis/Platform/Services/ServiceHub.cs deleted file mode 100644 index 2a21677..0000000 --- a/MoralisDotNet/Moralis/Platform/Services/ServiceHub.cs +++ /dev/null @@ -1,99 +0,0 @@ -using System; -using System.Net.Http; -using Moralis.Platform.Abstractions; -using Moralis.Platform.Objects; -using Moralis.Platform.Services.ClientServices; -using Moralis.Platform.Services.Infrastructure; -using Moralis.Platform.Utilities; - -namespace Moralis.Platform.Services -{ - /// - /// A service hub that uses late initialization to efficiently provide controllers and other dependencies to internal Moralis SDK systems. - /// - public class ServiceHub : IServiceHub where TUser : MoralisUser - { - private static ServiceHub instance; - - #region Instance - public bool AlwaysSave { get; set; } - LateInitializer LateInitializer { get; } = new LateInitializer { }; - private UniversalWebClient webClient; - - public ServiceHub() - { - webClient = new UniversalWebClient { }; - } - - public ServiceHub(IServerConnectionData connectionData, IJsonSerializer jsonSerializer, HttpClient httpClient = null) - { - //httpClient = httpClient is { } ? httpClient : new HttpClient(); - webClient = new UniversalWebClient(); - httpClient.DefaultRequestHeaders.Remove("IfModifiedSince"); - ServerConnectionData ??= connectionData; - JsonSerializer = jsonSerializer is { } ? jsonSerializer : throw new ArgumentException("jsonSerializer cannot be null."); - - AlwaysSave = true; - } - - /// - /// Included so that this can be set prior to initialization for systems - /// (Unity, Xamarin, etc.) that may not have Assembly Attributes available. - /// - public static HostManifestData ManifestData { get; set; } - - public IServerConnectionData ServerConnectionData { get; set; } - /// - /// Provides Serialization / Deserialization services. - /// - public IJsonSerializer JsonSerializer { get; set; } - public IMetadataService MetadataService => LateInitializer.GetValue(() => new MetadataService { HostManifestData = ManifestData ?? HostManifestData.Inferred, EnvironmentData = EnvironmentData.Inferred }); - - public IWebClient WebClient => LateInitializer.GetValue(() => webClient); - public ICacheService CacheService => LateInitializer.GetValue(() => new MoralisCacheService (MoralisCacheService.DefineRelativeFilePath("Moralis\\moralis.cachefile"))); - public IInstallationService InstallationService => LateInitializer.GetValue(() => new InstallationService(CacheService)); - public IMoralisCommandRunner CommandRunner => LateInitializer.GetValue(() => new MoralisCommandRunner(WebClient, InstallationService, MetadataService, ServerConnectionData, new Lazy>(() => UserService))); - public IUserService UserService => LateInitializer.GetValue(() => new MoralisUserService(CommandRunner, ObjectService, JsonSerializer)); - public ICurrentUserService CurrentUserService => LateInitializer.GetValue(() => new MoralisCurrentUserService(CacheService, JsonSerializer)); - public IObjectService ObjectService => LateInitializer.GetValue(() => new MoralisObjectService(CommandRunner, ServerConnectionData, JsonSerializer)); - public IQueryService QueryService => LateInitializer.GetValue(() => new MoralisQueryService(CommandRunner, this.CurrentUserService.CurrentUser?.sessionToken, JsonSerializer, ObjectService)); - public ISessionService SessionService => LateInitializer.GetValue(() => new MoralisSessionService(CommandRunner, JsonSerializer)); - public ICloudFunctionService CloudFunctionService => LateInitializer.GetValue(() => new MoralisCloudFunctionService(CommandRunner, ServerConnectionData, JsonSerializer)); - public IFileService FileService => LateInitializer.GetValue(() => new MoralisFileService(CommandRunner, JsonSerializer)); - - - public bool Reset() => LateInitializer.Used && LateInitializer.Reset(); - - public T Create(object[] parameters) where T : MoralisObject - { - T thing; - - if (parameters is { } && parameters.Length > 0) - thing = (T)Activator.CreateInstance(typeof(T), parameters); - else - thing = (T)Activator.CreateInstance(typeof(T)); - - thing.sessionToken = this.CurrentUserService.CurrentUser?.sessionToken; - thing.ObjectService = this.ObjectService; - - return thing; - } - #endregion - - public static ServiceHub GetInstance() { - if (!(instance is { })) - instance = new ServiceHub(); - - return instance; - } - - public static ServiceHub GetInstance(IServerConnectionData connectionData, HttpClient httpClient = null, IJsonSerializer jsonSerializer = null) - { - if (!(instance is { })) - instance = new ServiceHub(connectionData, jsonSerializer, httpClient); - - return instance; - } - } - -} diff --git a/MoralisDotNet/Moralis/Platform/Utilities/AssemblyLister.cs b/MoralisDotNet/Moralis/Platform/Utilities/AssemblyLister.cs deleted file mode 100644 index 7cd7663..0000000 --- a/MoralisDotNet/Moralis/Platform/Utilities/AssemblyLister.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; - -namespace Moralis.Platform.Utilities -{ - /// - /// A class that lets you list all loaded assemblies in a PCL-compliant way. - /// - public static class Lister - { - /// - /// Get all of the assemblies used by this application. - /// - public static IEnumerable AllAssemblies - { - get - { - // For each of the loaded assemblies, deeply walk all of their references. - HashSet seen = new HashSet(); - return AppDomain.CurrentDomain.GetAssemblies().SelectMany(asm => asm.DeepWalkReferences(seen)); - } - } - - private static IEnumerable DeepWalkReferences(this Assembly assembly, HashSet seen = null) - { - seen ??= new HashSet(); - - if (!seen.Add(assembly.FullName)) - return Enumerable.Empty(); - - List assemblies = new List { assembly }; - - foreach (AssemblyName reference in assembly.GetReferencedAssemblies()) - { - if (seen.Contains(reference.FullName)) - continue; - - Assembly referencedAsm = Assembly.Load(reference); - assemblies.AddRange(referencedAsm.DeepWalkReferences(seen)); - } - - return assemblies; - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Utilities/Conversion.cs b/MoralisDotNet/Moralis/Platform/Utilities/Conversion.cs deleted file mode 100644 index 75a79f8..0000000 --- a/MoralisDotNet/Moralis/Platform/Utilities/Conversion.cs +++ /dev/null @@ -1,140 +0,0 @@ - -using System; -using System.Collections.Generic; - -namespace Moralis.Platform.Utilities -{ - - /// - /// A set of utilities for converting generic types between each other. - /// - public static class Conversion - { - /// - /// Converts a value to the requested type -- coercing primitives to - /// the desired type, wrapping lists and dictionaries appropriately, - /// or else returning null. - /// - /// This should be used on any containers that might be coming from a - /// user to normalize the collection types. Collection types coming from - /// JSON deserialization can be safely assumed to be lists or dictionaries of - /// objects. - /// - public static T As(object value) where T : class => ConvertTo(value) as T; - - /// - /// Converts a value to the requested type -- coercing primitives to - /// the desired type, wrapping lists and dictionaries appropriately, - /// or else throwing an exception. - /// - /// This should be used on any containers that might be coming from a - /// user to normalize the collection types. Collection types coming from - /// JSON deserialization can be safely assumed to be lists or dictionaries of - /// objects. - /// - public static T To(object value) => (T) ConvertTo(value); - - /// - /// Converts a HTTP/HTTPS Uri to WS/WSS. - /// - /// - /// - public static string WebUriToWsURi(string source) - { - string wsUri = default; - - if (source is { }) - { - Uri r = new Uri(source.ToLower()); - - // Already a ws/wss uri, return source. - if (r.Scheme.Equals("ws") || r.Scheme.Equals("wss")) return source; - - // Determine scheme - string scheme = r.Scheme switch - { - "https" => "wss", - "http" => "ws", - _ => "wss" - }; - - // Determin port value. - string port = (r) switch - { - // Port 80 does not need to be specified if scheme is http. - { Port: 80, Scheme: "http" } => "", - // Port 443 does not need to be specified if scheme is https. - { Port: 443, Scheme: "https" } => "", - // Default is specified port. - _ => $":{r.Port}" - }; - - // Build WS/WSS Uri. - wsUri = $"{scheme}://{r.Host}{port}{r.AbsolutePath}"; - } - - return wsUri; - } - - /// - /// Converts a value to the requested type -- coercing primitives to - /// the desired type, wrapping lists and dictionaries appropriately, - /// or else passing the object along to the caller unchanged. - /// - /// This should be used on any containers that might be coming from a - /// user to normalize the collection types. Collection types coming from - /// JSON deserialization can be safely assumed to be lists or dictionaries of - /// objects. - /// - internal static object ConvertTo(object value) - { - if (value is T || value == null) - return value; - - if (typeof(T).IsPrimitive) - return (T) Convert.ChangeType(value, typeof(T), System.Globalization.CultureInfo.InvariantCulture); - - if (typeof(T).IsConstructedGenericType) - { - // Add lifting for nullables. Only supports conversions between primitives. - - if (typeof(T).CheckWrappedWithNullable() && typeof(T).GenericTypeArguments[0] is { IsPrimitive: true } innerType) - return (T) Convert.ChangeType(value, innerType, System.Globalization.CultureInfo.InvariantCulture); - - if (GetInterfaceType(value.GetType(), typeof(IList<>)) is { } listType && typeof(T).GetGenericTypeDefinition() == typeof(IList<>)) - return Activator.CreateInstance(typeof(FlexibleListWrapper<,>).MakeGenericType(typeof(T).GenericTypeArguments[0], listType.GenericTypeArguments[0]), value); - - if (GetInterfaceType(value.GetType(), typeof(IDictionary<,>)) is { } dictType && typeof(T).GetGenericTypeDefinition() == typeof(IDictionary<,>)) - return Activator.CreateInstance(typeof(FlexibleDictionaryWrapper<,>).MakeGenericType(typeof(T).GenericTypeArguments[1], dictType.GenericTypeArguments[1]), value); - } - - return value; - } - - /// - /// Holds a dictionary that maps a cache of interface types for related concrete types. - /// The lookup is slow the first time for each type because it has to enumerate all interface - /// on the object type, but made fast by the cache. - /// - /// The map is: - /// (object type, generic interface type) => constructed generic type - /// - static Dictionary, Type> InterfaceLookupCache { get; } = new Dictionary, Type>(); - - static Type GetInterfaceType(Type objType, Type genericInterfaceType) - { - Tuple cacheKey = new Tuple(objType, genericInterfaceType); - - if (InterfaceLookupCache.ContainsKey(cacheKey)) - return InterfaceLookupCache[cacheKey]; - - foreach (Type type in objType.GetInterfaces()) - if (type.IsConstructedGenericType && type.GetGenericTypeDefinition() == genericInterfaceType) - return InterfaceLookupCache[cacheKey] = type; - - return default; - } - - - } -} \ No newline at end of file diff --git a/MoralisDotNet/Moralis/Platform/Utilities/FileUtilities.cs b/MoralisDotNet/Moralis/Platform/Utilities/FileUtilities.cs deleted file mode 100644 index 3f3e35b..0000000 --- a/MoralisDotNet/Moralis/Platform/Utilities/FileUtilities.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System.IO; -using System.Text; -using System.Threading.Tasks; - -#pragma warning disable 1998 - -namespace Moralis.Platform.Utilities -{ - /// - /// WARNING File cache will not work in WebGL at this time, use a memory cache - /// as a replacement for use in WebGL. - /// A collection of utility methods and properties for writing to the - /// app-specific persistent storage folder. - /// - internal static class FileUtilities - { - -#if UNITY_WEBGL - private static string cacheData = null; -#else - private static string lockObj = "\0"; -#endif - /// - /// Asynchronously read all of the little-endian 16-bit character units (UTF-16) contained within the file wrapped by the provided instance. - /// - /// The instance wrapping the target file that string content is to be read from - /// A task that should contain the little-endian 16-bit character string (UTF-16) extracted from the if the read completes successfully - public static async Task ReadAllTextAsync(this FileInfo file) - { - // WARNING File cache will not work in WebGL at this time -#if UNITY_WEBGL - return await Task.FromResult(cacheData); -#else - string data = null; - lock (lockObj) - { - using StreamReader reader = new StreamReader(file.OpenRead(), Encoding.Unicode); - data = reader.ReadToEnd(); - } - - return data; -#endif - } - - /// - /// Asynchronously writes the provided little-endian 16-bit character string to the file wrapped by the provided instance. - /// - /// The instance wrapping the target file that is to be written to - /// The little-endian 16-bit Unicode character string (UTF-16) that is to be written to the - /// A task that completes once the write operation to the completes - public static void WriteContent(this FileInfo file, string content) - { -#if UNITY_WEBGL - // WARNING File cache will not work in WebGL at this time - cacheData = content; -#else - lock (lockObj) - { - using FileStream stream = new FileStream(Path.GetFullPath(file.FullName), FileMode.Create, FileAccess.Write, FileShare.Read, 4096, FileOptions.SequentialScan | FileOptions.Asynchronous); - byte[] data = Encoding.Unicode.GetBytes(content); - - stream.Write(data, 0, data.Length); - } -#endif - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Utilities/FlexibleDictionaryWrapper.cs b/MoralisDotNet/Moralis/Platform/Utilities/FlexibleDictionaryWrapper.cs deleted file mode 100644 index b727ee3..0000000 --- a/MoralisDotNet/Moralis/Platform/Utilities/FlexibleDictionaryWrapper.cs +++ /dev/null @@ -1,76 +0,0 @@ - -using System.Collections.Generic; -using System.Linq; - -namespace Moralis.Platform.Utilities -{ - /// - /// Provides a Dictionary implementation that can delegate to any other - /// dictionary, regardless of its value type. Used for coercion of - /// dictionaries when returning them to users. - /// - /// The resulting type of value in the dictionary. - /// The original type of value in the dictionary. - [Preserve(AllMembers = true, Conditional = false)] - public class FlexibleDictionaryWrapper : IDictionary - { - private readonly IDictionary toWrap; - public FlexibleDictionaryWrapper(IDictionary toWrap) => this.toWrap = toWrap; - - public void Add(string key, TOut value) => toWrap.Add(key, (TIn) Conversion.ConvertTo(value)); - - public bool ContainsKey(string key) => toWrap.ContainsKey(key); - - public ICollection Keys => toWrap.Keys; - - public bool Remove(string key) => toWrap.Remove(key); - - public bool TryGetValue(string key, out TOut value) - { - bool result = toWrap.TryGetValue(key, out TIn outValue); - value = (TOut) Conversion.ConvertTo(outValue); - return result; - } - - public ICollection Values => toWrap.Values - .Select(item => (TOut) Conversion.ConvertTo(item)).ToList(); - - public TOut this[string key] - { - get => (TOut) Conversion.ConvertTo(toWrap[key]); - set => toWrap[key] = (TIn) Conversion.ConvertTo(value); - } - - public void Add(KeyValuePair item) => toWrap.Add(new KeyValuePair(item.Key, - (TIn) Conversion.ConvertTo(item.Value))); - - public void Clear() => toWrap.Clear(); - - public bool Contains(KeyValuePair item) => toWrap.Contains(new KeyValuePair(item.Key, - (TIn) Conversion.ConvertTo(item.Value))); - - public void CopyTo(KeyValuePair[] array, int arrayIndex) - { - IEnumerable> converted = from pair in toWrap - select new KeyValuePair(pair.Key, - (TOut) Conversion.ConvertTo(pair.Value)); - converted.ToList().CopyTo(array, arrayIndex); - } - - public int Count => toWrap.Count; - - public bool IsReadOnly => toWrap.IsReadOnly; - - public bool Remove(KeyValuePair item) => toWrap.Remove(new KeyValuePair(item.Key, - (TIn) Conversion.ConvertTo(item.Value))); - - public IEnumerator> GetEnumerator() - { - foreach (KeyValuePair pair in toWrap) - yield return new KeyValuePair(pair.Key, - (TOut) Conversion.ConvertTo(pair.Value)); - } - - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Utilities/FlexibleListWrapper.cs b/MoralisDotNet/Moralis/Platform/Utilities/FlexibleListWrapper.cs deleted file mode 100644 index a4378c9..0000000 --- a/MoralisDotNet/Moralis/Platform/Utilities/FlexibleListWrapper.cs +++ /dev/null @@ -1,56 +0,0 @@ - -using System.Collections; -using System.Collections.Generic; -using System.Linq; - -namespace Moralis.Platform.Utilities -{ - /// - /// Provides a List implementation that can delegate to any other - /// list, regardless of its value type. Used for coercion of - /// lists when returning them to users. - /// - /// The resulting type of value in the list. - /// The original type of value in the list. - [Preserve(AllMembers = true, Conditional = false)] - public class FlexibleListWrapper : IList - { - private IList toWrap; - public FlexibleListWrapper(IList toWrap) => this.toWrap = toWrap; - - public int IndexOf(TOut item) => toWrap.IndexOf((TIn) Conversion.ConvertTo(item)); - - public void Insert(int index, TOut item) => toWrap.Insert(index, (TIn) Conversion.ConvertTo(item)); - - public void RemoveAt(int index) => toWrap.RemoveAt(index); - - public TOut this[int index] - { - get => (TOut) Conversion.ConvertTo(toWrap[index]); - set => toWrap[index] = (TIn) Conversion.ConvertTo(value); - } - - public void Add(TOut item) => toWrap.Add((TIn) Conversion.ConvertTo(item)); - - public void Clear() => toWrap.Clear(); - - public bool Contains(TOut item) => toWrap.Contains((TIn) Conversion.ConvertTo(item)); - - public void CopyTo(TOut[] array, int arrayIndex) => toWrap.Select(item => (TOut) Conversion.ConvertTo(item)) - .ToList().CopyTo(array, arrayIndex); - - public int Count => toWrap.Count; - - public bool IsReadOnly => toWrap.IsReadOnly; - - public bool Remove(TOut item) => toWrap.Remove((TIn) Conversion.ConvertTo(item)); - - public IEnumerator GetEnumerator() - { - foreach (object item in (IEnumerable) toWrap) - yield return (TOut) Conversion.ConvertTo(item); - } - - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Utilities/IdentityEqualityComparer.cs b/MoralisDotNet/Moralis/Platform/Utilities/IdentityEqualityComparer.cs deleted file mode 100644 index 2ac87c9..0000000 --- a/MoralisDotNet/Moralis/Platform/Utilities/IdentityEqualityComparer.cs +++ /dev/null @@ -1,18 +0,0 @@ - -using System.Collections.Generic; -using System.Runtime.CompilerServices; - -namespace Moralis.Platform.Utilities -{ - /// - /// An equality comparer that uses the object identity (i.e. ReferenceEquals) - /// rather than .Equals, allowing identity to be used for checking equality in - /// ISets and IDictionaries. - /// - public class IdentityEqualityComparer : IEqualityComparer - { - public bool Equals(T x, T y) => ReferenceEquals(x, y); - - public int GetHashCode(T obj) => RuntimeHelpers.GetHashCode(obj); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Utilities/InternalExtensions.cs b/MoralisDotNet/Moralis/Platform/Utilities/InternalExtensions.cs deleted file mode 100644 index fa9772c..0000000 --- a/MoralisDotNet/Moralis/Platform/Utilities/InternalExtensions.cs +++ /dev/null @@ -1,92 +0,0 @@ - -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Moralis.Platform.Utilities -{ - /// - /// Provides helper methods that allow us to use terser code elsewhere. - /// - public static class InternalExtensions - { - /// - /// Ensures a task (even null) is awaitable. - /// - /// - /// - /// - public static Task Safe(this Task task) - { - if (task is { }) - return task; - else - return Task.FromResult(default(T)); - } - - /// - /// Ensures a task (even null) is awaitable. - /// - /// - /// - public static Task Safe(this Task task) - { - - if (task is { }) - return task; - else - return Task.FromResult(null); - } - - public delegate void PartialAccessor(ref T arg); - - public static TValue GetOrDefault(this IDictionary self, - TKey key, - TValue defaultValue) - { - if (self.TryGetValue(key, out TValue value)) - return value; - return defaultValue; - } - - public static bool CollectionsEqual(this IEnumerable a, IEnumerable b) => Equals(a, b) || - a != null && b != null && - a.SequenceEqual(b); - - public static async void Wait(this Task task) //=> task.ContinueWith(t => - { - if (TaskStatus.Running.Equals(task.Status)) - { - await task; - } - } - - public static async Task Result(this Task task) - { - Task result = default; - - if (TaskStatus.Running.Equals(task.Status)) - await task; - - if (!task.Status.Equals(TaskStatus.Faulted) && !task.Status.Equals(TaskStatus.Canceled)) - { - result = task; - } - - return result.GetAwaiter().GetResult(); - } - - - //public static Task WhileAsync(Func> predicate, Func body) - //{ - // Func iterate = null; - // iterate = () => predicate().OnSuccess(t => - // { - // if (!t.Result) - // return Task.FromResult(0); - // return body().OnSuccess(_ => iterate()).Unwrap(); - // }).Unwrap(); - // return iterate(); - //} - } -} diff --git a/MoralisDotNet/Moralis/Platform/Utilities/JsonUtilities.cs b/MoralisDotNet/Moralis/Platform/Utilities/JsonUtilities.cs deleted file mode 100644 index d4230b2..0000000 --- a/MoralisDotNet/Moralis/Platform/Utilities/JsonUtilities.cs +++ /dev/null @@ -1,416 +0,0 @@ - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Reflection; -using System.Text; -using System.Text.RegularExpressions; - -namespace Moralis.Platform.Utilities -{ - /// - /// A simple recursive-descent JSON Parser based on the grammar defined at http://www.json.org - /// and http://tools.ietf.org/html/rfc4627 - /// - public class JsonUtilities - { - /// - /// Place at the start of a regex to force the match to begin wherever the search starts (i.e. - /// anchored at the index of the first character of the search, even when that search starts - /// in the middle of the string). - /// - private static readonly string startOfString = "\\G"; - private static readonly char startObject = '{'; - private static readonly char endObject = '}'; - private static readonly char startArray = '['; - private static readonly char endArray = ']'; - private static readonly char valueSeparator = ','; - private static readonly char nameSeparator = ':'; - private static readonly char[] falseValue = "false".ToCharArray(); - private static readonly char[] trueValue = "true".ToCharArray(); - private static readonly char[] nullValue = "null".ToCharArray(); - private static readonly Regex numberValue = new Regex(startOfString + @"-?(?:0|[1-9]\d*)(?\.\d+)?(?(?:e|E)(?:-|\+)?\d+)?"); - private static readonly Regex stringValue = new Regex(startOfString + "\"(?(?:[^\\\\\"]|(?\\\\(?:[\\\\\"/bfnrt]|u[0-9a-fA-F]{4})))*)\"", RegexOptions.Multiline); - - private static readonly Regex escapePattern = new Regex("\\\\|\"|[\u0000-\u001F]"); - - private class JsonStringParser - { - public string Input { get; private set; } - - public char[] InputAsArray { get; private set; } - public int CurrentIndex { get; private set; } - - public void Skip(int skip) => CurrentIndex += skip; - - public JsonStringParser(string input) - { - Input = input; - InputAsArray = input.ToCharArray(); - } - - /// - /// Parses JSON object syntax (e.g. '{}') - /// - internal bool ParseObject(out object output) - { - output = null; - int initialCurrentIndex = CurrentIndex; - if (!Accept(startObject)) - return false; - - Dictionary dict = new Dictionary { }; - while (true) - { - if (!ParseMember(out object pairValue)) - break; - - Tuple pair = pairValue as Tuple; - dict[pair.Item1] = pair.Item2; - if (!Accept(valueSeparator)) - break; - } - if (!Accept(endObject)) - return false; - output = dict; - return true; - } - - /// - /// Parses JSON member syntax (e.g. '"keyname" : null') - /// - private bool ParseMember(out object output) - { - output = null; - if (!ParseString(out object key)) - return false; - if (!Accept(nameSeparator)) - return false; - if (!ParseValue(out object value)) - return false; - output = new Tuple((string) key, value); - return true; - } - - /// - /// Parses JSON array syntax (e.g. '[]') - /// - internal bool ParseArray(out object output) - { - output = null; - if (!Accept(startArray)) - return false; - List list = new List(); - while (true) - { - if (!ParseValue(out object value)) - break; - list.Add(value); - if (!Accept(valueSeparator)) - break; - } - if (!Accept(endArray)) - return false; - output = list; - return true; - } - - /// - /// Parses a value (i.e. the right-hand side of an object member assignment or - /// an element in an array) - /// - private bool ParseValue(out object output) - { - if (Accept(falseValue)) - { - output = false; - return true; - } - else if (Accept(nullValue)) - { - output = null; - return true; - } - else if (Accept(trueValue)) - { - output = true; - return true; - } - return ParseObject(out output) || - ParseArray(out output) || - ParseNumber(out output) || - ParseString(out output); - } - - /// - /// Parses a JSON string (e.g. '"foo\u1234bar\n"') - /// - private bool ParseString(out object output) - { - output = null; - if (!Accept(stringValue, out Match m)) - return false; - // handle escapes: - int offset = 0; - Group contentCapture = m.Groups["content"]; - StringBuilder builder = new StringBuilder(contentCapture.Value); - foreach (Capture escape in m.Groups["escape"].Captures) - { - int index = escape.Index - contentCapture.Index - offset; - offset += escape.Length - 1; - builder.Remove(index + 1, escape.Length - 1); - switch (escape.Value[1]) - { - case '\"': - builder[index] = '\"'; - break; - case '\\': - builder[index] = '\\'; - break; - case '/': - builder[index] = '/'; - break; - case 'b': - builder[index] = '\b'; - break; - case 'f': - builder[index] = '\f'; - break; - case 'n': - builder[index] = '\n'; - break; - case 'r': - builder[index] = '\r'; - break; - case 't': - builder[index] = '\t'; - break; - case 'u': - builder[index] = (char) UInt16.Parse(escape.Value.Substring(2), NumberStyles.AllowHexSpecifier); - break; - default: - throw new ArgumentException("Unexpected escape character in string: " + escape.Value); - } - } - output = builder.ToString(); - return true; - } - - /// - /// Parses a number. Returns a long if the number is an integer or has an exponent, - /// otherwise returns a double. - /// - private bool ParseNumber(out object output) - { - output = null; - if (!Accept(numberValue, out Match m)) - return false; - if (m.Groups["frac"].Length > 0 || m.Groups["exp"].Length > 0) - { - // It's a double. - output = Double.Parse(m.Value, CultureInfo.InvariantCulture); - return true; - } - else - { - output = Int64.Parse(m.Value, CultureInfo.InvariantCulture); - return true; - } - } - - /// - /// Matches the string to a regex, consuming part of the string and returning the match. - /// - private bool Accept(Regex matcher, out Match match) - { - match = matcher.Match(Input, CurrentIndex); - if (match.Success) - Skip(match.Length); - return match.Success; - } - - /// - /// Find the first occurrences of a character, consuming part of the string. - /// - private bool Accept(char condition) - { - int step = 0; - int strLen = InputAsArray.Length; - int currentStep = CurrentIndex; - char currentChar; - - // Remove whitespace - while (currentStep < strLen && - ((currentChar = InputAsArray[currentStep]) == ' ' || - currentChar == '\r' || - currentChar == '\t' || - currentChar == '\n')) - { - ++step; - ++currentStep; - } - - bool match = currentStep < strLen && InputAsArray[currentStep] == condition; - if (match) - { - ++step; - ++currentStep; - - // Remove whitespace - while (currentStep < strLen && - ((currentChar = InputAsArray[currentStep]) == ' ' || - currentChar == '\r' || - currentChar == '\t' || - currentChar == '\n')) - { - ++step; - ++currentStep; - } - - Skip(step); - } - return match; - } - - /// - /// Find the first occurrences of a string, consuming part of the string. - /// - private bool Accept(char[] condition) - { - int step = 0; - int strLen = InputAsArray.Length; - int currentStep = CurrentIndex; - char currentChar; - - // Remove whitespace - while (currentStep < strLen && - ((currentChar = InputAsArray[currentStep]) == ' ' || - currentChar == '\r' || - currentChar == '\t' || - currentChar == '\n')) - { - ++step; - ++currentStep; - } - - bool strMatch = true; - for (int i = 0; currentStep < strLen && i < condition.Length; ++i, ++currentStep) - if (InputAsArray[currentStep] != condition[i]) - { - strMatch = false; - break; - } - - bool match = currentStep < strLen && strMatch; - if (match) - Skip(step + condition.Length); - return match; - } - } - - /// - /// Parses a JSON-text as defined in http://tools.ietf.org/html/rfc4627, returning an - /// IDictionary<string, object> or an IList<object> depending on whether - /// the value was an array or dictionary. Nested objects also match these types. - /// - public static object Parse(string input) - { - input = input.Trim(); - JsonStringParser parser = new JsonStringParser(input); - - if ((parser.ParseObject(out object output) || - parser.ParseArray(out output)) && - parser.CurrentIndex == input.Length) - return output; - throw new ArgumentException("Input JSON was invalid."); - } - - /// - /// Encodes a dictionary into a JSON string. Supports values that are - /// IDictionary<string, object>, IList<object>, strings, - /// nulls, and any of the primitive types. - /// - public static string Encode(IDictionary dict) - { - if (dict == null) - throw new ArgumentNullException(); - if (dict.Count == 0) - return "{}"; - StringBuilder builder = new StringBuilder("{"); - foreach (KeyValuePair pair in dict) - { - builder.Append(Encode(pair.Key)); - builder.Append(":"); - builder.Append(Encode(pair.Value)); - builder.Append(","); - } - builder[builder.Length - 1] = '}'; - return builder.ToString(); - } - - /// - /// Encodes a list into a JSON string. Supports values that are - /// IDictionary<string, object>, IList<object>, strings, - /// nulls, and any of the primitive types. - /// - public static string Encode(IList list) - { - if (list == null) - throw new ArgumentNullException(); - if (list.Count == 0) - return "[]"; - StringBuilder builder = new StringBuilder("["); - foreach (object item in list) - { - builder.Append(Encode(item)); - builder.Append(","); - } - builder[builder.Length - 1] = ']'; - return builder.ToString(); - } - - /// - /// Encodes an object into a JSON string. - /// - public static string Encode(object obj) - { - if (obj is IDictionary dict) - return Encode(dict); - if (obj is IList list) - return Encode(list); - if (obj is string str) - { - str = escapePattern.Replace(str, m => - { - switch (m.Value[0]) - { - case '\\': - return "\\\\"; - case '\"': - return "\\\""; - case '\b': - return "\\b"; - case '\f': - return "\\f"; - case '\n': - return "\\n"; - case '\r': - return "\\r"; - case '\t': - return "\\t"; - default: - return "\\u" + ((ushort) m.Value[0]).ToString("x4"); - } - }); - return "\"" + str + "\""; - } - if (obj is null) - return "null"; - if (obj is bool) - return (bool) obj ? "true" : "false"; - if (!obj.GetType().GetTypeInfo().IsPrimitive) - throw new ArgumentException("Unable to encode objects of type " + obj.GetType()); - return Convert.ToString(obj, CultureInfo.InvariantCulture); - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Utilities/LateInitializer.cs b/MoralisDotNet/Moralis/Platform/Utilities/LateInitializer.cs deleted file mode 100644 index fc7d791..0000000 --- a/MoralisDotNet/Moralis/Platform/Utilities/LateInitializer.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Moralis.Platform.Utilities -{ - /// - /// A wrapper over a dictionary from value generator to value. Uses the fact that lambda expressions in a specific location are cached, so the cost of instantiating a generator delegate is only incurred once at the call site of and subsequent calls look up the result of the first generation from the dictionary based on the hash of the generator delegate. This is effectively a lazy initialization mechanism that allows the member type to remain unchanged. - /// - internal class LateInitializer - { - Lazy, object>> Storage { get; set; } = new Lazy, object>> { }; - - public TData GetValue(Func generator) - { - lock (generator) - { - if (Storage.IsValueCreated && Storage.Value.Keys.OfType>().FirstOrDefault() is { } key && Storage.Value.TryGetValue(key as Func, out object data)) - { - return (TData) data; - } - else - { - TData result = generator.Invoke(); - - Storage.Value.Add(generator as Func, result); - return result; - } - } - } - - public bool ClearValue() - { - lock (Storage) - { - if (Storage.IsValueCreated && Storage.Value.Keys.OfType>().FirstOrDefault() is { } key) - { - lock (key) - { - Storage.Value.Remove(key as Func); - return true; - } - } - } - - return false; - } - - public bool SetValue(TData value, bool initialize = true) - { - lock (Storage) - { - if (Storage.IsValueCreated && Storage.Value.Keys.OfType>().FirstOrDefault() is { } key) - { - lock (key) - { - Storage.Value[key as Func] = value; - return true; - } - } - else if (initialize) - { - Storage.Value[new Func(() => value) as Func] = value; - return true; - } - } - - return false; - } - - public bool Reset() - { - lock (Storage) - { - if (Storage.IsValueCreated) - { - Storage.Value.Clear(); - return true; - } - } - - return false; - } - - public bool Used => Storage.IsValueCreated; - } -} diff --git a/MoralisDotNet/Moralis/Platform/Utilities/LockSet.cs b/MoralisDotNet/Moralis/Platform/Utilities/LockSet.cs deleted file mode 100644 index 70d2ec1..0000000 --- a/MoralisDotNet/Moralis/Platform/Utilities/LockSet.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.CompilerServices; -using System.Threading; - -namespace Moralis.Platform.Utilities -{ - public class LockSet - { - private static readonly ConditionalWeakTable stableIds = new ConditionalWeakTable(); - private static long nextStableId = 0; - - private readonly IEnumerable mutexes; - - public LockSet(IEnumerable mutexes) => this.mutexes = (from mutex in mutexes orderby GetStableId(mutex) select mutex).ToList(); - - public void Enter() - { - foreach (object mutex in mutexes) - Monitor.Enter(mutex); - } - - public void Exit() - { - foreach (object mutex in mutexes) - Monitor.Exit(mutex); - } - - private static IComparable GetStableId(object mutex) - { - lock (stableIds) - return stableIds.GetValue(mutex, k => nextStableId++); - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Utilities/MoralisFileExtensions.cs b/MoralisDotNet/Moralis/Platform/Utilities/MoralisFileExtensions.cs deleted file mode 100644 index 9a6a772..0000000 --- a/MoralisDotNet/Moralis/Platform/Utilities/MoralisFileExtensions.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; -using Moralis.Platform.Objects; - -namespace Moralis.Platform.Utilities -{ - public class MoralisFileExtensions - { - public static MoralisFile Create(string name, Uri uri, string mimeType = null) => new MoralisFile(name, uri, mimeType); - } -} diff --git a/MoralisDotNet/Moralis/Platform/Utilities/ReflectionUtilities.cs b/MoralisDotNet/Moralis/Platform/Utilities/ReflectionUtilities.cs deleted file mode 100644 index 05ada11..0000000 --- a/MoralisDotNet/Moralis/Platform/Utilities/ReflectionUtilities.cs +++ /dev/null @@ -1,42 +0,0 @@ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; - -namespace Moralis.Platform.Utilities -{ - public static class ReflectionUtilities - { - /// - /// Gets all of the defined constructors that aren't static on a given instance. - /// - /// - /// - public static IEnumerable GetInstanceConstructors(this Type type) => type.GetTypeInfo().DeclaredConstructors.Where(constructor => (constructor.Attributes & MethodAttributes.Static) == 0); - - /// - /// This method helps simplify the process of getting a constructor for a type. - /// A method like this exists in .NET but is not allowed in a Portable Class Library, - /// so we've built our own. - /// - /// - /// - /// - public static ConstructorInfo FindConstructor(this Type self, params Type[] parameterTypes) => self.GetConstructors().Where(constructor => constructor.GetParameters().Select(parameter => parameter.ParameterType).SequenceEqual(parameterTypes)).SingleOrDefault(); - - /// - /// Checks if a instance is another instance wrapped with . - /// - /// - /// - public static bool CheckWrappedWithNullable(this Type type) => type.IsConstructedGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)); - - /// - /// Gets the value of if the type has a custom attribute of type . - /// - /// - /// - //public static string GetParseClassName(this Type type) => type.GetCustomAttribute()?.ClassName; - } -} diff --git a/MoralisDotNet/Moralis/Platform/Utilities/SynchronizedEventHandler.cs b/MoralisDotNet/Moralis/Platform/Utilities/SynchronizedEventHandler.cs deleted file mode 100644 index cfbdfe6..0000000 --- a/MoralisDotNet/Moralis/Platform/Utilities/SynchronizedEventHandler.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; - -namespace Moralis.Platform.Utilities -{ - /// - /// Represents an event handler that calls back from the synchronization context - /// that subscribed. - /// Should look like an EventArgs, but may not inherit EventArgs if T is implemented by the Windows team. - /// - public class SynchronizedEventHandler - { - LinkedList> Callbacks { get; } = new LinkedList> { }; - - public void Add(Delegate target) - { - lock (Callbacks) - { - TaskFactory factory = SynchronizationContext.Current is { } ? new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.FromCurrentSynchronizationContext()) : Task.Factory; - - foreach (Delegate invocation in target.GetInvocationList()) - { - Callbacks.AddLast(new Tuple(invocation, factory)); - } - } - } - - public void Remove(Delegate target) - { - lock (Callbacks) - { - if (Callbacks.Count == 0) - { - return; - } - - foreach (Delegate invocation in target.GetInvocationList()) - { - LinkedListNode> node = Callbacks.First; - - while (node != null) - { - if (node.Value.Item1 == invocation) - { - Callbacks.Remove(node); - break; - } - node = node.Next; - } - } - } - } - - public Task Invoke(object sender, T args) - { - IEnumerable> toInvoke; - Task[] toContinue = new[] { Task.FromResult(0) }; - - lock (Callbacks) - { - toInvoke = Callbacks.ToList(); - } - - List> invocations = toInvoke.Select(callback => callback.Item2.ContinueWhenAll(toContinue, _ => callback.Item1.DynamicInvoke(sender, args))).ToList(); - return Task.WhenAll(invocations); - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Utilities/TaskQueue.cs b/MoralisDotNet/Moralis/Platform/Utilities/TaskQueue.cs deleted file mode 100644 index 9194627..0000000 --- a/MoralisDotNet/Moralis/Platform/Utilities/TaskQueue.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace Moralis.Platform.Utilities -{ - /// - /// A helper class for enqueuing tasks - /// - public class TaskQueue - { - /// - /// We only need to keep the tail of the queue. Cancelled tasks will - /// just complete normally/immediately when their turn arrives. - /// - Task Tail { get; set; } - - /// - /// Gets a cancellable task that can be safely awaited and is dependent - /// on the current tail of the queue. This essentially gives us a proxy - /// for the tail end of the queue whose awaiting can be cancelled. - /// - /// A cancellation token that cancels - /// the task even if the task is still in the queue. This allows the - /// running task to return immediately without breaking the dependency - /// chain. It also ensures that errors do not propagate. - /// A new task that should be awaited by enqueued tasks. - private Task GetTaskToAwait(CancellationToken cancellationToken) - { - lock (Mutex) - { - return (Tail ?? Task.FromResult(true)).ContinueWith(task => { }, cancellationToken); - } - } - - /// - /// Enqueues a task created by . If the task is - /// cancellable (or should be able to be cancelled while it is waiting in the - /// queue), pass a cancellationToken. - /// - /// The type of task. - /// A function given a task to await once state is - /// snapshotted (e.g. after capturing session tokens at the time of the save call). - /// Awaiting this task will wait for the created task's turn in the queue. - /// A cancellation token that can be used to - /// cancel waiting in the queue. - /// The task created by the taskStart function. - public T Enqueue(Func taskStart, CancellationToken cancellationToken = default) where T : Task - { - Task oldTail; - T task; - - lock (Mutex) - { - oldTail = Tail ?? Task.FromResult(true); - - // The task created by taskStart is responsible for waiting the - // task passed to it before doing its work (this gives it an opportunity - // to do startup work or save state before waiting for its turn in the queue - task = taskStart(GetTaskToAwait(cancellationToken)); - - // The tail task should be dependent on the old tail as well as the newly-created - // task. This prevents cancellation of the new task from causing the queue to run - // out of order. - Tail = Task.WhenAll(oldTail, task); - } - return task; - } - - public object Mutex { get; } = new object { }; - } -} diff --git a/MoralisDotNet/Moralis/Platform/Utilities/ThreadingUtilities.cs b/MoralisDotNet/Moralis/Platform/Utilities/ThreadingUtilities.cs deleted file mode 100644 index d09ce21..0000000 --- a/MoralisDotNet/Moralis/Platform/Utilities/ThreadingUtilities.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; - -namespace Moralis.Platform.Utilities -{ - internal static class ThreadingUtilities - { - public static void Lock(ref object @lock, Action operationToLock) - { - lock (@lock) - operationToLock(); - } - - public static TResult Lock(ref object @lock, Func operationToLock) - { - TResult result = default; - lock (@lock) - result = operationToLock(); - - return result; - } - } -} diff --git a/MoralisDotNet/Moralis/Platform/Utilities/XamarinAttributes.cs b/MoralisDotNet/Moralis/Platform/Utilities/XamarinAttributes.cs deleted file mode 100644 index 90867f8..0000000 --- a/MoralisDotNet/Moralis/Platform/Utilities/XamarinAttributes.cs +++ /dev/null @@ -1,407 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Moralis.Platform.Utilities -{ - /// - /// A reimplementation of Xamarin's PreserveAttribute. - /// This allows us to support AOT and linking for Xamarin platforms. - /// - [AttributeUsage(AttributeTargets.All)] - internal class PreserveAttribute : Attribute - { - public bool AllMembers; - public bool Conditional; - } - - [AttributeUsage(AttributeTargets.All)] - internal class LinkerSafeAttribute : Attribute - { - public LinkerSafeAttribute() { } - } - - [Preserve(AllMembers = true)] - internal class PreserveWrapperTypes - { - /// - /// Exists to ensure that generic types are AOT-compiled for the conversions we support. - /// Any new value types that we add support for will need to be registered here. - /// The method itself is never called, but by virtue of the Preserve attribute being set - /// on the class, these types will be AOT-compiled. - /// - /// This also applies to Unity. - /// - static List AOTPreservations => new List - { - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - - typeof(FlexibleListWrapper), - typeof(FlexibleListWrapper), - - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper), - - typeof(FlexibleDictionaryWrapper), - typeof(FlexibleDictionaryWrapper) - }; - } -} diff --git a/MoralisDotNet/Moralis/readme.md b/MoralisDotNet/Moralis/readme.md deleted file mode 100644 index 0b9b98e..0000000 --- a/MoralisDotNet/Moralis/readme.md +++ /dev/null @@ -1,7 +0,0 @@ -# Moralis DOT NET SDK # -The files in this directory and in the child directories of this directory for the Moralis -Dot Net SDK. These files should not be modified. - -The raw files are included in this project to ensure compatibility with Unity 3D. While the official -Nuget Package could be used, we have found that the pre-compiled DLLs can have some incompatibilities -within some Unity3D applications, esp. when re-rendered as Objective C and compiled on iOS. diff --git a/MoralisDotNetSdk.sln b/MoralisDotNetSdk.sln index 1439264..968967b 100644 --- a/MoralisDotNetSdk.sln +++ b/MoralisDotNetSdk.sln @@ -3,15 +3,11 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.1.32421.90 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Moralis.Platform.Tests", "MoralisDotNet.Platform.Tests\Moralis.Platform.Tests.csproj", "{5BAD7E55-86FE-4003-87B0-6DAE0A51CF8D}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Moralis", "MoralisDotNet\Moralis.csproj", "{5CE743DA-F956-4668-A679-753844FDC1F4}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Moralis.Web3Api.Integrated.Tests", "Moralis.Web3Api.Integrated.Tests\Moralis.Web3Api.Integrated.Tests.csproj", "{7E70DD68-D987-4019-8C4E-E72CE863721B}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Moralis.Platform.Integrated.Tests", "Moralis.Platform.Integrated.Tests\Moralis.Platform.Integrated.Tests.csproj", "{D147D0EE-C12E-41BA-9C22-EC5B9A24F8D5}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Moralis.AuthApi.Integrated.Tests", "Moralis.AuthApi.Integrated.Tests\Moralis.AuthApi.Integrated.Tests.csproj", "{97FBE648-520E-4887-BC75-D94551BBAB91}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Moralis.AuthApi.Integrated.Tests", "Moralis.AuthApi.Integrated.Tests\Moralis.AuthApi.Integrated.Tests.csproj", "{97FBE648-520E-4887-BC75-D94551BBAB91}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -19,10 +15,6 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {5BAD7E55-86FE-4003-87B0-6DAE0A51CF8D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5BAD7E55-86FE-4003-87B0-6DAE0A51CF8D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5BAD7E55-86FE-4003-87B0-6DAE0A51CF8D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5BAD7E55-86FE-4003-87B0-6DAE0A51CF8D}.Release|Any CPU.Build.0 = Release|Any CPU {5CE743DA-F956-4668-A679-753844FDC1F4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5CE743DA-F956-4668-A679-753844FDC1F4}.Debug|Any CPU.Build.0 = Debug|Any CPU {5CE743DA-F956-4668-A679-753844FDC1F4}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -31,10 +23,6 @@ Global {7E70DD68-D987-4019-8C4E-E72CE863721B}.Debug|Any CPU.Build.0 = Debug|Any CPU {7E70DD68-D987-4019-8C4E-E72CE863721B}.Release|Any CPU.ActiveCfg = Release|Any CPU {7E70DD68-D987-4019-8C4E-E72CE863721B}.Release|Any CPU.Build.0 = Release|Any CPU - {D147D0EE-C12E-41BA-9C22-EC5B9A24F8D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D147D0EE-C12E-41BA-9C22-EC5B9A24F8D5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D147D0EE-C12E-41BA-9C22-EC5B9A24F8D5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D147D0EE-C12E-41BA-9C22-EC5B9A24F8D5}.Release|Any CPU.Build.0 = Release|Any CPU {97FBE648-520E-4887-BC75-D94551BBAB91}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {97FBE648-520E-4887-BC75-D94551BBAB91}.Debug|Any CPU.Build.0 = Debug|Any CPU {97FBE648-520E-4887-BC75-D94551BBAB91}.Release|Any CPU.ActiveCfg = Release|Any CPU