Example #1
1
        public Image Scan(DeviceInfo device)
        {
            if (device == null)
                throw new ArgumentException("Device must be specified");

            var scanner = device.Connect();

            var wiaCommonDialog = new WPFCommonDialog();
            var item = scanner.Items[1];
            var image = (ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false);

            string fileName = Path.GetTempFileName();
            File.Delete(fileName);
            image.SaveFile(fileName);
            image = null;

            // add file to output list
            return Image.FromFile(fileName);
        }
        private void ActiveScanner(DeviceInfo selectedScanner)
        {
            if (selectedScanner != null && !selectedScanner.IsDeviceInfoOf(activeScanner))
            {
                DeactivateScanner();

                UpdateEventHistory(string.Format("Activate Scanner:{0}", selectedScanner.ServiceObjectName));
                try
                {
                    activeScanner = (Scanner)explorer.CreateInstance(selectedScanner);
                    activeScanner.Open();
                    activeScanner.Claim(1000);
                    activeScanner.DeviceEnabled = true;
                    activeScanner.DataEvent += new DataEventHandler(activeScanner_DataEvent);
                    activeScanner.ErrorEvent += new DeviceErrorEventHandler(activeScanner_ErrorEvent);
                    activeScanner.DecodeData = true;
                    activeScanner.DataEventEnabled = true;
                }
                catch (PosControlException)
                {
                    UpdateEventHistory(string.Format("Activation Failed:{0}", selectedScanner.ServiceObjectName));
                    activeScanner = null;
                }
            }
        }
Example #3
0
        public Deployer81(string desiredDevice, string appPath)
        {
            this.appPath = appPath;

            var devices = Utils.GetDevices();

            this.deviceInfo =
                devices.FirstOrDefault(
                    x =>
                    x.ToString().StartsWith(desiredDevice, StringComparison.OrdinalIgnoreCase)
                    && !x.ToString().Equals("Device"));

            // Exclude device
            if (this.deviceInfo == null)
            {
                Logger.Warn("Desired target {0} not found. Using default instead.", desiredDevice);

                this.deviceInfo = devices.First(x => !x.ToString().Equals("Device"));
            }

            var propertyInfo = this.deviceInfo.GetType().GetTypeInfo().GetDeclaredProperty("DeviceId");
            var deviceId = (string)propertyInfo.GetValue(this.deviceInfo);
            this.connectableDevice =
                new MultiTargetingConnectivity(CultureInfo.CurrentUICulture.LCID).GetConnectableDevice(deviceId);

            Logger.Info("Target emulator: {0}", this.DeviceName);
        }
Example #4
0
 public static DeviceInfo From(DeviceInfo di)
 {
     DeviceInfo result = new DeviceInfo(di.DriveName);
     result.DeviceXml = di.DeviceXml;
     result.DeviceName = di.DeviceName;
     return result;
 }
 public void addDevice(int deviceID, DeviceInfo deviceInfo, DeviceType deviceType)
 {
     Debug.Log("addDevice("+deviceID+", "+deviceInfo+", "+deviceType+")");
     bool alreadyEquiped = (!_equipedDevices.Exists(device => device.getID() == deviceID));
     bool alreadyInventory = (!_inventoryDevices.Exists(device => device.getID() == deviceID));
     if(alreadyEquiped || alreadyInventory) {
         Vector3 localPosition;
         UnityEngine.Transform parent;
         List<DisplayedDevice> devices;
         int newDeviceId = deviceID;
         if(deviceType == DeviceType.Equiped) {
             parent = equipPanel.transform;
             devices = _equipedDevices;
             if(deviceID == 0) {
                 newDeviceId = devices.Count;
             }
             Debug.Log("addDevice("+newDeviceId+") in equipment");
         } else {
             parent = inventoryPanel.transform;
             devices = _inventoryDevices;
             Debug.Log("addDevice("+newDeviceId+") in inventory");
         }
         localPosition = getNewPosition(deviceType);
         DisplayedDevice newDevice = DisplayedDevice.Create (parent, localPosition, newDeviceId, deviceType, deviceInfo, this);
         devices.Add(newDevice);
         //let's add reaction to reaction engine
         //for each module of deviceInfo, add to reaction engine
         //deviceInfo._modules.ForEach( module => module.addToReactionEngine(celliaMediumID, reactionEngine));
     } else {
         Debug.Log("addDevice failed: alreadyEquiped="+alreadyEquiped+", alreadyInventory="+alreadyInventory);
     }
 }
Example #6
0
        public static bool Update(UserConfiguration userConfig, DeviceInfo deviceInfo)
        {
            var deviceInfos = new List<DeviceInfo>();
            deviceInfos.Add(deviceInfo);

            return Update(userConfig, deviceInfos);
        }
Example #7
0
        public ArcazeDevice(DeviceInfo info)
        {
            this.arcazeDevice = new ArcazeHid();
            Connect(ref info);

            this.arcazeDevice.DeviceRemoved += new EventHandler<HidEventArgs>(this.DeviceRemoved);
            this.arcazeDevice.OurDeviceRemoved += new EventHandler<HidEventArgs>(this.OurDeviceRemoved);
        }
 /// <summary>
 /// Get Information for a Device (CPU/GPU/...)
 /// </summary>
 /// <returns></returns>
 public static OpenCLErrorCode GetDeviceInfo(DeviceHandle device,
                                       DeviceInfo paramName,
                                       IntPtr paramValueSize,
                                       InfoBuffer paramValue,
                                       out IntPtr paramValueSizeRet)
 {
     return clGetDeviceInfo((device as IHandleData).Handle, paramName, paramValueSize, paramValue.Address, out paramValueSizeRet);
 }
 public static void InstallApplication(
     DeviceInfo deviceInfo, 
     IAppManifestInfo manifestInfo, 
     DeploymentOptions deploymentOptions, 
     string packageFile)
 {
     DeployApplication(DeployAppMode.Install, deviceInfo, manifestInfo, deploymentOptions, packageFile);
 }
Example #10
0
        public void Load()
        {
            var device = new DeviceInfo();
            device.Load();

            ScreenResolution = string.Format(CultureInfo.InvariantCulture, "{0}x{1}", device.ScreenResolution.Width, device.ScreenResolution.Height);

            RaisePropertyChanged("ScreenResolution");
        }
Example #11
0
 /// <summary>
 /// Checks to see if the current device or the useragent string contain each
 /// other at the start.
 /// </summary>
 /// <param name="userAgent">The useragent being searched for.</param>
 /// <param name="bestMatch">Reference to the best matching device so far.</param>
 /// <param name="maxInitialString">The maximum number of characters that have matched in the search so far.</param>
 /// <param name="current">The current device being checked for a match.</param>
 private static void Check(string userAgent, ref DeviceInfo bestMatch, ref int maxInitialString,
     DeviceInfo current)
 {
     if ((userAgent.StartsWith(current.UserAgent) ||
          current.UserAgent.StartsWith(userAgent)) &&
         maxInitialString < current.UserAgent.Length)
     {
         maxInitialString = current.UserAgent.Length;
         bestMatch = current;
     }
 }
Example #12
0
		public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
		{
			var ignored = base.OnCreateView(inflater, container, savedInstanceState);
			this.EnsureBindingContextIsSet(savedInstanceState);
			View _view = this.BindingInflate(Resource.Layout.MenuView, null);

			_deviceInfoPlugin = Mvx.Resolve<IMvxDeviceInfo>();
			_deviceInfo = _deviceInfoPlugin.GetDeviceInfo ();

			View mv = _view.FindViewById (Resource.Id.menu_view_layout_main);
			TreeListView treeView = (TreeListView)_view.FindViewById (Resource.Id.menu_categories_listview);
			return _view;
		}
Example #13
0
        /// <summary>
        /// 尝试登陆某一个设备
        /// </summary>
        /// <returns>是否登陆成功</returns>
        private bool LoginDevice(DeviceInfo loginInfo)
        {
            //某个设备可能回登陆失败所以要try。
            //todo
            try
            {
            }
            catch (Exception)
            {

                throw;
            }
            return true;
        }
        /// <summary>
        /// 把String转换成Object
        /// </summary>
        /// <param name="deviceConfig">按一定格式排列的设备信息字符串</param>
        private DeviceInfo StringToObject(string deviceConfig)
        {
            string[] configs = deviceConfig.Split(',');
            if (configs.Length == 7)
            {
                try
                {
                    DeviceInfo deviceLoginInfo = new DeviceInfo();

                    if (ParameterCheck.IsIpAddress(configs[0]))
                    {
                        deviceLoginInfo.Ip = configs[0];
                    }

                    LogInType type;
                    if (Enum.TryParse(configs[1],true,out type))
                    {
                        deviceLoginInfo.Type = type;
                    }

                    int port;
                    if (int.TryParse(configs[2], out port))
                    {
                        deviceLoginInfo.Port = port;
                    }

                    deviceLoginInfo.LoginReq = configs[3].Equals("true",StringComparison.CurrentCultureIgnoreCase);
                    LogInStatus status;
                    if (Enum.TryParse(configs[4], true, out status))
                    {
                        deviceLoginInfo.Status = status;
                    }

                    deviceLoginInfo.BelongTo = configs[5];

                    if (ParameterCheck.IsIpAddress(configs[6]))
                    {
                        deviceLoginInfo.LocalIp = configs[6];
                    }
                    return deviceLoginInfo;
                }
                catch (Exception)
                {
                    //todo log
                    return null;
                }
            }
            return null;
        }
Example #15
0
        /// <summary>
        /// 
        /// </summary>
        public MerchantInfo()
        {
            supportsManualRefunds = true;
            supportsTipAdjust = true;
            supportsVaultCards = true;
            supportsPreAuths = true;
            merchantID = "";
            merchantMId = "";
            merchantName = "";

            Device = new DeviceInfo();
            Device.Name = "";
            Device.Serial = "";
            Device.Model = "";
        }
Example #16
0
 private DeviceInfo BuildEntity()
 {
     DeviceInfo user = new DeviceInfo();
     user.ID = GetFormInteger("id");
     user.IP = Request.Form["ip"];
     user.Port = Request.Form["port"];
     user.DeviceType = Request.Form["deviceType"];
     user.UserName = Request.Form["userName"];
     user.Password = Request.Form["password"];
     user.AntNo = GetFormInteger("antNo");
     user.AccessFlag = GetFormInteger("accessFlag");
     user.Location = Request.Form["location"];
     user.Active = Request.Form["active"] == "true";
     return user;
 }
Example #17
0
        public Deployer81(string desiredDevice)
        {
            var devices = Utils.GetDevices();

            this.deviceInfo =
                devices.FirstOrDefault(x => x.ToString().StartsWith(desiredDevice, StringComparison.OrdinalIgnoreCase) && !x.ToString().Equals("Device"));

            // Exclude device
            if (this.deviceInfo == null)
            {
                Logger.Warn("Desired target {0} not found. Using default instead.", desiredDevice);

                this.deviceInfo = devices.First(x => !x.ToString().Equals("Device"));
            }

            Logger.Info("Target emulator: {0}", this.DeviceName);
        }
