/// <summary>
		/// <c>SymbolLabelInfoConfigDialog</c>'s constructor.
		/// </summary>
		/// <param name="parent">
		/// The dialog's parent window.
		/// </param>
		public SymbolLabelDialog(Window parent)
		{
			XML gxml = new XML(null, "gui.glade","symbolLabelDialog",null);
			
			gxml.Autoconnect(this);
			
			symbolLabelDialog.Modal = true;
			symbolLabelDialog.Resizable = false;
			symbolLabelDialog.TransientFor = parent;
			
			CellRendererText cellRenderer = new CellRendererText();			
			
			cellRenderer.Xalign = 0.5f;
			symbolLabelsTV.AppendColumn("Símbolo", cellRenderer,"text",0);
			symbolLabelsTV.AppendColumn("Etiqueta", new CellRendererText(),"text",1);
			
			symbolLabelsModel = new ListStore(typeof(string), 
			                                  typeof(string));
			
			symbolLabelsTV.Model = symbolLabelsModel;
			
			symbolLabelsTV.Selection.Changed += OnSymbolLabelsTVSelectionChanged;
			
			foreach (SymbolLabelInfo info in LibraryConfig.Instance.Symbols)
			{				
				symbolLabelsModel.AppendValues(info.Symbol, info.Label);
			}
			
			changes = false;
		}
Пример #2
0
 public void InitComponent()
 {
     gxml = new XML (null, "fastopen.glade", "window", null);
     gxml.Autoconnect (this);
     window.Icon = new Gdk.Pixbuf (null, "fastopen.png");
     AppContext.Init ();
 }
		public SelectRenamedClassDialog (IEnumerable<IType> classes)
		{
			XML glade = new XML (null, "gui.glade", "SelectRenamedClassDialog", null);
			glade.Autoconnect (this);
			
			store = new ListStore (typeof(Pixbuf), typeof(string));
			treeClasses.Model = store;
			
			TreeViewColumn column = new TreeViewColumn ();
		
			var pr = new CellRendererPixbuf ();
			column.PackStart (pr, false);
			column.AddAttribute (pr, "pixbuf", 0);
			
			CellRendererText crt = new CellRendererText ();
			column.PackStart (crt, true);
			column.AddAttribute (crt, "text", 1);
			
			treeClasses.AppendColumn (column);
			
			foreach (IType cls in classes) {
				Pixbuf pic = ImageService.GetPixbuf (cls.StockIcon);
				store.AppendValues (pic, cls.FullName);
			}
		}
Пример #4
0
        /// Create New Accept User Dialog
        public AcceptUser(PeerSocket peer)
        {
            XML xml = new XML(null, "AcceptUserDialog.glade", "dialog", null);
            xml.Autoconnect(this);

            // Get UserInfo
            UserInfo userInfo = peer.Info as UserInfo;

            // Initialize GUI
            this.labelTitle.Text = "<span size='x-large'><b>Accept User</b> (";
            if (userInfo.SecureAuthentication == true) {
                this.image.Pixbuf = StockIcons.GetPixbuf("SecureAuth");
                this.labelTitle.Text += "Secure";
                this.dialog.Title += " (Secure Authentication)";
            } else {
                this.image.Pixbuf = StockIcons.GetPixbuf("InsecureAuth");
                this.labelTitle.Text += "Insecure";
                this.dialog.Title += " (Insecure Authentication)";
            }
            this.labelTitle.Text += ")</span>";
            this.labelTitle.UseMarkup = true;

            entryName.Text = userInfo.Name;
            entryIP.Text = peer.GetRemoteIP().ToString();

            this.dialog.ShowAll();
        }
Пример #5
0
        public LoginDialog(Window parent, string errorMsg)
            : base("Login", parent)
        {
            XML gxml = new XML(null, "MultiMC.GTKGUI.LoginDialog.glade",
                "loginTable", null);
            gxml.Autoconnect(this);

            labelErrorMsg.Text = errorMsg;

            Alignment loginAlign = new Alignment(0.5f, 0.5f, 1, 1);
            loginAlign.Add(loginTable);
            loginAlign.SetPadding(4, 4, 4, 4);
            this.VBox.Add(loginAlign);
            loginAlign.ShowAll();

            okButton = this.AddButton("_OK", ResponseType.Ok) as Button;
            cancelButton = this.AddButton("_Cancel", ResponseType.Cancel) as Button;

            this.Default = okButton;

            this.WidthRequest = 420;

            labelErrorMsg.Visible = !string.IsNullOrEmpty(labelErrorMsg.Text);

            entryPassword.Visibility = false;
        }
        public AddinLoadErrorDialog(AddinError[] errors)
        {
            XML glade = new XML (null, "MonoDevelop.Startup.glade", "addinLoadErrorDialog", null);
            glade.Autoconnect (this);

            TreeStore store = new TreeStore (typeof(string));
            errorTree.AppendColumn ("Addin", new CellRendererText (), "text", 0);
            errorTree.Model = store;

            bool fatal = false;

            foreach (AddinError err in errors) {
                string name = Path.GetFileNameWithoutExtension (err.AddinFile);
                if (err.Fatal) name += " (Fatal error)";
                TreeIter it = store.AppendValues (name);
                store.AppendValues (it, "Full Path: " + err.AddinFile);
                store.AppendValues (it, "Error: " + err.Exception.Message);
                it = store.AppendValues (it, "Exception: " + err.Exception.GetType ());
                store.AppendValues (it, err.Exception.StackTrace.ToString ());
                if (err.Fatal) fatal = true;
            }

            //			addinLoadErrorDialog.ShowAll ();

            if (fatal) {
                noButton.Hide ();
                yesButton.Hide ();
                labelContinue.Hide ();
                closeButton.Show ();
                labelFatal.Show ();
            }
        }
Пример #7
0
 public GladeWindow(Assembly assembly, string resourceName, string windowName)
 {
     xml = new XML (assembly, resourceName, windowName, null);
     xml.Autoconnect (this);
     window = (Window)xml[windowName];
     window.DeleteEvent += window_DeleteEvent;
 }
Пример #8
0
        public WebViewer()
            : base(WindowType.Toplevel)
        {
            xml = new XML (null, "MainWindow.glade", "mainBox", null);
            xml.Autoconnect (this);
            Gdk.Pixbuf pix = new Gdk.Pixbuf (null, "webnotes-16.png");

            //Window settings
            Title = "WebNotes";
            WindowPosition = WindowPosition.Center;
            Icon = pix;
            Resize (650,600);

            //Trayicon stuff
            trayIcon = new TrayIcon ("WebNotes");
            EventBox ebox = new EventBox ();
            ebox.ButtonPressEvent += ButtonPressed;
            Image image = new Image (pix);
            ebox.Add (image);
            trayIcon.Add (ebox);
            trayIcon.ShowAll ();

            //Gecko webcontrol
            wc = new WebControl ();
            wc.LoadUrl ("http://localhost:8000");
            geckoBox.Add (wc);

            optionMenu.Changed += OptionChanged;
            BuildMenu ();
            int firstPage = list.IndexOf ("WikiHome");
            if (firstPage != -1)
            optionMenu.SetHistory ((uint)firstPage);

            Add (mainBox);
        }
		public SelectRenamedClassDialog (IEnumerable<INamedTypeSymbol> classes)
		{
			XML glade = new XML (null, "gui.glade", "SelectRenamedClassDialog", null);
			glade.Autoconnect (this);
			
			store = new ListStore (typeof(Xwt.Drawing.Image), typeof(string));
			treeClasses.Model = store;
			
			TreeViewColumn column = new TreeViewColumn ();
		
			var pr = new CellRendererImage ();
			column.PackStart (pr, false);
			column.AddAttribute (pr, "image", 0);
			
			CellRendererText crt = new CellRendererText ();
			column.PackStart (crt, true);
			column.AddAttribute (crt, "text", 1);

			treeClasses.AppendColumn (column);
			
			foreach (var cls in classes) {
				var pic = ImageService.GetIcon (cls.GetStockIcon ());
				store.AppendValues (pic, cls.GetFullName ());
			}
		}
Пример #10
0
    public GtkSharpVectorViewer(string[] args)
    {
        XML glade = new XML (null, "svg-viewer.glade", "MainWindow", null);
        glade.Autoconnect (this);

        glade["bgEventBox"].ModifyBg(StateType.Normal, glade["MainWindow"].Style.Background (Gtk.StateType.Active));

        svgWidget = new SvgImageWidget();

        //	mainPaned.Add2 (svgWidget);
        //	mainPaned.Pack2 (svgWidget, false, false);
        //	mainHBox.PackStart (svgWidget, true, true, 0);

        (glade["svgViewport"] as Viewport).Add(svgWidget);

        svgWidget.Show();

        testsStore = new TreeStore(typeof(string));
        testsTreeView.Model = testsStore;
        testsTreeView.AppendColumn("Test Name", new CellRendererText(), "text", 0);

        if (args.Length > 0) {
            LoadUri (new Uri(args[0]));
        }

        AddW3CTests ();
    }
		/// <summary>
		/// <see cref="ExpressionRuleCallWidget"/>'s constructor.
		/// </summary>
		/// <param name="container">
		/// A <see cref="IExpressionItemContainer"/>
		/// </param>
		public ExpressionGroupWidget(IExpressionItemContainer container) 
			: base(container)
		{
			// We load the glade widgets.
			Glade.XML gladeXml = new XML("mathtextrecognizer.glade",
			                             "expressionGroupWidgetBase");
			
			gladeXml.Autoconnect(this);
			
			this.Add(expressionGroupWidgetBase);
			
			this.HeightRequest = expressionGroupWidgetBase.HeightRequest;
			
			// The menu is created.
			addItemMenu = new AddSubItemMenu(this);
			
			// We tell the widget to redraw itself when the size is changed,
			// fixs some graphical glitches.
			expGroupItemsScroller.Hadjustment.ValueChanged +=
				delegate(object sender, EventArgs args)
			{
				expGroupItemsScroller.QueueDraw();
			};
			
			this.ShowAll();
		}
		/// <summary>
		/// <c>DatabaseInfoDialog</c>'s constructor.
		/// </summary>
		/// <param name="parent">
		/// The dialog's parent window.
		/// </param>
		public DatabaseInfoDialog(Window parent)
		{
			XML gxml = new XML(null, "gui.glade", "databaseInfoDialog", null);
			gxml.Autoconnect(this);
			
			this.databaseInfoDialog.TransientFor = parent;
			this.databaseInfoDialog.Modal = true;
		}
