How call `StreamJsonRpc` server side template function on client side - rpc

When I use Microsoft StreamJsonRpc library, I can not find the solution of on client side call RPC server side template function. Server side has class GreeterServer that contains a template function SetPerson, how should I set the params to invoke it on client side with JsonRpc.InvokeAsync method?
//server side
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class GreeterServer
{
public bool SetPerson<T>(T value)
{
if (typeof(T) == typeof(Person))
{
(value as Person).Age = 15;
}
return true;
}
}
//client side
var ret = (await jsonRpc.InvokeAsync<bool>("SetPerson", ??));

Related

MS Text Analytics Cognitive Service: how to work with local database?

Microsoft provides a service to analyze text data called Text Analytics Cognitive Service.
Is it possible to use this service with local database? i.e. not in Azure
I work with some large databases and as for me it can be interesting to use it for:
Language detection
Key phrase extraction
Named Entity recognition
Sentiment analysis
Once you pull your data that you would like to detect its language
from your local database, you just need to fetch it then just pass in
below method. It would analysis your value in response.
API Access Keys:
private static readonly string endpointKey = "YourEndPonitKey";
private static readonly string endpoint = "https://YourServiceURL.cognitiveservices.azure.com/text/analytics/v2.1/languages";
Code Snippet:
public async Task<object> DetectLanguageAsync(string InputFromDbOrUser)
{
try
{
DetectedLanguageResponseModel ObjDitectedLanguageResponse = new DetectedLanguageResponseModel();
//Create laguage detection request param
RequestModel objRequestModel = new RequestModel();
objRequestModel.id = "1";
objRequestModel.text = InputFromDbOrUser;
//Made Document List
List<RequestModel> Objdocuments = new List<RequestModel>();
Objdocuments.Add(objRequestModel);
//Bind Request Model
LanguageDetection objRequestList = new LanguageDetection();
objRequestList.documents = Objdocuments;
// Bind and Serialize Request Object
var serializedObject = JsonConvert.SerializeObject(objRequestList);
// Call Language Detection API
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint);
request.Content = new StringContent(serializedObject, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", endpointKey);
var response = await client.SendAsync(request);
//Check status code and retrive response
if (response.IsSuccessStatusCode)
{
ResponseModel objResponse = JsonConvert.DeserializeObject<ResponseModel>(await response.Content.ReadAsStringAsync());
//Check Response List
foreach (var item in objResponse.documents)
{
//Checkings Empty Response and Return to Caller
if (objResponse.documents != null)
{
ObjDitectedLanguageResponse.Language = objResponse.documents[0].detectedLanguages[0].name;
return ObjDitectedLanguageResponse;
}
else
{
return "Sorry, I am not able to find a related topic! Would you like me to Bing Search?";
}
}
}
else
{
var result_string = await response.Content.ReadAsStringAsync();
return result_string;
}
}
return ObjDitectedLanguageResponse;
}
catch (Exception ex)
{
throw new NotImplementedException(ex.Message, ex.InnerException);
}
}
Class Used:
public class DetectedLanguage
{
public string name { get; set; }
public string iso6391Name { get; set; }
}
public class DetectedLanguageResponseModel
{
public dynamic Language { get; set; }
}
public class LanguageDetection
{
public List<RequestModel> documents { get; set; }
}
public class RequestModel
{
public string id { get; set; }
public string text { get; set; }
}
public class ResponseDocument
{
public string id { get; set; }
public List<DetectedLanguage> detectedLanguages { get; set; }
}
public class ResponseModel
{
public List<ResponseDocument> documents { get; set; }
public List<object> errors { get; set; }
}
Note: The current limit is 5,120 characters for each document; if you need to analyze larger documents, you can break them up into
smaller chunks for more you could refer official document
Hope that would help. If you need more implementation assistance please have a look on here

Error when adding Where or OrderBy clauses to Azure Mobile Apps request

