How to call a constructor function with new - interop

I'm a new with ReScript. I try to use it with Telegraf. I imported telegraf:
#module("telegraf")
How I can call Telegraf constructor?
let tg = new telegraf.Telegraf("bot_token")

Just add the #new annotation:
type t
#module("telegraf") #new
external telegraf: string => t = "Telegraf"
let tg = telegraf("")
generates
var Telegraf = require("telegraf");
var tg = new Telegraf.Telegraf("");
Playground

Related

How to retrieve the extendedProperties associated with emails in the sent folder from exchange

We have created extendedProperties on emails using
val uId = getUniqueId();
val emailExtendedPropDef = new ExtendedPropertyDefinition(uId,"uniqueId", MapiPropertyType.String)
try {
email.setExtendedProperty(emailExtendedPropDef, uId.toString)
email.sendAndSaveCopy()
} catch {
case e: Exception =>
error(s"Exception in setting extended property for user $from", e)
throw e
}
Now we want to iterate over the emails in sent folder and go over the extendedProperties for the emails that have been set
val view = new ItemView(1000)
var extendedPropertyIndex = 0
var bodyList = new ListBuffer[String]()
val propertySet = new PropertySet(BasePropertySet.FirstClassProperties
try {
val findResults = service.findItems(WellKnownFolderName.SentItems, view)
if (findResults.getTotalCount > 0) {
val iterator = findResults.getItems().iterator()
while(iterator.hasNext) {
val item = iterator.next()
val extendedPropertyCollection = item.getExtendedProperties()
println("count is "+extendedPropertyCollection.getCount())
if (extendedPropertyCollection.getCount() > 0)
{
//do some processing
}
}
}
}
We are able to successfully retrieve the items but not their extended properties not sure why
We have been getting the count as 0 eventhough we know for these items we have set the extendedProperty using the above logic ......
It will be of great help if someone could point us in the right direction on why we are receiving 0 count for the extended properties and also our requirement is to retrieve all the emails with extendedProperties set
Update : tried with these options
val emailIdPropDef = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.PublicStrings,"uniqueId", MapiPropertyType.String)
val propertySet = new PropertySet(BasePropertySet.FirstClassProperties, emailIdPropDef)
view.setPropertySet(propertySet)
But still no luck any pointer in the right direction will be of great help
Exchange will only return the extended properties you request it to return. So you need to add the extended property to the PropertySet your using in the FindItems operation and it will then get returned if it has been set on any objects that FindItem returns.eg this property
val emailExtendedPropDef = new ExtendedPropertyDefinition(uId,"uniqueId", MapiPropertyType.String)
needs to be added to this Propertyset
val propertySet = new PropertySet(BasePropertySet.FirstClassProperties)
and that property set should be used on this ItemView
val view = new ItemView(1000)
val.PropertySet = propertySet

Use IConfService to query object by Attributes

How do I query objects by attribute (instead of 'Filter Keys') using the Genesys Platform SDK?
Endpoint endpoint = new Endpoint("DEV", "the host", 12020);
endpoint.ServicePrincipalName = "the host/the principle";
_confServerProtocol = new ConfServerProtocol(endpoint);
_confServerProtocol.ClientApplicationType = (int)CfgAppType.CFGSCE;
_confServerProtocol.ClientName = "default";
_confServerProtocol.UserName = "the userid";
_confServerProtocol.Open();
IConfService confService = ConfServiceFactory.CreateConfService(_confServerProtocol);
CfgPersonQuery query = new CfgPersonQuery();
// Need to filter based on an Attribute Value (specifically externalID)
var foo = confService.RetrieveMultipleObjects<CfgPerson>(query);
This worked for me:
CfgXPathBasedQuery query = new CfgXPathBasedQuery(confService, CfgObjectType.CFGPerson, "CfgPerson[#externalID='the value']");
Use below:
Uri uri = new Uri("tcp://Host:Port");
Endpoint endpoint = new Endpoint(Guid.NewGuid().ToString(), uri);
ConfServerProtocol confProtocol = new ConfServerProtocol(endpoint);
confProtocol.ClientApplicationType = (int)CfgAppType.CFGSCE;
confProtocol.ClientName = "default";
confProtocol.UserName = "xxxxxx";
confProtocol.UserPassword = "xxxxxx";
//Channel Open
confProtocol.Open();
IConfService confService = ConfServiceFactory.CreateConfService(confProtocol);
CfgPersonQuery query = new CfgPersonQuery();
query.UserName = "AgentID";
CfgPerson person = confService.RetrieveObjects<CfgPerson>(query);
string ExtID = person.ExternalId;
Note: In this way, Filtering is not possible through ExternalId.