Example #18
0
    public static DisplayedDevice Create(
		Transform parentTransform, 
		Vector3 localPosition, 
		int deviceID, 
		DevicesDisplayer.DeviceType deviceType,
		DeviceInfo deviceInfo,
		DevicesDisplayer devicesDisplayer
		)
    {
        Debug.Log("create device "+deviceID
        + " parentTransform="+parentTransform
        + " localPosition="+localPosition
        + " deviceType="+deviceType
        + "deviceInfo="+deviceInfo
        + "devicesDisplayer="+devicesDisplayer);

        GameObject newDevice = Instantiate(prefab, new Vector3(0.0f, 0.0f, 0.0f), Quaternion.identity) as GameObject;
        newDevice.transform.parent = parentTransform;
        newDevice.transform.localPosition = localPosition;
        newDevice.transform.localScale = new Vector3(1f, 1f, 0);

        DisplayedDevice deviceScript = newDevice.GetComponent<DisplayedDevice>();
        deviceScript._deviceID = deviceID;
        deviceScript._deviceType = deviceType;
        deviceScript._deviceInfo = deviceInfo;
        deviceScript._devicesDisplayer = devicesDisplayer;
        deviceScript._currentSpriteName = deviceInfo._spriteName;
        /*
        //deviceScript._sprite = newDevice.transform.GetComponentInChildren<UISprite>();
        GameObject background = newDevice.transform.Find("Background").gameObject;
        if(background) {
            deviceScript._sprite = background.GetComponent<UISprite>();
            Debug.Log("init _sprite as "+deviceScript._sprite);
        } else {
            Debug.Log("init _sprite impossible: no background found");
        }
        */

        //do additional initialization steps here

        return deviceScript;
    }
Example #19
0
        internal static byte[] CreateKeyChange(DeviceInfo devInfo)
        {
            List<byte> keyChangePacket = new List<byte>();

            //LOCAL IP
            keyChangePacket.AddRange(MessageBuilder.HexToByteArray(GMPDataTags.DT_IP));
            keyChangePacket.AddRange(MessageBuilder.AddLength(6));

            String[] strLocalIP = getLocalIP().Split('.');//devInfo.DevIP.ToString().Split('.');

            String ip12Format = "";
            for (int i = 0; i < strLocalIP.Length; i++)
            {
                ip12Format += String.Format("{0:D3}", Convert.ToInt32(strLocalIP[i]));
            }
            for (int i = 0; i < ip12Format.Length; i++)
            {
                String strByte = ip12Format.Substring(i, 2);

                keyChangePacket.AddRange(MessageBuilder.ConvertIntToBCD(Convert.ToInt32(strByte), 1));
                i++;
            }

            //BRAND
            keyChangePacket.AddRange(MessageBuilder.HexToByteArray(GMPDataTags.DT_BRAND));
            keyChangePacket.AddRange(MessageBuilder.AddLength(devInfo.Brand.Length));
            keyChangePacket.AddRange(Encoding.ASCII.GetBytes(devInfo.Brand));

            //MODEL
            keyChangePacket.AddRange(MessageBuilder.HexToByteArray(GMPDataTags.DT_MODEL));
            keyChangePacket.AddRange(MessageBuilder.AddLength(devInfo.Model.Length));
            keyChangePacket.AddRange(Encoding.ASCII.GetBytes(devInfo.Model));

            //SERIAL
            keyChangePacket.AddRange(MessageBuilder.HexToByteArray(GMPDataTags.DT_SERIAL));
            keyChangePacket.AddRange(MessageBuilder.AddLength(devInfo.TerminalNo.Length));
            keyChangePacket.AddRange(Encoding.ASCII.GetBytes(devInfo.TerminalNo));

            return keyChangePacket.ToArray();
        }
        private EventInfo CreateEventInfoBase(Event errorData)
        {
            var appInfo = new AppInfo
            {
                Version = Config.AppVersion,
                ReleaseStage = Config.ReleaseStage,
                AppArchitecture = Diagnostics.AppArchitecture,
                ClrVersion = Diagnostics.ClrVersion
            };

            var userInfo = new UserInfo
            {
                Id = errorData.UserId,
                Email = errorData.UserEmail,
                Name = errorData.UserName
            };

            var deviceInfo = new DeviceInfo
            {
                OSVersion = Diagnostics.DetectedOSVersion,
                ServicePack = Diagnostics.ServicePack,
                OSArchitecture = Diagnostics.OSArchitecture,
                ProcessorCount = Diagnostics.ProcessorCount,
                MachineName = Diagnostics.MachineName,
                HostName = Diagnostics.HostName
            };

            var eventInfo = new EventInfo
            {
                App = appInfo,
                Device = deviceInfo,
                Severity = errorData.Severity,
                User = userInfo,
                Context = errorData.Context,
                GroupingHash = errorData.GroupingHash,
                Exceptions = new List<ExceptionInfo>()
            };
            return eventInfo;
        }
Example #21
0
        public Image Scan(DeviceInfo device, PageSize pageSize, ColorDepth colorDepth, Resolution resolution, Orientation orientation, bool setSize = true)
        {
            if (device == null)
                throw new ArgumentException("Device must be specified");

            var scanner = device.Connect();

            var wiaCommonDialog = new WPFCommonDialog();
            var item = scanner.Items[1];

            SetupPageSize(item, pageSize, colorDepth, resolution, orientation, setSize);

            var image = (ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false);

            string fileName = Path.GetTempFileName();
            File.Delete(fileName);
            image.SaveFile(fileName);
            image = null;

            // add file to output list
            return Image.FromFile(fileName);
        }
        public Deployer(string desiredDevice, bool strict, string appPath)
        {
            this.appPath = appPath;

            this.deviceInfo = Devices.Instance.GetMatchingDevice(desiredDevice, strict);

            if (this.deviceInfo == null)
            {
                throw new AutomationException(
                    string.Format(
                        "Could not find a device to launch. You requested '{0}', but the available devices were:\n{1}", 
                        desiredDevice, 
                        Devices.Instance));
            }

            var propertyInfo = this.deviceInfo.GetType().GetTypeInfo().GetDeclaredProperty("DeviceId");
            var deviceId = (string)propertyInfo.GetValue(this.deviceInfo);
            this.connectableDevice =
                new MultiTargetingConnectivity(CultureInfo.CurrentUICulture.LCID).GetConnectableDevice(deviceId);

            Logger.Info("Target emulator: '{0}'", this.DeviceName);
        }
Example #23
0
 public Task <ICommsSerial> GetBT(DeviceInfo first)
 {
     throw new NotImplementedException();
 }
Example #24
0
        /// <summary>
        /// Send response to the client according to request information
        /// </summary>
        /// <param name="request">Http request from client</param>
        /// <returns>A string corresponding to the status of the operation</returns>
        public string SendResponse(HttpListenerRequest request)
        {
            Console.WriteLine(request.Url);
            string rawUrl = request.RawUrl.Replace("%20", " ");

            string[] parsedRequest = rawUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            int fieldSize = parsedRequest.Length;

            if (parsedRequest.Length == 0)
            {
                return("");
            }
            else if (request.HttpMethod == "POST")
            {
                string           deviceRequested = parsedRequest[0];
                ControllerDevice device          = IsDeviceConnected(deviceRequested);
                if (device == null)
                {
                    return("Device Not Found");

                    throw new InvalidDeviceException("Device Not Found!");
                }
                else
                {
                    if (device.DeviceInfo.ApiType == "LocalLib")
                    {
                        int indexRequested = Int32.Parse(parsedRequest[1]);
                        IEnumerable <USBDeviceMethod> resultList =
                            from result in device.DeviceInfo.FunctionArray
                            where result.ButtonIndex == indexRequested
                            select result;

                        string     functionRequested = resultList.First().Name;
                        MethodInfo method            = GetMethodInfo(device, functionRequested);
                        if (method == null)
                        {
                            return("Method Not Found");

                            throw new InvalidMethodException("Method Not Found!");
                        }
                        else
                        {
                            Task.Run(() =>
                            {
                                bool lockTaken = false;
                                try
                                {
                                    Monitor.TryEnter(device._lock, ref lockTaken);
                                    if (lockTaken)
                                    {
                                        string[] parameters = new string[fieldSize - 2];
                                        Array.Copy(parsedRequest, 2, parameters, 0, fieldSize - 2);

                                        if (deviceRequested == "Jaco")
                                        {
                                            Console.WriteLine(method.Invoke(device.DeviceObject, parameters));
                                        }
                                        else
                                        {
                                            Array.Copy(parsedRequest, 2, parameters, 0, fieldSize - 2);
                                            method.Invoke(device.DeviceObject, parameters);
                                        }
                                    }
                                }
                                finally
                                {
                                    if (lockTaken)
                                    {
                                        Monitor.Exit(device._lock);
                                    }
                                }
                            });
                            return("OK");
                        }
                    }
                    else if (device.DeviceInfo.ApiType == "Http")
                    {
                        int indexRequested = Int32.Parse(parsedRequest[1]);
                        IEnumerable <RemoteDeviceMethod> resultList =
                            from result in device.DeviceInfo.Methods
                            where result.ButtonIndex == indexRequested
                            select result;

                        string     functionRequested = resultList.First().Method;
                        DeviceInfo deviceInfo        = device.DeviceInfo;
                        foreach (RemoteDeviceMethod method in deviceInfo.Methods)
                        {
                            if (method.Method == functionRequested)
                            {
                                HttpRequestMessage message;
                                if (device.DeviceInfo.Device == "Alexa")
                                {
                                    byte[] buffer = new byte[5000];
                                    request.InputStream.Read(buffer, 0, 5000);
                                    string content = System.Text.Encoding.UTF8.GetString(TrimNull(buffer));
                                    content = JsonConvert.DeserializeObject <Dictionary <string, string> >(method.Data)["input"] + content;
                                    content = JsonConvert.SerializeObject(new Dictionary <string, string> {
                                        ["input"] = content
                                    });
                                    message = FormRequestMessage(
                                        method.HttpMethod,
                                        method.Link,
                                        content
                                        );
                                    var response = SendToRemoteServerAsync(message).Result;
                                    if (!response.IsSuccessStatusCode)
                                    {
                                        string errorPhrase = response.ReasonPhrase;
                                        //return errorPhrase;
                                    }

                                    string result = response.Content.ReadAsStringAsync().Result;

                                    result = method.Link.Substring(0, method.Link.Length - 4) + result;
                                    Task.Run(() =>
                                    {
                                        bool lockTaken = false;
                                        try
                                        {
                                            Monitor.TryEnter(device._lock, ref lockTaken);
                                            if (lockTaken)
                                            {
                                                AudioPlayer.Play(result);
                                            }
                                        }
                                        finally
                                        {
                                            if (lockTaken)
                                            {
                                                Monitor.Exit(device._lock);
                                            }
                                        }
                                    });
                                }
                                else
                                {
                                    Task.Run(() =>
                                    {
                                        bool lockTaken = false;
                                        try
                                        {
                                            Monitor.TryEnter(device._lock, ref lockTaken);
                                            if (lockTaken)
                                            {
                                                message = FormRequestMessage(
                                                    method.HttpMethod,
                                                    method.Link,
                                                    method.Data,
                                                    "application/json"
                                                    );
                                                var result = SendToRemoteServerAsync(message);
                                            }
                                        }
                                        finally
                                        {
                                            if (lockTaken)
                                            {
                                                Monitor.Exit(device._lock);
                                            }
                                        }
                                    });
                                }
                            }
                            //else throw new InvalidMethodException("Method not found!");
                        }

                        return("OK");
                    }
                    else
                    {
                        return("Invalid Device API Type");

                        throw new InvalidDeviceException("Invalid device API type");
                    }
                }
            }


            else
            {
                return("Error");
            }
        }
        public DeviceInfo GetDeviceInfo()
        {
            var deviceInfo = new DeviceInfo
            {
                DeviceType      = "WindowsPhone",
                DeviceName      = DeviceStatus.DeviceName,
                HardwareVersion = DeviceStatus.DeviceHardwareVersion,
                SoftwareVersion = Environment.OSVersion.Version.ToString(),
                Manufacturer    = DeviceStatus.DeviceManufacturer
            };

            if (Environment.OSVersion.Version.Major >= 8)
            {
                object anid2;
                if (UserExtendedProperties.TryGetValue("ANID2", out anid2))
                {
                    if (anid2 != null)
                    {
                        deviceInfo.HardwareId = anid2.ToString();
                    }
                }
            }

            if (String.IsNullOrEmpty(deviceInfo.HardwareId))
            {
                object anid;
                if (UserExtendedProperties.TryGetValue("ANID", out anid))
                {
                    if (anid != null)
                    {
                        deviceInfo.HardwareId = anid.ToString();
                    }
                }
            }
#if DEBUG
            if (deviceInfo.DeviceName == "XDeviceEmulator")
            {
                deviceInfo.HardwareId = "Emulator";
            }
#endif

            var instance  = Application.Current.Host.Content;
            var getMethod = instance.GetType().GetProperty("ScaleFactor").GetGetMethod();
            var value     = (int)getMethod.Invoke(instance, null);

            deviceInfo.ScreenWidth  = 480;
            deviceInfo.ScreenHeight = 800;

            switch (value)
            {
            case 150:
                deviceInfo.ScreenWidth  = 720;
                deviceInfo.ScreenHeight = 1280;
                break;

            case 160:
                deviceInfo.ScreenWidth  = 768;
                deviceInfo.ScreenHeight = 1280;
                break;
            }
            return(deviceInfo);
        }