Пример #13
0
        public Widget CustomWidgetHandler(XML xml, string func_name, string name, string string1, string string2, int int1, int int2)
        {
            if (func_name.Equals ("CreateGeckoControl")) {
            return new Gecko.WebControl ();
              }

              return null;
        }
		/// <summary>
		/// <c>SymbolLabelEditorDialog</c>'s constructor.
		/// </summary>
		/// <param name="parent">
		/// This dialog parent's window.
		/// </param>
		public SymbolLabelListDialog(Window parent)
		{
			XML gxml = new XML(null, "gui.glade", "symbolLabelEditorDialog",null);			
			gxml.Autoconnect(this);
			
			symbolLabelEditorDialog.TransientFor = parent;
			
			symbolLabelEditorDialog.AddActionWidget(okBtn, ResponseType.Ok);
		}
Пример #15
0
		/// <summary>
		/// <see cref="AddSubItemMenu"/>'s constructor.
		/// </summary>
		/// <param name="container">
		/// A <see cref="IExpressionItemContainer"/> 
		/// Where the elements created by the menu items
		/// will be stored.
		/// </param>
		public AddSubItemMenu(IExpressionItemContainer container)
		{
			Glade.XML gladeXml =new XML("mathtextrecognizer.glade",
			                            "addExpressionItemMenu");
			
			gladeXml.Autoconnect(this);				
			
			this.container = container;
		}
Пример #16
0
        public LoadWebImage()
        {
            XML xml = new XML(null, "LoadWebImageDialog.glade", "dialog", null);
            xml.Autoconnect(this);

            this.image.Pixbuf = StockIcons.GetPixbuf("NyIVImage");

            this.dialog.ShowAll();
        }
Пример #17
0
        public EditModsDialog(Window parent, Instance inst)
            : base("Edit Mods", parent)
        {
            this.inst = inst;

            XML gxml = new XML(null, "MultiMC.GTKGUI.EditModsDialog.glade",
                "vboxEditMods", null);
            gxml.Autoconnect(this);

            this.VBox.PackStart(vboxEditMods);

            this.AddButton("_Cancel", ResponseType.Cancel);
            this.AddButton("_OK", ResponseType.Ok);

            WidthRequest = 600;
            HeightRequest = 500;
            // the Jar page is active by default. FIXME: determine dynamically!
            currentMode = Mode.Jar;

            modStore = new ListStore(typeof(string), typeof(Mod));
            jarModList.Model = modStore;
            jarModList.AppendColumn("Mod Name", new CellRendererText(), "text", 0);

            mlModStore = new ListStore(typeof(string), typeof(Mod));
            mlModList.Model = mlModStore;
            mlModList.AppendColumn("Mod Name", new CellRendererText(), "text", 0);

            //mlModList.Selection.Mode = SelectionMode.Multiple;

            inst.InstMods.ModFileChanged += (o, args) => LoadModList();

            // Listen for key presses
            jarModList.KeyPressEvent += new KeyPressEventHandler(jarModList_KeyPressEvent);
            mlModList.KeyPressEvent += new KeyPressEventHandler(mlModList_KeyPressEvent);

            // set up drag & drop
            jarModList.EnableModelDragDest(targetEntries,Gdk.DragAction.Default);
            jarModList.EnableModelDragSource(Gdk.ModifierType.Button1Mask,srcEntries,Gdk.DragAction.Move);
            jarModList.DragDataReceived += OnDragDataReceived;
            jarModList.DragDataGet += (object o, DragDataGetArgs args) =>
            {
                TreeIter iter;
                TreeModel model;
                if(!jarModList.Selection.GetSelected (out iter))
                    return;
                Gdk.Atom[] targets = args.Context.Targets;
                TreePath tp = modStore.GetPath(iter);
                int idx = tp.Indices[0];

                args.SelectionData.Set(targets[0],0,System.Text.Encoding.UTF8.GetBytes( idx.ToString() ));
            };

            Drag.DestSet(mlModList, DestDefaults.All, targetEntries, Gdk.DragAction.Default);
            mlModList.DragDataReceived += OnDragDataReceived;
            mlModList.EnableModelDragDest(targetEntries,Gdk.DragAction.Default);
        }
Пример #18
0
        /// Create new Dialog
        public SetPort()
        {
            XML xml = new XML(null, "SetPortDialog.glade", "dialog", null);
            xml.Autoconnect(this);

            Port = P2PManager.Port;

            this.image.Pixbuf = StockIcons.GetPixbuf("Channel");
            this.dialog.ShowAll();
        }
Пример #19
0
 public static void AddView(XML.Objects.Organisation.View view)
 {
     XmlDocument doc = init(parametersFilePath);
     XmlNode parent, node;
     parent = doc.SelectSingleNode("/root/Clients/Client[@name='" + view.Project.Client + "']/Project[@name='" + view.Project + "']");
     XmlDocument tempDoc = new XmlDocument();
     tempDoc.LoadXml("<View name='" + view.Name + "' tag='" + view.Tag + "'></View>");
     node = doc.ImportNode(tempDoc.FirstChild, true);
     parent.AppendChild(node);
     doc.Save(parametersFilePath);
 }
Пример #20
0
        /// Create New Proxy Settings Dialog
        public ProxySettings()
        {
            XML xml = new XML(null, "ProxySettingsDialog.glade", "dialog", null);
            xml.Autoconnect(this);
            this.image.Pixbuf = StockIcons.GetPixbuf("Proxy");

            proxy = new Niry.GUI.Gtk2.ProxySettings();
            this.vbox.PackStart(proxy, true, true, 2);

            this.dialog.ShowAll();
        }
Пример #21
0
 static ImportDialog()
 {
     gxml = new Glade.XML (null,
                   WorkbenchSingleton.GLADEFILE,
                   "ImportDialog",
                   null);
     importDialog = (Dialog) gxml["ImportDialog"];
     typeCombo = (Combo) gxml["typeCombo"];
     formatCombo = (Combo) gxml["formatCombo"];
     okButton = (Button) gxml["okButton"];
 }
Пример #22
0
 public static void Main()
 {
     Application.Init ();
     XML gxml = new XML ("toplevel.glade",
                 "window1",
                 null);
     window = (Window) gxml["window1"];
     item = (MenuItem) gxml["new1"];
     label = (Label) gxml["label1"];
         window.DeleteEvent += new DeleteEventHandler (OnDelete);
     Application.Run ();
 }
		/// <summary>
		/// <see cref="OutputSettingsDialog"/>'s constructor.
		/// </summary>
		/// <param name="parent">
		/// The <see cref="Window"/> this dialog is modal to.
		/// </param>
		public OutputSettingsDialog(Window parent)
		{
			Glade.XML gladeXml = new XML("mathtextrecognizer.glade",
			                             "outputSettingsDialog");
			
			gladeXml.Autoconnect(this);
			
			this.outputSettingsDialog.TransientFor =  parent;
			
			InitializeWidgets();
			
		}
		/// <summary>
		/// <c>LearnSymbolDatabaseChooserDialog</c>'s constructor.
		/// </summary>
		/// <param name="parent">
		/// The dialog's parent dialog, to which it's modal.
		/// </param>
		/// <param name="databases">
		/// The databases the user can choose from.
		/// </param>
		public LearnSymbolDatabaseChooserDialog(Window parent,
		                                        List<DatabaseFileInfo> databases)
		{
			XML gxml = new XML(null, 
			                   "mathtextrecognizer.glade", 
			                   "learnSymbolDatabaseChooserDialog",
			                   null);
			
			gxml.Autoconnect(this);
			
			learnSymbolDatabaseChooserDialog.Modal=true;
			learnSymbolDatabaseChooserDialog.Resizable = false;
			learnSymbolDatabaseChooserDialog.TransientFor = parent;
			
			databaseHash = new Dictionary<string,DatabaseFileInfo>();
			
			optionsTooltips = new Tooltips();
			
			RadioButton groupRB = new RadioButton("group");
			foreach(DatabaseFileInfo databaseInfo in databases)
			{
				// We add a new option per database
				string label = System.IO.Path.GetFileName(databaseInfo.Path);
				RadioButton optionRB = new RadioButton(groupRB, label);
				
				optionRB.Clicked += new EventHandler(OnOptionRBClicked);
				optionsVB.Add(optionRB);
				
				MathTextDatabase database = databaseInfo.Database;
			
				
				optionsTooltips.SetTip(optionRB, 
				                       String.Format("{0}\n{1}",
				                                     database.ShortDescription,
				                                     database.Description),
				                       "database description");
				
				databaseHash.Add(label, databaseInfo);
			}
			
			// We add the option of creating a new database.
			newRB = new RadioButton(groupRB, "Crear nueva base de datos");
			newRB.Clicked += new EventHandler(OnOptionRBClicked);
			optionsVB.Add(newRB);
			optionsTooltips.SetTip(newRB, 
			                       "Te permite crear una base de datos nueva",
			                       "new databse description");
			
			optionsTooltips.Enable();
			
			learnSymbolDatabaseChooserDialog.ShowAll();
		}
		/// <summary>
		/// <see cref="ExpressionItemOptionsDialog"/>'s constructor.
		/// </summary>
		public ExpressionItemOptionsDialog(Window parent, Type expressionType)
		{
			XML gladeXml = new XML("mathtextrecognizer.glade",
			                       "expressionItemOptionsDialog");
			
			gladeXml.Autoconnect(this);
			
			addItemMenu = new AddSubItemMenu(this);
			
			this.expressionItemOptionsDialog.TransientFor = parent;
			
			InitializeWidgets(expressionType);
		}
	private void createCallback(bool succeeded, XML.WebResponse response)
	{
		if (succeeded)
		{
			Debug.Log("Client created!");
			LoginCanvas.SetActive(true);
			this.gameObject.SetActive(false);
		}
		else
		{
			Debug.LogError("Failed to create Client");
		}
	}
