How to assign a calendar event with C # in Hotmail/Outlook? - javascript

And I wish the following objective:
assign an event to the hotmail calendar
I have the following code:
using Microsoft.Live;
private void editEvent()
{
try
{
var authClient = new LiveAuthClient();
LiveLoginResult result = await authClient.LoginAsync(new string[] { "wl.signin", "wl.calendars", "wl.calendars_update" });
if (result.Status == LiveConnectSessionStatus.Connected)
{
var eventToPost = new Dictionary<string, object>();
eventToPost.Add("name", "program my c# - 2nd trial");
eventToPost.Add("calendar_id", "calendar.136c10ca65544801.99c35f9a9fb341a3af35daa82f4569f8");
eventToPost.Add("description", "this should be 2nd calendar");
eventToPost.Add("start_time", "2019-09-10T01:30:00-08:00");
eventToPost.Add("end_time", "2019-09-12T03:00:00-08:00");
eventToPost.Add("location", "business placeeeeeee");
eventToPost.Add("is_all_day_event", false);
eventToPost.Add("availability", "busy");
eventToPost.Add("visibility", "public");
this.session = result.Session;
connected = true;
this.connectClient = new LiveConnectClient(result.Session);
var meResult = await connectClient.PutAsync("event.136c10ca6a355671.5f21a7994c7e40fd800bc48dcc07300b.991d1912ec6b4523a0f08839992aa2bb", eventToPost);
meData = meResult.Result;
}
}
catch (LiveAuthException ex)
{
// Display an error message.
}
catch (LiveConnectException ex)
{
// Display an error message.
infoTextBlock.Text += ex.Data + " ..." + ex.Message;
}
}
In which I try to test it to see how it works and if it fulfills the desired objective.
But I do not know which library works LiveAuthClient and LiveConnectSessionStatus
Download the nuget package live sdk package, but it still shows error in LiveAuthClient and LiveConnectSessionStatus
I would like to know which library should download to test its operation, since I want to add an event to the Hotmail calendar with C # or Javascript. If anyone knows, or if you have an example, I would greatly appreciate it.

Related

When making a list by query request in GMail via C#, what's the "source"?

Context: C#, JavaScript, ClearScript
I've written a plugin for my ClearScript-enabled JavaScript that connects to GMail. Everything's fine regarding OAuth2 etc. What's not working is a query against the inbox. If I request the inbox without a query, that gives me data, but I don't want millions of records.
attach(".\\Plugin_GMail.dll")
var tuple = Plugin_GMail.GoogleMail.Mail.Mail_Authenticate(REDACTED)
var service = Plugin_GMail.GoogleMail.Mail.Mail_CreateService(tuple.Item1, "mail")
var request = service.Users.Labels.List("me");
var labels = request.Execute().Labels;
var before = new Date(2022,11,31).valueOf();
var after = new Date(2022,0,1).valueOf();
var res = Plugin_GMail.GoogleMail.Mail.Messages_ListByQuery(service, "me", "before:$b after:$a".replace("$b",before).replace("$a",after),true)
The code for Messages_ListByQuery is
public static string Messages_ListByQuery(GmailService service, string userId, string query, bool debug = false)
{
if (debug) Debugger.Launch();
var msgList = new List<Message>();
var result = new JSONResponse();
var request = service.Users.Messages.List(userId);
request.MaxResults = 500;
request.Q = query;
request.LabelIds = "INBOX";
while (true)
{
try
{
var msgs = request.Execute().Messages;
if (msgs.Count() == 0)
{
break;
}
msgList.AddRange(msgs);
}
catch (Exception e)
{
result.Error = e.Message;
break;
}
}
result.Cargo = msgList;
return JsonConvert.SerializeObject(result);
}
So the response after executing the query-based List is
{"Error":"Value cannot be null.\r\nParameter name: source","Cargo":[],"Crew":null}
I have been through the documentation and can't find anything about "source". And there's nothing in the Playground about "source" either. Where next?
Your code is telling it to just loop forever, getting the same page of results.
while (true) // loop forever
{
try
{
var msgs = request.Execute().Messages; // get first page of results
if (msgs.Count() == 0)
{
break; // will never hit unless user has no messages. in their inbox at all.
}
msgList.AddRange(msgs); // keeps adding first page of messages over and over.
}
catch (Exception e)
{
result.Error = e.Message;
break;
}
}
The line
var msgs = request.Execute().Messages;
Is just going to say run the request and get me messages. Which will always return messages as your running the same request over and over.
The following line is just going to add the messages to your list.
msgList.AddRange(msgs);
So with the while true you are telling your app to just request the same 500 rows again and again forever.
You should instead look at using the next page token and getting the next page of results instead of the same results over and over.

