Exemplo n.º 1
0
    public static void Main()
    {
        BusG.Init ();
        Application.Init ();

        Window win = new Window ("D-Bus#");
        win.SetDefaultSize (640, 480);
        win.Destroyed += delegate {Application.Quit ();};
        win.ShowAll ();

        bus = Bus.Session;
        sysBus = Bus.System.GetObject<IBus> ("org.freedesktop.DBus", new ObjectPath ("/org/freedesktop/DBus"));

        string bus_name = "org.ndesk.gtest";
        ObjectPath path = new ObjectPath ("/org/ndesk/test");

        if (bus.RequestName (bus_name) == RequestNameReply.PrimaryOwner) {
            //create a new instance of the object to be exported
            demo = new DemoObject ();
            sysBus.NameOwnerChanged += demo.FireChange;
            bus.Register (path, demo);
        } else {
            //import a remote to a local proxy
            demo = bus.GetObject<DemoObject> (bus_name, path);
        }

        //run the main loop
        Application.Run ();
    }
Exemplo n.º 2
0
        public GenerationMenuWidget(Window parent, IElement referer, Bus bus, string busName)
        {
            if (referer.Data != null) {
                MenuItem path = new MenuItem("Call " + referer.Name + "...");
                ObjectPath p = new ObjectPath(referer.Parent.Parent.Path);

                if (!referer.Data.IsProperty) {
                    path.Activated += delegate {
                        MethodInvokeDialog diag = new MethodInvokeDialog (parent, bus, busName, p, referer);

                        while (diag.Run () == (int)ResponseType.None);
                        diag.Destroy();
                    };
                } else {
                    path.Activated += delegate {
                        PropertyInvokeDialog diag = new PropertyInvokeDialog (parent, bus, busName, p, referer);

                        while (diag.Run () == (int)ResponseType.None);
                        diag.Destroy();
                    };
                }

                this.Append(path);
                path.ShowAll();
            }
        }
        private void createTestVirtualDocument()
        {
                // create a new DataObject to use as the parent node
                ObjectIdentity emptyIdentity = new ObjectIdentity(DefaultRepository);
                DataObject parentDO = new DataObject(emptyIdentity);
                parentDO.Type = "dm_document";
                PropertySet parentProperties = new PropertySet();
                parentProperties.Set("object_name", SampleContentManager.testVdmObjectName);
                parentDO.Properties = parentProperties;

                // link into a folder
                ObjectPath objectPath = new ObjectPath(SampleContentManager.sourcePath);
                ObjectIdentity sampleFolderIdentity = new ObjectIdentity(objectPath, DefaultRepository);
                ReferenceRelationship sampleFolderRelationship = new ReferenceRelationship();
                sampleFolderRelationship.Name = Relationship.RELATIONSHIP_FOLDER;
                sampleFolderRelationship.Target = sampleFolderIdentity;
                sampleFolderRelationship.TargetRole = Relationship.ROLE_PARENT;
                parentDO.Relationships.Add(sampleFolderRelationship);

                // get id of document to use for first child node
                ObjectIdentity child0Id = new ObjectIdentity();
                child0Id.RepositoryName = DefaultRepository;
                child0Id.Value = new Qualification(SampleContentManager.gifImageQualString);

                // get id of document to use for second child node
                ObjectIdentity child1Id = new ObjectIdentity();
                child1Id.RepositoryName = DefaultRepository;
                child1Id.Value = new Qualification(SampleContentManager.gifImage1QualString);

                ObjectIdentitySet childNodes = new ObjectIdentitySet();
                childNodes.AddIdentity(child0Id);
                childNodes.AddIdentity(child1Id);

                virtualDocumentServiceDemo.AddChildNodes(parentDO, childNodes);
        }
Exemplo n.º 4
0
    public static void Main()
    {
        BusG.Init ();
        Application.Init ();

        btn = new Button ("Click me");
        btn.Clicked += OnClick;

        VBox vb = new VBox (false, 2);
        vb.PackStart (btn, false, true, 0);

        Window win = new Window ("D-Bus#");
        win.SetDefaultSize (640, 480);
        win.Add (vb);
        win.Destroyed += delegate {Application.Quit ();};
        win.ShowAll ();

        bus = Bus.Session;

        string bus_name = "org.ndesk.gtest";
        ObjectPath path = new ObjectPath ("/org/ndesk/btn");

        if (bus.RequestName (bus_name) == RequestNameReply.PrimaryOwner) {
            bus.Register (path, btn);
            rbtn = btn;
        } else {
            rbtn = bus.GetObject<Button> (bus_name, path);
        }

        //run the main loop
        Application.Run ();
    }
        public void ObjServiceMove(String sourceObjectPathString,
                                   String targetLocPathString,
                                   String sourceLocPathString)
        {
            // identify the object to move
            ObjectPath objPath = new ObjectPath(sourceObjectPathString);
            ObjectIdentity docToCopy = new ObjectIdentity();
            docToCopy.Value = objPath;
            docToCopy.RepositoryName = DefaultRepository;

            // identify the folder to move from
            ObjectPath fromFolderPath = new ObjectPath();
            fromFolderPath.Path = sourceLocPathString;
            ObjectIdentity fromFolderIdentity = new ObjectIdentity();
            fromFolderIdentity.Value = fromFolderPath;
            fromFolderIdentity.RepositoryName = DefaultRepository;
            ObjectLocation fromLocation = new ObjectLocation();
            fromLocation.Identity = fromFolderIdentity;

            // identify the folder to move to
            ObjectPath folderPath = new ObjectPath(targetLocPathString);
            ObjectIdentity toFolderIdentity = new ObjectIdentity();
            toFolderIdentity.Value = folderPath;
            toFolderIdentity.RepositoryName = DefaultRepository;
            ObjectLocation toLocation = new ObjectLocation();
            toLocation.Identity = toFolderIdentity;

            OperationOptions operationOptions = null;
            objectService.Move(new ObjectIdentitySet(docToCopy),
                               fromLocation,
                               toLocation,
                               new DataPackage(),
                               operationOptions);
        }
Exemplo n.º 6
0
 public DynamicExportObject(Connection conn, ObjectPath object_path, object obj)
     : base(conn, object_path, obj)
 {
     //this.obj = obj;
     ScriptRuntime runtime = ScriptRuntime.CreateFromConfiguration ();
     ops = runtime.CreateOperations ();
 }
Exemplo n.º 7
0
    public static void Main()
    {
        BusG.Init ();
        Application.Init ();

        Button btn = new Button ("Click me");
        btn.Clicked += OnClick;

        VBox vb = new VBox (false, 2);
        vb.PackStart (btn, false, true, 0);

        Window win = new Window ("D-Bus#");
        win.SetDefaultSize (640, 480);
        win.Add (vb);
        win.Destroyed += delegate {Application.Quit ();};
        win.ShowAll ();

        bus = Bus.Session;

        string bus_name = "org.ndesk.gtest";
        ObjectPath path = new ObjectPath ("/org/ndesk/test");

        if (bus.RequestName (bus_name) == RequestNameReply.PrimaryOwner) {
            //create a new instance of the object to be exported
            demo = new DemoObject ();
            bus.Register (path, demo);
        } else {
            //import a remote to a local proxy
            demo = bus.GetObject<DemoObject> (bus_name, path);
        }

        //run the main loop
        Application.Run ();
    }
