Class that holds references to common game parts as a singleton.
Inheritance: MonoBehaviour
Example #1
0
        private void SendSlackNotification(IEnumerable <Dto.CryptoCurrency> cryptoCurrencies)
        {
            var bitStampEth = cryptoCurrencies.First(p => p.Currency == Currency.Eth && p.Provider == Provider.BitStamp);

            var btcTurkEth = cryptoCurrencies.First(p => p.Currency == Currency.Eth && p.Provider == Provider.BtcTurk);

            var bitStampBtc = cryptoCurrencies.First(p => p.Currency == Currency.Btc && p.Provider == Provider.BitStamp);

            var btcTurkBtc = cryptoCurrencies.First(p => p.Currency == Currency.Btc && p.Provider == Provider.BtcTurk);

            var ethDiffLimit = decimal.Parse(Statics.GetConfigKey(ConfigKeys.EthDiff));

            var diffEth             = btcTurkEth.UsdValue - bitStampEth.UsdValue;
            var ethProfitPercentage = GetProfitPercentage(btcTurkEth.UsdValue, diffEth);

            var diffBtc             = btcTurkBtc.UsdValue - bitStampBtc.UsdValue;
            var btcProfitPercentage = GetProfitPercentage(btcTurkBtc.UsdValue, diffBtc);

            if (diffEth >= ethDiffLimit)
            {
                var slackToken = Statics.GetConfigKey(ConfigKeys.SlackToken);

                var ethText       = $"BtcTurk/Bitstamp\nETH Diff\n{btcTurkEth.UsdValue.ToMoneyMarketMoneyFormat()} - {bitStampEth.UsdValue.ToMoneyMarketMoneyFormat()} = {diffEth.ToMoneyMarketMoneyFormat()} USD";
                var btcText       = $"BTC Diff\n{btcTurkBtc.UsdValue.ToMoneyMarketMoneyFormat()} - {bitStampBtc.UsdValue.ToMoneyMarketMoneyFormat()} = {diffBtc.ToMoneyMarketMoneyFormat()} USD";
                var ethProfitText = $"ETH profit = {ethProfitPercentage.ToMoneyMarketMoneyFormat()}";
                var btcProfitText = $"BTC profit = {btcProfitPercentage.ToMoneyMarketMoneyFormat()}";
                var payload       = new SlackMessage
                {
                    token   = slackToken,
                    channel = "#general",
                    text    = $"{ethText}\n{btcText}\n{ethProfitText}\n{btcProfitText}"
                };

                var slackClient = SlackApiClient.Instance;

                slackClient.InvokeApi <SlackMessage, object>("chat.postMessage", payload);
            }
        }
Example #2
0
 void doEventDelay()
 {
     if (!CanTriggerEvent())
     {
         return;
     }
     tk2dRuntime.TileMap.TileInfo eventTile = GetTileInfo(_x, _y, 1);
     if (eventTile != null)
     {
         //处理区域图上的事件
         if (eventTile.stringVal == "Event")
         {
             string id = Application.loadedLevelName + "_" + _x + "_" + _y;
             Messenger.Broadcast <string>(NotifyTypes.DealSceneEvent, id);
         }
     }
     else
     {
         //之前没有触发任何事件则在这里处理随机遇敌
         List <RateData> ratesData = Statics.GetMeetEnemyRates(UserModel.CurrentUserData.CurrentAreaSceneName);
         RateData        rateData;
         for (int i = 0; i < ratesData.Count; i++)
         {
             rateData = ratesData[i];
             if (rateData.Rate > 0 && rateData.IsTrigger(250f))
             {
                 if (AreaMainPanelCtrl.MakeCostNocturnalClothing())
                 {
                     Statics.CreatePopMsg(Vector3.zero, "被敌人发现后脱下夜行衣摆脱了对方", Color.yellow, 30);
                     break;
                 }
                 Messenger.Broadcast <string>(NotifyTypes.CreateBattle, rateData.Id); //遇敌
                 eventTriggerDate = Time.fixedTime;
                 break;
             }
         }
     }
 }
        public ActionResult Edit()
        {
            Account account = GetAuthCookieAccount();

            if (account == null)
            {
                return(RedirectToAction("Login", "Account"));
            }

            Account impersonateAccount = Statics.ImpersonateGet(Session);

            if (impersonateAccount != null)
            {
                account = impersonateAccount;
            }

            List <Degree> availableDegrees = new List <Degree>();

            availableDegrees = _degreeService.GetDegrees();

            if (account.Degree == null || account.Degree.Id <= 0)
            {
                account.Degree = availableDegrees[0];
            }
            if (account.Concentration == null || account.Concentration.Id <= 0)
            {
                account.Concentration = availableDegrees[0].Concentrations[0];
            }

            AccountViewModel model = new AccountViewModel
            {
                Account          = account,
                AvailableDegrees = availableDegrees,
                Impersonating    = (impersonateAccount != null)
            };

            return(View(model));
        }
    public void PushHard()
    {
        if (!Application.isShowingSplashScreen)
        {
            //スプラッシュ表示後

            if (Statics.unlockHard == 1)
            {
                Statics.level = 2;
                if (Statics.isWatchOpening == false)
                {
                    Statics.isWatchOpening = true;
                    SceneManager.LoadScene("Opening");
                }
                else
                {
                    SceneManager.LoadScene("Stage01");
                    //	if(Statics.charactor == 1)SceneManager.LoadScene ("Stage02");
                }
            }
            if (Statics.unlockHard == 0)
            {
                if (Statics.coin >= 70)
                {
                    Statics.coin -= 70;
                    Statics.Save();
                    Statics.unlockHard = 1;
                    Statics.SaveUnlock();
                    CheckUnlock();
                }
                else
                {
                    cointext.text = "コインが足りません";
                }
            }
        }
        //	start.gameObject.SetActive (false);
    }
