Ejemplo n.º 1
0
        public static DeviceIdentifier Identify(DeviceClass hsDevice)
        {
            var childAddress = hsDevice.get_Address(null);

            var parts = childAddress.Split(AddressSeparator);

            if (parts.Length != 4)
            {
                return(null);
            }

            DeviceType?deviceType = ParseDeviceType(parts[2]);

            if (deviceType == null)
            {
                return(null);
            }

            string deviceTypeData = parts[3];

            if (deviceTypeData == null)
            {
                return(null);
            }

            return(new DeviceIdentifier(parts[1], deviceType.Value, deviceTypeData));
        }
    public virtual TokenIdentity Authenticate(
        ISocialUser socialUser,
        DeviceType?deviceType       = null,
        string deviceRegistrationID = null)
    {
        using (var usersRepo = new UsersRepository())
        {
            var user = usersRepo.GetUserBySocialID(socialUser.SocialUserID, socialUser.SocialNetwork);

            user = (user ?? new User()).CopyFrom(socialUser);

            user.AuthToken = System.Guid.NewGuid().ToString();

            if (user.ID == default(int))
            {
                usersRepo.Add(user);
            }

            usersRepo.SaveChanges();

            return(new TokenIdentity
            {
                AuthToken = user.AuthToken,
                SocialUser = user,
                UserID = user.ID
            });
        }
    }