Exemplo n.º 8
0
        public Account(ObjectPath accountPath)
        {
            this.accountPath = accountPath;

            this.iAccount = Bus.Session.GetObject<IAccount> (EmpathyPlugin.ACCOUNTMANAGER_IFACE, accountPath);
            this.iAccountProp = Bus.Session.GetObject<Properties> (EmpathyPlugin.ACCOUNTMANAGER_IFACE, accountPath);
            ConnectionStatus connectionStatus = (ConnectionStatus)this.iAccountProp.Get (EmpathyPlugin.ACCOUNT_IFACE, "ConnectionStatus");

            string[] tabStr = accountPath.ToString().Split("/".ToCharArray());
            int length = tabStr.Length;
            this.proto = tabStr[length - 2];
            this.cm = tabStr[length - 3];

            this.connectionPath = (ObjectPath)this.iAccountProp.Get (EmpathyPlugin.ACCOUNT_IFACE, "Connection");
            this.connectionBusIFace = connectionPath.ToString ().Replace ("/", ".").Substring (1);
            if (connectionStatus == ConnectionStatus.Connected) {
                this.iConnection = Bus.Session.GetObject<IConnection> (connectionBusIFace, connectionPath);
            } else {
                this.iConnection = null;
            }

            //			 this.iAccount.Nickname
            //				this.name = (string)this.iAccountProp.Get (TelepathyPlugin.ACCOUNT_IFACE, "Nickname");
            //			 this.iAccount.DisplayName
            this.name = (string)this.iAccountProp.Get (EmpathyPlugin.ACCOUNT_IFACE, "DisplayName");
        }
Exemplo n.º 9
0
 public Signal(ObjectPath path, string @interface, string member)
 {
     message.Header.MessageType = MessageType.Signal;
     message.Header.Flags = HeaderFlag.NoReplyExpected | HeaderFlag.NoAutoStart;
     message.Header[FieldCode.Path] = path;
     message.Header[FieldCode.Interface] = @interface;
     message.Header[FieldCode.Member] = member;
 }
 public void HandleTube(string bus_name,
                         ObjectPath conn,
                         ObjectPath channel,
                         uint handle_type,
                         uint handle)
 {
     return;
 }
Exemplo n.º 11
0
		public void NewConnection (ObjectPath device, FileDescriptor fileDescriptor, IDictionary<string,object> properties)
		{
			System.Console.WriteLine ("NewConnection");
			_fileDescriptor = fileDescriptor;
			if (NewConnectionAction != null) {
				NewConnectionAction (device, _fileDescriptor, properties);
			}
		}
Exemplo n.º 12
0
 public Signal(Message message)
 {
     this.message = message;
     Path = (ObjectPath)message.Header[FieldCode.Path];
     Interface = (string)message.Header[FieldCode.Interface];
     Member = (string)message.Header[FieldCode.Member];
     Sender = (string)message.Header[FieldCode.Sender];
 }
		public Expression GetReplacementExpression(Expression currentJoin, ObjectPath<PropertyInfo> propertyPath)
		{
			int index;
			var indexFound = -1;

			for (index = this.replacementExpressionForPropertyPathsByJoin.Count - 1; index >= 0; index--)
			{
				Expression retval;

				if (currentJoin == this.replacementExpressionForPropertyPathsByJoin[index].Left)
				{
					indexFound = index;
				}

				if (index > indexFound)
				{
					continue;
				}
				
				if (this.replacementExpressionForPropertyPathsByJoin[index].Right.TryGetValue(propertyPath, out retval))
				{
					return retval;	
				}
			}

			for (index = this.replacementExpressionForPropertyPathsByJoin.Count - 1; index >= 0; index--)
			{
				Expression retval;

				if (currentJoin == this.replacementExpressionForPropertyPathsByJoin[index].Left)
				{
					indexFound = index;
				}

				if (index > indexFound)
				{
					continue;
				}

				if (this.replacementExpressionForPropertyPathsByJoin[index].Right.TryGetValue(propertyPath, out retval))
				{
					return retval;
				}

				if (this.replacementExpressionForPropertyPathsByJoin[index].Right.TryGetValue(ObjectPath<PropertyInfo>.Empty, out retval))
				{
					foreach (var property in propertyPath)
					{
						retval = Expression.Property(retval, property.Name);
					}

					return retval;
				}
			}

			return null;
		}
Exemplo n.º 14
0
		public void ConstructorTest ()
		{
			var x = new ObjectPath ("/");
			Assert.AreEqual (x.ToString (), "/", "#1");
			Assert.AreEqual (x, ObjectPath.Root, "#2");

			x = new ObjectPath ("/this/01234567890/__Test__");
			Assert.AreEqual ("/this/01234567890/__Test__", x.ToString (), "#3");
		}
Exemplo n.º 15
0
	public static void Main ()
	{
		Bus bus = Bus.Session;

		ObjectPath myPath = new ObjectPath ("/org/ndesk/test");
		string myName = "org.ndesk.test";

		//TODO: write the rest of this demo and implement
	}
 private void setSampleFolderRelationship()
 {
     ObjectPath objectPath = new ObjectPath(sourcePath);
     ObjectIdentity sampleFolderIdentity = new ObjectIdentity(objectPath, serviceDemo.DefaultRepository);
     sampleFolderRelationship = new ReferenceRelationship();
     sampleFolderRelationship.Name = Relationship.RELATIONSHIP_FOLDER;
     sampleFolderRelationship.Target = sampleFolderIdentity;
     sampleFolderRelationship.TargetRole = Relationship.ROLE_PARENT;
 }