Example #5
0
        private bool AddTypeImpl(Type type, int recursionLevel)
        {
            if (type == null)
            {
                return(false);
            }

            if (type.IsArray)
            {
                AddTypeImpl(type.GetElementType(), recursionLevel);
                return(false);
            }

            // Load type and stop if it is already loaded.
            if (!LoadTypeToScriptContext(type))
            {
                return(false);
            }

            // Add static.
            if (!Statics.ContainsKey(type.Name))
            {
                Statics.Add(type.Name, new Member {
                    Name = type.Name, Type = type
                });
                InstancesAndStaticsDirty = true;
            }

            if (recursionLevel-- > 0)
            {
                // Add static members.
                AddMembers(StaticMembers, type, BindingFlags.Static | BindingFlags.Public, recursionLevel);
                // Add instance members.
                AddMembers(InstanceMembers, type, BindingFlags.Instance | BindingFlags.Public, recursionLevel);
            }

            return(true);
        }
Example #6
0
        private void InitializeProviderMetadata()
        {
#if FEATURE_MANAGED_ETW
            if (m_traits != null)
            {
                List <byte> traitMetaData = new List <byte>(100);
                for (int i = 0; i < m_traits.Length - 1; i += 2)
                {
                    if (m_traits[i].StartsWith("ETW_", StringComparison.Ordinal))
                    {
                        string etwTrait = m_traits[i].Substring(4);
                        byte   traitNum;
                        if (!byte.TryParse(etwTrait, out traitNum))
                        {
                            if (etwTrait == "GROUP")
                            {
                                traitNum = 1;
                            }
                            else
                            {
                                throw new ArgumentException(SR.Format(SR.EventSource_UnknownEtwTrait, etwTrait), "traits");
                            }
                        }
                        string value  = m_traits[i + 1];
                        int    lenPos = traitMetaData.Count;
                        traitMetaData.Add(0);                                           // Emit size (to be filled in later)
                        traitMetaData.Add(0);
                        traitMetaData.Add(traitNum);                                    // Emit Trait number
                        var valueLen = AddValueToMetaData(traitMetaData, value) + 3;    // Emit the value bytes +3 accounts for 3 bytes we emited above.
                        traitMetaData[lenPos]     = unchecked ((byte)valueLen);         // Fill in size
                        traitMetaData[lenPos + 1] = unchecked ((byte)(valueLen >> 8));
                    }
                }
                providerMetadata = Statics.MetadataForString(this.Name, 0, traitMetaData.Count, 0);
                int startPos = providerMetadata.Length - traitMetaData.Count;
                foreach (var b in traitMetaData)
                    providerMetadata[startPos++] = b; }
            }
Example #7
0
        internal TraceLoggingEventTypes(
            string name,
            EventTags tags,
            System.Reflection.ParameterInfo[] paramInfos)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            Contract.EndContractBlock();

            this.typeInfos = MakeArray(paramInfos);
            this.name      = name;
            this.tags      = tags;
            this.level     = Statics.DefaultLevel;

            var collector = new TraceLoggingMetadataCollector();

            for (int i = 0; i < typeInfos.Length; ++i)
            {
                var typeInfo = typeInfos[i];
                this.level     = Statics.Combine((int)typeInfo.Level, this.level);
                this.opcode    = Statics.Combine((int)typeInfo.Opcode, this.opcode);
                this.keywords |= typeInfo.Keywords;
                var paramName = paramInfos[i].Name;
                if (Statics.ShouldOverrideFieldName(paramName))
                {
                    paramName = typeInfo.Name;
                }
                typeInfo.WriteMetadata(collector, paramName, EventFieldFormat.Default);
            }

            this.typeMetadata = collector.GetMetadata();
            this.scratchSize  = collector.ScratchSize;
            this.dataCount    = collector.DataCount;
            this.pinCount     = collector.PinCount;
        }