Пример #27
0
 public static void AddClientProjectView(Client client, Project project, XML.Objects.Organisation.View view)
 {
     XmlDocument doc = init(parametersFilePath);
     XmlNode parent, node;
     XmlNodeList xmlNodeList = doc.SelectNodes("/root/Clients");
     XmlDocument tempDoc = new XmlDocument();
     parent = doc.SelectSingleNode("/root/Clients");
     tempDoc.LoadXml("<Client name='" + client + "'> <Project name='" + project +
         "'><View name='" + view.Name + "' tag='" + view.Tag + "'></View> </Project> </Client>");
     node = doc.ImportNode(tempDoc.FirstChild, true);
     parent.AppendChild(node);
     doc.Save(parametersFilePath);
 }
		/// <summary>
		/// <see cref="ExpressionRuleCallWidget"/>'s constructor.
		/// </summary>
		/// <param name="container">
		/// A <see cref="IExpressionItemContainer"/>
		/// </param>
		public ExpressionRuleCallWidget(IExpressionItemContainer container) 
			: base(container)
		{
			Glade.XML gladeXml = new XML("mathtextrecognizer.glade",
			                             "expressionRuleWidgetBase");
			
			gladeXml.Autoconnect(this);
			
			this.Add(expressionRuleWidgetBase);
			
			this.HeightRequest = expressionRuleWidgetBase.HeightRequest;
			
			this.ShowAll();
		}
	private void createCallback(bool succeeded, XML.WebResponse response)
	{
		if (succeeded)
		{
			Debug.Log("Game created!");
			ManageGamesCanvas.SetActive(true);
			this.gameObject.SetActive(false);
			ManageGamesManager.Refresh();
		}
		else
		{
			Debug.LogError("Failed to create Game");
		}
	}
Пример #30
0
	private void loginCallback(bool succeeded, XML.WebResponse response)
	{
		if (succeeded)
		{
			Debug.Log("Logged In with ClientID: " + response.ClientID);
			ClientID = new Guid(response.ClientID);
			ClientMainScreenCanvas.SetActive(true);
			this.gameObject.SetActive(false);
		}
		else
		{
			Debug.LogError("Failed to login");
		}
	}
Пример #31
0
        override public void Setup_BeforeAdd(XML xml)
        {
            base.Setup_BeforeAdd(xml);

            string str;

            str = xml.GetAttribute("font");
            if (str != null)
            {
                _textFormat.font = str;
            }

            str = xml.GetAttribute("fontSize");
            if (str != null)
            {
                _textFormat.size = int.Parse(str);
            }

            str = xml.GetAttribute("color");
            if (str != null)
            {
                _textFormat.color = ToolSet.ConvertFromHtmlColor(str);
            }

            str = xml.GetAttribute("align");
            if (str != null)
            {
                this.align = FieldTypes.ParseAlign(str);
            }

            str = xml.GetAttribute("vAlign");
            if (str != null)
            {
                this.verticalAlign = FieldTypes.ParseVerticalAlign(str);
            }

            str = xml.GetAttribute("leading");
            if (str != null)
            {
                _textFormat.lineSpacing = int.Parse(str);
            }

            str = xml.GetAttribute("letterSpacing");
            if (str != null)
            {
                _textFormat.letterSpacing = int.Parse(str);
            }

            _ubbEnabled = xml.GetAttributeBool("ubb", false);

            str = xml.GetAttribute("autoSize");
            if (str != null)
            {
                this.autoSize = FieldTypes.ParseAutoSizeType(str);
            }

            _textFormat.underline = xml.GetAttributeBool("underline", false);
            _textFormat.italic    = xml.GetAttributeBool("italic", false);
            _textFormat.bold      = xml.GetAttributeBool("bold", false);
            this.singleLine       = xml.GetAttributeBool("singleLine", false);
            str = xml.GetAttribute("strokeColor");
            if (str != null)
            {
                this.strokeColor = ToolSet.ConvertFromHtmlColor(str);
                this.stroke      = xml.GetAttributeInt("strokeSize", 1);
            }

            str = xml.GetAttribute("shadowColor");
            if (str != null)
            {
                this.strokeColor  = ToolSet.ConvertFromHtmlColor(str);
                this.shadowOffset = xml.GetAttributeVector("shadowOffset");
            }
        }