Exemplo n.º 17
0
	public static void Main ()
	{
		Bus bus = Bus.Session;

		string bus_name = "org.ndesk.test";
		ObjectPath path = new ObjectPath ("/org/ndesk/test");
		ObjectPath cppath = new ObjectPath ("/org/ndesk/CodeProvider");

		IDemoOne demo;

		if (bus.RequestName (bus_name) == RequestNameReply.PrimaryOwner) {
			//create a new instance of the object to be exported
			demo = new Demo ();
			bus.Register (path, demo);

			DCodeProvider dcp = new DCodeProvider();
			bus.Register (cppath, dcp);

			//run the main loop
			while (true)
				bus.Iterate ();

		} else {
			//import a remote to a local proxy
			//demo = bus.GetObject<IDemo> (bus_name, path);
			demo = bus.GetObject<DemoProx> (bus_name, path);
			//RunTest (demo);

			ICodeProvider idcp = bus.GetObject<ICodeProvider> (bus_name, cppath);

			DMethodInfo dmi = idcp.GetMethod ("DemoProx", "SayRepeatedly");

			DArgumentInfo[] fields = idcp.GetFields ("DemoProx");
			foreach (DArgumentInfo field in fields)
				Console.WriteLine("Field: " + field.Name);

			//DynamicMethod dm = new DynamicMethod (dmi.Name, typeof(void), new Type[] { typeof(object), typeof(int), typeof(string) }, typeof(DemoBase));
			//ILGenerator ilg = dm.GetILGenerator ();
			//dmi.Implement (ilg);

			DynamicMethod dm = dmi.GetDM ();

			SayRepeatedlyHandler cb = (SayRepeatedlyHandler)dm.CreateDelegate (typeof (SayRepeatedlyHandler), demo);
			int retVal;
			retVal = cb (12, "Works!");
			Console.WriteLine("retVal: " + retVal);

			/*
			for (int i = 0 ; i != dmi.Code.Length ; i++) {
				if (!dmi.Code[i].Emit(ilg))
					throw new Exception(String.Format("Code gen failure at i={0} {1}", i, dmi.Code[i].opCode));
			}
			*/
			//SayRepeatedlyHandler
		}
	}
Exemplo n.º 18
0
        /// <summary>
        /// Gets the bus name for the specified connection manager object path
        /// </summary>
        /// <returns>The bus name</returns>
        /// <param name='objectPath'>The object path</param>
        public static string BusName(ObjectPath objectPath)
        {
            // TODO: Is there a better (proper?) way to do this?

            // ObjectPath is eg. /org/freedesktop/Telepathy/Connection/gabble/jabber/daniel_40d15_2ebiz_2f3e9348f3
            // Connection manager type is 5th item (eg. "gabble")
            string connType = objectPath.ToString().Split('/')[5];

            return string.Format("org.freedesktop.Telepathy.ConnectionManager.{0}", connType);
        }
Exemplo n.º 19
0
        public MethodCaller(Bus bus, string busName, ObjectPath path,
		                    string iname, string name, InvocationData data)
            : base(iname)
        {
            this.bus = bus;
            this.busName = busName;
            this.path = path;
            this.name = name;
            this.data = data;
        }
Exemplo n.º 20
0
		public void RequestDisconnection (ObjectPath device)
		{
			System.Console.WriteLine ("RequestDisconnection");
			if (RequestDisconnectionAction != null) {
				RequestDisconnectionAction (device, _fileDescriptor);
			} else {
				if (_fileDescriptor != null) {
					_fileDescriptor.Close ();
				}
			}
		}
Exemplo n.º 21
0
        public void InterfaceThroughWireTest()
        {
            ObjectIntrospectedImpl impl = new ObjectIntrospectedImpl ();
            ObjectPath path = new ObjectPath ("/org/dbussharp/test");
            Bus.Session.Register (path, impl);

            const string ServiceName = "org.dbussharp.testservice";
            Bus.Session.RequestName (ServiceName);
            var iface = Bus.Session.GetObject<org.freedesktop.DBus.Introspectable> ("org.dbussharp.testservice", path);

            Assert.IsTrue (XNode.DeepEquals (XDocument.Parse (expectedOutputSimpleInterface),
                                             XDocument.Parse (iface.Introspect ())));
        }
Exemplo n.º 22
0
        //dynamically defines a Type for the proxy object using D-Bus introspection
        public object GetObject(string bus_name, ObjectPath path)
        {
            org.freedesktop.DBus.Introspectable intros = GetObject<org.freedesktop.DBus.Introspectable> (bus_name, path);
            string data = intros.Introspect ();

            StringReader sr = new StringReader (data);
            XmlSerializer sz = new XmlSerializer (typeof (Node));
            Node node = (Node)sz.Deserialize (sr);

            Type type = TypeDefiner.Define (node.Interfaces);

            return GetObject (type, bus_name, path);
        }
Exemplo n.º 23
0
 public MethodCall(ObjectPath path, string @interface, string member, string destination, Signature signature)
 {
     message.Header.MessageType = MessageType.MethodCall;
     message.ReplyExpected = true;
     message.Header[FieldCode.Path] = path;
     message.Header[FieldCode.Interface] = @interface;
     message.Header[FieldCode.Member] = member;
     message.Header[FieldCode.Destination] = destination;
     //TODO: consider setting Sender here for p2p situations
     //this will allow us to remove the p2p hacks in MethodCall and Message
     #if PROTO_REPLY_SIGNATURE
     //TODO
     #endif
     message.Signature = signature;
 }
Exemplo n.º 24
0
		public void Equality ()
		{
			string pathText = "/org/freedesktop/DBus";

			ObjectPath a = new ObjectPath (pathText);
			ObjectPath b = new ObjectPath (pathText);

			Assert.IsTrue (a.Equals (b));
			Assert.AreEqual (String.Empty.CompareTo (null), a.CompareTo (null));
			Assert.IsTrue (a == b);
			Assert.IsFalse (a != b);

			ObjectPath c = new ObjectPath (pathText + "/foo");
			Assert.IsFalse (a == c);
		}
Exemplo n.º 25
0
		bool InitializePrivateBus (Bus bus)
		{
			if (bus.RequestName (BusName) != RequestNameReply.PrimaryOwner) {
				Log<DBusManager>.Error ("Bus Name '{0}' is already owned", BusName);
				return false;
			}
			
			docky = new DockyDBus ();
			docky.QuitCalled += HandleQuitCalled;
			docky.SettingsCalled += HandleSettingsCalled;
			docky.AboutCalled += HandleAboutCalled;
			
			ObjectPath dockyPath = new ObjectPath (DockyPath);
			bus.Register (dockyPath, docky);
			Log<DBusManager>.Debug ("DBus Registered: {0}", BusName);
			
			return true;
		}
Exemplo n.º 26
0
        public PropertyInvokeDialog(Window parent, Bus bus, string busName, ObjectPath path, IElement element)
            : base(element.Name, parent, DialogFlags.DestroyWithParent | DialogFlags.Modal)
        {
            this.Build ();
            this.parent = parent;
            this.setAlign.HideAll ();
            this.WidthRequest = 250;
            this.HeightRequest = 150;
            this.propertyName.Text = element.Name;
            this.propertyType = Mapper.DTypeFromString (element.Data.ReturnType);

            try {
                this.caller = new PropertyCaller (bus, busName, path, element.Parent.Name, element.Name, element.Data);
            } catch (Exception e) {
                Logging.Error ("Error while creating the invocation proxy", e, parent);
                buttonExecute.Sensitive = false;
            }
        }
Exemplo n.º 27
0
        public MethodInvokeDialog(Window parent, Bus bus, string busName, ObjectPath path, IElement element)
            : base(element.Name, parent, DialogFlags.DestroyWithParent | DialogFlags.Modal)
        {
            this.Build ();
            this.SetDefaultSize (-1, -1);
            this.methodName.Text = element.Name;
            this.parent = parent;
            this.TransientFor = parent;

            try {
                BuildInterface (element);
                caller = new MethodCaller(bus, busName, path, element.Parent.Name, element.Name, element.Data);
            } catch (Exception e) {
                Logging.Error ("Error while creating the invocation proxy", e, parent);
                buttonExecute.Sensitive = false;
            }

            this.ShowAll ();
        }