Example #8
0
    private void Send(object param)
    {
        MemoryStream stream = new MemoryStream();

        ProtoBuf.Serializer.NonGeneric.Serialize(stream, param);
        byte[] bs = stream.ToArray();
        Frame  f  = null;

        if (socket.getProtocal().GetType() == typeof(Varint32HeaderProtocol))
        {
            f = new Varint32Frame(512);
        }
        else
        {
            f = new Frame(512);
        }
        f.PutShort(MessageQueueHandler.GetProtocolCMD(param.GetType()));
        Debug.LogWarning("上行 cmd=" + MessageQueueHandler.GetProtocolCMD(param.GetType()) + ", type=" + param.GetType().ToString() + ", " + Time.fixedTime);
        Statics.SetXor(bs);
        f.PutBytes(bs);
        f.End();
        socket.Send(f);
    }
Example #9
0
        /// <summary>
        ///
        /// </summary>
        public void AddEmail()
        {
            string email = Statics.GetUserInput("Enter New Email Address: ", ConsoleColor.Gray, ConsoleColor.Green);

            if (email != "")
            {
                if (!Statics.Emails.Contains(email))
                {
                    Statics.Emails.Add(email);
                    Statics.PersistEmail();
                    Statics.Display($"Email Added: ", false, ConsoleColor.Gray);
                    Statics.Display($"{email}", true, ConsoleColor.Green);
                    Statics.Display($"New Emails Count: ", false, ConsoleColor.Gray);
                    Statics.Display($"{Statics.Emails.Count}", true, ConsoleColor.Green);
                    Statics.PressAnyKey();
                }
                else
                {
                    Statics.Display($"Email already exists.", true, ConsoleColor.Red);
                    Statics.PressAnyKey();
                }
            }
        }
Example #10
0
        public override bool Equals(object obj)
        {
            var tech = obj as IdsTech;

            return(tech != null &&
                   ThreatName == tech.ThreatName &&
                   ThreatType == tech.ThreatType &&
                   ThreatSubType == tech.ThreatSubType &&
                   Level == tech.Level &&
                   Statics.IpEquals(SourceIp, tech.SourceIp) &&
                   SourcePort == tech.SourcePort &&
                   Statics.IpEquals(TargetIp, tech.TargetIp) &&
                   TargetPort == tech.TargetPort &&
                   SourceInterface == tech.SourceInterface &&
                   TargetInterface == tech.TargetInterface &&
                   AppProtocol == tech.AppProtocol &&
                   Action == tech.Action &&
                   SecurityStrategy == tech.SecurityStrategy &&
                   StartTime == tech.StartTime &&
                   EndTime == tech.EndTime &&
                   TestEngine == tech.TestEngine &&
                   Comment == tech.Comment);
        }
Example #11
0
    IEnumerator StartMessage()
    {
        AudioManager.Instance.PlaySound("Collect");
        UIManager.Instance.ShowDialog();
        GameManager.Instance.GameVideo();
        PlayerManager.Instance.m_rb.velocity = Vector2.zero;
        yield return(new WaitForSeconds(0.6f));

        StartCoroutine(Statics.Flash(GetComponentInChildren <SpriteRenderer>(), Color.white, Color.clear, 0.7f));
        foreach (var item in Messages)
        {
            UIManager.Instance.ShowText(item);
            MouseDown = false; while (!MouseDown)
            {
                yield return(new WaitForEndOfFrame());
            }
        }
        //MouseDown = false; while (!MouseDown) yield return new WaitForEndOfFrame();
        UIManager.Instance.HideDialogAndText();
        GameManager.Instance.GameRestart();
        GetComponentInChildren <Collider2D>().enabled = false;
        Destroy(gameObject);
    }