Example #26
0
        private static bool VerifyMachineCode(ref string stateCode)
        {
            bool VerifySign = false;

            try
            {
                if (!File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), @"TempPPF\protectppf.dat")))
                {
                    return(VerifySign);
                }
                using (StreamReader objInput = new StreamReader(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), @"TempPPF\protectppf.dat"), System.Text.Encoding.UTF8))
                {
                    string contents = CodeRegister.Decrypt("aoto0587", objInput.ReadToEnd().Trim());

                    contents = contents.Substring(contents.IndexOf("_") + 1, contents.Length - contents.IndexOf("_") - 1);

                    //string[] split = System.Text.RegularExpressions.Regex.Split(contents, "&", RegexOptions.None);

                    string curMachineCode = CodeRegister.GetMd5("南京奥拓电子" + DeviceInfo.Instance().CpuID + DeviceInfo.Instance().MacAddress + DeviceInfo.Instance().DiskID + DeviceInfo.Instance().SystemType);

                    if (contents.Contains(curMachineCode))
                    {
                        if (DateTime.Compare(DateTime.Now, DateTime.Parse(contents.Replace(curMachineCode + "_", ""))) < 0)
                        {
                            VerifySign = true;
                            stateCode  = "激活成功";
                        }
                    }
                }
            }
            catch
            {
                //不记录日志
                VerifySign = false;
            }
            finally
            {
                if (!VerifySign)
                {
                    stateCode = "激活失败";
                    File.Delete(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), @"TempPPF\protectppf.dat"));
                }
            }
            return(VerifySign);
        }
Example #27
0
        void UpdateDiDevices()
        {
            if (!UpdateDevicesEnabled)
            {
                return;
            }
            UpdateDevicesEnabled = false;
            // Make sure that interface handle is created, before starting device updates.
            UserDevice[] deleteDevices;
            // Add connected devices.
            var insertDevices = new List <UserDevice>();
            var updateDevices = new List <KeyValuePair <UserDevice, DeviceInstance> >();
            // List of connected devices (can be a very long operation).
            var devices = new List <DeviceInstance>();
            // Controllers.
            var controllerInstances = Manager.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AllDevices).ToList();

            foreach (var item in controllerInstances)
            {
                devices.Add(item);
            }
            // Pointers.
            var pointerInstances = Manager.GetDevices(DeviceClass.Pointer, DeviceEnumerationFlags.AllDevices).ToList();

            foreach (var item in pointerInstances)
            {
                devices.Add(item);
            }
            // Keyboards.
            var keyboardInstances = Manager.GetDevices(DeviceClass.Keyboard, DeviceEnumerationFlags.AllDevices).ToList();

            foreach (var item in keyboardInstances)
            {
                devices.Add(item);
            }
            if (Program.IsClosing)
            {
                return;
            }
            // List of connected devices.
            var deviceInstanceGuid = devices.Select(x => x.InstanceGuid).ToList();
            // List of current devices.
            var currentInstanceGuids = SettingsManager.UserDevices.Items.Select(x => x.InstanceGuid).ToArray();

            deleteDevices = SettingsManager.UserDevices.Items.Where(x => !deviceInstanceGuid.Contains(x.InstanceGuid)).ToArray();
            var addedDevices   = devices.Where(x => !currentInstanceGuids.Contains(x.InstanceGuid)).ToArray();
            var updatedDevices = devices.Where(x => currentInstanceGuids.Contains(x.InstanceGuid)).ToArray();

            // Must find better way to find Device than by Vendor ID and Product ID.
            if (addedDevices.Length > 0)
            {
                //Joystick    = new Guid("6f1d2b70-d5a0-11cf-bfc7-444553540000");
                //SysMouse    = new Guid("6f1d2b60-d5a0-11cf-bfc7-444553540000");
                //SysKeyboard = new Guid("6f1d2b61-d5a0-11cf-bfc7-444553540000");
                DeviceInfo[] devInfos = DeviceDetector.GetDevices();
                DeviceInfo[] intInfos = null;
                // Controllers.
                var controllers = addedDevices
                                  .Where(x => x.Type != SharpDX.DirectInput.DeviceType.Mouse && x.Type != SharpDX.DirectInput.DeviceType.Keyboard)
                                  .Select(x => new Joystick(Manager, x.InstanceGuid)).ToArray();
                // Get interfaces.
                var interfacePaths = controllers.Select(x => x.Properties.InterfacePath).ToArray();
                intInfos = DeviceDetector.GetInterfaces(interfacePaths);
                for (int i = 0; i < addedDevices.Length; i++)
                {
                    var device = addedDevices[i];
                    var ud     = new UserDevice();
                    RefreshDevice(ud, device);
                    DeviceInfo hid = null;
                    DeviceInfo dev = null;
                    if (device.IsHumanInterfaceDevice)
                    {
                        // Get interface info for added devices.
                        hid = intInfos.FirstOrDefault(x => x.DevicePath == ud.Device.Properties.InterfacePath);
                        // Get device info for added devices.
                        dev = devInfos.FirstOrDefault(x => x.DeviceId == ud.HidDeviceId);
                    }
                    ud.LoadHidDeviceInfo(hid);
                    ud.LoadDevDeviceInfo(dev);
                    var isVirtual = false;
                    if (hid != null)
                    {
                        DeviceInfo p = hid;
                        do
                        {
                            p = DeviceDetector.GetParentDevice(Guid.Empty, JocysCom.ClassLibrary.Win32.DIGCF.DIGCF_ALLCLASSES, p.DeviceId);
                            if (p != null && string.Compare(p.HardwareId, VirtualDriverInstaller.ViGEmBusHardwareId, true) == 0)
                            {
                                isVirtual = true;
                                break;
                            }
                        } while (p != null);
                    }
                    if (!isVirtual)
                    {
                        insertDevices.Add(ud);
                    }
                }
            }
            //if (insertDevices.Count > 0)
            //{
            //	CloudPanel.Add(CloudAction.Insert, insertDevices.ToArray(), true);
            //}
            for (int i = 0; i < updatedDevices.Length; i++)
            {
                var device = updatedDevices[i];
                var di     = SettingsManager.UserDevices.Items.First(x => x.InstanceGuid.Equals(device.InstanceGuid));
                updateDevices.Add(new KeyValuePair <UserDevice, DeviceInstance>(di, device));
            }
            if (Program.IsClosing)
            {
                return;
            }
            // Remove disconnected devices.
            for (int i = 0; i < deleteDevices.Length; i++)
            {
                deleteDevices[i].IsOnline = false;
            }
            for (int i = 0; i < insertDevices.Count; i++)
            {
                var ud = insertDevices[i];
                SettingsManager.UserDevices.Items.Add(ud);
            }
            for (int i = 0; i < updateDevices.Count; i++)
            {
                var kv = updateDevices[i];
                RefreshDevice(kv.Key, kv.Value);
            }
            // Enable Test instances.
            TestDeviceHelper.EnableTestInstances();
            RefreshDevicesCount++;
            var ev = DevicesUpdated;

            if (ev != null)
            {
                ev(this, new DInputEventArgs());
            }
            //	var game = CurrentGame;
            //	if (game != null)
            //	{
            //		// Auto-configure new devices.
            //		AutoConfigure(game);
            //	}
        }
Example #28
0
 public void Setup()
 {
     DeviceInfo.SetCurrent(mockDeviceInfo = new MockDeviceInfo());
 }
Example #29
0
        public bool CardReaderIdentifier(string vidStrg, string pidStrg, string optionalStrg)
        {
            uint deviceCount = 0;
            uint apiOpt;
            int  dwSize      = (Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));
            bool devicefound = false;

            if (vidStrg == "")
            {
                vidStrg = "VID_1243";
            }
            if (pidStrg == "")
            {
                pidStrg = "PID_E000";
            }
            if (optionalStrg == "")
            {
                optionalStrg = "MI_00";
            }
            if (GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, (uint)dwSize) != 0)
            {
                throw new ApplicationException("An error occurred while retrieving the list of devices. Error in GetRawInputDeviceList. Detailed Error is " + ProcessLastError());
            }
            IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int)(dwSize * deviceCount));

            if (pRawInputDeviceList == null)
            {
                throw new ApplicationException("Memory allocation failed");
            }

            apiOpt = GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, (uint)dwSize);
            if (apiOpt < 0)
            {
                throw new ApplicationException("Could not fetch raw device list. Failure in GetRawInputDeviceList - Second call. Detailed Error is " + ProcessLastError());
            }

            for (uint devCount = 0; devCount < deviceCount; devCount++)
            {
                string deviceName;
                uint   pcbSize = 0;

                RAWINPUTDEVICELIST rid = (RAWINPUTDEVICELIST)Marshal.PtrToStructure(
                    new IntPtr((pRawInputDeviceList.ToInt32() + (dwSize * devCount))),
                    typeof(RAWINPUTDEVICELIST));

                GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, IntPtr.Zero, ref pcbSize);

                if (pcbSize > 0)
                {
                    IntPtr pData = Marshal.AllocHGlobal((int)pcbSize);
                    GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, pData, ref pcbSize);
                    deviceName = (string)Marshal.PtrToStringAnsi(pData);
                    String upperCasedeviceName = deviceName.ToUpper();
                    if (rid.dwType == RIM_TYPEKEYBOARD)
                    {
                        if (upperCasedeviceName.Contains(vidStrg.ToUpper()) && upperCasedeviceName.Contains(pidStrg.ToUpper()) && upperCasedeviceName.Contains(optionalStrg.ToUpper()))
                        {
                            if (devicefound == false)
                            {
                                devicefound        = true;
                                dInfo              = new DeviceInfo();
                                dInfo.deviceName   = deviceName;
                                dInfo.deviceHandle = rid.hDevice;
                                dInfo.deviceType   = GetDeviceType(rid.dwType);
                                dInfo.Name         = deviceName;
                            }
                            else
                            {
                                throw new ApplicationException("Multiple card readers have been found with the same vendor and product id");
                            }
                        }
                    }
                    Marshal.FreeHGlobal(pData);
                }
            }
            Marshal.FreeHGlobal(pRawInputDeviceList);
            return(devicefound);
        }