Exemplo n.º 28
0
 public MethodCall(Message message)
 {
     this.message = message;
     Path = (ObjectPath)message.Header[FieldCode.Path];
     Interface = (string)message.Header[FieldCode.Interface];
     Member = (string)message.Header[FieldCode.Member];
     Destination = (string)message.Header[FieldCode.Destination];
     //TODO: filled by the bus so reliable, but not the case for p2p
     //so we make it optional here, but this needs some more thought
     //if (message.Header.Fields.ContainsKey (FieldCode.Sender))
     Sender = (string)message.Header[FieldCode.Sender];
     #if PROTO_REPLY_SIGNATURE
     //TODO: note that an empty ReplySignature should really be treated differently to the field not existing!
     if (message.Header.Fields.ContainsKey (FieldCode.ReplySignature))
         ReplySignature = (Signature)message.Header[FieldCode.ReplySignature];
     else
         ReplySignature = Signature.Empty;
     #endif
     Signature = message.Signature;
 }
        public void DeleteTestCabinet(String repository)
        {
            if (!isDataCleanedUp)
            {
                Console.WriteLine("Test cabinet, folders, and sample images will not be deleted because SampleContentManager.isDataCleanedUp = false");
                return;
            }
            DeleteProfile deleteProfile = new DeleteProfile();
            deleteProfile.IsDeepDeleteFolders = true;
            deleteProfile.IsDeepDeleteChildrenInFolders = true;
            OperationOptions operationOptions = new OperationOptions();
            operationOptions.DeleteProfile = deleteProfile;

            ObjectPath objectPath = new ObjectPath(testCabinetPath);
            ObjectIdentity sampleCabinetIdentity = new ObjectIdentity(objectPath, repository);
            ObjectIdentitySet objIdSet = new ObjectIdentitySet();
            objIdSet.AddIdentity(sampleCabinetIdentity);

            objectService.Delete(objIdSet, operationOptions);
            Console.WriteLine("Deleted test cabinet " + testCabinetPath + " on " + repository);
        }
Exemplo n.º 30
0
        public void ShowObjectIdentity()
        {
            String repName = "MyRepositoryName";
            ObjectIdentity[] objectIdentities = new ObjectIdentity[4];

            // repository only is required to represent an object that has not been created
            objectIdentities[0] = new ObjectIdentity(repName);

            // show each form of unique identifier
            ObjectId objId = new ObjectId("090007d280075180");
            objectIdentities[1] = new ObjectIdentity(objId, repName);
            Qualification qualification = new Qualification("dm_document where r_object_id = '090007d280075180'");
            objectIdentities[2] = new ObjectIdentity(qualification, repName);

            ObjectPath objPath = new ObjectPath("/testCabinet/testFolder/testDoc");
            objectIdentities[3] = new ObjectIdentity(objPath, repName);

            foreach (ObjectIdentity identity in objectIdentities)
            {
                Console.WriteLine(identity.GetValueAsString());
            }
        }
Exemplo n.º 31
0
 private void LoadShellItems(XmlElement shellXE, SubGroupItem groupItem)
 {
     foreach (XmlElement itemXE in shellXE.SelectNodes("Item"))
     {
         if (!JudgeOSVersion(itemXE))
         {
             continue;
         }
         if (!FileExists(itemXE))
         {
             continue;
         }
         XmlElement szXE    = (XmlElement)itemXE.SelectSingleNode("Value/REG_SZ");
         string     keyName = itemXE.GetAttribute("KeyName");
         if (keyName.IsNullOrWhiteSpace())
         {
             continue;
         }
         EnhanceShellItem item = new EnhanceShellItem()
         {
             RegPath       = $@"{groupItem.TargetPath}\shell\{keyName}",
             FoldGroupItem = groupItem,
             ItemXE        = itemXE
         };
         if (szXE != null)
         {
             item.Text = ResourceString.GetDirectString(szXE.GetAttribute("MUIVerb"));
             if (szXE.HasAttribute("Icon"))
             {
                 item.Image = ResourceIcon.GetIcon(szXE.GetAttribute("Icon"))?.ToBitmap();
             }
             else if (szXE.HasAttribute("HasLUAShield"))
             {
                 item.Image = AppImage.Shield;
             }
             else
             {
                 XmlElement cmdXE = (XmlElement)itemXE.SelectSingleNode("SubKey/Command");
                 if (cmdXE != null)
                 {
                     Icon icon = null;
                     if (cmdXE.HasAttribute("Default"))
                     {
                         string filePath = ObjectPath.ExtractFilePath(cmdXE.GetAttribute("Default"));
                         icon = ResourceIcon.GetIcon(filePath);
                     }
                     item.Image = icon?.ToBitmap();
                     icon?.Dispose();
                 }
             }
         }
         if (item.Image == null)
         {
             item.Image = AppImage.NotFound;
         }
         if (item.Text.IsNullOrWhiteSpace())
         {
             item.Text = keyName;
         }
         item.ChkVisible.Checked = item.ItemVisible;
         string tip = itemXE.GetAttribute("Tip");
         if (itemXE.GetElementsByTagName("CreateFile").Count > 0)
         {
             if (!tip.IsNullOrWhiteSpace())
             {
                 tip += "\n";
             }
             tip += AppString.Tip.CommandFiles;
         }
         MyToolTip.SetToolTip(item.ChkVisible, tip);
         this.AddItem(item);
     }
 }
Exemplo n.º 32
0
 public ArgMatchTest(int argNum, ObjectPath value)
 {
     ArgNum    = argNum;
     Signature = Signature.ObjectPathSig;
     Value     = value;
 }
Exemplo n.º 33
0
 void Move(ObjectPath path)
 {
     transform.position += (path.GetDeltaPos());
 }
Exemplo n.º 34
0
 public EvaluationResult SetValue(ObjectPath path, string value, EvaluationOptions options)
 {
     return(new EvaluationResult(Session.protocolClient.SendRequestSync(new SetVariableRequest(ParentVariablesReference, Name, value)).Value));
 }
Exemplo n.º 35
0
 public void SetRawValue(ObjectPath path, object value, EvaluationOptions options)
 {
 }