Example #12
0
 public static void PrefLoading()
 {
     if (PlayerPrefs.HasKey("GlobalVolume"))
     {
         Statics.setVolume(PlayerPrefs.GetFloat("GlobalVolume"));
     }
     if (PlayerPrefs.HasKey("SoundVolume"))
     {
         Statics.soundVolume = PlayerPrefs.GetFloat("SoundVolume");
     }
     if (PlayerPrefs.HasKey("MusicVolume"))
     {
         Statics.musicVolume = PlayerPrefs.GetFloat("MusicVolume");
     }
     if (PlayerPrefs.HasKey("ControlMethod"))
     {
         Statics.selectedControlMethod = (ControlType)PlayerPrefs.GetInt("ControlMethod");
     }
     else
     {
                     #if UNITY_ANDROID
         Statics.selectedControlMethod = ControlType.freedragging;
                     #elif UNITY_EDITOR || UNITY_STANDALONE
         Statics.selectedControlMethod = ControlType.keyboard;
                     #else
         Statics.selectedControlMethod = ControlType.freedragging;
                     #endif
     }
     if (PlayerPrefs.HasKey("LevelsComplete"))
     {
         levelsComplete = PlayerPrefs.GetInt("LevelsComplete");
     }
     if (PlayerPrefs.HasKey("BestEndless"))
     {
         bestEndless = PlayerPrefs.GetInt("BestEndless");
     }
 }
Example #13
0
        /// <summary>
        /// Move the player to a new field based on which arrow key is currently pressed
        /// </summary>
        private void MoveFighter(Fighter f)
        {
            Position m = null;

            // check for registered move of player
            if (this.nextMove != null && f.GetType().Equals(typeof(Player)))
            {
                m             = this.nextMove;
                this.nextMove = null;
            }
            else if (f.GetType().Equals(typeof(Monster)))
            {
                // just move the monster
                List <Position> lp = LevelGenerator.GetNeighbourAccessFields(this.level, f);
                if (lp.Count > 0)
                {
                    // move towards player
                    int minDist = LevelGenerator.GetMinDistMove(this.player.Position, lp);
                    m = lp[minDist];
                }
            }
            if (m != null)
            {
                // check for valid move (free field and not against current face)
                if (Statics.IsValidMove(m, this.level, f))
                {
                    MakeMove(m, f, this.level);
                }
                else
                {
                    // not valid, but nevertheless change the
                    // direction the player is facing
                    Direction dir = Statics.GetMoveDirection(f.Position, m);
                    f.Face = (dir);
                }
            }
        }
Example #14
0
        public List <EmailModel> GetNewsletter()
        {
            List <EmailModel> Models = new List <EmailModel>();

            base.Connect();
            DataTable dt = base.Select("SELECT [Mail_Id],[EmailAddress],[Date],[IsActive] FROM [tbl_Newsletter]");

            base.DC();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var model = new EmailModel()
                {
                    Num     = i + 1,
                    EmailId = Convert.ToInt32(dt.Rows[i]["Mail_Id"]),
                    Active  = Convert.ToInt32(dt.Rows[i]["IsActive"]),
                    Email   = dt.Rows[i]["EmailAddress"].ToString(),
                    Date    = Statics.DateReturner(dt.Rows[i]["Date"].ToString(), "ShortDate")
                };
                Models.Add(model);
            }

            return(Models);
        }
        public Account GetAuthCookieAccount()
        {
            if (Lib.Statics.HasAuthCookie(Request))
            {
                string username = GetAuthCookieUsername();
                if (!string.IsNullOrWhiteSpace(username))
                {
                    Account account = new Account()
                    {
                        Username = username
                    };
                    account = _accountService.GetAccount(account.Username);

                    if (account == null || account.Id <= 0)
                    {
                        Statics.KillCookie(Request);
                        return(null);
                    }

                    return(account);
                }
            }
            return(null);
        }
Example #16
0
    private void find_nearest_target(Enemy enemy)
    {
        List <Slot> punits = Formation.I.get_highest_full_slots(Unit.PLAYER);

        Slot nearest_punit_slot = null;
        int  nearest_distance   = 100;

        foreach (Slot slot in punits)
        {
            if (!enemy.can_target(slot)) // Control for melee vs flying
            {
                continue;
            }

            int distance = Statics.calc_distance(enemy.get_slot(), slot);
            if (distance < nearest_distance)
            {
                nearest_distance   = distance;
                nearest_punit_slot = slot;
            }
        }
        //Debug.Log("setting target: " + nearest_punit_slot.get_punit());
        enemy.target = nearest_punit_slot;
    }
Example #17
0
 public void continue_pressed()
 {
     if (!gameOver)
     {
         inGameMenu.enabled = false;
         Time.timeScale     = 1;
     }
     else
     {
         if (matchover)
         {
             int i = 0;
             PlayerPrefsHandler.SetPersistentVar <int>(Statics.player_score(0), ref i, 0, true);
             PlayerPrefsHandler.SetPersistentVar <int>(Statics.player_score(1), ref i, 0, true);
             Time.timeScale = 1;
             SceneManager.LoadScene(0);
         }
         else
         {
             Time.timeScale = 1;
             SceneManager.LoadScene(2);
         }
     }
 }