Ejemplo n.º 3
0
 public Port(byte portId, string friendlyName, bool externalPort, DeviceType?expectedDevice = null, bool isVirtual = false)
 {
     PortId         = portId;
     FriendlyName   = friendlyName;
     ExternalPort   = externalPort;
     ExpectedDevice = expectedDevice;
     IsVirtual      = isVirtual;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SetPushTokenRequest" /> class.
 /// </summary>
 /// <param name="pushToken">pushToken.</param>
 /// <param name="description">description.</param>
 /// <param name="device">device.</param>
 /// <param name="bitflexDeviceId">bitflexDeviceId.</param>
 /// <param name="publicKey">publicKey.</param>
 public SetPushTokenRequest(string pushToken = default(string), string description = default(string), DeviceType?device = default(DeviceType?), string bitflexDeviceId = default(string), string publicKey = default(string))
 {
     this.PushToken       = pushToken;
     this.Description     = description;
     this.Device          = device;
     this.BitflexDeviceId = bitflexDeviceId;
     this.PublicKey       = publicKey;
 }
Ejemplo n.º 5
0
        protected virtual void ApplyDeviceParams()
        {
            if (updating)
            {
                return;
            }

            DeviceParams deviceParams = null;

            if (device != null)
            {
                deviceParams = device.Parameters;
                device.Dispose();
            }
            else
            {
                deviceParams = new DeviceParams();
            }

            if (newDeviceType == null)
            {
                newDeviceType = GraphicsDeviceType;
            }

            switch (newDeviceType)
            {
            case DeviceType.Gdi:
                device = new GdiGraphicsDevice(graphics, GetCurrentViewport());
                break;

            case DeviceType.Direct3D:
                Type xnaDeviceType = GetXnaGraphicsDeviceType();
                if (xnaDeviceType == null)
                {
                    goto case DeviceType.Gdi;
                }
                device = (GraphicsDevice)Activator.CreateInstance(xnaDeviceType, this.Handle, GetCurrentViewport());
                break;

            default:
                device = null;
                break;
            }

            if (device != null)
            {
                deviceParams.Viewport = null;
                device.Parameters     = deviceParams;
            }

            Scene original = scene;

            RecreateScene(device, original.Camera, original.Projection);

            newDeviceType = null;

            Invalidate();
        }
        public DialogSelectDevicesToBeUpgradedViewModel(
            ICollectionModel <Device> deviceDataModel,
            IUpgradeTasksModel upgradeTaskDataModel,
            IDialogService dialogService,
            upgrade upgradeFile)
        {
            this._deviceDataModel      = deviceDataModel;
            this._upgradeTaskDataModel = upgradeTaskDataModel;
            this._dialogService        = dialogService;
            this._upgradeFile          = upgradeFile;
            if (upgradeFile.filetype.HasValue)
            {
                if (upgradeFile.filetype == (int)UpgradeFileType.SoftwareUpgrade)
                {
                    _deviceType = (DeviceType?)upgradeFile.device_type;
                }
            }

            Devices = (ListCollectionView) new ListCollectionView((IList)_deviceDataModel.Data);
            using (Devices.DeferRefresh())
            {
                Devices.Filter = delegate(object obj)
                {
                    Device device = obj as Device;
                    if (device != null && device.type.HasValue)
                    {
                        if (_deviceType.HasValue)
                        {
                            if (device.type == (int)_deviceType)
                            {
                                return(true);
                            }
                        }
                        else
                        {
                            switch (device.type)
                            {
                            // case (int)DeviceType.Control_Server:
                            case (int)DeviceType.Door_Camera:
                            case (int)DeviceType.Lobby_Phone_Unit:
                            case (int)DeviceType.Lobby_Phone_Building:
                            case (int)DeviceType.Lobby_Phone_Area:
                            case (int)DeviceType.Indoor_Phone:
                            case (int)DeviceType.Administrator_Unit:
                            case (int)DeviceType.Indoor_Phone_SD:
                            // case (int)DeviceType.Mobile_Phone:
                            case (int)DeviceType.Emergency_Intercom_Unit:
                                // case (int)DeviceType.IPCAM:
                                return(true);
                            }
                        }
                    }
                    return(false);
                };
                Devices.SortDescriptions.Add(new SortDescription("ip", ListSortDirection.Ascending));
            }
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PushToken" /> class.
 /// </summary>
 /// <param name="id">id.</param>
 /// <param name="userId">userId.</param>
 /// <param name="device">device.</param>
 /// <param name="deviceId">deviceId.</param>
 /// <param name="token">token.</param>
 /// <param name="description">description.</param>
 public PushToken(string id = default(string), string userId = default(string), DeviceType?device = default(DeviceType?), string deviceId = default(string), string token = default(string), string description = default(string))
 {
     this.Id          = id;
     this.UserId      = userId;
     this.Device      = device;
     this.DeviceId    = deviceId;
     this.Token       = token;
     this.Description = description;
 }
Ejemplo n.º 8
0
 public LogFileRow(string originalRow, RowType type, DateTime?logDateTime, float?measure, DeviceType?deviceType, string name)
 {
     OriginalRow = originalRow;
     Type        = type;
     LogDateTime = logDateTime;
     Measure     = measure;
     DeviceType  = deviceType;
     Name        = name;
 }
Ejemplo n.º 9
0
        public Telemetry ConstructorTest(
            string metricDate,
            DeviceType?deviceType,
            string metricValue
            )
        {
            Telemetry target = new Telemetry(metricDate, deviceType, metricValue);

            return(target);
            // TODO: ajouter des assertions à méthode TelemetryTest.ConstructorTest(Nullable`1<DateTime>, Nullable`1<DeviceType>, String)
        }
Ejemplo n.º 10
0
 public Telemetry(string metricDate = null, DeviceType?deviceType = null, string metricValue = null)
 {
     if (metricDate != null)
     {
         this.metricDate = metricDate;
     }
     if (deviceType != null)
     {
         this.deviceType = deviceType.ToString();
     }
     this.metricValue = metricValue;
 }
Ejemplo n.º 11
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string userAgent = filterContext.HttpContext.Request.UserAgent;

            if (string.IsNullOrWhiteSpace(userAgent) || // http头里的user agent为空的
                filterContext.HttpContext.Request.BySearchEngine() || // 来自搜索引擎的爬虫的请求
                filterContext.HttpContext.Request.ByApp() || // 来自App客户端的请求
                filterContext.HttpContext.Request.IsAjaxRequest() ||  // 来自于Ajax的请求
                string.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.InvariantCultureIgnoreCase) == false    // 来自非Get方式的请求(如Post)
                )
            {
                // 不做任何基于设备类型的页面跳转
                return;
            }
            DeviceType?dType = RouteHelper.CurrentSupportedDeviceTypeInConfig;

            if (dType == null) // 没有特别设置当前页面所支持的设备
            {
                return;
            }
            DeviceType curType = DeviceNameDetector.GetDeviceType(userAgent);

            if (curType == dType.Value) // 当前访问设备就是特别设置的支持的设备
            {
                return;
            }
            string url = RouteHelper.RedirectUrlForUnsupportedDevices;

            if (string.IsNullOrWhiteSpace(url)) // 没有设定Redirect到的地址
            {
                return;
            }
            if (url.IndexOf('{') >= 0 && url.IndexOf('}') > 0)
            {
                var rdata      = RouteHelper.GetCurrentRouteData();
                var collection = rdata.Values;
                if (collection != null && collection.Count > 0)
                {
                    // 可能配置的跳转目标是一个url模板,那么需要使用当前请求的模板参数的值来应用到跳转到的模板url里
                    foreach (var entry in collection)
                    {
                        url = url.Replace("{" + entry.Key + "}", entry.Value == null ? string.Empty : entry.Value.ToString());
                    }
                }
            }
            if (filterContext.HttpContext.Request.QueryString.Count > 0) // 当前请求带有QueryString参数,那么需要将querystring参数排序后拼接到跳转目标的url上去
            {
                url = url + filterContext.HttpContext.Request.GetSortedQueryString(true);
            }
            filterContext.Result = new RedirectResult(url, false);
        }