Exemplo n.º 36
0
        public ObjectValue[] GetChildren(ObjectPath path, int firstItemIndex, int count, EvaluationOptions options)
        {
            EvaluationContext cctx = ctx.WithOptions(options);

            if (path.Length > 1)
            {
                // Looking for children of an array element
                int[]  idx = StringToIndices(path [1]);
                object obj = array.GetElement(idx);
                return(cctx.Adapter.GetObjectValueChildren(cctx, new ArrayObjectSource(array, path[1]), obj, firstItemIndex, count));
            }

            int  lowerBound;
            int  upperBound;
            bool isLastDimension;

            if (bounds.Length > 1)
            {
                int rank = baseIndices.Length;
                lowerBound      = 0;
                upperBound      = bounds [rank] - 1;
                isLastDimension = rank == bounds.Length - 1;
            }
            else
            {
                lowerBound      = 0;
                upperBound      = bounds [0] - 1;
                isLastDimension = true;
            }

            int len;
            int initalIndex;

            if (!IsRange)
            {
                initalIndex = lowerBound;
                len         = upperBound + 1;
            }
            else
            {
                initalIndex = firstIndex;
                len         = lastIndex - firstIndex + 1;
            }

            if (firstItemIndex == -1)
            {
                firstItemIndex = 0;
                count          = len;
            }

            // Make sure the group doesn't have too many elements. If so, divide
            int div = 1;

            while (len / div > MaxChildCount)
            {
                div *= 10;
            }

            if (div == 1 && isLastDimension)
            {
                // Return array elements

                ObjectValue[] values  = new ObjectValue [count];
                ObjectPath    newPath = new ObjectPath("this");

                int[] curIndex = new int [baseIndices.Length + 1];
                Array.Copy(baseIndices, curIndex, baseIndices.Length);
                string curIndexStr = IndicesToString(baseIndices);
                if (baseIndices.Length > 0)
                {
                    curIndexStr += ",";
                }
                curIndex [curIndex.Length - 1] = initalIndex + firstItemIndex;
                var elems = array.GetElements(curIndex, System.Math.Min(values.Length, upperBound + 1));

                for (int n = 0; n < values.Length; n++)
                {
                    int         index = n + initalIndex + firstItemIndex;
                    string      sidx  = curIndexStr + index.ToString();
                    ObjectValue val;
                    string      ename = "[" + sidx.Replace(",", ", ") + "]";
                    if (index > upperBound)
                    {
                        val = ObjectValue.CreateUnknown(sidx);
                    }
                    else
                    {
                        curIndex [curIndex.Length - 1] = index;
                        val = cctx.Adapter.CreateObjectValue(cctx, this, newPath.Append(sidx), elems.GetValue(n), ObjectValueFlags.ArrayElement);
                        if (elems.GetValue(n) != null && !cctx.Adapter.IsNull(cctx, elems.GetValue(n)))
                        {
                            TypeDisplayData tdata = cctx.Adapter.GetTypeDisplayData(cctx, cctx.Adapter.GetValueType(cctx, elems.GetValue(n)));
                            if (!string.IsNullOrEmpty(tdata.NameDisplayString))
                            {
                                ename = cctx.Adapter.EvaluateDisplayString(cctx, elems.GetValue(n), tdata.NameDisplayString);
                            }
                        }
                    }
                    val.Name   = ename;
                    values [n] = val;
                }
                return(values);
            }
            else if (!isLastDimension && div == 1)
            {
                // Return an array element group for each index

                List <ObjectValue> list = new List <ObjectValue> ();
                for (int i = 0; i < count; i++)
                {
                    int         index = i + initalIndex + firstItemIndex;
                    ObjectValue val;

                    // This array must be created at every call to avoid sharing
                    // changes with all array groups
                    int[] curIndex = new int [baseIndices.Length + 1];
                    Array.Copy(baseIndices, curIndex, baseIndices.Length);
                    curIndex [curIndex.Length - 1] = index;

                    if (index > upperBound)
                    {
                        val = ObjectValue.CreateUnknown("");
                    }
                    else
                    {
                        ArrayElementGroup grp = new ArrayElementGroup(cctx, array, curIndex);
                        val = grp.CreateObjectValue();
                    }
                    list.Add(val);
                }
                return(list.ToArray());
            }
            else
            {
                // Too many elements. Split the array.

                // Don't make divisions of 10 elements, min is 100
                if (div == 10)
                {
                    div = 100;
                }

                // Create the child groups
                int i = initalIndex + firstItemIndex;
                len += i;
                List <ObjectValue> list = new List <ObjectValue> ();
                while (i < len)
                {
                    int end = i + div - 1;
                    if (end > len)
                    {
                        end = len - 1;
                    }
                    ArrayElementGroup grp = new ArrayElementGroup(cctx, array, baseIndices, i, end);
                    list.Add(grp.CreateObjectValue());
                    i += div;
                }
                return(list.ToArray());
            }
        }
Exemplo n.º 37
0
 public override DataTable LoadOverview(DbConnection conn, ObjectPath parpath)
 {
     DbConnectionExtension.SafeChangeDatabase(conn, parpath);
     return(DbConnectionExtension.LoadTableFromQuery(conn, "select * from USER_SEQUENCES"));
 }
Exemplo n.º 38
0
 public StringOperations(ObjectPath path)
 {
     _path = path;
 }
 public void SetRawValue(ObjectPath path, object value, EvaluationOptions options)
 {
     throw new NotImplementedException();
 }
        private static void EnqueueObjectPathQueues(
            ContextPair contextPair,
            ObjectPath objectPath)
        {
            var oldInstance = objectPath.OldInstance;
            var newInstance = objectPath.NewInstance;

            var type = GetTypeFromObjects(oldInstance, newInstance);

            if (type == null)
            {
                throw new InvalidOperationException("The type could not be determined.");
            }

            if (IsSimpleType(type))
            {
                throw new InvalidOperationException("This method can't be called with simple types.");
            }

            var seenObjectsOld = contextPair.OldInstanceContext.SeenObjects;
            var seenObjectsNew = contextPair.NewInstanceContext.SeenObjects;

            if (seenObjectsOld.Contains(objectPath.OldInstance) || seenObjectsNew.Contains(objectPath.NewInstance))
            {
                return;
            }

            if (objectPath.OldInstance != null)
            {
                seenObjectsOld.Add(objectPath.OldInstance);
            }

            if (objectPath.NewInstance != null)
            {
                seenObjectsNew.Add(objectPath.NewInstance);
            }

            var objectPathQueue = contextPair.ObjectPathQueue;

            var properties = type.GetProperties();

            foreach (var property in properties)
            {
                try
                {
                    objectPathQueue.Enqueue(new ObjectPath()
                    {
                        OldInstance      = oldInstance == null ? null : property.GetValue(oldInstance),
                        NewInstance      = newInstance == null ? null : property.GetValue(newInstance),
                        Properties       = property.PropertyType.GetProperties(),
                        BasePropertyPath = AddToPropertyPath(
                            objectPath.BasePropertyPath,
                            property.Name),
                        ParentChanges = objectPath.ParentChanges
                    });
                }
                catch (Exception ex)
                {
                    throw new Exception($"An error occured while comparing {AddToPropertyPath(objectPath.BasePropertyPath, property.Name)}.", ex);
                }
            }
        }