Example #18
0
    public void AdjustCharSelectionWindow()
    {
        string character = Statics.GetCharacter();

        if (character == "female")
        {
            femaleDesc.SetActive(true);
            maleButton.SetActive(false);
            nbButton.SetActive(false);
        }
        if (character == "male")
        {
            maleDesc.SetActive(true);
            femaleButton.SetActive(false);
            nbButton.SetActive(false);
        }
        if (character == "non-binary")
        {
            nbDesc.SetActive(true);
            femaleButton.SetActive(false);
            maleButton.SetActive(false);
        }
        backButton.SetActive(true);
    }
Example #19
0
        public BusinessResponse RefreshTickers()
        {
            var resp = new BusinessResponse
            {
                ResponseCode = ResponseCode.Fail
            };

            var usdSellRate = Statics.GetLatestUsdSellRate();

            var cryptoCurrencies = new List <Dto.CryptoCurrency>();

            var refresherClasses = GetRefresherClassNames();


            foreach (var refresherClass in refresherClasses)
            {
                var cryptoCurrencyClassName = GetCryptoCurrencyClassName(refresherClass);
                var type = Type.GetType(cryptoCurrencyClassName);

                var obj = Activator.CreateInstance(type, true);

                var ticker = obj as ITicker;

                ticker.UsdSellRate = usdSellRate;

                cryptoCurrencies.AddRange(ticker.GetCurrentCryptoCurrency());
            }

            UpdateCryptoCurrencies(cryptoCurrencies);
            UpdateUsdSellRate(usdSellRate);

            SendSlackNotification(cryptoCurrencies);

            resp.ResponseCode = ResponseCode.Success;
            return(resp);
        }