Example #30
0
        private bool setAudioDevice(string preferredDevice = null)
        {
            updateAvailableAudioDevices();

            string oldDevice = currentAudioDevice;
            string newDevice = preferredDevice;

            if (string.IsNullOrEmpty(newDevice))
            {
                newDevice = audioDevices.Find(df => df.IsDefault).Name;
            }

            bool oldDeviceValid = Bass.CurrentDevice >= 0;

            if (oldDeviceValid)
            {
                DeviceInfo oldDeviceInfo = Bass.GetDeviceInfo(Bass.CurrentDevice);
                oldDeviceValid &= oldDeviceInfo.IsEnabled && oldDeviceInfo.IsInitialized;
            }

            if (newDevice == oldDevice)
            {
                //check the old device is still valid
                if (oldDeviceValid)
                {
                    return(true);
                }
            }

            if (string.IsNullOrEmpty(newDevice))
            {
                return(false);
            }

            int newDeviceIndex = audioDevices.FindIndex(df => df.Name == newDevice);

            DeviceInfo newDeviceInfo = new DeviceInfo();

            try
            {
                if (newDeviceIndex >= 0)
                {
                    newDeviceInfo = Bass.GetDeviceInfo(newDeviceIndex);
                }
                //we may have previously initialised this device.
            }
            catch
            {
            }

            if (oldDeviceValid && (newDeviceInfo.Driver == null || !newDeviceInfo.IsEnabled))
            {
                //handles the case we are trying to load a user setting which is currently unavailable,
                //and we have already fallen back to a sane default.
                return(true);
            }

            if (!Bass.Init(newDeviceIndex) && Bass.LastError != Errors.Already)
            {
                //the new device didn't go as planned. we need another option.

                if (preferredDevice == null)
                {
                    //we're f****d. the default device won't initialise.
                    currentAudioDevice = null;
                    return(false);
                }

                //let's try again using the default device.
                return(setAudioDevice());
            }

            if (Bass.LastError == Errors.Already)
            {
                // We check if the initialization error is that we already initialized the device
                // If it is, it means we can just tell Bass to use the already initialized device without much
                // other fuzz.
                Bass.CurrentDevice = newDeviceIndex;
                Bass.Free();
                Bass.Init(newDeviceIndex);
            }

            Trace.Assert(Bass.LastError == Errors.OK);

            //we have successfully initialised a new device.
            currentAudioDevice = newDevice;

            UpdateDevice(newDeviceIndex);

            Bass.PlaybackBufferLength = 100;
            Bass.UpdatePeriod         = 5;

            return(true);
        }
Example #31
0
    static void Load(UserSettings settings)
    {
        m_PrimaryKey = CloudUser.instance.primaryKey;         // we need this to use back-compatible approach

        string json = settings != null?settings.GetString("options", null) : null;

        JsonData data = string.IsNullOrEmpty(json) == false?JsonMapper.ToObject(json) : null;

        sensitivity = GetFloat(data, "Sensitivity", DefaultSensitivity);
        soundVolume = GetFloat(data, "SoundVolume", DefaultSoundVolume);
        musicVolume = GetFloat(data, "MusicVolume", DefaultMusicVolume);
        subtitles   = GetBool(data, "Subtitles", DefaultSubtitles);
        invertYAxis = GetBool(data, "InvertYAxis", DefaultInvertYAxis);
        fullScreenResolution.width  = GetInt(data, "FullScreenWidth", 0);
        fullScreenResolution.height = GetInt(data, "FullScreenHeight", 0);

        leftHandAiming  = GetBool(data, "LeftHandAiming", DefaultLeftHandAiming);
        m_ControlScheme = (GuiOptions.E_ControlScheme)GetInt(data, "ControlScheme", (int)DefaultScheme);

        //rozmisteni controls
        FireUseButton.Offset.x = GetFloat(data, "FireButtonX", 0);
        FireUseButton.Offset.y = GetFloat(data, "FireButtonY", 0);

        //PauseButton.Offset.x = GetFloat(data, "PauseButtonX", 0);
        //PauseButton.Offset.y = GetFloat(data, "PauseButtonY", 0);

        WeaponButton.Offset.x = GetFloat(data, "WeaponButtonX", 0);
        WeaponButton.Offset.y = GetFloat(data, "WeaponButtonY", 0);

        for (int i = 0; i < GadgetButtons.Length; i++)
        {
            GadgetButtons[i].Offset.x = GetFloat(data, "GadgetButtonX" + i, 0);
            GadgetButtons[i].Offset.y = GetFloat(data, "GadgetButtonY" + i, 0);
        }

        MoveStick.Offset.x = GetFloat(data, "MoveStickX", 0);
        MoveStick.Offset.y = GetFloat(data, "MoveStickY", 0);

        ReloadButton.Offset.x = GetFloat(data, "ReloadButtonX", 0);
        ReloadButton.Offset.y = GetFloat(data, "ReloadButtonY", 0);

        RollButton.Offset.x = GetFloat(data, "RollButtonX", 0);
        RollButton.Offset.y = GetFloat(data, "RollButtonY", 0);

        SprintButton.Offset.x = GetFloat(data, "SprintButtonX", 0);
        SprintButton.Offset.y = GetFloat(data, "SprintButtonY", 0);

        floatingFireButton = GetBool(data, "FireButtonFloating", false);
        fireButtonScale    = GetFloat(data, "FireButtonScale", 1.0f);

        // we need to store this value into player prefs
        // so it's global and we can read it on app start
        graphicDetail = PlayerPrefs.GetInt("GraphicDetail", GetDefaultGraphics());

        musicOn = GetBool(data, "MusicOn", DefaultMusicOn);

        showHints = GetBool(data, "ShowHints", true);

        showMogaHelp = GetBool(data, "ShowMogaHelp", true);
        // apply options ...

        if (MusicManager.Instance)
        {
            MusicManager.Instance.ApplyOptionsChange();
        }

        DeviceInfo.Initialize((DeviceInfo.Performance)graphicDetail);

        try
        {
            language = (E_Language)GetInt(data, "Language", (int)DefaultLanguage);
        }
        catch (System.Exception e)
        {
            Debug.LogException(e);
            language = DefaultLanguage;
        }

        AudioListener.volume = soundVolume;
    }
Example #32
0
 public static int GetDefaultGraphics()
 {
     return((int)DeviceInfo.GetDetectedPerformanceLevel());
 }
Example #33
0
    //--------------------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------------------

    void ApplyGraphicsOptions()
    {
#if UNITY_EDITOR
        DeviceInfo.Initialize((DeviceInfo.Performance)GuiOptions.graphicDetail);
#endif
    }
Example #34
0
 public void TearDown()
 {
     DeviceInfo.SetCurrent(null);
 }
        private bool PrepareDevice_WASAPI()
        {
            Log.Debug("Initializing WASAPI device: {0}...", _Profile.WASAPIDevice);

              _WASAPIDeviceNumber = -1;
              BASS_WASAPI_DEVICEINFO[] devices = BassWasapi.BASS_WASAPI_GetDeviceInfos();
              for (int i = 0; i < devices.Length; i++)
              {
            if (devices[i].name == _Profile.WASAPIDevice)
            {
              _WASAPIDeviceNumber = i;
              break;
            }
              }

              bool result = (_WASAPIDeviceNumber > -1);
              if (!result)
            HandleError(ErrorCode.MiscError, "Specified WASAPI device not found.");

              if (result)
              {
            string sharedDescr = _Profile.WASAPIExclusive ? "exclusive" : "shared";
            string eventDescr = _Profile.WASAPIEvent ? "pull" : "push";

            Log.Info("Using WASAPI Device {0}, {1}, {2}", _Profile.WASAPIDevice, sharedDescr, eventDescr);
            BASS_WASAPI_DEVICEINFO wasapiDeviceInfo = BassWasapi.BASS_WASAPI_GetDeviceInfo(_WASAPIDeviceNumber);

            _DeviceInfo = new WASAPIDeviceInfo(wasapiDeviceInfo, _Profile.WASAPIExclusive, GetMinExclWASAPIRate(), GetMaxExclWASAPIRate(), GetExclWASAPIChannels());
              }

              return result;
        }
 private static extern OpenCLErrorCode clGetDeviceInfo(IntPtr device,
                                                 DeviceInfo paramName,
                                                 IntPtr paramValueSize,
                                                 IntPtr paramValue,
                                                 out IntPtr paramValueSizeRet);
        // Token: 0x060000B9 RID: 185 RVA: 0x00008144 File Offset: 0x00006344
        private void CleanUpOldDevices(MailboxSession mailboxSession)
        {
            int num = 0;

            try
            {
                IThrottlingPolicy throttlingPolicy = (this.budget != null) ? this.budget.ThrottlingPolicy : null;
                if (throttlingPolicy == null || throttlingPolicy.EasMaxInactivityForDeviceCleanup.IsUnlimited || GlobalSettings.MaxNoOfPartnershipToAutoClean == 0)
                {
                    AirSyncDiagnostics.TraceInfo <string, int>(ExTraceGlobals.RequestsTracer, null, "No cleanUp required for stale devices. Reason:{0}, MaxNoOfPartnershipsToAutoClean:{1}", (throttlingPolicy == null) ? "No throttling policy set." : "EasMaxInactivityForDeviceCleanup set to Unlimited.", GlobalSettings.MaxNoOfPartnershipToAutoClean);
                }
                else
                {
                    TimeSpan          timeSpan          = TimeSpan.FromDays(throttlingPolicy.EasMaxInactivityForDeviceCleanup.Value);
                    ExDateTime        utcNow            = ExDateTime.UtcNow;
                    MobileDevice[]    easDevices        = null;
                    ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
                    {
                        easDevices = this.session.Find <MobileDevice>(MobileDevice.GetRootId(this.userId), QueryScope.OneLevel, null, null, 0);
                    });
                    if (!adoperationResult.Succeeded)
                    {
                        AirSyncDiagnostics.TraceDebug <string>(ExTraceGlobals.RequestsTracer, null, "Exception occurred during AD Operation during . Message:{0}", adoperationResult.Exception.Message);
                    }
                    else
                    {
                        if (easDevices != null)
                        {
                            List <MobileDevice> list = new List <MobileDevice>(easDevices);
                            if (!this.CleanUpMangledDevices(list, out num))
                            {
                                goto IL_271;
                            }
                            using (List <MobileDevice> .Enumerator enumerator = list.GetEnumerator())
                            {
                                while (enumerator.MoveNext())
                                {
                                    MobileDevice device = enumerator.Current;
                                    if (device.WhenChangedUTC == null || !(ExDateTime.UtcNow.Subtract(new ExDateTime(ExTimeZone.UtcTimeZone, device.WhenChangedUTC.Value)) < timeSpan))
                                    {
                                        if (DeviceInfo.CleanUpMobileDevice(mailboxSession, DeviceIdentity.FromMobileDevice(device), timeSpan))
                                        {
                                            AirSyncDiagnostics.TraceDebug <MobileClientType, string, string>(ExTraceGlobals.RequestsTracer, null, "Delete device from AD as it doesn't exist in sync state. ClientType :{0} , DeviceType:{1}, DeviceId:{2}", device.ClientType, device.DeviceType, device.DeviceId);
                                            adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
                                            {
                                                this.session.Delete(device);
                                            });
                                            if (!adoperationResult.Succeeded)
                                            {
                                                AirSyncDiagnostics.TraceDebug <string>(ExTraceGlobals.RequestsTracer, null, "Exception occurred during AD Operation during . Message:{0}", adoperationResult.Exception.Message);
                                            }
                                            num++;
                                        }
                                        TimeSpan t = ExDateTime.UtcNow.Subtract(utcNow);
                                        if (num >= GlobalSettings.MaxNoOfPartnershipToAutoClean || t >= GlobalSettings.MaxCleanUpExecutionTime)
                                        {
                                            AirSyncDiagnostics.TraceDebug <int, double>(ExTraceGlobals.RequestsTracer, null, "Done Cleaning up stale devices. DevicesCleaned:{0}, ExecutionTime(in ms):{1}", num, t.TotalMilliseconds);
                                            break;
                                        }
                                    }
                                }
                                goto IL_271;
                            }
                        }
                        AirSyncDiagnostics.TraceInfo(ExTraceGlobals.RequestsTracer, null, "No devices in AD for current user.");
                        IL_271 :;
                    }
                }
            }
            finally
            {
                if (this.clientType != MobileClientType.MOWA && Command.CurrentCommand != null)
                {
                    Command.CurrentCommand.ProtocolLogger.SetValue(ProtocolLoggerData.NoOfDevicesRemoved, num);
                }
            }
        }