Пример #32
0
        /// <summary>
        /// Generates HTML from Script output.
        /// </summary>
        /// <param name="Result">Script output.</param>
        /// <param name="Output">HTML output.</param>
        /// <param name="AloneInParagraph">If the script output is to be presented alone in a paragraph.</param>
        /// <param name="Variables">Current variables.</param>
        public static void GenerateHTML(object Result, StringBuilder Output, bool AloneInParagraph, Variables Variables)
        {
            if (Result is Graph G)
            {
                using (SKImage Bmp = G.CreateBitmap(Variables, out GraphSettings GraphSettings))
                {
                    SKData Data = Bmp.Encode(SKEncodedImageFormat.Png, 100);
                    byte[] Bin  = Data.ToArray();

                    if (AloneInParagraph)
                    {
                        Output.Append("<figure>");
                    }

                    Output.Append("<img border=\"2\" width=\"");
                    Output.Append(GraphSettings.Width.ToString());
                    Output.Append("\" height=\"");
                    Output.Append(GraphSettings.Height.ToString());
                    Output.Append("\" src=\"data:image/png;base64,");
                    Output.Append(Convert.ToBase64String(Bin, 0, Bin.Length));
                    Output.Append("\" />");

                    if (AloneInParagraph)
                    {
                        Output.Append("</figure>");
                    }

                    Data.Dispose();
                }
            }
            else if (Result is SKImage Img)
            {
                using (SKData Data = Img.Encode(SKEncodedImageFormat.Png, 100))
                {
                    byte[] Bin = Data.ToArray();

                    if (AloneInParagraph)
                    {
                        Output.Append("<figure>");
                    }

                    Output.Append("<img border=\"2\" width=\"");
                    Output.Append(Img.Width.ToString());
                    Output.Append("\" height=\"");
                    Output.Append(Img.Height.ToString());
                    Output.Append("\" src=\"data:image/png;base64,");
                    Output.Append(Convert.ToBase64String(Bin, 0, Bin.Length));
                    Output.Append("\" />");

                    if (AloneInParagraph)
                    {
                        Output.Append("</figure>");
                    }
                }
            }
            else if (Result is Exception ex)
            {
                ex = Log.UnnestException(ex);

                if (ex is AggregateException ex2)
                {
                    foreach (Exception ex3 in ex2.InnerExceptions)
                    {
                        Output.Append("<p><font style=\"color:red\">");
                        Output.Append(XML.HtmlValueEncode(ex3.Message));
                        Output.AppendLine("</font></p>");
                    }
                }
                else
                {
                    if (AloneInParagraph)
                    {
                        Output.Append("<p>");
                    }

                    Output.Append("<font style=\"color:red\">");
                    Output.Append(XML.HtmlValueEncode(ex.Message));
                    Output.Append("</font>");

                    if (AloneInParagraph)
                    {
                        Output.Append("</p>");
                    }
                }
            }
            else if (Result is ObjectMatrix M && M.ColumnNames != null)
            {
                Output.Append("<table><thead><tr>");

                foreach (string s2 in M.ColumnNames)
                {
                    Output.Append("<th>");
                    Output.Append(FormatText(XML.HtmlValueEncode(s2)));
                    Output.Append("</th>");
                }

                Output.Append("</tr></thead><tbody>");

                int x, y;

                for (y = 0; y < M.Rows; y++)
                {
                    Output.Append("<tr>");

                    for (x = 0; x < M.Columns; x++)
                    {
                        Output.Append("<td>");

                        object Item = M.GetElement(x, y).AssociatedObjectValue;
                        if (Item != null)
                        {
                            if (Item is string s2)
                            {
                                Output.Append(FormatText(XML.HtmlValueEncode(s2)));
                            }
                            else
                            {
                                Output.Append(FormatText(XML.HtmlValueEncode(Expression.ToString(Item))));
                            }
                        }

                        Output.Append("</td>");
                    }

                    Output.Append("</tr>");
                }

                Output.Append("</tbody></table>");
            }
Пример #33
0
 /// <summary>
 /// Set strings source.
 /// </summary>
 /// <param name="source"></param>
 public static void SetStringsSource(XML source)
 {
     TranslationHelper.LoadFromXML(source);
 }
Пример #34
0
    private static void Main(string[] args)
    //****************************************************************************80
    //
    //  Purpose:
    //
    //    MAIN is the main program for TET_MESH_TO_XML.
    //
    //  Discussion:
    //
    //    TET_MESH_TO_XML converts a tet mesh, using 4 or 10 node
    //    tetrahedral elements, to a DOLFIN XML mesh file.
    //
    //  Usage:
    //
    //    tet_mesh_to_xml prefix
    //
    //    where prefix is the common file prefix:
    //
    //    * prefix_nodes.txt,       the node coordinates;
    //    * prefix_elements.txt,    the linear element definitions.
    //    * prefix.xml,             the DOLFIN XML mesh file.
    //
    //  Licensing:
    //
    //    This code is distributed under the GNU LGPL license.
    //
    //  Modified:
    //
    //    04 June 2013
    //
    //  Author:
    //
    //    John Burkardt
    //
    //  Reference:
    //
    //    Anders Logg, Kent-Andre Mardal, Garth Wells,
    //    Automated Solution of Differential Equations by the Finite Element
    //    Method: The FEniCS Book,
    //    Lecture Notes in Computational Science and Engineering,
    //    Springer, 2011,
    //    ISBN13: 978-3642230981
    //
    {
        string prefix;

        Console.WriteLine("");
        Console.WriteLine("TET_MESH_TO_XML;");
        Console.WriteLine("  Convert a tet mesh to DOLFIN XML format");
        Console.WriteLine("");
        Console.WriteLine("  Read \"prefix\"_nodes.txt, node coordinates.");
        Console.WriteLine("  Read \"prefix\"_elements.txt, 4, 10 or 20 node element definitions.");
        Console.WriteLine("");
        Console.WriteLine("  Create \"prefix\".xml, a corresponding DOLFIN XML mesh file.");
        Console.WriteLine("");
        //
        //  Get the filename prefix.
        //
        try
        {
            prefix = args[0];
        }
        catch
        {
            Console.WriteLine("");
            Console.WriteLine("TET_MESH_TO_XML:");
            Console.WriteLine("  Please enter the filename prefix.");

            prefix = Console.ReadLine();
        }

        //
        //  Create the filenames.
        //
        string node_filename    = prefix + "_nodes.txt";
        string element_filename = prefix + "_elements.txt";
        string xml_filename     = prefix + ".xml";
        //
        //  Read the node data.
        //
        TableHeader h        = typeMethods.r8mat_header_read(node_filename);
        int         dim_num  = h.m;
        int         node_num = h.n;

        if (dim_num != 3)
        {
            Console.WriteLine("");
            Console.WriteLine("TET_MESH_TO_XML; - Fatal error!");
            Console.WriteLine("  The spatial dimension must be 3.");
            return;
        }

        Console.WriteLine("");
        Console.WriteLine("  Read the header of \"" + node_filename + "\".");
        Console.WriteLine("");
        Console.WriteLine("  Spatial dimension = " + dim_num + "");
        Console.WriteLine("  Number of nodes   = " + node_num + "");

        double[] node_xyz = typeMethods.r8mat_data_read(node_filename, dim_num, node_num);

        Console.WriteLine("");
        Console.WriteLine("  Read the data in \"" + node_filename + "\".");

        typeMethods.r8mat_transpose_print_some(dim_num, node_num,
                                               node_xyz, 1, 1, dim_num, 5, "  First 5 nodes:");
        //
        //  Read the element data.
        //
        h = typeMethods.i4mat_header_read(element_filename);
        int element_order = h.m;
        int element_num   = h.n;

        switch (element_order)
        {
        case 4:
            break;

        case 10:
            break;

        case 20:
            break;

        default:
            Console.WriteLine("");
            Console.WriteLine("TET_MESH_TO_XML - Fatal error!");
            Console.WriteLine("  The tet mesh must have order 4, 10, or 20.");
            return;
        }

        Console.WriteLine("");
        Console.WriteLine("  Read the header of \"" + element_filename + "\".");
        Console.WriteLine("");
        Console.WriteLine("  Element order = " + element_order + "");
        Console.WriteLine("  Number of elements  = " + element_num + "");

        int[] element_node = typeMethods.i4mat_data_read(element_filename, element_order,
                                                         element_num);

        Console.WriteLine("");
        Console.WriteLine("  Read the data in \"" + element_filename + "\".");

        typeMethods.i4mat_transpose_print_some(element_order, element_num,
                                               element_node, 1, 1, element_order, 5, "  First 5 elements:");
        //
        //  Use 0-based indexing.
        //
        TetMesh.tet_mesh_base_zero(node_num, element_order, element_num, ref element_node);
        //
        //  Write the DOLFIN XML file.
        //
        XML.xml_write(xml_filename, dim_num, node_num, node_xyz, element_order,
                      element_num, element_node);

        Console.WriteLine("");
        Console.WriteLine("  Created XML file \"" + xml_filename + "\".");

        Console.WriteLine("");
        Console.WriteLine("TET_MESH_TO_XML;");
        Console.WriteLine("  Normal end of execution.");
        Console.WriteLine("");
    }
Пример #35
0
        public void Setup(XML xml)
        {
            string str;

            _controller = _owner.parent.GetController(xml.GetAttribute("controller"));
            if (_controller == null)
            {
                return;
            }

            Init();

            str = xml.GetAttribute("tween");
            if (str != null)
            {
                tween = true;
            }

            str = xml.GetAttribute("ease");
            if (str != null)
            {
                easeType = FieldTypes.ParseEaseType(str);
            }

            str = xml.GetAttribute("duration");
            if (str != null)
            {
                tweenTime = float.Parse(str);
            }

            str = xml.GetAttribute("delay");
            if (str != null)
            {
                delay = float.Parse(str);
            }

            if (this is GearDisplay)
            {
                string[] pages = xml.GetAttributeArray("pages");
                if (pages != null)
                {
                    ((GearDisplay)this).pages.AddRange(pages);
                }
            }
            else
            {
                string[] pages  = xml.GetAttributeArray("pages");
                string[] values = xml.GetAttributeArray("values", '|');

                if (pages != null && values != null)
                {
                    for (int i = 0; i < values.Length; i++)
                    {
                        str = values[i];
                        if (str != "-")
                        {
                            AddStatus(pages[i], str);
                        }
                    }
                }
                str = xml.GetAttribute("default");
                if (str != null)
                {
                    AddStatus(null, str);
                }
            }
        }
Пример #36
0
        private void ChatMessageReceived(object P)
        {
            MessageEventArgs e = (MessageEventArgs)P;
            ChatView         ChatView;

            string Message    = e.Body;
            bool   IsMarkdown = false;

            foreach (XmlNode N in e.Message.ChildNodes)
            {
                if (N.LocalName == "content" && N.NamespaceURI == "urn:xmpp:content")
                {
                    string Type = XML.Attribute((XmlElement)N, "type");
                    if (Type == "text/markdown")
                    {
                        IsMarkdown = true;

                        Type = N.InnerText;
                        if (!string.IsNullOrEmpty(Type))
                        {
                            Message = Type;
                        }

                        break;
                    }
                }
            }

            foreach (TabItem TabItem in this.Tabs.Items)
            {
                ChatView = TabItem.Content as ChatView;
                if (ChatView == null)
                {
                    continue;
                }

                XmppContact XmppContact = ChatView.Node as XmppContact;
                if (XmppContact == null)
                {
                    continue;
                }

                if (XmppContact.BareJID != e.FromBareJID)
                {
                    continue;
                }

                XmppAccountNode XmppAccountNode = XmppContact.XmppAccountNode;
                if (XmppAccountNode == null)
                {
                    continue;
                }

                if (XmppAccountNode.BareJID != XmppClient.GetBareJID(e.To))
                {
                    continue;
                }

                ChatView.ChatMessageReceived(Message, IsMarkdown, this);
                return;
            }

            foreach (TreeNode Node in this.MainView.ConnectionTree.Items)
            {
                XmppAccountNode XmppAccountNode = Node as XmppAccountNode;
                if (XmppAccountNode == null)
                {
                    continue;
                }

                if (XmppAccountNode.BareJID != XmppClient.GetBareJID(e.To))
                {
                    continue;
                }

                if (XmppAccountNode.TryGetChild(e.FromBareJID, out TreeNode ContactNode))
                {
                    TabItem TabItem2 = MainWindow.NewTab(e.FromBareJID);
                    this.Tabs.Items.Add(TabItem2);

                    ChatView         = new ChatView(ContactNode);
                    TabItem2.Content = ChatView;

                    ChatView.ChatMessageReceived(Message, IsMarkdown, this);
                    return;
                }
            }
        }
Пример #37
0
        public void AddQuestion(
            string question,
            string answer1,
            bool answer1IsTrue,
            string answer2,
            bool answer2IsTrue,
            string answer3,
            bool answer3IsTrue,
            string answer4,
            bool answer4IsTrue)
        {
            List <Answer> answers   = new List <Answer>();
            XML           questions = new XML().Deserialize();

            bool questionExistInDB = questions.QuestionsList.Any(q => q.Values == question);

            if (questionExistInDB)
            {
                ViewModelMessageWindow messageWindow = new ViewModelMessageWindow();
                messageWindow.SendMessage("\n\nTakie pytanie już istenieje!");
                messageWindow.OpenWindow(300, 200);
                return;
            }

            Answer answerFirst = new Answer
            {
                Id   = 1,
                IsOk = answer1IsTrue,
                Name = answer1
            };

            Answer answerSecond = new Answer
            {
                Id   = 2,
                IsOk = answer2IsTrue,
                Name = answer2
            };

            Answer answerThird = new Answer
            {
                Id   = 3,
                IsOk = answer3IsTrue,
                Name = answer3
            };

            Answer answerFourth = new Answer
            {
                Id   = 4,
                IsOk = answer4IsTrue,
                Name = answer4
            };

            answers.Add(answerFirst);
            answers.Add(answerSecond);
            answers.Add(answerThird);
            answers.Add(answerFourth);

            questions.QuestionsList.Add(
                new XML.Question()
            {
                Id     = questions.QuestionsList.Count + 1,
                Values = question,
                Items  = answers
            });


            XML.Serialize(questions);

            Messenger.Default.Send <RefreshQuestions>(new RefreshQuestions
            {
                Refresh = true
            });

            ViewModelMessageWindow message = new ViewModelMessageWindow();

            message.SendMessage("\n\nPytanie zostało dodane.");
            message.OpenWindow(300, 200);
        }
Пример #38
0
        public void Setup(XML xml)
        {
            string str;

            _controller = _owner.parent.GetController(xml.GetAttribute("controller"));
            if (_controller == null)
            {
                return;
            }

            Init();

            str = xml.GetAttribute("tween");
            if (str != null)
            {
                tween = true;
            }

            str = xml.GetAttribute("ease");
            if (str != null)
            {
                easeType = EaseTypeUtils.ParseEaseType(str);
            }

            str = xml.GetAttribute("duration");
            if (str != null)
            {
                tweenTime = float.Parse(str);
            }

            str = xml.GetAttribute("delay");
            if (str != null)
            {
                delay = float.Parse(str);
            }

            if (this is GearDisplay)
            {
                string[] pages = xml.GetAttributeArray("pages");
                if (pages != null)
                {
                    ((GearDisplay)this).pages = pages;
                }
            }
            else
            {
                string[] pages  = xml.GetAttributeArray("pages");
                string[] values = xml.GetAttributeArray("values", '|');

                if (pages != null)
                {
                    int cnt1 = pages.Length;
                    int cnt2 = values != null ? values.Length : 0;
                    for (int i = 0; i < cnt1; i++)
                    {
                        if (i < cnt2)
                        {
                            str = values[i];
                        }
                        else
                        {
                            str = string.Empty;
                        }
                        AddStatus(pages[i], str);
                    }
                }
                str = xml.GetAttribute("default");
                if (str != null)
                {
                    AddStatus(null, str);
                }
            }
        }
Пример #39
0
 internal Item(XmlElement E)
 {
     this.jid  = XML.Attribute(E, "jid");
     this.node = XML.Attribute(E, "node");
     this.name = XML.Attribute(E, "name");
 }
Пример #40
0
        static void Main(string[] args)
        {
            //Set the path of the file containing the data set
            //string dataFilePath = @"C:\Users\kevin\Desktop\squaredtest.csv"; NutrioxDataset
            string dataFilePath = @"C:\Users\Bruker\Desktop\NutrioxDataset.csv";

            //string dataFilePath = @"C:\Users\Bruker\Desktop\-5to5-200Rows.csv";

            //Create a new data set
            DataSet.DataSet dataSet = new DataSet.DataSet(dataFilePath, true);

            //Apply desired data preprocessing to the data set
            dataSet.PreProcessDataSet(NormalizationType.MinMax, 2, EncodingType.None, null);

            //Create a model hyperparameter layer structure
            LayerStructure layerStructure = new LayerStructure()
            {
                numberOfInputNodes = 2, HiddenLayerList = new List <int> {
                    5, 5
                }, numberOfOutputNodes = 1
            };

            //Create an instance of the desired optimalization strategy to use

            var regularizationStrategyFactory = new RegularizationStrategyFactory();
            StochasticGradientDescent SGD     = new StochasticGradientDescent(new SigmoidFunction(), new IdentityFunction(), new MeanSquaredError(), RegularizationType.None, regularizationStrategyFactory);

            //Create training hyperparameters
            TrainingParameters trainingParams = new TrainingParameters()
            {
                epochs = 500, learningRate = 0.01, momentum = 0.01, RegularizationLambda = 0.00
            };

            //Create an instance of a neural network
            //ArtificialNeuralNetwork ann = new ArtificialNeuralNetwork(layerStructure, trainingParams, dataSet, SGD, new GaussianDistribution());

            //Or Load a Network from XML

            XML xml = new XML();

            ArtificialNeuralNetwork ann = xml.LoadNetwork(@"C:\Users\Bruker\Desktop\BestNet.xml", dataSet) as ArtificialNeuralNetwork;

            //Apply the desired training/test data set split ratios.
            ann.SplitDataSetIntoTrainAndTestSets(0.7);

            //Initiate network training
            //ann.TrainNetwork();

            var crossValidationStrategyFactory = new CrossValidationStrategyFactory();
            NetworkEvaluator evaluator         = new NetworkEvaluator(ann);
            CrossValidator   crossValidator    = new CrossValidator(ann, evaluator, crossValidationStrategyFactory);

            //Cross-validate the fitted model
            //crossValidator.KFold(10, 0.007);

            //Evaluate the fitted model on the test set
            evaluator.EvaluateNetwork(0.007);


            //--Optional--//

            //Serialize and save the fitted model

            //XML xml = new XML();
            //xml.SaveNetwork(dataFilePath, ann);

            //Extract model information

            //ann.SaveListOfErrors();

            //ann.GetApproximatedFunction(ann.SavePath + "/Function.txt");

            Console.ReadLine();
        }
Пример #41
0
 public void Add(XML xml)
 {
     rawList.Add(xml);
 }
Пример #42
0
        /// <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) == 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;
                }

                this.BodyReceived(XmlResponse, true);
            }
            catch (Exception ex)
            {
                this.bindingInterface.ConnectionError(ex);
            }
        }
