How to mocking DbRawSqlQuery<int> result? - c#

I created a method for check that in db has a stored procedure.
public class StoredProcedure : IStoredProcedure
{
private readonly IDbContextProvider<MyDbContext> _dbContextProvider;
public StoredProcedure(IDbContextProvider<MyDbContext> dbContextProvider)
{
_dbContextProvider = dbContextProvider;
}
public bool ExistsStoredProcedure(string procedureName)
{
var query = string.Format(
"SELECT COUNT(*) FROM [sys].[objects] WHERE [type_desc] = 'SQL_STORED_PROCEDURE' AND [name] = '{0}';",
procedureName);
var request = _dbContextProvider.DbContext.Database.SqlQuery<int>(query).Single();
return request > 0 ? true : throw new UserFriendlyException(
$"Хранимая процедура {procedureName} не найдена в БД {_dbContextProvider.DbContext.Database.Connection.Database}");
}
}
Also, I want to write a unit test for him.
public class StoredProcedureTests
{
private readonly IStoredProcedure _storedProcedure;
private readonly Mock<IDbContextProvider<MyDbContext>> _mockDbProvider;
public StoredProcedureTests()
{
_mockDbProvider = new Mock<IDbContextProvider<MyDbContext>>();
_storedProcedure = new StoredProcedure(_mockDbProvider.Object);
}
[Fact]
public void CheckValueIfStoredProcedureExist()
{
const int count = 1;
var rawMock = new Mock<DbRawSqlQuery<int>>();
rawMock.Setup(i => i.Single()).Returns(count);
_mockDbProvider.Setup(i => i.DbContext.Database.SqlQuery<int>(It.IsAny<string>())).Returns(rawMock.Object);
var result = _storedProcedure.ExistsStoredProcedure(string.Empty);
Assert.True(result);
}
}
But, i get an error, when i try rawMock.Setup
try
{
rawMock.Setup(i => i.Single()).Returns(count);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
Invalid setup on an extension method: i => i.Single()
How to correctly write this stub?
UPD I try like advised Johnny
try
{
IEnumerable<int> list = new List<int> {1};
var mq = new Mock<DbRawSqlQuery<int>>();
mq.Setup(i => i.GetEnumerator()).Returns(list.GetEnumerator);
_mockDbProvider.Setup(i => i.DbContext.Database.SqlQuery<int>(It.IsAny<string>())).Returns(mq.Object);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
And i have a new error
Invalid setup on a non-virtual (overridable in VB) member: i => i.DbContext.Database.SqlQuery(It.IsAny(), new[] { })

Related

Make method more Rx like by replacing List<T> and TaskCompletionSource<T>

This is a request-response model (like HTTP) but over sockets/websockets. We know which response corresponds to which request by comparing the request IDs.
The workflow is as following:
Subscribe to the observables Error, ContractDetails (_itemObservable) and ContractDetailsEnd (_itemEndObservable)
Match request id to response id and push the corresponding messages via .OnNext(...) to ContractDetails. When there is nothing else left to push, push a final message to ContractDetailsEnd which essentially does .OnCompleted.
Cleanup – unsubscribe, i.e. dispose the observables
In the first snippet below I use a List<TItemArgs>, CancellationTokenSource and a TaskCompletionSource<TItemArgs>. That's completely unnecessary if everything was Rx style. It would have definitely been less lines of code too.
The second snippet is my personal attempt to make it look more Rx like. It has some issues that I want to resolve:
I don't think the try/catch block is necessary since .Subscribe could handle errors
.Timeout didn't work out for me – if the request is not matched within a few seconds, it should return a Result<IEnumerable<TItemArgs>>.FromError(new TimeoutError(...))
In addition to the errors, a message pushed to _errorSubject should also return an error such as Result<IEnumerable<TItemArgs>>.FromError(new RemoteError(...)) but .Merge(errorMessages.Any(_ => false)) is not working.
In my attempt I use ReplaySubject in opposed to AsyncSubject because I believe AsyncSubject is only useful when I'm only interested in the last value of the sequence and want to avoid getting all previous values, which is not in my case. In my case I want to return all values, so ReplaySubject would be more suitable as it keeps track of all the previous values and wants all subscribers to receive the same values, regardless of when they subscribed.
public async ValueTask<Result<IEnumerable<TItemArgs>>> ExecuteAsync(Action<int> action)
{
var requestId = _client.GetNextRequestId();
var data = new List<TItemArgs>();
var cts = new CancellationTokenSource(_timeout);
var tcs = new TaskCompletionSource<IEnumerable<TItemArgs>>();
cts.Token.Register(() =>
{
tcs.TrySetCanceled();
}, false);
void OnError(ErrorData msg)
{
tcs.SetException(new IBClientException(msg.RequestId, msg.Code, msg.Message, msg.AdvancedOrderRejectJson));
}
void OnDetails(TItemArgs item)
{
data.Add(item);
}
void OnDetailsEnd(TItemListEndArgs item)
{
tcs.TrySetResult(data);
}
var disposable = new CompositeDisposable();
_client.Error
.Where(e => HasRequestId && e.RequestId == requestId)
.Subscribe(OnError)
.DisposeWith(disposable);
_itemObservable
.Where(item => MatchRequest(item, _itemRequestIdExtractor, requestId))
.Subscribe(OnDetails)
.DisposeWith(disposable);
_itemEndObservable
.Where(item => MatchRequest(item, _itemListEndRequestIdExtractor, requestId))
.Subscribe(OnDetailsEnd)
.DisposeWith(disposable);
action(requestId);
try
{
await tcs.Task.ContinueWith(x =>
{
disposable.Dispose();
cts.Dispose();
}, TaskContinuationOptions.RunContinuationsAsynchronously);
return Result<IEnumerable<TItemArgs>>.FromSuccess(tcs.Task.Result);
}
catch (Exception e)
{
return Result<IEnumerable<TItemArgs>>.FromError(new RemoteError(e.Message, null));
}
}
My attempt
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive.Subjects;
var client = new IBClient();
var result = await client.GetContractDetailsAsync();
if (result.Success)
{
foreach (var item in result.Data!)
{
Console.WriteLine($"RequestId: {item.RequestId} | Data: {item.ContractDetails}");
}
}
public sealed class IBClient
{
private int _nextValidId;
private readonly Subject<ErrorData> _errorSubject = new();
public IObservable<ErrorData> Error => _errorSubject.AsObservable();
private readonly Subject<ContractDetailsData> _contractDetailsSubject = new();
public IObservable<ContractDetailsData> ContractDetails => _contractDetailsSubject.AsObservable();
private readonly Subject<RequestEndData> _contractDetailsEndSubject = new();
public IObservable<RequestEndData> ContractDetailsEnd => _contractDetailsEndSubject.AsObservable();
public ValueTask<Result<IEnumerable<ContractDetailsData>>> GetContractDetailsAsync()
{
return new PendingRequest<ContractDetailsData, RequestEndData>(
this,
ContractDetails,
ContractDetailsEnd,
e => e.RequestId,
e => e.RequestId)
.ExecuteAsync(reqId => TestCall(reqId));
}
private void TestCall(int requestId)
{
_contractDetailsSubject.OnNext(new ContractDetailsData(requestId, "hey from test call"));
_contractDetailsSubject.OnNext(new ContractDetailsData(requestId, "hey two"));
// TODO: Errors doesn't seem to work
// _errorSubject.OnNext(new ErrorData(requestId, 123, "Error happened", ""));
_contractDetailsEndSubject.OnNext(new RequestEndData(requestId));
// There shouldn't be matched.
_contractDetailsSubject.OnNext(new ContractDetailsData(123, "fake ones, so we know it works"));
_contractDetailsEndSubject.OnNext(new RequestEndData(123));
}
public int GetNextRequestId()
{
return Interlocked.Increment(ref _nextValidId);
}
}
public sealed class PendingRequest<TItemArgs, TItemListEndArgs>
{
private readonly TimeSpan _timeout = TimeSpan.FromSeconds(2);
private readonly IBClient _client;
private readonly IObservable<TItemArgs> _itemObservable;
private readonly IObservable<TItemListEndArgs> _itemEndObservable;
private readonly Func<TItemArgs, int>? _itemRequestIdExtractor;
private readonly Func<TItemListEndArgs, int>? _itemListEndRequestIdExtractor;
public PendingRequest(
IBClient client,
IObservable<TItemArgs> itemObservable,
IObservable<TItemListEndArgs> itemEndObservable,
Func<TItemArgs, int>? itemRequestIdExtractor = null,
Func<TItemListEndArgs, int>? itemListEndRequestIdExtractor = null)
{
_client = client;
_itemObservable = itemObservable;
_itemEndObservable = itemEndObservable;
_itemRequestIdExtractor = itemRequestIdExtractor;
_itemListEndRequestIdExtractor = itemListEndRequestIdExtractor;
}
private bool HasRequestId => _itemRequestIdExtractor != null && _itemListEndRequestIdExtractor != null;
public async ValueTask<Result<IEnumerable<TItemArgs>>> ExecuteAsync(Action<int> action, IScheduler? scheduler = null)
{
scheduler ??= ImmediateScheduler.Instance;
var requestId = _client.GetNextRequestId();
var results = new ReplaySubject<TItemArgs>();
try
{
var errorMessages = _client.Error
.Where(e => HasRequestId && e.RequestId == requestId);
using (_itemObservable
.Where(item => MatchRequest(item, _itemRequestIdExtractor, requestId))
.ObserveOn(scheduler)
.Subscribe(results))
using (_itemEndObservable
.Any(item => MatchRequest(item, _itemListEndRequestIdExtractor, requestId))
.Merge(errorMessages.Any(_ => false)) // TODO: ???
.ObserveOn(scheduler)
.Subscribe(_ => results.OnCompleted()))
{
action(requestId);
// Don't want an Exception thrown if there result list is empty
await results.DefaultIfEmpty();
return Result<IEnumerable<TItemArgs>>.FromSuccess(results.ToEnumerable());
}
}
catch (Exception ex)
{
return Result<IEnumerable<TItemArgs>>.FromError(new RemoteError(ex.Message, null));
}
}
private bool MatchRequest<T>(T item, Func<T, int>? idExtractor, int id)
{
return !HasRequestId || (idExtractor != null && idExtractor(item) == id);
}
}
public sealed class ContractDetailsData
{
public ContractDetailsData(int requestId, string contractDetails)
{
RequestId = requestId;
ContractDetails = contractDetails;
}
public int RequestId { get; }
public string ContractDetails { get; }
}
public sealed class ErrorData
{
public ErrorData(int requestId, int code, string message, string advancedOrderRejectJson)
{
RequestId = requestId;
Code = code;
Message = message;
AdvancedOrderRejectJson = advancedOrderRejectJson;
}
public int RequestId { get; }
public int Code { get; }
public string Message { get; }
public string AdvancedOrderRejectJson { get; }
}
public sealed class RequestEndData
{
public RequestEndData(int requestId)
{
RequestId = requestId;
}
public int RequestId { get; }
}
public class IBClientException : Exception
{
public IBClientException(int requestId, int errorCode, string message, string advancedOrderRejectJson)
: base(message)
{
RequestId = requestId;
ErrorCode = errorCode;
AdvancedOrderRejectJson = advancedOrderRejectJson;
}
public IBClientException(string err)
: base(err)
{
}
public IBClientException(Exception e)
{
Exception = e;
}
public int RequestId { get; }
public int ErrorCode { get; }
public string? AdvancedOrderRejectJson { get; }
public Exception? Exception { get; }
}
public abstract record Error(int? Code, string Message, object? Data);
public record RemoteError : Error
{
public RemoteError(string message, object? data) : base(null, message, data)
{
}
public RemoteError(int? code, string message, object? data) : base(code, message, data)
{
}
}
public record Result<T>(bool Success, T? Data, Error? Error)
{
public Result(T data) : this(true, data, default)
{
}
public Result(Error error) : this(false, default, error)
{
}
public static Result<T> FromSuccess(T data)
{
return new Result<T>(data);
}
public static Result<T> FromError<TError>(TError error) where TError : Error
{
return new Result<T>(error);
}
}
public static class DisposableExtensions
{
public static T DisposeWith<T>(this T disposable, ICollection<IDisposable> collection)
where T : IDisposable
{
ArgumentNullException.ThrowIfNull(disposable);
ArgumentNullException.ThrowIfNull(collection);
collection.Add(disposable);
return disposable;
}
}
Here's a good start:
IObservable<TItemArgs> observable =
Observable
.Merge(
_itemObservable
.Where(item => MatchRequest(item, _itemRequestIdExtractor, requestId))
.Select(item => Notification.CreateOnNext(item))
.Take(1),
_itemEndObservable
.Any(item => MatchRequest(item, _itemListEndRequestIdExtractor, requestId))
.Select(item => Notification.CreateOnCompleted<TItemArgs>()))
.Dematerialize();
And here's a final observable without the ReplaySubject.
private static async Task<Result<IEnumerable<Details>>> Test(IScheduler scheduler) =>
await
Observable
.Defer(() =>
{
var client = new IBClient();
var requestId = 1;
return Observable.Create<Result<IEnumerable<Details>>>(o =>
{
IDisposable subscription =
Observable
.Merge(
client.Details.Where(x => x.RequestId == requestId).Select(x => Notification.CreateOnNext(x)),
client.DetailsEnd.Any(x => x.RequestId == requestId).Select(x => Notification.CreateOnCompleted<Details>()),
client.Error.Where(x => x.RequestId == requestId).Select(x => Notification.CreateOnError<Details>(new Exception($"Code: {x.Code}, Message: {x.Message}"))))
.Dematerialize()
.Synchronize()
.ToArray()
.Select(items => Result<IEnumerable<Details>>.FromSuccess(items))
.Catch<Result<IEnumerable<Details>>, Exception>(ex => Observable.Return(Result<IEnumerable<Details>>.FromError(new Error(null, ex.Message, null))))
.Timeout(TimeSpan.FromSeconds(2))
.ObserveOn(scheduler)
.Subscribe(o);
client.Emit(2, 4);
client.Emit(requestId, 42);
client.EmitEnd(2);
client.Emit(requestId, 62);
client.Emit(requestId, 123);
//client.EmitError(requestId, 123, "Something bad happened");
client.EmitEnd(requestId);
client.Emit(requestId, 1);
return subscription;
});
});

How to access the static method via MOQ in c sharp

I am using mock library in my .Net unit test and getting an error
cannot be accessed with an instance reference instead use type name.
I am getting this error at following line in my test method where it is calling cq.Instance. I am new to mock library. Could somebody let me know how do I call the static method?
attributeValue.Setup(cq => cq.Instance().CallQueryAsync(request, 1)).Returns(attrValue);
Actual method to be tested
public static async Task<AttributeValueList> GetAttributeSecDateValueList(int attrId)
{
try
{
var request = AttributeValue.ResolveRequest(attrId);
var response = await AsyncProxy<AttributeValue>.Instance().CallQueryAsync(request, (int)AttributeValue.OperationType.GetSecDateValues);
var coll = new AttributeValueList();
coll.AddRange(response);
return coll;
}
catch (Exception e)
{
throw e;
}
}
Proxy class
public class AsyncProxy<RT> : IDisposable
where RT : class, new()
{
readonly WebServiceProxy<RT> _wsProxy;
private AsyncProxy(WebServiceProxy<RT> webServiceProxy)
{
_wsProxy = webServiceProxy;
}
public static async Task<IEnumerable<RT>> Load(object parameters)
{
return await Instance().CallQueryAsync(parameters);
}
public static AsyncProxy<RT> Instance()
{
return new AsyncProxy<RT>(WebServiceProxy<RT>.Instance());
}
/// <summary>
/// Return result set of Poco as smartCollection
/// </summary>
public async Task<SmartCollection<RT>> CallQueryAsync(object request, int? uniqueIdentifier = null, bool isLongRunning = false, [CallerMemberName]string memberName = "")
{
//#if DEBUG
// var stopwatch = new Stopwatch();
// stopwatch.Start();
//#endif
try
{
// We want to get rid of the proxy as soon as we are done with it
using (_wsProxy)
{
var awaited = await _wsProxy.CallQueryAsync(request, uniqueIdentifier, isLongRunning);
if (awaited == null)
return null;
var observableCollection = new SmartCollection<RT>();
foreach (var item in awaited)
observableCollection.Add(item as RT);
return observableCollection;
}
}
finally
{
Dispose();
//#if DEBUG
// stopwatch.Stop();
// Debug.WriteLine(null);
// Debug.WriteLine($"****>>>>> AsyncProxy {memberName} took {stopwatch.ElapsedMilliseconds} ms <<<<<<<<****");
//#endif
}
}
}
test method
[TestMethod]
public void test()
{
Task<SmartCollection<AttributeValue>> attrValue = null;
var request = new AttributeValue();
var attributeValue = new Mock<AsyncProxy<AttributeValue>>();
attributeValue.Setup(cq => cq.Instance().CallQueryAsync(request, 1)).Returns(attrValue);
}

Unit testing data layer's stored functions/procedures using OrmLite without an open connection

I am trying to unit test our DB layer's stored procedures/functions using OrmLite's ScalarAsync(), for example, with the PostgreSQL dialect. (I tried using SqlLite in-memory but it doesn't do stored procedures or functions.)
I found some hints in the unit-tests for OrmLite on GitHub as well as an article which points to them.
Here's what I have:
[Fact]
public async Task TestMyMethod_CallsMyStoredProcedure()
{
// Arrange
Mock<IDashboardDbConnectionFactory> mockConnFac = new();
MockDialectProvider prov = new();
prov.ExecFilter = new MockStoredProcExecFilter();
OrmLiteConnectionFactory dbFactory =
new(
"User ID=asdf;Password=asdf;Host=localhost;Port=5432;Database=asdf;Pooling=true;Connection Lifetime=0;",
prov, false);
OrmLiteConfig.ExecFilter = new MockStoredProcExecFilter();
mockConnFac.Setup(m => m.OpenAsync(It.IsAny<ISecurityContext>()))
.Returns(async () =>
{
OrmLiteConnection asdf = new(dbFactory);
OrmLiteConfig.ExecFilter = new MockStoredProcExecFilter();
await asdf.OpenAsync();
return asdf;
});
mockConnFac.Setup(m => m.Open(It.IsAny<ISecurityContext>()))
.Returns(() =>
{
OrmLiteConnection asdf = new(dbFactory);
OrmLiteConfig.ExecFilter = new MockStoredProcExecFilter();
asdf.Open();
return asdf;
});
// Act
MyDataLayerCLass target = new(mockConnFac.Object, new NullLoggerFactory());
bool test1 =
await target.ExecMyStoredProcAsync(new Mock<ISecurityContext>().Object, Guid.NewGuid());
// Assert
Assert.True(test1);
}
private class MockDialectProvider : PostgreSqlDialectProvider
{
public MockDialectProvider()
{
base.ExecFilter = new MockStoredProcExecFilter();
}
public new IOrmLiteExecFilter ExecFilter { get; set; } = new MockStoredProcExecFilter();
}
private class MockStoredProcExecFilter : OrmLiteExecFilter
{
public override T Exec<T>(IDbConnection dbConn, Func<IDbCommand, T> filter)
{
try
{
T val = base.Exec(dbConn, filter);
if (dbConn.GetLastSql() == "select central_data.my_stored_function(#UserId, #ParentId)")
return (T)(object)true;
return val;
}
catch (Exception)
{
if (dbConn.GetLastSql() == "select central_data.my_stored_function(#UserId, #ParentId)")
return (T)(object)true;
throw;
}
}
public override async Task<T> Exec<T>(IDbConnection dbConn, Func<IDbCommand, Task<T>> filter)
{
try
{
// This is where the breakpoint hits. Returns false b/c the ids
// don't match actual records in the DB.
T val = await base.Exec(dbConn, filter);
if (dbConn.GetLastSql() == "select central_data.my_stored_function(#UserId, #ParentId)")
return (T)(object)true;
return val;
}
catch (Exception)
{
string sql = dbConn.GetLastSql();
if (sql == "select central_data.my_stored_function(#UserId, #ParentId)")
{
return (T)(object)true;
}
throw;
}
}
}
The problem is that it requires a valid connection to a valid database. So it's really an integration test when what I want is a unit test. Is there a way to run the dialect provider without an open connection?

How to write repository unit tests with respect to Cosmos database(SQLApi + CosmosClient)

I have a class as below :
public class CosmosRepository: ICosmosRepository
{
private ICosmoDBSettings cosmoDbSettings;
private CosmosClient cosmosClient;
private static readonly object syncLock = new object();
// The database we will create
private Database database;
public CosmosRepository(ICosmoDBSettings cosmoDBSettings)
{
this.cosmoDbSettings = cosmoDBSettings;
this.InitializeComponents();
}
private void InitializeComponents()
{
try
{
if (cosmosClient != null)
{
return;
}
lock (syncLock)
{
if (cosmosClient != null)
{
return;
}
this.cosmosClient = new CosmosClient(
cosmoDbSettings.CosmosDbUri
, cosmoDbSettings.CosmosDbAuthKey
, new CosmosClientOptions
{
ConnectionMode = ConnectionMode.Direct
}
);
this.database = this.cosmosClient.CreateDatabaseIfNotExistsAsync(cosmoDbSettings.DocumentDbDataBaseName).Result;
}
}
catch (Exception ex)
{
throw ex;
}
}
}
I have my repository method as:
Don't bother about hardcoded values.
public async Task<Employee> GetById()
{
var container = this.database.GetContainer("Employees");
var document = await container.ReadItemAsync<Employee>("44A85B9E-2522-4BDB-891A-
9EA91F6D4CBF", new PartitionKey("PartitionKeyValue"));
return document.Response;
}
Note
How to write Unit Test(MS Unit tests) in .NET Core with respect to Cosmos Database?
How to mock CosmosClient and all its methods.
Could someone help me with this issue?
My UnitTests looks like:
public class UnitTest1
{
private Mock<ICosmoDBSettings> cosmoDbSettings;
private Mock<CosmosClient> cosmosClient;
private Mock<Database> database;
[TestMethod]
public async Task TestMethod()
{
this.CreateSubject();
var databaseResponse = new Mock<DatabaseResponse>();
var helper = new CosmosDBHelper(this.cosmoDbSettings.Object);
this.cosmosClient.Setup(d => d.CreateDatabaseIfNotExistsAsync("TestDatabase", It.IsAny<int>(), It.IsAny<RequestOptions>(), It.IsAny<CancellationToken>())).ReturnsAsync(databaseResponse.Object);
var mockContainer = new Mock<Container>();
this.database.Setup(x => x.GetContainer(It.IsAny<string>())).Returns(mockContainer.Object);
var mockItemResponse = new Mock<ItemResponse<PortalAccount>>();
mockItemResponse.Setup(x => x.StatusCode).Returns(It.IsAny<HttpStatusCode>);
var mockPortalAccount = new PortalAccount { PortalAccountGuid = Guid.NewGuid() };
mockItemResponse.Setup(x => x.Resource).Returns(mockPortalAccount);
mockContainer.Setup(c => c.ReadItemAsync<PortalAccount>(It.IsAny<string>(),It.IsAny<PartitionKey>(), It.IsAny<ItemRequestOptions>(), It.IsAny<CancellationToken>())).ReturnsAsync(mockItemResponse.Object);
var pas = helper.GetById().Result;
Assert.AreEqual(pas.PortalAccountGuid, mockPortalAccount.PortalAccountGuid);
}
public void CreateSubject(ICosmoDBSettings cosmoDBSettings = null)
{
this.cosmoDbSettings = cosmoDbSettings ?? new Mock<ICosmoDBSettings>();
this.cosmoDbSettings.Setup(x => x.CosmosDbUri).Returns("https://localhost:8085/");
this.cosmoDbSettings.Setup(x => x.CosmosDbAuthKey).Returns("C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==");
this.cosmoDbSettings.Setup(x => x.DocumentDbDataBaseName).Returns("TestDatabase");
this.database = new Mock<Database>();
this.cosmosClient = new Mock<CosmosClient>();
}
}
Note:
Exception:
Response status code does not indicate success: 404 Substatus: 0 Reason: (Microsoft.Azure.Documents.DocumentClientException: Message: {"Errors":["Resource Not Found"]}
I'm not creating a document. directly I'm fetching the document because I'm returning the mock response only. Is it correct??

Consuming Datasnap server with c#

I have a Datasnap Server and i need consuming the data with a windows phone.
The TSituacaoProxy class, when i sends a parameter (Id), the return must be a JSON object.
But the error is shown:
Object reference not set to an instance of an object.
My Code:
private void clique(object sender, RoutedEventArgs e)
{
DSRESTConnection connection = new DSRESTConnection();
connection.setHost("10.0.0.10");
connection.setPort(8080);
connection.setProtocol("http");
connection.setUserName("master");
connection.setPassword("C28861C83BD5397187FD55D04C2547F9");
connection.setContext("datasnap/REST");
DSProxy.TSituacaoProxy Proxy = new DSProxy.TSituacaoProxy(connection, ExceptionCallback);
TJSONObject jObject = TJSONObject.Parse("22");
Proxy.Loader(jObject, (TJSONObject Result) =>
{
MessageBox.Show(Result.ToString());
}, ExceptionCallback);
}
public void ExceptionCallback(Exception e)
{
MessageBox.Show(e.Message);
}
TSituacaoProxy class:
public class TSituacaoProxy : DSAdmin
{
public TSituacaoProxy(DSRESTConnection Connection, ExceptionCallback ExCal)
: base(Connection, ExCal)
{
}
private DSRESTParameterMetaData[] TSituacaoProxy_teste_Metadata;
private DSRESTParameterMetaData[] get_TSituacaoProxy_teste_Metadata()
{
if (TSituacaoProxy_teste_Metadata == null)
{
TSituacaoProxy_teste_Metadata = new DSRESTParameterMetaData[]
{
new DSRESTParameterMetaData("xValue", DSRESTParamDirection.Input, DBXDataTypes.WideStringType, "string"),
new DSRESTParameterMetaData("", DSRESTParamDirection.ReturnValue, DBXDataTypes.WideStringType, "string"),
};
}
return TSituacaoProxy_teste_Metadata;
}
The Loader method:
public delegate void LoaderCallback(TJSONObject Result);
public void Loader(TJSONObject xId, LoaderCallback callback = null, ExceptionCallback ExCal = null)
{
DSRESTCommand cmd = getConnection().CreateCommand();
cmd.setRequestType(DSHTTPRequestType.POST);
cmd.setText("TSituacaoProxy.Loader");
cmd.prepare(get_TSituacaoProxy_Loader_Metadata());
InternalConnectionDelegate LoaderDel = () =>
{
if (callback != null)
{
try
{
callback.DynamicInvoke((TJSONObject)cmd.getParameter(1).getValue().GetAsJSONValue());
}
catch (Exception ex)
{
if (ExCal != null) getConnection().syncContext.Send(new SendOrPostCallback(x => ExCal.DynamicInvoke(ex.InnerException)), null);
else getConnection().syncContext.Send(new SendOrPostCallback(x => BaseExCal.DynamicInvoke(ex.InnerException)), null);
}
}
};
cmd.getParameter(0).getValue().SetAsJSONValue(xId);
getConnection().execute(cmd, this, LoaderDel, ExCal);
}
private DSRESTParameterMetaData[] TSituacaoProxy_Select_Metadata;
private DSRESTParameterMetaData[] get_TSituacaoProxy_Select_Metadata()
{
if (TSituacaoProxy_Select_Metadata == null)
{
TSituacaoProxy_Select_Metadata = new DSRESTParameterMetaData[]
{
new DSRESTParameterMetaData("xAssorts", DSRESTParamDirection.Input, DBXDataTypes.JsonValueType, "TJSONArray"),
new DSRESTParameterMetaData("", DSRESTParamDirection.ReturnValue, DBXDataTypes.JsonValueType, "TJSONArray"),
};
}
return TSituacaoProxy_Select_Metadata;
}
change code in dsrestconnection.cs
this
HttpWebRequest Client = (HttpWebRequest)WebRequest.Create(URL + "?" + DateTime.Now.Ticks.ToString());
to this
HttpWebRequest Client =(HttpWebRequest)WebRequestCreator.ClientHttp.Create(new Uri(URL + "?" + DateTime.Now.Ticks.ToString()));

Categories

Resources