Example #38
0
 internal static extern uint GetRawInputDeviceInfo(
   IntPtr deviceHandle,
   uint uiCommand,
   ref DeviceInfo data,
   ref uint dataSize);
Example #39
0
        private static bool VerifyMachineCode(string keypath)
        {
            bool VerifySign = false;

            try
            {
                using (StreamReader objInput = new StreamReader(Path.Combine(keypath, ""), System.Text.Encoding.UTF8))
                {
                    string[] strContents = objInput.ReadToEnd().Trim().TrimEnd('&').Split('&');

                    string deviceInfo = DeviceInfo.Instance().CpuID + DeviceInfo.Instance().MacAddress + DeviceInfo.Instance().DiskID + DeviceInfo.Instance().SystemType;

                    string curMachineCode = CodeRegister.GetMd5("南京奥拓电子" + deviceInfo);

                    foreach (string var in strContents)
                    {
                        string contents = CodeRegister.Decrypt("aoto0587", var);

                        contents = contents.Substring(contents.IndexOf("_") + 1, contents.Length - contents.IndexOf("_") - 1);
                        if (contents.Contains(curMachineCode))
                        {
                            if (DateTime.Compare(DateTime.Now, DateTime.Parse(contents.Replace(curMachineCode + "_", ""))) < 0)
                            {
                                if (File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), @"TempPPF\protectppf.dat")))
                                {
                                    File.Delete(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), @"TempPPF\protectppf.dat"));
                                }
                                using (Stream strSall = new FileStream(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), @"TempPPF\protectppf.dat"), FileMode.Create, FileAccess.Write))
                                {
                                    using (StreamWriter strWirtSall = new StreamWriter(strSall, UTF8Encoding.UTF8))
                                    {
                                        strWirtSall.Write(var);
                                    }
                                }

                                VerifySign = true;
                                break;
                            }
                        }
                    }
                }
            }
            catch
            {
                //不记录日志
                VerifySign = false;
            }

            return(VerifySign);
        }
Example #40
0
 private void UPnPControlPointSearchSink(
     IPEndPoint source,
     IPEndPoint local,
     Uri LocationURL,
     string USN,
     string SearchTarget,
     int MaxAge
 )
 {
     lock (this.deviceTableLock)
     {
         if (!this.deviceTable.ContainsKey(USN))
         {
             DeviceInfo info = new DeviceInfo();
             info.Device = null;
             info.UDN = USN;
             info.NotifyTime = DateTime.Now;
             info.BaseURL = LocationURL;
             info.MaxAge = MaxAge;
             info.LocalEP = local;
             info.SourceEP = source;
             this.deviceTable[USN] = info;
             this.deviceFactory.CreateDevice(info.BaseURL, info.MaxAge, IPAddress.Any, info.UDN);
         }
         else
         {
             DeviceInfo info2 = (DeviceInfo)this.deviceTable[USN];
             if (info2.Device != null)
             {
                 if (info2.BaseURL.Equals(LocationURL))
                 {
                     this.deviceUpdateClock.Remove(info2);
                     info2.PendingBaseURL = null;
                     info2.PendingMaxAge = 0;
                     info2.PendingLocalEP = null;
                     info2.PendingSourceEP = null;
                     info2.NotifyTime = DateTime.Now;
                     this.deviceTable[USN] = info2;
                     this.deviceLifeTimeClock.Add(info2.UDN, MaxAge);
                 }
                 else if (info2.NotifyTime.AddSeconds(10.0).Ticks < DateTime.Now.Ticks)
                 {
                     info2.PendingBaseURL = LocationURL;
                     info2.PendingMaxAge = MaxAge;
                     info2.PendingLocalEP = local;
                     info2.PendingSourceEP = source;
                     this.deviceUpdateClock.Add(info2.UDN, 3);
                 }
             }
         }
     }
 }
Example #41
0
 public void Init(DeviceInfo deviceInfo)
 {
     Socket = new SocketInfo(deviceInfo);
 }
Example #42
0
 public extern static int clGetDeviceInfo(
     IntPtr device,
     DeviceInfo param_name,
     IntPtr param_value_size,
     byte[] param_value,
     out IntPtr param_value_size_ret);
Example #43
0
        internal static DeviceInfo[] GetList()
        {
            var deviceIDs = new List <string>();

            try
            {
                var mgmtObjSearcher =
                    new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
                var objCol = mgmtObjSearcher.Get();

                deviceIDs.AddRange(from ManagementObject drive in objCol select(string) drive["DeviceID"]);

                mgmtObjSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_TapeDrive");
                objCol          = mgmtObjSearcher.Get();

                deviceIDs.AddRange(from ManagementObject drive in objCol select(string) drive["DeviceID"]);

                mgmtObjSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_CDROMDrive");
                objCol          = mgmtObjSearcher.Get();

                deviceIDs.AddRange(from ManagementObject drive in objCol select(string) drive["Drive"]);
            }
            catch (Exception)
            {
#if DEBUG
                throw;
#else
                return(null);
#endif
            }

            var devList = new List <DeviceInfo>();

            foreach (var devId in deviceIDs)
            {
                if (devId is null)
                {
                    continue;
                }

                var physId = devId;
                // TODO: This can be done better
                if (devId.Length == 2 && devId[1] == ':')
                {
                    physId = "\\\\?\\" + devId;
                }
                var fd = Extern.CreateFile(physId, 0, FileShare.Read | FileShare.Write, IntPtr.Zero,
                                           FileMode.OpenExisting, 0, IntPtr.Zero);
                if (fd.IsInvalid)
                {
                    continue;
                }

                var query = new StoragePropertyQuery
                {
                    PropertyId           = StoragePropertyId.Device,
                    QueryType            = StorageQueryType.Standard,
                    AdditionalParameters = new byte[1]
                };

                //StorageDeviceDescriptor descriptor = new StorageDeviceDescriptor();
                //descriptor.RawDeviceProperties = new byte[16384];

                var descriptorPtr = Marshal.AllocHGlobal(1000);
                var descriptorB   = new byte[1000];

                uint returned = 0;
                var  error    = 0;

                var hasError = !Extern.DeviceIoControlStorageQuery(fd, WindowsIoctl.IoctlStorageQueryProperty,
                                                                   ref query, (uint)Marshal.SizeOf(query),
                                                                   descriptorPtr, 1000, ref returned, IntPtr.Zero);

                if (hasError)
                {
                    error = Marshal.GetLastWin32Error();
                }

                Marshal.Copy(descriptorPtr, descriptorB, 0, 1000);

                if (hasError && error != 0)
                {
                    continue;
                }

                var descriptor = new StorageDeviceDescriptor
                {
                    Version               = BitConverter.ToUInt32(descriptorB, 0),
                    Size                  = BitConverter.ToUInt32(descriptorB, 4),
                    DeviceType            = descriptorB[8],
                    DeviceTypeModifier    = descriptorB[9],
                    RemovableMedia        = BitConverter.ToBoolean(descriptorB, 10),
                    CommandQueueing       = BitConverter.ToBoolean(descriptorB, 11),
                    VendorIdOffset        = BitConverter.ToInt32(descriptorB, 12),
                    ProductIdOffset       = BitConverter.ToInt32(descriptorB, 16),
                    ProductRevisionOffset = BitConverter.ToInt32(descriptorB, 20),
                    SerialNumberOffset    = BitConverter.ToInt32(descriptorB, 24),
                    BusType               = (StorageBusType)BitConverter.ToUInt32(descriptorB, 28),
                    RawPropertiesLength   = BitConverter.ToUInt32(descriptorB, 32)
                };

                var info = new DeviceInfo {
                    Path = physId, Bus = descriptor.BusType.ToString()
                };

                if (descriptor.VendorIdOffset > 0)
                {
                    info.Vendor =
                        StringHandlers.CToString(descriptorB, Encoding.ASCII, start: descriptor.VendorIdOffset);
                }
                if (descriptor.ProductIdOffset > 0)
                {
                    info.Model =
                        StringHandlers.CToString(descriptorB, Encoding.ASCII, start: descriptor.ProductIdOffset);
                }
                // TODO: Get serial number of SCSI and USB devices, probably also FireWire (untested)
                if (descriptor.SerialNumberOffset > 0)
                {
                    info.Serial =
                        StringHandlers.CToString(descriptorB, Encoding.ASCII, start: descriptor.SerialNumberOffset);

                    // fix any serial numbers that are returned as hex-strings
                    if (Array.TrueForAll(info.Serial.ToCharArray(), c => "0123456789abcdef".IndexOf(c) >= 0) &&
                        info.Serial.Length == 40)
                    {
                        info.Serial = HexStringToString(info.Serial).Trim();
                    }
                }

                if ((string.IsNullOrEmpty(info.Vendor) || info.Vendor == "ATA") && info.Model != null)
                {
                    var pieces = info.Model.Split(' ');
                    if (pieces.Length > 1)
                    {
                        info.Vendor = pieces[0];
                        info.Model  = info.Model.Substring(pieces[0].Length + 1);
                    }
                }

                switch (descriptor.BusType)
                {
                case StorageBusType.SCSI:
                case StorageBusType.ATAPI:
                case StorageBusType.ATA:
                case StorageBusType.FireWire:
                case StorageBusType.SSA:
                case StorageBusType.Fibre:
                case StorageBusType.USB:
                case StorageBusType.iSCSI:
                case StorageBusType.SAS:
                case StorageBusType.SATA:
                case StorageBusType.SecureDigital:
                case StorageBusType.MultiMediaCard:
                    info.Supported = true;
                    break;
                }

                Marshal.FreeHGlobal(descriptorPtr);
                devList.Add(info);
            }

            var devices = devList.ToArray();

            return(devices);
        }