Ejemplo n.º 12
0
        private static void MapRoute(
            RouteCollection routes, bool cutOutUrlFirstSection,
            string name,
            string url,
            RouteValueDictionary defaults,
            RouteValueDictionary constraints,
            string area,
            string[] namespaces, DeviceType?dt, string redirectUrl, string domain, string authKey)
        {
            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }
            if (url == null)
            {
                throw new ArgumentNullException("url");
            }

            Route route = new CustomRoute(url, new MvcRouteHandler(), name, cutOutUrlFirstSection);

            route.Defaults    = defaults;
            route.Constraints = constraints;
            if (string.IsNullOrWhiteSpace(area) == false)
            {
                route.DataTokens["Area"] = area;
            }
            if (namespaces != null && namespaces.Length > 0)
            {
                route.DataTokens["Namespaces"]           = namespaces;
                route.DataTokens["UseNamespaceFallback"] = false;
            }
            if (dt.HasValue)
            {
                route.DataTokens["_ibb_device_type"] = dt.Value;
            }
            if (string.IsNullOrWhiteSpace(redirectUrl) == false)
            {
                route.DataTokens["_ibb_redirectUrlForOtherDevices"] = redirectUrl;
            }
            if (string.IsNullOrWhiteSpace(domain) == false)
            {
                route.DataTokens["_ibb_domain"] = domain;
            }
            if (string.IsNullOrWhiteSpace(authKey) == false)
            {
                route.DataTokens["_ibb_authKey"] = authKey;
            }
            routes.Add(name, route);
        }
Ejemplo n.º 13
0
        private static DeviceType?ParseDeviceType(string part)
        {
            DeviceType?deviceType = null;

            foreach (var value in Enum.GetValues(typeof(DeviceType)))
            {
                if (EnumHelper.GetDescription((DeviceType)value) == part)
                {
                    deviceType = (DeviceType)value;
                    break;
                }
            }

            return(deviceType);
        }
