I have never used ASP.NET before and I don't quite understand how the MVC system works, but my application is much more simple than the tutorials provided.
I have a webpage in HTML, and I currently have a C# program that gets key presses from my keyboard (Making a webpage that displays key presses). Both of these work, and the C# program prints to the terminal.
I can't however, seem to connect the two, by making a web page that has data bindings so that whenever a C# class updates, it changes the HTML content without page refresh.
This would probably require learning a lot, but I'm hoping to make it with a few files (maybe a controller isn't needed since the page has no interaction?). I'm not sure how to even make a DOTNET project, as the sample one has many built-in pages and routes that I don't understand.
So basically, this is my C# program (with DLL in the same dir)
using System;
using WootingAnalogSDKNET;
// We'll also include this for the Thread.Sleep call we'll have later on
using System.Threading;
using System;
using System.IO;
using System.Net;
using System.Threading;
Console.WriteLine("Hello Analog SDK!");
// Initialise the SDK
var (noDevices, error) = WootingAnalogSDK.Initialise();
// If the number of devices is at least 0 it indicates the initialisation was successful
if (noDevices >= 0) {
Console.WriteLine($"Analog SDK Successfully initialised with {noDevices} devices!");
}
else {
Console.WriteLine($"Analog SDK failed to initialise: {error}");
System.Environment.Exit(1);
}
while (true) {
var (keys, readErr) = WootingAnalogSDK.ReadFullBuffer(20);
if (readErr == WootingAnalogResult.Ok)
{
// Go through all the keys that were read and output them
foreach (var analog in keys)
{
Console.Write($"({analog.Item1},{analog.Item2})");
}
// We want to put on the new line character only if keys have been read and output to the console
if (keys.Count > 0)
Console.WriteLine();
}
else
{
Console.WriteLine($"Read failed with {readErr}");
// We want to put more of a delay in when we get an error as we don't want to spam the log with the errors
Thread.Sleep(1000);
}
// We want to have a bit of a delay so we don't spam the console with new values
Thread.Sleep(100);
}
Thank you in advance for you help!
Related
I am setting up LaunchDarkly to control my first feature flag and its working fine from server & client side.
Now I am trying LaunchDarkly Bootstrap approach (From the below given Link) and tried like below my code, but it's not accepting the double braces and I do not know How to get flag value by using the bootstrap approach, so where I did go wrong in my code?. Could anyone please help me with an example?
Link,
https://docs.launchdarkly.com/docs/js-sdk-reference#section-bootstrapping
Initialized client with Bootstrap option as below,
client = LDClient.initialize(sdkKey, userContext.user, options = {
bootstrap: {
{{ ldclient.all_flags(userContext.user) }}
}
});
And my function to get the flag value,
isFeatureEnabled: function (featureFlag, properties) {
console.log("Before Variation");
//we shall update the custom properties into user context.
if (properties) {
for (var k in properties) {
userContext.user.custom[k] = properties[k];
}
}
//later make the identity call to update the user details.
client.identify(userContext.user, null, function () { /*rules updated*/
console.log("New user's flags available");
//validate the feature flag
var showFeature = client.variation(featureFlag);
if (!showFeature) {
window.in8.platform.showUnauthorized('');
}
console.log("after Variation");
});
}
Full disclosure, My name is John, and I am part of the support team here at LaunchDarkly. I'll be happy to help you out with this problem
Firstly, it appears you are using an older version of the bootstrapping example. The new example has a typo fix, and uses the new all_flags_state method.
I see two major issues here. There is the primary issue of how to bootstrap flag variations from the back-end to the front-end, and how to appropriately utilize LaunchDarkly when using bootstrapping. I will tackle the issue of how to bootstrap flag variations from the back-end first.
The example in LaunchDarkly's documentation utilizes templating to include the bootstrapped values to the front end. Templating is a strategy for including programmatically generated content in your static source or text files. Templating is commonly used when compiling or deploying code, or at runtime when serving content to clients. This is done to render information only available at that time in the final version.
Different templating languages behave in different ways, but generally speaking you include tokens in your source or text files which direct the template renderer to replace that token with data you supply it.
In the documentation it mentions that this example is for templating using Ruby, but the example is using Mustache rendering, and Mustache is available in many different languages. Templating is a strategy for including programmatically generated content in your static source or text files. This is commonly used when compiling or deploying code, or at runtime when serving content to clients. This is done to render information only available at that time in the final version.
The example may not work depending on which back-end language and framework you are using. According to the tags associated with your question, I feel safe to assume that you are using .NET to power your back-end, which doesn't have a prescribed templating language. There are many open source solutions out there, though.
In the following example I'm going to use https://github.com/rexm/Handlebars.Net to render the a users bootstrapped flag values into the result variable. I am going to borrow code available from the example in the handle bars repo, and from LaunchDarkly's hello-bootstrap and hello-dotnet repos, which are available here: https://github.com/launchdarkly/hello-bootstrap & https://github.com/launchdarkly/hello-dotnet
string source =
#"
<html>
<head>
<script src=""https://app.launchdarkly.com/snippet/ldclient.min.js""></script>
<script>
window.ldBootstrap={{ldBootstrap}};
window.ldClientsideId=""{{ldClientsideId}}"";
window.ldUser={{ldUser}};
</script>
</head>
<body>
<h1>LaunchDarkly server-side bootstrap example</h1>
<ul>
<li><code>normal client</code>: <span class=""normal"">initializing…</span></li>
<li><code>bootstrapped client</code>: <span class=""bootstrap"">initializing…</span></li>
</ul>
<script>
var user = window.ldUser;
console.log(`Clients initialized`);
var client = LDClient.initialize(window.ldClientsideId, user);
var bootstrapClient = LDClient.initialize(window.ldClientsideId, user, {
bootstrap: window.ldBootstrap
});
client.on('ready', handleUpdateNormalClient);
client.on('change', handleUpdateNormalClient);
bootstrapClient.on('ready', handleUpdateBootstrapClient);
bootstrapClient.on('change', handleUpdateBootstrapClient);
function handleUpdateNormalClient(){
console.log(`Normal SDK updated`);
render('.normal', client);
}
function handleUpdateBootstrapClient(){
console.log(`Bootstrapped SDK updated`);
render('.bootstrap', bootstrapClient);
}
function render(selector, targetClient) {
document.querySelector(selector).innerHTML = JSON.stringify(targetClient.allFlags(user), null, 2);
}
</script>
</body>
</html>";
var template = Handlebars.Compile(source);
Configuration ldConfig = LaunchDarkly.Client.Configuration.Default("YOUR_SDK_KEY");
LdClient client = new LdClient(ldConfig);
User user = User.WithKey("bob#example.com")
.AndFirstName("Bob")
.AndLastName("Loblaw")
.AndCustomAttribute("groups", "beta_testers");
var data = new {
ldBootstrap: JsonConvert.SerializeObject(client.AllFlagsState(user)),
ldUser = JsonConvert.SerializeObject(user),
ldClientsideId = "YOUR_CLIENT_SIDE_ID"
};
var result = template(data);
You could take this example and adapt it to render your static source code when serving the page to your users.
The second issue is how you are utilizing the SDK. I see that you are calling identify before evaluating your user every time. Each time you call identify the SDK needs to reinitialize. This means that even after bootstrapping your initial variations you will force the SDK to reinitialize by calling identify, removing all benefits of bootstrapping. As a solution, detect if your user object has changed. if it has, then call identify. Otherwise, do not call identify so that the SDK uses the cached user attributes.
If you want to dive deeper into this and provide us with some more of the source for your wrapper you can reach out to us at support#launchdarkly.com
I am getting this error
System.IO.FileNotFoundException: 'Could not load file or assembly 'CefSharp.Core, Version=63.0.3.0, Culture=neutral, PublicKeyToken=40c4b6fc221f4138'. The system cannot find the file specified.'
I am trying to run the cefsharp.minimalexample.offscreen program in .net core 2.0. in visual studio 2017
what I have done so far
1 . Created .net core console application
2 . Installed NuGet packages Cefsharp.Offscreen (which installs the dependencies cefsharp.common and redist)
3 . Installed Microsoft.windows.compatibility nuget package to get the system.drawing in .net core (It was not working with System.Drawing.Common as the Cefsharp ScreenshotAsync function using system.drawing)
These steps will clear all the errors and the project will build successfully.
I am getting the above mentioned error.
I have checked all the required files mentioned in the Cefsharp documentation in the current running folder (debug). All files are available ,Still error is not going away.
It works fine in old Dot net versions 4.6.
I could not find any helping documents for implementing cefsharp.offscreen with .net core any where.
This is the code from the example provided in the Cefsharp.offscreen.
Please let me know if you can shed some light on this issue. Thanks in advance.
public class Program
{
private static ChromiumWebBrowser browser;
public static void Main(string[] args)
{
const string testUrl = "https://www.google.com/";
Console.WriteLine("This example application will load {0}, take a screenshot, and save it to your desktop.", testUrl);
Console.WriteLine("You may see Chromium debugging output, please wait...");
Console.WriteLine();
var settings = new CefSettings()
{
//By default CefSharp will use an in-memory cache, you need to specify a Cache Folder to persist data
CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache")
};
//Perform dependency check to make sure all relevant resources are in our output directory.
Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);
// Create the offscreen Chromium browser.
browser = new ChromiumWebBrowser(testUrl);
// An event that is fired when the first page is finished loading.
// This returns to us from another thread.
browser.LoadingStateChanged += BrowserLoadingStateChanged;
// We have to wait for something, otherwise the process will exit too soon.
Console.ReadKey();
// Clean up Chromium objects. You need to call this in your application otherwise
// you will get a crash when closing.
Cef.Shutdown();
}
private static void BrowserLoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
// Check to see if loading is complete - this event is called twice, one when loading starts
// second time when it's finished
// (rather than an iframe within the main frame).
if (!e.IsLoading)
{
// Remove the load event handler, because we only want one snapshot of the initial page.
browser.LoadingStateChanged -= BrowserLoadingStateChanged;
var scriptTask = browser.EvaluateScriptAsync("document.getElementById('lst-ib').value = 'CefSharp Was Here!'");
scriptTask.ContinueWith(t =>
{
//Give the browser a little time to render
Thread.Sleep(500);
// Wait for the screenshot to be taken.
var task = browser.ScreenshotAsync();
task.ContinueWith(x =>
{
// Make a file to save it to (e.g. C:\Users\jan\Desktop\CefSharp screenshot.png)
var screenshotPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "CefSharp screenshot.png");
Console.WriteLine();
Console.WriteLine("Screenshot ready. Saving to {0}", screenshotPath);
// Save the Bitmap to the path.
// The image type is auto-detected via the ".png" extension.
task.Result.Save(screenshotPath);
// We no longer need the Bitmap.
// Dispose it to avoid keeping the memory alive. Especially important in 32-bit applications.
task.Result.Dispose();
Console.WriteLine("Screenshot saved. Launching your default image viewer...");
// Tell Windows to launch the saved image.
Process.Start(screenshotPath);
Console.WriteLine("Image viewer launched. Press any key to exit.");
}, TaskScheduler.Default);
});
}
}
}
I've an Android Activity and I've got a Button that button need to access some Javascript function. Simply my app get the user info(ID,pass) then go to web page(this operation doing backgrun with asynctask class) write these two info as ID and pass then user click the Log In button in my app button has to use some js function
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
this is the func. i need to use
My post and get request for connection the site are
POST//
URL url = new URL(params[0]); //http://login.cu.edu.tr/Login.aspx? site=https://derskayit.cu.edu.tr&ReturnUrl=%2f
connection=(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(data);
writer.flush();
these codes for the put the ID and pass
GET //
reader= new BufferedReader((new InputStreamReader(connection.getInputStream())));
StringBuilder builder = new StringBuilder();
String line;
while((line= reader.readLine())!=null){
builder.append(line + "\n");
}
text=builder.toString();
there is any help or suggestion for me i am very confused about that situation and i feel really bad myself thanks for helps anyway. Have a nice day
For using Javascript without a webView to make requests!
The question has already an answer here in this question
The javax.script package is not part of the Android SDK. You can execute JavaScript in a WebView, as described here. You perhaps can use Rhino, as described here. You might also take a look at the Scripting Layer for Android project.
Also a similar question was asked here
You can execute JavaScript without a WebView. You can use AndroidJSCore. Here is a quick example how you might do it:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://your_website_here/file.js");
HttpResponse response = client.execute(request);
String js = EntityUtils.toString(response.getEntity());
JSContext context = new JSContext();
context.evaluateScript(js);
context.evaluateScript("question.vote(0);");
However, this most likely won't work outside of a WebView, because I presume you are not only relying on JavaScript, but AJAX, which is not part of pure JavaScript. It requires a browser implementation.
Is there a reason you don't use a hidden WebView and simply inject your code?
// Create a WebView and load a page that includes your JS file
webView.evaluateJavascript("question.vote(0);", null);
Otherwise:
Yes you can make HTTP POST and HTTP GET requests without using WebView. But if you want to use a webView remember Javascript in a webview is disabled by default (for security purposes). So before calling any javascript functions make sure you enable javascript in your webview like this
webView.getSettings().setJavaScriptEnabled( true );
And after that javascript will be enabled in your webView.
But in case you do not want to use a webview and javascript to make http requests. There is a lot of alternative methods you can define a Button in your activity's layout in xml. And respond with a http request on button Clicked listener!
Also remember making http Request using Android/Java default classes is a huge task and error prone and requires you to care about using async tasks to avoid blocking the UI thread.
Alternatively
In android we use ready-made library to make http requests. Google has a good library called Volley. it is easy to customize,respond to errors and it automatically making request out of the main thread.See more explanation here!. If there is still some problems comment below!
I'm writing a simple Automator script in Javascript.
I want to send a key-code(or key-storke) to an OS X application that is not in front.
Basically, I want to run this code and do my things while the script opens a certain application, write text, and hit enter - all of this without bothering my other work.
I want something like this:
Application("System Events").processes['someApp'].windows[0].textFields[0].keyCode(76);
In Script Dictionary, there is keyCode method under Processes Suite.
The above code, however, throws an error that follows:
execution error: Error on line 16: Error: Named parameters must be passed as an object. (-2700)
I understand that the following code works fine, but it require the application to be running in front:
// KeyCode 76 => "Enter"
Application("System Events").keyCode(76);
UPDATE: I'm trying to search something on iTunes(Apple Music). Is this possible without bringing iTunes app upfront?
It's possible to write text in application that is not in front with the help of the GUI Scripting (accessibility), but :
You need to know what UI elements are in the window of your specific
application, and to know the attributes and properties of the
specific element.
You need to add your script in the System Preferences --> Security
& Privacy --> Accessibility.
Here's a sample script (tested on macOS Sierra) to write some text at the position of the cursor in the front document of the "TextEdit" application.
Application("System Events").processes['TextEdit'].windows[0].scrollAreas[0].textAreas[0].attributes["AXSelectedText"].value = "some text" + "\r" // r is the return KEY
Update
To send some key code to a background application, you can use the CGEventPostToPid() method of the Carbon framework.
Here's the script to search some text in iTunes (Works on my computer, macOS Sierra and iTunes Version 10.6.2).
ObjC.import('Carbon')
iPid = Application("System Events").processes['iTunes'].unixId()
searchField = Application("System Events").processes['iTunes'].windows[0].textFields[0]
searchField.buttons[0].actions['AXPress'].perform()
delay(0.1) // increase it, if no search
searchField.focused = true
delay(0.3) // increase it, if no search
searchField.value = "world" // the searching text
searchField.actions["AXConfirm"].perform()
delay(0.1) // increase it, if no search
// ** carbon methods to send the enter key to a background application ***
enterDown = $.CGEventCreateKeyboardEvent($(), 76, true);
enterUp = $.CGEventCreateKeyboardEvent($(), 76, false);
$.CGEventPostToPid(iPid, enterDown);
delay(0.1)
$.CGEventPostToPid(iPid, enterUp);
I need to call a javascript function inside a chrome-window from a windows service written in c#.
The browser is entirely at my disposal so I can configuration is no problem.
For example, the windows service is a file checker, when a certain file is changed there has to popup a js alert.
-EDIT-
The following works fine for client to client communication (server-side code).
So when a specific event happens on the server I can display this on the client (I hoped commented would do that)
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Client;
using SignalR.Hosting.Self;
using SignalR.Hubs;
namespace Net.SignalR.SelfHost
{
class Program
{
static void Main(string[] args)
{
string url = "http://localhost:8081/";
var server = new Server(url);
server.MapHubs();
server.Start();
Console.WriteLine("SignalR server started at " + url);
Console.ReadLine();
// Clients[collection].flush("bericht: " + message + collection);
}
//public void PushMessage(string bericht)
//{
// var hubConnection = new HubConnection("http://localhost:8081/");
// var serverHub = hubConnection.CreateProxy("CollectionHub");
// serverHub.On("flush", message => System.Console.WriteLine(message));
// hubConnection.Start().Wait();
// serverHub.Invoke("Subscribe", "Product");
// string line = null;
// while ((line = bericht) != null)
// {
// serverHub.Invoke("Publish", line, "Product").Wait();
// }
// System.Console.Read();
//}
public class CollectionHub : Hub
{
public void Subscribe(string collectionName)
{
Groups.Add(Context.ConnectionId, collectionName);
Console.WriteLine("Subscribed to: " + collectionName);
//serverHub.Invoke("Publish", "dit is een eerste test", "Product").Wait();
}
public Task Unsubscribe(string collectionName)
{
return Clients[collectionName].leave(Context.ConnectionId);
}
public void Publish(string message, string collection)
{
Clients[collection].flush("bericht: " + message + collection);
}
}
}
}
Sounds like you are describing SignalR.
What is ASP.NET SignalR?
ASP.NET SignalR is a new library for ASP.NET
developers that makes it incredibly simple to add real-time web
functionality to your applications. What is "real-time web"
functionality? It's the ability to have your server-side code push
content to the connected clients as it happens, in real-time.
You may have heard of WebSockets, a new HTML5 API that enables
bi-directional communication between the browser and server. SignalR
will use WebSockets under the covers when it's available, and
gracefully fallback to other techniques and technologies when it
isn't, while your application code stays the same.
SignalR also provides a very simple, high-level API for doing server
to client RPC (call JavaScript functions in your clients' browsers
from server-side .NET code) in your ASP.NET application, as well as
adding useful hooks for connection management, e.g. connect/disconnect
events, grouping connections, authorization.
What can you do with ASP.NET SignalR?
SignalR can be used to add any
sort of "real-time" web functionality to your ASP.NET application.
While chat is often used as an example, you can do a whole lot more.
Any time a user refreshes a web page to see new data, or the page
implements Ajax long polling to retrieve new data, is candidate for
using SignalR.
What it basicly does, is giving you access to the client AND server side functions in both directions, a simple example of it's usage can be found on the asp.net website which will give you a good idea on how to use it and what it's capable of doing.
You want to be using something like signal IR to do that, its what its designed for, essentially you are describing real time functionality;
Signal IR can be found here and has a great section on javascript in its wiki
In particular you probably want to take a look at Hubs