Example #44
0
        private void dybutton_Click(object sender, EventArgs e)
        {
            #region verify
            if (string.IsNullOrEmpty(zhtextBox.Text.Trim()))
            {
                ShowMeg(q(Msg_Type.msgzhnoempty));//"幢号信息不能为空");
                return;
            }
            if (string.IsNullOrEmpty(kssjdateTimePicker.Text.Trim()))
            {
                ShowMeg(q(Msg_Type.msgslkssjnoempty));//"开始时间不能为空");
                return;
            }
            if (judge.IsDate(jssjdateTimePicker.Text.Trim()) == false)
            {
                //ShowMeg("开始时间不能正确的时间格式");
                ShowMeg(q(Msg_Type.msgkssjformat));
                return;
            }
            if (string.IsNullOrEmpty(jssjdateTimePicker.Text.Trim()))
            {
                ShowMeg(q(Msg_Type.msgjssjnoempty));//"结束时间不能为空");
                return;
            }
            if (judge.IsDate(jssjdateTimePicker.Text.Trim()) == false)
            {
                ShowMeg(q(Msg_Type.msgjssjformat));
                return;
            }
            TimeSpan midtine = DateTime.Parse(jssjdateTimePicker.Text.Trim()) - DateTime.Parse(kssjdateTimePicker.Text.Trim());
            if (midtine.TotalMinutes < 0)
            {
                ShowMeg(q(Msg_Type.msgksgtjs));
                return;
            }
            else if (midtine.TotalMinutes == 0)
            {
                ShowMeg(q(Msg_Type.msgkssjnqjssj));//"开始时间不能等于结束时间"
                return;
            }


            if (Convert.ToInt32(fsnumericUpDown.Value) <= 0)
            {
                ShowMeg(q(Msg_Type.msgprintnoempty));//"打印张数必须大于0");
                return;
            }
            if (string.IsNullOrEmpty(pctextBox.Text.Trim()))
            {
                ShowMeg(q(Msg_Type.msgpcnoempty));//"批次信息不能为空");
                return;
            }
            if (pctextBox.Text.Trim().Length > 10)
            {
                ShowMeg(q(Msg_Type.msgpclengthten));//"批次信息不能超过10位");
                return;
            }
            if (string.IsNullOrEmpty(bstextBox.Text.Trim()))
            {
                ShowMeg(q(Msg_Type.msgbsnoempty));//"板数信息不能为空");
                return;
            }
            if (string.IsNullOrEmpty(mbsltextBox.Text.Trim()))
            {
                ShowMeg(q(Msg_Type.msgmbslnoempty));//"每板数量不能为空");
                return;
            }

            if (MES_PD_SCRW_LIST.GC == BranchGC)
            {
                if (!bzrichTextBox.Text.Contains(ZXVerifyStr))
                {
                    ShowMeg("工厂" + MES_PD_SCRW_LIST.GC + "必须有\"" + ZXVerifyStr + "\"信息");
                    return;
                }
                else
                {
                    //int index = bzrichTextBox.Text.IndexOf(ZXVerifyStr) + 4;
                    //if (bzrichTextBox.Text.Length == index)
                    //{
                    //    ShowMeg(MES_PD_SCRW_LIST.GCDYMS + "必须填写\""+ZXVerifyStr+"\" 相关信息");
                    // return;
                    //}
                }
            }
            #endregion
            int ws = 0;
            if (IsLR61scx)
            {
                if (Convert.ToString(sdxtcombobox.SelectedValue).Equals("0"))
                {
                    ShowMeg(q(Msg_Type.msglr61havesdxt));//"LR61素电必须选择素电线体"
                    return;
                }
            }

            if (!string.IsNullOrEmpty(wstextBox.Text.Trim()))
            {
                ws = Convert.ToInt32(wstextBox.Text.Trim());
            }

            MES_PD_SCRW_ZXCC_INSERT model = new MES_PD_SCRW_ZXCC_INSERT();
            if (!Convert.ToString(zflbcomboBox.SelectedValue).Equals("0"))
            {
                model.ZFDCLB = Convert.ToInt32(zflbcomboBox.SelectedValue);
            }
            model.GC     = MES_PD_SCRW_LIST.GC;
            model.RWBH   = MES_PD_SCRW_LIST.RWBH;
            model.TH     = Convert.ToInt32(zhtextBox.Text.Trim());
            model.KSTIME = kssjdateTimePicker.Text.Trim();
            model.JSTIME = jssjdateTimePicker.Text.Trim();
            model.JLR    = Convert.ToInt32(getUserInfo("staffid"));
            model.CPZT   = Convert.ToInt32(cpztcomboBox.SelectedValue);
            model.PC     = pctextBox.Text.Trim();

            model.REMARK   = bzrichTextBox.Text;
            model.DCSLBS   = Convert.ToInt32(bstextBox.Text.Trim());
            model.DCSLMBSL = Convert.ToInt32(mbsltextBox.Text.Trim());
            model.DCSLYS   = ws;
            model.SL       = Convert.ToDecimal(hjsltextBox.Text.Trim());
            model.TMSX     = (int)Print_Type.zxlot;
            model.TMLB     = 1;
            model.MAC      = DeviceInfo.GetNetCardMAC().Substring(0, 17);
            MES_RETURN_UI res = ServicModel.PD_SCRW.ZX_CC(model, getToken());
            if (res.TYPE.Equals("S"))
            {
                PrintInfoByTM(res.TM, res.GC, Convert.ToInt32(fsnumericUpDown.Value), RigthType, Print_Type.zxlot);
                if (block != null)
                {
                    block(model.RWBH);
                    this.Close();
                }
            }
            else
            {
                ShowMeg(res.MESSAGE);
            }
        }
Example #45
0
        void ShowDeviceInfo(Joystick device, DeviceInfo dInfo)
        {
            if (device == null)
            {
                // clean everything here.
                AppHelper.SetText(DeviceProductNameTextBox, "");
                AppHelper.SetText(DeviceVendorNameTextBox, "");
                AppHelper.SetText(DeviceProductGuidTextBox, "");
                AppHelper.SetText(DeviceInstanceGuidTextBox, "");
                AppHelper.SetText(DiCapFfStateTextBox, "");
                AppHelper.SetText(DiCapAxesTextBox, "");
                AppHelper.SetText(DiCapButtonsTextBox, "");
                AppHelper.SetText(DiCapDPadsTextBox, "");
                if (DiEffectsTable.Rows.Count > 0)
                {
                    DiEffectsTable.Rows.Clear();
                }
                return;
            }
            lock (MainForm.XInputLock)
            {
                var isLoaded = XInput.IsLoaded;
                if (isLoaded)
                {
                    XInput.FreeLibrary();
                }
                device.Unacquire();
                device.SetCooperativeLevel(MainForm.Current, CooperativeLevel.Foreground | CooperativeLevel.Exclusive);
                effects = new List <EffectInfo>();
                try
                {
                    device.Acquire();
                    var forceFeedback = device.Capabilities.Flags.HasFlag(DeviceFlags.ForceFeedback);
                    forceFeedbackState = forceFeedback ? "YES" : "NO";
                    effects            = device.GetEffects(EffectType.All);
                }
                catch (Exception)
                {
                    forceFeedbackState = "ERROR";
                }
                DiEffectsTable.Rows.Clear();
                foreach (var eff in effects)
                {
                    DiEffectsTable.Rows.Add(new object[] {
                        eff.Name,
                        ((EffectParameterFlags)eff.StaticParameters).ToString(),
                        ((EffectParameterFlags)eff.DynamicParameters).ToString()
                    });
                }
                device.Unacquire();
                device.SetCooperativeLevel(MainForm.Current, CooperativeLevel.Background | CooperativeLevel.NonExclusive);
                if (isLoaded)
                {
                    Exception error;
                    XInput.ReLoadLibrary(XInput.LibraryName, out error);
                }
            }
            AppHelper.SetText(DiCapFfStateTextBox, forceFeedbackState);
            AppHelper.SetText(DiCapButtonsTextBox, device.Capabilities.ButtonCount.ToString());
            AppHelper.SetText(DiCapDPadsTextBox, device.Capabilities.PovCount.ToString());
            var objects = AppHelper.GetDeviceObjects(device);

            DiObjectsDataGridView.DataSource = objects;
            var actuators = objects.Where(x => x.Flags.HasFlag(DeviceObjectTypeFlags.ForceFeedbackActuator));

            AppHelper.SetText(ActuatorsTextBox, actuators.Count().ToString());
            var di           = device.Information;
            var slidersCount = objects.Where(x => x.GuidValue.Equals(SharpDX.DirectInput.ObjectGuid.Slider)).Count();

            AppHelper.SetText(DiCapAxesTextBox, (device.Capabilities.AxeCount - slidersCount).ToString());
            AppHelper.SetText(SlidersTextBox, slidersCount.ToString());
            // Update PID and VID always so they wont be overwritten by load settings.
            short vid = BitConverter.ToInt16(di.ProductGuid.ToByteArray(), 0);
            short pid = BitConverter.ToInt16(di.ProductGuid.ToByteArray(), 2);

            AppHelper.SetText(DeviceVidTextBox, "0x{0}", vid.ToString("X4"));
            AppHelper.SetText(DevicePidTextBox, "0x{0}", pid.ToString("X4"));
            AppHelper.SetText(DeviceProductNameTextBox, di.ProductName);
            AppHelper.SetText(DeviceVendorNameTextBox, dInfo == null ? "" : dInfo.Manufacturer);
            AppHelper.SetText(DeviceProductGuidTextBox, di.ProductGuid.ToString());
            AppHelper.SetText(DeviceInstanceGuidTextBox, di.InstanceGuid.ToString());
            AppHelper.SetText(DeviceTypeTextBox, di.Type.ToString());
        }
Example #46
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="deviceInfo">A DeviceInfo representing the device of interest</param>
        /// <param name="name">A user Agent String</param>
        /// <returns></returns>
        private T Capability <T>(DeviceInfo deviceInfo, string name)
        {
            string ret = deviceInfo.GetCapability(name);

            return((T)Convert.ChangeType(ret, typeof(T)));
        }
Example #47
0
 public Task <ICommsSerial> GetUSB(DeviceInfo di)
 {
     throw new NotImplementedException();
 }