Пример #43
0
        private bool UpdateRoster(out string[] removed, out string[] added, out RichTextWindow window)
        {
            this._state = RosterState.FetchingMembers;
            removed     = new string[0];
            added       = new string[0];
            window      = null;

            DateTime      startTime  = DateTime.Now;
            List <string> oldMembers = new List <string>();
            List <string> newMembers = new List <string>();

            using (IDbCommand command = this._database.Connection.CreateCommand())
            {
                command.CommandText = "SELECT ID FROM organizations";
                IDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    try
                    {
                        int id = (int)reader.GetInt64(0);
                        OrganizationResult org = XML.GetOrganization(id, this._bot.Dimension, false, true);
                        if (org == null || org.Members == null || org.Members.Items == null || org.Members.Items.Length == 0)
                        {
                            throw new Exception();
                        }

                        foreach (OrganizationMember member in org.Members.Items)
                        {
                            newMembers.Add(member.Nickname);
                        }
                    }
                    catch
                    {
                        reader.Close(); return(false);
                    }
                }
                reader.Close();
            }

            using (IDbCommand command = this._database.Connection.CreateCommand())
            {
                command.CommandText = "SELECT Username FROM members";
                IDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    try
                    {
                        string name = reader.GetString(0);
                        oldMembers.Add(name);
                    }
                    catch { }
                }
                reader.Close();
            }
            this._state         = RosterState.CrossCheckingMembers;
            this._progressMax   = newMembers.Count + oldMembers.Count;
            this._progressValue = 0;
            List <string> addMembers    = new List <string>();
            List <string> removeMembers = new List <string>();

            foreach (string member in newMembers)
            {
                if (!oldMembers.Contains(member))
                {
                    addMembers.Add(member);
                    this._bot.GetMainBot().SendNameLookup(member);
                }
                this._progressValue++;
            }
            foreach (string member in oldMembers)
            {
                if (!newMembers.Contains(member))
                {
                    removeMembers.Add(member);
                }
                this._progressValue++;
            }

            this._state         = RosterState.RemovingMembers;
            this._progressMax   = removeMembers.Count;
            this._progressValue = 0;
            foreach (string member in removeMembers)
            {
                this._bot.Users.RemoveUser(member);
                this._bot.Users.RemoveAlt(member);
                this._bot.FriendList.Remove("notify", member);
                this._database.ExecuteNonQuery("DELETE FROM members WHERE Username = '******'");
                this._progressValue++;
            }

            this._state         = RosterState.AddingMembers;
            this._progressMax   = addMembers.Count;
            this._progressValue = 0;

            List <string> failed = new List <string>();

            foreach (string member in addMembers)
            {
                if (this._bot.Users.AddUser(member, UserLevel.Member))
                {
                    this._bot.FriendList.Add("notify", member);
                    this._database.ExecuteNonQuery("INSERT INTO members VALUES ('" + member + "', 0)");
                }
                else
                {
                    failed.Add(member);
                }
                this._progressValue++;
            }
            foreach (string member in failed)
            {
                addMembers.Remove(member);
            }

            added   = addMembers.ToArray();
            removed = removeMembers.ToArray();
            TimeSpan elapsed = DateTime.Now - startTime;

            window = new RichTextWindow(this._bot);
            window.AppendTitle("Roster Update Report");
            window.AppendHighlight("Processing Time: ");
            window.AppendNormal(String.Format("{0:00}:{1:00}:{2:00}", Math.Floor(elapsed.TotalHours), elapsed.Minutes, elapsed.Seconds));
            window.AppendLineBreak();
            window.AppendHighlight("Members Added: ");
            window.AppendNormal(added.Length.ToString());
            window.AppendLineBreak();
            window.AppendHighlight("Members Removed: ");
            window.AppendNormal(removed.Length.ToString());
            window.AppendLineBreak();
            if (added.Length > 0)
            {
                window.AppendLineBreak();
                window.AppendHeader("Added Members");
                foreach (string member in added)
                {
                    window.AppendHighlight(member);
                    window.AppendLineBreak();
                }
            }
            if (removed.Length > 0)
            {
                window.AppendLineBreak();
                window.AppendHeader("Removed Members");
                foreach (string member in removed)
                {
                    window.AppendHighlight(member);
                    window.AppendLineBreak();
                }
            }
            this._state = RosterState.Idle;
            return(true);
        }