Exemplo n.º 41
0
 public StringOperations()
 {
     _path = Path;
 }
        private static void ScanForChanges(ContextPair contextPair, ObjectPath objectPath, ChangeCollection result)
        {
            var pathType = GetTypeFromObjects(
                objectPath.OldInstance,
                objectPath.NewInstance);

            if (IsSimpleType(pathType))
            {
                var shallowChange = GetShallowChange(
                    objectPath.BasePropertyPath,
                    objectPath.OldInstance,
                    objectPath.NewInstance);
                if (shallowChange == Change.Empty)
                {
                    return;
                }

                result.Add(shallowChange);
                if (objectPath.ParentChanges == null)
                {
                    return;
                }

                foreach (var parentChange in objectPath.ParentChanges)
                {
                    result.Add(parentChange);
                }
            }
            else if (IsEnumerableType(pathType))
            {
                if (pathType == null)
                {
                    throw new InvalidOperationException("Type was enumerable despite being null.");
                }

                Array?itemsOldArray;
                Array?itemsNewArray;

                if (pathType.IsArray)
                {
                    itemsOldArray = (Array?)objectPath.OldInstance;
                    itemsNewArray = (Array?)objectPath.NewInstance;
                }
                else
                {
                    var genericType = pathType
                                      .GetInterfaces()
                                      .Single(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IEnumerable <>))
                                      .GetGenericArguments()
                                      .Single();

                    var toArrayMethod = typeof(Enumerable)
                                        .GetMethods()
                                        .Single(x =>
                                                x.Name == nameof(Enumerable.ToArray) &&
                                                x.IsGenericMethod)
                                        .MakeGenericMethod(genericType);

                    var emptyMethod = typeof(Array)
                                      .GetMethods()
                                      .Single(x =>
                                              x.Name == nameof(Array.Empty) &&
                                              x.IsGenericMethod)
                                      .MakeGenericMethod(genericType);

                    itemsOldArray = objectPath.OldInstance == null
                        ? (Array)emptyMethod.Invoke(null, Array.Empty <object>())
                        : (Array)toArrayMethod.Invoke(null, new[] { objectPath.OldInstance });

                    itemsNewArray = objectPath.NewInstance == null
                        ? (Array)emptyMethod.Invoke(null, Array.Empty <object>())
                        : (Array)toArrayMethod.Invoke(null, new[] { objectPath.NewInstance });
                }

                var maxCount = Math.Max(
                    itemsOldArray?.Length ?? 0,
                    itemsNewArray?.Length ?? 0);

                var newItemsOldArray = new object[maxCount];
                var newItemsNewArray = new object[maxCount];

                Array.Copy(itemsOldArray ?? Array.Empty <object>(), newItemsOldArray, itemsOldArray?.Length ?? 0);
                Array.Copy(itemsNewArray ?? Array.Empty <object>(), newItemsNewArray, itemsNewArray?.Length ?? 0);

                var shallowChange = new Change(
                    objectPath.BasePropertyPath ?? string.Empty,
                    objectPath.OldInstance,
                    objectPath.NewInstance);
                var newParentChanges = new[]
                {
                    shallowChange
                };

                var parentChanges = objectPath.ParentChanges == null ?
                                    newParentChanges :
                                    objectPath
                                    .ParentChanges
                                    .Union(newParentChanges)
                                    .Distinct()
                                    .ToArray();

                for (var i = 0; i < maxCount; i++)
                {
                    var itemOldInstance = newItemsOldArray[i];
                    var itemNewInstance = newItemsNewArray[i];

                    var itemType = GetTypeFromObjects(itemOldInstance, itemNewInstance);
                    if (itemType == null)
                    {
                        continue;
                    }

                    var arrayItemObjectPath = new ObjectPath()
                    {
                        BasePropertyPath = AddToPropertyPath(
                            objectPath.BasePropertyPath,
                            i.ToString()),
                        OldInstance   = itemOldInstance,
                        NewInstance   = itemNewInstance,
                        Properties    = itemType.GetProperties(),
                        ParentChanges = parentChanges
                    };

                    contextPair.ObjectPathQueue.Enqueue(arrayItemObjectPath);
                }
            }
            else
            {
                EnqueueObjectPathQueues(
                    contextPair,
                    objectPath);
            }
        }
Exemplo n.º 43
0
 static void AppendPathArg(StringBuilder sb, int index, ObjectPath value)
 {
     Append(sb, "arg" + index + "path", value.ToString());
 }
Exemplo n.º 44
0
 public MatchTest(ObjectPath value)
 {
     Signature = Signature.ObjectPathSig;
     Value     = value;
 }
Exemplo n.º 45
0
 public override DataTable LoadOverview(DbConnection conn, ObjectPath parpath)
 {
     return(DbConnectionExtension.LoadTableFromQuery(conn, "select * from USER_TRIGGERS"));
 }
        /// <summary>
        /// Return results of the call to QnA Maker.
        /// </summary>
        /// <param name="dialogContext">Context object containing information for a single turn of conversation with a user.</param>
        /// <param name="activity">The incoming activity received from the user. The Text property value is used as the query text for QnA Maker.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <param name="telemetryProperties">Additional properties to be logged to telemetry with the LuisResult event.</param>
        /// <param name="telemetryMetrics">Additional metrics to be logged to telemetry with the LuisResult event.</param>
        /// <returns>A <see cref="RecognizerResult"/> containing the QnA Maker result.</returns>
        public override async Task <RecognizerResult> RecognizeAsync(DialogContext dialogContext, Activity activity, CancellationToken cancellationToken, Dictionary <string, string> telemetryProperties = null, Dictionary <string, double> telemetryMetrics = null)
        {
            // Identify matched intents
            var recognizerResult = new RecognizerResult
            {
                Text    = activity.Text,
                Intents = new Dictionary <string, IntentScore>(),
            };

            if (string.IsNullOrEmpty(activity.Text))
            {
                recognizerResult.Intents.Add("None", new IntentScore());
                return(recognizerResult);
            }

            var filters = new List <Metadata>();

            if (IncludeDialogNameInMetadata.GetValue(dialogContext.State))
            {
                filters.Add(new Metadata
                {
                    Name  = "dialogName",
                    Value = dialogContext.ActiveDialog.Id
                });
            }

            // if there is $qna.metadata set add to filters
            var externalMetadata = Metadata?.GetValue(dialogContext.State);

            if (externalMetadata != null)
            {
                filters.AddRange(externalMetadata);
            }

            // Calling QnAMaker to get response.
            var qnaClient = await GetQnAMakerClientAsync(dialogContext).ConfigureAwait(false);

            var answers = await qnaClient.GetAnswersAsync(
                dialogContext.Context,
                new QnAMakerOptions
            {
                Context        = Context?.GetValue(dialogContext.State),
                ScoreThreshold = Threshold.GetValue(dialogContext.State),
                StrictFilters  = filters.ToArray(),
                Top            = Top.GetValue(dialogContext.State),
                QnAId          = QnAId.GetValue(dialogContext.State),
                RankerType     = RankerType.GetValue(dialogContext.State),
                IsTest         = IsTest
            },
                null).ConfigureAwait(false);

            if (answers.Any())
            {
                QueryResult topAnswer = null;
                foreach (var answer in answers)
                {
                    if (topAnswer == null || answer.Score > topAnswer.Score)
                    {
                        topAnswer = answer;
                    }
                }

                if (topAnswer.Answer.Trim().ToUpperInvariant().StartsWith(IntentPrefix.ToUpperInvariant(), StringComparison.Ordinal))
                {
                    recognizerResult.Intents.Add(topAnswer.Answer.Trim().Substring(IntentPrefix.Length).Trim(), new IntentScore {
                        Score = topAnswer.Score
                    });
                }
                else
                {
                    recognizerResult.Intents.Add(QnAMatchIntent, new IntentScore {
                        Score = topAnswer.Score
                    });
                }

                var answerArray = new JArray();
                answerArray.Add(topAnswer.Answer);
                ObjectPath.SetPathValue(recognizerResult, "entities.answer", answerArray);

                var instance = new JArray();
                var data     = JObject.FromObject(topAnswer);
                data["startIndex"] = 0;
                data["endIndex"]   = activity.Text.Length;
                instance.Add(data);
                ObjectPath.SetPathValue(recognizerResult, "entities.$instance.answer", instance);

                recognizerResult.Properties["answers"] = answers;
            }
            else
            {
                recognizerResult.Intents.Add("None", new IntentScore {
                    Score = 1.0f
                });
            }

            TrackRecognizerResult(dialogContext, "QnAMakerRecognizerResult", FillRecognizerResultTelemetryProperties(recognizerResult, telemetryProperties), telemetryMetrics);

            return(recognizerResult);
        }