Example #48
0
 /// <summary>
 /// Creates a new instance of <see cref="DeviceCreatedEvent"/>.
 /// </summary>
 /// <param name="device">The device updated.</param>
 /// <param name="user">Related user.</param>
 public DeviceUpdatedEvent(DeviceInfo device, SingleUserInfo user)
 {
     Device = device;
     User   = user;
 }
    public static List <DeviceInfo> GetAllCOMPorts()
    {
        Guid   guidComPorts   = new Guid(GUID_DEVINTERFACE_COMPORT);
        IntPtr hDeviceInfoSet = SetupDiGetClassDevs(
            ref guidComPorts, 0, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);

        if (hDeviceInfoSet == IntPtr.Zero)
        {
            throw new Exception("Failed to get device information set for the COM ports");
        }

        try
        {
            List <DeviceInfo> devices      = new List <DeviceInfo>();
            Int32             iMemberIndex = 0;
            while (true)
            {
                SP_DEVINFO_DATA deviceInfoData = new SP_DEVINFO_DATA();
                deviceInfoData.cbSize = Marshal.SizeOf(typeof(SP_DEVINFO_DATA));
                bool success = SetupDiEnumDeviceInfo(hDeviceInfoSet, iMemberIndex, ref deviceInfoData);
                if (!success)
                {
                    log.Info("no more devices " + GetLastError());
                    // No more devices in the device information set
                    break;
                }

                DeviceInfo deviceInfo = new DeviceInfo();
                try
                {
                    deviceInfo.name = GetDeviceName(hDeviceInfoSet, deviceInfoData);
                }
                catch (Exception e)
                {
                    log.Error(e);
                    iMemberIndex++;
                    continue;
                }

                try
                {
                    deviceInfo.description =
                        GetDeviceDescription(hDeviceInfoSet, deviceInfoData, SPDRP.SPDRP_DEVICEDESC);
                }
                catch (Exception e)
                {
                    log.Error(e);
                    iMemberIndex++;
                    continue;
                }

                try
                {
                    deviceInfo.hardwareid =
                        GetDeviceDescription(hDeviceInfoSet, deviceInfoData, SPDRP.SPDRP_HARDWAREID);
                }
                catch (Exception e)
                {
                    log.Error(e);
                    iMemberIndex++;
                    continue;
                }

                foreach (SPDRP prop in Enum.GetValues(typeof(SPDRP)))
                {
                    try
                    {
                        log.Info((SPDRP)prop + ": " +
                                 GetDeviceDescription(hDeviceInfoSet, deviceInfoData, (SPDRP)prop));
                    }
                    catch
                    {
                    }
                }

                //https://github.com/tpn/winsdk-10/blob/master/Include/10.0.10240.0/shared/devpkey.h

                var list = new[]
                {
                    DEFINE_DEVPROPKEY("DEVPKEY_Device_DeviceDesc", 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1,
                                      0x46, 0xa8, 0x50, 0xe0, 2),        // DEVPROP_TYPE_STRING
                    DEFINE_DEVPROPKEY("DEVPKEY_Device_Manufacturer", 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1,
                                      0x46, 0xa8, 0x50, 0xe0, 13),       // DEVPROP_TYPE_STRING
                    DEFINE_DEVPROPKEY("DEVPKEY_Device_FriendlyName", 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1,
                                      0x46, 0xa8, 0x50, 0xe0, 14),       // DEVPROP_TYPE_STRING
                    DEFINE_DEVPROPKEY("DEVPKEY_Device_EnumeratorName", 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67,
                                      0xd1, 0x46, 0xa8, 0x50, 0xe0, 24), // DEVPROP_TYPE_STRING

                    DEFINE_DEVPROPKEY("DEVPKEY_Device_Model", 0x78c34fc8, 0x104a, 0x4aca, 0x9e, 0xa4, 0x52, 0x4d, 0x52,
                                      0x99, 0x6e, 0x57, 39), // DEVPROP_TYPE_STRING

                    DEFINE_DEVPROPKEY("DEVPKEY_Device_BusReportedDeviceDesc", 0x540b947e, 0x8b40, 0x45bc, 0xa8, 0xa2,
                                      0x6a, 0x0b, 0x89, 0x4c, 0xbd, 0xa2, 4), // DEVPROP_TYPE_STRING

                    DEFINE_DEVPROPKEY("DEVPKEY_DeviceContainer_FriendlyName", 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77,
                                      0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 12288), // DEVPROP_TYPE_STRING

                    DEFINE_DEVPROPKEY("DEVPKEY_DeviceContainer_Manufacturer", 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77,
                                      0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 8192), // DEVPROP_TYPE_STRING

                    DEFINE_DEVPROPKEY("DEVPKEY_DeviceContainer_ModelName", 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A,
                                      0xE0, 0x40, 0x4A, 0x96, 0xCD, 8194), // DEVPROP_TYPE_STRING (localizable)

                    DEFINE_DEVPROPKEY("DEVPKEY_DeviceContainer_ModelNumber", 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77,
                                      0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 8195),     // DEVPROP_TYPE_STRING
                    DEFINE_DEVPROPKEY("DEVPKEY_DeviceContainer_DeviceDescription1", 0x78c34fc8, 0x104a, 0x4aca, 0x9e,
                                      0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57, 81), // DEVPROP_TYPE_STRING

                    DEFINE_DEVPROPKEY("DEVPKEY_DeviceContainer_DeviceDescription2", 0x78c34fc8, 0x104a, 0x4aca, 0x9e,
                                      0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57, 82), // DEVPROP_TYPE_STRING
                };

                ulong propertyType = 0;
                int   requiredSize = 0;
                for (int i = 0; i < list.Length; i++)
                {
                    IntPtr buffer = Marshal.AllocHGlobal(1024);
                    try
                    {
                        if (SetupDiGetDevicePropertyW(hDeviceInfoSet, ref deviceInfoData, ref list[i], out propertyType,
                                                      buffer, 1024, out requiredSize, 0))
                        {
                            var out11 = Marshal.PtrToStringAuto(buffer);
                            log.Info(list[i].name + " " + out11);

                            if (list[i].name == "DEVPKEY_Device_BusReportedDeviceDesc")
                            {
                                deviceInfo.board = out11;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex);
                    }

                    Marshal.FreeHGlobal(buffer);
                }

                devices.Add(deviceInfo);

                iMemberIndex++;
            }

            return(devices);
        }
        finally
        {
            SetupDiDestroyDeviceInfoList(hDeviceInfoSet);
        }
    }
Example #50
0
        /// <summary>
        /// Updates this device's deviceInformation
        /// </summary>
        /// <param name="deviceUpdate"></param>
        public void Update(DeviceInformationUpdate deviceUpdate)
        {
            DeviceInfo.Update(deviceUpdate);

            OnPropertyChanged(new PropertyChangedEventArgs("DeviceInfo"));
        }
        private bool PrepareDevice_DirectSound()
        {
            Log.Debug("Initializing DirectSound device: {0}...", _Profile.DirectSoundDevice);

              int deviceNo;

              if (_Profile.DirectSoundDevice == ConfigProfile.Defaults.DirectSoundDevice || _Profile.DirectSoundDevice == String.Empty)
              {
            Log.Info("Using default DirectSound device");
            deviceNo = -1;
              }
              else
              {
            deviceNo = -1;
            BASS_DEVICEINFO[] devices = Bass.BASS_GetDeviceInfos();
            for (int i = 0; i < devices.Length; i++)
            {
              if (devices[i].name == _Profile.DirectSoundDevice)
              {
            deviceNo = i;
            break;
              }
            }
            if (deviceNo == -1)
              Log.Warn("specified DirectSound device does not exist. Using default DirectSound Device");
            else
              Log.Info("Using DirectSound Device {0}", _Profile.DirectSoundDevice);
              }

              BASSInit flags = BASSInit.BASS_DEVICE_DEFAULT;

              if (deviceNo != _LastDeviceInfoDevice)
            // Only do this the first time this device is initialized; because it's kinda slow.
            flags |= BASSInit.BASS_DEVICE_LATENCY;

              bool result = Bass.BASS_Init(
              deviceNo,
              _DataStreamInfo.BASSChannelInfo.freq,
              flags,
              IntPtr.Zero,
              Guid.Empty);

              if (!result)
              {
            BASSError error = Bass.BASS_ErrorGetCode();
            if (error == BASSError.BASS_ERROR_ALREADY)
              result = true;
            else
              HandleError(ErrorCode.DeviceError, String.Format("BASS_Init() failed: {0}", error));
              }

              if (result)
              {
            // Bass will maximize the value to 100 ms
            Bass.BASS_SetConfig(BASSConfig.BASS_CONFIG_UPDATEPERIOD, _Profile.BASSPlayBackBufferSize / 4);

            if (deviceNo != _LastDeviceInfoDevice)
            {
              // Retrieve deviceinfo only the first time we use this device, because
              // retrieving latency and minbuf (BASSInit.BASS_DEVICE_LATENCY)
              // slows down initialization quite a bit.
              _LastDeviceInfoDevice = deviceNo;
              BASS_INFO bassInfo = Bass.BASS_GetInfo();
              _DeviceInfo = new DSDeviceInfo(bassInfo);

              if (_DebugMode)
              {
            Log.Debug(String.Format(
                "DirectX device info: dsver = {0}, minbuf = {1}",
                 bassInfo.dsver,
                 bassInfo.minbuf));
              }
            }
              }
              return result;
        }
Example #52
0
 public override void Setup()
 {
     base.Setup();
     DeviceInfo.SetCurrent(mockDeviceInfo = new MockDeviceInfo());
 }
        internal void SSDPNotifySink(IPEndPoint source, IPEndPoint local, Uri LocationURL, bool IsAlive, string USN, string SearchTarget, int MaxAge, HTTPMessage Packet)
        {
            UPnPDevice device = null;

            if (SearchTarget == "upnp:rootdevice")
            {
                if (!IsAlive)
                {
                    lock (this.deviceTableLock)
                    {
                        device = this.UnprotectedRemoveMe(USN);
                    }
                    if (device != null)
                    {
                        device.Removed();
                    }
                    if (device != null)
                    {
                        this.OnRemovedDeviceEvent.Fire(this, device);
                    }
                }
                else
                {
                    lock (this.deviceTableLock)
                    {
                        if (!this.deviceTable.ContainsKey(USN))
                        {
                            DeviceInfo info = new DeviceInfo();
                            info.Device           = null;
                            info.UDN              = USN;
                            info.NotifyTime       = DateTime.Now;
                            info.BaseURL          = LocationURL;
                            info.MaxAge           = MaxAge;
                            info.LocalEP          = local;
                            info.SourceEP         = source;
                            this.deviceTable[USN] = info;
                            this.deviceFactory.CreateDevice(info.BaseURL, info.MaxAge);
                        }
                        else
                        {
                            DeviceInfo info2 = (DeviceInfo)this.deviceTable[USN];
                            if (info2.Device != null)
                            {
                                if (info2.BaseURL.Equals(LocationURL))
                                {
                                    this.deviceUpdateClock.Remove(info2);
                                    info2.PendingBaseURL  = null;
                                    info2.PendingMaxAge   = 0;
                                    info2.PendingLocalEP  = null;
                                    info2.PendingSourceEP = null;
                                    info2.NotifyTime      = DateTime.Now;
                                    this.deviceTable[USN] = info2;
                                    this.deviceLifeTimeClock.Add(info2.UDN, MaxAge);
                                }
                                else if (info2.NotifyTime.AddSeconds(10.0).Ticks < DateTime.Now.Ticks)
                                {
                                    info2.PendingBaseURL  = LocationURL;
                                    info2.PendingMaxAge   = MaxAge;
                                    info2.PendingLocalEP  = local;
                                    info2.PendingSourceEP = source;
                                    this.deviceTable[USN] = info2;
                                    this.deviceUpdateClock.Add(info2.UDN, 3);
                                }
                            }
                        }
                    }
                }
            }
        }
Example #54
0
 public static bool UpdateClient(DeviceInfo deviceInfo)
 {
     DelClient(deviceInfo);
     return(AddClient(deviceInfo));
 }
Example #55
0
    public static List<DeviceDetails> EnumerateDevices()
    {
      uint deviceCount = 0;
      int dwSize = Marshal.SizeOf(typeof (RAWINPUTDEVICELIST));

      // Get the number of raw input devices in the list,
      // then allocate sufficient memory and get the entire list
      if (GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, (uint) dwSize) == 0)
      {
        IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int) (dwSize*deviceCount));
        GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, (uint) dwSize);

        List<DeviceDetails> devices = new List<DeviceDetails>((int) deviceCount);

        // Iterate through the list, discarding undesired items
        // and retrieving further information on keyboard devices
        for (int i = 0; i < deviceCount; i++)
        {
          uint pcbSize = 0;

          IntPtr location;
          int offset = dwSize*i;

          if (IntPtr.Size == 4)
            location = new IntPtr(pRawInputDeviceList.ToInt32() + offset);
          else
            location = new IntPtr(pRawInputDeviceList.ToInt64() + offset);

          RAWINPUTDEVICELIST rid = (RAWINPUTDEVICELIST) Marshal.PtrToStructure(location, typeof (RAWINPUTDEVICELIST));

          GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, IntPtr.Zero, ref pcbSize);

          if (pcbSize > 0)
          {
            IntPtr pData = Marshal.AllocHGlobal((int) pcbSize);
            GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, pData, ref pcbSize);
            string deviceName = Marshal.PtrToStringAnsi(pData);

            // Drop the "root" keyboard and mouse devices used for Terminal Services and the Remote Desktop
            if (deviceName.ToUpperInvariant().Contains("ROOT"))
              continue;

            // If the device is identified in the list as a keyboard or 
            // HID device, create a DeviceInfo object to store information 
            // about it

            // Get Detailed Info ...
            uint size = (uint) Marshal.SizeOf(typeof (DeviceInfo));
            DeviceInfo di = new DeviceInfo();
            di.Size = Marshal.SizeOf(typeof (DeviceInfo));
            GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICEINFO, ref di, ref size);

            di = new DeviceInfo();
            di.Size = Marshal.SizeOf(typeof (DeviceInfo));
            GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICEINFO, ref di, ref size);

            DeviceDetails details = new DeviceDetails();
            //details.Name = deviceName;
            details.ID = deviceName;

            switch (di.Type)
            {
              case RawInputType.HID:
                {
                  string vidAndPid = String.Format("Vid_{0:x4}&Pid_{1:x4}", di.HIDInfo.VendorID, di.HIDInfo.ProductID);
                  details.Name = String.Format("HID: {0}", GetFriendlyName(vidAndPid));
                  //details.ID = GetDeviceDesc(deviceName);

                  details.UsagePage = di.HIDInfo.UsagePage;
                  details.Usage = di.HIDInfo.Usage;

                  devices.Add(details);
                  break;
                }

              case RawInputType.Keyboard:
                {
                  details.Name = "HID Keyboard";
                  //details.ID = String.Format("{0}-{1}", di.KeyboardInfo.Type, di.KeyboardInfo.SubType);

                  details.UsagePage = 0x01;
                  details.Usage = 0x06;

                  devices.Add(details);
                  break;
                }

              case RawInputType.Mouse:
                {
                  details.Name = "HID Mouse";

                  details.UsagePage = 0x01;
                  details.Usage = 0x02;

                  devices.Add(details);
                  break;
                }
            }

            Marshal.FreeHGlobal(pData);
          }
        }

        Marshal.FreeHGlobal(pRawInputDeviceList);

        return devices;
      }
      else
      {
        throw new InvalidOperationException("An error occurred while retrieving the list of devices");
      }
    }