Пример #44
0
        internal static void ParseResultSet(int Offset, int MaxCount, object Sender, IqResultEventArgs e, SearchResultEventHandler Callback, object State)
        {
            List <SearchResultThing> Things   = new List <SearchResultThing>();
            List <MetaDataTag>       MetaData = new List <MetaDataTag>();
            ThingReference           Node;
            XmlElement E = e.FirstElement;
            XmlElement E2, E3;
            string     Jid;
            string     OwnerJid;
            string     NodeId;
            string     SourceId;
            string     Partition;
            string     Name;
            bool       More = false;

            if (e.Ok && E != null && E.LocalName == "found" && E.NamespaceURI == NamespaceDiscovery)
            {
                More = XML.Attribute(E, "more", false);

                foreach (XmlNode N in E.ChildNodes)
                {
                    E2 = N as XmlElement;
                    if (E2.LocalName == "thing" && E2.NamespaceURI == NamespaceDiscovery)
                    {
                        Jid       = XML.Attribute(E2, "jid");
                        OwnerJid  = XML.Attribute(E2, "owner");
                        NodeId    = XML.Attribute(E2, "id");
                        SourceId  = XML.Attribute(E2, "src");
                        Partition = XML.Attribute(E2, "pt");

                        if (string.IsNullOrEmpty(NodeId) && string.IsNullOrEmpty(SourceId) && string.IsNullOrEmpty(Partition))
                        {
                            Node = ThingReference.Empty;
                        }
                        else
                        {
                            Node = new ThingReference(NodeId, SourceId, Partition);
                        }

                        MetaData.Clear();
                        foreach (XmlNode N2 in E2.ChildNodes)
                        {
                            E3 = N2 as XmlElement;
                            if (E3 == null)
                            {
                                continue;
                            }

                            Name = XML.Attribute(E3, "name");

                            switch (E3.LocalName)
                            {
                            case "str":
                                MetaData.Add(new MetaDataStringTag(Name, XML.Attribute(E3, "value")));
                                break;

                            case "num":
                                MetaData.Add(new MetaDataNumericTag(Name, XML.Attribute(E3, "value", 0.0)));
                                break;
                            }
                        }

                        Things.Add(new SearchResultThing(Jid, OwnerJid, Node, MetaData.ToArray()));
                    }
                }
            }

            if (Callback != null)
            {
                SearchResultEventArgs e2 = new SearchResultEventArgs(e, State, Offset, MaxCount, More, Things.ToArray());

                try
                {
                    Callback(Sender, e2);
                }
                catch (Exception ex)
                {
                    Log.Critical(ex);
                }
            }
        }
Пример #45
0
 public void Save(string path = null)
 {
     XML.Serialize(path ?? CONFIG_PATH, this);
 }
Пример #46
0
        private void QueryHandler(object Sender, IqEventArgs e)
        {
            string     StreamId = XML.Attribute(e.Query, "sid");
            XmlElement E;

            if (string.IsNullOrEmpty(StreamId) || StreamId != Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(StreamId)))
            {
                throw new NotAcceptableException("Invalid Stream ID.", e.IQ);
            }

            string Host = null;
            string JID  = null;
            int    Port = 0;

            foreach (XmlNode N in e.Query.ChildNodes)
            {
                E = N as XmlElement;
                if (E == null)
                {
                    continue;
                }

                if (E.LocalName == "streamhost" && E.NamespaceURI == Namespace)
                {
                    Host = XML.Attribute(E, "host");
                    JID  = XML.Attribute(E, "jid");
                    Port = XML.Attribute(E, "port", 0);

                    break;
                }
            }

            if (string.IsNullOrEmpty(JID) || string.IsNullOrEmpty(Host) || Port <= 0 || Port >= 0x10000)
            {
                throw new BadRequestException("Invalid parameters.", e.IQ);
            }

            ValidateStreamEventHandler h  = this.OnOpen;
            ValidateStreamEventArgs    e2 = new ValidateStreamEventArgs(this.client, e, StreamId);

            if (h != null)
            {
                try
                {
                    h(this, e2);
                }
                catch (Exception ex)
                {
                    Log.Critical(ex);
                }
            }

            if (e2.DataCallback == null || e2.CloseCallback == null)
            {
                throw new NotAcceptableException("Stream not expected.", e.IQ);
            }

            Socks5Client Client;

            lock (this.streams)
            {
                if (this.streams.ContainsKey(StreamId))
                {
                    throw new ConflictException("Stream already exists.", e.IQ);
                }

                Client = new Socks5Client(Host, Port, JID)
                {
                    CallbackState = e2.State
                };

                this.streams[StreamId] = Client;
            }

            Client.Tag = new Socks5QueryState()
            {
                streamId   = StreamId,
                eventargs  = e,
                eventargs2 = e2
            };

            Client.OnDataReceived += e2.DataCallback;
            Client.OnStateChange  += this.ClientStateChanged;
        }