Using JavaScript with WkWebView - error on UserMessageHandler

When sending a message through Javascript to iOS, I encountered this error message that I can't find any information online: "Can only call UserMessageHandler.postMessage on instances of UserMessageHandler".
I am using a webview to render a webpage on iOS.
I tried adding the same script from native code and I was able to receive the message. However, the same script shows the above error if I deploy it on the web site.
let scriptSource = "window.webkit.messageHandlers.jsHandler.postMessage({command: 'command goes here'});"
let userScript = WKUserScript(source: scriptSource, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
userContentController.addUserScript(userScript)
on the web end, I used the following code
key: "onExit",
value: function() {
var t = function() {
try {
return window.webkit.messageHandlers.jsHandler.postMessage || null
} catch (t) {
return null
}
}();
if (t)
try {
t({
command: "command goes here"
}), console.log("window.webkit.messageHandlers.jsHandler.postMessage called successfully")
} catch (t) {
console.log("error thrown when calling window.webkit.messageHandlers.jsHandler.postMessage - " + (t || {}).message)
}
else
console.log("window.webkit.messageHandlers.jsHandler.postMessage not found!")
}
Explicit bind this will resolve the error:
window.webkit.messageHandlers.jsHandler.postMessage.bind(window.webkit.messageHandlers.jsHandler)

Can't run javascript alerts in universal app's webview at payment gateway

I am integrating payment gateway in my universal windows app where I open the URL in a webview. However, webview can't seem to display javascript alert messages or popups. I read online that I need to add url's of website in package manifest to enable Scriptnotify event to run but given it's a payment gateway, it's not feasible to add url's for all bank websites. Is there a way to handle this ?
Also I am handling the ScriptNotify event as this, but this seems to be partially correct.
private async void MyWebView_ScriptNotify(object sender, NotifyEventArgs e)
{
Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog(e.Value);
await dialog.ShowAsync();
}
private async void MyWebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
string result = await this.MyWebView.InvokeScriptAsync("eval", new string[] { "window.alert = function (AlertMessage) {window.external.notify(AlertMessage)}" });
}
After banging my head for a week or two, finally found the solution, following are the necessary event handlers :
private async void MyWebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
string result = await this.MyWebView.InvokeScriptAsync("eval", new string[] { "window.confirm = function (ConfirmMessage) {window.external.notify(ConfirmMessage)}" });
}
private async void MyWebView_ScriptNotify(object sender, NotifyEventArgs e)
{
Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog(e.Value);
dialog.Commands.Add(new UICommand("Yes"));
dialog.Commands.Add(new UICommand("No"));
// Set the command that will be invoked by default
dialog.DefaultCommandIndex = 0;
// Set the command to be invoked when escape is pressed
dialog.CancelCommandIndex = 1;
var result = await dialog.ShowAsync();
if (result.Label.Equals("Yes"))
{
string res = await MyWebView.InvokeScriptAsync("eval", new string[] { "window.confirm = function (ConfirmMessage) {return true}" });
}
else
{
string res = await MyWebView.InvokeScriptAsync("eval", new string[] { "window.confirm = function (ConfirmMessage) {return false}" });
}
}