Example #56
0
 public bool NeedsToChangeIcon(DeviceInfo deviceInfo)
 {
     return(false);
 }
Example #57
0
 internal void SSDPNotifySink(
     IPEndPoint source,
     IPEndPoint local,
     Uri LocationURL,
     bool IsAlive,
     string USN,
     string SearchTarget,
     int MaxAge,
     HTTPMessage Packet
 )
 {
     UPnPDevice device = null;
     if (SearchTarget == searchFilter)
     {
         if (!IsAlive)
         {
             lock (this.deviceTableLock)
             {
                 device = this.UnprotectedRemoveMe(USN);
             }
             if (device != null)
             {
                 //device.Removed();
             }
             if (device != null)
             {
                 this.OnRemovedDeviceEvent.Fire(this, device);
             }
         }
         else
         {
             lock (this.deviceTableLock)
             {
                 if (!this.deviceTable.ContainsKey(USN))
                 {
                     DeviceInfo info = new DeviceInfo();
                     info.Device = null;
                     info.UDN = USN;
                     info.NotifyTime = DateTime.Now;
                     info.BaseURL = LocationURL;
                     info.MaxAge = MaxAge;
                     info.LocalEP = local;
                     info.SourceEP = source;
                     this.deviceTable[USN] = info;
                     this.deviceFactory.CreateDevice(info.BaseURL, info.MaxAge, IPAddress.Any, info.UDN);
                 }
                 else
                 {
                     DeviceInfo info2 = (DeviceInfo)this.deviceTable[USN];
                     if (info2.Device != null)
                     {
                         if (info2.BaseURL.Equals(LocationURL))
                         {
                             this.deviceUpdateClock.Remove(info2);
                             info2.PendingBaseURL = null;
                             info2.PendingMaxAge = 0;
                             info2.PendingLocalEP = null;
                             info2.PendingSourceEP = null;
                             info2.NotifyTime = DateTime.Now;
                             this.deviceTable[USN] = info2;
                             this.deviceLifeTimeClock.Add(info2.UDN, MaxAge);
                         }
                         else if (info2.NotifyTime.AddSeconds(10.0).Ticks < DateTime.Now.Ticks)
                         {
                             info2.PendingBaseURL = LocationURL;
                             info2.PendingMaxAge = MaxAge;
                             info2.PendingLocalEP = local;
                             info2.PendingSourceEP = source;
                             this.deviceTable[USN] = info2;
                             this.deviceUpdateClock.Add(info2.UDN, 3);
                         }
                     }
                 }
             }
         }
     }
 }
Example #58
0
        void _managementEventWatcher_EventArrived(object sender, EventArrivedEventArgs e)
        {
            ManagementBaseObject mbo = null;

            mbo = (ManagementBaseObject)e.NewEvent;
            try
            {
                PropertyData prop = mbo.Properties["DriveName"];
                if (prop != null)
                {
                    string driveName = (string)prop.Value;
                    prop = mbo.Properties["EventType"];
                    if (prop != null)
                    {
                        bool inserted = ((UInt16)prop.Value == 2);

                        lock (_connectedDevices)
                        {
                            if (inserted)
                            {
                                bool insert = true;
                                for (int i = 0; i < _connectedDevices.Count; i++)
                                {
                                    if (_connectedDevices[i].DriveName == driveName)
                                    {
                                        insert = false;
                                        break;
                                    }
                                }
                                if (insert)
                                {
                                    DeviceInfo di = new DeviceInfo(driveName);
                                    if (ProcessDrive(di))
                                    {
                                        _connectedDevices.Add(di);
                                        if (DeviceAddedEvent != null)
                                        {
                                            DeviceAddedEvent(this, new DeviceInfoEventArgs(di));
                                        }
                                    }
                                }
                            }
                            else
                            {
                                for (int i = 0; i < _connectedDevices.Count; i++)
                                {
                                    if (_connectedDevices[i].DriveName == driveName)
                                    {
                                        DeviceInfo di = _connectedDevices[i];
                                        _connectedDevices.RemoveAt(i);
                                        if (DeviceRemovedEvent != null)
                                        {
                                            DeviceRemovedEvent(this, new DeviceInfoEventArgs(di));
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Core.ApplicationData.Instance.Logger.AddLog(this, ex);
            }
        }
	void InitializePreviewPlugin(string preferredDeviceName, Camera camera)
	{
		// Test library compatibility
		if (DesktopWrapper.GetInterfaceVersion() != 3)
		{
			Debug.LogError("You appear to be using incompatible versions of StringWrapper.cs and String.bundle; Please make sure you're using the latest versions of both.");
			
			return;
		}

		// Enumerate devices
		uint maxDeviceCount = 10;
		DeviceInfo[] deviceInfo = new DeviceInfo[maxDeviceCount];
		
		uint deviceCount = DesktopWrapper.EnumerateDevices(deviceInfo, maxDeviceCount);
		
		for (int i = 0; i < deviceCount; i++)
		{
			Debug.Log("Found camera \"" + deviceInfo[i].name + "\" (" + (deviceInfo[i].isAvailable ? "available for use.)" : "not available for use.)"));
		}
		
		if (deviceCount > 0)
		{
			uint i;
			
			for (i = 0; i < deviceCount; i++)
			{
				if (deviceInfo[i].name == preferredDeviceName) break;
			}
			
			if (i < deviceCount)
			{
				Debug.Log("Capturing video from preferred device \"" + deviceInfo[i].name + "\".");
			}
			else
			{
				i = 0;

				if (preferredDeviceName != null)
				{
					Debug.Log("Preferred device was not found. Using \"" + deviceInfo[i].name + "\".");
				}
				else
				{
					Debug.Log("Capturing video from device \"" + deviceInfo[i].name + "\".");
				}
			}
			
			if (DesktopWrapper.InitTracker(deviceInfo[i].id, ref previewWidth, ref previewHeight, _previewCamApproxVerticalFOV))
			{
				CreateVideoMaterial();
				CreateVideoMesh();
				
				float scale = camera.farClipPlane * 0.99f;
				
				float verticalScale = scale * Mathf.Tan(_previewCamApproxVerticalFOV * Mathf.PI / 360f);
				
				videoPlaneObject = new GameObject("Video Plane", new Type[] {typeof(MeshRenderer), typeof(MeshFilter)});
				videoPlaneObject.hideFlags = HideFlags.HideAndDontSave;
				videoPlaneObject.active = false;
				
				videoPlaneObject.renderer.material = videoMaterial;
				
				MeshFilter meshFilter = (MeshFilter)videoPlaneObject.GetComponent(typeof(MeshFilter));
				meshFilter.sharedMesh = videoPlaneMesh;
				
				videoPlaneObject.transform.parent = camera.transform;
				videoPlaneObject.transform.localPosition = new Vector3(0, 0, scale);
				videoPlaneObject.transform.localRotation = Quaternion.identity;
				videoPlaneObject.transform.localScale = new Vector3(verticalScale * (float)previewWidth / previewHeight, verticalScale, 1);
				
				wasInitialized = true;
			}
			else
			{
				Debug.Log("Failed to initialize String.");
			}
		}
		else
		{
			Debug.LogError("No devices suitable for video capture were detected.");
		}
	}
Example #60
0
 public DeviceInfoEventArgs(DeviceInfo deviceInfo)
 {
     _deviceInfo = deviceInfo;
 }