I want to create small app to parse sms. I use Visual Studio with Xamarin.
I found these peace of code and want to adapt is for my need.
But getContentResolver() method is not defined. I know, that it needs application context, but i don't understand how to get it.
Could someone give me an example please?
// Create Sent box URI
Uri sentURI = Uri.parse("content://sms/sent");
// List required columns
String[] reqCols = new String[] { "_id", "address", "body" };
// Get Content Resolver object, which will deal with Content Provider
ContentResolver cr = getContentResolver();
// Fetch Sent SMS Message from Built-in Content Provider
Cursor c = cr.query(sentURI, reqCols, null, null, null);
In Java world, you'll see methods like getContentResolver and setContentResolver. In Xamarin and C# those two will be combined to one property called ContentResolver. The latter part of your code should be like this:
// Fetch Sent SMS Message from Built-in Content Provider
Cursor c = ContentResolver.Query(sentURI, reqCols, null, null, null);
When porting Java code to C# (Xamarin), you can usually get basic stuff to work by capitalizing method names. With that logic, you should also modify the first line to this:
Uri sentURI = Uri.Parse("content://sms/sent");
However, this is a very simplified example. Knowing both Java and C# and how to use both the Android and Xamarin documentation will take you quite far.
Related
Hi I am using Microsoft Cognitive Services and it's giving me an exception for some unknown reason. This is the way I declared FaceServiceRestClient:
var faceServiceClient = new FaceServiceRestClient("MY_KEY");
when I run above code it throws an exception by saying "Your Subscription key is invalid". I checked 3-4 times Key is correct, I also regenerated key and used it still exception is there.
Now, I added second parameter, thats URL so not my declaration is as follows:
var faceServiceClient = new FaceServiceRestClient("MY_KEY", "https://australiaeast.api.cognitive.microsoft.com/face/v1.0" );
For above statement I get an exception as "Java.Lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=MY_KEY/detect"
This is how I am calling detect method (If you want to see)
Com.Microsoft.Projectoxford.Face.Contract.Face[] result = faceServiceClient.Detect(#params[0], true, false, null);
I do not understand exactly where to look at or which declaration is correct. & BTW this is Xamarin application and I used Xamarin.Microsoft.Cognitive.Face package. If you want to anything else in my code please Comment I will share code snippet.
Can anyone please help?
Thank you
"Java.Lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=MY_KEY/detect"
That package wraps the Android/Java API and that API is different then the other platforms. In the case of FaceServiceRestClient, the Azure Face Endpoint is the first param, and your Face API key is the second.
Note: They did not even name the parameters in the binding library so you will see param names such as p0 p1 throughout the C# API :-( I ended up using Rekognition to work around the throughput limitations of Cognitive services, but that is a different story)
I stripped down a camera/photo tagger that I wrote to get you started.
Example:
await Task.Run(() =>
{
var faceServiceClient = new FaceServiceRestClient(faceEndpoint, faceAPIKey);
using (var imageFileStream = camera.SingleImageStream)
{
var faceAttributes = new FaceServiceClientFaceAttributeType[] { FaceServiceClientFaceAttributeType.Gender, FaceServiceClientFaceAttributeType.Age, FaceServiceClientFaceAttributeType.Smile, FaceServiceClientFaceAttributeType.Glasses, FaceServiceClientFaceAttributeType.FacialHair };
var faces = faceServiceClient.Detect(imageFileStream, true, false, faceAttributes);
foreach (var face in faces)
{
Log.Debug(TAG, $"{face.FaceRectangle.Left}:{face.FaceRectangle.Top}:{face.FaceRectangle.Width}:{face.FaceRectangle.Height}");
DrawFaceRect(face.FaceRectangle);
TagPhoto(face.FaceAttributes);
}
}
});
I am using Discord.NET version 1.0.2 to clear things up
I have a MessageReceived Task in my Discord Bot application:
private async Task MessageReceived(SocketMessage message)
This task, as can already be deducted, runs every time a message is received in Discord to this bot. I am trying to figure out how to add a reaction to a message that the bot has received, however. Under SocketMessage there are no methods to add reactions to the message received. I looked online and found that RestUserMessage contains the method AddReactionAsync(IEmote, RequestOptions). I then casted Socket Message to a RestUserMessage as so
var rMessage = (RestUserMessage) await message.Channel.GetMessageAsync(message.Id);
Running the AddReactionAsync method under my variable rMessage for RestUserMessage works, but the parameters are not taken correctly as I can perceive from my reading online and the documentation.
IEmote appears to be a string, but a string does not fulfill this parameter, saying that there is no conversion from a String to an IEmote. I tried casting this String to an IEmote but that did not work.
The RequestOptions variable seems to fulfill the parameter perfectly fine as a new RequestOptions().
My full code for this is:
private async Task MessageReceived(SocketMessage message)
{
var rMessage = (RestUserMessage) await message.Channel.GetMessageAsync(message.Id);
rMessage.AddReactionAsync(???, new RequestOptions());
}
How do I fulfill this IEmote parameter correctly and or how do I define an IEmote variable. Also, is defining a new RequestOptions() variable the correct thing to fulfill this parameter as well. Is this also the correct way to add reactions to a message through Discord.NET and if not what is?
The research I have done:
https://github.com/RogueException/Discord.Net/issues/490
https://discord.foxbot.me/docs/api/Discord.Rest.RestUserMessage.html
https://discord.foxbot.me/docs/api/Discord.IEmote.html
https://discord.foxbot.me/docs/api/Discord.RequestOptions.html
If you head over to Emojipedia, and grab the unicode version as shown below :
After that is copied, you have to create a new Emoji object, like so :
var YourEmoji = new Emoji("😀");
You can then add a reaction to the desired message, I'm going to use Context.Message :
Context.Message.AddReactionAsync(YourEmoji);
Unknown's solution works for regular emotes, but won't work for guild-specific emotes.
This is the solution I came up with:
SocketGuild guild = ((SocketGuildChannel) message.Channel).Guild;
IEmote emote = guild.Emotes.First(e => e.Name == "my-custom-emote");
message.AddReactionAsync(emote);
You already found the way to adding the emoji, but I'll follow up with an additional way of adding a guild emoji to a message. You'd need the raw string of the emoji in this case. Don't confuse it with Emoji, Emoji represents an Unicode emoji, but Emote is from Discord.Net and stands for a custom emoji. The AddReactionAsync method accepts both objects thanks to the IEmote interface.
Emote emote = Emote.Parse("<:craig_cat:603083214281506817>")
In this case, we're creating an Emote object with the emoji called craig_cat and the provided ID.
In order to get the raw string to parse, in your Discord client, simply send the emoji (:craig_cat:), but with a backslash (\) before it.
Note, in case of an animated emoji, it will look like the following:
Emote emote = Emote.Parse("<a:running:703588456198307900>")
There has to be an a before the punctuation mark to identify it as an animated emoji.
In both cases, you can add it to the message by these examples:
Context.Message.AddReactionAsync(emote); //Adds the reaction to the user's message that triggered the task (works only in a command)
Most of the other interfaces/objects also support this method, casting would help though.
You can also use this raw format at any time to include the emoji in a message.
I am new to JINT, and trying to just do some basic tests to kind of learn the ropes. My first attempt was to just store some javascript in my database, load it, and execute it in a unit test. So that looks essentially like this....
[Fact]
public void can_use_jint_engine() {
using (var database = DocumentStore()) {
using (var session = database.OpenSession()) {
var source = session.Load<Statistic>("statistics/1");
// join the list of strings into a single script
var script = String.Join("\n", source.Scripting);
// this will create the script
// console.log("this is a test from jint.");
//
var engine = new Jint.Engine();
// attempt to execute the script
engine.Execute(script);
}
}
}
And it doesn't work, I get this error, which makes absolutely no sense to me, and I cannot find any documentation on.
Jint.Runtime.JavaScriptExceptionconsole is not defined at
Jint.Engine.Execute(Program program) at
Jint.Engine.Execute(String source) at
SampleProject.Installers.Instanced.__testing_installer.can_use_jint_engine()
in _testing_installer.cs: line 318
Can anyone assist in shedding some light on this? I'm pretty confused at this point.
With JavaScript there are three entities - we care about. The host (browser, your application etc), the engine (JINT in this case) and the script ("console.log(...)") in this case.
JavaScript defines a bunch of functions and object as part of the language, but console is not one of them. By convention, browsers define a console object that can be used in the manner you describe. However, since your app is not a browser (and JINT does not do this by itself), there's no console object defined in your namespace (globals).
What you need to do is add a console object that will be accessible in JINT. You can find how to do this in the docs, but here's a simple example of how to add a log function to the engine so it can be used from the JS code (example taken from github).
var engine = new Engine()
.SetValue("log", new Action<object>(Console.WriteLine))
;
engine.Execute(#"
function hello() {
log('Hello World');
};
hello();
");
Vmware's .net api reference is somewhat confusing and hard to follow. I have been able to connect to my vcenter host then get a list of esxi hosts. Then I have been able get all the running modules on the host using HostKernelModuleSystem, and probe the properties on the variable "mod"... but I am not able to figure out how to get license info, I tried creating an object lic below, trying all different kinds of "types" from vmware with the word license in the type. but, it never works it has a problem converting the line with LicenseManagerLicenseInfo lic = .... I always get the following:
"Cannot convert type 'Vmware.Vim.Viewbase' to
'Vmware.Vim.LicenseManagerLicenseInfo'"
but the declaration above it for "mod" works fine.
I have also tried:
HostLicenseConnectInfo
LicenseAssignmentManagerLicenseAssignment
LicenseManager
I am hoping someone who has worked with vmware .net api can shed some light on what i am doing wrong? I am new to C# about 1 year :) but these VMware APIs are somewhat confusing to me.
esxList = client.FindEntityViews(typeof(HostSystem), null, null, null);
foreach (HostSystem host in esxList)
{
HostKernelModuleSystem mod = (HostKernelModuleSystem)client.GetView(host.ConfigManager.KernelModuleSystem, null);
LicenseManagerLicenseInfo lic = (LicenseManagerLicenseInfo)client.GetView(host.ConfigManager.LicenseManager, null);
string name = lic.Name;
}
I'll have to go to work tomorrow to look at this ( don't have ESX and VMWare SDK for .NET at home ) but I've done a bit of this work.
I wrote a generics method that wraps FindEntityViews and takes a filter as an argument. That makes it easy to search for anything. Also I've noticed that searches come back as ManagedObjectReferences and can't be cast to the subclasses. You have to construct them passing the ManagedObjectReference as an argument.
Also I find searching for PowerCLI examples and watching the classes in the immeadiate window very help in navigating this API. It's a fairly decent SDK but they put all of the classes in a single namespace and there's lots of little style inconsistencies ( Device instead of Devices and properties that take strings instead of enums when an enum exists ).
i figured out how to do it :) , by using http://vcenter_hostname/mob I was able to walk through api better. here is what I did, plus instead of of using "host" which was type HostSystem I jused my instance of my vCenter host "client"
VMware.Vim.LicenseManager lic_manager = (VMware.Vim.LicenseManager)client.GetView(client.ServiceContent.LicenseManager, null);
LicenseManagerLicenseInfo[] lic_found = lic_manager.Licenses;
foreach (LicenseManagerLicenseInfo lic in lic_found)
{
string test = lic.Name.ToString();
string test2 = lic.LicenseKey.ToString();
}
I'm trying to get a C++ service to load an XML document from a MSMQ message generated by C#. I can't really change the C++ side of things because I'm trying to inject test messages into the queue. The C++ service is using the following to load the XML.
CComPtr<IXMLDOMDocument2> spDOM;
CComPtr<IXMLDOMNode> spNode;
CComBSTR bstrVal;
if(_FAILED(hr = spDOM.CoCreateInstance(CLSID_DOMDocument30)))
{
g_infoLog->LogCOMError(hr, "CWorker::ProcessBody() Can't Create DOM");
pWork->m_nFailure = WORKFAIL_BADXML;
goto Exit;
}
hr = spDOM->loadXML(bstrBody, &vbResult);
The C# code to send the MSMQ message looks like this (just test code not pretty):
// open the queue
var mq = new MessageQueue(destinationQueue)
{
// store message on disk at all intermediaries
DefaultPropertiesToSend = { Recoverable = true },
// set the formatter to Binary, default is XML
Formatter = new BinaryMessageFormatter()
};
// send message
mq.Send(messageContent, "TestMessage");
mq.Close();
I tried to send the same message using BinaryMessageFormatter but it puts what I think are unicode characters at the top before the XML starts.
.....ÿÿÿ
ÿ.......
......À)
If I use the default XML formatter the message has the following top element. The C++ service doesn't seem to handle this.
<?xml version="1 .0"?>..<string>& lt;
Do you know of a way I could easily clean up the unicode characters when using the binary formatter? If so I think it might work.
Have you tried the ActiveXMessageFormatter? It might not compile with it as the formatter, i have no way to test here, but it might.
EDIT: just tried and it compiles ok, whether the result is any better i still couldn't say for sure.