Catch all JavaScript client-side errors on the server-side

How can I catch any exception that occurs in the client side code like "Pause On Caught Exceptions" on chrome developer tools?
I found the solution!
I have used the C# and MVC.
Add a new class to customize your js files bundle like this:
public class CustomScriptBundle : ScriptBundle
{
public CustomScriptBundle(string virtualPath) : base(virtualPath)
{
Builder = new CustomScriptBundleBuilder();
}
public CustomScriptBundle(string virtualPath, string cdnPath)
: base(virtualPath, cdnPath)
{
Builder = new CustomScriptBundleBuilder();
}
}
And, create another class to change the content of the js files as follows::
class CustomScriptBundleBuilder : IBundleBuilder
{
private string Read(BundleFile file)
{
//read file
FileInfo fileInfo = new FileInfo(HttpContext.Current.Server.MapPath(#file.IncludedVirtualPath));
using (var reader = fileInfo.OpenText())
{
return reader.ReadToEnd();
}
}
public string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<BundleFile> files)
{
var content = new StringBuilder();
foreach (var fileInfo in files)
{
var contents = new StringBuilder(Read(fileInfo));
//a regular expersion to get catch blocks
const string pattern = #"\bcatch\b(\s*)*\((?<errVariable>([^)])*)\)(\s*)*\{(?<blockContent>([^{}])*(\{([^}])*\})*([^}])*)\}";
var regex = new Regex(pattern);
var matches = regex.Matches(contents.ToString());
for (var i = matches.Count - 1; i >= 0; i--) //from end to start! (to avoid loss index)
{
var match = matches[i];
//catch( errVariable )
var errVariable = match.Groups["errVariable"].ToString();
//start index of catch block
var blockContentIndex = match.Groups["blockContent"].Index;
var hasContent = match.Groups["blockContent"].Length > 2;
contents.Insert(blockContentIndex,
string.Format("if(customErrorLogging)customErrorLogging({0}){1}", errVariable, hasContent ? ";" : ""));
}
var parser = new JSParser(contents.ToString());
var bundleValue = parser.Parse(parser.Settings).ToCode();
content.Append(bundleValue);
content.AppendLine(";");
}
return content.ToString();
}
}
Now, include your js files in application Bundles with your class:
BundleTable.Bundles.Add(new CustomScriptBundle("~/scripts/vendor").Include("~/scripts/any.js"));
Finally, in a new js file write customErrorLogging function as described below, and add it to your project's main html form:
"use strict";
var customErrorLogging = function (ex) {
//do something
};
window.onerror = function (message, file, line, col, error) {
customErrorLogging({
message: message,
file: file,
line: line,
col: col,
error: error
}, this);
return true;
};
Now, you can catch all exceptions in your application and manage them :)
You can use try/catch blocks:
try {
myUnsafeFunction(); // this may cause an error which we want to handle
}
catch (e) {
logMyErrors(e); // here the variable e holds information about the error; do any post-processing you wish with it
}
As the name indicates, you try to execute some code in the "try" block. If an error is thrown, you can perform specific tasks (such as, say, logging the error in a specific way) in the "catch" block.
Many more options are available: you can have multiple "catch" blocks depending on the type of error that was thrown, etc.
More information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
see a small example how you can catch an Exception:
try {
alert("proper alert!");
aert("error this is not a function!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
<body>
<p id="demo"></p>
</body>
put you code in try Block and try to catch error in catch Block.

MSScriptControl Issue on Windows Server 2008

So I'm using the MSScriptControl to run some javascript in my app and I want to be able to get some information about any errors the script may cause.
MSScriptControl.ScriptControlClass script = new MSScriptControl.ScriptControlClass();
try
{
script.Language = "JScript";
script.Timeout = 15000;
script.Eval(Code);
}
catch (Exception ex)
{
MSScriptControl.Error err = script.Error;
ret = new Exception("Error on line: " + err.Line + ", Description: " + err.Description);
}
The code works fine on my development machine, a Windows 7 box, and gives me a line number with an error. So I happily publish and push it to the production machine which always tells me the error occurred at line 0 and no description is provided.
I tried going to http://www.microsoft.com/download/en/details.aspx?id=1949 to download the latest version but installing it had no effect. I also set the property Embed Interop Types to false as well as copying my own msscript.ocx file into the Windows 2008 server's system32 directory but neither of these attempts resolved anything.
Anyone have any recommendations?
If you want to do it in all native c# without any 3rd party or "component" external dependencies use a CodeDomProvider with a tiny JScript bootstrap, like this:
private static readonly MethodInfo eval = CodeDomProvider
.CreateProvider("JScript")
.CompileAssemblyFromSource(new CompilerParameters(), "package e{class v{public static function e(e:String):Object{return eval(e);}}}")
.CompiledAssembly
.GetType("e.v")
.GetMethod("e");
private static object JsEval(string jscript)
{
try
{
return eval.Invoke(null, new[] { jscript });
}
catch (Exception ex)
{
return ex;
}
}
that creates a JsEval(string) method that you can use anywhere in your code to "eval" a string as JavaScript (well JScript)... So calling:
MessageBox.Show("" + JsEval("2 + 2")); // 4
MessageBox.Show("" + JsEval("(function(){ return 3+7; })();")); // 10
MessageBox.Show("" + JsEval("function yay(a) { return a + 1; } yay(2);")); // 3
depending on your use you may not want to instantiate these members statically. if you want to manipulate complex objects you will need create a wrapper to reflectively extract data (or you could cast as the appropriate JScript counterpart, but I've never tried this as you'd have to include the JScript assemblies).
here is an example of a wrapper class that does everything JavaScript will let you do natively, adding anymore high level functionality would probably be cumbersome enough so that you'd be better off either extracting the members into a dictionary / hash table OR alternatively serializing and deserializing on the other end
private class JsObjectWrapper : IEnumerable
{
public readonly object jsObject;
private static PropertyInfo itemAccessor = null;
private static MethodInfo getEnumerator = null;
public JsObjectWrapper(object jsObject)
{
this.jsObject = jsObject;
if (itemAccessor == null)
{
itemAccessor = jsObject.GetType().GetProperty("Item", new Type[] { typeof(string) });
}
if (getEnumerator == null)
{
getEnumerator = jsObject.GetType().GetInterface("IEnumerable").GetMethod("GetEnumerator");
}
}
public object this[string key]
{
get { return itemAccessor.GetValue(jsObject, new object[] { key }); }
set { itemAccessor.SetValue(jsObject, value, new object[] { key }); }
}
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)getEnumerator.Invoke(jsObject, null);
}
}
you can see this in action by doing this:
var jsObj = JsEval("var x = { a:7, b:9 };");
var csObj = new JsObjectWrapper(jsObj);
MessageBox.Show("a: " + csObj["a"]); // a: 7
MessageBox.Show("b: " + csObj["b"]); // b: 9
csObj["yay!"] = 69;
foreach (string key in csObj)
{
MessageBox.Show("" + key + ": " + csObj[key]); // "key": "value"
}
i personally have used code similar to this to great effect at one point or another and can vouch for it's availability and runnability inside a server environment.. I hope this helps -ck
Regarding the problem you face just some thoughts:
according to the link you provided this control neither supports Windows 7 nor Windows 2008
it might be a security issue with regards to COM/UAC etc.
it might be a problem because of bitness if you compiled for AnyCPU, try using x86
Regarding possible alternatives:
Using JScript you can build an evaluator rather easily which is supported anywhere .NET 4 runs (including Windows Server 2008).
Using JInt as a JavaScript interpreter

Categories

Resources