Ejemplo n.º 14
0
        /*
         * private bool SendMsg(int targetSubnetId, int targetDeviceId, byte[] operateCode, byte[] content, int? senderSubnetId, int? senderDeviceId, byte[] senderDeviceType)
         * {
         *      try
         *      {
         *              if (senderSubnetId == null) senderSubnetId = 0;
         *              if (senderDeviceId == null) senderDeviceId = 0;
         *              if (senderDeviceType == null) senderDeviceType = new byte[2];
         *
         *              var s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
         *              var broadcast = IPAddress.Parse(_ipAddress);
         *              //byte[] sendbuf = GetTestBufToSend();
         *              byte[] sendbuf = BuildBufToSend(targetSubnetId, targetDeviceId, operateCode, content, (int)senderSubnetId, (int)senderDeviceId, senderDeviceType);
         *
         *              if (LogToFile)
         *              {
         *                      var senderDeviceTypeHex = ByteArrayToString(senderDeviceType, 0, senderDeviceType.Length);
         *                      var operateCodeHex = ByteArrayToString(operateCode, 0, operateCode.Length);
         *                      var contentHex = ByteArrayToString(content, 0, content.Length);
         *                      var contentLength = content.Length;
         *                      var rawDataBytes = StringToByteArray(ByteArrayToString(sendbuf, 0, sendbuf.Length));
         *
         *                      var rawData = "";
         *                      foreach (var t in rawDataBytes)
         *                              rawData += t + " ";
         *
         *                      WriteToFile(senderSubnetId + ";" + senderDeviceId + ";" + senderDeviceTypeHex + ";" +
         *                                                                      GetDeviceType(senderDeviceTypeHex) + ";" +
         *                                                                      operateCodeHex + ";" + GetOperateCode(operateCodeHex) + ";" +
         *                                                                      targetSubnetId + ";" + targetDeviceId + ";" + contentHex + ";" + contentLength + ";" + rawData);
         *              }
         *
         *              var ep = new IPEndPoint(broadcast, _port);
         *              s.SendTo(sendbuf, ep);
         *      }
         *      catch (Exception ex)
         *      {
         *              return false;
         *      }
         *
         *      return true;
         * }
         */

        //private byte[] IntToByteArray(int value)
        //{
        //	var bytes = new byte[2];
        //	bytes[0] = (byte)(value >> 8);
        //	bytes[1] = (byte)(value);

        //	return bytes;
        //}


        /*
         * private byte[] OperateCodeToByteArray(OperationCode operateCode)
         * {
         * var value = (int)operateCode;
         * var bytes = new byte[2];
         * bytes[0] = (byte)(value >> 8);
         * bytes[1] = (byte)(value);
         *
         * return bytes;
         * }
         */



        private byte[] DeviceTypeToByteArray(DeviceType?deviceType)
        {
            if (deviceType == null)
            {
                return(new byte[2]);
            }

            var value = (int)deviceType;
            var bytes = new byte[2];

            bytes[0] = (byte)(value >> 8);
            bytes[1] = (byte)(value);

            return(bytes);
        }
        public void UnregisterDevice(int?userId, string token, DeviceType?type)
        {
            using (var connection = GetSqlConnection())
            {
                using (var command = new SqlCommand(@"DELETE FROM te_Mobile_PushDeviceRegistrations WHERE Token = @Token AND (UserId = @UserId or @UserId IS NULL) AND (Device = @Device OR @Device IS NULL)", connection))
                {
                    command.Parameters.Add(new SqlParameter("UserId", userId.HasValue ? (object)userId.Value : DBNull.Value));
                    command.Parameters.Add(new SqlParameter("Token", token));
                    command.Parameters.Add(new SqlParameter("Device", type.HasValue ? (object)type.Value : DBNull.Value));

                    connection.Open();
                    command.ExecuteNonQuery();
                    connection.Close();
                }
            }
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Initializes a new instance of the Device class.
 /// </summary>
 /// <param name="id">The identifier.</param>
 /// <param name="name">The name.</param>
 /// <param name="type">The type.</param>
 /// <param name="activationTime">The UTC time at which the device was
 /// activated</param>
 /// <param name="allowedDeviceOperations">Operations that are allowed
 /// on the device based on its current state</param>
 /// <param name="culture">Language culture setting on the device. For
 /// eg: "en-US"</param>
 /// <param name="deviceCapabilities">Device can be configured either as
 /// FileServer or IscsiServer</param>
 /// <param name="deviceDescription">Short description given for the
 /// device</param>
 /// <param name="domainName">Fully qualified name of the domain to
 /// which the device is attached</param>
 /// <param name="deviceSoftwareVersion">Version number of the software
 /// running on the device</param>
 /// <param name="friendlySoftwareName">Friendly name for the software
 /// version</param>
 /// <param name="deviceConfigurationStatus">"Complete" if the device
 /// has been successfully registered as File/IscsiServer and the
 /// creation of share/volume is complete, "Pending" if the device is
 /// only registered but the creation of share/volume is complete is
 /// still pending. Possible values include: 'Complete',
 /// 'Pending'</param>
 /// <param name="modelDescription">Name of the device model</param>
 /// <param name="status">Current status of the device. Possible values
 /// include: 'Unknown', 'Online', 'Offline', 'RequiresAttention',
 /// 'MaintenanceMode', 'Creating', 'Provisioning', 'Deleted',
 /// 'ReadyToSetup', 'Deactivated', 'Deactivating'</param>
 /// <param name="deviceType">Type of the device. Possible values
 /// include: 'Invalid', 'Appliance', 'VirtualAppliance',
 /// 'Series9000OnPremVirtualAppliance', 'Series9000VirtualAppliance',
 /// 'Series9000PhysicalAppliance'</param>
 /// <param name="details">subclass containing more storage-related
 /// information about the device. This field will be populated only if
 /// the get call is made with $expand = details.</param>
 public Device(string id = default(string), string name = default(string), string type = default(string), System.DateTime?activationTime = default(System.DateTime?), IList <DeviceOperation?> allowedDeviceOperations = default(IList <DeviceOperation?>), string culture = default(string), IList <SupportedDeviceCapabilities?> deviceCapabilities = default(IList <SupportedDeviceCapabilities?>), string deviceDescription = default(string), string domainName = default(string), string deviceSoftwareVersion = default(string), string friendlySoftwareName = default(string), DeviceConfigurationStatus?deviceConfigurationStatus = default(DeviceConfigurationStatus?), string modelDescription = default(string), DeviceStatus?status = default(DeviceStatus?), DeviceType?deviceType = default(DeviceType?), DeviceDetails details = default(DeviceDetails))
     : base(id, name, type)
 {
     ActivationTime          = activationTime;
     AllowedDeviceOperations = allowedDeviceOperations;
     Culture                   = culture;
     DeviceCapabilities        = deviceCapabilities;
     DeviceDescription         = deviceDescription;
     DomainName                = domainName;
     DeviceSoftwareVersion     = deviceSoftwareVersion;
     FriendlySoftwareName      = friendlySoftwareName;
     DeviceConfigurationStatus = deviceConfigurationStatus;
     ModelDescription          = modelDescription;
     Status     = status;
     DeviceType = deviceType;
     Details    = details;
     CustomInit();
 }
Ejemplo n.º 17
0
        public static bool GetIsMobileAppUser(Guid userId, DeviceType?type)
        {
            string userEmail = CoreContext.UserManager.GetUsers(userId).Email;

            var query = new SqlQuery("push_app_user")
                        .SelectCount()
                        .Where("user_email", userEmail);

            if (type.HasValue)
            {
                query.Where("device_type", (int)type.Value);
            }

            using (var db = new DbManager("core"))
            {
                return(db.ExecuteScalar <int>(query) > 0);
            }
        }
    public TokenIdentity Post(
        SocialNetwork socialNetwork,
        string socialUserID,
        [FromUri] string socialAuthToken,
        [FromUri] string deviceRegistrationID = null,
        [FromUri] DeviceType?deviceType       = null)
    {
        var socialManager = new SocialManager();

        var user = socialManager.GetSocialUser(socialNetwork, socialUserID, socialAuthToken);

        var tokenIdentity = new AuthCacheManager()
                            .Authenticate(
            user,
            deviceType,
            deviceRegistrationID);

        return(tokenIdentity);
    }
Ejemplo n.º 19
0
        public Canvas3D()
        {
            InitializeComponent();

            MinimumSize = new Size(1, 1);
            TabStop     = false;
            BackColor   = Color.CornflowerBlue;
            SetStyle(ControlStyles.Opaque, true);

            this.Resize   += Canvas3D_Resize;
            this.Disposed += Canvas3D_Disposed;

            newDeviceType = DeviceType.Gdi;

            RecreateScene(null, null, new Matrix());
            updating = true;

            graphics = this.CreateGraphics();
            updating = false;
            ApplyDeviceParams();
        }
    public override TokenIdentity Authenticate(
        ISocialUser socialUser,
        DeviceType?deviceType       = null,
        string deviceRegistrationID = null)
    {
        if (socialUser == null)
        {
            throw new ArgumentNullException("socialUser");
        }
        var identity = base.Authenticate(socialUser, deviceType, deviceRegistrationID);

        HttpRuntime.Cache.Add(
            identity.AuthToken,
            identity,
            null,
            DateTime.Now.AddDays(7),
            Cache.NoSlidingExpiration,
            CacheItemPriority.Default,
            null);

        return(identity);
    }
Ejemplo n.º 21
0
        public static DeviceType GetDeviceType()
        {
            if (!_deviceType.HasValue)
            {
                try
                {
                    var qualifiers = ResourceContext.GetForCurrentView().QualifierValues;
                    string deviceFamily = null;
                    if (qualifiers.ContainsKey("DeviceFamily"))
                    {
                        deviceFamily = qualifiers["DeviceFamily"];
                    }

                    if (string.IsNullOrWhiteSpace(deviceFamily) || deviceFamily.Equals("Desktop", StringComparison.OrdinalIgnoreCase))
                    {
                        _deviceType = DeviceType.Windows;
                    }
                    else if (deviceFamily.Equals("Mobile", StringComparison.OrdinalIgnoreCase))
                    {
                        _deviceType = DeviceType.Phone;
                    }
                    else if (deviceFamily.Equals("Xbox", StringComparison.OrdinalIgnoreCase))
                    {
                        _deviceType = DeviceType.Xbox;
                    }
                    else if (deviceFamily.Equals("Holographic", StringComparison.OrdinalIgnoreCase))
                    {
                        _deviceType = DeviceType.Holographic;
                    }
                }
                catch
                {
                    // If we can't determine the device type for whatever reason assume Windows
                    _deviceType = DeviceType.Windows;
                }
            }

            return _deviceType.Value;
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Gets the type of the device.
        /// </summary>
        /// <returns>DeviceType.</returns>
        public static DeviceType GetDeviceType()
        {
            if (_deviceType.HasValue)
            {
                return _deviceType.Value;
            }

#if NET || SL5
            _deviceType = DeviceType.Desktop;
#elif WINDOWS_PHONE
            _deviceType = DeviceType.Phone;
#elif UAP
            var deviceFamily = Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily;
            if (string.Equals(deviceFamily, "Windows.Mobile", StringComparison.OrdinalIgnoreCase))
            {
                _deviceType = DeviceType.Phone;
            }
            else if (string.Equals(deviceFamily, "Windows.Desktop", StringComparison.OrdinalIgnoreCase))
            {
                _deviceType = DeviceType.Desktop;
            }
            else
            {
                // TODO: add more support like xbox and IoT, but need devices for this
                _deviceType = DeviceType.Unknown;
            }
#elif NETFX_CORE
            // Assume tablet for WinRT
            _deviceType = DeviceType.Tablet;
#elif IOS
            _deviceType = DeviceType.Unknown;
#elif ANDROID
            _deviceType = DeviceType.Unknown;
#else
            _deviceType = DeviceType.Unknown;
#endif

            return _deviceType.Value;
        }
Ejemplo n.º 23
0
        public static DeviceType GetDeviceType()
        {
            if (!_deviceType.HasValue)
            {
                try
                {
                    var    qualifiers   = ResourceContext.GetForCurrentView().QualifierValues;
                    string deviceFamily = null;
                    if (qualifiers.ContainsKey("DeviceFamily"))
                    {
                        deviceFamily = qualifiers["DeviceFamily"];
                    }

                    if (string.IsNullOrWhiteSpace(deviceFamily) || deviceFamily.Equals("Desktop", StringComparison.OrdinalIgnoreCase))
                    {
                        _deviceType = DeviceType.Windows;
                    }
                    else if (deviceFamily.Equals("Mobile", StringComparison.OrdinalIgnoreCase))
                    {
                        _deviceType = DeviceType.Phone;
                    }
                    else if (deviceFamily.Equals("Xbox", StringComparison.OrdinalIgnoreCase))
                    {
                        _deviceType = DeviceType.Xbox;
                    }
                    else if (deviceFamily.Equals("Holographic", StringComparison.OrdinalIgnoreCase))
                    {
                        _deviceType = DeviceType.Holographic;
                    }
                }
                catch
                {
                    // If we can't determine the device type for whatever reason assume Windows
                    _deviceType = DeviceType.Windows;
                }
            }

            return(_deviceType.Value);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Gets the type of the device.
        /// </summary>
        /// <returns>DeviceType.</returns>
        public static DeviceType GetDeviceType()
        {
            if (_deviceType.HasValue)
            {
                return(_deviceType.Value);
            }

#if NET || SL5
            _deviceType = DeviceType.Desktop;
#elif WINDOWS_PHONE
            _deviceType = DeviceType.Phone;
#elif UAP
            var deviceFamily = Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily;
            if (string.Equals(deviceFamily, "Windows.Mobile", StringComparison.OrdinalIgnoreCase))
            {
                _deviceType = DeviceType.Phone;
            }
            else if (string.Equals(deviceFamily, "Windows.Desktop", StringComparison.OrdinalIgnoreCase))
            {
                _deviceType = DeviceType.Desktop;
            }
            else
            {
                // TODO: add more support like xbox and IoT, but need devices for this
                _deviceType = DeviceType.Unknown;
            }
#elif NETFX_CORE
            // Assume tablet for WinRT
            _deviceType = DeviceType.Tablet;
#elif IOS
            _deviceType = DeviceType.Unknown;
#elif ANDROID
            _deviceType = DeviceType.Unknown;
#else
            _deviceType = DeviceType.Unknown;
#endif

            return(_deviceType.Value);
        }
 internal static string ToSerializedValue(this DeviceType?value)
 {
     return(value == null ? null : ((DeviceType)value).ToSerializedValue());
 }
Ejemplo n.º 26
0
        private Command Receive(DeviceType?filterOnSourceDeviceType = null)
        {
            //if (_listener.Client == null) _listener = new UdpClient(_port);

            try
            {
                // Synchronous receive
                var ipEndPoint = EndPoint;
                var bytes      = Listener.Receive(ref ipEndPoint);

                const int indexLengthOfDataPackage = 16;
                const int indexOriginalSubnetId    = 17;
                const int indexOriginalDeviceId    = 18;
                const int indexOriginalDeviceType  = 19;
                const int indexOperateCode         = 21;
                const int indexTargetSubnetId      = 23;
                const int indexTargetDeviceId      = 24;
                const int indexAdditionalContent   = 25;
                int       lengthOfDataPackage      = bytes[indexLengthOfDataPackage];
                var       additionalContentLength  = lengthOfDataPackage - 1 - 1 - 1 - 2 - 2 - 1 - 1 - 1 - 1;

                //if (_filterOriginalDeviceId != null && (_filterOriginalDeviceId != hdlData.SourceDeviceId))
                //	return null;

                var cmd = new Command
                {
                    RawData       = bytes,
                    SourceAddress = new DeviceAddress {
                        DeviceId = bytes[indexOriginalDeviceId], SubnetId = bytes[indexOriginalSubnetId]
                    },
                    SourceDeviceTypeBytes = GetByteArray(bytes, indexOriginalDeviceType, 2),
                    OperationCodeBytes    = GetByteArray(bytes, indexOperateCode, 2),
                    TargetAddress         = new DeviceAddress {
                        DeviceId = bytes[indexTargetDeviceId], SubnetId = bytes[indexTargetSubnetId]
                    },
                    AdditionalContent = GetByteArray(bytes, indexAdditionalContent, additionalContentLength),
                    Success           = true
                };

                if (filterOnSourceDeviceType != null && filterOnSourceDeviceType != cmd.SourceDeviceType)
                {
                    return(null);
                }

                // CRC verification code
                var crcH = bytes[bytes.Length - 2];
                var crcL = bytes[bytes.Length - 1];
                var calculatedChecksum = CalculateChecksum(bytes);

                if (crcH == calculatedChecksum.CrcHigh && crcL == calculatedChecksum.CrcLow)
                {
                    return(cmd);
                }

                cmd.Success = false;
                cmd.ErrorMessageSpecified = true;
                cmd.ErrorMessage          = "Checksum error";
                return(cmd);
            }
            catch (SocketException socketEx)
            {
                return(new Command {
                    Success = false, ErrorMessage = socketEx.Message, ErrorMessageSpecified = true
                });
            }
            catch (Exception ex)
            {
                return(new Command {
                    Success = false, ErrorMessage = ex.Message, ErrorMessageSpecified = true
                });
            }
        }
Ejemplo n.º 27
0
 public void AttachDevice(IPoweredUpDevice device, DeviceType type)
 {
     DeviceType = type;
     _device    = device;
 }
Ejemplo n.º 28
0
 public void DetachDevice()
 {
     DeviceType = null;
     _device    = null;
 }
Ejemplo n.º 29
0
 public DeploymentDeviceModel(byte portId, DeviceType?deviceType)
 {
     PortId     = portId;
     DeviceType = deviceType;
 }
Ejemplo n.º 30
0
        //call this on call back when something is beeing plugged in or unplugged
        void InitializeJoystickIfPossible()
        {
            // try to dispose of the old joystick
            if (m_joystick != null)
            {
                m_joystick.Dispose();
                m_joystick = null;
                SetJoystickConnected(false);
                m_joystickType = null;
            }
            if (m_joystick == null)
            {
                // Joystick disabled?
                if (m_joystickInstanceName == null) return;

                //  Try to grab the joystick with the correct instance name
                var attachedDevices = MyDirectInput.DirectInput.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AttachedOnly);
                foreach (var device in attachedDevices)
                {
                    if (device.InstanceName != m_joystickInstanceName)
                        continue;

                    try
                    {
                        //device.Type
                        m_joystick = new Joystick(MyDirectInput.DirectInput, device.InstanceGuid);
                        m_joystickType = device.Type;

                        //MethodInfo setCooperativeLevel = typeof(Device).GetMethod("SetCooperativeLevel",
                        //                                                             new[]
                        //                                                                 {
                        //                                                                     typeof (IntPtr),
                        //                                                                     typeof (CooperativeLevel)
                        //                                                                 });

                        m_joystick.SetCooperativeLevel(m_windowHandle, CooperativeLevel.NonExclusive | CooperativeLevel.Background);
                        //// Workaround for not need to reference System.Windows.Forms
                        //setCooperativeLevel.Invoke(m_joystick,
                        //                           new object[]
                        //                               {
                        //                                   m_windowHandle,
                        //                                   CooperativeLevel.NonExclusive | CooperativeLevel.Background
                        //                               });

                        break;
                    }
                    catch (SharpDX.SharpDXException)
                    {
                    }
                }

                // load and acquire joystick
                // both joystick and xbox 360 gamepad are treated as joystick device by slimdx
                if (m_joystick != null)
                {
                    int sliderCount = 0;
                    m_joystickXAxisSupported = m_joystickYAxisSupported = m_joystickZAxisSupported = false;
                    m_joystickRotationXAxisSupported = m_joystickRotationYAxisSupported = m_joystickRotationZAxisSupported = false;
                    m_joystickSlider1AxisSupported = m_joystickSlider2AxisSupported = false;
                    foreach (DeviceObjectInstance doi in m_joystick.GetObjects())
                    {
                        if ((doi.ObjectId.Flags & DeviceObjectTypeFlags.Axis) != 0)
                        {
                            // set range 0..65535 for each axis
                            m_joystick.GetObjectPropertiesById(doi.ObjectId).Range = new InputRange(0, 65535);

                            // find out which axes are supported
                            if (doi.ObjectType == ObjectGuid.XAxis) m_joystickXAxisSupported = true;
                            else if (doi.ObjectType == ObjectGuid.YAxis) m_joystickYAxisSupported = true;
                            else if (doi.ObjectType == ObjectGuid.ZAxis) m_joystickZAxisSupported = true;
                            else if (doi.ObjectType == ObjectGuid.RxAxis) m_joystickRotationXAxisSupported = true;
                            else if (doi.ObjectType == ObjectGuid.RyAxis) m_joystickRotationYAxisSupported = true;
                            else if (doi.ObjectType == ObjectGuid.RzAxis) m_joystickRotationZAxisSupported = true;
                            else if (doi.ObjectType == ObjectGuid.Slider)
                            {
                                sliderCount++;
                                if (sliderCount >= 1) m_joystickSlider1AxisSupported = true;
                                if (sliderCount >= 2) m_joystickSlider2AxisSupported = true;
                            }
                        }
                    }

                    // acquire the device
                    try
                    {
                        m_joystick.Acquire();
                        SetJoystickConnected(true);
                    }
                    catch (SharpDX.SharpDXException)
                    {
                    }
                }
            }
        }
Ejemplo n.º 31
0
        private static void MapByRoutingCollection(RouteCollection routes, bool cutOutUrlFirstSection, string areaName, RoutingCollection routingCollection, NamespacesCollection namespacesCollection)
        {
            if (routingCollection == null || routingCollection.Count <= 0)
            {
                return;
            }
            List <string> namespaces = new List <string>();

            if (namespacesCollection != null)
            {
                foreach (Namespace ns in namespacesCollection)
                {
                    namespaces.Add(ns.Name);
                }
            }
            DeviceType?dtype = null;
            string     tmp   = routingCollection.Device;
            DeviceType tt;

            if (string.IsNullOrWhiteSpace(tmp) == false && Enum.TryParse <DeviceType>(tmp, true, out tt))
            {
                dtype = tt;
            }
            string re_url = routingCollection.RedirectUrlForOtherDevices;
            string domain = routingCollection.Domain;

            foreach (RoutingItem routingItem in routingCollection)
            {
                RouteValueDictionary defaults    = new RouteValueDictionary();
                RouteValueDictionary constraints = new RouteValueDictionary();
                if (string.IsNullOrWhiteSpace(routingItem.Controller) == false)
                {
                    defaults.Add("controller", routingItem.Controller);
                }
                if (string.IsNullOrWhiteSpace(routingItem.Action) == false)
                {
                    defaults.Add("action", routingItem.Action);
                }
                foreach (Parameter param in routingItem.Paramaters)
                {
                    if (string.IsNullOrWhiteSpace(param.Value) == false)
                    {
                        string v = param.Value.Trim();
                        if (v == "UrlParameter.Optional")
                        {
                            defaults.Add(param.Name, UrlParameter.Optional);
                        }
                        else
                        {
                            defaults.Add(param.Name, v);
                        }
                    }
                    if (string.IsNullOrWhiteSpace(param.Constraint) == false)
                    {
                        constraints.Add(param.Name, param.Constraint);
                    }
                }
                MapRoute(routes, cutOutUrlFirstSection, routingItem.Name, routingItem.Url, defaults, constraints, areaName, namespaces.ToArray(),
                         dtype, string.IsNullOrWhiteSpace(routingItem.RedirectUrlForOtherDevices) ? re_url : routingItem.RedirectUrlForOtherDevices, domain, routingItem.AuthKey);
            }
        }
Ejemplo n.º 32
0
 public bool IsMobileAppUser(DeviceType?type)
 {
     return(UsageData.GetIsMobileAppUser(SecurityContext.CurrentAccount.ID, type));
 }
Ejemplo n.º 33
0
 public MockDeviceInfo(DevicePlatform?platform = null, DeviceIdiom?idiom = null, DeviceType?deviceType = null)
 {
     Platform   = platform ?? DevicePlatform.Unknown;
     Idiom      = idiom ?? DeviceIdiom.Unknown;
     DeviceType = deviceType ?? DeviceType.Unknown;
 }