Example #20
0
        public static int Insert(Login value)
        {
            try
            {
                SqliteConnection connection = new SqliteConnection(Statics.GetConnectionString());
                connection.Open();
                SqliteCommand command = connection.CreateCommand();

                string commandStr = string.Format("INSERT INTO Login (UserName,IsAuthorized,SessionKey) VALUES('{0}','{1}','{2}');SELECT last_insert_rowid();",
                                                  value.UserName, value.IsAuthorized, value.SessionKey);
                command.CommandText = commandStr;

                var result = command.ExecuteScalar();

                connection.Close();

                int id = 0;

                if (result != null)
                {
                    id = Convert.ToInt32(result);

                    return(id);
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                throw ex;
#else
                return(-1);
#endif
            }

            return(-1);
        }
Example #21
0
    /// <summary>
    /// 清空临时禁用事件
    /// </summary>
    public void ClearDisableEventIdMapping(List <SceneEventType> excepts = null)
    {
        List <string> clearKeys = new List <string>();
        EventData     eventData;

        foreach (string key in DisableEventIdMapping.Keys)
        {
            eventData = DisableEventIdMapping[key];
            if (excepts != null && excepts.FindIndex(type => type == eventData.Type) >= 0)
            {
                continue;
            }
            Map.Layers[2].ClearTile(eventData.X, eventData.Y);
            clearKeys.Add(key);
        }
        Map.Build(tk2dTileMap.BuildFlags.Default);
        Statics.ChangeLayers(GameObject.Find("TileMap Render Data").transform, "Ground");
        for (int i = 0, len = clearKeys.Count; i < len; i++)
        {
            DisableEventIdMapping.Remove(clearKeys[i]);
        }

        PlayerPrefs.SetString("DisableEventIdMapping", JsonManager.GetInstance().SerializeObject(DisableEventIdMapping));
    }
Example #22
0
 void Update()
 {
     if (Input.GetKeyDown(KeyCode.Escape) && prevSceneName != "" && _asyncOp == null)
     {
         _asyncOp = Application.LoadLevelAsync(prevSceneName);
         if (audio)
         {
             _asyncOp.allowSceneActivation = false;
             audio.Play();
         }
     }
     else if (Input.GetKeyDown(KeyCode.Escape) && prevSceneName == "" && quit)
     {
         Statics.PrefStoring();
         Application.Quit();
     }
     if (_asyncOp != null && audio)
     {
         if (!audio.isPlaying)
         {
             _asyncOp.allowSceneActivation = true;
         }
     }
 }
Example #23
0
    private void HandleShowResult(ShowResult result)
    {
        switch (result)
        {
        case ShowResult.Finished:
            Debug.Log("The ad was successfully shown.");
            Statics.coin += 20;
            Statics.Save();
            //
            // YOUR CODE TO REWARD THE GAMER
            // Give coins etc.
            break;

        case ShowResult.Skipped:
            Debug.Log("The ad was skipped before reaching the end.");
            Statics.coin += 20;
            Statics.Save();
            break;

        case ShowResult.Failed:
            //Debug.LogError("The ad failed to be shown.");
            break;
        }
    }
            public override Func <PropertyValue, PropertyValue> GetPropertyGetter(PropertyInfo property)
            {
                var type = property.PropertyType;

                if (!Statics.IsValueType(type))
                {
                    var getter = (Func <TContainer, object>)GetGetMethod(property, type);
                    return(container => new PropertyValue(getter((TContainer)container.ReferenceValue)));
                }
                else
                {
                    if (type.GetTypeInfo().IsEnum)
                    {
                        type = Enum.GetUnderlyingType(type);
                    }

                    if (type == typeof(bool))
                    {
                        var f = (Func <TContainer, bool>)GetGetMethod(property, type); return(container => new PropertyValue(f((TContainer)container.ReferenceValue)));
                    }
                    if (type == typeof(byte))
                    {
                        var f = (Func <TContainer, byte>)GetGetMethod(property, type); return(container => new PropertyValue(f((TContainer)container.ReferenceValue)));
                    }
                    if (type == typeof(sbyte))
                    {
                        var f = (Func <TContainer, sbyte>)GetGetMethod(property, type); return(container => new PropertyValue(f((TContainer)container.ReferenceValue)));
                    }
                    if (type == typeof(char))
                    {
                        var f = (Func <TContainer, char>)GetGetMethod(property, type); return(container => new PropertyValue(f((TContainer)container.ReferenceValue)));
                    }
                    if (type == typeof(short))
                    {
                        var f = (Func <TContainer, short>)GetGetMethod(property, type); return(container => new PropertyValue(f((TContainer)container.ReferenceValue)));
                    }
                    if (type == typeof(ushort))
                    {
                        var f = (Func <TContainer, ushort>)GetGetMethod(property, type); return(container => new PropertyValue(f((TContainer)container.ReferenceValue)));
                    }
                    if (type == typeof(int))
                    {
                        var f = (Func <TContainer, int>)GetGetMethod(property, type); return(container => new PropertyValue(f((TContainer)container.ReferenceValue)));
                    }
                    if (type == typeof(uint))
                    {
                        var f = (Func <TContainer, uint>)GetGetMethod(property, type); return(container => new PropertyValue(f((TContainer)container.ReferenceValue)));
                    }
                    if (type == typeof(long))
                    {
                        var f = (Func <TContainer, long>)GetGetMethod(property, type); return(container => new PropertyValue(f((TContainer)container.ReferenceValue)));
                    }
                    if (type == typeof(ulong))
                    {
                        var f = (Func <TContainer, ulong>)GetGetMethod(property, type); return(container => new PropertyValue(f((TContainer)container.ReferenceValue)));
                    }
                    if (type == typeof(IntPtr))
                    {
                        var f = (Func <TContainer, IntPtr>)GetGetMethod(property, type); return(container => new PropertyValue(f((TContainer)container.ReferenceValue)));
                    }
                    if (type == typeof(UIntPtr))
                    {
                        var f = (Func <TContainer, UIntPtr>)GetGetMethod(property, type); return(container => new PropertyValue(f((TContainer)container.ReferenceValue)));
                    }
                    if (type == typeof(float))
                    {
                        var f = (Func <TContainer, float>)GetGetMethod(property, type); return(container => new PropertyValue(f((TContainer)container.ReferenceValue)));
                    }
                    if (type == typeof(double))
                    {
                        var f = (Func <TContainer, double>)GetGetMethod(property, type); return(container => new PropertyValue(f((TContainer)container.ReferenceValue)));
                    }
                    if (type == typeof(Guid))
                    {
                        var f = (Func <TContainer, Guid>)GetGetMethod(property, type); return(container => new PropertyValue(f((TContainer)container.ReferenceValue)));
                    }
                    if (type == typeof(DateTime))
                    {
                        var f = (Func <TContainer, DateTime>)GetGetMethod(property, type); return(container => new PropertyValue(f((TContainer)container.ReferenceValue)));
                    }
                    if (type == typeof(DateTimeOffset))
                    {
                        var f = (Func <TContainer, DateTimeOffset>)GetGetMethod(property, type); return(container => new PropertyValue(f((TContainer)container.ReferenceValue)));
                    }
                    if (type == typeof(TimeSpan))
                    {
                        var f = (Func <TContainer, TimeSpan>)GetGetMethod(property, type); return(container => new PropertyValue(f((TContainer)container.ReferenceValue)));
                    }
                    if (type == typeof(decimal))
                    {
                        var f = (Func <TContainer, decimal>)GetGetMethod(property, type); return(container => new PropertyValue(f((TContainer)container.ReferenceValue)));
                    }

                    return(container => new PropertyValue(property.GetValue(container.ReferenceValue)));
                }
            }
Example #25
0
 public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format)
 {
     collector.AddScalar(name, Statics.Format32(format, TraceLoggingDataType.Int32));
 }