SignatureVerificationFailedException in JwtAuthForWebAPI

I have wired up the JwtAuthForWebAPI nuget project but I am not able to validate the generated tokens. I end up getting a 500 error. I am using the exact same key value for both token generation and also when configuring JwtAuthenticationMessageHandler.
This is the code to generate a token:
var tokenHandler = new JwtSecurityTokenHandler();
var symmetricKey = JsonWebTokenSecretKey.GetBytes();
var now = DateTime.UtcNow;
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(
new[]{
new Claim(JwtClaimKeys.Audience, SessionManager.Current.ApplicationId.ToString()),
new Claim(JwtClaimKeys.Subject, userLoginRequest.ApplicationInstanceId.ToString())
}),
TokenIssuerName = "My Company",
Lifetime = new Lifetime(now, now.AddMinutes(tokenLifetimeInMinutes)),
SigningCredentials = new SigningCredentials(
new InMemorySymmetricSecurityKey(symmetricKey),
"http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
"http://www.w3.org/2001/04/xmlenc#sha256")
};
tokenDescriptor.Subject.AddClaims(GetRoles(userLoginRequest));
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
This is the code to register the authentication handler:
var keyBuilder = new SecurityTokenBuilder();
var jwtHandler = new JwtAuthenticationMessageHandler
{
Issuer = "My Company",
AllowedAudience = ApplicationId.ToString(),
SigningToken = keyBuilder.CreateFromKey(JsonWebTokenSecretKey),
PrincipalTransformer = new MyUserPrincipleTransformer()
};
config.MessageHandlers.Add(jwtHandler);
This is the error I get:
{"Message":"An error has occurred.","ExceptionMessage":"IDX10503: Signature validation failed. Keys tried: 'System.IdentityModel.Tokens.InMemorySymmetricSecurityKey\r\n'.\nExceptions caught:\n ''.\ntoken: '{\"typ\":\"JWT\",\"alg\":\"HS256\"}.{\"aud\":\"1\",\"sub\":\"3\",\"role\":[\"User\",\"Admin\"],\"iss\":\"My Company\",\"exp\":1429547369,\"nbf\":1429543769}'","ExceptionType":"System.IdentityModel.SignatureVerificationFailedException",
"StackTrace":"
at System.IdentityModel.Tokens.JwtSecurityTokenHandler.ValidateSignature(String token, TokenValidationParameters validationParameters)\r\n
at System.IdentityModel.Tokens.JwtSecurityTokenHandler.ValidateToken(String securityToken, TokenValidationParameters validationParameters, SecurityToken& validatedToken)\r\n
at JwtAuthForWebAPI.JwtSecurityTokenHandlerAdapter.ValidateToken(IJwtSecurityToken securityToken, TokenValidationParameters validationParameters)\r\n
at JwtAuthForWebAPI.JwtAuthenticationMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n
at System.Web.Http.HttpServer.<SendAsync>d__0.MoveNext()"}
This is an example JSON token:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwic3ViIjoiMyIsInJvbGUiOlsiVXNlciIsIkFkbWluIl0sImlzcyI6Ik15IENvbXBhbnkiLCJleHAiOjE0Mjk1NTE4MjgsIm5iZiI6MTQyOTU0ODIyOH0.9wA_RBir9u7Cn_-Fy2T-Q_IDUfz6B928IEbIgXD9Bug
Interestingly, I am able to validate the token with my key using http://jwt.io. I suspect it may have something to do with the JwtAuthForWebAPI library looking at something different than what the System.Identity JWT library is generating?
this is Jamie (author of the JwtAuthForWebAPI package). The server config code - specifically, SecurityTokenBuilder.CreateFromKey(string) - assumes the given string is base64 encoded. It was either that, or assumptions or parameters are needed that would indicate which encoding to use for converting to a byte array. I chose to assume the string was base64 encoded. I'm sure there's a clearer way to go about converting the string key into a SecurityToken, but that's the way the code is today.
In SmokeTests.cs within the JwtAuthForWebAPI.SampleClient project, you can see that I used the Convert.FromBase64String() method, as opposed to using the GetBytes() method from an Encoding class:
public const string SymmetricKey = "YQBiAGMAZABlAGYAZwBoAGkAagBrAGwAbQBuAG8AcABxAHIAcwB0AHUAdgB3AHgAeQB6ADAAMQAyADMANAA1AA==";
// ...
var key = Convert.FromBase64String(SymmetricKey);
var credentials = new SigningCredentials(
new InMemorySymmetricSecurityKey(key),
"http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
"http://www.w3.org/2001/04/xmlenc#sha256");
Feel free to keep using your current token generation code, but on the server...
Please try specifying a base64 encoded version of JsonWebTokenSecretKey in the server configuration code. You can use a site like https://www.base64encode.org/ to encode it, or try code like this:
var base64key = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonWebTokenSecretKey));
var keyBuilder = new SecurityTokenBuilder();
var jwtHandler = new JwtAuthenticationMessageHandler
{
Issuer = "My Company",
AllowedAudience = ApplicationId.ToString(),
SigningToken = keyBuilder.CreateFromKey(base64key),
PrincipalTransformer = new MyUserPrincipleTransformer()
};
Let me know whether or not that works.
Also, I'm going to update the library to catch the SignatureVerificationFailedException exception and return a 401, as opposed to letting an internal server error happen. You'll still need to specify your key as a base64 string, but at least such configuration issues won't cause a 500 error.
Again, please let me know if that does the trick.
it's just my code sample base on #Jamie answer
protected string GetUsername(string token)
{
string secret = "keyyyyy!#3";
var key = Convert.FromBase64String(secret);
var IssuerSigningKey = new SymmetricSecurityKey(key);
IdentityModelEventSource.ShowPII = true;
var SigningCredentials = new SigningCredentials(
IssuerSigningKey,
SecurityAlgorithms.HmacSha256Signature);
var handler = new JwtSecurityTokenHandler();
var tokenSecure = handler.ReadToken(token) as SecurityToken;
var validations = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = IssuerSigningKey,
ValidateIssuer = false,
ValidateAudience = false
};
var claims = handler.ValidateToken(token, validations, out tokenSecure);
return claims.Identity.Name;
}

