I have a program running through unity3d webGL, it works pretty well but I found getting feedback from people within the program is becoming a problem.
So I created a very basic form that the user can fill out in the program, press send and it will send to me.
My problem is that the information coming through is a sequence of numbers and not the messages.
Here is the various parts of the code if you spot something please let me know.
C# Unity3d form code
public void Send_help()
{
string the_date = DateTime.Now.ToString ("yyyy MMMMM dd");
string the_message = help_message.text;
string the_email = help_email.text;
Tcontroller.GetComponent<Trcontroller> ().Send_helpMessage (the_date,the_email,the_message);
Help_stuff.gameObject.SetActive (false);
audio.PlayOneShot (next);
}
The Send_helpMessage in the Tcontroller
private static extern void Message_help(string d, string e, string m);
[DllImport("__Internal")] //The imported function in my pluggin
public void Send_helpMessage(string date, string email, string message)
{
Message_help (date, email, message);
}
The pluggin code
var talk = {
Message_help: function(d,e,m)
{
Send_message_help(d,e,m);
}
};
mergeInto(LibraryManager.library, talk);
The website code
var this_date = '';
var this_email = '';
var this_message = '';
function Send_message_help(d,e,m)
{
this_date = d;
this_email = e;
this_message = m;
var Data = '&this_date='+this_date+'&this_email='+this_email+'&this_message='+this_message;
$.ajax({
url : "message.php",
type: "POST",
data : Data
});
};
Finally the pHp code
$MS = new mysqli ( $db_host, $db_username, $db_pass, $db_name );
$this_date = $_POST['this_date'];
$this_email = $_POST['this_email'];
$this_message = $_POST['this_message'];
$sqlupdate_user_message = "INSERT into contact(email, date, message) values('$this_email','$this_date','$this_message')";
mysqli_query ( $connMS, $sqlupdate_user_message );
mysqli_close($MS);
You can put any type of string value you want, the output to the database comes across as numbers
I know that WebGL is still new but it serves my purpose and everything else in terms of communication between webgl and the database has been fine with the exception of this form. Thanks for help in advance.
Please try this in plugin code(*.jslib):
var talk = {
Message_help: function(d,e,m)
{
var date = Pointer_stringify(d);
var email = Pointer_stringify(e);
var message = Pointer_stringify(m);
Send_message_help(date,email,message);
}
};
mergeInto(LibraryManager.library, talk);
When you send string from Unity WebGL to jslib, you need Pointer_stringify helper function to change it back to string. You can find more on this
link
Related
New Info:
I thought I would paste this in full as I can not seem to find any samples on the web of a c# solution for StarLink so hopefully anyone else looking for something may find this helpful and may contribute.
My New Proto File - (partial) - I took the advise of Yuri below. Thanks for the direction here. I was able to I have been using this tool and it has brought a lot of insight but I am still stuck on the c# side of the solution. I am an old VB.Net developer though I have done a bunch in c# I am by no means savvy in it and am probably missing something so simple. Again, any insight would be awesome. I can not post the full proto here as stack has char limit on posts. this is the first bit with messages etc. I can post more if it helps but trying to keep it to the important part.
syntax = "proto3";
option csharp_namespace = "SpaceX.API.Device";
package SpaceX.API.Device;
service Device {
//rpc Handle (.SpaceX.API.Device.Request) returns (.SpaceX.API.Device.Response) {}
//rpc Stream (stream .SpaceX.API.Device.ToDevice) returns (stream .SpaceX.API.Device.FromDevice) {}
rpc Handle (Request) returns (Response);
rpc Stream (Request) returns (Response);
}
message ToDevice {
string message = 1;
}
message Request {
uint64 id = 1;
string target_id = 13;
uint64 epoch_id = 14;
oneof request {
SignedData signed_request = 15;
RebootRequest reboot = 1001;
SpeedTestRequest speed_test = 1003;
GetStatusRequest get_status = 1004;
AuthenticateRequest authenticate = 1005;
GetNextIdRequest get_next_id = 1006;
GetHistoryRequest get_history = 1007;
GetDeviceInfoRequest get_device_info = 1008;
GetPingRequest get_ping = 1009;
SetTrustedKeysRequest set_trusted_keys = 1010;
FactoryResetRequest factory_reset = 1011;
GetLogRequest get_log = 1012;
SetSkuRequest set_sku = 1013;
UpdateRequest update = 1014;
GetNetworkInterfacesRequest get_network_interfaces = 1015;
PingHostRequest ping_host = 1016;
GetLocationRequest get_location = 1017;
EnableFlowRequest enable_flow = 1018;
GetHeapDumpRequest get_heap_dump = 1019;
RestartControlRequest restart_control = 1020;
FuseRequest fuse = 1021;
GetPersistentStatsRequest get_persistent_stats = 1022;
GetConnectionsRequest get_connections = 1023;
FlushTelemRequest flush_telem = 1026;
StartSpeedtestRequest start_speedtest = 1027;
GetSpeedtestStatusRequest get_speedtest_status = 1028;
ReportClientSpeedtestRequest report_client_speedtest = 1029;
InitiateRemoteSshRequest initiate_remote_ssh = 1030;
SelfTestRequest self_test = 1031;
SetTestModeRequest set_test_mode = 1032;
DishStowRequest dish_stow = 2002;
DishGetContextRequest dish_get_context = 2003;
DishSetEmcRequest dish_set_emc = 2007;
DishGetObstructionMapRequest dish_get_obstruction_map = 2008;
DishGetEmcRequest dish_get_emc = 2009;
DishSetConfigRequest dish_set_config = 2010;
DishGetConfigRequest dish_get_config = 2011;
StartDishSelfTestRequest start_dish_self_test = 2012;
WifiSetConfigRequest wifi_set_config = 3001;
WifiGetClientsRequest wifi_get_clients = 3002;
WifiSetupRequest wifi_setup = 3003;
WifiGetPingMetricsRequest wifi_get_ping_metrics = 3007;
WifiGetDiagnosticsRequest wifi_get_diagnostics = 3008;
WifiGetConfigRequest wifi_get_config = 3009;
WifiSetMeshDeviceTrustRequest wifi_set_mesh_device_trust = 3012;
WifiSetMeshConfigRequest wifi_set_mesh_config = 3013;
WifiGetClientHistoryRequest wifi_get_client_history = 3015;
TransceiverIFLoopbackTestRequest transceiver_if_loopback_test = 4001;
TransceiverGetStatusRequest transceiver_get_status = 4003;
TransceiverGetTelemetryRequest transceiver_get_telemetry = 4004;
}
reserved 1025, 3011, 3014;
}
message SignedData {
bytes data = 1;
bytes signature = 2;
}
My New .cs
I have tried many things from Microsoft's examples to thing I can gather from other samples. I simply can not get it to work and am lost. Again, any insight would be amazing and hopefully helpful to others looking for a solution in c#. You will see my commented code of this I have been playing with. Basically I am attempting to achieve three things and have made some movement in one of them.
Goals:
1 - Use Server Reflection to discover services.
I think I got this one resolved with dot-net grpc.
2 - Simply want to check available methods under a service and potentially either check or generate a new .proto file in case things change. StaLink does not publish its proto schema so I assume it could change anytime without warning.
3 - Just run any one of the available methods. I have tried the GetDeviceInfoRequest but can not seem to construct the request message properly. I have not been able to get this accomplishe in the gRPCurl tool either. I can do it on the basic service shown by Microsoft of course but these methods seem to be more complex and I simply get all kinds of errors.
Again, any insight or assistance would be amazing. Thanks to any and all in advance.
New .cs File
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Net.Client;
using Grpc.Reflection.V1Alpha;
using ServerReflectionClient = Grpc.Reflection.V1Alpha.ServerReflection.ServerReflectionClient;
using SpaceX.API.Device;
public class Program
{
static async Task Main(string[] args)
{
//SETUP CHANNEL AND CLIENT
using var channel = GrpcChannel.ForAddress("http://192.168.100.1:9200");
var client = new ServerReflectionClient(channel);
var StarLinkClient = new Device.DeviceClient(channel);
//using var call = StarLinkClient.StreamAsync(new ToDevice { Request = GetDeviceInfoRequest });
//await foreach (var response in call.ResponseStream.ReadAllAsync())
//var request = Device.GetDeviceInfoRequest;
//var reply = await StarLinkClient.HandleAsync(
// new Request {'"getDeviceInfo" : {} '});
//Console.WriteLine(reply.Message);
//=============================================SERVER REFLECTION=============================================================
Console.WriteLine("Calling reflection service:");
var response = await SingleRequestAsync(client, new ServerReflectionRequest
{
ListServices = "" // Get all services
});
Console.WriteLine("Services:");
foreach (var item in response.ListServicesResponse.Service)
{
Console.WriteLine("- " + item.Name);
Console.WriteLine();
var StarLink = item.Name;
//Console.WriteLine(StarLink.getStatus());
}
//=============================================SERVER REFLECTION=============================================================
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
void setupchannel()
{
}
private static Task SingleRequestAsync(ServerReflectionClient client, Metadata metadata)
{
throw new NotImplementedException();
}
private static async Task<ServerReflectionResponse> SingleRequestAsync(ServerReflectionClient client, ServerReflectionRequest request)
{
using var call = client.ServerReflectionInfo();
await call.RequestStream.WriteAsync(request);
Debug.Assert(await call.ResponseStream.MoveNext());
var response = call.ResponseStream.Current;
await call.RequestStream.CompleteAsync();
return response;
}
}
Again, thanks in advance to anyone willing to assist here. Hopefully this helps others as well.
I am trying to write a script that will open an issue typed in the console.
For some reason the issue variable comes back empty in the debugger.
class Program
{
public async static Task Main()
{
var client = new GitHubClient(new ProductHeaderValue("test-app"));
var user = await client.User.Get("medic17");
var tokenAuth = new Credentials(APIKeys.GithubPersinalAccessToken);
client.Credentials = tokenAuth;
var exampleIssue = new NewIssue("test body");
var issue = await client.Issue.Create("owner","name", exampleIssue);
}
}
APIKeys holds my token.
Thanks
I found a solution hope this helps someone else as well.
class Program
{
public async static Task Main()
{
// client initialization and authentication
var client = new GitHubClient(new ProductHeaderValue("<anything>"));
var user = await client.User.Get("<user>");
var tokenAuth = new Credentials(APIKeys.GithubPersinalAccessToken);
client.Credentials = tokenAuth;
// user input
Console.WriteLine("Give a title for your issue: ");
string userIssueTitle = Console.ReadLine().Trim();
Console.WriteLine("Describe your issue:", Environment.NewLine);
string userIssue = Console.ReadLine().Trim();
// input validation
while (string.IsNullOrEmpty(userIssue) || string.IsNullOrEmpty(userIssueTitle))
{
Console.WriteLine("ERROR: Both fields must contain text");
Console.ReadLine();
break;
}
var newIssue = new NewIssue(userIssueTitle) { Body = userIssue };
var issue = await client.Issue.Create(<owner>, <repo> newIssue);
var issueId = issue.Id;
Console.WriteLine($"SUCCESS: your issue id is {issueId} ");
Console.ReadLine();
}
}
Note
You need to store your keys in a separate file and write a class for it so your authentication flow might be different.
Note 2
You must replace all text with real values.
Still a little confused the app is OpenSource for transport since it deals with HIPPA data, users who want to use it need GitHub account if they want to do any error reporting. I assume I don’t share the authToken in the source of the project but the desktop Binary needs it plus the users GitHub login and password. Any pointers? I have tried just using username password that gets entered when creating issue but that fails with “not found”. It seems like any secret that gets deployed with binary app is potentially an issue.
I'm a noob when it comes to programming, but I would like to make a Language Request-Handler where I get an array (Syntax: say language text), split it up,set the device language on the language give to me and let the device speak the text given. I couldn't really find anything about setting a language on a device.
I'm doing an UWP-Project, so I can only use the Windows.Media.Speechsynthezier.
This is my (unfinished!) code at the moment:
//public class LanguageRequestHandler
string _request;
SpeechSynthesizer synth;
private SpeechSynthesizer _synth;
public LanguageRequestHandler( string request)
{
_request = request;
_synth = new SpeechSynthesizer();
var voice = SpeechSynthesizer.AllVoices.SingleOrDefault(i => i.Gender == VoiceGender.Female) ?? SpeechSynthesizer.DefaultVoice;
_synth.Voice = voice;
}
//That should be only a check if the command send to me has the right invocation
public string GetResponse()
{
string response = "invalid command";
string[] args = _request.Split(' ');
if (args[0] == "say")
{
response = CheckLanguage(args[1]);
}
return response;
}
//Here I want to check what language is requested and I actually wanted to set the langauge the device should speak (but as you know by it looks, it is unfinished)
public string CheckLanguage(string language)
{
string response = "No language selected";
string[] args = _request.Split(' ');
if (language == "spanish")
{
}
else if(language == "english")
{
}
else if (language == "german")
{
}
else if (language == "french")
{
}
return language;
}
//Here I'm splitting the Text give to me and putting it together to a sentence that should be later on translated
public string Text(string text)
{
string response = "No text given to translate";
string[] args = _request.Split(' ');
for (int i = 2; i < args.Length; i++)
{
response += args[i] + " ";
}
return text;
}
//Lastly I'm trying to set the volume of the device and synthesis from text to speech which should be streamed to the device and let it speak
public async void Talk(string message)
{
MediaPlayer mp = new MediaPlayer { Volume = 100 };
var stream = await _synth.SynthesizeTextToStreamAsync(message);
mp.Source = MediaSource.CreateFromStream(stream, stream.ContentType);
mp.Play();
}
You could open the 'Windows Settings -> Time& Language -> Language -> Add a language -> Select one language and click the Options button -> Click the Download button below the Speech'.
After that, go to the Speech on the left menus and set the speech language.
I found out that I need to add the Language.Contains()Function to set or change a language. It should be noted that you need to insert a BCP47 Code for the desired language (Example:
i.Language.Contains("fr-FR") for French)
"var voice = SpeechSynthesizer.AllVoices.SingleOrDefault(i => i.Gender == VoiceGender.Female && i.Language.Contains(_request)) ?? SpeechSynthesizer.DefaultVoice;"
Since I found a solution to this problem, I somehow need to split the _request given to me (since the syntax is "say ") and just give it the the BCP47 Code in it (thats why I made the method Checklanguage, it should take it out of the array and put the code in it)
On a project I am working on, I'm building a feature that lets users generate a report - in my case, it will go on an envelope - on-demand from information stored in our database. The problem I'm trying to solve, is that a blank PDF is being generated.
I've tried some sanity checks. First I set a breakpoint in Visual Studio and ensured that the models being passed to the report had fixed data; the reports were blank. Next, I tried including a static label that's not tied to any data, to determine if it's a report data-binding issue - the static label is not appearing in the generated report either.
More stymying, is that I've used similar code in the past without issue. I have no idea why a blank PDF file would be generated in this case.
I've read the 'Similar Questions' provided by StackOverflow, specifically this question from one year ago, but it had no answers, and thus nothing to learn from it. I've also tried the requisite Google searches, but found nothing relevant.
The only thing I cannot provide is the actual ActiveReport itself. I've checked this for Silly Programmer Errors™ like having everything hidden, or transparent labels, or similar silly things. Unfortunately, I've made no such errors.
Report Code:
public partial class EnvelopeReport : SectionReport
{
public EnvelopeReport()
{
InitializeComponent();
}
internal void RunReport(IEnumerable<PrintedAddress> model)
{
if (model != null)
{
DataSource = model;
}
Run();
}
private void OnReportStart(object sender, EventArgs e)
{
Document.Printer.PrinterName = string.Empty;
PageSettings.PaperKind = PaperKind.Number10Envelope;
PageSettings.Margins.Top = 0.25f;
PageSettings.Margins.Left = 0.5f;
PageSettings.Margins.Right = 0.5f;
PageSettings.Margins.Bottom = 0.25f;
}
}
Web API Controller Code:
[HttpGet]
public HttpResponseMessage EnvelopeReport(int addressId, string attentionTo, bool isConfidential)
{
Address address = AddressRepository.GetAddress(addressId, true);
List<PrintedAddress> models = new List<PrintedAddress>
{
new PrintedAddress(address, attentionTo, isConfidential)
};
var report = new EnvelopeReport();
report.RunReport(models);
var pdfExporter = new ActiveReportsPdfExporter();
var reportBytes = pdfExporter.ExportPdf(report);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new ByteArrayContent(reportBytes, 0, reportBytes.Length);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Envelope Report.pdf"
};
return response;
}
PDF Exporter:
public class ActiveReportsPdfExporter
{
private readonly PdfExport _pdfExport;
public ActiveReportsPdfExporter()
{
_pdfExport = new PdfExport();
}
public byte[] ExportPdf(SectionReport report)
{
using (var stream = new MemoryStream())
{
_pdfExport.Export(report.Document, stream);
return stream.ToArray();
}
}
public Stream ExportPdfToStream(SectionReport report)
{
var stream = new MemoryStream();
_pdfExport.Export(report.Document, stream);
return stream;
}
}
Client Service (Angular):
(function () {
angular.module('app').factory('addressSvc', [
'$http', addressSvc
]);
function addressSvc($http) {
var service = {
printAddress: function(addressId, attentionTo, someFlag) {
var args = {
'addressId': thingId,
'attentionTo': attentionTo,
'isConfidential': isConfidential
};
return $http.get('/api/common/EnvelopeReport', { 'params': args });
}
};
return service;
}
})();
Client Controller (Angular):
(function() {
angular.module('app').controller('someCtrl', [
'$window', 'addressSvc', controller
]);
function controller($window, addressSvc) {
var vm = this;
vm.attentionTo = ''; // Bound to UI.
vm.isConfidential = ''; // Also bound to UI.
vm.address = {}; // Unimportant how we get this.
vm.printAddress = printAddress;
function printAddress() {
addressSvc.printAddress(vm.address.id, vm.attentionTo, vm.isConfidential)
.then(function(result) {
var file = new Blob([result], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
if(window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(file, 'Envelope.pdf');
} else {
$window.open(fileURL);
}
});
}
}
)();
Question: Why is this code generating an empty PDF? I've used the Report/API Controller structure successfully in the past to generate PDFs, but usually in the context of MVC, not Web API. Another potential point of failure is the client code - I've not previously passed reports between server and client this way.
So, it turns out my server-side code was completely sane. The Client code was off.
Instead of Blobbing the data returned from the server and all of that work, what I instead needed to do was build a URL...and call $window.open(url); This is because my server code as it stands will return the PDF file as-is.
I'm new to Facebook apps. I'm trying to create an MVC 4 application with Facebook Application as my Project Template.
I'm trying to catch the page id on which the page tab is created and I've got it somehow.
My problem here is when someone visits my app, I want to know the page id through which they are viewing the page tab. I've searched a lot where I got to know that I've to use FacebookSignedRequest for this. But this class is not available to me.
Thanks in advance for any help.
If you are simply trying to parse the signed_request parameter from Facebook, you can do so using the following C# code.
This code also verifies the hash using your own app_secret param, to ensure the signed_request originated from Facebook.
public static string DecodeSignedRequest(string signed_request)
{
try
{
if (signed_request.Contains("."))
{
string[] split = signed_request.Split('.');
string signatureRaw = FixBase64String(split[0]);
string dataRaw = FixBase64String(split[1]);
// the decoded signature
byte[] signature = Convert.FromBase64String(signatureRaw);
byte[] dataBuffer = Convert.FromBase64String(dataRaw);
// JSON object
string data = Encoding.UTF8.GetString(dataBuffer);
byte[] appSecretBytes = Encoding.UTF8.GetBytes(app_secret);
System.Security.Cryptography.HMAC hmac = new System.Security.Cryptography.HMACSHA256(appSecretBytes);
byte[] expectedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(split[1]));
if (expectedHash.SequenceEqual(signature))
{
return data;
}
}
}
catch
{
// error
}
return "";
}
private static string FixBase64String(string str)
{
while (str.Length % 4 != 0)
{
str = str.PadRight(str.Length + 1, '=');
}
return str.Replace("-", "+").Replace("_", "/");
}
All I had to do was create a Facebook Client object and call the ParseSignedRequest method with the app secret.
var fb = new FacebookClient();
dynamic signedRequest = fb.ParseSignedRequest(appSecret, Request.Form["signed_request"]);
This returns a Json object which we have to parse using JObject.Parse