I'm developing an Azure Mobile App service to interface to my Xamarin application.
I've created, connected and successfully populated an SQL Database, but when I try to add some filters to my request, for example an orderby() or where() clauses, it returns me a Bad Request error.
For example, this request: https://myapp.azurewebsites.net/tables/Race?$orderby=iRound%20desc,iYear%20desc&$top=1&ZUMO-API-VERSION=2.0.0 gives me {"message":"The query specified in the URI is not valid. Could not find a property named 'IYear' on type 'MyType'."}.
My configuration method is this:
HttpConfiguration config = new HttpConfiguration();
new MobileAppConfiguration()
.AddTablesWithEntityFramework()
.ApplyTo(config);
config.MapHttpAttributeRoutes();
Database.SetInitializer(new CreateDatabaseIfNotExists<MainDataContext>());
app.UseWebApi(config);
and my DbContext is this:
public class MainDataContext : DbContext
{
private const string connectionStringName = "Name=MS_TableConnectionString";
public MainDataContext() : base(connectionStringName)
{
Database.Log = s => WriteLog(s);
}
public void WriteLog(string msg)
{
System.Diagnostics.Debug.WriteLine(msg);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(
new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>(
"ServiceTableColumn", (property, attributes) => attributes.Single().ColumnType.ToString()));
}
public DbSet<Race> Race { get; set; }
public DbSet ...ecc...
}
Following this guide, I added a migration after creating my TableControllers. So the TableController for the example type shown above is pretty standard:
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
public class RaceController : TableController<Race>
{
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
MainDataContext context = new MainDataContext();
DomainManager = new EntityDomainManager<Race>(context, Request);
}
// GET tables/Race
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
public IQueryable<Race> GetAllRace()
{
return Query();
}
// GET tables/Race/48D68C86-6EA6-4C25-AA33-223FC9A27959
public SingleResult<Race> GetRace(string id)
{
return Lookup(id);
}
// PATCH tables/Race/48D68C86-6EA6-4C25-AA33-223FC9A27959
public Task<Race> PatchRace(string id, Delta<Race> patch)
{
return UpdateAsync(id, patch);
}
// POST tables/Race
public async Task<IHttpActionResult> PostRace(Race item)
{
Race current = await InsertAsync(item);
return CreatedAtRoute("Tables", new { id = current.Id }, current);
}
// DELETE tables/Race/48D68C86-6EA6-4C25-AA33-223FC9A27959
public Task DeleteRace(string id)
{
return DeleteAsync(id);
}
}
As you can see, I already tried to add the EnableQuery attribute to my TableController, as seen on Google. I also tried to add these filters to the HttpConfiguration object, without any success:
config.Filters.Add(new EnableQueryAttribute
{
PageSize = 10,
AllowedArithmeticOperators = AllowedArithmeticOperators.All,
AllowedFunctions = AllowedFunctions.All,
AllowedLogicalOperators = AllowedLogicalOperators.All,
AllowedQueryOptions = AllowedQueryOptions.All
});
config.AddODataQueryFilter(new EnableQueryAttribute
{
PageSize = 10,
AllowedArithmeticOperators = AllowedArithmeticOperators.All,
AllowedFunctions = AllowedFunctions.All,
AllowedLogicalOperators = AllowedLogicalOperators.All,
AllowedQueryOptions = AllowedQueryOptions.All
});
I don't know what to investigate more, as things seems to be changing too fast for a newbie like me who's first got into Azure.
EDIT
I forgot to say that asking for the complete table, so for example https://myapp.azurewebsites.net/tables/Race?ZUMO-API-VERSION=2.0.0, returns correctly the entire dataset. The problem occurs only when adding some clauses to the request.
EDIT 2
My model is like this:
public class Race : EntityData
{
public int iRaceId { get; set; }
public int iYear { get; set; }
public int iRound { get; set; }
ecc..
}
and the database table that was automatically created is this, including all the properties inherited from EntityData:
Database table schema
Digging into the source code, Azure Mobile Apps sets up camelCase encoding of all requests and responses. It then puts them back after transmission accordign to rules - so iRaceId becomes IRaceId on the server.
The easiest solution to this is to bypass the auto-naming and use a JsonProperty attribute on each property within your server-side DTO and client-side DTO so that they match and will get encoding/decoded according to your rules.
So:
public class Race : EntityData
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("raceId")]
public int iRaceId { get; set; }
[JsonProperty("year")]
public int iYear { get; set; }
[JsonProperty("round")]
public int iRound { get; set; }
etc..
}

Is it normal to return actor's proxy from service

I have some service which accepts some data and then, as I think, should return an actor initialized with some values.
public class MyService : StatefulService, IMyService
{
public IMyActor DoThings(Data data)
{
var actor = ActorProxy.Create<IMyActor>(new ActorId(Guid.NewGuid()));
actor.Init(data);
//some other things
return actor;
}
}
Another service would do this:
var service = ServiceProxy.Create<ICommandBrokerService>(new Uri("fabric:/App"), ServicePartitionKey.Singleton);
var actor = service.DoThings(data);
var state = actor.GetState();
//...
So, is it okay to return an actor in such a way, or should I return actor's id and request a proxy on a call sight?
UPD:
According to a #LoekD 's answer I did a wrapper to be a little type-safety.
[DataContract(Name = "ActorReferenceOf{0}Wrapper")]
public class ActorReferenceWrapper<T>
{
[DataMember]
public ActorReference ActorReference { get; private set; }
public ActorReferenceWrapper(ActorReference actorRef)
{
ActorReference = actorRef ?? throw new ArgumentNullException();
}
public T Bind()
{
return (T)ActorReference.Bind(typeof(T));
}
public IActorService GetActorService(IActorProxyFactory serviceProxy=null)
{
return ActorReference.GetActorService(serviceProxy);
}
public TService GetActorService<TService>(IActorProxyFactory serviceProxyFactory) where TService : IActorService
{
return serviceProxyFactory.CreateActorServiceProxy<TService>(ActorReference.ServiceUri,
ActorReference.ActorId);
}
public static implicit operator ActorReference(ActorReferenceWrapper<T> actorRef)
{
return actorRef.ActorReference;
}
public static explicit operator ActorReferenceWrapper<T>(ActorReference actorReference)
{
return new ActorReferenceWrapper<T>(actorReference);
}
}
No, the types used in SF remoting must be DataContractSerializable. The contracts you use can only have fields and properties, no methods.
So, instead of returning the proxy, return an Actor Reference.
Next, use Bind to create a proxy from it.