how can manual create a ODataQueryOptions on .ashx

i would like to reconstruction my last project.
in past, i did't use any Web API.
can i just use the ODataQueryOptions to do $filter, $orderby , $top ,$skip
for my query in my own handler.ashx ?
some thing like.
var option = new ODataQueryOptions(request.params);
var query = option.ApplyTo(db.products);
Based on sfuqua's answer above I made my own helper class that builds OdataQueryOptions class based on Odata Uri:
using System.Linq;
using System.Net.Http;
using System.Web.Http.OData;
using System.Web.Http.OData.Builder;
using System.Web.Http.OData.Query;
namespace OdataHelpers
{
public static class ODataBuilder<T>
{
public static ODataQueryOptions<T> BuildOptions(string oDataUri)
{
var baseUri = "";
var odUri = "";
var spl = oDataUri.Split('?');
if (spl.Count() == 0)
odUri = spl[0];
else
{
baseUri = spl[0];
odUri = spl[1];
}
if (string.IsNullOrEmpty(baseUri))
baseUri = "http://localhost/api/" + typeof(T).Name;
var request = new HttpRequestMessage(HttpMethod.Get, baseUri + "?" + oDataUri.Replace("?", ""));
var modelBuilder = new ODataConventionModelBuilder();
modelBuilder.AddEntity(typeof(T));
var edmModel = modelBuilder.GetEdmModel();
var oDataQueryContext = new ODataQueryContext(edmModel, typeof(T));
return new ODataQueryOptions<T>(oDataQueryContext, request);
}
}
}
Example use:
var OdataStuff = ODataBuilder<CustomerIntView>.BuildOptions("$orderby=Id");
One way to accomplish this is by manually constructing the request URI and setting that in the request parameter of the ODataQueryOptions constructor. So this may not be precisely what the original poster was looking for (question needed some clarification).
In my case I have a unit test, and I wanted to validate that the odata options were being applied to my queryable object. In the following sample code, assume that you are testing a ProductController that has a ProductName field in it.
// Manually set an OData query parameter
const string restUrl = "http://localhost/api/product?$orderby=ProductName";
// Need to construct an HTTP Context and a Request, then inject them into the controller
var config = new HttpConfiguration();
var request = new HttpRequestMessage(HttpMethod.Post, restUrl);
var route = config.Routes.MapHttpRoute(WebApiConfig.DefaultRouteName, "api/{controller}/{id}");
var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "Product" } });
var controller = new ProductController()
{
Request = request,
ControllerContext = new HttpControllerContext(config, routeData, request),
Url = new UrlHelper(request)
};
// Build up the OData query parameters
var modelBuilder = new ODataConventionModelBuilder();
modelBuilder.AddEntity(typeof(Product));
var edmModel = modelBuilder.GetEdmModel();
var oDataQueryContext = new ODataQueryContext(edmModel, typeof(Product));
var oDataQueryOptions = new ODataQueryOptions<Product>(oDataQueryContext, _controller.Request);
// Finally, call the controller
var result = controller.Get(oDataQueryOptions);
I do think you can if you can constructor an instance of ODataQueryOptions.
But, What's this:
var option = new ODataQueryOptions(request.params);
Web API doesn't provide such constructor. Is it your own implementation?
Thanks.