Пример #47
0
        private bool Listener_OnCommand(UserInfo user, string message)
        {
            // !online
            if (message.ToLower() == "!online")
            {
                string   reply  = string.Empty;
                string[] online = this.Bot.FriendList.Online("notify");
                if (online.Length == 0)
                {
                    reply += "No users online.";
                }
                else
                {
                    reply += "Online: " + string.Join(", ", online) + ".";
                }

                if (this.RelayMode == "guest" || this.RelayMode == "both")
                {
                    Dictionary <UInt32, Friend> list = this.Bot.PrivateChannel.List();
                    List <string> guests             = new List <string>();
                    foreach (KeyValuePair <UInt32, Friend> guest in list)
                    {
                        guests.Add(Format.UppercaseFirst(guest.Value.User));
                    }
                    if (guests.Count > 0)
                    {
                        reply += " Guests: " + string.Join(", ", guests.ToArray());
                    }
                }
                IRCQueue.Enqueue(Plugins.IRCQueue.Priority.High, new Plugins.IRCQueue.IRCQueueItem(user.Nick, reply));
                return(true);
            }

            // !is and !whois
            if (message.Trim().Contains(" "))
            {
                string[] parts    = message.Trim().Split(' ');
                string   command  = parts[0];
                string   username = parts[1];
                switch (command)
                {
                case "!is":
                    UInt32      userid = this.Bot.GetUserID(username);
                    OnlineState state  = this.Bot.FriendList.IsOnline(userid);
                    if (state == OnlineState.Timeout)
                    {
                        IRCQueue.Enqueue(Plugins.IRCQueue.Priority.High, new Plugins.IRCQueue.IRCQueueItem(user.Nick, "Request timed out. Please try again later"));
                        return(true);
                    }
                    if (state == OnlineState.Unknown)
                    {
                        IRCQueue.Enqueue(Plugins.IRCQueue.Priority.High, new Plugins.IRCQueue.IRCQueueItem(user.Nick, "No such user: "******"Online";
                    if (state == OnlineState.Offline)
                    {
                        append = "Offline";
                        Int64 seen = this.Bot.FriendList.Seen(username);
                        if (seen > 1)
                        {
                            append += " and was last seen online at " + Format.DateTime(seen, FormatStyle.Large) + " GMT";
                        }
                    }
                    IRCQueue.Enqueue(Plugins.IRCQueue.Priority.High, new Plugins.IRCQueue.IRCQueueItem(user.Nick, String.Format("{0} is currently {1}", Format.UppercaseFirst(username), append)));
                    break;

                case "!whois":
                    if (this.Bot.GetUserID(username) < 100)
                    {
                        IRCQueue.Enqueue(Plugins.IRCQueue.Priority.High, new Plugins.IRCQueue.IRCQueueItem(user.Nick, "No such user: "******"Unable to gather information on that user"));
                        return(true);
                    }
                    IRCQueue.Enqueue(Plugins.IRCQueue.Priority.High, new Plugins.IRCQueue.IRCQueueItem(user.Nick, Format.Whois(whois, FormatStyle.Large)));
                    break;
                }
            }
            return(false);
        }
Пример #48
0
        /// <summary>
        /// Sets properties and attributes of class in accordance with XML definition.
        /// </summary>
        /// <param name="Definition">XML definition</param>
        public override Task FromXml(XmlElement Definition)
        {
            this.componentAddress = XML.Attribute(Definition, "componentAddress");

            return(base.FromXml(Definition));
        }
Пример #49
0
        /// <summary>
        /// Sets properties and attributes of class in accordance with XML definition.
        /// </summary>
        /// <param name="Definition">XML definition</param>
        public override Task FromXml(XmlElement Definition)
        {
            this.rsaKeyName = XML.Attribute(Definition, "rsaKeyName");

            return(base.FromXml(Definition));
        }
Пример #50
0
        private void InitiationResponse(object Sender, IqResultEventArgs e)
        {
            InitiationRec Rec = (InitiationRec)e.State;

            if (e.Ok)
            {
                XmlElement E = e.FirstElement;

                if (E != null && E.LocalName == "query" && E.NamespaceURI == Namespace && XML.Attribute(E, "sid") == Rec.streamId)
                {
                    XmlElement E2;
                    string     StreamHostUsed = null;

                    foreach (XmlNode N in E.ChildNodes)
                    {
                        E2 = N as XmlElement;
                        if (E2.LocalName == "streamhost-used" && E2.NamespaceURI == Namespace)
                        {
                            StreamHostUsed = XML.Attribute(E2, "jid");
                            break;
                        }
                    }

                    if (!string.IsNullOrEmpty(StreamHostUsed) && StreamHostUsed == this.host)
                    {
                        Rec.stream = new Socks5Client(this.host, this.port, this.jid);
                        Rec.stream.OnStateChange += Rec.StateChanged;

                        lock (this.streams)
                        {
                            this.streams[Rec.streamId] = Rec.stream;
                        }
                    }
                    else
                    {
                        this.Callback(Rec.callback, Rec.state, false, null, Rec.streamId);
                    }
                }
                else
                {
                    this.Callback(Rec.callback, Rec.state, false, null, Rec.streamId);
                }
            }
            else
            {
                this.Callback(Rec.callback, Rec.state, false, null, Rec.streamId);
            }
        }
Пример #51
0
        /// <summary>
        /// Executes the POST method on the resource.
        /// </summary>
        /// <param name="Request">HTTP Request</param>
        /// <param name="Response">HTTP Response</param>
        /// <exception cref="HttpException">If an error occurred when processing the method.</exception>
        public async Task POST(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request, "Admin.Data.Backup");

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            object Obj = Request.DecodeData();

            if (!(Obj is Dictionary <string, object> Parameters))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("repair", out Obj) || !(Obj is bool Repair))
            {
                throw new BadRequestException();
            }

            if (!CanStartAnalyzeDB())
            {
                Response.StatusCode    = 409;
                Response.StatusMessage = "Conflict";
                Response.ContentType   = "text/plain";
                await Response.Write("Analysis is underway.");
            }

            string BasePath = Export.FullExportFolder;

            if (!Directory.Exists(BasePath))
            {
                Directory.CreateDirectory(BasePath);
            }

            BasePath += Path.DirectorySeparatorChar;

            string FullFileName = Path.Combine(BasePath, "DBReport " + DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss"));

            FullFileName = StartExport.GetUniqueFileName(FullFileName, ".xml");
            FileStream fs = null;

            try
            {
                fs = new FileStream(FullFileName, FileMode.Create, FileAccess.Write);
                DateTime  Created   = File.GetCreationTime(FullFileName);
                XmlWriter XmlOutput = XmlWriter.Create(fs, XML.WriterSettings(true, false));
                string    FileName  = FullFileName.Substring(BasePath.Length);

                Task _ = Task.Run(() => DoAnalyze(FullFileName, FileName, Created, XmlOutput, fs, Repair));

                Response.StatusCode  = 200;
                Response.ContentType = "text/plain";
                await Response.Write(FileName);

                await Response.SendResponse();
            }
            catch (Exception ex)
            {
                if (!(fs is null))
                {
                    fs.Dispose();
                    File.Delete(FullFileName);
                }

                await Response.SendResponse(ex);
            }
        }
Пример #52
0
 /// <summary>
 /// Generates HTML for the markdown element.
 /// </summary>
 /// <param name="Output">HTML will be output here.</param>
 public override void GenerateHTML(StringBuilder Output)
 {
     Output.Append("<code>");
     Output.Append(XML.HtmlValueEncode(this.code));
     Output.Append("</code>");
 }
Пример #53
0
        public void SetToXml(string xmlFile)
        {
            if (xmlFile.Equals("Clear all", StringComparison.OrdinalIgnoreCase))
            {
                foreach (ListViewItem item in listViewExternalCommands.Items)
                {
                    item.SubItems[1].Text = String.Empty;
                }

                return;
            }

            string fileName = Path.Combine(Common.FolderSTB, xmlFile + ".xml");

            XmlDocument doc = new XmlDocument();

            doc.Load(fileName);

            XmlNodeList nodeList = doc.DocumentElement.ChildNodes;

            string       command;
            BlastCommand blastCommand;

            bool   useForAllBlastCommands = false;
            string useForAllBlasterPort   = String.Empty;

            int blastCommandCount = 0;

            for (int i = 0; i < 12; i++)
            {
                if (i == 10)
                {
                    command = XML.GetString(nodeList, "SelectCommand", String.Empty);
                }
                else if (i == 11)
                {
                    command = XML.GetString(nodeList, "PreChangeCommand", String.Empty);
                }
                else
                {
                    command = XML.GetString(nodeList, String.Format("Digit{0}", i), String.Empty);
                }

                if (command.StartsWith(Common.CmdPrefixSTB, StringComparison.OrdinalIgnoreCase))
                {
                    blastCommandCount++;
                }
            }

            for (int i = 0; i < 12; i++)
            {
                if (i == 10)
                {
                    command = XML.GetString(nodeList, "SelectCommand", String.Empty);
                }
                else if (i == 11)
                {
                    command = XML.GetString(nodeList, "PreChangeCommand", String.Empty);
                }
                else
                {
                    command = XML.GetString(nodeList, String.Format("Digit{0}", i), String.Empty);
                }

                if (command.StartsWith(Common.CmdPrefixSTB, StringComparison.OrdinalIgnoreCase))
                {
                    blastCommand = new BlastCommand(
                        TV2BlasterPlugin.BlastIR,
                        Common.FolderSTB,
                        TV2BlasterPlugin.TransceiverInformation.Ports,
                        command.Substring(Common.CmdPrefixSTB.Length),
                        blastCommandCount--);

                    if (useForAllBlastCommands)
                    {
                        blastCommand.BlasterPort = useForAllBlasterPort;
                        listViewExternalCommands.Items[i].SubItems[1].Text = Common.CmdPrefixSTB + blastCommand.CommandString;
                    }
                    else
                    {
                        if (blastCommand.ShowDialog(this) == DialogResult.OK)
                        {
                            if (blastCommand.UseForAll)
                            {
                                useForAllBlastCommands = true;
                                useForAllBlasterPort   = blastCommand.BlasterPort;
                            }
                            listViewExternalCommands.Items[i].SubItems[1].Text = Common.CmdPrefixSTB + blastCommand.CommandString;
                        }
                        else
                        {
                            blastCommand = new BlastCommand(
                                TV2BlasterPlugin.BlastIR,
                                Common.FolderSTB,
                                TV2BlasterPlugin.TransceiverInformation.Ports,
                                command.Substring(Common.CmdPrefixSTB.Length));

                            listViewExternalCommands.Items[i].SubItems[1].Text = Common.CmdPrefixSTB + blastCommand.CommandString;
                        }
                    }
                }
                else
                {
                    listViewExternalCommands.Items[i].SubItems[1].Text = command;
                }
            }

            numericUpDownPauseTime.Value =
                new Decimal(XML.GetInt(nodeList, "PauseTime", Decimal.ToInt32(numericUpDownPauseTime.Value)));
            checkBoxUsePreChange.Checked = XML.GetBool(nodeList, "UsePreChangeCommand", checkBoxUsePreChange.Checked);
            checkBoxSendSelect.Checked   = XML.GetBool(nodeList, "SendSelect", checkBoxSendSelect.Checked);
            checkBoxDoubleSelect.Checked = XML.GetBool(nodeList, "DoubleChannelSelect", checkBoxDoubleSelect.Checked);
            numericUpDownRepeat.Value    =
                new Decimal(XML.GetInt(nodeList, "RepeatChannelCommands", Decimal.ToInt32(numericUpDownRepeat.Value)));
            numericUpDownRepeatDelay.Value =
                new Decimal(XML.GetInt(nodeList, "RepeatDelay", Decimal.ToInt32(numericUpDownRepeatDelay.Value)));

            int digitsWas = comboBoxChDigits.SelectedIndex;

            if (digitsWas > 0)
            {
                digitsWas--;
            }
            int digits = XML.GetInt(nodeList, "ChannelDigits", digitsWas);

            if (digits > 0)
            {
                digits++;
            }
            comboBoxChDigits.SelectedIndex = digits;
        }
Пример #54
0
        public void Load(XmlDocument Xml, string FileName)
        {
            XmlElement E;
            DateTime   Timestamp;
            Color      ForegroundColor;
            Color      BackgroundColor;
            string     Message;

            byte[] Data;
            bool   IsData;

            XSL.Validate(FileName, Xml, sniffRoot, sniffNamespace, schema);

            this.SnifferListView.Items.Clear();

            foreach (XmlNode N in Xml.DocumentElement.ChildNodes)
            {
                E = N as XmlElement;
                if (E is null)
                {
                    continue;
                }

                if (!Enum.TryParse <SniffItemType>(E.LocalName, out SniffItemType Type))
                {
                    continue;
                }

                Timestamp = XML.Attribute(E, "timestamp", DateTime.MinValue);

                switch (Type)
                {
                case SniffItemType.DataReceived:
                    ForegroundColor = Colors.White;
                    BackgroundColor = Colors.Navy;
                    IsData          = true;
                    break;

                case SniffItemType.DataTransmitted:
                    ForegroundColor = Colors.Black;
                    BackgroundColor = Colors.White;
                    IsData          = true;
                    break;

                case SniffItemType.TextReceived:
                    ForegroundColor = Colors.White;
                    BackgroundColor = Colors.Navy;
                    IsData          = false;
                    break;

                case SniffItemType.TextTransmitted:
                    ForegroundColor = Colors.Black;
                    BackgroundColor = Colors.White;
                    IsData          = false;
                    break;

                case SniffItemType.Information:
                    ForegroundColor = Colors.Yellow;
                    BackgroundColor = Colors.DarkGreen;
                    IsData          = false;
                    break;

                case SniffItemType.Warning:
                    ForegroundColor = Colors.Black;
                    BackgroundColor = Colors.Yellow;
                    IsData          = false;
                    break;

                case SniffItemType.Error:
                    ForegroundColor = Colors.Yellow;
                    BackgroundColor = Colors.Red;
                    IsData          = false;
                    break;

                case SniffItemType.Exception:
                    ForegroundColor = Colors.Yellow;
                    BackgroundColor = Colors.DarkRed;
                    IsData          = false;
                    break;

                default:
                    continue;
                }

                if (IsData)
                {
                    Data    = System.Convert.FromBase64String(E.InnerText);
                    Message = TabSniffer.HexToString(Data);
                }
                else
                {
                    Data    = null;
                    Message = E.InnerText;
                }

                this.Add(new SniffItem(Type, Message, Data, ForegroundColor, BackgroundColor));
            }
        }
Пример #55
0
        public override void ConstructFromXML(XML xml)
        {
            base.ConstructFromXML(xml);

            bg = (GImage)this.GetChild("bg");
        }
Пример #56
0
        private void BodyReceived(string Xml, bool First)
        {
            string Body;
            int    i, j;

            i = Xml.IndexOf("<body");
            if (i >= 0)
            {
                i = Xml.IndexOf('>', i + 5);
                if (i > 0)
                {
                    Body = Xml.Substring(0, i + 1);

                    if (Xml[i - 1] == '/')
                    {
                        Xml = null;
                    }
                    else
                    {
                        Body += "</body>";

                        j = Xml.LastIndexOf("</body");
                        if (i < 0)
                        {
                            Xml = Xml.Substring(i + 1);
                        }
                        else
                        {
                            Xml = Xml.Substring(i + 1, j - i - 1).Trim();
                        }
                    }

                    bool        Terminate    = false;
                    string      Condition    = null;
                    string      To           = null;
                    string      From         = null;
                    string      Version      = null;
                    string      Language     = null;
                    string      StreamPrefix = "stream";
                    XmlDocument BodyDoc      = new XmlDocument();
                    LinkedList <KeyValuePair <string, string> > Namespaces = null;
                    BodyDoc.LoadXml(Body);

                    foreach (XmlAttribute Attr in BodyDoc.DocumentElement.Attributes)
                    {
                        switch (Attr.Name)
                        {
                        case "type":
                            if (Attr.Value == "terminate")
                            {
                                Terminate = true;
                            }
                            break;

                        case "condition":
                            Condition = Attr.Value;
                            break;

                        case "xml:lang":
                            Language = Attr.Value;
                            break;

                        default:
                            if (Attr.Prefix == "xmlns")
                            {
                                if (Attr.Value == XmppClient.NamespaceStream)
                                {
                                    StreamPrefix = Attr.LocalName;
                                }
                                else
                                {
                                    if (Namespaces == null)
                                    {
                                        Namespaces = new LinkedList <KeyValuePair <string, string> >();
                                    }

                                    Namespaces.AddLast(new KeyValuePair <string, string>(Attr.Prefix, Attr.Value));
                                }
                            }
                            else if (Attr.LocalName == "version" && Attr.NamespaceURI == BoshNamespace)
                            {
                                Version = Attr.Value;
                            }
                            break;
                        }
                    }

                    if (Terminate)
                    {
                        this.terminated = true;

                        lock (this.httpClients)
                        {
                            this.outputQueue.Clear();
                        }

                        throw new Exception("Session terminated. Condition: " + Condition);
                    }

                    if (First)
                    {
                        First = false;

                        StringBuilder sb = new StringBuilder();

                        sb.Append('<');
                        sb.Append(StreamPrefix);
                        sb.Append(":stream xmlns:");
                        sb.Append(StreamPrefix);
                        sb.Append("='");
                        sb.Append(XmppClient.NamespaceStream);

                        if (To != null)
                        {
                            sb.Append("' to='");
                            sb.Append(XML.Encode(To));
                        }

                        if (From != null)
                        {
                            sb.Append("' from='");
                            sb.Append(XML.Encode(From));
                        }

                        if (Version != null)
                        {
                            sb.Append("' version='");
                            sb.Append(XML.Encode(Version));
                        }

                        if (Language != null)
                        {
                            sb.Append("' xml:lang='");
                            sb.Append(XML.Encode(Language));
                        }

                        sb.Append("' xmlns='");
                        sb.Append(XmppClient.NamespaceClient);

                        if (Namespaces != null)
                        {
                            foreach (KeyValuePair <string, string> P in Namespaces)
                            {
                                sb.Append("' xmlns:");
                                sb.Append(P.Key);
                                sb.Append("='");
                                sb.Append(XML.Encode(P.Value));
                            }
                        }

                        sb.Append("'>");

                        this.bindingInterface.StreamHeader = sb.ToString();

                        sb.Clear();
                        sb.Append("</");
                        sb.Append(StreamPrefix);
                        sb.Append(":stream>");

                        this.bindingInterface.StreamFooter = sb.ToString();
                    }
                }
            }

            if (Xml != null)
            {
                this.RaiseOnReceived(Xml);
            }
        }
Пример #57
0
        /// <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.ChildNodes)
            {
                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 == null ||
                Result.archiveReq == null ||
                Result.archiveOpt == null ||
                Result.signBefore <= Result.signAfter)
            {
                return(null);
            }

            List <HumanReadableText> ForHumans = new List <HumanReadableText>();
            List <Role>            Roles       = new List <Role>();
            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;
                    break;
                }

                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 == 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 == null || RoleRef == 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 == 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":
                    List <Parameter> Parameters = new List <Parameter>();

                    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 == 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 == 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 "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 == 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 "schemaHash":
                            Result.contentSchemaHash = 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 == null)
                    {
                        return(null);
                    }

                    Result.serverSignature = ServerSignature;
                    break;

                default:
                    return(null);
                }
            }

            if (Content == null || ForHumans.Count == 0 || !PartsDefined)
            {
                return(null);
            }

            Result.roles                = Roles.ToArray();
            Result.forMachines          = Content;
            Result.forMachinesLocalName = Content.LocalName;
            Result.forMachinesNamespace = Content.NamespaceURI;
            Result.forHumans            = ForHumans.ToArray();
            Result.clientSignatures     = Signatures.ToArray();

            return(Result);
        }