Servicestack : From route to operation

Can I retrieve the operation DTO from url route inside a service stack service ?
Example :
public class HelloService : IService
{
public object Any(HelloRequest request)
{
//Here I want to retrieve operation Dto.
//In this case if request.AnotherApiRoute is "/another?Age=33"
//then result could be operation AnotherRequest
return new HelloResponse { Result = "Hello, " + name };
}
}
public class AnotherApiService : IService
{
public object Another(AnotherRequest request)
{
return new AnotherResponse { Result = "Your Age : " + Age };
}
}
//OPERATIONS
[Route("/hello/{Name}")]
public class Hello : IReturn<HelloResponse>
{
public string Name { get; set; }
public string AnotherApiRoute {get; set;}
}
public class HelloResponse
{
public string Result { get; set; }
}
[Route("/another/{Age}")]
public class AnotherRequest : IReturn<AnotherResponse>
{
public string Age { get; set; }
}
public class AnotherResponse
{
public string Result { get; set; }
}
Thanks for your suggests
If you want access to the HTTP Request Context the Service was executed in you should inherit from the convenience Service base class (or have your service also implement IRequiresRequestContext so Request is injected), e.g:
public class HelloService : Service
{
public object Any(Hello request)
{
var pathInfo = base.Request.PathInfo;
return new HelloResponse { Result = "Hello, " + name };
}
}
But what you're after is unclear since the Request DTO is the Operation DTO for that request. If instead you wanted to call another Service from within your Service you can do it with Resolving the Service from the IOC (which also injects the current HTTP Request) with:
public class HelloService : Service
{
public object Any(Hello request)
{
using (var service = base.ResolveService<AnotherService>())
{
var anotherDto = request.ConvertTo<Another>();
return service.Any(anotherDto);
}
}
}
Alternatively you can just execute the Service by passing in the Request DTO, and let ServiceStack call the appropriate Service, e.g:
public class HelloService : Service
{
public object Any(Hello request)
{
var anotherDto = request.ConvertTo<Another>();
return base.ExecuteRequest(anotherDto);
}
}

Deserializing a json string to C#.net classes using JsonConvert.DeserializeObject (v 4.0.8.14612)

In my web app, I have written some tests to test my deserializing logic that parses a json string in to my C# classes. These tests runs fine on my computer, but they fail on our CI environment with this error message:
Test(s) failed. System.TypeInitializationException : The type initializer for 'Newtonsoft.Json.JsonConvert' threw an exception. ----> System.Security.VerificationException : Operation could destabilize the runtime.
One json string example is this (from the test class):
private const string MatrikkelJson = "{'Gaardsnummer':'9','Bruksnummer':'9','Festenummer':'8','Seksjonsnummer':'8','BlankAllowed':'False','AttrType':'Matrikkel'}";
This string should be deserialized to this class:
public class MatrikkelDTO : AttributeBaseDTO
{
public string Gaardsnummer { get; set; }
public string Bruksnummer { get; set; }
public string Festenummer { get; set; }
public string Seksjonsnummer { get; set; }
}
public class AttributeBaseDTO
{
public bool BlankAllowed { get; set; }
public string AttrType { get; set; }
}
The method that deserializes the json string works like this:
I first deserialize the baseobject to get the AttrType property. Using that information I deserialize the json string to the specific type (I have several classes that inherits from AttributBaseDTO.
public AttributeValidationHandlerResponse ValidateAttribute(string serializedObject)
{
var response = new AttributeValidationHandlerResponse();
response.Result = false;
//hack... this handler gets called when opening newdocument.aspx. don't know why.
if (serializedObject.Contains("function"))
{
response.Message = "";
return response;
}
if (String.IsNullOrEmpty(serializedObject))
{
response.Message = "attributeobject";
return response;
}
var message = "";
var attributeBase = JsonConvert.DeserializeObject<AttributeBaseDTO>(serializedObject);
if (attributeBase.AttrType == "Matrikkel")
{
var attribute = ConvertJsonStringToAttribute<MatrikkelDTO>(serializedObject);
response = ValidateMatrikkel(attribute);
}
return response;
}
internal T ConvertJsonStringToAttribute<T>(string serializedObject)
{
return JsonConvert.DeserializeObject<T>(serializedObject);
}
But I can't figure out why it works on my machine and not on the build server.
I'm using VS 2010, asp.net 4.0, net framework 4.0. Test framework is nunit 2.5.5
Any clues anyone?

Resources