Example #26
0
        public void DataReceived(object sender, UsbLibrary.DataRecievedEventArgs e)
        {
            Array.Clear(writeBuffer, 0, writeBuffer.Length);
            char[] asciiChars = new char[Encoding.ASCII.GetCharCount(e.data, 0, e.data.Length)];
            Encoding.ASCII.GetChars(e.data, 0, e.data.Length, asciiChars, 0);
            string newString = new string(asciiChars);

            tempString += new string(asciiChars).Substring(5);
            tempString  = tempString.Replace("\0", string.Empty);

            //send read number of results on device message
            if (_HeaderRead && !_NumResultsRead && _CountStep <= 3)
            {
                GetSampleCountMessages();
                return;
            }

            ////send read config message
            //if (_HeaderRead && _NumResultsRead && !_ConfigRead && _CountStep <= 1)
            //{
            //    GetConfigMessages();
            //    return;
            //}

            //preheader
            if (tempString.StartsWith(Statics.GetStringFromAsciiCode((byte)AsciiCodes.ENQ)) && tempString.Length == 1)
            {
                tempString     = string.Empty;
                writeBuffer[3] = (byte)AsciiCodes.RH;
                writeBuffer[4] = (byte)AsciiCodes.ACK;
                Port.SpecifiedDevice.SendData(writeBuffer);
                return;
            }

            //new line detected so frame is complete
            if (tempString.Contains("\r\n"))
            {
                tempString = tempString.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)[0];

                //header
                if (tempString.Contains(((char)AsciiCodes.STX).ToString() + "1H"))
                {
                    _HeaderRead = true;
                    ParseHeader(tempString);
                    tempString     = string.Empty;
                    writeBuffer[3] = (byte)AsciiCodes.RH;
                    writeBuffer[4] = (byte)AsciiCodes.EOT;
                    Port.SpecifiedDevice.SendData(writeBuffer);
                    Thread.Sleep(100);
                    return;
                }

                //patient record
                if (tempString.Length > tempString.IndexOf((char)AsciiCodes.STX) + 2 && tempString[tempString.IndexOf((char)AsciiCodes.STX) + 2] == 'P')
                {
                    tempString = string.Empty;
                }

                //terminator record
                if (tempString.Length > tempString.IndexOf((char)AsciiCodes.STX) + 2 && tempString[tempString.IndexOf((char)AsciiCodes.STX) + 2] == 'L')
                {
                    tempString = string.Empty;
                }

                //glucose record
                if (tempString.Contains("^^^Glucose"))
                {
                    string[] splitrecord = tempString.Split(new string[] { "|", "\r", "^" }, StringSplitOptions.RemoveEmptyEntries);
                    int      year        = int.Parse(splitrecord[7].Substring(0, 4));
                    int      month       = int.Parse(splitrecord[7].Substring(4, 2));
                    int      day         = int.Parse(splitrecord[7].Substring(6, 2));
                    int      hour        = int.Parse(splitrecord[7].Substring(8, 2));
                    int      minute      = int.Parse(splitrecord[7].Substring(10, 2));

                    DateTime dtTimeStamp = new DateTime(year, month, day, hour, minute, 0);

                    int    glucose      = int.Parse(splitrecord[3]);
                    string sampleFormat = splitrecord[4];

                    this.SampleFormat = sampleFormat.ToLowerInvariant().Contains("mmol") ? SampleFormat.MMOL : SampleFormat.MGDL;

                    //put the record in the dataset and raise the read event
                    try
                    {
                        if (Records.FindByTimestamp(dtTimeStamp) == null)
                        {
                            //only insert non-duplicate records
                            OnRecordRead(new RecordReadEventArgs(this._Records.AddRecordRow(dtTimeStamp, glucose, sampleFormat)));
                            RecordsRead++;
                        } //if
                    }     //try
                    catch
                    {
                    }//catch

                    tempString = string.Empty;
                }

                //num results message arrived
                if (tempString.Contains("D|") && !_NumResultsRead)
                {
                    //cut message out of string
                    string    message = tempString.Substring(tempString.IndexOf("D|"));
                    string [] splits  = tempString.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                    this.SampleCount = Convert.ToInt32(splits[1]);
                    tempString       = string.Empty;
                    _NumResultsRead  = true;
                    _CountStep       = 0;
                    Thread.Sleep(100);
                    OnHeaderRead(new HeaderReadEventArgs(SampleCount, this));
                    //GetConfigMessages();
                    return;
                }

                ////results format
                //if (tempString.Contains("D|") && !_ConfigRead)
                //{
                //    //cut message out of string
                //    string message = tempString.Substring(tempString.IndexOf("D|"));
                //    string[] splits = tempString.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                //    BitArray bitary = new BitArray(Byte.Parse(splits[1]));
                //    SampleFormat = (bitary.Get(2)) ? SampleFormat.MMOL : SampleFormat.MGDL;
                //    tempString = string.Empty;
                //    _ConfigRead = true;
                //    _CountStep = 0;
                //    Thread.Sleep(100);
                //    return;
                //}
            }

            //end of transmission encountered after a header record is read
            if (_HeaderRead && _NumResultsRead && RecordsRead >= SampleCount)
            {
                _HeaderRead          = false;
                Port.OnDataRecieved -= new UsbLibrary.DataRecievedEventHandler(DataReceived);
                Port.SpecifiedDevice.DataRecieved -= SpecifiedDevice_DataRecieved;
                OnReadFinished(new ReadFinishedEventArgs(this));
                Close();
                Dispose();
                return;
            }//elseif

            if (_NumResultsRead)// && _ConfigRead)
            {
                Array.Clear(writeBuffer, 0, writeBuffer.Length);
                writeBuffer[4] = (byte)AsciiCodes.RH;
                writeBuffer[5] = (byte)AsciiCodes.ACK;
                Port.SpecifiedDevice.SendData(writeBuffer);
                Thread.Sleep(100);
            }
        }
