Apache Pulsar: application using DotPulsar - .net-core

I build a small NET Core app to test Pulsar. I am trying to repeat steps described here https://pulsar.apache.org/docs/en/client-libraries-dotnet/
I have added the NuGet DotPulsar.
And I have errors during the compilation.
For example,
var data = Encoding.UTF8.GetBytes("Hello World");
var messageId = await pulsarProducer.NewMessage()
.Property("SomeKey", "SomeValue")
.Send(data);
IProducer does not contains definition for NewMessage() etc. How to fix it?

The 'NewMessage' method on IProducer is actually an extension method, so you need a using statement for 'DotPulsar.Extensions'.
Best regards
db

Related

Reading JS library from CDN within Mirth

I'm doing some testing around Mirth-Connect. I have a test channel that the datatypes are Raw for the source and one destination. The destination is not doing anything right now. In the source, the connector type is JavaScript Reader, and the code is doing the following...
var url = new java.net.URL('https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.fp.min.js');
var conn = url.openConnection();
conn.setRequestMethod('GET');
if(conn.getResponseCode() === 200) {
var body = org.apache.commons.io.IOUtils.toString(conn.getInputStream(), 'UTF-8');
logger.debug('CONTENT: ' + body);
globalMap.put('_', body);
}
conn.disconnect();
// This code is in source but also tested in destination
logger.debug('FROM GLOBAL: ' + $('_')); // library was found
var arr = [1, 2, 3, 4];
var _ = $('_');
var newArr = _.chunk(arr, 2);
The error I'm getting is: TypeError: Cannot find function chunk in object.
The reason I want to do this is to build custom/internal libraries with unit test and serve them with an internal/company CDN and allow Mirth to consume them.
How can I make the library available to Mirth?
Rhino actually has commonjs support, but mirth doesn't have it enabled by default. Here's how you can use it in your channel.
channel deploy script
with (JavaImporter(
org.mozilla.javascript.Context,
org.mozilla.javascript.commonjs.module.Require,
org.mozilla.javascript.commonjs.module.provider.SoftCachingModuleScriptProvider,
org.mozilla.javascript.commonjs.module.provider.UrlModuleSourceProvider,
java.net.URI
)) {
var require = new Require(
Context.getCurrentContext(),
this,
new SoftCachingModuleScriptProvider(new UrlModuleSourceProvider([
// Search path. You can add multiple URIs to this array
new URI('https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/')
],null)),
null,
null,
true
);
} // end JavaImporter
var _ = require('lodash.min');
require('lodash.fp.min')(_); // convert lodash to fp
$gc('_', _);
Note: There's something funky with the cdnjs lodash fp packages that don't detect the environment correctly and force that weird two stage import. If you use https://cdn.jsdelivr.net/npm/lodash#4.17.15/ instead you only need to do var _ = require('fp'); and it loads everything in one step.
transformer
var _ = $gc('_');
logger.info(JSON.stringify(_.chunk(2)([1,2,3,4])));
Note: This is the correct way to use fp/chunk. In your OP you were calling with the standard chunk syntax.
Additional Commentary
I think it's probably ok to do it this way where you download the library once at deploy time and store it in the globalChannelMap, then retrieve it from the map where needed. It would probably also work to store the require object itself in the map if you wanted to call it elsewhere. It will cache and reuse the object created for future calls to the same resource.
I would not create new Require objects anywhere but the deploy script, or you will be redownloading the resource on every message (or every poll in the case of a Javascript Reader.)
Edit: I guess for an internal webhost, this could be desirable in a Javascript Reader if you intend for it to pick up changes immediately on the next poll without a redeploy, assuming you would be upgrading the library in place instead of incrementing a version
The benefit to using Code Templates, as Vibin suggested is that they get compiled directly into your channel at deploy time and there is no additional fetching step at runtime. Making the library available is as simple as assigning it to your channel.
Even though importing third party libraries could be an option, I was actually looking into this for our team to write our own custom functions, write unit-test for them, and lastly be able to pull that code inside Mirth. I was experimenting with lodash but it was not my end goal to use it, it is. My solution was to do a REST GET call with java in the global script. Your URL would be the GitHub raw URL of the code you want to pull in. Same code of my original question but like I said, the URL is the raw GitHub URL for the function I want to pull in.

Unable to set TimeSpan based parameter on an Azure Service Bus subscription filter using Microsoft.Azure.ServiceBus library