Exemplo n.º 47
0
 public override DataTable LoadOverview(DbConnection conn, ObjectPath parpath)
 {
     return(conn.LoadTableFromQuery("select * from USER_OBJECTS WHERE OBJECT_TYPE='FUNCTION'"));
 }
 public EvaluationResult SetValue(ObjectPath path, string value, EvaluationOptions options)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 49
0
 public override DataTable LoadOverview(DbConnection conn, ObjectPath parpath)
 {
     return(conn.LoadTableFromQuery("select * from USER_PROCEDURES"));
 }
Exemplo n.º 50
0
 public object GetRawValue(ObjectPath path, EvaluationOptions options)
 {
     return(null);
 }
Exemplo n.º 51
0
 public void Write(ObjectPath val)
 {
     Write(val.Value);
 }
Exemplo n.º 52
0
 public EvaluationResult SetValue(ObjectPath path, string value, EvaluationOptions options)
 {
     session.SelectThread(threadId);
     session.RunCommand("-var-assign", path.Join("."), value);
     return(new EvaluationResult(value));
 }
Exemplo n.º 53
0
 public LightSensor(Context context, ObjectPath opath)
 {
     this.light_sensor = context.GetObject <ILightSensor> (opath);
 }
Exemplo n.º 54
0
 internal UpdateCallback(IObjectValueUpdateCallback callback, ObjectPath path)
 {
     this.callback = callback;
     this.path     = path;
 }
 public ObjectValue[] GetChildren(ObjectPath path, int index, int count, EvaluationOptions options)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 56
0
        protected override ObjectValue[] GetChildrenSafe(ObjectPath path, int index, int count,
                                                         IEvaluationOptions options)
        {
            var allocatorTempObject     = Evaluate("global::Unity.Collections.Allocator.Temp");
            var componentDataType       = GetType("Unity.Entities.IComponentData").NotNull();
            var sharedComponentDataType = GetType("Unity.Entities.ISharedComponentData").NotNull();

            var entityManagerGetComponentTypesMethod      = myEntityManagerType.GetMethod("GetComponentTypes");
            var entityManagerGetSharedComponentDataMethod = myEntityManagerType.GetMethod("GetSharedComponentData");
            var entityManagerGetComponentDataMethod       = myEntityManagerType.GetMethod("GetComponentData");

            var componentTypesArray = Invoke(entityManagerGetComponentTypesMethod, myEntityManagerType,
                                             myEntityManagerObject, myEntityObject, allocatorTempObject.Value).NotNull();
            var componentTypesArrayLength =
                (PrimitiveValue)Adaptor.GetMember(Context, null, componentTypesArray, "Length").Value;

            var numberOfComponentTypes = (int)componentTypesArrayLength.Value;

            var objectValues = new List <ObjectValue>();

            for (var currentIndex = 0; currentIndex < numberOfComponentTypes; currentIndex++)
            {
                try
                {
                    var currentIndexValue = Adaptor.CreateValue(Context, currentIndex);
                    var currentComponent  = Adaptor
                                            .GetIndexerReference(Context, componentTypesArray, new[] { currentIndexValue }).Value;
                    var currentComponentType = currentComponent.Type;

                    var getManagedTypeMethod    = currentComponentType.GetMethod("GetManagedType");
                    var dataManagedType         = Invoke(getManagedTypeMethod, currentComponentType, currentComponent);
                    var dataManagedTypeFullName =
                        ((StringMirror)Adaptor.GetMember(Context, null, dataManagedType, "FullName").Value).Value;
                    var dataManagedTypeShortName =
                        ((StringMirror)Adaptor.GetMember(Context, null, dataManagedType, "Name").Value).Value;
                    var dataType = GetType(dataManagedTypeFullName);

                    MethodMirror getComponentDataMethod;
                    if (componentDataType.IsAssignableFrom(dataType))
                    {
                        getComponentDataMethod = entityManagerGetComponentDataMethod;
                    }
                    else if (sharedComponentDataType.IsAssignableFrom(dataType))
                    {
                        getComponentDataMethod = entityManagerGetSharedComponentDataMethod;
                    }
                    else
                    {
                        ourLogger.Warn("Unknown type of component data: {0}", dataManagedTypeFullName);
                        continue;
                    }

                    var getComponentDataMethodWithTypeArgs =
                        getComponentDataMethod.MakeGenericMethod(new[] { dataType });
                    var result = Invoke(getComponentDataMethodWithTypeArgs, myEntityManagerType,
                                        myEntityManagerObject, myEntityObject);
                    objectValues.Add(LiteralValueReference
                                     .CreateTargetObjectLiteral(Adaptor, Context, dataManagedTypeShortName, result)
                                     .CreateObjectValue(options));
                }
                catch (Exception e)
                {
                    ourLogger.Error(e, "Failed to fetch parameter {0} of entity {1}", currentIndex, myEntityObject);
                }
            }

            return(objectValues.ToArray());
        }
Exemplo n.º 57
0
 public ObjectValue GetValue(ObjectPath path, EvaluationOptions options)
 {
     throw new NotSupportedException();
 }
