Raspberry Pi, Windows IoT, C# - c#

I am currently experimenting with my Raspberry Pi with Grove sensors and Windows IoT. I am trying to transfer information from the Raspberry Pi to Azure and I receive an error (In line 85).
The code looks this way:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;
using Windows.ApplicationModel.Background;
using GrovePi;
using GrovePi.I2CDevices;
using GrovePi.Sensors;
using GrovePi.Common;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Client;
using Newtonsoft.Json;
// The Background Application template is documented at http://go.microsoft.com/fwlink/?LinkID=533884&clcid=0x409
namespace GrooveTHS
{
public sealed class StartupTask : IBackgroundTask
{
IRgbLcdDisplay LCDDisplay;
public void Run(IBackgroundTaskInstance taskInstance)
{
IDHTTemperatureAndHumiditySensor sensor = DeviceFactory.Build.DHTTemperatureAndHumiditySensor(Pin.DigitalPin7, DHTModel.Dht11); // pinD7
LCDDisplay = DeviceFactory.Build.RgbLcdDisplay(); // pinI2C-1
IRotaryAngleSensor potentiometer = DeviceFactory.Build.RotaryAngleSensor(Pin.AnalogPin2); // pinA2
ILed red = DeviceFactory.Build.Led(Pin.DigitalPin5); // pinD5
ILed green = DeviceFactory.Build.Led(Pin.DigitalPin6); // pinD6
IUltrasonicRangerSensor dsensor = DeviceFactory.Build.UltraSonicSensor(Pin.DigitalPin4); // pin D4
double angle = 0;
double tmax = 0;
while (true)
{
Task.Delay(500).Wait();
angle = potentiometer.SensorValue();
sensor.Measure();
string sensortemp = sensor.TemperatureInCelsius.ToString();
tmax = Math.Floor(angle / 10);
string sensorvalue = dsensor.MeasureInCentimeters().ToString();
if (sensor.TemperatureInCelsius > tmax)
{
System.Diagnostics.Debug.WriteLine("Raumtemperatur: " + sensortemp + "C " + "Tmax: " + tmax.ToString() + "C");
red.AnalogWrite(Convert.ToByte(240));
green.AnalogWrite(Convert.ToByte(0));
}
else
{
System.Diagnostics.Debug.WriteLine("Raumtemperatur: " + sensortemp + "C" + "Tmax: " + tmax.ToString() + "C");
red.AnalogWrite(Convert.ToByte(0));
green.AnalogWrite(Convert.ToByte(240));
}
if (dsensor.MeasureInCentimeters() < 150)
{
LCDDisplay.SetBacklightRgb(BitConverter.GetBytes(990)[0], BitConverter.GetBytes(990)[0], BitConverter.GetBytes(990)[0]);
LCDDisplay.SetText("Raumtemperatur: " + sensortemp + "C " + "Tmax: " + tmax.ToString() + "C");
}
else
{
LCDDisplay.SetText("");
LCDDisplay.SetBacklightRgb(BitConverter.GetBytes(0)[0], BitConverter.GetBytes(0)[0], BitConverter.GetBytes(0)[0]);
}
}
}
static async void SendDeviceToCloudMessagesAsync(long inputDistance)
{
string iotHubUri = "IotHubAuburn.azure-devices.net"; // ! put in value !
string deviceId = "jb"; // ! put in value !
string deviceKey = "sHGJlQbLLMeMExNaqtvh8/7N7MHWlBZ0ESj2ePahSwQ="; // ! put in value !
DateTime time = DateTime.UtcNow;
var deviceClient = DeviceClient.Create(iotHubUri, AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), TransportType.Http1);
JSON jsonStr = new JSON();
jsonStr.distance = inputDistance;
jsonStr.time = time;
jsonStr.deviceId = deviceId;
var list = JsonConvert.SerializeObject(jsonStr);
System.Diagnostics.Debug.WriteLine(list);
var message = new Message(Encoding.UTF8.GetBytes(list));
await deviceClient.SendEventAsync(message);
}
}
}
And errors I am getting are following (Translated from german language):
1) CS0246 The type or a namespacename "JSON" was not found (maybe a
using-derective or a reprimand assembly is missing).
2) CS0246 The type or a namespacename "JSON" was not found (maybe a
using-derective or a reprimand assembly is missing).
Kind regards,
Alex