Using the older "Windows.Azure.ServiceBus" library, I am able to setup a SqlFilter that takes as its parameters a TimeSpan, but when I try the same using the "Microsoft.Azure.ServiceBus" library it fails with the following error:
Object is not of supported type: TimeSpan. Only following types are
supported through HTTP: string,int,long,bool,double,DateTime
What I am trying to do:
I want to have 2 subscriptions on my topic (highPriority, normalPriority)
Messages have a user property called "StartDate"
If StartDate <= 1 day, then it should go to highPriority subscription, else it should go to normalPriority. [i.e (StartDate - sys.EnqueuedDateTimeUtc) <= 24 hours].
Code that works (when using the older .net-framework Windows.Azure.ServiceBus package):
SqlFilter highMessagesFilter =
new SqlFilter("(StartDate-sys.EnqueuedTimeUtc) <= #TimeSpanImmediateWindow");
highMessagesFilter.Parameters.Add("#TimeSpanImmediateWindow", TimeSpan.FromDays(1));
var subscription = SubscriptionClient.CreateFromConnectionString(connectionString,topicName, subName1);
subscription.RemoveRule(RuleDescription.DefaultRuleName);
subscription.AddRule(new RuleDescription()
{
Name = RuleDescription.DefaultRuleName,
Filter = highMessagesFilter,
Action = new SqlRuleAction("set priorityCalc = (StartDate-sys.EnqueuedTimeUtc)")
});
Where as, this code (using: Microsoft.Azure.ServiceBus) doesnt work:
var filter = new SqlFilter("(StartDate-sys.EnqueuedTimeUtc) <= #TimeSpanHoursImmediateWindow");
filter.Parameters.Add("#TimeSpanHoursImmediateWindow",TimeSpan.FromDays(1));
var ruleDescription = new RuleDescription
{
Filter = filter,
Action = new SqlRuleAction(#"
SET HighPriority = TRUE;
SET Window = StartDate - sys.EnqueuedTimeUtc
"),
Name = RuleDescription.DefaultRuleName,
};
await managementClient.UpdateRuleAsync(topicPath,subscriptionName,ruleDescription);
The above code throws the following error:
Object is not of supported type: TimeSpan. Only following types are
supported through HTTP: string,int,long,bool,double,DateTime
If instead of managementClient.UpdateRuleAsync, I try using the following code:
var subClient = new SubscriptionClient(connectionString, topicPath, subscriptionName);
await subClient.RemoveRuleAsync(RuleDescription.DefaultRuleName);
await subClient.AddRuleAsync(ruleDescription);
It fails, with the following error (ServiceBusException):
Message The service was unable to process the request; please retry
the operation. For more information on exception types and proper
exception handling, please refer to
http://go.microsoft.com/fwlink/?LinkId=761101
The microsoft link is to a list of exceptions, and FilterException, but its not!
Here is the stack trace of the 2nd exception:
at
Microsoft.Azure.ServiceBus.Amqp.AmqpSubscriptionClient.OnAddRuleAsync(RuleDescription
description) in
C:\source\azure-service-bus-dotnet\src\Microsoft.Azure.ServiceBus\Amqp\AmqpSubscriptionClient.cs:line
132 at
Microsoft.Azure.ServiceBus.SubscriptionClient.AddRuleAsync(RuleDescription
description) in
C:\source\azure-service-bus-dotnet\src\Microsoft.Azure.ServiceBus\SubscriptionClient.cs:line
499 at UserQuery.Main() in
C:\Users\XXXX\AppData\Local\Temp\LINQPad6_quhgasgl\niqvie\LINQPadQuery.cs:line
82
So my questions are:
Can I use TimeSpan parameters using .net standard library? or will I have to use the older .net framework library if I wanted to use TimeSpans.
Is there a better way to implement what I am trying to do, a way that would work with the newer .net standard library? (FYI: I thought about sending the calculation as the parameter (decimal) and then the parameter would be a double, instead of a TimeSpan). And in fact, thats what I might end up doing.
If the library is throwing an exception stating that TimeSpan is not a supported type, then it's pretty much what you have. Note that the .NET Standard client has two implementations, the ManagementClient and some operations via entity clients, such as subscription client. The latter is implemented using AMQP. ManagementClient is entirely based on HTTP. While it would be ideal to use the AMQP implementation, it's incomplete. I would recommend relying on the ManagementClient. This is likely the reason why modifying rules using a subscription client is throwing an exception.
Regarding a better way - your idea sounds right. As long as it's not a type that the new client doesn't accept. Also, you can raise an issue with the library team at https://github.com/Azure/azure-sdk-for-net/issues if you'd like to know the reason why TimeSpan is no longer supported.

How to create database for a Semantic Logging Application Block with SqlDatabaseSink

How to set up the SQL Server database for Semantic logging.
Does the table for logging information needs to be created earlier?
If yes, what is the schema to be used.
I have the following code :
var listener = new ObservableEventListener();
string connectionString = #"Data Source=nibc2025;Initial Catalog=TreeDataBase;Integrated Security=True;User Id=sa;Password=nous#123";
listener.EnableEvents(AuditingEventSource.Log, EventLevel.LogAlways, Keywords.All);
databaseSubscription = listener.LogToSqlDatabase
(
"Test",
connectionString,
"Traces",
Buffering.DefaultBufferingInterval,
1,
Timeout.InfiniteTimeSpan, 500
);
// The following one line of code is not part of this function.
// It is just added here to show this is how I log my information.
// Inside LogInformation method I call the 'Write' method
AuditingEventSource.Log.LogInformation("sgsgg", "sgsg");
databaseSubscription.Sink.FlushAsync().Wait();
Well, Since this thread gets the most hits on Google regarding Semantic Logging onto SQL DB or even SLAB ...
The scripts to create the DB lies here
\packages\EnterpriseLibrary.SemanticLogging.Database.1.0.1304.0\scripts
And to create the EventSource and Fire the Blocks, information are given here, for a shortcut and quick fix solution
http://entlib.codeplex.com/discussions/540723
Regards,
OK. I got it. the script was in the packages folder. I had overlooked that.

JClouds not able to get the list of images

I have used the code below:
Iterable<Module> modules = ImmutableSet.<Module> of(
new SshjSshClientModule());
ContextBuilder builder = ContextBuilder.newBuilder(provider).endpoint(endpoint)
.credentials(identity, credential)
.modules(modules);
System.out.printf(">> initializing %s%n", builder.getApiMetadata());
ComputeService compute = builder.buildView(ComputeServiceContext.class).getComputeService();
System.out.println(compute1.listImages());
but I am getting the following error message.........
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 787
at org.jclouds.json.internal.DeserializationConstructorAndReflectiveTypeAdapterFactory$DeserializeIntoParameterizedConstructor.read(DeserializationConstructorAndReflectiveTypeAdapterFactory.java:181)
at org.jclouds.json.internal.NullFilteringTypeAdapterFactories$IterableTypeAdapter.readAndBuild(NullFilteringTypeAdapterFactories.java:92)
The code was working... before...
You've definitely hit a bug somewhere between the version of jclouds you're using and whatever version of whatever cloud you're using. We'll need more information to fix this. Please go through the instruction on how to Report a Bug to Apache jclouds.

Help with Replacing implicitly typed VAR variables with their corresponding explicit type

My below code worked fine while running in .NET 4.0 but when I run the same code in .NET 2.0 I am getting an error at var I found that var is not accepted in .NET 2.0 and older but my Plesk 9.0.1 do not allow me to use .NET 4.0 also I cannot upgrade my plesk at this time because of traffic to my server. Well, anybody please convert the below code such that is works even with .NET 2.0. Thanks in advance.
var app = new hMailServer.Application();
app.Authenticate("Administrator", "********");
var domain = app.Domains.get_ItemByName("mydomain.ext");
var account = domain.Accounts.Add();
account.Address = "user#mydomain.ext";
account.Password = "secret";
account.Active = true;
account.MaxSize = 1000;
account.PersonFirstName = "";
account.Save();
Just instead of var what can I use? I tried string which is not accepted. Any idea?
First line I used as hMailServer.Application app = new hMailServer.Application(); Its accepted bur at the var domain and var account .NET 2.0 is not accepting.
Just instead of var what can I use?
Use the actual types (read the documentation of the API you are using to understand what those types are):
hMailServer.Application app = new hMailServer.Application();
app.Authenticate("Administrator", "********");
hMailServer.Domain domain = app.Domains.get_ItemByName("mydomain.ext");
hMailServer.Account account = domain.Accounts.Add();
...
Also note that var was introduced in C# 3.0 and not 4.0.
Basically you need to identify the type of your variables and then declare them.. you could do it by hovering over the variable and visual studio should show you the return type or the type of variable it is.
Or install Resharper (a productivity tool) for visual studio it should assist you with the same.. You can do things like pull out variable for a particular piece of code and it will take care of identifying the type etc of your varaible.. You should be able to get a trial version.
You might have to do this en masse that is why I am suggesting this.
P.S: I am not markerting Resharper.. just a regular user of the software and in awe of the same.

Resources