private void GetGroups(HttpRequest Request, HttpResponse Response) { try { Gateway.AssertUserAuthenticated(Request); if (!Request.HasData) { throw new BadRequestException(); } string StartsWith = Request.DecodeData() as string; if (string.IsNullOrEmpty(StartsWith)) { throw new BadRequestException(); } SuggestionEventArgs e = new SuggestionEventArgs(StartsWith.Trim()); foreach (RosterItem Item in Gateway.XmppClient.Roster) { foreach (string Group in Item.Groups) { e.AddSuggestion(Group); } } try { OnGetGroupSuggestions?.Invoke(this, e); } catch (Exception ex) { Log.Critical(ex); } StringBuilder sb = new StringBuilder(); string[] Groups = e.ToArray(); bool First = true; int Nr = 0; sb.Append("{\"groups\":["); foreach (string Group in Groups) { if (First) { First = false; } else { sb.Append(','); } sb.Append('"'); sb.Append(CommonTypes.JsonStringEncode(Group)); sb.Append('"'); Nr++; } sb.Append("],\"count\":"); sb.Append(Nr.ToString()); sb.Append("}"); Response.ContentType = "application/json"; Response.Write(sb.ToString()); Response.SendResponse(); } catch (Exception ex) { Response.SendResponse(ex); } finally { Response.Dispose(); } }
private async void Init() { try { Log.Informational("Starting application."); Types.Initialize( typeof(FilesProvider).GetTypeInfo().Assembly, typeof(RuntimeSettings).GetTypeInfo().Assembly, typeof(IContentEncoder).GetTypeInfo().Assembly, typeof(ICoapContentFormat).GetTypeInfo().Assembly, typeof(IDtlsCredentials).GetTypeInfo().Assembly, typeof(App).GetTypeInfo().Assembly); db = new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path + Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000); Database.Register(db); await db.RepairIfInproperShutdown(null); await db.Start(); #if GPIO gpio = GpioController.GetDefault(); if (gpio != null) { if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) && Status == GpioOpenStatus.PinOpened) { if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output)) { this.gpioPin.SetDriveMode(GpioPinDriveMode.Output); this.output = await RuntimeSettings.GetAsync("Actuator.Output", false); this.gpioPin.Write(this.output.Value ? GpioPinValue.High : GpioPinValue.Low); await MainPage.Instance.OutputSet(this.output.Value); Log.Informational("Setting Control Parameter.", string.Empty, "Startup", new KeyValuePair <string, object>("Output", this.output.Value)); } else { Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString()); } } else { Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString()); } } #else DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync(); DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device"); if (DeviceInfo is null) { Log.Error("Unable to find Arduino device."); } else { Log.Informational("Connecting to " + DeviceInfo.Name); this.arduinoUsb = new UsbSerial(DeviceInfo); this.arduinoUsb.ConnectionEstablished += () => Log.Informational("USB connection established."); this.arduino = new RemoteDevice(this.arduinoUsb); this.arduino.DeviceReady += async() => { try { Log.Informational("Device ready."); this.arduino.pinMode(13, PinMode.OUTPUT); // Onboard LED. this.arduino.digitalWrite(13, PinState.HIGH); this.arduino.pinMode(8, PinMode.INPUT); // PIR sensor (motion detection). this.arduino.pinMode(9, PinMode.OUTPUT); // Relay. this.output = await RuntimeSettings.GetAsync("Actuator.Output", false); this.arduino.digitalWrite(9, this.output.Value ? PinState.HIGH : PinState.LOW); await MainPage.Instance.OutputSet(this.output.Value); Log.Informational("Setting Control Parameter.", string.Empty, "Startup", new KeyValuePair <string, object>("Output", this.output.Value)); this.arduino.pinMode("A0", PinMode.ANALOG); // Light sensor. } catch (Exception ex) { Log.Critical(ex); } }; this.arduinoUsb.ConnectionFailed += message => { Log.Error("USB connection failed: " + message); }; this.arduinoUsb.ConnectionLost += message => { Log.Error("USB connection lost: " + message); }; this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1); } #endif this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty); if (string.IsNullOrEmpty(this.deviceId)) { this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty); await RuntimeSettings.SetAsync("DeviceId", this.deviceId); } Log.Informational("Device ID: " + this.deviceId); /************************************************************************************ * To create an unencrypted CoAP Endpoint on the default CoAP port: * * this.coapEndpoint = new CoapEndpoint(); * * To create an unencrypted CoAP Endpoint on the default CoAP port, * with a sniffer that outputs communication to the window: * * this.coapEndpoint = new CoapEndpoint(new LogSniffer()); * * To create a DTLS encrypted CoAP endpoint, on the default CoAPS port, using * the users defined in the IUserSource users: * * this.coapEndpoint = new CoapEndpoint(CoapEndpoint.DefaultCoapsPort, this.users); * * To create a CoAP endpoint, that listens to both the default CoAP port, for * unencrypted communication, and the default CoAPS port, for encrypted, * authenticated and authorized communication, using * the users defined in the IUserSource users. Only users having the given * privilege (if not empty) will be authorized to access resources on the endpoint: * * this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort }, * new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, "PRIVILEGE", false, false); * ************************************************************************************/ this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort }, new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, string.Empty, false, false); this.outputResource = this.coapEndpoint.Register("/Output", (req, resp) => { string s; if (this.output.HasValue) { s = this.output.Value ? "true" : "false"; } else { s = "-"; } resp.Respond(CoapCode.Content, s, 64); }, async(req, resp) => { try { string s = req.Decode() as string; if (s is null && req.Payload != null) { s = Encoding.UTF8.GetString(req.Payload); } if (s is null || !CommonTypes.TryParse(s, out bool Output)) { resp.RST(CoapCode.BadRequest); } else { resp.Respond(CoapCode.Changed); await this.SetOutput(Output, req.From.ToString()); } } catch (Exception ex) { Log.Critical(ex); } }, Notifications.Acknowledged, "Digital Output.", null, null,
/// <summary> /// Parses an accept header string. /// </summary> /// <param name="Value">Accept header string</param> /// <returns>Parsed items.</returns> public static AcceptRecord[] Parse(string Value) { List <AcceptRecord> Records = new List <AcceptRecord>(); List <KeyValuePair <string, string> > Parameters = null; StringBuilder sb = new StringBuilder(); AcceptRecord Record = null; string ParameterName = null; string ParameterValue = null; double q; int State = 0; int Order = 0; foreach (char ch in Value) { switch (State) { case 0: // Item name. if (ch <= 32) { break; } else if (ch == ';' || ch == ',') { Record = new AcceptRecord(); Record.Item = sb.ToString().Trim(); Record.Order = Order++; sb.Clear(); if (ch == ';') { State++; } else { Records.Add(Record); Record = null; } } else { sb.Append(ch); } break; case 1: // Parameter Name if (ch == '=') { ParameterName = sb.ToString().Trim(); sb.Clear(); State++; } else if (ch == ';' || ch == ',') { ParameterName = sb.ToString().Trim(); sb.Clear(); if (Parameters == null) { Parameters = new List <KeyValuePair <string, string> >(); } Parameters.Add(new KeyValuePair <string, string>(ParameterName, string.Empty)); ParameterName = null; if (ch == ',') { Record.Parameters = Parameters.ToArray(); Records.Add(Record); Record = null; Parameters = null; State = 0; } } else { sb.Append(ch); } break; case 2: // Parameter value. if (ch == '"') { State++; } else if (ch == '\'') { State += 3; } else if (ch == ';' || ch == ',') { ParameterValue = sb.ToString().Trim(); sb.Clear(); if (ParameterName == "q" && CommonTypes.TryParse(ParameterValue, out q)) { Record.Quality = q; } else { if (Parameters == null) { Parameters = new List <KeyValuePair <string, string> >(); } Parameters.Add(new KeyValuePair <string, string>(ParameterName, ParameterValue)); } ParameterName = null; ParameterValue = null; if (ch == ',') { if (Parameters != null) { Record.Parameters = Parameters.ToArray(); } Records.Add(Record); Record = null; Parameters = null; State = 0; } else { State--; } } else { sb.Append(ch); } break; case 3: // "Value" if (ch == '"') { State--; } else if (ch == '\\') { State++; } else { sb.Append(ch); } break; case 4: // Escape sb.Append(ch); State--; break; case 5: // 'Value' if (ch == '\'') { State -= 3; } else if (ch == '\\') { State++; } else { sb.Append(ch); } break; case 6: // Escape sb.Append(ch); State--; break; } } switch (State) { case 0: Record = new AcceptRecord(); Record.Item = sb.ToString().Trim(); Record.Order = Order++; if (!string.IsNullOrEmpty(Record.Item)) { Records.Add(Record); } break; case 1: ParameterName = sb.ToString().Trim(); if (!string.IsNullOrEmpty(ParameterName)) { if (Parameters == null) { Parameters = new List <KeyValuePair <string, string> >(); } Parameters.Add(new KeyValuePair <string, string>(ParameterName, string.Empty)); } if (Parameters != null) { Record.Parameters = Parameters.ToArray(); } Records.Add(Record); break; case 2: case 3: case 4: case 5: case 6: ParameterValue = sb.ToString().Trim(); if (ParameterName == "q" && CommonTypes.TryParse(ParameterValue, out q)) { Record.Quality = q; } else { if (Parameters == null) { Parameters = new List <KeyValuePair <string, string> >(); } Parameters.Add(new KeyValuePair <string, string>(ParameterName, ParameterValue)); } if (Parameters != null) { Record.Parameters = Parameters.ToArray(); } Records.Add(Record); break; } Records.Sort(CompareRecords); return(Records.ToArray()); }
/// <summary> /// Analyzes the object database /// </summary> /// <param name="FullPath">Full path of report file</param> /// <param name="FileName">Filename of report</param> /// <param name="Created">Time when report file was created</param> /// <param name="XmlOutput">XML Output</param> /// <param name="fs">File stream</param> /// <param name="Repair">If database should be repaired, if errors are found</param> public static async Task DoAnalyze(string FullPath, string FileName, DateTime Created, XmlWriter XmlOutput, FileStream fs, bool Repair) { try { Log.Informational("Starting analyzing database.", FileName); ExportFormats.ExportFormat.UpdateClientsFileUpdated(FileName, 0, Created); await Database.Analyze(XmlOutput, Path.Combine(Gateway.AppDataFolder, "Transforms", "DbStatXmlToHtml.xslt"), Gateway.AppDataFolder, false, Repair); XmlOutput.Flush(); fs.Flush(); ExportFormats.ExportFormat.UpdateClientsFileUpdated(FileName, fs.Length, Created); XmlOutput.Dispose(); XmlOutput = null; fs.Dispose(); fs = null; if (xslt is null) { xslt = XSL.LoadTransform(typeof(Gateway).Namespace + ".Transforms.DbStatXmlToHtml.xslt"); } string s = File.ReadAllText(FullPath); s = XSL.Transform(s, xslt); byte[] Bin = utf8Bom.GetBytes(s); string FullPath2 = FullPath.Substring(0, FullPath.Length - 4) + ".html"; File.WriteAllBytes(FullPath2, Bin); ExportFormats.ExportFormat.UpdateClientsFileUpdated(FileName.Substring(0, FileName.Length - 4) + ".html", Bin.Length, Created); Log.Informational("Database analysis successfully completed.", FileName); } catch (Exception ex) { Log.Critical(ex); string[] Tabs = ClientEvents.GetTabIDsForLocation("/Settings/Backup.md"); ClientEvents.PushEvent(Tabs, "BackupFailed", "{\"fileName\":\"" + CommonTypes.JsonStringEncode(FileName) + "\", \"message\": \"" + CommonTypes.JsonStringEncode(ex.Message) + "\"}", true, "User"); } finally { try { XmlOutput?.Dispose(); fs?.Dispose(); } catch (Exception ex) { Log.Critical(ex); } lock (synchObject) { analyzing = false; } } }
private static string SearchForInstallationFolder(Environment.SpecialFolder SpecialFolder) { string Folder; try { Folder = Environment.GetFolderPath(SpecialFolder); } catch (Exception) { return(null); // Folder not defined for the operating system. } if (String.IsNullOrEmpty(Folder)) { return(null); } if (!Directory.Exists(Folder)) { return(null); } string FolderName; string BestFolder = null; double BestVersion = 0; string[] SubFolders; try { SubFolders = Directory.GetDirectories(Folder); } catch (UnauthorizedAccessException) { return(null); } catch (Exception ex) { Log.Critical(ex); return(null); } foreach (string SubFolder in SubFolders) { FolderName = Path.GetFileName(SubFolder); if (!FolderName.StartsWith("Graphviz", StringComparison.CurrentCultureIgnoreCase)) { continue; } if (!CommonTypes.TryParse(FolderName.Substring(8), out double Version)) { Version = 1.0; } if (BestFolder == null || Version > BestVersion) { BestFolder = SubFolder; BestVersion = Version; } } return(BestFolder); }
/// <summary> /// Gets a data form containing editable parameters from an object. /// </summary> /// <param name="Client">Client</param> /// <param name="e">IQ Event Arguments describing the request.</param> /// <param name="EditableObject">Object whose parameters will be edited.</param> /// <param name="Title">Title of form.</param> /// <returns>Data form containing editable parameters.</returns> public static async Task <DataForm> GetEditableForm(XmppClient Client, IqEventArgs e, object EditableObject, string Title) { Type T = EditableObject.GetType(); string DefaultLanguageCode = GetDefaultLanguageCode(T); DataForm Parameters = new DataForm(Client, FormType.Form, e.To, e.From); Language Language = await ConcentratorServer.GetLanguage(e.Query, DefaultLanguageCode); Namespace Namespace = await Language.GetNamespaceAsync(T.Namespace); List <Field> Fields = new List <Field>(); List <Page> Pages = new List <Page>(); Dictionary <string, Page> PageByLabel = new Dictionary <string, Page>(); Dictionary <string, Section> SectionByPageAndSectionLabel = null; List <KeyValuePair <string, string> > Options = null; string Header; string ToolTip; string PageLabel; string SectionLabel; string s; int StringId; bool Required; bool ReadOnly; bool Masked; bool Alpha; bool DateOnly; HeaderAttribute HeaderAttribute; ToolTipAttribute ToolTipAttribute; PageAttribute PageAttribute; SectionAttribute SectionAttribute; OptionAttribute OptionAttribute; TextAttribute TextAttribute; RegularExpressionAttribute RegularExpressionAttribute; LinkedList <string> TextAttributes; RangeAttribute RangeAttribute; ValidationMethod ValidationMethod; Type PropertyType; Field Field; Page DefaultPage = null; Page Page; if (Namespace == null) { Namespace = await Language.CreateNamespaceAsync(T.Namespace); } foreach (PropertyInfo PI in T.GetRuntimeProperties()) { if (!PI.CanRead || !PI.CanWrite) { continue; } Header = ToolTip = PageLabel = SectionLabel = null; TextAttributes = null; ValidationMethod = null; Required = ReadOnly = Masked = Alpha = DateOnly = false; foreach (Attribute Attr in PI.GetCustomAttributes()) { if ((HeaderAttribute = Attr as HeaderAttribute) != null) { Header = HeaderAttribute.Header; StringId = HeaderAttribute.StringId; if (StringId > 0) { Header = await Namespace.GetStringAsync(StringId, Header); } } else if ((ToolTipAttribute = Attr as ToolTipAttribute) != null) { ToolTip = ToolTipAttribute.ToolTip; StringId = ToolTipAttribute.StringId; if (StringId > 0) { ToolTip = await Namespace.GetStringAsync(StringId, ToolTip); } } else if ((PageAttribute = Attr as PageAttribute) != null) { PageLabel = PageAttribute.Label; StringId = PageAttribute.StringId; if (StringId > 0) { PageLabel = await Namespace.GetStringAsync(StringId, PageLabel); } } else if ((SectionAttribute = Attr as SectionAttribute) != null) { SectionLabel = SectionAttribute.Label; StringId = SectionAttribute.StringId; if (StringId > 0) { SectionLabel = await Namespace.GetStringAsync(StringId, SectionLabel); } } else if ((TextAttribute = Attr as TextAttribute) != null) { if (TextAttributes == null) { TextAttributes = new LinkedList <string>(); } StringId = TextAttribute.StringId; if (StringId > 0) { TextAttributes.AddLast(await Namespace.GetStringAsync(StringId, TextAttribute.Label)); } else { TextAttributes.AddLast(TextAttribute.Label); } } else if ((OptionAttribute = Attr as OptionAttribute) != null) { if (Options == null) { Options = new List <KeyValuePair <string, string> >(); } StringId = OptionAttribute.StringId; if (StringId > 0) { Options.Add(new KeyValuePair <string, string>(OptionAttribute.Option.ToString(), await Namespace.GetStringAsync(StringId, TextAttribute.Label))); } else { Options.Add(new KeyValuePair <string, string>(OptionAttribute.Option.ToString(), OptionAttribute.Label)); } } else if ((RegularExpressionAttribute = Attr as RegularExpressionAttribute) != null) { ValidationMethod = new RegexValidation(RegularExpressionAttribute.Pattern); } else if ((RangeAttribute = Attr as RangeAttribute) != null) { ValidationMethod = new RangeValidation(RangeAttribute.Min, RangeAttribute.Max); } else if (Attr is OpenAttribute) { ValidationMethod = new OpenValidation(); } else if (Attr is RequiredAttribute) { Required = true; } else if (Attr is ReadOnlyAttribute) { ReadOnly = true; } else if (Attr is MaskedAttribute) { Masked = true; } else if (Attr is AlphaChannelAttribute) { Alpha = true; } else if (Attr is DateOnlyAttribute) { DateOnly = true; } } if (Header == null) { continue; } PropertyType = PI.PropertyType; Field = null; if (PropertyType == typeof(string[])) { if (ValidationMethod == null) { ValidationMethod = new BasicValidation(); } if (Options == null) { Field = new TextMultiField(Parameters, PI.Name, Header, Required, (string[])PI.GetValue(EditableObject), null, ToolTip, StringDataType.Instance, ValidationMethod, string.Empty, false, ReadOnly, false); } else { Field = new ListMultiField(Parameters, PI.Name, Header, Required, (string[])PI.GetValue(EditableObject), Options.ToArray(), ToolTip, StringDataType.Instance, ValidationMethod, string.Empty, false, ReadOnly, false); } } else if (PropertyType == typeof(Enum)) { if (ValidationMethod == null) { ValidationMethod = new BasicValidation(); } if (Options == null) { Options = new List <KeyValuePair <string, string> >(); foreach (string Option in Enum.GetNames(PropertyType)) { Options.Add(new KeyValuePair <string, string>(Option, Option)); } } Field = new ListSingleField(Parameters, PI.Name, Header, Required, new string[] { PI.GetValue(EditableObject).ToString() }, Options.ToArray(), ToolTip, null, ValidationMethod, string.Empty, false, ReadOnly, false); } else if (PropertyType == typeof(bool)) { if (ValidationMethod == null) { ValidationMethod = new BasicValidation(); } Field = new BooleanField(Parameters, PI.Name, Header, Required, new string[] { CommonTypes.Encode((bool)PI.GetValue(EditableObject)) }, Options?.ToArray(), ToolTip, BooleanDataType.Instance, ValidationMethod, string.Empty, false, ReadOnly, false); } else { DataType DataType; if (PropertyType == typeof(string)) { DataType = StringDataType.Instance; } else if (PropertyType == typeof(byte)) { DataType = ByteDataType.Instance; } else if (PropertyType == typeof(short)) { DataType = ShortDataType.Instance; } else if (PropertyType == typeof(int)) { DataType = IntDataType.Instance; } else if (PropertyType == typeof(long)) { DataType = LongDataType.Instance; } else if (PropertyType == typeof(sbyte)) { DataType = ShortDataType.Instance; if (ValidationMethod == null) { ValidationMethod = new RangeValidation(sbyte.MinValue.ToString(), sbyte.MaxValue.ToString()); } } else if (PropertyType == typeof(ushort)) { DataType = IntDataType.Instance; if (ValidationMethod == null) { ValidationMethod = new RangeValidation(ushort.MinValue.ToString(), ushort.MaxValue.ToString()); } } else if (PropertyType == typeof(uint)) { DataType = LongDataType.Instance; if (ValidationMethod == null) { ValidationMethod = new RangeValidation(uint.MinValue.ToString(), uint.MaxValue.ToString()); } } else if (PropertyType == typeof(ulong)) { DataType = IntegerDataType.Instance; if (ValidationMethod == null) { ValidationMethod = new RangeValidation(ulong.MinValue.ToString(), ulong.MaxValue.ToString()); } } else if (PropertyType == typeof(DateTime)) { if (DateOnly) { DataType = DateDataType.Instance; } else { DataType = DateTimeDataType.Instance; } } else if (PropertyType == typeof(decimal)) { DataType = DecimalDataType.Instance; } else if (PropertyType == typeof(double)) { DataType = DoubleDataType.Instance; } else if (PropertyType == typeof(float)) { DataType = DoubleDataType.Instance; // Use xs:double anyway } else if (PropertyType == typeof(TimeSpan)) { DataType = TimeDataType.Instance; } else if (PropertyType == typeof(Uri)) { DataType = AnyUriDataType.Instance; } else if (PropertyType == typeof(SKColor)) { if (Alpha) { DataType = ColorAlphaDataType.Instance; } else { DataType = ColorDataType.Instance; } } else { DataType = null; } if (ValidationMethod == null) { ValidationMethod = new BasicValidation(); } if (Masked) { Field = new TextPrivateField(Parameters, PI.Name, Header, Required, new string[] { (string)PI.GetValue(EditableObject) }, Options?.ToArray(), ToolTip, StringDataType.Instance, ValidationMethod, string.Empty, false, ReadOnly, false); } else if (Options == null) { Field = new TextSingleField(Parameters, PI.Name, Header, Required, new string[] { (string)PI.GetValue(EditableObject) }, null, ToolTip, StringDataType.Instance, ValidationMethod, string.Empty, false, ReadOnly, false); } else { Field = new ListSingleField(Parameters, PI.Name, Header, Required, new string[] { (string)PI.GetValue(EditableObject) }, Options.ToArray(), ToolTip, StringDataType.Instance, ValidationMethod, string.Empty, false, ReadOnly, false); } } if (Field == null) { continue; } Fields.Add(Field); if (string.IsNullOrEmpty(PageLabel)) { if (DefaultPage == null) { DefaultPage = new Page(Parameters, string.Empty); Pages.Add(DefaultPage); PageByLabel[string.Empty] = DefaultPage; } Page = DefaultPage; PageLabel = string.Empty; } else { if (!PageByLabel.TryGetValue(PageLabel, out Page)) { Page = new Page(Parameters, PageLabel); Pages.Add(Page); PageByLabel[PageLabel] = Page; } } if (string.IsNullOrEmpty(SectionLabel)) { if (TextAttributes != null) { foreach (string Text in TextAttributes) { Page.Add(new TextElement(Parameters, Text)); } } Page.Add(new FieldReference(Parameters, Field.Var)); } else { if (SectionByPageAndSectionLabel == null) { SectionByPageAndSectionLabel = new Dictionary <string, Section>(); } s = PageLabel + " \xa0 " + SectionLabel; if (!SectionByPageAndSectionLabel.TryGetValue(s, out Section Section)) { Section = new Section(Parameters, SectionLabel); SectionByPageAndSectionLabel[s] = Section; Page.Add(Section); } if (TextAttributes != null) { foreach (string Text in TextAttributes) { Section.Add(new TextElement(Parameters, Text)); } } Section.Add(new FieldReference(Parameters, Field.Var)); } } Parameters.Title = Title; Parameters.Fields = Fields.ToArray(); Parameters.Pages = Pages.ToArray(); return(Parameters); }
/// <summary> /// Creates a BOSH session. /// </summary> public override async void CreateSession() { try { StringBuilder Xml; int i, c; lock (this.httpClients) { this.terminated = false; this.outputQueue.Clear(); c = this.httpClients.Length; for (i = 0; i < c; i++) { if ((this.active[i] && this.httpClients[i] != null) || i == 0) { this.httpClients[i]?.Dispose(); this.httpClients[i] = new HttpClient(new HttpClientHandler() { #if !NETFW ServerCertificateCustomValidationCallback = this.RemoteCertificateValidationCallback, #endif UseCookies = false }) { Timeout = TimeSpan.FromMilliseconds(60000) }; this.httpClients[i].DefaultRequestHeaders.ExpectContinue = false; this.active[i] = false; } } this.GenerateKeysLocked(); Xml = new StringBuilder(); Xml.Append("<body content='text/xml; charset=utf-8' from='"); Xml.Append(XML.Encode(this.xmppClient.BareJID)); Xml.Append("' hold='1' rid='"); Xml.Append((this.rid++).ToString()); Xml.Append("' to='"); Xml.Append(XML.Encode(this.xmppClient.Domain)); Xml.Append("' newkey='"); Xml.Append(this.keys.First.Value); this.keys.RemoveFirst(); } #if ECHO Xml.Append("' echo='0"); #endif Xml.Append("' ver='1.11' wait='30' xml:lang='"); Xml.Append(XML.Encode(this.xmppClient.Language)); Xml.Append("' xmpp:version='1.0' xmlns='"); Xml.Append(HttpBindNamespace); Xml.Append("' xmlns:xmpp='"); Xml.Append(BoshNamespace); Xml.Append("'/>"); string s = Xml.ToString(); if (this.xmppClient.HasSniffers) { this.xmppClient.Information("Initiating session."); this.xmppClient.TransmitText(s); } HttpContent Content = new StringContent(s, System.Text.Encoding.UTF8, "text/xml"); XmlDocument ResponseXml; this.bindingInterface.NextPing = DateTime.Now.AddMinutes(1); HttpResponseMessage Response = await this.httpClients[0].PostAsync(this.url, Content); Response.EnsureSuccessStatusCode(); Stream Stream = await Response.Content.ReadAsStreamAsync(); // Regardless of status code, we check for XML content. XmlElement Body; byte[] Bin = await Response.Content.ReadAsByteArrayAsync(); string CharSet = Response.Content.Headers.ContentType.CharSet; Encoding Encoding; if (string.IsNullOrEmpty(CharSet)) { Encoding = Encoding.UTF8; } else { Encoding = System.Text.Encoding.GetEncoding(CharSet); } string XmlResponse = Encoding.GetString(Bin); if (this.xmppClient.HasSniffers) { this.xmppClient.ReceiveText(XmlResponse); } ResponseXml = new XmlDocument(); ResponseXml.LoadXml(XmlResponse); if ((Body = ResponseXml.DocumentElement) is null || Body.LocalName != "body" || Body.NamespaceURI != HttpBindNamespace) { throw new Exception("Unexpected response returned."); } this.sid = null; foreach (XmlAttribute Attr in Body.Attributes) { switch (Attr.Name) { case "sid": this.sid = Attr.Value; break; case "wait": if (!int.TryParse(Attr.Value, out this.waitSeconds)) { throw new Exception("Invalid wait period."); } break; case "requests": if (!int.TryParse(Attr.Value, out this.requests)) { throw new Exception("Invalid number of requests."); } break; case "ver": if (!CommonTypes.TryParse(Attr.Value, out this.version)) { throw new Exception("Invalid version number."); } break; case "polling": if (!int.TryParse(Attr.Value, out this.pollingSeconds)) { throw new Exception("Invalid polling period."); } break; case "inactivity": if (!int.TryParse(Attr.Value, out this.inactivitySeconds)) { throw new Exception("Invalid inactivity period."); } break; case "maxpause": if (!int.TryParse(Attr.Value, out this.maxPauseSeconds)) { throw new Exception("Invalid maximum pause period."); } break; case "hold": if (!int.TryParse(Attr.Value, out this.hold)) { throw new Exception("Invalid maximum number of requests."); } break; case "to": this.to = Attr.Value; break; case "from": this.from = Attr.Value; break; case "accept": this.accept = Attr.Value; break; case "charsets": this.charsets = Attr.Value; break; case "ack": if (!long.TryParse(Attr.Value, out long l) || l != this.rid) { throw new Exception("Response acknowledgement invalid."); } break; default: switch (Attr.LocalName) { case "restartlogic": if (Attr.NamespaceURI == BoshNamespace && CommonTypes.TryParse(Attr.Value, out bool b)) { this.restartLogic = true; } break; } break; } } if (string.IsNullOrEmpty(this.sid)) { throw new Exception("Session not granted."); } if (this.requests > 1) { Array.Resize <HttpClient>(ref this.httpClients, this.requests); Array.Resize <bool>(ref this.active, this.requests); } for (i = 0; i < this.requests; i++) { if (this.httpClients[i] != null) { if (this.active[i]) { this.httpClients[i].Dispose(); this.httpClients[i] = null; } else { continue; } } this.httpClients[i] = new HttpClient(new HttpClientHandler() { #if !NETFW ServerCertificateCustomValidationCallback = this.RemoteCertificateValidationCallback, #endif UseCookies = false }) { Timeout = TimeSpan.FromMilliseconds(60000) }; this.httpClients[i].DefaultRequestHeaders.ExpectContinue = false; this.active[i] = false; } await this.BodyReceived(XmlResponse, true); } catch (Exception ex) { this.bindingInterface.ConnectionError(ex); } }
/// <summary> /// Performs an HTTP request. /// </summary> /// <param name="To">Full JID of entity to query.</param> /// <param name="Method">HTTP Method.</param> /// <param name="LocalResource">Local resource.</param> /// <param name="HttpVersion">HTTP Version.</param> /// <param name="Headers">HTTP headers.</param> /// <param name="DataStream">Data Stream, if any, or null, if no data is sent.</param> /// <param name="Callback">Callback method to call when response is returned.</param> /// <param name="DataCallback">Local resource.</param> /// <param name="State">State object to pass on to the callback method.</param> public void Request(string To, string Method, string LocalResource, double HttpVersion, IEnumerable <HttpField> Headers, Stream DataStream, HttpxResponseEventHandler Callback, HttpxResponseDataEventHandler DataCallback, object State) { // TODO: Local IP & port for quick P2P response (TLS, or POST back, web hook). StringBuilder Xml = new StringBuilder(); Xml.Append("<req xmlns='"); Xml.Append(Namespace); Xml.Append("' method='"); Xml.Append(Method); Xml.Append("' resource='"); Xml.Append(XML.Encode(LocalResource)); Xml.Append("' version='"); Xml.Append(HttpVersion.ToString("F1").Replace(System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator, ".")); Xml.Append("' maxChunkSize='"); Xml.Append(this.maxChunkSize.ToString()); Xml.Append("' sipub='false' ibb='"); Xml.Append(CommonTypes.Encode(this.ibbClient != null)); Xml.Append("' s5='"); Xml.Append(CommonTypes.Encode(this.socks5Proxy != null)); Xml.Append("' jingle='false'>"); Xml.Append("<headers xmlns='"); Xml.Append(HttpxClient.NamespaceHeaders); Xml.Append("'>"); foreach (HttpField HeaderField in Headers) { Xml.Append("<header name='"); Xml.Append(XML.Encode(HeaderField.Key)); Xml.Append("'>"); Xml.Append(XML.Encode(HeaderField.Value)); Xml.Append("</header>"); } Xml.Append("</headers>"); string StreamId = null; if (DataStream != null) { if (DataStream.Length < this.maxChunkSize) { int c = (int)DataStream.Length; byte[] Data = new byte[c]; DataStream.Position = 0; DataStream.Read(Data, 0, c); Xml.Append("<data><base64>"); Xml.Append(Convert.ToBase64String(Data)); Xml.Append("</base64></data>"); } else { StreamId = Guid.NewGuid().ToString().Replace("-", string.Empty); Xml.Append("<data><chunkedBase64 streamId='"); Xml.Append(StreamId); Xml.Append("'/></data>"); } } Xml.Append("</req>"); if (this.e2e != null) { this.e2e.SendIqSet(this.client, E2ETransmission.NormalIfNotE2E, To, Xml.ToString(), this.ResponseHandler, new object[] { Callback, DataCallback, State }, 60000, 0); } else { this.client.SendIqSet(To, Xml.ToString(), this.ResponseHandler, new object[] { Callback, DataCallback, State }, 60000, 0); } if (!string.IsNullOrEmpty(StreamId)) { byte[] Data = new byte[this.maxChunkSize]; long Pos = 0; long Len = DataStream.Length; int Nr = 0; int i; DataStream.Position = 0; while (Pos < Len) { if (Pos + this.maxChunkSize <= Len) { i = this.maxChunkSize; } else { i = (int)(Len - Pos); } DataStream.Read(Data, 0, i); Xml.Clear(); Xml.Append("<chunk xmlns='"); Xml.Append(Namespace); Xml.Append("' streamId='"); Xml.Append(StreamId); Xml.Append("' nr='"); Xml.Append(Nr.ToString()); Xml.Append("'>"); Xml.Append(Convert.ToBase64String(Data, 0, i)); Xml.Append("</chunk>"); Nr++; if (this.e2e != null) { this.e2e.SendMessage(this.client, E2ETransmission.NormalIfNotE2E, QoSLevel.Unacknowledged, MessageType.Normal, string.Empty, To, Xml.ToString(), string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, null, null); } else { this.client.SendMessage(MessageType.Normal, To, Xml.ToString(), string.Empty, string.Empty, string.Empty, string.Empty, string.Empty); } } } }
private Data FindDataType(MqttContent Content) { try { string s = Encoding.UTF8.GetString(Content.Data); if (long.TryParse(s, out long i)) { this.RemoveWarning(); return(new IntegerData(this, i)); } if (CommonTypes.TryParse(s, out double x, out byte NrDecimals)) { this.RemoveWarning(); return(new FloatingPointData(this, x, NrDecimals)); } if (CommonTypes.TryParse(s, out bool b)) { this.RemoveWarning(); return(new BooleanData(this, b)); } if (System.Guid.TryParse(s, out Guid Guid)) { this.RemoveWarning(); return(new GuidData(this, Guid)); } if (System.TimeSpan.TryParse(s, out TimeSpan TimeSpan)) { this.RemoveWarning(); return(new TimeSpanData(this, TimeSpan)); } if (System.DateTime.TryParse(s, out DateTime DateTime)) { this.RemoveWarning(); return(new DateTimeData(this, DateTime)); } if (CommonTypes.TryParseRfc822(s, out DateTimeOffset DateTimeOffset)) { this.RemoveWarning(); return(new DateTimeOffsetData(this, DateTimeOffset)); } if (Waher.Content.Duration.TryParse(s, out Duration Duration)) { this.RemoveWarning(); return(new DurationData(this, Duration)); } if (s.StartsWith("<") && s.EndsWith(">")) { try { XmlDocument Doc = new XmlDocument(); Doc.LoadXml(s); this.RemoveWarning(); return(new XmlData(this, s, Doc)); } catch (Exception) { // Not XML } } if ((s.StartsWith("{") && s.EndsWith("}")) || (s.StartsWith("[") && s.EndsWith("]"))) { try { object Obj = JSON.Parse(s); this.RemoveWarning(); return(new JsonData(this, s, Obj)); } catch (Exception) { // Not JSON } } if (s.IndexOfAny(controlCharacters) >= 0) { this.RemoveWarning(); return(new BinaryData(this, Content.Data)); } if (Base64Data.RegEx.IsMatch(s)) { this.RemoveWarning(); byte[] Data = Convert.FromBase64String(s.Trim()); if (Data.Length > 0) { return(new Base64Data(this, Data)); } } if (HexStringData.RegEx.IsMatch(s)) { this.RemoveWarning(); byte[] Data = Security.Hashes.StringToBinary(s.Trim()); if (Data.Length > 0) { return(new HexStringData(this, Data)); } } Match M = QuantityData.RegEx.Match(s); if (M.Success && CommonTypes.TryParse(M.Groups["Magnitude"].Value, out x, out NrDecimals)) { this.RemoveWarning(); return(new QuantityData(this, x, NrDecimals, M.Groups["Unit"].Value)); } if (!this.hasWarning.HasValue || !this.hasWarning.Value) { this.node?.LogWarningAsync("Format", "Unrecognized string format: " + s); this.hasWarning = true; } return(new StringData(this, s)); } catch (Exception) { return(new BinaryData(this, Content.Data)); } }
/// <summary> /// Serializes the Contract, in normalized form. /// </summary> /// <param name="Xml">XML Output</param> /// <param name="IncludeNamespace">If namespace attribute should be included.</param> /// <param name="IncludeIdAttribute">If id attribute should be included.</param> /// <param name="IncludeClientSignatures">If client signatures should be included.</param> /// <param name="IncludeStatus">If the status element should be included.</param> /// <param name="IncludeServerSignature">If the server signature should be included.</param> public void Serialize(StringBuilder Xml, bool IncludeNamespace, bool IncludeIdAttribute, bool IncludeClientSignatures, bool IncludeStatus, bool IncludeServerSignature) { Xml.Append("<contract archiveOpt=\""); Xml.Append(this.archiveOpt.ToString()); Xml.Append("\" archiveReq=\""); Xml.Append(this.archiveReq.ToString()); Xml.Append("\" canActAsTemplate=\""); Xml.Append(CommonTypes.Encode(this.canActAsTemplate)); Xml.Append("\" duration=\""); Xml.Append(this.duration.ToString()); Xml.Append('"'); if (IncludeIdAttribute) { Xml.Append(" id=\""); Xml.Append(XML.Encode(this.contractId)); Xml.Append('"'); } if (this.signAfter.HasValue) { Xml.Append(" signAfter=\""); Xml.Append(XML.Encode(this.signAfter.Value)); Xml.Append('"'); } if (this.signBefore.HasValue) { Xml.Append(" signBefore=\""); Xml.Append(XML.Encode(this.signBefore.Value)); Xml.Append('"'); } Xml.Append(" visibility=\""); Xml.Append(this.visibility.ToString()); Xml.Append('"'); if (IncludeNamespace) { Xml.Append(" xmlns=\""); Xml.Append(ContractsClient.NamespaceSmartContracts); Xml.Append('"'); } Xml.Append('>'); NormalizeXml(this.forMachines, Xml, ContractsClient.NamespaceSmartContracts); if (this.roles != null) { foreach (Role Role in this.roles) { Xml.Append("<role maxCount=\""); Xml.Append(Role.MaxCount.ToString()); Xml.Append("\" minCount=\""); Xml.Append(Role.MinCount.ToString()); Xml.Append("\" name=\""); Xml.Append(XML.Encode(Role.Name)); Xml.Append("\">"); foreach (HumanReadableText Description in Role.Descriptions) { Description.Serialize(Xml, "description", false); } Xml.Append("</role>"); } } Xml.Append("<parts>"); switch (this.partsMode) { case ContractParts.Open: Xml.Append("<open/>"); break; case ContractParts.TemplateOnly: Xml.Append("<templateOnly/>"); break; case ContractParts.ExplicitlyDefined: if (this.parts != null) { foreach (Part Part in this.parts) { Xml.Append("<part legalId=\""); Xml.Append(XML.Encode(Part.LegalId)); Xml.Append("\" role=\""); Xml.Append(XML.Encode(Part.Role)); Xml.Append("\"/>"); } } break; } Xml.Append("</parts>"); if (this.parameters != null && this.parameters.Length > 0) { Xml.Append("<parameters>"); foreach (Parameter Parameter in this.parameters) { Parameter.Serialize(Xml); } Xml.Append("</parameters>"); } if (this.forHumans != null && this.forHumans.Length > 0) { foreach (HumanReadableText Text in this.forHumans) { Text.Serialize(Xml); } } if (IncludeClientSignatures && this.clientSignatures != null) { foreach (Signature Signature in this.clientSignatures) { Signature.Serialize(Xml); } } if (IncludeStatus) { Xml.Append("<status created=\""); Xml.Append(XML.Encode(this.created)); if (this.from != DateTime.MinValue) { Xml.Append("\" from=\""); Xml.Append(XML.Encode(this.from)); } Xml.Append("\" provider=\""); Xml.Append(XML.Encode(this.provider)); if (this.contentSchemaDigest != null && this.contentSchemaDigest.Length > 0) { Xml.Append("\" schemaDigest=\""); Xml.Append(Convert.ToBase64String(this.contentSchemaDigest)); Xml.Append("\" schemaHashFunction=\""); Xml.Append(this.contentSchemaHashFunction.ToString()); } Xml.Append("\" state=\""); Xml.Append(this.state.ToString()); if (!string.IsNullOrEmpty(this.templateId)) { Xml.Append("\" templateId=\""); Xml.Append(XML.Encode(this.templateId)); } if (this.to != DateTime.MaxValue) { Xml.Append("\" to=\""); Xml.Append(XML.Encode(this.to)); } if (this.updated != DateTime.MinValue) { Xml.Append("\" updated=\""); Xml.Append(XML.Encode(this.updated)); } Xml.Append("\"/>"); } if (IncludeServerSignature) { this.serverSignature?.Serialize(Xml); } Xml.Append("</contract>"); }
/// <summary> /// Parses a contract from is XML representation. /// </summary> /// <param name="Xml">XML representation</param> /// <param name="HasStatus">If a status element was found.</param> /// <returns>Parsed contract, or null if it contains errors.</returns> public static Contract Parse(XmlElement Xml, out bool HasStatus) { Contract Result = new Contract(); bool HasVisibility = false; HasStatus = false; foreach (XmlAttribute Attr in Xml.Attributes) { switch (Attr.Name) { case "id": Result.contractId = Attr.Value; break; case "visibility": if (Enum.TryParse <ContractVisibility>(Attr.Value, out ContractVisibility Visibility)) { Result.visibility = Visibility; HasVisibility = true; } else { return(null); } break; case "duration": if (Duration.TryParse(Attr.Value, out Duration D)) { Result.duration = D; } else { return(null); } break; case "archiveReq": if (Duration.TryParse(Attr.Value, out D)) { Result.archiveReq = D; } else { return(null); } break; case "archiveOpt": if (Duration.TryParse(Attr.Value, out D)) { Result.archiveOpt = D; } else { return(null); } break; case "signAfter": if (DateTime.TryParse(Attr.Value, out DateTime TP)) { Result.signAfter = TP; } else { return(null); } break; case "signBefore": if (DateTime.TryParse(Attr.Value, out TP)) { Result.signBefore = TP; } else { return(null); } break; case "canActAsTemplate": if (CommonTypes.TryParse(Attr.Value, out bool b)) { Result.canActAsTemplate = b; } else { return(null); } break; case "xmlns": break; default: if (Attr.Prefix == "xmlns") { break; } else { return(null); } } } if (!HasVisibility || Result.duration is null || Result.archiveReq is null || Result.archiveOpt is null || Result.signBefore <= Result.signAfter) { return(null); } List <HumanReadableText> ForHumans = new List <HumanReadableText>(); List <Role> Roles = new List <Role>(); List <Parameter> Parameters = new List <Parameter>(); List <ClientSignature> Signatures = new List <ClientSignature>(); XmlElement Content = null; HumanReadableText Text; bool First = true; bool PartsDefined = false; foreach (XmlNode N in Xml.ChildNodes) { if (!(N is XmlElement E)) { continue; } if (First) { Content = E; First = false; continue; } switch (E.LocalName) { case "role": List <HumanReadableText> Descriptions = new List <HumanReadableText>(); Role Role = new Role() { MinCount = -1, MaxCount = -1 }; foreach (XmlAttribute Attr in E.Attributes) { switch (Attr.Name) { case "name": Role.Name = Attr.Value; if (string.IsNullOrEmpty(Role.Name)) { return(null); } break; case "minCount": if (int.TryParse(Attr.Value, out int i) && i >= 0) { Role.MinCount = i; } else { return(null); } break; case "maxCount": if (int.TryParse(Attr.Value, out i) && i >= 0) { Role.MaxCount = i; } else { return(null); } break; case "xmlns": break; default: if (Attr.Prefix == "xmlns") { break; } else { return(null); } } } if (string.IsNullOrEmpty(Role.Name) || Role.MinCount < 0 || Role.MaxCount < 0) { return(null); } foreach (XmlNode N2 in E.ChildNodes) { if (N2 is XmlElement E2) { if (E2.LocalName == "description") { Text = HumanReadableText.Parse(E2); if (Text is null || !Text.IsWellDefined) { return(null); } Descriptions.Add(Text); } else { return(null); } } } if (Descriptions.Count == 0) { return(null); } Role.Descriptions = Descriptions.ToArray(); Roles.Add(Role); break; case "parts": List <Part> Parts = null; ContractParts?Mode = null; foreach (XmlNode N2 in E.ChildNodes) { if (N2 is XmlElement E2) { switch (E2.LocalName) { case "open": if (Mode.HasValue) { return(null); } Mode = ContractParts.Open; break; case "templateOnly": if (Mode.HasValue) { return(null); } Mode = ContractParts.TemplateOnly; break; case "part": if (Mode.HasValue) { if (Mode.Value != ContractParts.ExplicitlyDefined) { return(null); } } else { Mode = ContractParts.ExplicitlyDefined; } string LegalId = null; string RoleRef = null; foreach (XmlAttribute Attr in E2.Attributes) { switch (Attr.Name) { case "legalId": LegalId = Attr.Value; break; case "role": RoleRef = Attr.Value; break; case "xmlns": break; default: if (Attr.Prefix == "xmlns") { break; } else { return(null); } } } if (LegalId is null || RoleRef is null || string.IsNullOrEmpty(LegalId) || string.IsNullOrEmpty(RoleRef)) { return(null); } bool RoleFound = false; foreach (Role Role2 in Roles) { if (Role2.Name == RoleRef) { RoleFound = true; break; } } if (!RoleFound) { return(null); } if (Parts is null) { Parts = new List <Part>(); } Parts.Add(new Part() { LegalId = LegalId, Role = RoleRef }); break; default: return(null); } } } if (!Mode.HasValue) { return(null); } Result.partsMode = Mode.Value; Result.parts = Parts?.ToArray(); PartsDefined = true; break; case "parameters": foreach (XmlNode N2 in E.ChildNodes) { if (N2 is XmlElement E2) { string Name = XML.Attribute(E2, "name"); if (string.IsNullOrEmpty(Name)) { return(null); } Descriptions = new List <HumanReadableText>(); foreach (XmlNode N3 in E2.ChildNodes) { if (N3 is XmlElement E3) { if (E3.LocalName == "description") { Text = HumanReadableText.Parse(E3); if (Text is null || !Text.IsWellDefined) { return(null); } Descriptions.Add(Text); } else { return(null); } } } switch (E2.LocalName) { case "stringParameter": Parameters.Add(new StringParameter() { Name = Name, Value = XML.Attribute(E2, "value"), Descriptions = Descriptions.ToArray() }); break; case "numericalParameter": Parameters.Add(new NumericalParameter() { Name = Name, Value = XML.Attribute(E2, "value", 0.0), Descriptions = Descriptions.ToArray() }); break; default: return(null); } } } if (Parameters.Count == 0) { return(null); } break; case "humanReadableText": Text = HumanReadableText.Parse(E); if (Text is null || !Text.IsWellDefined) { return(null); } ForHumans.Add(Text); break; case "signature": ClientSignature Signature = new ClientSignature(); foreach (XmlAttribute Attr in E.Attributes) { switch (Attr.Name) { case "legalId": Signature.LegalId = Attr.Value; break; case "bareJid": Signature.BareJid = Attr.Value; break; case "role": Signature.Role = Attr.Value; break; case "timestamp": if (XML.TryParse(Attr.Value, out DateTime TP)) { Signature.Timestamp = TP; } else { return(null); } break; case "transferable": if (CommonTypes.TryParse(Attr.Value, out bool b)) { Signature.Transferable = b; } else { return(null); } break; case "s1": Signature.S1 = Convert.FromBase64String(Attr.Value); break; case "s2": Signature.S2 = Convert.FromBase64String(Attr.Value); break; case "xmlns": break; default: if (Attr.Prefix == "xmlns") { break; } else { return(null); } } } if (string.IsNullOrEmpty(Signature.LegalId) || string.IsNullOrEmpty(Signature.BareJid) || string.IsNullOrEmpty(Signature.Role) || Signature.Timestamp == DateTime.MinValue || Signature.S1 is null) { return(null); } Signatures.Add(Signature); break; case "status": HasStatus = true; foreach (XmlAttribute Attr in E.Attributes) { switch (Attr.Name) { case "provider": Result.provider = Attr.Value; break; case "state": if (Enum.TryParse <ContractState>(Attr.Value, out ContractState ContractState)) { Result.state = ContractState; } break; case "created": if (XML.TryParse(Attr.Value, out DateTime TP)) { Result.created = TP; } break; case "updated": if (XML.TryParse(Attr.Value, out TP)) { Result.updated = TP; } break; case "from": if (XML.TryParse(Attr.Value, out TP)) { Result.from = TP; } break; case "to": if (XML.TryParse(Attr.Value, out TP)) { Result.to = TP; } break; case "templateId": Result.templateId = Attr.Value; break; case "schemaDigest": Result.contentSchemaDigest = Convert.FromBase64String(Attr.Value); break; case "schemaHashFunction": if (Enum.TryParse <HashFunction>(Attr.Value, out HashFunction H)) { Result.contentSchemaHashFunction = H; } else { return(null); } break; case "xmlns": break; default: if (Attr.Prefix == "xmlns") { break; } else { return(null); } } } break; case "serverSignature": ServerSignature ServerSignature = new ServerSignature(); foreach (XmlAttribute Attr in E.Attributes) { switch (Attr.Name) { case "timestamp": if (XML.TryParse(Attr.Value, out DateTime TP)) { ServerSignature.Timestamp = TP; } else { return(null); } break; case "s1": ServerSignature.S1 = Convert.FromBase64String(Attr.Value); break; case "s2": ServerSignature.S2 = Convert.FromBase64String(Attr.Value); break; case "xmlns": break; default: if (Attr.Prefix == "xmlns") { break; } else { return(null); } } } if (ServerSignature.Timestamp == DateTime.MinValue || ServerSignature.S1 is null) { return(null); } Result.serverSignature = ServerSignature; break; default: return(null); } } if (Content is null || ForHumans.Count == 0 || !PartsDefined) { return(null); } Result.roles = Roles.ToArray(); Result.parameters = Parameters.ToArray(); Result.forMachines = Content; Result.forMachinesLocalName = Content.LocalName; Result.forMachinesNamespace = Content.NamespaceURI; Result.forHumans = ForHumans.ToArray(); Result.clientSignatures = Signatures.ToArray(); return(Result); }
/// <summary> /// Executes the ranged GET method on the resource. /// </summary> /// <param name="Request">HTTP Request</param> /// <param name="Response">HTTP Response</param> /// <param name="FirstInterval">First byte range interval.</param> /// <exception cref="HttpException">If an error occurred when processing the method.</exception> public void GET(HttpRequest Request, HttpResponse Response, ByteRangeInterval FirstInterval) { string FullPath = this.GetFullPath(Request); if (!File.Exists(FullPath)) { throw new NotFoundException(); } HttpRequestHeader Header = Request.Header; DateTime LastModified = File.GetLastWriteTime(FullPath).ToUniversalTime(); DateTimeOffset? Limit; CacheRec Rec; if (Header.IfRange != null && (Limit = Header.IfRange.Timestamp).HasValue && !LessOrEqual(LastModified, Limit.Value.ToUniversalTime())) { Response.StatusCode = 200; this.GET(Request, Response); // No ranged request. return; } Rec = this.CheckCacheHeaders(FullPath, LastModified, Request); string ContentType = InternetContent.GetContentType(Path.GetExtension(FullPath)); Stream f = CheckAcceptable(Request, Response, ref ContentType, out bool Dynamic, FullPath, Request.Header.Resource); Rec.IsDynamic = Dynamic; ReadProgress Progress = new ReadProgress() { Response = Response, f = f ?? File.OpenRead(FullPath) }; ByteRangeInterval Interval = FirstInterval; Progress.TotalLength = Progress.f.Length; long i = 0; long j; long First; if (FirstInterval.First.HasValue) { First = FirstInterval.First.Value; } else { First = Progress.TotalLength - FirstInterval.Last.Value; } Progress.f.Position = First; Progress.BytesLeft = Interval.GetIntervalLength(Progress.TotalLength); Progress.Next = Interval.Next; while (Interval != null) { j = Interval.GetIntervalLength(Progress.TotalLength); if (j > i) { i = j; } Interval = Interval.Next; } Progress.BlockSize = (int)Math.Min(BufferSize, i); Progress.Buffer = new byte[Progress.BlockSize]; if (FirstInterval.Next == null) { Progress.Boundary = null; Progress.ContentType = null; Response.ContentType = ContentType; Response.ContentLength = FirstInterval.GetIntervalLength(Progress.f.Length); Response.SetHeader("Content-Range", ContentByteRangeInterval.ContentRangeToString(First, First + Progress.BytesLeft - 1, Progress.TotalLength)); } else { Progress.Boundary = Guid.NewGuid().ToString().Replace("-", string.Empty); Progress.ContentType = ContentType; Response.ContentType = "multipart/byteranges; boundary=" + Progress.Boundary; // chunked transfer encoding will be used } if (!Rec.IsDynamic) { Response.SetHeader("ETag", Rec.ETag); Response.SetHeader("Last-Modified", CommonTypes.EncodeRfc822(LastModified)); } if (Response.OnlyHeader || Progress.BytesLeft == 0) { Response.SendResponse(); Progress.Dispose(); } else { if (FirstInterval.Next != null) { Response.WriteLine(); Response.WriteLine("--" + Progress.Boundary); Response.WriteLine("Content-Type: " + Progress.ContentType); Response.WriteLine("Content-Range: " + ContentByteRangeInterval.ContentRangeToString(First, First + Progress.BytesLeft - 1, Progress.TotalLength)); Response.WriteLine(); } Task T = Progress.BeginRead(); } }
private void RequestResponse(object Sender, HttpxResponseEventArgs e) { ReadoutState State2 = (ReadoutState)e.State; State2.Response.StatusCode = e.StatusCode; State2.Response.StatusMessage = e.StatusMessage; if (e.HttpResponse != null) { foreach (KeyValuePair <string, string> Field in e.HttpResponse.GetHeaders()) { switch (Field.Key.ToLower()) { case "cookie": case "set-cookie": // Do not forward cookies. break; case "content-type": State2.ContentType = Field.Value; State2.Response.SetHeader(Field.Key, Field.Value); break; case "etag": State2.ETag = Field.Value; State2.Response.SetHeader(Field.Key, Field.Value); break; case "last-modified": DateTimeOffset TP; if (CommonTypes.TryParseRfc822(Field.Value, out TP)) { State2.LastModified = TP; } State2.Response.SetHeader(Field.Key, Field.Value); break; case "expires": if (CommonTypes.TryParseRfc822(Field.Value, out TP)) { State2.Expires = TP; } State2.Response.SetHeader(Field.Key, Field.Value); break; case "cache-control": State2.CacheControl = Field.Value; State2.Response.SetHeader(Field.Key, Field.Value); break; case "pragma": State2.Pragma = Field.Value; State2.Response.SetHeader(Field.Key, Field.Value); break; default: State2.Response.SetHeader(Field.Key, Field.Value); break; } } } if (!e.HasData) { State2.Response.SendResponse(); } else { if (e.StatusCode == 200 && State2.Cacheable && State2.CanCache && this.httpxCache.CanCache(State2.BareJid, State2.LocalResource, State2.ContentType)) { State2.TempOutput = new TemporaryFile(); } if (e.Data != null) { this.BinaryDataReceived(State2, true, e.Data); } } }
/// <summary> /// Parses a personal event from its XML representation /// </summary> /// <param name="E">XML representation of personal event.</param> /// <returns>Personal event object.</returns> public override IPersonalEvent Parse(XmlElement E) { UserLocation Result = new UserLocation(); foreach (XmlNode N in E.ChildNodes) { if (N is XmlElement E2) { switch (E2.LocalName) { case "accuracy": if (CommonTypes.TryParse(E2.InnerText, out decimal d)) { Result.accuracy = d; } break; case "alt": if (CommonTypes.TryParse(E2.InnerText, out d)) { Result.alt = d; } break; case "altaccuracy": if (CommonTypes.TryParse(E2.InnerText, out d)) { Result.altaccuracy = d; } break; case "area": Result.area = E2.InnerText; break; case "bearing": if (CommonTypes.TryParse(E2.InnerText, out d)) { Result.bearing = d; } break; case "building": Result.building = E2.InnerText; break; case "country": Result.country = E2.InnerText; break; case "countrycode": Result.countrycode = E2.InnerText; break; case "datum": Result.datum = E2.InnerText; break; case "description": Result.description = E2.InnerText; break; case "error": if (CommonTypes.TryParse(E2.InnerText, out d)) { Result.accuracy = d; } break; case "floor": Result.floor = E2.InnerText; break; case "lat": if (CommonTypes.TryParse(E2.InnerText, out d)) { Result.lat = d; } break; case "locality": Result.locality = E2.InnerText; break; case "lon": if (CommonTypes.TryParse(E2.InnerText, out d)) { Result.lon = d; } break; case "postalcode": Result.postalcode = E2.InnerText; break; case "region": Result.region = E2.InnerText; break; case "room": Result.room = E2.InnerText; break; case "speed": if (CommonTypes.TryParse(E2.InnerText, out d)) { Result.speed = d; } break; case "street": Result.street = E2.InnerText; break; case "text": Result.text = E2.InnerText; break; case "timestamp": if (XML.TryParse(E2.InnerText, out DateTime TP)) { Result.timestamp = TP; } break; case "tzo": Result.tzo = E2.InnerText; break; case "uri": try { Result.uri = new Uri(E2.InnerText); } catch (Exception) { // Ignore. } break; } } } return(Result); }
/// <summary> /// Exports gateway data /// </summary> /// <param name="Output">Export Output</param> /// <param name="Database">If the contents of the database is to be exported.</param> /// <param name="WebContent">If web content is to be exported.</param> /// <param name="Folders">Root subfolders to export.</param> public static async Task DoExport(IExportFormat Output, bool Database, bool WebContent, string[] Folders) { try { List <KeyValuePair <string, object> > Tags = new List <KeyValuePair <string, object> >() { new KeyValuePair <string, object>("Database", Database) }; foreach (string Folder in Folders) { Tags.Add(new KeyValuePair <string, object>(Folder, true)); } Log.Informational("Starting export.", Output.FileName, Tags.ToArray()); await Output.Start(); if (Database) { StringBuilder Temp = new StringBuilder(); using (XmlWriter w = XmlWriter.Create(Temp, XML.WriterSettings(false, true))) { await Persistence.Database.Analyze(w, Path.Combine(Gateway.AppDataFolder, "Transforms", "DbStatXmlToHtml.xslt"), Path.Combine(Gateway.RootFolder, "Data"), false, true); } await Persistence.Database.Export(Output); } if (WebContent || Folders.Length > 0) { await Output.StartFiles(); try { string[] FileNames; string Folder2; if (WebContent) { await ExportFile(Path.Combine(Gateway.AppDataFolder, "Gateway.config"), Output); FileNames = Directory.GetFiles(Gateway.RootFolder, "*.*", SearchOption.TopDirectoryOnly); foreach (string FileName in FileNames) { await ExportFile(FileName, Output); } Export.FolderCategory[] ExportFolders = Export.GetRegisteredFolders(); foreach (string Folder in Directory.GetDirectories(Gateway.RootFolder, "*.*", SearchOption.TopDirectoryOnly)) { bool IsWebContent = true; foreach (Export.FolderCategory FolderCategory in ExportFolders) { foreach (string Folder3 in FolderCategory.Folders) { if (string.Compare(Folder3, Folder, true) == 0) { IsWebContent = false; break; } } if (!IsWebContent) { break; } } if (IsWebContent) { FileNames = Directory.GetFiles(Folder, "*.*", SearchOption.AllDirectories); foreach (string FileName in FileNames) { await ExportFile(FileName, Output); } } } } foreach (string Folder in Folders) { if (Directory.Exists(Folder2 = Path.Combine(Gateway.RootFolder, Folder))) { FileNames = Directory.GetFiles(Folder2, "*.*", SearchOption.AllDirectories); foreach (string FileName in FileNames) { await ExportFile(FileName, Output); } } } } finally { await Output.EndFiles(); } } Log.Informational("Export successfully completed.", Output.FileName); } catch (Exception ex) { Log.Critical(ex); string[] Tabs = ClientEvents.GetTabIDsForLocation("/Settings/Backup.md"); ClientEvents.PushEvent(Tabs, "BackupFailed", "{\"fileName\":\"" + CommonTypes.JsonStringEncode(Output.FileName) + "\", \"message\": \"" + CommonTypes.JsonStringEncode(ex.Message) + "\"}", true, "User"); } finally { try { await Output.End(); Output.Dispose(); } catch (Exception ex) { Log.Critical(ex); } lock (synchObject) { exporting = false; } } }
/// <summary> /// Decodes an object. /// </summary> /// <param name="ContentType">Internet Content Type.</param> /// <param name="Data">Encoded object.</param> /// <param name="Encoding">Any encoding specified. Can be null if no encoding specified.</param> /// <param name="Fields">Any content-type related fields and their corresponding values.</param> /// <param name="BaseUri">Base URI, if any. If not available, value is null.</param> /// <returns>Decoded object.</returns> /// <exception cref="ArgumentException">If the object cannot be decoded.</exception> public object Decode(string ContentType, byte[] Data, Encoding Encoding, KeyValuePair <string, string>[] Fields, Uri BaseUri) { string s = CommonTypes.GetString(Data, Encoding); return(CSV.Parse(s)); }
/// <summary> /// Procedure to execute a Find query. Although the full query results are retrieved from the DB and stored /// internally in an object, data will be returned in 'pages' of data, each page holding a defined number /// of records. /// </summary> /// <param name="ACriteriaData">HashTable containing non-empty Find parameters.</param> public void PerformSearch(DataTable ACriteriaData) { string PaymentNumberSQLPart; FPagedDataSetObject = new TPagedDataSet(null); DataRow CriteriaRow = PrepareDataRow(ACriteriaData); Int32 ledgerNumber = (Int32)CriteriaRow["LedgerNumber"]; if (FSearchTransactions) { if (CommonTypes.ParseDBType(DBAccess.GDBAccessObj.DBType) == TDBType.SQLite) { // Fix for SQLite: it does not support the 'to_char' Function PaymentNumberSQLPart = "PUB_a_ap_payment.a_payment_number_i as InvNum, "; } else { // whereas PostgreSQL does! PaymentNumberSQLPart = "to_char(PUB_a_ap_payment.a_payment_number_i, '99999') as InvNum, "; } Int64 PartnerKey = Convert.ToInt64(CriteriaRow["PartnerKey"]); String SqlQuery = "SELECT DISTINCT " + "0 as ApDocumentId, " + "PUB_a_ap_payment.a_payment_number_i as ApNum, " + PaymentNumberSQLPart + "true as CreditNote, " + "'Payment' as Type, " + "PUB_a_ap_payment.a_currency_code_c as Currency, " + "PUB_a_ap_payment.a_amount_n as Amount, " + "0 AS OutstandingAmount, " + "'' as Status, " + "0 as DiscountPercent, " + "0 as DiscountDays, " + "PUB_a_ap_payment.s_date_created_d as Date " + " FROM PUB_a_ap_payment LEFT JOIN PUB_a_ap_document_payment on PUB_a_ap_payment.a_payment_number_i = PUB_a_ap_document_payment.a_payment_number_i" + " LEFT JOIN PUB_a_ap_document on PUB_a_ap_document_payment.a_ap_document_id_i = PUB_a_ap_document.a_ap_document_id_i\n" + " WHERE PUB_a_ap_document_payment.a_ledger_number_i=" + ledgerNumber + " AND p_partner_key_n=" + PartnerKey + "\n UNION\n" + " SELECT " + "a_ap_document_id_i as ApDocumentId, " + "a_ap_number_i as ApNum, " + "a_document_code_c as InvNum, " + "a_credit_note_flag_l as CreditNote, " + "'Invoice' as Type, " + "a_currency_code_c AS Currency, " + "a_total_amount_n as Amount, " + "a_total_amount_n AS OutstandingAmount, " + "a_document_status_c as Status, " + "a_discount_percentage_n as DiscountPercent, " + "a_discount_days_i as DiscountDays, " + "a_date_issued_d as Date " + "FROM PUB_a_ap_document " + "WHERE a_ledger_number_i=" + ledgerNumber + " " + "AND p_partner_key_n=" + PartnerKey + " " + "ORDER BY Date DESC"; FPagedDataSetObject.FindParameters = new TPagedDataSet.TAsyncFindParameters(SqlQuery); FPagedDataSetObject.FindParameters.FSearchName = "ATransactions"; } else { if (!FSearchSupplierOrInvoice) { String SqlQuery = "SELECT " + "PUB_a_ap_document.a_ap_number_i AS ApNumber, " + "PUB_a_ap_document.a_document_code_c AS DocumentCode, " + "PUB_p_partner.p_partner_short_name_c AS PartnerShortName, " + "PUB_a_ap_document.a_currency_code_c AS CurrencyCode, " + "PUB_a_ap_document.a_total_amount_n AS TotalAmount, " + "PUB_a_ap_document.a_total_amount_n AS OutstandingAmount, " + "PUB_a_ap_document.a_document_status_c AS DocumentStatus, " + "PUB_a_ap_document.a_date_issued_d AS DateIssued, " + "PUB_a_ap_document.a_date_issued_d AS DateDue, " + "PUB_a_ap_document.a_date_issued_d AS DateDiscountUntil, " + "PUB_a_ap_document.a_credit_terms_i AS CreditTerms, " + "PUB_a_ap_document.a_discount_percentage_n AS DiscountPercentage, " + "PUB_a_ap_document.a_discount_days_i AS DiscountDays, " + "'none' AS DiscountMsg, " + "false AS Selected, " + "PUB_a_ap_document.a_credit_note_flag_l AS CreditNoteFlag, " + "PUB_a_ap_document.a_ap_document_id_i AS ApDocumentId " + "FROM PUB_a_ap_document, PUB_a_ap_supplier, PUB_p_partner " + "WHERE PUB_a_ap_document.a_ledger_number_i=" + ledgerNumber + " " + "AND PUB_a_ap_document.a_document_status_c <> 'CANCELLED' " + "AND PUB_a_ap_document.a_document_status_c <> 'PAID' " + "AND PUB_a_ap_supplier.p_partner_key_n = PUB_p_partner.p_partner_key_n " + "AND PUB_a_ap_document.p_partner_key_n = PUB_p_partner.p_partner_key_n " + "ORDER BY PUB_a_ap_document.a_ap_number_i DESC"; FPagedDataSetObject.FindParameters = new TPagedDataSet.TAsyncFindParameters(SqlQuery); FPagedDataSetObject.FindParameters.FSearchName = "AInvoices"; } else { String SqlQuery = "SELECT " + "PUB_a_ap_supplier.p_partner_key_n AS PartnerKey, " + "PUB_p_partner.p_partner_short_name_c AS PartnerShortName, " + "PUB_a_ap_supplier.a_currency_code_c AS CurrencyCode, " + "PUB_p_partner.p_status_code_c AS StatusCode " + "FROM PUB_a_ap_supplier, PUB_p_partner " + "WHERE "; if (((String)CriteriaRow["SupplierId"]).Length > 0) // If the search box is empty, I'll not add this at all... { SqlQuery += String.Format("p_partner_short_name_c LIKE '{0}' AND ", (String)CriteriaRow["SupplierId"] + "%"); } SqlQuery += "PUB_a_ap_supplier.p_partner_key_n = PUB_p_partner.p_partner_key_n " + "ORDER BY PartnerShortName"; FPagedDataSetObject.FindParameters = new TPagedDataSet.TAsyncFindParameters(SqlQuery); FPagedDataSetObject.FindParameters.FSearchName = "ASuppliers"; } } string session = TSession.GetSessionID(); // // Start the Find Thread // try { ThreadStart myThreadStart = delegate { FPagedDataSetObject.ExecuteQuery(session, "AP TFindUIConnector"); }; FFindThread = new Thread(myThreadStart); FFindThread.Name = "APFind" + Guid.NewGuid().ToString(); FFindThread.Start(); } catch (Exception) { throw; } }
static int Main(string[] args) { try { Encoding Encoding = Encoding.UTF8; string ProgramDataFolder = null; string OutputFileName = null; string XsltPath = null; string s; int BlockSize = 8192; int BlobBlockSize = 8192; int i = 0; int c = args.Length; bool Help = false; bool Encryption = false; bool Export = false; while (i < c) { s = args[i++].ToLower(); switch (s) { case "-d": if (i >= c) { throw new Exception("Missing program data folder."); } if (string.IsNullOrEmpty(ProgramDataFolder)) { ProgramDataFolder = args[i++]; } else { throw new Exception("Only one program data folder allowed."); } break; case "-o": if (i >= c) { throw new Exception("Missing output file name."); } if (string.IsNullOrEmpty(OutputFileName)) { OutputFileName = args[i++]; } else { throw new Exception("Only one output file name allowed."); } break; case "-bs": if (i >= c) { throw new Exception("Block size missing."); } if (!int.TryParse(args[i++], out BlockSize)) { throw new Exception("Invalid block size"); } break; case "-bbs": if (i >= c) { throw new Exception("Blob Block size missing."); } if (!int.TryParse(args[i++], out BlobBlockSize)) { throw new Exception("Invalid blob block size"); } break; case "-enc": if (i >= c) { throw new Exception("Text encoding missing."); } Encoding = Encoding.GetEncoding(args[i++]); break; case "-t": if (i >= c) { throw new Exception("XSLT transform missing."); } XsltPath = args[i++]; break; case "-e": Encryption = true; break; case "-x": Export = true; break; case "-?": Help = true; break; default: throw new Exception("Unrecognized switch: " + s); } } if (Help || c == 0) { Console.Out.WriteLine("Analyzes an object database created by the Waher.Persistence.Files or"); Console.Out.WriteLine("<see Waher.Persistence.FilesLW libraries, such as the IoT Gateway database."); Console.Out.WriteLine(); Console.Out.WriteLine("Command line switches:"); Console.Out.WriteLine(); Console.Out.WriteLine("-d APP_DATA_FOLDER Points to the application data folder."); Console.Out.WriteLine("-o OUTPUT_FILE File name of report file."); Console.Out.WriteLine("-e If encryption is used by the database."); Console.Out.WriteLine("-bs BLOCK_SIZE Block size, in bytes. Default=8192."); Console.Out.WriteLine("-bbs BLOB_BLOCK_SIZE BLOB block size, in bytes. Default=8192."); Console.Out.WriteLine("-enc ENCODING Text encoding. Default=UTF-8"); Console.Out.WriteLine("-t XSLT transform to use."); Console.Out.WriteLine("-x Export contents of each collection."); Console.Out.WriteLine("-? Help."); return(0); } if (string.IsNullOrEmpty(ProgramDataFolder)) { throw new Exception("No program data folder set"); } if (!Directory.Exists(ProgramDataFolder)) { throw new Exception("Program data folder does not exist."); } if (string.IsNullOrEmpty(OutputFileName)) { throw new Exception("No output filename specified."); } Types.Initialize( typeof(Database).Assembly, typeof(FilesProvider).Assembly); using (FilesProvider FilesProvider = new FilesProvider(ProgramDataFolder, "Default", BlockSize, 10000, BlobBlockSize, Encoding, 10000, Encryption, false)) { Database.Register(FilesProvider); using (StreamWriter f = File.CreateText(OutputFileName)) { XmlWriterSettings Settings = new XmlWriterSettings() { Encoding = Encoding, Indent = true, IndentChars = "\t", NewLineChars = Console.Out.NewLine, OmitXmlDeclaration = false, WriteEndDocumentOnClose = true }; using (XmlWriter w = XmlWriter.Create(f, Settings)) { w.WriteStartDocument(); if (string.IsNullOrEmpty(XsltPath)) { i = ProgramDataFolder.LastIndexOf(Path.DirectorySeparatorChar); if (i > 0) { s = Path.Combine(ProgramDataFolder.Substring(0, i), "Transforms", "DbStatXmlToHtml.xslt"); if (File.Exists(s)) { XsltPath = s; } } } if (!string.IsNullOrEmpty(XsltPath)) { w.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"" + XML.Encode(XsltPath) + "\""); } w.WriteStartElement("DatabaseStatistics", "http://waher.se/Schema/Persistence/Statistics.xsd"); foreach (ObjectBTreeFile File in FilesProvider.Files) { w.WriteStartElement("File"); w.WriteAttributeString("id", File.Id.ToString()); w.WriteAttributeString("collectionName", File.CollectionName); w.WriteAttributeString("fileName", Path.GetRelativePath(ProgramDataFolder, File.FileName)); w.WriteAttributeString("blockSize", File.BlockSize.ToString()); w.WriteAttributeString("blobFileName", Path.GetRelativePath(ProgramDataFolder, File.BlobFileName)); w.WriteAttributeString("blobBlockSize", File.BlobBlockSize.ToString()); w.WriteAttributeString("count", File.Count.ToString()); w.WriteAttributeString("encoding", File.Encoding.WebName); w.WriteAttributeString("encrypted", CommonTypes.Encode(File.Encrypted)); w.WriteAttributeString("inlineObjectSizeLimit", File.InlineObjectSizeLimit.ToString()); w.WriteAttributeString("isReadOnly", CommonTypes.Encode(File.IsReadOnly)); w.WriteAttributeString("timeoutMs", File.TimeoutMilliseconds.ToString()); FileStatistics Stat = File.ComputeStatistics().Result; WriteStat(w, File, Stat); foreach (IndexBTreeFile Index in File.Indices) { w.WriteStartElement("Index"); w.WriteAttributeString("id", Index.IndexFile.Id.ToString()); w.WriteAttributeString("fileName", Path.GetRelativePath(ProgramDataFolder, Index.IndexFile.FileName)); w.WriteAttributeString("blockSize", Index.IndexFile.BlockSize.ToString()); w.WriteAttributeString("blobFileName", Index.IndexFile.BlobFileName); w.WriteAttributeString("blobBlockSize", Index.IndexFile.BlobBlockSize.ToString()); w.WriteAttributeString("count", Index.IndexFile.Count.ToString()); w.WriteAttributeString("encoding", Index.IndexFile.Encoding.WebName); w.WriteAttributeString("encrypted", CommonTypes.Encode(Index.IndexFile.Encrypted)); w.WriteAttributeString("inlineObjectSizeLimit", Index.IndexFile.InlineObjectSizeLimit.ToString()); w.WriteAttributeString("isReadOnly", CommonTypes.Encode(Index.IndexFile.IsReadOnly)); w.WriteAttributeString("timeoutMs", Index.IndexFile.TimeoutMilliseconds.ToString()); foreach (string Field in Index.FieldNames) { w.WriteElementString("Field", Field); } Stat = Index.IndexFile.ComputeStatistics().Result; WriteStat(w, Index.IndexFile, Stat); w.WriteEndElement(); } if (Export) { File.ExportGraphXML(w, true).Wait(); } w.WriteEndElement(); } w.WriteEndElement(); w.WriteEndDocument(); } } } return(0); } catch (Exception ex) { Console.Out.WriteLine(ex.Message); return(-1); } }
/// <summary> /// Sets parameters from a data form in an object. /// </summary> /// <param name="e">IQ Event Arguments describing the request.</param> /// <param name="EditableObject">Object whose parameters will be set.</param> /// <param name="Form">Data Form.</param> /// <returns>Any errors encountered, or null if parameters was set properly.</returns> public static async Task <KeyValuePair <string, string>[]> SetEditableForm(IqEventArgs e, object EditableObject, DataForm Form) { Type T = EditableObject.GetType(); string DefaultLanguageCode = GetDefaultLanguageCode(T); List <KeyValuePair <string, string> > Errors = null; PropertyInfo PI; Language Language = await ConcentratorServer.GetLanguage(e.Query, DefaultLanguageCode); Namespace Namespace = await Language.GetNamespaceAsync(T.Namespace); Namespace ConcentratorNamespace = await Language.GetNamespaceAsync(typeof(ConcentratorServer).Namespace); LinkedList <KeyValuePair <PropertyInfo, object> > ToSet = null; ValidationMethod ValidationMethod; OptionAttribute OptionAttribute; RegularExpressionAttribute RegularExpressionAttribute; RangeAttribute RangeAttribute; DataType DataType; Type PropertyType; string Header; object ValueToSet; object[] Parsed; bool ReadOnly; bool Alpha; bool DateOnly; bool HasHeader; bool HasOptions; bool ValidOption; if (Namespace == null) { Namespace = await Language.CreateNamespaceAsync(T.Namespace); } if (ConcentratorNamespace == null) { ConcentratorNamespace = await Language.CreateNamespaceAsync(typeof(ConcentratorServer).Namespace); } foreach (Field Field in Form.Fields) { PI = T.GetRuntimeProperty(Field.Var); if (PI == null) { AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(1, "Property not found.")); continue; } if (!PI.CanRead || !PI.CanWrite) { AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(2, "Property not editable.")); continue; } Header = null; ValidationMethod = null; ReadOnly = Alpha = DateOnly = HasHeader = HasOptions = ValidOption = false; foreach (Attribute Attr in PI.GetCustomAttributes()) { if (Attr is HeaderAttribute) { HasHeader = true; } else if ((OptionAttribute = Attr as OptionAttribute) != null) { HasOptions = true; if (Field.ValueString == OptionAttribute.Option.ToString()) { ValidOption = true; } } else if ((RegularExpressionAttribute = Attr as RegularExpressionAttribute) != null) { ValidationMethod = new RegexValidation(RegularExpressionAttribute.Pattern); } else if ((RangeAttribute = Attr as RangeAttribute) != null) { ValidationMethod = new RangeValidation(RangeAttribute.Min, RangeAttribute.Max); } else if (Attr is OpenAttribute) { ValidationMethod = new OpenValidation(); } else if (Attr is ReadOnlyAttribute) { ReadOnly = true; } else if (Attr is AlphaChannelAttribute) { Alpha = true; } else if (Attr is DateOnlyAttribute) { DateOnly = true; } } if (Header == null) { AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(2, "Property not editable.")); continue; } if (ReadOnly) { if (Field.ValueString != PI.GetValue(EditableObject).ToString()) { AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(3, "Property is read-only.")); } continue; } if (HasOptions && !ValidOption) { AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(4, "Select a valid option.")); continue; } PropertyType = PI.PropertyType; ValueToSet = null; Parsed = null; DataType = null; if (PropertyType == typeof(string[])) { if (ValidationMethod == null) { ValidationMethod = new BasicValidation(); } ValueToSet = Parsed = Field.ValueStrings; DataType = StringDataType.Instance; } else if (PropertyType == typeof(Enum)) { if (ValidationMethod == null) { ValidationMethod = new BasicValidation(); } try { ValueToSet = Enum.Parse(PropertyType, Field.ValueString); } catch (Exception) { AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(4, "Select a valid option.")); continue; } } else if (PropertyType == typeof(bool)) { if (ValidationMethod == null) { ValidationMethod = new BasicValidation(); } if (!CommonTypes.TryParse(Field.ValueString, out bool b)) { AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(5, "Invalid boolean value.")); continue; } DataType = BooleanDataType.Instance; } else { if (PropertyType == typeof(string)) { DataType = StringDataType.Instance; } else if (PropertyType == typeof(byte)) { DataType = ByteDataType.Instance; } else if (PropertyType == typeof(short)) { DataType = ShortDataType.Instance; } else if (PropertyType == typeof(int)) { DataType = IntDataType.Instance; } else if (PropertyType == typeof(long)) { DataType = LongDataType.Instance; } else if (PropertyType == typeof(sbyte)) { DataType = ShortDataType.Instance; if (ValidationMethod == null) { ValidationMethod = new RangeValidation(sbyte.MinValue.ToString(), sbyte.MaxValue.ToString()); } } else if (PropertyType == typeof(ushort)) { DataType = IntDataType.Instance; if (ValidationMethod == null) { ValidationMethod = new RangeValidation(ushort.MinValue.ToString(), ushort.MaxValue.ToString()); } } else if (PropertyType == typeof(uint)) { DataType = LongDataType.Instance; if (ValidationMethod == null) { ValidationMethod = new RangeValidation(uint.MinValue.ToString(), uint.MaxValue.ToString()); } } else if (PropertyType == typeof(ulong)) { DataType = IntegerDataType.Instance; if (ValidationMethod == null) { ValidationMethod = new RangeValidation(ulong.MinValue.ToString(), ulong.MaxValue.ToString()); } } else if (PropertyType == typeof(DateTime)) { if (DateOnly) { DataType = DateDataType.Instance; } else { DataType = DateTimeDataType.Instance; } } else if (PropertyType == typeof(decimal)) { DataType = DecimalDataType.Instance; } else if (PropertyType == typeof(double)) { DataType = DoubleDataType.Instance; } else if (PropertyType == typeof(float)) { DataType = DoubleDataType.Instance; // Use xs:double anyway } else if (PropertyType == typeof(TimeSpan)) { DataType = TimeDataType.Instance; } else if (PropertyType == typeof(Uri)) { DataType = AnyUriDataType.Instance; } else if (PropertyType == typeof(SKColor)) { if (Alpha) { DataType = ColorAlphaDataType.Instance; } else { DataType = ColorDataType.Instance; } } else { DataType = null; } if (ValidationMethod == null) { ValidationMethod = new BasicValidation(); } try { ValueToSet = DataType.Parse(Field.ValueString); } catch (Exception) { AddError(ref Errors, Field.Var, await ConcentratorNamespace.GetStringAsync(6, "Invalid value.")); continue; } } if (Parsed == null) { Parsed = new object[] { ValueToSet } } ; ValidationMethod.Validate(Field, DataType, Parsed, Field.ValueStrings); if (Field.HasError) { AddError(ref Errors, Field.Var, Field.Error); continue; } if (ToSet == null) { ToSet = new LinkedList <KeyValuePair <PropertyInfo, object> >(); } ToSet.AddLast(new KeyValuePair <PropertyInfo, object>(PI, ValueToSet)); } if (Errors == null) { foreach (KeyValuePair <PropertyInfo, object> P in ToSet) { try { P.Key.SetValue(EditableObject, P.Value); } catch (Exception ex) { AddError(ref Errors, P.Key.Name, ex.Message); } } } if (Errors == null) { return(null); } else { return(Errors.ToArray()); } }
/// <summary> /// Adds defined identity fields to a sensor data readout. /// </summary> /// <param name="Fields">List of fields being constructed.</param> /// <param name="Now">Timestamp of readout.</param> public virtual void AddIdentityReadout(List <Field> Fields, DateTime Now) { string Module = typeof(MeteringTopology).Namespace; if (!string.IsNullOrEmpty(this.name)) { Fields.Add(new StringField(this, Now, "Name", this.name, FieldType.Identity, FieldQoS.AutomaticReadout, Module, 30)); } if (!string.IsNullOrEmpty(this.className)) { Fields.Add(new StringField(this, Now, "Class", this.className, FieldType.Identity, FieldQoS.AutomaticReadout, Module, 33)); } if (!string.IsNullOrEmpty(this.serialNumber)) { Fields.Add(new StringField(this, Now, "Serial Number", this.serialNumber, FieldType.Identity, FieldQoS.AutomaticReadout, Module, 91)); } if (!string.IsNullOrEmpty(this.meterNumber)) { Fields.Add(new StringField(this, Now, "Meter Number", this.meterNumber, FieldType.Identity, FieldQoS.AutomaticReadout, Module, 92)); } if (!string.IsNullOrEmpty(this.meterLocation)) { Fields.Add(new StringField(this, Now, "Meter Location", this.meterLocation, FieldType.Identity, FieldQoS.AutomaticReadout, Module, 93)); } if (!string.IsNullOrEmpty(this.manufacturerDomain)) { Fields.Add(new StringField(this, Now, "Manufacturer", this.manufacturerDomain, FieldType.Identity, FieldQoS.AutomaticReadout, Module, 45)); } if (!string.IsNullOrEmpty(this.model)) { Fields.Add(new StringField(this, Now, "Model", this.model, FieldType.Identity, FieldQoS.AutomaticReadout, Module, 48)); } if (this.version.HasValue) { Fields.Add(new QuantityField(this, Now, "Version", this.version.Value, CommonTypes.GetNrDecimals(this.version.Value), string.Empty, FieldType.Identity, FieldQoS.AutomaticReadout, Module, 80)); } if (!string.IsNullOrEmpty(this.country)) { Fields.Add(new StringField(this, Now, "Country", this.country, FieldType.Identity, FieldQoS.AutomaticReadout, Module, 54)); } if (!string.IsNullOrEmpty(this.region)) { Fields.Add(new StringField(this, Now, "Region", this.region, FieldType.Identity, FieldQoS.AutomaticReadout, Module, 57)); } if (!string.IsNullOrEmpty(this.city)) { Fields.Add(new StringField(this, Now, "City", this.city, FieldType.Identity, FieldQoS.AutomaticReadout, Module, 60)); } if (!string.IsNullOrEmpty(this.area)) { Fields.Add(new StringField(this, Now, "Area", this.area, FieldType.Identity, FieldQoS.AutomaticReadout, Module, 63)); } string s = this.StreetAndNr; if (!string.IsNullOrEmpty(s)) { Fields.Add(new StringField(this, Now, "Street", s, FieldType.Identity, FieldQoS.AutomaticReadout, Module, 66)); } if (!string.IsNullOrEmpty(this.building)) { Fields.Add(new StringField(this, Now, "Building", this.building, FieldType.Identity, FieldQoS.AutomaticReadout, Module, 71)); } if (!string.IsNullOrEmpty(this.apartment)) { Fields.Add(new StringField(this, Now, "Apartment", this.apartment, FieldType.Identity, FieldQoS.AutomaticReadout, Module, 74)); } if (!string.IsNullOrEmpty(this.room)) { Fields.Add(new StringField(this, Now, "Room", this.room, FieldType.Identity, FieldQoS.AutomaticReadout, Module, 77)); } if (this.latitude.HasValue) { Fields.Add(new QuantityField(this, Now, "Latitude", this.latitude.Value, CommonTypes.GetNrDecimals(this.latitude.Value), string.Empty, FieldType.Identity, FieldQoS.AutomaticReadout, Module, 88)); } if (this.longitude.HasValue) { Fields.Add(new QuantityField(this, Now, "Longitude", this.longitude.Value, CommonTypes.GetNrDecimals(this.longitude.Value), string.Empty, FieldType.Identity, FieldQoS.AutomaticReadout, Module, 89)); } if (this.altitude.HasValue) { Fields.Add(new QuantityField(this, Now, "Altitude", this.altitude.Value, CommonTypes.GetNrDecimals(this.altitude.Value), string.Empty, FieldType.Identity, FieldQoS.AutomaticReadout, Module, 90)); } }
public override ControlParameter[] GetControlParameters() { return(new ControlParameter[] { new BooleanControlParameter("Value", "Publish", "Value.", "Boolean value of topic.", (n) => Task.FromResult <bool?>(this.value), (n, v) => { this.value = v; this.topic.MqttClient.PUBLISH(this.topic.FullTopic, this.qos, this.retain, Encoding.UTF8.GetBytes(CommonTypes.Encode(v))); return Task.CompletedTask; }) }); }
internal AcmeAccount(AcmeClient Client, Uri Location, IEnumerable <KeyValuePair <string, object> > Obj) : base(Client, Location, Location) { foreach (KeyValuePair <string, object> P in Obj) { switch (P.Key) { case "status": if (!Enum.TryParse <AcmeAccountStatus>(P.Value as string, out this.status)) { throw new ArgumentException("Invalid ACME account status: " + P.Value.ToString(), "status"); } break; case "contact": if (P.Value is Array A) { List <string> Contact = new List <string>(); foreach (object Obj2 in A) { if (Obj2 is string s) { Contact.Add(s); } } this.contact = Contact.ToArray(); } break; case "termsOfServiceAgreed": if (CommonTypes.TryParse(P.Value as string, out bool b)) { this.termsOfServiceAgreed = b; } else { throw new ArgumentException("Invalid boolean value.", "termsOfServiceAgreed"); } break; case "orders": this.orders = new Uri(P.Value as string); break; case "initialIp": this.initialIp = P.Value as string; break; case "createdAt": if (XML.TryParse(P.Value as string, out DateTime TP)) { this.createdAt = TP; } else { throw new ArgumentException("Invalid date and time value.", "createdAt"); } break; } } }
private void BooleanResponse(IqResultEventArgs e, string ExpectedElement, BooleanResponseEventHandler Callback, object State) { XmlElement E; if (!e.Ok || (E = e.FirstElement) == null || E.LocalName != ExpectedElement || !CommonTypes.TryParse(E.InnerText, out bool Response)) { e.Ok = false; Response = false; } if (Callback != null) { try { Callback(this, new BooleanResponseEventArgs(Response, e)); } catch (Exception ex) { Log.Critical(ex); } } }
private async void Init() { try { Log.Informational("Starting application."); Types.Initialize( typeof(FilesProvider).GetTypeInfo().Assembly, typeof(RuntimeSettings).GetTypeInfo().Assembly, typeof(IContentEncoder).GetTypeInfo().Assembly, typeof(ImageCodec).GetTypeInfo().Assembly, typeof(MarkdownDocument).GetTypeInfo().Assembly, typeof(MarkdownToHtmlConverter).GetTypeInfo().Assembly, typeof(IJwsAlgorithm).GetTypeInfo().Assembly, typeof(Expression).GetTypeInfo().Assembly, typeof(App).GetTypeInfo().Assembly); db = new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path + Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000); Database.Register(db); await db.RepairIfInproperShutdown(null); await db.Start(); #if GPIO gpio = GpioController.GetDefault(); if (gpio != null) { if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) && Status == GpioOpenStatus.PinOpened) { if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output)) { this.gpioPin.SetDriveMode(GpioPinDriveMode.Output); this.output = await RuntimeSettings.GetAsync("Actuator.Output", false); this.gpioPin.Write(this.output.Value ? GpioPinValue.High : GpioPinValue.Low); await MainPage.Instance.OutputSet(this.output.Value); Log.Informational("Setting Control Parameter.", string.Empty, "Startup", new KeyValuePair <string, object>("Output", this.output.Value)); } else { Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString()); } } else { Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString()); } } #else DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync(); DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device"); if (DeviceInfo is null) { Log.Error("Unable to find Arduino device."); } else { Log.Informational("Connecting to " + DeviceInfo.Name); this.arduinoUsb = new UsbSerial(DeviceInfo); this.arduinoUsb.ConnectionEstablished += () => Log.Informational("USB connection established."); this.arduino = new RemoteDevice(this.arduinoUsb); this.arduino.DeviceReady += async() => { try { Log.Informational("Device ready."); this.arduino.pinMode(13, PinMode.OUTPUT); // Onboard LED. this.arduino.digitalWrite(13, PinState.HIGH); this.arduino.pinMode(8, PinMode.INPUT); // PIR sensor (motion detection). this.arduino.pinMode(9, PinMode.OUTPUT); // Relay. this.output = await RuntimeSettings.GetAsync("Actuator.Output", false); this.arduino.digitalWrite(9, this.output.Value ? PinState.HIGH : PinState.LOW); await MainPage.Instance.OutputSet(this.output.Value); Log.Informational("Setting Control Parameter.", string.Empty, "Startup", new KeyValuePair <string, object>("Output", this.output.Value)); this.arduino.pinMode("A0", PinMode.ANALOG); // Light sensor. } catch (Exception ex) { Log.Critical(ex); } }; this.arduinoUsb.ConnectionFailed += message => { Log.Error("USB connection failed: " + message); }; this.arduinoUsb.ConnectionLost += message => { Log.Error("USB connection lost: " + message); }; this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1); } #endif this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty); if (string.IsNullOrEmpty(this.deviceId)) { this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty); await RuntimeSettings.SetAsync("DeviceId", this.deviceId); } Log.Informational("Device ID: " + this.deviceId); this.tokenAuthentication = new JwtAuthentication(this.deviceId, this.users, this.tokenFactory); this.httpServer = new HttpServer(); //this.httpServer = new HttpServer(new LogSniffer()); StorageFile File = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Root/favicon.ico")); string Root = File.Path; Root = Root.Substring(0, Root.Length - 11); this.httpServer.Register(new HttpFolderResource(string.Empty, Root, false, false, true, true)); this.httpServer.Register("/", (req, resp) => { throw new TemporaryRedirectException("/Index.md"); }); this.httpServer.Register("/Momentary", (req, resp) => { resp.SetHeader("Cache-Control", "max-age=0, no-cache, no-store"); if (req.Header.Accept != null) { switch (req.Header.Accept.GetBestAlternative("text/xml", "application/xml", "application/json")) { case "text/xml": case "application/xml": this.ReturnMomentaryAsXml(req, resp); break; case "application/json": this.ReturnMomentaryAsJson(req, resp); break; default: throw new NotAcceptableException(); } } else { this.ReturnMomentaryAsXml(req, resp); } }, this.tokenAuthentication); this.httpServer.Register("/Set", null, async(req, resp) => { try { if (!req.HasData) { throw new BadRequestException(); } if (!(req.DecodeData() is string s) || !CommonTypes.TryParse(s, out bool OutputValue)) { throw new BadRequestException(); } if (req.Header.Accept != null) { switch (req.Header.Accept.GetBestAlternative("text/xml", "application/xml", "application/json")) { case "text/xml": case "application/xml": await this.SetOutput(OutputValue, req.RemoteEndPoint); this.ReturnMomentaryAsXml(req, resp); break; case "application/json": await this.SetOutput(OutputValue, req.RemoteEndPoint); this.ReturnMomentaryAsJson(req, resp); break; default: throw new NotAcceptableException(); } } else { await this.SetOutput(OutputValue, req.RemoteEndPoint); this.ReturnMomentaryAsXml(req, resp); } resp.SendResponse(); } catch (Exception ex) { resp.SendResponse(ex); } }, false, this.tokenAuthentication); this.httpServer.Register("/Login", null, (req, resp) => { if (!req.HasData || req.Session is null) { throw new BadRequestException(); } object Obj = req.DecodeData(); if (!(Obj is Dictionary <string, string> Form) || !Form.TryGetValue("UserName", out string UserName) || !Form.TryGetValue("Password", out string Password)) { throw new BadRequestException(); } string From = null; if (req.Session.TryGetVariable("from", out Variable v)) { From = v.ValueObject as string; } if (string.IsNullOrEmpty(From)) { From = "/Index.md"; } IUser User = this.Login(UserName, Password); if (User != null) { Log.Informational("User logged in.", UserName, req.RemoteEndPoint, "LoginSuccessful", EventLevel.Minor); req.Session["User"] = User; req.Session.Remove("LoginError"); throw new SeeOtherException(From); } else { Log.Warning("Invalid login attempt.", UserName, req.RemoteEndPoint, "LoginFailure", EventLevel.Minor); req.Session["LoginError"] = "Invalid login credentials provided."; } throw new SeeOtherException(req.Header.Referer.Value); }, true, false, true); this.httpServer.Register("/GetSessionToken", null, (req, resp) => { IUser User; if (!req.Session.TryGetVariable("User", out Variable v) || (User = v.ValueObject as IUser) is null) { throw new ForbiddenException(); } string Token = this.tokenFactory.Create(new KeyValuePair <string, object>("sub", User.UserName)); resp.ContentType = JwtCodec.ContentType; resp.Write(Token); }, true, false, true); }
private async void Init() { try { Log.Informational("Starting application."); Types.Initialize( typeof(FilesProvider).GetTypeInfo().Assembly, typeof(RuntimeSettings).GetTypeInfo().Assembly, typeof(IContentEncoder).GetTypeInfo().Assembly, typeof(ICoapContentFormat).GetTypeInfo().Assembly, typeof(IDtlsCredentials).GetTypeInfo().Assembly, typeof(Lwm2mClient).GetTypeInfo().Assembly, typeof(App).GetTypeInfo().Assembly); Database.Register(new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path + Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000)); #if GPIO gpio = GpioController.GetDefault(); if (gpio != null) { if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) && Status == GpioOpenStatus.PinOpened) { if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output)) { this.gpioPin.SetDriveMode(GpioPinDriveMode.Output); this.output = await RuntimeSettings.GetAsync("Actuator.Output", false); this.gpioPin.Write(this.output.Value ? GpioPinValue.High : GpioPinValue.Low); this.digitalOutput0?.Set(this.output.Value); this.actuation0?.Set(this.output.Value); await MainPage.Instance.OutputSet(this.output.Value); Log.Informational("Setting Control Parameter.", string.Empty, "Startup", new KeyValuePair <string, object>("Output", this.output.Value)); } else { Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString()); } } else { Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString()); } } #else DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync(); DeviceInformation DeviceInfo = this.FindDevice(Devices, "Arduino", "USB Serial Device"); if (DeviceInfo == null) { Log.Error("Unable to find Arduino device."); } else { Log.Informational("Connecting to " + DeviceInfo.Name); this.arduinoUsb = new UsbSerial(DeviceInfo); this.arduinoUsb.ConnectionEstablished += () => Log.Informational("USB connection established."); this.arduino = new RemoteDevice(this.arduinoUsb); this.arduino.DeviceReady += async() => { try { Log.Informational("Device ready."); this.arduino.pinMode(13, PinMode.OUTPUT); // Onboard LED. this.arduino.digitalWrite(13, PinState.HIGH); this.arduino.pinMode(8, PinMode.INPUT); // PIR sensor (motion detection). this.arduino.pinMode(9, PinMode.OUTPUT); // Relay. this.output = await RuntimeSettings.GetAsync("Actuator.Output", false); this.arduino.digitalWrite(9, this.output.Value ? PinState.HIGH : PinState.LOW); this.digitalOutput0?.Set(this.output.Value); this.actuation0?.Set(this.output.Value); await MainPage.Instance.OutputSet(this.output.Value); Log.Informational("Setting Control Parameter.", string.Empty, "Startup", new KeyValuePair <string, object>("Output", this.output.Value)); this.arduino.pinMode("A0", PinMode.ANALOG); // Light sensor. } catch (Exception ex) { Log.Critical(ex); } }; this.arduinoUsb.ConnectionFailed += message => { Log.Error("USB connection failed: " + message); }; this.arduinoUsb.ConnectionLost += message => { Log.Error("USB connection lost: " + message); }; this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1); } #endif this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty); if (string.IsNullOrEmpty(this.deviceId)) { this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty); await RuntimeSettings.SetAsync("DeviceId", this.deviceId); } Log.Informational("Device ID: " + this.deviceId); /************************************************************************************ * To create an unencrypted CoAP Endpoint on the default CoAP port: * * this.coapEndpoint = new CoapEndpoint(); * * To create an unencrypted CoAP Endpoint on the default CoAP port, * with a sniffer that outputs communication to the window: * * this.coapEndpoint = new CoapEndpoint(new LogSniffer()); * * To create a DTLS encrypted CoAP endpoint, on the default CoAPS port, using * the users defined in the IUserSource users: * * this.coapEndpoint = new CoapEndpoint(CoapEndpoint.DefaultCoapsPort, this.users); * * To create a CoAP endpoint, that listens to both the default CoAP port, for * unencrypted communication, and the default CoAPS port, for encrypted, * authenticated and authorized communication, using * the users defined in the IUserSource users. Only users having the given * privilege (if not empty) will be authorized to access resources on the endpoint: * * this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort }, * new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, "PRIVILEGE", false, false); * ************************************************************************************/ this.coapEndpoint = new CoapEndpoint(new int[] { CoapEndpoint.DefaultCoapPort }, new int[] { CoapEndpoint.DefaultCoapsPort }, this.users, string.Empty, false, false); this.outputResource = this.coapEndpoint.Register("/Output", (req, resp) => { string s; if (this.output.HasValue) { s = this.output.Value ? "true" : "false"; } else { s = "-"; } resp.Respond(CoapCode.Content, s, 64); }, async(req, resp) => { try { string s = req.Decode() as string; if (s == null && req.Payload != null) { s = Encoding.UTF8.GetString(req.Payload); } if (s == null || !CommonTypes.TryParse(s, out bool Output)) { resp.RST(CoapCode.BadRequest); } else { resp.Respond(CoapCode.Changed); await this.SetOutput(Output, req.From.ToString()); } } catch (Exception ex) { Log.Critical(ex); } }, Notifications.Acknowledged, "Digital Output.", null, null, new int[] { PlainText.ContentFormatCode }); this.outputResource?.TriggerAll(new TimeSpan(0, 1, 0)); this.lwm2mClient = new Lwm2mClient("MIoT:Actuator:" + this.deviceId, this.coapEndpoint, new Lwm2mSecurityObject(), new Lwm2mServerObject(), new Lwm2mAccessControlObject(), new Lwm2mDeviceObject("Waher Data AB", "ActuatorLwm2m", this.deviceId, "1.0", "Actuator", "1.0", "1.0"), new DigitalOutput(this.digitalOutput0 = new DigitalOutputInstance(0, this.output.HasValue && this.output.Value, "Relay")), new Actuation(this.actuation0 = new ActuationInstance(0, this.output.HasValue && this.output.Value, "Relay"))); this.digitalOutput0.OnRemoteUpdate += async(Sender, e) => { try { await this.SetOutput(((DigitalOutputInstance)Sender).Value, e.Request.From.ToString()); } catch (Exception ex) { Log.Critical(ex); } }; this.actuation0.OnRemoteUpdate += async(Sender, e) => { try { await this.SetOutput(((ActuationInstance)Sender).Value, e.Request.From.ToString()); } catch (Exception ex) { Log.Critical(ex); } }; await this.lwm2mClient.LoadBootstrapInfo(); this.lwm2mClient.OnStateChanged += (sender, e) => { Log.Informational("LWM2M state changed to " + this.lwm2mClient.State.ToString() + "."); }; this.lwm2mClient.OnBootstrapCompleted += (sender, e) => { Log.Informational("Bootstrap procedure completed."); }; this.lwm2mClient.OnBootstrapFailed += (sender, e) => { Log.Error("Bootstrap procedure failed."); this.coapEndpoint.ScheduleEvent(async(P) => { try { await this.RequestBootstrap(); } catch (Exception ex) { Log.Critical(ex); } }, DateTime.Now.AddMinutes(15), null); }; this.lwm2mClient.OnRegistrationSuccessful += (sender, e) => { Log.Informational("Server registration completed."); }; this.lwm2mClient.OnRegistrationFailed += (sender, e) => { Log.Error("Server registration failed."); }; this.lwm2mClient.OnDeregistrationSuccessful += (sender, e) => { Log.Informational("Server deregistration completed."); }; this.lwm2mClient.OnDeregistrationFailed += (sender, e) => { Log.Error("Server deregistration failed."); }; this.lwm2mClient.OnRebootRequest += async(sender, e) => { Log.Warning("Reboot is requested."); try { await this.RequestBootstrap(); } catch (Exception ex) { Log.Critical(ex); } }; await this.RequestBootstrap(); } catch (Exception ex) { Log.Emergency(ex); MessageDialog Dialog = new MessageDialog(ex.Message, "Error"); await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => await Dialog.ShowAsync()); } }
/// <summary> /// Analyzes the difference between the clock on the local machine with the clock on /// another machine, connected to the XMPP network, and compatible with the IEEE /// XMPP IoT extensions. /// /// Command line switches: /// /// -h HOST XMPP Server host name. /// -p PORT XMPP Port number, if different from 5222 /// -a ACCOUNT XMPP Account name to use when connecting to the server. /// -pwd PASSWORD PASSWORD to use when authenticating with the server. /// -i INTERVAL Interval (in milliseconds) used to check clocks. /// -j JID JID of clock source to monitor. /// Default=5000. /// -r RECORDS Number of measurements to collect. /// -n HISTORY Number of records in history. Averages are calculated /// on records in this history. Default=100 /// -w WINDOW Filter window size. The window is used to detect /// and eliminate bad measurements. Default=16 /// -s SPIKE_POS Spike position. Where spikes are detected, in /// window. Default=6 /// -sw SPIKE_WIDTH Spike width. Number of measurements in a row that can /// constitute a spike. Default=3 /// -o OUTPUT_FILE File name of report file. /// -enc ENCODING Text encoding. Default=UTF-8 /// -t TRANSFORM_FILE XSLT transform to use. /// -? Help. /// </summary> static int Main(string[] args) { try { Encoding Encoding = Encoding.UTF8; string OutputFileName = null; string XsltPath = null; string Host = null; string Account = null; string Password = null; string Jid = null; string s; int Port = 5222; int Records = 0; int Interval = 5000; int History = 100; int Window = 16; int SpikePos = 6; int SpikeWidth = 3; int i = 0; int c = args.Length; bool Help = false; while (i < c) { s = args[i++].ToLower(); switch (s) { case "-o": if (i >= c) { throw new Exception("Missing output file name."); } if (string.IsNullOrEmpty(OutputFileName)) { OutputFileName = args[i++]; } else { throw new Exception("Only one output file name allowed."); } break; case "-h": if (i >= c) { throw new Exception("Missing host name."); } if (string.IsNullOrEmpty(Host)) { Host = args[i++]; } else { throw new Exception("Only one host name allowed."); } break; case "-p": if (i >= c) { throw new Exception("Missing port number."); } if (!int.TryParse(args[i++], out Port) || Port <= 0 || Port > 65535) { throw new Exception("Invalid port number."); } break; case "-j": if (i >= c) { throw new Exception("Missing JID."); } if (string.IsNullOrEmpty(Jid)) { Jid = args[i++]; } else { throw new Exception("Only one JID allowed."); } break; case "-i": if (i >= c) { throw new Exception("Missing interval."); } if (!int.TryParse(args[i++], out Interval) || Interval < 1000) { throw new Exception("Invalid interval."); } break; case "-r": if (i >= c) { throw new Exception("Missing number of records to collect."); } if (!int.TryParse(args[i++], out Records) || Records <= 0) { throw new Exception("Invalid number of records to collect."); } break; case "-n": if (i >= c) { throw new Exception("Missing number of history records."); } if (!int.TryParse(args[i++], out History) || History <= 0) { throw new Exception("Invalid number of history records."); } break; case "-w": if (i >= c) { throw new Exception("Missing window size."); } if (!int.TryParse(args[i++], out Window) || Window <= 0) { throw new Exception("Invalid window size."); } break; case "-s": if (i >= c) { throw new Exception("Missing spike position."); } if (!int.TryParse(args[i++], out SpikePos) || SpikePos <= 0) { throw new Exception("Invalid spike position."); } break; case "-sw": if (i >= c) { throw new Exception("Missing spike width."); } if (!int.TryParse(args[i++], out SpikeWidth) || SpikeWidth <= 0) { throw new Exception("Invalid spike width."); } break; case "-a": if (i >= c) { throw new Exception("Missing account name."); } if (string.IsNullOrEmpty(Account)) { Account = args[i++]; } else { throw new Exception("Only one account name allowed."); } break; case "-pwd": if (i >= c) { throw new Exception("Missing password."); } if (string.IsNullOrEmpty(Password)) { Password = args[i++]; } else { throw new Exception("Only one password allowed."); } break; case "-enc": if (i >= c) { throw new Exception("Text encoding missing."); } Encoding = Encoding.GetEncoding(args[i++]); break; case "-t": if (i >= c) { throw new Exception("XSLT transform missing."); } XsltPath = args[i++]; break; case "-?": Help = true; break; default: throw new Exception("Unrecognized switch: " + s); } } if (Help || c == 0) { Console.Out.WriteLine("Analyzes the difference between the clock on the local machine with the clock on"); Console.Out.WriteLine("another machine, connected to the XMPP network, and compatible with the IEEE"); Console.Out.WriteLine("XMPP IoT extensions."); Console.Out.WriteLine(); Console.Out.WriteLine("Command line switches:"); Console.Out.WriteLine(); Console.Out.WriteLine("-h HOST XMPP Server host name."); Console.Out.WriteLine("-p PORT XMPP Port number, if different from 5222"); Console.Out.WriteLine("-a ACCOUNT XMPP Account name to use when connecting to the server."); Console.Out.WriteLine("-pwd PASSWORD PASSWORD to use when authenticating with the server."); Console.Out.WriteLine("-j JID JID of clock source to monitor."); Console.Out.WriteLine("-i INTERVAL Interval (in milliseconds) used to check clocks."); Console.Out.WriteLine(" Default=5000."); Console.Out.WriteLine("-r RECORDS Number of measurements to collect."); Console.Out.WriteLine("-n HISTORY Number of records in history. Averages are calculated"); Console.Out.WriteLine(" on records in this history. Default=100"); Console.Out.WriteLine("-w WINDOW Filter window size. The window is used to detect"); Console.Out.WriteLine(" and eliminate bad measurements. Default=16"); Console.Out.WriteLine("-s SPIKE_POS Spike position. Where spikes are detected, in"); Console.Out.WriteLine(" window. Default=6"); Console.Out.WriteLine("-sw SPIKE_WIDTH Spike width. Number of measurements in a row that can"); Console.Out.WriteLine(" constitute a spike. Default=3"); Console.Out.WriteLine("-o OUTPUT_FILE File name of report file."); Console.Out.WriteLine("-enc ENCODING Text encoding. Default=UTF-8"); Console.Out.WriteLine("-t TRANSFORM_FILE XSLT transform to use."); Console.Out.WriteLine("-? Help."); return(0); } if (string.IsNullOrEmpty(Host)) { throw new Exception("No host name specified."); } if (string.IsNullOrEmpty(Account)) { throw new Exception("No account name specified."); } if (string.IsNullOrEmpty(Password)) { throw new Exception("No password specified."); } if (string.IsNullOrEmpty(Jid)) { throw new Exception("No clock source JID specified."); } if (Records <= 0) { throw new Exception("Number of records to collect not specified."); } if (string.IsNullOrEmpty(OutputFileName)) { throw new Exception("No output filename specified."); } XmppCredentials Credentials = new XmppCredentials() { Host = Host, Port = Port, Account = Account, Password = Password, AllowCramMD5 = true, AllowEncryption = true, AllowDigestMD5 = true, AllowPlain = true, AllowScramSHA1 = true, AllowRegistration = false }; using (XmppClient Client = new XmppClient(Credentials, "en", typeof(Program).Assembly)) { ManualResetEvent Done = new ManualResetEvent(false); ManualResetEvent Error = new ManualResetEvent(false); Client.OnStateChanged += (sender, NewState) => { switch (NewState) { case XmppState.Connected: Done.Set(); break; case XmppState.Error: case XmppState.Offline: Error.Set(); break; } }; Client.Connect(); i = WaitHandle.WaitAny(new WaitHandle[] { Done, Error }); if (i == 1) { throw new Exception("Unable to connect to broker."); } if (Jid.Contains("@") && !Jid.Contains("/")) { RosterItem Contact = Client.GetRosterItem(Jid); if (Contact == null || (Contact.State != SubscriptionState.Both && Contact.State != SubscriptionState.To)) { Done.Reset(); Client.OnPresenceSubscribed += (sender, e) => { if (string.Compare(e.FromBareJID, Jid, true) == 0) { Done.Set(); } }; Client.OnPresenceUnsubscribed += (sender, e) => { if (string.Compare(e.FromBareJID, Jid, true) == 0) { Error.Set(); } }; Console.WriteLine("Requesting presence subscription to " + Jid); Client.RequestPresenceSubscription(Jid); i = WaitHandle.WaitAny(new WaitHandle[] { Done, Error }); if (i == 1) { throw new Exception("Unable to obtain presence subscription."); } Console.WriteLine("Presence subscription obtained."); } } ManualResetEvent Done2 = new ManualResetEvent(false); using (StreamWriter f = File.CreateText(OutputFileName)) { XmlWriterSettings Settings = new XmlWriterSettings() { Encoding = Encoding, Indent = true, IndentChars = "\t", NewLineChars = Console.Out.NewLine, OmitXmlDeclaration = false, WriteEndDocumentOnClose = true }; using (XmlWriter w = XmlWriter.Create(f, Settings)) { w.WriteStartDocument(); if (!string.IsNullOrEmpty(XsltPath)) { w.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"" + XML.Encode(XsltPath) + "\""); } w.WriteStartElement("ClockStatistics", "http://waher.se/Schema/Networking/ClockStatistics.xsd"); w.WriteStartElement("Parameters"); w.WriteAttributeString("clientJid", Client.BareJID); w.WriteAttributeString("sourceJid", Jid); w.WriteAttributeString("records", Records.ToString()); w.WriteAttributeString("interval", Interval.ToString()); w.WriteAttributeString("history", History.ToString()); w.WriteAttributeString("window", Window.ToString()); w.WriteAttributeString("spikePos", SpikePos.ToString()); w.WriteAttributeString("spikeWidth", SpikeWidth.ToString()); w.WriteAttributeString("hfFreq", System.Diagnostics.Stopwatch.Frequency.ToString()); w.WriteEndElement(); w.WriteStartElement("Samples"); using (SynchronizationClient SynchClient = new SynchronizationClient(Client)) { SynchClient.OnUpdated += (sender, e) => { DateTime TP = DateTime.Now; double? StdDev; w.WriteStartElement("Sample"); w.WriteAttributeString("timestamp", XML.Encode(TP)); if (SynchClient.RawLatency100Ns.HasValue) { w.WriteAttributeString("rawLatencyMs", CommonTypes.Encode(SynchClient.RawLatency100Ns.Value * 1e-4)); } if (SynchClient.LatencySpikeRemoved.HasValue) { w.WriteAttributeString("spikeLatencyRemoved", CommonTypes.Encode(SynchClient.LatencySpikeRemoved.Value)); } if (SynchClient.RawClockDifference100Ns.HasValue) { w.WriteAttributeString("rawDifferenceMs", CommonTypes.Encode(SynchClient.RawClockDifference100Ns.Value * 1e-4)); } if (SynchClient.ClockDifferenceSpikeRemoved.HasValue) { w.WriteAttributeString("spikeDifferenceRemoved", CommonTypes.Encode(SynchClient.ClockDifferenceSpikeRemoved.Value)); } if (SynchClient.FilteredLatency100Ns.HasValue) { w.WriteAttributeString("filteredLatencyMs", CommonTypes.Encode(SynchClient.FilteredLatency100Ns.Value * 1e-4)); } if (SynchClient.FilteredClockDifference100Ns.HasValue) { w.WriteAttributeString("filteredDifferenceMs", CommonTypes.Encode(SynchClient.FilteredClockDifference100Ns.Value * 1e-4)); } if (SynchClient.AvgLatency100Ns.HasValue) { w.WriteAttributeString("avgLatencyMs", CommonTypes.Encode(SynchClient.AvgLatency100Ns.Value * 1e-4)); } if (SynchClient.AvgClockDifference100Ns.HasValue) { w.WriteAttributeString("avgDifferenceMs", CommonTypes.Encode(SynchClient.AvgClockDifference100Ns.Value * 1e-4)); } StdDev = SynchClient.CalcStdDevLatency100Ns(); if (StdDev.HasValue) { w.WriteAttributeString("stdDevLatencyMs", CommonTypes.Encode(StdDev.Value * 1e-4)); } StdDev = SynchClient.CalcStdDevClockDifference100Ns(); if (StdDev.HasValue) { w.WriteAttributeString("stdDevDifferenceMs", CommonTypes.Encode(StdDev.Value * 1e-4)); } if (SynchClient.RawLatencyHf.HasValue) { w.WriteAttributeString("rawLatencyHf", SynchClient.RawLatencyHf.Value.ToString()); } if (SynchClient.LatencyHfSpikeRemoved.HasValue) { w.WriteAttributeString("spikeLatencyHfRemoved", CommonTypes.Encode(SynchClient.LatencyHfSpikeRemoved.Value)); } if (SynchClient.RawClockDifferenceHf.HasValue) { w.WriteAttributeString("rawDifferenceHf", SynchClient.RawClockDifferenceHf.Value.ToString()); } if (SynchClient.ClockDifferenceHfSpikeRemoved.HasValue) { w.WriteAttributeString("spikeDifferenceHfRemoved", CommonTypes.Encode(SynchClient.ClockDifferenceHfSpikeRemoved.Value)); } if (SynchClient.FilteredLatencyHf.HasValue) { w.WriteAttributeString("filteredLatencyHf", SynchClient.FilteredLatencyHf.ToString()); } if (SynchClient.FilteredClockDifferenceHf.HasValue) { w.WriteAttributeString("filteredDifferenceHf", SynchClient.FilteredClockDifferenceHf.ToString()); } if (SynchClient.AvgLatencyHf.HasValue) { w.WriteAttributeString("avgLatencyHf", SynchClient.AvgLatencyHf.ToString()); } if (SynchClient.AvgClockDifferenceHf.HasValue) { w.WriteAttributeString("avgDifferenceHf", SynchClient.AvgClockDifferenceHf.ToString()); } StdDev = SynchClient.CalcStdDevLatencyHf(); if (StdDev.HasValue) { w.WriteAttributeString("stdDevLatencyHf", CommonTypes.Encode(StdDev.Value)); } StdDev = SynchClient.CalcStdDevClockDifferenceHf(); if (StdDev.HasValue) { w.WriteAttributeString("stdDevDifferenceHf", CommonTypes.Encode(StdDev.Value)); } w.WriteEndElement(); Console.Out.Write("."); if (--Records <= 0) { Done2.Set(); } }; SynchClient.MonitorClockDifference(Jid, Interval, History, Window, SpikePos, SpikeWidth, true); Done2.WaitOne(); } w.WriteEndElement(); w.WriteEndElement(); w.WriteEndDocument(); w.Flush(); Console.Out.WriteLine(); } } } return(0); } catch (Exception ex) { Console.Out.WriteLine(ex.Message); return(-1); } }
private Task Client_OnContentReceived(object Sender, MqttContent Content) { string Xml = System.Text.Encoding.UTF8.GetString(Content.Data); XmlDocument Doc = new XmlDocument(); try { Doc.LoadXml(Xml); } catch (Exception) { return(Task.CompletedTask); } XmlElement E = Doc.DocumentElement; if (E.LocalName != "log" || E.NamespaceURI != MqttEventSink.NamespaceEventLogging) { return(Task.CompletedTask); } XmlElement E2; List <KeyValuePair <string, object> > Tags = new List <KeyValuePair <string, object> >(); DateTime Timestamp = XML.Attribute(E, "timestamp", DateTime.MinValue); string EventId = XML.Attribute(E, "id"); EventType Type = (EventType)XML.Attribute(E, "type", EventType.Informational); EventLevel Level = (EventLevel)XML.Attribute(E, "level", EventLevel.Minor); string Object = XML.Attribute(E, "object"); string Actor = XML.Attribute(E, "subject"); string Facility = XML.Attribute(E, "facility"); string Module = XML.Attribute(E, "module"); string Message = string.Empty; string StackTrace = string.Empty; foreach (XmlNode N in E.ChildNodes) { switch (N.LocalName) { case "message": Message = N.InnerText; break; case "tag": E2 = (XmlElement)N; string TagName = XML.Attribute(E2, "name"); string TagValue = XML.Attribute(E2, "value"); string TagType = XML.Attribute(E2, "type"); object TagValueParsed = TagValue; switch (TagType) { case "xs:anyURI": Uri URI; if (Uri.TryCreate(TagValue, UriKind.Absolute, out URI)) { TagValueParsed = URI; } break; case "xs:boolean": bool b; if (CommonTypes.TryParse(TagValue, out b)) { TagValueParsed = b; } break; case "xs:unsignedByte": byte ui8; if (byte.TryParse(TagValue, out ui8)) { TagValueParsed = ui8; } break; case "xs:short": short i16; if (short.TryParse(TagValue, out i16)) { TagValueParsed = i16; } break; case "xs:int": int i32; if (int.TryParse(TagValue, out i32)) { TagValueParsed = i32; } break; case "xs:long": long i64; if (long.TryParse(TagValue, out i64)) { TagValueParsed = i64; } break; case "xs:byte": sbyte i8; if (sbyte.TryParse(TagValue, out i8)) { TagValueParsed = i8; } break; case "xs:unsignedShort": ushort ui16; if (ushort.TryParse(TagValue, out ui16)) { TagValueParsed = ui16; } break; case "xs:unsignedInt": uint ui32; if (uint.TryParse(TagValue, out ui32)) { TagValueParsed = ui32; } break; case "xs:unsignedLong": ulong ui64; if (ulong.TryParse(TagValue, out ui64)) { TagValueParsed = ui64; } break; case "xs:decimal": decimal d; if (CommonTypes.TryParse(TagValue, out d)) { TagValueParsed = d; } break; case "xs:double": double d2; if (CommonTypes.TryParse(TagValue, out d2)) { TagValueParsed = d2; } break; case "xs:float": float f; if (CommonTypes.TryParse(TagValue, out f)) { TagValueParsed = f; } break; case "xs:time": TimeSpan TS; if (TimeSpan.TryParse(TagValue, out TS)) { TagValueParsed = TS; } break; case "xs:date": case "xs:dateTime": DateTime DT; if (XML.TryParse(TagValue, out DT)) { TagValueParsed = DT; } break; case "xs:string": case "xs:language": default: break; } Tags.Add(new KeyValuePair <string, object>(TagName, TagValueParsed)); break; case "stackTrace": StackTrace = N.InnerText; break; } } if (string.IsNullOrEmpty(Facility)) { Facility = Content.Topic; } Event Event = new Event(Timestamp, Type, Message, Object, Actor, EventId, Level, Facility, Module, StackTrace, Tags.ToArray()); EventEventHandler h = this.OnEvent; if (h is null) { Log.Event(Event); } else { try { h(this, new EventEventArgs(Content, Event)); } catch (Exception ex) { Log.Critical(ex); } } return(Task.CompletedTask); }
public override void BeforeContent(HttpResponse Response, bool ExpectContent) { this.response.Append("<resp xmlns='"); this.response.Append(HttpxClient.Namespace); this.response.Append("' version='1.1' statusCode='"); this.response.Append(Response.StatusCode.ToString()); this.response.Append("' statusMessage='"); this.response.Append(XML.Encode(Response.StatusMessage)); this.response.Append("'><headers xmlns='"); this.response.Append(HttpxClient.NamespaceHeaders); this.response.Append("'>"); if (Response.ContentLength.HasValue) { this.chunked = (Response.ContentLength.Value > this.maxChunkSize); } else if (ExpectContent) { this.chunked = true; } else { if ((Response.StatusCode < 100 || Response.StatusCode > 199) && Response.StatusCode != 204 && Response.StatusCode != 304) { this.response.Append("<header name='Content-Length'>0</header>"); } } foreach (KeyValuePair <string, string> P in Response.GetHeaders()) { this.response.Append("<header name='"); this.response.Append(XML.Encode(P.Key)); this.response.Append("'>"); this.response.Append(XML.Encode(P.Value)); this.response.Append("</header>"); } this.response.Append("</headers>"); if (this.chunked.HasValue) { if (this.chunked.Value) { this.streamId = Guid.NewGuid().ToString().Replace("-", string.Empty); if (this.socks5Proxy != null) { this.response.Append("<data><s5 sid='"); this.response.Append(this.streamId); this.response.Append("' e2e='"); this.response.Append(CommonTypes.Encode(this.e2e != null)); this.response.Append("'/></data>"); this.ReturnResponse(); this.socks5Output = new P2P.SOCKS5.OutgoingStream(this.streamId, this.from, this.to, 49152, this.e2e, this.e2eReference); this.socks5Output.OnAbort += this.IbbOutput_OnAbort; this.socks5Proxy.InitiateSession(this.to, this.streamId, this.InitiationCallback, null); } else if (this.ibbClient != null) { this.response.Append("<data><ibb sid='"); this.response.Append(this.streamId); this.response.Append("'/></data>"); this.ReturnResponse(); this.ibbOutput = this.ibbClient.OpenStream(this.to, this.maxChunkSize, this.streamId, this.e2e); this.ibbOutput.OnAbort += this.IbbOutput_OnAbort; } else { this.chunk = new byte[this.maxChunkSize]; this.response.Append("<data><chunkedBase64 streamId='"); this.response.Append(this.streamId); this.response.Append("'/></data>"); this.ReturnResponse(); } lock (activeStreams) { activeStreams[this.from + " " + this.streamId] = this; } } else { this.response.Append("<data><base64>"); } } else { this.ReturnResponse(); } }
public override void Search() { SearchForThingsDialog Dialog = new SearchForThingsDialog() { Owner = MainWindow.currentInstance }; bool?Result = Dialog.ShowDialog(); if (Result.HasValue && Result.Value) { Rule[] Rules = Dialog.GetRules(); List <SearchOperator> Operators = new List <SearchOperator>(); bool Numeric; foreach (Rule Rule in Rules) { Numeric = CommonTypes.TryParse(Rule.Value1, out double d); switch (Rule.Operator) { case Operator.Equality: if (Numeric) { Operators.Add(new NumericTagEqualTo(Rule.Tag, d)); } else { Operators.Add(new StringTagEqualTo(Rule.Tag, Rule.Value1)); } break; case Operator.NonEquality: if (Numeric) { Operators.Add(new NumericTagNotEqualTo(Rule.Tag, d)); } else { Operators.Add(new StringTagNotEqualTo(Rule.Tag, Rule.Value1)); } break; case Operator.GreaterThan: if (Numeric) { Operators.Add(new NumericTagGreaterThan(Rule.Tag, d)); } else { Operators.Add(new StringTagGreaterThan(Rule.Tag, Rule.Value1)); } break; case Operator.GreaterThanOrEqualTo: if (Numeric) { Operators.Add(new NumericTagGreaterThanOrEqualTo(Rule.Tag, d)); } else { Operators.Add(new StringTagGreaterThanOrEqualTo(Rule.Tag, Rule.Value1)); } break; case Operator.LesserThan: if (Numeric) { Operators.Add(new NumericTagLesserThan(Rule.Tag, d)); } else { Operators.Add(new StringTagLesserThan(Rule.Tag, Rule.Value1)); } break; case Operator.LesserThanOrEqualTo: if (Numeric) { Operators.Add(new NumericTagLesserThanOrEqualTo(Rule.Tag, d)); } else { Operators.Add(new StringTagLesserThanOrEqualTo(Rule.Tag, Rule.Value1)); } break; case Operator.InRange: Numeric &= CommonTypes.TryParse(Rule.Value2, out double d2); if (Numeric) { Operators.Add(new NumericTagInRange(Rule.Tag, d, true, d2, true)); } else { Operators.Add(new StringTagInRange(Rule.Tag, Rule.Value1, true, Rule.Value2, true)); } break; case Operator.NotInRange: Numeric &= CommonTypes.TryParse(Rule.Value2, out d2); if (Numeric) { Operators.Add(new NumericTagNotInRange(Rule.Tag, d, true, d2, true)); } else { Operators.Add(new StringTagNotInRange(Rule.Tag, Rule.Value1, true, Rule.Value2, true)); } break; case Operator.Wildcard: Operators.Add(new StringTagLike(Rule.Tag, Rule.Value1, "*")); break; } } this.registryClient.Search(0, 100, Operators.ToArray(), (sender, e) => { this.ShowResult(e); }, null); } }
public static void Main(string[] args) { new TLogging("delivery/bin/Ict.Tools.DataMigrateStatistics.log"); new TAppSettingsManager(false); string row_count_location = TAppSettingsManager.GetValue("fulldumpPath", "delivery/bin/fulldump") + Path.DirectorySeparatorChar + "_row_count.txt"; if (File.Exists(row_count_location)) { DBAccess.GDBAccessObj = new TDataBase(); TCmdOpts cmdLine = new TCmdOpts(); string xmlfile = cmdLine.GetOptValue("petraxml"); DBAccess.GDBAccessObj.EstablishDBConnection(CommonTypes.ParseDBType(cmdLine.GetOptValue("type")), cmdLine.GetOptValue("host"), cmdLine.GetOptValue("port"), cmdLine.GetOptValue("database"), cmdLine.GetOptValue("username"), cmdLine.GetOptValue( "password"), ""); TDataDefinitionParser parserNew = new TDataDefinitionParser(xmlfile, false); TDataDefinitionStore storeNew = new TDataDefinitionStore(); parserNew.ParseDocument(ref storeNew, false, true); List <TTable> newTables = storeNew.GetTables(); // table names and row numbers on alternate lines string[] checkRows = File.ReadAllLines(row_count_location); Console.WriteLine(); Console.WriteLine("--- Testing all rows have loaded successfully ---"); int totalRows = 0; // total number of rows in database int totalCheckRows = 0; // total number of rows there should be in the database bool rowsMissing = false; foreach (TTable newTable in newTables) { if (newTable.strName != "s_login") // ignore this table as the row count changes everytime a connection is made to the database { int i = 0; int rowCount; // number of rows actually in table int rowCountCheck = 0; // number of rows there should be in table // count rows in table string sql = "SELECT count(*) from " + newTable.strName + ";"; rowCount = Convert.ToInt32(DBAccess.GDBAccessObj.ExecuteScalar(sql, IsolationLevel.ReadUncommitted)); // read how many rows there should be in the same table while (i < checkRows.Length) { if (checkRows[i] == newTable.strName) { rowCountCheck = Convert.ToInt32(checkRows[i + 1]); break; } i += 2; } totalRows += rowCount; totalCheckRows += rowCountCheck; // if there are rows missing if (rowCount != rowCountCheck) { Console.Write(newTable.strName + " is incomplete. "); Console.WriteLine((rowCountCheck - rowCount) + " out of " + rowCountCheck + " rows did not load!"); rowsMissing = true; } } } // if all rows are present if (!rowsMissing) { Console.WriteLine("All rows successfully loaded."); } // write a summary of the number of rows successfully loaded Console.WriteLine(); Console.WriteLine("--- Total number of rows loaded ---"); Console.WriteLine(totalRows + " out of " + totalCheckRows + " rows loaded successfully."); string percentage = (((double)totalRows / totalCheckRows) * 100).ToString("#.##"); Console.WriteLine(percentage + "%"); Console.WriteLine(); DBAccess.GDBAccessObj.CloseDBConnection(); } else { TLogging.Log("Warning: unable to perform a row count test. _row_count.txt is missing from the folder .../delivery/bin/fulldump."); TLogging.Log(""); } }