Пример #58
0
        public override void ConstructFromXML(XML xml)
        {
            base.ConstructFromXML(xml);

            m_List = (GList)this.GetChildAt(2);
        }
Пример #59
0
        public void Load(XmlDocument Xml, string FileName)
        {
            MarkdownDocument Markdown;
            XmlElement       E;
            DateTime         Timestamp;
            Color            ForegroundColor;
            Color            BackgroundColor;

            XSL.Validate(FileName, Xml, chatRoot, chatNamespace, schema);

            this.ChatListView.Items.Clear();

            foreach (XmlNode N in Xml.DocumentElement.ChildNodes)
            {
                E = N as XmlElement;
                if (E is null)
                {
                    continue;
                }

                if (!Enum.TryParse <ChatItemType>(E.LocalName, out ChatItemType Type))
                {
                    continue;
                }

                Timestamp = XML.Attribute(E, "timestamp", DateTime.MinValue);

                switch (Type)
                {
                case ChatItemType.Received:
                    ForegroundColor = Colors.Black;
                    BackgroundColor = Colors.AliceBlue;
                    break;

                case ChatItemType.Transmitted:
                    ForegroundColor = Colors.Black;
                    BackgroundColor = Colors.Honeydew;
                    break;

                default:
                    continue;
                }

                try
                {
                    Markdown = new MarkdownDocument(E.InnerText, GetMarkdownSettings());
                }
                catch (Exception)
                {
                    Markdown = null;
                }

                ChatItem     Item         = new ChatItem(Type, Timestamp, E.InnerText, Markdown, ForegroundColor, BackgroundColor);
                ListViewItem ListViewItem = new ListViewItem()
                {
                    Content    = Item,
                    Foreground = new SolidColorBrush(ForegroundColor),
                    Background = new SolidColorBrush(BackgroundColor),
                    Margin     = new Thickness(0)
                };
                this.ChatListView.Items.Add(ListViewItem);
                this.ChatListView.ScrollIntoView(ListViewItem);
            }
        }
Пример #60
0
        /// <summary>
        /// Normalizes an XML element.
        /// </summary>
        /// <param name="Xml">XML element to normalize</param>
        /// <param name="Output">Normalized XML will be output here</param>
        /// <param name="CurrentNamespace">Namespace at the encapsulating entity.</param>
        public static void NormalizeXml(XmlElement Xml, StringBuilder Output, string CurrentNamespace)
        {
            Output.Append('<');

            SortedDictionary <string, string> Attributes = null;
            string TagName = Xml.LocalName;

            if (!string.IsNullOrEmpty(Xml.Prefix))
            {
                TagName = Xml.Prefix + ":" + TagName;
            }

            Output.Append(TagName);

            foreach (XmlAttribute Attr in Xml.Attributes)
            {
                if (Attributes == null)
                {
                    Attributes = new SortedDictionary <string, string>();
                }

                Attributes[Attr.Name] = Attr.Value;
            }

            if (Xml.NamespaceURI != CurrentNamespace && string.IsNullOrEmpty(Xml.Prefix))
            {
                Attributes["xmlns"] = Xml.NamespaceURI;
                CurrentNamespace    = Xml.NamespaceURI;
            }
            else
            {
                Attributes.Remove("xmlns");
            }

            foreach (KeyValuePair <string, string> Attr in Attributes)
            {
                Output.Append(' ');
                Output.Append(Attr.Key);
                Output.Append("=\"");
                Output.Append(XML.Encode(Attr.Value));
                Output.Append('"');
            }

            bool HasElements = false;

            foreach (XmlNode N in Xml.ChildNodes)
            {
                if (N is XmlElement E)
                {
                    if (!HasElements)
                    {
                        HasElements = true;
                        Output.Append('>');
                    }

                    NormalizeXml(E, Output, CurrentNamespace);
                }
            }

            if (HasElements)
            {
                Output.Append("</");
                Output.Append(TagName);
                Output.Append('>');
            }
            else
            {
                Output.Append("/>");
            }
        }