The error means that the "JSON" class definition can't be found.
As #Eric Magers pointed out, you can find from the code source you referenced where is the JSON class defined.
Or you can also define your own "JSON" class, for example, like this:
internal class JSON
{
public JSON()
{
}
public string deviceId { get; internal set; }
public long distance { get; internal set; }
public DateTime time { get; internal set; }
}
Another method without defining "JSON" class like this:
string dataBuffer;
DateTime time = DateTime.UtcNow;
long inputDistance = 0;
String deviceId = "MyCSharpDevice";
dataBuffer = string.Format("{{\"deviceId\":\"{0}\",\"distance\":{1},\"time\":{2}}}", deviceId, inputDistance, time);
Message message = new Message(Encoding.UTF8.GetBytes(dataBuffer));
await deviceClient.SendEventAsync(message);
For sending messages to Azure IoT Hub using HTTP protocol in C# you can reference this official sample. Note: the official sample is in Console Application and you are using a background application on Windows IoT Core. Application types are different but how to use Azure IoT Hub SDK is the same.

Related

opening sap and then proceeding to login screen through c# Automation

I am trying to open sap and connect to the gui using the following code . I Had to remove the earlier post due to some mistakes in post . I want to open sap logon 730 screen and then proceed to logon screen where i want to login using some credentials.I am getting some errors of connection entry point not found in the first code named opensap . login is working now. BUt still i cant make the SapBOX screen automatically process to the login screen. Please help in the code . Any help will be highly appreciated . Thanks
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SAPFEWSELib;
using SapROTWr;
using AVTAR.SAPLibrary;
using AVTAR.CustomLibrary;
namespace AvatarTest1 {
public class Sap {
public static GuiApplication SapGuiApp { get; set; }
public static GuiConnection SapConnection { get; set; }
public static GuiSession SapSession { get; set; }
public static void openSap(string env) {
Sap.SapGuiApp = new GuiApplication();
string connectString = null;
if (env.ToUpper().Equals("DEFAULT")) {
connectString = "1.0 Test ERP (DEFAULT)";
//connectString = "ASHOST = n7p.naan.as.com SYSNR = N7P
CLIENT =
460 _USER = ***** PASSWD = ****";*******";
} else {
connectString = env;
}
Sap.SapConnection = Sap.SapGuiApp.OpenConnection(connectString,
Sync: true); //creates connection
//Sap.SapSession = (GuiSession)Sap.SapConnection.Sessions.Item(0);
//creates the Gui session off the connection you made
}
public void Login(string userId,string pass,string clientid) {
try {
for (int i = 0; i <= 50; i++) {
Sap.SapSession = SapGuiApp.ActiveSession;
}
// System.Diagnostics.Process.Start(#"C:\Program
Files\SAP\FrontEnd\SAPgui\saplogon.exe");
GuiTextField Clientfield =
(GuiTextField)SapSession.ActiveWindow.FindById("wnd[0] / usr / txtRSYST -
MANDT");
GuiTextField UserIDField =
(GuiTextField)SapSession.ActiveWindow.FindById("wnd[0]/usr/txtRSYST-BNAME");
GuiTextField PassField =
(GuiTextField)SapSession.ActiveWindow.FindById("wnd[0]/usr/pwdRSYST-BCODE");
//GuiTextField LanguageField =
(GuiTextField)SapSession.ActiveWindow.FindById("wnd[0]/usr/txtRSYST-BNAME");
Clientfield.SetFocus();
Clientfield.Text = clientid;
UserIDField.SetFocus();
UserIDField.Text = userId;
PassField.SetFocus();
PassField.Text = pass;
//Sap.SapSession ssn= new SapSession.FindById("wnd[0]")
GuiButton enter =
(GuiButton)SapSession.ActiveWindow.FindById("wnd[0]");
enter.Press();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
In your Code you commented out "System.Diagnostics.Process.Start(#"C:\Program
Files\SAP\FrontEnd\SAPgui\saplogon.exe");"
Go with this aproach, but use "sapshcut.exe" from the same Folder instead!
(this will be available on the most systems)
In this case it could be as simple as that:
string strProg="C:\Program Files\SAP\FrontEnd\SAPgui\sapshcut.exe";
string strParam="-system=N7P -client=460 -user=youruser -password=yourpassword -language=EN";
System.Diagnostics.Process.Start(strProg,strParam);
Find an (VBA)Examle with some pre-Tests on the Commanline at trouble using excel macro for access to sap
Hope this will do ist for you!

Malformed Syslog Packet when using LEEF format

I'm using SyslogNet library to send SIEM Syslog message from my app to 3rd party vendors SIEM system in LEEF format (in this it's QRadar).
However, I the message doesn't get sent and nowhere the procedure produce any exception.
I can see and confirm that the string correlates to the correct template/format according to Rfc5424 for LEEF messages (see example below the code).
The only indication that the message was not sent properly is a WireShark trace showing the that the message was consisted of only a few bytes and more importantly is considered a malformed packet:
The code is as follows:
using System.IO;
using System.Text;
using System.Reflection;
using SyslogNet.Client;
using SyslogNet.Client.Serialization;
using SyslogNet.Client.Transport;
using Severity = SyslogNet.Client.Severity;
namespace Providers.Syslog
{
public class SyslogLogger
{
private readonly SyslogSettings _syslogSettings;
private readonly SyslogUdpSender _syslogUdpSender;
public SyslogLogger(SyslogSettings syslogSettings)
{
_syslogSettings = syslogSettings;
_syslogUdpSender = new SyslogUdpSender(syslogSettings.SyslogServerName, syslogSettings.SyslogServerPort);
}
public void Log(string message)
{
var syslogMessage = new SyslogMessage(
null,
(Facility)_syslogSettings.Facility,
Severity.Informational,
null,
_syslogSettings.Identity,
message);
_syslogUdpSender.Send(syslogMessage, new SyslogMessageSerializer());
}
private class SyslogMessageSerializer : SyslogMessageSerializerBase, ISyslogMessageSerializer
{
private const int AppNameMaxLength = 32;
public void Serialize(SyslogMessage message, Stream stream)
{
var priorityValue = CalculatePriorityValue(message.Facility, message.Severity);
string timestamp = null;
if (message.DateTimeOffset.HasValue)
{
var dt = message.DateTimeOffset.Value;
var day = dt.Day < 10 ? " " + dt.Day : dt.Day.ToString();
timestamp = string.Concat(dt.ToString("MMM "), day, dt.ToString(" HH:mm:ss"));
}
var headerBuilder = new StringBuilder();
headerBuilder.Append("<").Append(priorityValue).Append(">");
if (!string.IsNullOrEmpty(timestamp))
{
headerBuilder.Append(timestamp).Append(" ");
}
if (!string.IsNullOrEmpty(message.HostName))
{
headerBuilder.Append(message.HostName).Append(" ");
}
if (!message.Message.IsSiemOrientadTemplate())
{
var appName = message.AppName;
headerBuilder.Append(string.IsNullOrWhiteSpace(appName)
? appName
: (appName.Length > AppNameMaxLength ? appName.Substring(0, AppNameMaxLength) : appName) + ": ");
headerBuilder.Append(message.Message ?? "No Content");
}
var encoding = new UTF8Encoding(false);
var bytes = encoding.GetBytes(headerBuilder.ToString());
stream.Write(bytes, 0, bytes.Length);
}
}
}
}
e.g. of a message (I removed actual data and put on placeholders):
"LEEF:2.0|CompanyNameString|ProduceNameString|VersionString|int|^|
^cat=Test - QRADAR^sev=6^DescriptionString=^Timestamp=Apr 03 2017 14:48:02^userNameString=domain\DisplayName^accountName=samAccountName^proto=Syslog"
Any help will be much appreciated as it's been a while and I couldn't find a solution. Thanks in advance!
Finally found the issue.
I overlooked the fact that the content was in an "if" clause for non-SIEM systems.
Moving this line out of the clause resolve the issue for all syslog provider types.
headerBuilder.Append(message.Message ?? "No Content");

RallyDev - Getting Tasks for Stories using Rally.RestAPI.dll and Service V2.0

I'm pulling data off the Rally server at https://rally1.rallydev.com using C# and the Rally.RestAPI.dll. The server was recently upgraded to webservice v2.0 and I'm having some problems getting tasks for a user story. I know the way child collections are presented were changed in the API with the move to 2.0, but what I'm trying isn't working.
v2.0 removed the ability to return child collections in the same
response for performance reasons. Now fetching a collection will return
an object with the count and the url from which to get the collection
data.A separate request is needed to get to the elements of the
collection.
Here is the code that iterates over user story results, accesses "Tasks" collection on stories and issues a separate request to access individual Task attributes:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using Rally.RestApi;
using Rally.RestApi.Response;
namespace aRestApp_CollectionOfTasks
{
class Program
{
static void Main(string[] args)
{
//Initialize the REST API
RallyRestApi restApi;
restApi = new RallyRestApi("user#co.com", "secret", "https://rally1.rallydev.com", "v2.0");
//Set our Workspace and Project scopings
String workspaceRef = "/workspace/11111"; //please replace this OID with an OID of your workspace
String projectRef = "/project/22222"; //please replace this OID with an OID of your project
bool projectScopingUp = false;
bool projectScopingDown = true;
Request storyRequest = new Request("HierarchicalRequirement");
storyRequest.Workspace = workspaceRef;
storyRequest.Project = projectRef;
storyRequest.ProjectScopeUp = projectScopingUp;
storyRequest.ProjectScopeDown = projectScopingDown;
storyRequest.Fetch = new List<string>()
{
"Name",
"FormattedID",
"Tasks",
"Estimate"
};
storyRequest.Query = new Query("LastUpdateDate", Query.Operator.GreaterThan, "2013-08-01");
QueryResult queryStoryResults = restApi.Query(storyRequest);
foreach (var s in queryStoryResults.Results)
{
Console.WriteLine("----------");
Console.WriteLine("FormattedID: " + s["FormattedID"] + " Name: " + s["Name"]);
//Console.WriteLine("Tasks ref: " + s["Tasks"]._ref);
Request taskRequest = new Request(s["Tasks"]);
QueryResult queryTaskResult = restApi.Query(taskRequest);
if (queryTaskResult.TotalResultCount > 0)
{
foreach (var t in queryTaskResult.Results)
{
var taskEstimate = t["Estimate"];
var taskName = t["Name"];
Console.WriteLine("Task Name: " + taskName + " Estimate: " + taskEstimate);
}
}
else
{
Console.WriteLine("no tasks found");
}
}
}
}
}

Using C#, how do I set a Rally weblink field?

Here's a screenshot of the field I'm trying to update:
How do I update the URL field?
WebLink type fields consist of two parts: LinkID and DisplayString. In order to set a LinkID (which corresponds to the variable ${id} in your screenshot, a DisplayString needs also to be set to an empty string.
Here is a full code example that uses Rally .NET REST toolkit:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using Rally.RestApi;
using Rally.RestApi.Response;
namespace aRestApp_CollectionOfTasks
{
class Program
{
static void Main(string[] args)
{
//Initialize the REST API
RallyRestApi restApi;
restApi = new RallyRestApi("user#co.com", "secret", "https://rally1.rallydev.com", "v2.0");
//Set our Workspace and Project scopings
String workspaceRef = "/workspace/1111"; //please replace this OID with an OID of your workspace
String projectRef = "/project/2222"; //please replace this OID with an OID of your project
bool projectScopingUp = false;
bool projectScopingDown = true;
Request storyRequest = new Request("Defect");
storyRequest.Workspace = workspaceRef;
storyRequest.Project = projectRef;
storyRequest.ProjectScopeUp = projectScopingUp;
storyRequest.ProjectScopeDown = projectScopingDown;
storyRequest.Fetch = new List<string>()
{
"Name",
"_ref",
"c_JiraLink"
};
storyRequest.Query = new Query("FormattedID", Query.Operator.Equals, "DE170");
QueryResult queryStoryResults = restApi.Query(storyRequest);
foreach (var s in queryStoryResults.Results)
{
Console.WriteLine(" Name: " + s["Name"] + " JiraLink's DisplayString: " + s["c_JiraLink"]["DisplayString"] + " JiraLink's LinkID: " + s["c_JiraLink"]["LinkID"]);
DynamicJsonObject toUpdate = new DynamicJsonObject();
DynamicJsonObject myLink = new DynamicJsonObject();
myLink["LinkID"] = "NM-3";
myLink["DisplayString"] = "";
toUpdate["c_JiraLink"] = myLink;
OperationResult updateResult = restApi.Update(s["_ref"], toUpdate);
}
}
}
}
Note that this is not different from a more general example of setting LinkID of a WebLink type of filed using a browser's REST client.
Method: POST
URL:
https://rally1.rallydev.com/slm/webservice/v2.0/defect/3807704995?key=abc123...
Request Body:
{
"defect":
{
"c_JiraLink":{
"DisplayString":"",
"LinkID":"NM-2"
}
}
}

How to use PrintCapabilities Class in C#

I am trying to intercept a printer job and change the attributes of the print job. I can intercept the print job and get information regarding it. I followed this article for that
http://www.codeproject.com/Questions/423178/printing-order-intercept-with-csharp
Now I want to change the paper size of the print job and for that I found this article
http://social.msdn.microsoft.com/Forums/en/windowsxps/thread/8af6ba92-5d2c-444b-91f4-a8747739c1b7
But the problem is I cannot create class PrintCapabilities. Am I missing something ?? Please help.
My current code looks like the following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Printing;
namespace PrintJob
{
class EvenWatch
{
private ManagementEventWatcher manEWatch;
public EvenWatch(string host)
{
System.Management.ManagementScope oMs = new System.Management
.ManagementScope(#"\\" + host + #"\root\cimv2");
oMs.Connect();
manEWatch = new ManagementEventWatcher(oMs, new EventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 0.1 WHERE TargetInstance ISA 'Win32_PrintJob'"));
manEWatch.EventArrived += new EventArrivedEventHandler(
mewPrintJobs_EventArrived);
manEWatch.Start();
}
static void mewPrintJobs_EventArrived(object sender, EventArrivedEventArgs e)
{
foreach (PropertyData prop in e.NewEvent.Properties)
{
string val = prop.Value == null ? "null" : prop.Value.ToString();
}
ManagementBaseObject printJob = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value;
string v = "";
foreach (PropertyData propp in printJob.Properties)
{
string name = propp.Name;
string val = propp.Value == null ? "null" : propp.Value.ToString();
val += "\n";
v += name + ":" + val;
}
PrintQueue printerSpooler = null;
printerSpooler = new PrintQueue(new PrintServer(), "EPSON LQ-300+ /II ESC/P 2");
PrintJobSettings printJobSetting = printerSpooler.CurrentJobSettings;
string desc = printJobSetting.Description;
//printerSpooler.CurrentJobSettings.CurrentPrintTicket
Console.WriteLine("-------");
Console.WriteLine(v);
}
}
}
I actually found out the answer. If you are using 4.0 you should also reference ReachFramework.dll once you do that the magic does happen :)

Categories

Resources