How to produce a Subquery using non-generic Lambda2

i'm very new to LINQ? please help me
How would you translate the following generic Lambda function into a lambda expression :
objects.Where(objects=>values.Contains(objects.DistrictId) );
I'm trying to create a full lambda expression without any or direct call. Something like :
var innerItem = Expression.Parameter(typeof(Objects), "objects");
var innerProperty = Expression.Property(innerItem, "ID");
var innerMethodExpression = Expression.Call(innerProperty,null);
var innerLambda = Expression.Lambda<Func<Objects, bool>>(innerMethodExpression, innerItem);
var outerItem = Expression.Parameter(typeof(int[]), "item");
var containsMethod = typeof(string).GetMethod("Contains", new[] { typeof(int) });
var containsMethodExpression = Expression.Call(innerMethodExpression, containsMethod, innerLambda);
var outerLambda = Expression.Lambda<Func<Objects, bool>>(containsMethodExpression, outerItem);
collection = collection.AsQueryable<Objects>().Where(outerLambda);
But i can't understand what is wrong
In your example,
The Lambda function is
objects.Where(objects=>values.Contains(objects.DistrictId) );
so your lambda expression should be
Expression<Func<Objects, int>> ObjectsExp = objects=>values.Contains(objects.DistrictId);
Assume DistrictId is integer type for your out Result.

Resources