Example #27
0
        public TypeAnalysis(
            Type dataType,
            EventDataAttribute eventAttrib,
            List <Type> recursionCheck)
        {
            var propertyInfos = Statics.GetProperties(dataType);
            var propertyList  = new List <PropertyAnalysis>();

            foreach (var propertyInfo in propertyInfos)
            {
                if (Statics.HasCustomAttribute(propertyInfo, typeof(EventIgnoreAttribute)))
                {
                    continue;
                }

                if (!propertyInfo.CanRead ||
                    propertyInfo.GetIndexParameters().Length != 0)
                {
                    continue;
                }

                MethodInfo getterInfo = Statics.GetGetMethod(propertyInfo);
                if (getterInfo == null)
                {
                    continue;
                }

                if (getterInfo.IsStatic || !getterInfo.IsPublic)
                {
                    continue;
                }

                var propertyType     = propertyInfo.PropertyType;
                var propertyTypeInfo = TraceLoggingTypeInfo.GetInstance(propertyType, recursionCheck);
                var fieldAttribute   = Statics.GetCustomAttribute <EventFieldAttribute>(propertyInfo);

                string propertyName =
                    fieldAttribute != null && fieldAttribute.Name != null
                    ? fieldAttribute.Name
                    : Statics.ShouldOverrideFieldName(propertyInfo.Name)
                    ? propertyTypeInfo.Name
                    : propertyInfo.Name;
                propertyList.Add(new PropertyAnalysis(
                                     propertyName,
                                     propertyInfo,
                                     propertyTypeInfo,
                                     fieldAttribute));
            }

            this.properties = propertyList.ToArray();

            foreach (var property in this.properties)
            {
                var typeInfo = property.typeInfo;
                this.level     = (EventLevel)Statics.Combine((int)typeInfo.Level, (int)this.level);
                this.opcode    = (EventOpcode)Statics.Combine((int)typeInfo.Opcode, (int)this.opcode);
                this.keywords |= typeInfo.Keywords;
                this.tags     |= typeInfo.Tags;
            }

            if (eventAttrib != null)
            {
                this.level     = (EventLevel)Statics.Combine((int)eventAttrib.Level, (int)this.level);
                this.opcode    = (EventOpcode)Statics.Combine((int)eventAttrib.Opcode, (int)this.opcode);
                this.keywords |= eventAttrib.Keywords;
                this.tags     |= eventAttrib.Tags;
                this.name      = eventAttrib.Name;
            }

            if (this.name == null)
            {
                this.name = dataType.Name;
            }
        }
Example #28
0
 public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format)
 {
     collector.AddArray(name, Statics.Format64(format, TraceLoggingDataType.Double));
 }
Example #29
0
 public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format)
 {
     collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.Double, format));
 }
Example #30
0
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     Statics.CleanThreadContextAndAssert();
 }
Example #31
0
    void Awake()
    {
        instance = this;

        Initialise();
    }