Exemplo n.º 58
0
    public static void Main(string[] args)
    {
        Bus conn;

        if (args.Length == 0)
        {
            conn = Bus.Session;
        }
        else
        {
            if (args[0] == "--session")
            {
                conn = Bus.Session;
            }
            else if (args[0] == "--system")
            {
                conn = Bus.System;
            }
            else
            {
                conn = Bus.Open(args[0]);
            }
        }

        IBus bus = conn.GetObject <IBus> ("org.freedesktop.DBus", new ObjectPath("/org/freedesktop/DBus"));

        Console.WriteLine(bus.ListNames().Length);

        var obj     = conn.GetObject <Interface> (Constants.BusName, Constants.ObjectPath);
        var obj2    = conn.GetObject <Interface2> (Constants.BusName, Constants.ObjectPath);
        var objIntr = conn.GetObject <Introspectable> (Constants.BusName, Constants.ObjectPath);

        obj.Ping();
        Console.WriteLine(obj.GetBytes(3).Length);

        Console.WriteLine("conn.UnixFDSupported = " + conn.UnixFDSupported);
        if (!conn.UnixFDSupported)
        {
            return;
        }

        using (var disposableList = new DisposableList()) {
            var res = obj.GetFD(disposableList, false);
            Console.WriteLine("Got FD:");
            Mono.Unix.Native.Stdlib.system("ls -l /proc/$PPID/fd/" + res.Handle);
        }
        using (var disposableList = new DisposableList()) {
            var res = obj.GetFDList(disposableList, false);
            Console.WriteLine("Got FDs:");
            foreach (var fd in res)
            {
                Mono.Unix.Native.Stdlib.system("ls -l /proc/$PPID/fd/" + fd.Handle);
            }
        }
        using (var disposableList = new DisposableList()) {
            var res = (UnixFD[])obj.GetFDListVariant(disposableList, false);
            Console.WriteLine("Got FDs as variant:");
            foreach (var fd in res)
            {
                Mono.Unix.Native.Stdlib.system("ls -l /proc/$PPID/fd/" + fd.Handle);
            }
        }

        using (var disposableList = new DisposableList()) {
            try {
                obj.GetFD(disposableList, true);
                throw new Exception("Expected an exception");
            } catch (Exception e) {
                if (!e.Message.Contains("Throwing an exception after creating a UnixFD object"))
                {
                    throw;
                }
            }
        }
        using (var disposableList = new DisposableList()) {
            try {
                obj.GetFDList(disposableList, true);
                throw new Exception("Expected an exception");
            } catch (Exception e) {
                if (!e.Message.Contains("Throwing an exception after creating a UnixFD object"))
                {
                    throw;
                }
            }
        }
        using (var disposableList = new DisposableList()) {
            try {
                obj.GetFDListVariant(disposableList, true);
                throw new Exception("Expected an exception");
            } catch (Exception e) {
                if (!e.Message.Contains("Throwing an exception after creating a UnixFD object"))
                {
                    throw;
                }
            }
        }

        // Check whether this leaks an FD
        obj.GetFD(null, false);
        obj.GetFDList(null, false);
        obj.GetFDListVariant(null, false);
        try { obj.GetFD(null, true); } catch {}
        try { obj.GetFDList(null, true); } catch {}
        try { obj.GetFDListVariant(null, true); } catch {}
        obj2.GetFD(false);
        obj2.GetFDList(false);
        obj2.GetFDListVariant(false);
        try { obj2.GetFD(true); } catch {}
        try { obj2.GetFDList(true); } catch {}
        try { obj2.GetFDListVariant(true); } catch {}

        var fd_ = Syscall.open("/dev/zero", OpenFlags.O_RDWR, 0);

        if (fd_ < 0)
        {
            UnixMarshal.ThrowExceptionForLastError();
        }
        using (var fd = new UnixFD(fd_)) {
            obj.SendFD(fd);
            obj.SendFD(fd);
            obj.SendFDList(new UnixFD[] { fd, fd });
            obj.SendFDListVariant(new UnixFD[] { fd, fd });

            var impl  = new SignalsImpl();
            var spath = new ObjectPath("/mono_dbus_sharp_test/Signals");
            conn.Register(spath, impl);
            obj.RegisterSignalInterface(conn.UniqueName, spath);
            impl.CallGotFD(fd);
        }

        Console.WriteLine(objIntr.Introspect().Length);

        obj.ListOpenFDs();
        Console.WriteLine("Open FDs:");
        Mono.Unix.Native.Stdlib.system("ls -l /proc/$PPID/fd/");
    }
Exemplo n.º 59
0
        public override async Task <RecognizerResult> RecognizeAsync(DialogContext dialogContext, string text, string locale, CancellationToken cancellationToken)
        {
            // Identify matched intents
            var utterance = text ?? string.Empty;

            var recognizerResult = new RecognizerResult()
            {
                Text    = utterance,
                Intents = new Dictionary <string, IntentScore>(),
            };

            List <Metadata> filters = new List <Metadata>()
            {
                new Metadata()
                {
                    Name = "dialogName", Value = dialogContext.ActiveDialog.Id
                }
            };

            // if there is $qna.metadata set add to filters
            var externalMetadata = dialogContext.GetState().GetValue <Metadata[]>("$qna.metadata");

            if (externalMetadata != null)
            {
                filters.AddRange(externalMetadata);
            }

            // Calling QnAMaker to get response.
            var qnaClient = await GetQnAMakerClientAsync(dialogContext).ConfigureAwait(false);

            var answers = await qnaClient.GetAnswersAsync(
                dialogContext.Context,
                new QnAMakerOptions
            {
                Context        = dialogContext.GetState().GetValue <QnARequestContext>("$qna.context"),
                ScoreThreshold = this.Threshold,
                StrictFilters  = filters.ToArray(),
                Top            = this.Top,
                QnAId          = 0,
                RankerType     = this.RankerType,
                IsTest         = this.IsTest
            },
                null).ConfigureAwait(false);

            if (answers.Any())
            {
                QueryResult topAnswer = null;
                foreach (var answer in answers)
                {
                    if ((topAnswer == null) || (answer.Score > topAnswer.Score))
                    {
                        topAnswer = answer;
                    }
                }

                if (topAnswer.Answer.Trim().ToLower().StartsWith(IntentPrefix))
                {
                    recognizerResult.Intents.Add(topAnswer.Answer.Trim().Substring(IntentPrefix.Length).Trim(), new IntentScore()
                    {
                        Score = topAnswer.Score
                    });
                }
                else
                {
                    recognizerResult.Intents.Add(QnAMatchIntent, new IntentScore()
                    {
                        Score = topAnswer.Score
                    });
                }

                var answerArray = new JArray();
                answerArray.Add(topAnswer.Answer);
                ObjectPath.SetPathValue(recognizerResult, "entities.answer", answerArray);

                var instance = new JArray();
                instance.Add(JObject.FromObject(topAnswer));
                ObjectPath.SetPathValue(recognizerResult, "entities.$instance.answer", instance);

                recognizerResult.Properties["answers"] = answers;
            }
            else
            {
                recognizerResult.Intents.Add("None", new IntentScore()
                {
                    Score = 1.0f
                });
            }

            return(recognizerResult);
        }
Exemplo n.º 60
0
 public override DataTable LoadOverview(DbConnection conn, ObjectPath parpath)
 {
     conn.SafeChangeDatabase(parpath);
     return(conn.GetSchema("Triggers"));
 }