public static void CreateStateChangeEvents(List <CombatItem> stateChangeEvents, MetaEventsContainer metaDataEvents, StatusEventsContainer statusEvents, List <RewardEvent> rewardEvents, AgentData agentData)
        {
            foreach (CombatItem c in stateChangeEvents)
            {
                switch (c.IsStateChange)
                {
                case ParseEnum.StateChange.EnterCombat:
                    var enterCombatEvt = new EnterCombatEvent(c, agentData);
                    GeneralHelper.Add(statusEvents.EnterCombatEvents, enterCombatEvt.Src, enterCombatEvt);
                    break;

                case ParseEnum.StateChange.ExitCombat:
                    var exitCombatEvt = new ExitCombatEvent(c, agentData);
                    GeneralHelper.Add(statusEvents.ExitCombatEvents, exitCombatEvt.Src, exitCombatEvt);
                    break;

                case ParseEnum.StateChange.ChangeUp:
                    var aliveEvt = new AliveEvent(c, agentData);
                    GeneralHelper.Add(statusEvents.AliveEvents, aliveEvt.Src, aliveEvt);
                    break;

                case ParseEnum.StateChange.ChangeDead:
                    var deadEvt = new DeadEvent(c, agentData);
                    GeneralHelper.Add(statusEvents.DeadEvents, deadEvt.Src, deadEvt);
                    break;

                case ParseEnum.StateChange.ChangeDown:
                    var downEvt = new DownEvent(c, agentData);
                    GeneralHelper.Add(statusEvents.DownEvents, downEvt.Src, downEvt);
                    break;

                case ParseEnum.StateChange.Spawn:
                    var spawnEvt = new SpawnEvent(c, agentData);
                    GeneralHelper.Add(statusEvents.SpawnEvents, spawnEvt.Src, spawnEvt);
                    break;

                case ParseEnum.StateChange.Despawn:
                    var despawnEvt = new DespawnEvent(c, agentData);
                    GeneralHelper.Add(statusEvents.DespawnEvents, despawnEvt.Src, despawnEvt);
                    break;

                case ParseEnum.StateChange.HealthUpdate:
                    var healthEvt = new HealthUpdateEvent(c, agentData);
                    GeneralHelper.Add(statusEvents.HealthUpdateEvents, healthEvt.Src, healthEvt);
                    break;

                case ParseEnum.StateChange.LogStart:
                    metaDataEvents.LogStartEvents.Add(new LogStartEvent(c));
                    break;

                case ParseEnum.StateChange.LogEnd:
                    metaDataEvents.LogEndEvents.Add(new LogEndEvent(c));
                    break;

                case ParseEnum.StateChange.MaxHealthUpdate:
                    var maxHealthEvt = new MaxHealthUpdateEvent(c, agentData);
                    GeneralHelper.Add(statusEvents.MaxHealthUpdateEvents, maxHealthEvt.Src, maxHealthEvt);
                    break;

                case ParseEnum.StateChange.PointOfView:
                    metaDataEvents.PointOfViewEvents.Add(new PointOfViewEvent(c, agentData));
                    break;

                case ParseEnum.StateChange.Language:
                    metaDataEvents.LanguageEvents.Add(new LanguageEvent(c));
                    break;

                case ParseEnum.StateChange.GWBuild:
                    metaDataEvents.BuildEvents.Add(new BuildEvent(c));
                    break;

                case ParseEnum.StateChange.ShardId:
                    metaDataEvents.ShardEvents.Add(new ShardEvent(c));
                    break;

                case ParseEnum.StateChange.Reward:
                    rewardEvents.Add(new RewardEvent(c));
                    break;

                case ParseEnum.StateChange.TeamChange:
                    var tcEvt = new TeamChangeEvent(c, agentData);
                    GeneralHelper.Add(statusEvents.TeamChangeEvents, tcEvt.Src, tcEvt);
                    break;

                case ParseEnum.StateChange.AttackTarget:
                    var aTEvt = new AttackTargetEvent(c, agentData);
                    GeneralHelper.Add(statusEvents.AttackTargetEvents, aTEvt.Src, aTEvt);
                    break;

                case ParseEnum.StateChange.Targetable:
                    var tarEvt = new TargetableEvent(c, agentData);
                    GeneralHelper.Add(statusEvents.TargetableEvents, tarEvt.Src, tarEvt);
                    break;

                case ParseEnum.StateChange.MapID:
                    metaDataEvents.MapIDEvents.Add(new MapIDEvent(c));
                    break;

                case ParseEnum.StateChange.Guild:
                    var gEvt = new GuildEvent(c, agentData);
                    GeneralHelper.Add(metaDataEvents.GuildEvents, gEvt.Src, gEvt);
                    break;
                }
            }
        }
 /// <summary>
 /// Helper, to allow the use of anonymous delegates.
 /// </summary>
 public object Invoke(GeneralHelper.DefaultDelegate delegateInstance)
 {
     object result;
     Invoke(delegateInstance, TimeSpan.MaxValue, out result);
     return result;
 }
 /// <summary>
 /// 
 /// </summary>
 public bool Invoke(GeneralHelper.DefaultDelegate delegateInstance, TimeSpan timeOut)
 {
     object dummy;
     return Invoke((Delegate)delegateInstance, timeOut, out dummy);
 }
 /// <summary>
 /// Helper.
 /// </summary>
 public static IAsyncResult BeginManagedInvoke(Control invocationControl, GeneralHelper.DefaultDelegate d)
 {
     return BeginManagedInvoke(invocationControl, (Delegate)d);
 }
 /// <summary>
 /// Helper.
 /// </summary>
 public static bool BeginFilteredManagedInvoke(Control control, TimeSpan minimumInvocationInterval, GeneralHelper.DefaultDelegate d)
 {
     return BeginFilteredManagedInvoke(control, minimumInvocationInterval, (Delegate)d);
 }
Example #6
0
 private void buttonOk_Click(object sender, EventArgs e)
 {
     Submit();
     GeneralHelper.ProcessStart("osu!.exe");
     Close();
 }
Example #7
0
        private static void TriggerSportCombat(GameUser user, GameUser toUser, int sportNum, ref string sportsPrizeString, UserMail userMail)
        {
            CombatProcessContainer combatProcessList = null;
            int rewardGoin   = 0;
            int rewardObtion = 0; //荣誉值
            int experence    = 0; //经验
            int winNum       = 0;

            //原因:gameuser加了连胜字段
            winNum = user.VictoryNum;

            int rankIndex;
            int torankIndex;
            Ranking <UserRank> ranking = RankingFactory.Get <UserRank>(CombatRanking.RankingKey);

            if (!ranking.TryGetRankNo(m => m.UserID == user.UserID, out rankIndex) || !ranking.TryGetRankNo(m => m.UserID == toUser.UserID, out torankIndex))
            {
                return;
            }
            UserRank userRank   = ranking.Find(s => s.UserID == user.UserID);
            UserRank toUserRank = ranking.Find(s => s.UserID == toUser.UserID);

            if (userRank == null || toUserRank == null)
            {
                return;
            }

            //修改wuzf,两个地方调用Doing()方法
            ISingleCombat sportCombat = CombatFactory.TriggerTournament(user, toUser);

            if (sportCombat == null)
            {
                return;
            }
            bool isWin = sportCombat.Doing();

            if (isWin)
            {
                winNum = MathUtils.Addition(winNum, 1, int.MaxValue);
                userRank.VictoryNum   = winNum;
                toUserRank.VictoryNum = 0;
                toUser.VictoryNum     = 0;
                new PersonalCacheStruct <GameUser>().UpdateSelf(toUser.PersonalId);
                rewardGoin   = (user.UserLv * 40); //GetRewardGameCoin(user, user.UserLv);
                experence    = (user.UserLv * 10);
                rewardObtion = 10;
                AddFoe(user, toUser);
            }
            else
            {
                winNum = 0;
                userRank.VictoryNum = 0;
                rewardGoin          = (user.UserLv * 20);
                if (!rewardGoin.IsValid())
                {
                    rewardGoin = 0;
                }
                experence    = (user.UserLv * 5);
                rewardObtion = 5;
            }


            //公会贡献
            UserHelper.Contribution(user.UserID, rewardObtion);
            if (!string.IsNullOrEmpty(user.MercenariesID))
            {
                GuildMemberLog.AddLog(user.MercenariesID, new MemberLog
                {
                    UserID     = user.UserID,
                    IdolID     = 0,
                    LogType    = 1,
                    GainObtion = rewardObtion,
                    Experience = rewardObtion,
                    GainAura   = 0,
                    InsertDate = DateTime.Now,
                });
            }
            user.VictoryNum = winNum;
            new PersonalCacheStruct <GameUser>().UpdateSelf(user.PersonalId);
            user.ExpNum   = MathUtils.Addition(user.ExpNum, rewardObtion, int.MaxValue);
            user.GameCoin = MathUtils.Addition(user.GameCoin, rewardGoin, int.MaxValue);
            GeneralHelper.UserGeneralExp(user.UserID, 0, experence);

            int _rankTopId   = 0;
            int _ranktoTopID = 0;

            if (isWin && rankIndex > torankIndex)
            {
                _rankTopId   = toUserRank.RankId;
                _ranktoTopID = userRank.RankId;
            }
            else
            {
                _rankTopId   = userRank.RankId;
                _ranktoTopID = toUserRank.RankId;
            }

            combatProcessList = (CombatProcessContainer)sportCombat.GetProcessResult();
            user.SportsCombatQueue.Enqueue(new SportsCombat()
            {
                ToUser        = toUser.UserID,
                ToUserName    = toUser.NickName,
                TopID         = _rankTopId,
                IsWin         = isWin,
                RewardGoin    = rewardGoin,
                RewardObtian  = rewardObtion,
                SportsNum     = sportNum,
                WinNum        = winNum,
                CombatDate    = DateTime.Now,
                CombatProcess = combatProcessList,
                IsSelf        = true,
                RankStatus    = GetRankStatus(isWin, userRank, toUserRank)
            });

            UserDailyRestrain dailyRestrain = new PersonalCacheStruct <UserDailyRestrain>().FindKey(toUser.UserID) ?? new UserDailyRestrain();

            toUser.SportsCombatQueue.Enqueue(new SportsCombat()
            {
                ToUser        = user.UserID,
                ToUserName    = user.NickName,
                TopID         = _ranktoTopID,
                IsWin         = !isWin,
                RewardGoin    = 0,
                RewardObtian  = 0,
                SportsNum     = dailyRestrain.Funtion9,
                WinNum        = toUserRank.VictoryNum,
                CombatDate    = DateTime.Now,
                CombatProcess = combatProcessList,
                IsSelf        = false,
                RankStatus    = GetRankStatus(!isWin, toUserRank, userRank)
            });

            //日志
            UserCombatLog log = new UserCombatLog()
            {
                CombatLogID   = Guid.NewGuid().ToString(),
                UserID        = user.UserID,
                CityID        = 0,
                PlotID        = 0,
                NpcID         = 0,
                CombatType    = CombatType.User,
                HostileUser   = toUser.UserID,
                IsWin         = isWin,
                CombatProcess = JsonUtils.Serialize(combatProcessList),
                CreateDate    = DateTime.Now
            };
            var sender = DataSyncManager.GetDataSender();

            sender.Send(log);

            string prizeContent = string.Empty;

            MysteryHelper.IsTriggerMyStery(user, MysteryType.Jingjichang, out prizeContent);
            MysteryInfo mysteryInfo = new ShareCacheStruct <MysteryInfo>().FindKey(MysteryType.Jingjichang);

            if (!string.IsNullOrEmpty(prizeContent) && mysteryInfo != null)
            {
                var prompt    = string.Empty;
                var broadcast = string.Empty;
                if (isWin)
                {
                    prompt    = mysteryInfo.WinPrompt;
                    broadcast = mysteryInfo.WinBroadcast;
                }
                else
                {
                    prompt    = mysteryInfo.Prompt;
                    broadcast = mysteryInfo.Broadcast;
                }
                sportsPrizeString = string.Format(prompt, toUser.NickName, prizeContent);
                string broadContent     = string.Format(broadcast, toUser.NickName, prizeContent);
                var    broadcastService = new TjxBroadcastService(null);
                var    msg = broadcastService.Create(NoticeType.System, broadContent);
                broadcastService.Send(msg);
            }
            //sportsPrizeString = SportsPrizeHelper.DoPrize(user.UserID, isWin, toUser.NickName);
            //var userMail = new UserMail(Guid.NewGuid());
            var mailText = string.Format(LanguageManager.GetLang().SportsRankLetterForWin, user.NickName);

            if (isWin)
            {
                if (rankIndex > torankIndex)
                {
                    //SportsRankPrize(rankIndex, user, torankIndex);
                    //SportsRankPrize(torankIndex, toUser, rankIndex);
                    ranking.TryMove(rankIndex, torankIndex);
                    //user.RankID = torankIndex;
                    //user.RankDate = DateTime.Now;
                    //toUser.RankID = rankIndex;
                    //toUser.RankDate = DateTime.Now;
                    new PersonalCacheStruct <GameUser>().UpdateSelf(user.PersonalId);
                    new PersonalCacheStruct <GameUser>().UpdateSelf(toUser.PersonalId);
                    mailText = string.Format(LanguageManager.GetLang().SportsRankLetterForFailure, user.NickName, rankIndex);
                }
                else
                {
                    mailText = string.Format(LanguageManager.GetLang().SportsRankLetterForFailureRank, user.NickName, rankIndex);
                }
                UserHelper.SprostSystemChat(userRank, toUserRank);
                NoviceHelper.SportCombatFestival(user, winNum, userRank.VictoryNum);
            }
            userMail.Content = mailText;
            var userid = toUser.UserID.ToInt();

            userMail.ToUserID            = userid;
            userMail.UserId              = userid;
            userMail.MailType            = (int)MailType.Fight;
            userMail.ToUserName          = toUser.NickName;
            userMail.FromUserName        = LanguageManager.GetLang().St_SystemMailTitle;
            userMail.FromUserId          = LanguageManager.GetLang().SystemUserId;
            userMail.SendDate            = DateTime.Now;
            userMail.Title               = string.Empty;
            userMail.CounterattackUserID = user.UserID.ToInt();
            userMail.CombatProcess       = JsonUtils.Serialize(combatProcessList);
            userMail.IsWin               = isWin;
        }
Example #8
0
        public void Execute(IServiceProvider serviceProvider)
        {
            SqlDataAccess sda = null;

            sda = new SqlDataAccess();
            sda.openConnection(Globals.ConnectionString);

            try
            {
                #region | SERVICE |
                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

                #region | Validate Request |
                //Target yoksa veya Entity tipinde değilse, devam etme.
                if (!context.InputParameters.Contains("Target") || !(context.InputParameters["Target"] is Entity))
                {
                    return;
                }
                #endregion

                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                #endregion

                Entity entity = (Entity)context.InputParameters["Target"];

                #region | SET TITLECASE |
                if (entity.Attributes.Contains("firstname") && !string.IsNullOrEmpty(entity["firstname"].ToString()))
                {
                    entity["firstname"] = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(entity["firstname"].ToString().ToLower());
                }
                if (entity.Attributes.Contains("lastname") && !string.IsNullOrEmpty(entity["lastname"].ToString()))
                {
                    entity["lastname"] = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(entity["lastname"].ToString().ToLower());
                }
                #endregion

                #region | CHECK DUPLICATE |
                if (entity.Attributes.Contains("new_tcidentitynumber"))
                {
                    if (entity["new_tcidentitynumber"] != null)
                    {
                        string identityNumber = entity["new_tcidentitynumber"].ToString();

                        MsCrmResult identityResult = ContactHelper.CheckDuplicateIdentity(identityNumber, sda);
                        if (!identityResult.Success)
                        {
                            throw new Exception(identityResult.Result);
                        }
                    }
                }

                if (entity.Attributes.Contains("emailaddress1"))
                {
                    string email = entity["emailaddress1"].ToString();

                    MsCrmResult emailResult = ContactHelper.CheckDuplicateEmail(email, sda);
                    if (!emailResult.Success)
                    {
                        throw new Exception(emailResult.Result);
                    }
                }
                else
                {
                    throw new Exception("Email adresi boş bırakılamaz!");
                }

                if (entity.Attributes.Contains("mobilephone"))
                {
                    string mobilePhone = entity["mobilephone"].ToString();

                    MsCrmResult phoneResult = ContactHelper.CheckDuplicatePhone(mobilePhone, sda);
                    if (!phoneResult.Success)
                    {
                        throw new Exception(phoneResult.Result);
                    }

                    TelephoneNumber number = GeneralHelper.CheckTelephoneNumber(mobilePhone);
                    if (number.isFormatOK)
                    {
                        entity["new_countrycodemobilephone"] = number.countryCode;
                        entity["new_cellphonenumber"]        = number.phoneNo;
                    }
                    else
                    {
                        throw new Exception("Lütfen doğru bir telefon giriniz!");
                    }
                }
                else
                {
                    throw new Exception("Cep Telefonu boş bırakılamaz!");
                }
                #endregion

                #region | SET CUSTOMER NUMBER|
                ContactHelper.SetCustomerNumber(entity, sda);
                #endregion
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
            finally
            {
                if (sda != null)
                {
                    sda.closeConnection();
                }
            }
        }
Example #9
0
        /// <summary>
        /// Parses agent related data
        /// </summary>
        private void ParseAgentData(Stream stream)
        {
            using (var reader = CreateReader(stream))
            {
                // 4 bytes: player count
                int playerCount = reader.ReadInt32();

                // 96 bytes: each player
                for (int i = 0; i < playerCount; i++)
                {
                    // 8 bytes: agent
                    ulong agent = reader.ReadUInt64();

                    // 4 bytes: profession
                    uint prof = reader.ReadUInt32();

                    // 4 bytes: is_elite
                    uint isElite = reader.ReadUInt32();

                    // 2 bytes: toughness
                    uint toughness = reader.ReadUInt16();
                    // 2 bytes: healing
                    uint concentration = reader.ReadUInt16();
                    // 2 bytes: healing
                    uint healing = reader.ReadUInt16();
                    // 2 bytes: hitbox width
                    uint hbWidth = (uint)2 * reader.ReadUInt16();
                    // 2 bytes: condition
                    uint condition = reader.ReadUInt16();
                    // 2 bytes: hitbox height
                    uint hbHeight = (uint)2 * reader.ReadUInt16();
                    // 68 bytes: name
                    string name = ParseHelper.GetString(stream, 68, false);
                    //Save
                    string agentProf = GeneralHelper.GetAgentProfString(_logData.BuildVersion, _aPIController, prof, isElite);
                    AgentItem.AgentType type;
                    ushort ID = 0;
                    switch (agentProf)
                    {
                    case "NPC":
                        // NPC
                        try
                        {
                            ID = ushort.Parse(prof.ToString().PadLeft(5, '0'));
                        }
                        catch (FormatException)
                        {
                            ID = 0;
                        }
                        type = AgentItem.AgentType.NPC;
                        break;

                    case "GDG":
                        // Gadget
                        try
                        {
                            ID = ushort.Parse((prof & 0x0000ffff).ToString().PadLeft(5, '0'));
                        }
                        catch (FormatException)
                        {
                            ID = 0;
                        }
                        type = AgentItem.AgentType.Gadget;
                        break;

                    default:
                        // Player
                        type = AgentItem.AgentType.Player;
                        break;
                    }
                    _allAgentsList.Add(new AgentItem(agent, name, agentProf, ID, type, toughness, healing, condition, concentration, hbWidth, hbHeight));
                }
            }
        }
Example #10
0
        public static bool MoveInPlace(bool allowDefiniteMove = false)
        {
            if (!Directory.Exists(STAGING_COMPLETE_FOLDER))
            {
                return(true);
            }

            Log(@"Attempting to MoveInPlace");

            ConfigManagerCompact.LoadConfig();

            try
            {
                foreach (string file in Directory.GetFiles(STAGING_COMPLETE_FOLDER))
                {
                    if (!AuthenticodeTools.IsTrusted(file))
                    {
                        if (Path.GetFileName(file) == @"bass.dll")
                        {
                            //bass.dll has internal checksum verification that causes it to think the file was tampered if we sign it.
                        }
                        else
                        {
                            Log(@"Authenticode signature check failed on {0}!", file);
                            GeneralHelper.FileDelete(file);
                            continue;
                        }
                    }

                    if (new FileInfo(file).Length == 0)
                    {
                        GeneralHelper.FileDelete(file);
                        continue;
                    }

                    string destination = Path.GetFileName(file);

                    if (SafelyMove(file, destination, 200, 5, allowDefiniteMove))
                    {
                        Log(@"{0} => {1}: OK", file, destination);
                        ConfigManagerCompact.Configuration[@"h_" + destination] = getMd5(destination);
                    }
                    else
                    {
                        Log(@"{0} => {1}: FAIL", file, destination);
                        return(false);
                    }
                }
            }
            catch
            {
                return(false);
            }

            Cleanup();

            ConfigManagerCompact.SaveConfig();

            Log(@"MoveInPlace successful!");

            return(true);
        }
Example #11
0
        public override bool TakeAction()
        {
            if (ContextUser.UserStatus == UserStatus.CountryCombat)
            {
                ErrorCode = LanguageManager.GetLang().ErrorCode;
                ErrorInfo = LanguageManager.GetLang().St1902_CountryCombatNotUpEmbattle;
                return(false);
            }

            _userEmbattlePos = new PersonalCacheStruct <UserEmbattle>().FindAll(ContextUser.UserID, m => m.MagicID == magicID);
            Dictionary <int, short> generalPos = GetEmbattle(generalID.Split(','), location.Split(','));
            short rePostion = GeneralHelper.ReplacePostion(ContextUser.UserID, magicID);

            foreach (KeyValuePair <int, short> keyValuePair in generalPos)
            {
                if (keyValuePair.Value == rePostion && keyValuePair.Key == LanguageManager.GetLang().GameUserGeneralID)
                {
                    ErrorCode = LanguageManager.GetLang().ErrorCode;
                    ErrorInfo = LanguageManager.GetLang().St1902_PostionNotGeneral;
                    return(false);
                }
            }

            bool isModify = false;

            foreach (UserEmbattle embattle in _userEmbattlePos)
            {
                int generalId;
                if (TryFindGeneralId(generalPos, embattle.Position, out generalId))
                {
                    // 如果是左右交换
                    if (ops == 0)
                    {
                        foreach (KeyValuePair <int, short> keyValuePair in generalPos)
                        {
                            if (keyValuePair.Value == embattle.Position)
                            {
                                embattle.GeneralID = keyValuePair.Key;
                            }
                        }
                    }
                    else if (ops == 1)
                    {
                        // 佣兵上阵或移除时,对 IsBattle 和 Position 进行更改
                        var userGeneral = new PersonalCacheStruct <UserGeneral>().FindKey(ContextUser.UserID, embattle.GeneralID);
                        if (userGeneral != null)
                        {
                            if (generalId != embattle.GeneralID)
                            {
                                userGeneral.IsBattle = false;
                                userGeneral.Position = 0;
                            }
                        }
                        userGeneral = new PersonalCacheStruct <UserGeneral>().FindKey(ContextUser.UserID, generalId);
                        if (userGeneral != null)
                        {
                            userGeneral.IsBattle = true;
                            userGeneral.Position = embattle.Position;
                        }
                        embattle.GeneralID = generalId;
                    }
                }
                else
                {
                    embattle.GeneralID = 0;
                }
                //embattle.Update();
                isModify = true;
            }
            //var embattlesArray = new PersonalCacheStruct<UserEmbattle>().FindAll(ContextUser.UserID, m => m.GeneralID == LanguageManager.GetLang().GameUserGeneralID && m.MagicID == magicID);
            //if (embattlesArray.Count == 0)
            //{
            //    ErrorCode = LanguageManager.GetLang().ErrorCode;
            //    ErrorInfo = LanguageManager.GetLang().St1902_UserGeneralUnable;
            //    return false;
            //}
            if (UserHelper.IsUserEmbattle(ContextUser.UserID, magicID))
            {
                ErrorCode = LanguageManager.GetLang().ErrorCode;
                ErrorInfo = LanguageManager.GetLang().St4004_EmbattleEmpty;
                return(false);
            }

            if (isModify)
            {
                UserHelper.GetGameUserCombat(Uid);
            }
            return(true);
        }
Example #12
0
        private static UpdateStates doUpdate()
        {
            //ensure we have the correct version of .net available.
            if (ReleaseStream.ToString().Contains(@"40") && !DotNetFramework.CheckInstalled(FrameworkVersion.dotnet4))
            {
                Log(@"Not updating due to missing .NET 4 installation");
                LastError = new MissingFrameworkVersionException(FrameworkVersion.dotnet4);
                return(UpdateStates.Error);
            }

            try
            {
                ConfigManagerCompact.LoadConfig();

                //ensure we are starting clean.
                //note that we don't clear a pending update just yet because there are scenarios we can use this (see variable stagedAndWaitingToUpdate below).
                Cleanup(10000, false);

                List <DownloadableFileInfo> streamFiles = null;

                string rawString = string.Empty;

                try
                {
                    Log(@"Requesting update information...");

                    var sn = new pWebRequest <List <DownloadableFileInfo> >(string.Format(CENTRAL_UPDATE_URL + @"?action=check&stream={0}&time={1}", ReleaseStream.ToString().ToLower(), DateTime.Now.Ticks));
                    sn.BlockingPerform();
                    rawString = sn.ResponseString;

                    if (rawString == @"fallback")
                    {
                        Log(@"Server has requested an emergency fallback!");
                        return(UpdateStates.EmergencyFallback);
                    }

                    streamFiles = sn.ResponseObject;
                }
                catch (Exception e)
                {
                    LastError = e;
                    LastErrorExtraInformation = rawString;

                    Log(LastError.ToString());
                    Log(rawString);
                    return(UpdateStates.Error);
                }

                if (streamFiles == null || streamFiles.Count == 0)
                {
                    LastError = new Exception($@"update file returned no results ({rawString})");
                    Log(LastError.ToString());
                    return(UpdateStates.Error);
                }

tryAgain:
                bool stagedAndWaitingToUpdate = Directory.Exists(STAGING_COMPLETE_FOLDER);
                List <DownloadableFileInfo> updateFiles = new List <DownloadableFileInfo>();

                foreach (DownloadableFileInfo file in streamFiles)
                {
                    if (stagedAndWaitingToUpdate)
                    {
                        Log(@"A pending update is already waiting. Checking what we're working with...");

                        //special case where we already have a pending update.
                        //if we find *any* file which doesn't match, we should remove the folder and restart the process.

                        string pendingFilename = STAGING_COMPLETE_FOLDER + @"/" + file.filename;

                        if (File.Exists(pendingFilename))
                        {
                            Log(file.filename + @": PENDING");
                            //pending file exists and matches this update precisely.
                            if (getMd5(pendingFilename) == file.file_hash)
                            {
                                continue;
                            }
                        }
                        else if (File.Exists(file.filename) && getMd5(file.filename, true) == file.file_hash)
                        {
                            Log(file.filename + @": LATEST");
                            //current version is already newest.
                            continue;
                        }

                        Log(file.filename + @": MISMATCH");

                        //something isn't up-to-date. let's run the update process again without our pending version.
                        Reset(false);

                        goto tryAgain;
                    }

                    if (!File.Exists(file.filename))
                    {
                        updateFiles.Add(file);
                        Log(file.filename + @": NEW");
                    }
                    else if (getMd5(file.filename, true) != file.file_hash)
                    {
                        Log(file.filename + @": CHANGED (cached)");
                        updateFiles.Add(file);                                                                     //cached md5 check failed.
                    }
                    else if (file.filename == @"osu!.exe" && getMd5(file.filename, true) != getMd5(file.filename)) //special intensive check for main osu!.exe
                    {
                        Log(file.filename + @": CHANGED");
                        ConfigManagerCompact.ResetHashes();
                        goto tryAgain;
                    }
                }

                if (stagedAndWaitingToUpdate)
                {
                    Log(@"Pending updating is waiting and requires no further changes.");
                    //return early, as we've already done the rest of the process below in a previous run.
                    return(MoveInPlace() ? UpdateStates.Completed : UpdateStates.NeedsRestart);
                }

                if (updateFiles.Count == 0)
                {
                    Log(@"No changes to apply!");

                    if (!DotNetFramework.CheckInstalled(FrameworkVersion.dotnet4))
                    {
                        Log(@"Becuase we had no changes, let's let the user know they need a newer framework in the future");

                        //if there are no pending updates but the user doesn't have dotnet4 available, we should tell them to get it.
                        LastError = new MissingFrameworkVersionException(FrameworkVersion.dotnet4);
                        return(UpdateStates.Error);
                    }

                    return(UpdateStates.NoUpdate);
                }

                totalUpdatableFiles = updateFiles.Count;

                if (!Directory.Exists(STAGING_FOLDER))
                {
                    Log(@"Creating staging folder");
                    DirectoryInfo di = Directory.CreateDirectory(STAGING_FOLDER);
                    di.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
                }

                setCallbackStatus(UpdateStates.Updating);

                lock (ActiveFiles) ActiveFiles.AddRange(updateFiles);

                foreach (DownloadableFileInfo f in updateFiles)
                {
                    DownloadableFileInfo file = f;

                    Log(@"Processing {0}...", file.ToString());

                    if (File.Exists(file.filename))
                    {
                        Log(@"Exists locally; checking for patchability...");
                        string localHash = getMd5(file.filename);

                        //check for patchability...
                        try
                        {
                            var sn = new pWebRequest <List <DownloadableFileInfo> >(@"{0}?action=path&stream={1}&target={2}&existing={3}&time={4}",
                                                                                    CENTRAL_UPDATE_URL,
                                                                                    ReleaseStream.ToString().ToLower(),
                                                                                    file.file_version,
                                                                                    localHash,
                                                                                    DateTime.Now.Ticks);

                            sn.BlockingPerform();

                            List <DownloadableFileInfo> patchFiles = sn.ResponseObject;

                            if (patchFiles.Count > 1)
                            {
                                Log(@"Server returned {0} patch files", patchFiles.Count.ToString());
                                //copy the local version to the staging path.

                                File.Copy(file.filename, STAGING_FOLDER + @"/" + file.filename);

                                bool success = false;

                                lock (ActiveFiles)
                                    ActiveFiles.AddRange(patchFiles.GetRange(0, patchFiles.Count - 1));
                                totalUpdatableFiles += patchFiles.Count - 1;

                                try
                                {
                                    //we now know we have a patchable path, so let's try patching!
                                    foreach (DownloadableFileInfo patch in patchFiles)
                                    {
                                        try
                                        {
                                            if (patch.file_version == file.file_version)
                                            {
                                                Log(@"Reached end of patch chain ({0} / {1}), checking file checksum...",
                                                    patch.file_version.ToString(), patch.file_hash);

                                                //reached the end of patching.
                                                if (getMd5(STAGING_FOLDER + @"/" + file.filename) != file.file_hash)
                                                {
                                                    Log(@"Patching FAILED!");
                                                    throw new Exception(@"patching failed to end with correct checksum.");
                                                }

                                                Log(@"Patching success!");
                                                success = true;
                                                break; //patching successful!
                                            }

                                            string localPatchFilename = STAGING_FOLDER + @"/" + patch.filename + @"_patch";

                                            Log(@"Applying patch {0} (to {1})...", patch.file_version.ToString(), patch.file_hash);
                                            patch.Perform(true);
                                        }
                                        finally
                                        {
                                            lock (ActiveFiles) ActiveFiles.Remove(patch);
                                        }
                                    }

                                    if (success)
                                    {
                                        lock (ActiveFiles) ActiveFiles.Remove(file);
                                        continue;
                                    }
                                }
                                finally
                                {
                                    lock (ActiveFiles)
                                        patchFiles.ForEach(pf => ActiveFiles.Remove(pf));
                                }
                            }

                            Log(@"No patches available; falling back to full download");
                        }
                        catch (Exception e)
                        {
                            Log(@"Error occured during patching: " + e);
                            //an error occurred when trying to patch; fallback to a full update.
                        }
                    }

                    Log(@"Beginning download of {0} ({1})...", file.filename, file.url_full);
                    file.PerformThreaded(delegate
                    {
                        lock (ActiveFiles) ActiveFiles.Remove(file);
                        Log(@"Completed download of {0} ({1} files remain)!", file.filename, ActiveFiles.Count);
                    },
                                         delegate
                    {
                        Log(@"Failed download of {0}! Error: {1}", file.filename, file.Error);
                        //error occurred
                    });
                }

                while (ActiveFiles.Count > 0)
                {
                    foreach (DownloadableFileInfo dfi in ActiveFiles)
                    {
                        if (dfi.Error != null)
                        {
                            LastError = dfi.Error;
                            return(UpdateStates.Error);
                        }
                    }
                    Thread.Sleep(100);
                }

                if (State == UpdateStates.Updating)
                {
                    if (Directory.Exists(STAGING_COMPLETE_FOLDER))
                    {
                        Directory.Delete(STAGING_COMPLETE_FOLDER, true);
                    }

                    GeneralHelper.RecursiveMove(STAGING_FOLDER, STAGING_COMPLETE_FOLDER);

                    ConfigManagerCompact.Configuration[@"_ReleaseStream"] = ReleaseStream.ToString();

                    return(MoveInPlace() ? UpdateStates.Completed : UpdateStates.NeedsRestart);
                }

                return(UpdateStates.NoUpdate);
            }
            catch (ThreadAbortException)
            {
                Log(@"Thread was aborted!");
                foreach (DownloadableFileInfo dfi in ActiveFiles)
                {
                    dfi.Abort();
                }
                return(UpdateStates.NoUpdate);
            }
            catch (Exception e)
            {
                Log(@"Error: " + e.ToString());
                LastError = e;
                return(UpdateStates.Error);
            }
            finally
            {
                Log(@"Saving out global config");
                ConfigManagerCompact.SaveConfig();
                updateThread = null;
            }
        }
Example #13
0
        private SyndicationItem GetSyndicationItem(Store store, Product product, ProductCategory productCategory, int description, int isDetailLink)
        {
            if (productCategory == null)
            {
                return(null);
            }

            if (description == 0)
            {
                description = 300;
            }

            var    productDetailLink = LinkHelper.GetProductLink(product, productCategory.Name);
            String detailPage        = String.Format("http://{0}{1}", store.Domain.ToLower(), productDetailLink);

            if (isDetailLink == 1)
            {
                detailPage = String.Format("http://{0}{1}", store.Domain.ToLower(), "/products/productbuy/" + product.Id);
            }
            string desc = "";

            if (description > 0)
            {
                desc = GeneralHelper.GetDescription(product.Description, description);
            }
            var uri = new Uri(detailPage);
            var si  = new SyndicationItem(product.Name, desc, uri);

            if (product.UpdatedDate != null)
            {
                si.PublishDate = product.UpdatedDate.Value.ToUniversalTime();
            }


            if (!String.IsNullOrEmpty(productCategory.Name))
            {
                si.ElementExtensions.Add("products:category", String.Empty, productCategory.Name);
            }
            si.ElementExtensions.Add("guid", String.Empty, uri);



            if (product.ProductFiles.Any())
            {
                List <BaseFileEntity> baseFileEntities = product.ProductFiles != null && product.ProductFiles.Any() ? product.ProductFiles.Cast <BaseFileEntity>().ToList() : new List <BaseFileEntity>();
                var imageLiquid = new ImageLiquid(baseFileEntities, this.ImageWidth, this.ImageHeight);
                imageLiquid.ImageState = true;
                String imageSrcHtml = String.Format("http://{0}{1}", store.Domain.ToLower(), imageLiquid.SmallImageSource);
                try
                {
                    SyndicationLink imageLink =
                        SyndicationLink.CreateMediaEnclosureLink(new Uri(imageSrcHtml), "image/jpeg", 100);
                    si.Links.Add(imageLink);
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "GetSyndicationItem");
                }
            }

            return(si);
        }
Example #14
0
        internal static pTexture Load(string name, SkinSource source = SkinSource.All, TextureAtlas atlas = null)
        {
            if (name == null)
            {
                return(null);
            }

            if (SkinManager.IgnoreBeatmapSkin && source != SkinSource.Beatmap)
            {
                source &= ~SkinSource.Beatmap;
            }

            if (source == SkinSource.All)
            {
                switch (GameBase.Mode)
                {
                case OsuModes.Play:
                case OsuModes.Edit:
                    break;

                default:
                    //As a default, don't load from the beatmap unless we are in play or edit mode.
                    source &= ~SkinSource.Beatmap;
                    break;
                }
            }

            pTexture tex = null;

            Dictionary <string, pTexture> dic = null;

            if (!LookupCache.TryGetValue(source, out dic))
            {
                dic = LookupCache[source] = new Dictionary <string, pTexture>();
            }

            if (dic.TryGetValue(name, out tex))
            {
                return(tex);
            }

            try
            {
                //Check for beatmap-specific sprite availability
                Beatmap current = null;
                if ((source & SkinSource.Beatmap) > 0 && (current = BeatmapManager.Current) != null)
                {
                    if (BeatmapSpriteCache.TryGetValue(name, out tex))
                    {
                        //Cached sprite is available.
                        //Note that we must check null *inside* this if block because a cached null means this source has no available file.
                        //If we find a null, we don't want to enter the else block and check for a file every time, so we quietly ignore this source here.
                        if (tex != null)
                        {
                            return(tex);
                        }
                    }
                    else
                    {
                        string filename = name.IndexOf('.') < 0 ? name + @".png" : name;
                        using (Stream stream = current.GetFileStream(filename))
                        {
                            if (stream != null)
                            {
                                tex = pTexture.FromStream(stream, atlas);
                                if (tex != null)
                                {
                                    tex.Filename  = filename;
                                    tex.AssetName = name;
                                    tex.Source    = SkinSource.Beatmap;
                                    tex.UploadNextFrame();
                                }

                                BeatmapSpriteCache[name] = tex;

                                if (atlas != null)
                                {
                                    BeatmapTextureAtlases.Add(atlas);
                                }

                                return(tex);
                            }
                        }

                        BeatmapSpriteCache[name] = null;
                    }
                }

                if ((source & SkinSource.Skin) > 0 && !SkinManager.IsDefault)
                {
                    if (SkinSpriteCache.TryGetValue(name, out tex))
                    {
                        //Cached sprite is available.
                        //Note that we must check null *inside* this if block because a cached null means this source has no available file.
                        //If we find a null, we don't want to enter the else block and check for a file every time, so we quietly ignore this source here.
                        if (tex != null)
                        {
                            return(tex);
                        }
                    }
                    else
                    {
                        string filename = Path.Combine(SkinManager.Current.FullPath, name.IndexOf('.') < 0 ? name + @".png" : name);

                        string filename2x = filename.Insert(filename.LastIndexOf('.'), @"@2x");
                        if (GameBase.UseHighResolutionSprites && File.Exists(filename2x))
                        {
                            tex = pTexture.FromFile(filename2x, atlas);
                            SkinSpriteCache[name] = tex;

                            if (atlas != null)
                            {
                                SkinTextureAtlases.Add(atlas);
                            }

                            if (tex != null)
                            {
                                tex.DpiScale  = 2;
                                tex.Source    = SkinSource.Skin;
                                tex.AssetName = name;
                                tex.UploadNextFrame();
                            }
                            return(tex);
                        }

                        if (File.Exists(filename))
                        {
                            tex = pTexture.FromFile(filename, atlas);
                            SkinSpriteCache[name] = tex;

                            if (atlas != null)
                            {
                                SkinTextureAtlases.Add(atlas);
                            }

                            if (tex != null)
                            {
                                tex.Source    = SkinSource.Skin;
                                tex.AssetName = name;
                                tex.UploadNextFrame();
                            }
                            return(tex);
                        }

                        SkinSpriteCache[name] = null;
                    }
                }

                if ((source & SkinSource.Osu) == 0)
                {
                    return(null);
                }

                try
                {
                    if (DefaultSpriteCache.TryGetValue(name, out tex))
                    {
                        return(tex);
                    }

#if LOAD_LOCAL
                    if ((tex = Load(name, SkinSource.Skin)) != null)
                    {
                        return(tex);
                    }
#endif

                    name = GeneralHelper.PathSanitise(name);
                    tex  = name.IndexOf(Path.DirectorySeparatorChar) > 0 ? pTexture.FromFile(name, atlas) : pTexture.FromResourceStore(GeneralHelper.StripExtension(name), atlas);

                    DefaultSpriteCache[name] = tex;

                    if (atlas != null)
                    {
                        DefaultTextureAtlases.Add(atlas);
                    }

                    if (tex != null)
                    {
                        tex.Source    = SkinSource.Osu;
                        tex.AssetName = name;
                        tex.UploadNextFrame();
                    }
                    return(tex);
                }
                catch
                {
                    return(null);
                }
            }
            finally
            {
                dic[name] = tex;
            }
        }
Example #15
0
 /// <summary>
 /// Toggles the quick launch features.
 /// </summary>
 /// <param name="setting">Whether or not quick launch options should be enabled.</param>
 public void ToggleQuickLaunch(bool setting)
 {
     GeneralHelper.ToggleQuickLaunch(setting);
 }
Example #16
0
        private static void Main(string[] args)
        {
            Ts(); return;

            var mdsClient = new MDSClient("ET");

            mdsClient.Connect();

            bool isAuto    = false;
            int  autoCount = 100;

            Console.WriteLine("输入(auto),自动执行100次");
            isAuto = Console.ReadLine() == "auto";

            while (true)
            {
                if (!isAuto)
                {
                    string str = Console.ReadLine();
                    if (str == "end")
                    {
                        break;
                    }
                }
                else
                {
                    if (autoCount-- <= 0)
                    {
                        break;
                    }
                }

                Task[] ts = new Task[100];
                for (int i = 0; i < 100; i++)
                {
                    ts[i] = new Task(() =>
                    {
                        Random ran = new Random();
                        int number = ran.Next(0, 10);

                        var message = mdsClient.CreateMessage();
                        message.DestinationApplicationName = "DataCalc";
                        message.MessageData = GeneralHelper.SerializeObject(new RequestDataCalcMessage()
                        {
                            StructId = number,
                            DateTime = DateTime.Now
                        });

                        message.TransmitRule = MDS.Communication.Messages.MessageTransmitRules.NonPersistent;
                        message.Send();
                        Console.WriteLine("发送消息:结构物编号{0},采集时间:{1}", number, DateTime.Now);
                    });
                }

                foreach (Task task in ts)
                {
                    task.Start();
                }

                Thread.Sleep(200);
            }

            mdsClient.Disconnect();
            Console.ReadLine();
        }
Example #17
0
        public void Execute(IServiceProvider serviceProvider)
        {
            SqlDataAccess sda = null;

            try
            {
                sda = new SqlDataAccess();
                sda.openConnection(Globals.ConnectionString);

                #region | SERVICE |
                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

                #region | Validate Request |
                //Target yoksa veya Entity tipinde değilse, devam etme.
                if (!context.InputParameters.Contains("Target") || !(context.InputParameters["Target"] is Entity))
                {
                    return;
                }
                #endregion

                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                #endregion

                Entity entity = (Entity)context.InputParameters["Target"];

                #region | VARIABLES |
                List <ScoreLimit> lstLimits = new List <ScoreLimit>();

                EntityReference portal = null;
                EntityReference user   = null;

                if (entity.Contains("new_portalid") && entity["new_portalid"] != null)
                {
                    portal = (EntityReference)entity["new_portalid"];
                }

                if (entity.Contains("new_userid") && entity["new_userid"] != null)
                {
                    user = (EntityReference)entity["new_userid"];
                }
                #endregion

                MsCrmResultObject limitRes = ScoreHelper.GetScoreLimitsByType(ScoreType.PostComment, sda);

                if (limitRes.Success)
                {
                    lstLimits = (List <ScoreLimit>)limitRes.ReturnObject;

                    for (int i = 0; i < lstLimits.Count; i++)
                    {
                        int      recCount = 0;
                        DateTime start    = GeneralHelper.GetStartDateByScorePeriod(lstLimits[i].Period);
                        DateTime end      = GeneralHelper.GetEndDateByScorePeriod(lstLimits[i].Period);

                        recCount = CommentHelper.GetUserCommentCount(portal.Id, user.Id, start, end, sda);

                        if (lstLimits[i].Frequency >= recCount)
                        {
                            Score sc = new Score()
                            {
                                Point     = lstLimits[i].Point,
                                Portal    = portal,
                                User      = user,
                                ScoreType = ScoreType.PostComment
                            };

                            MsCrmResult scoreRes = ScoreHelper.CreateScore(sc, service);

                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //LOG
                throw new InvalidPluginExecutionException(ex.Message);
            }
            finally
            {
                if (sda != null)
                {
                    sda.closeConnection();
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        protected void PerformCalculation(object[] parametersArray, int beginIdxPosition, int actualStartingIndex)
        {
            // This is how the normal call looks like:
            //    TicTacTec.TA.Library.Core.Adx((int)parameters[0], (int)parameters[1], (double[])parameters[2],
            //    (double[])parameters[3], (double[])parameters[4], (int)parameters[5],
            //    out outBeginIdx, out outNBElemenet, (double[])parameters[8]);

            TicTacTec.TA.Library.Core.RetCode code = (TicTacTec.TA.Library.Core.RetCode)
                                                     _methodInfo.Invoke(null, parametersArray);

            int outBeginIdx  = (int)parametersArray[beginIdxPosition];
            int outNBElement = (int)parametersArray[beginIdxPosition + 1];

            lock (this)
            {
                for (int i = 0; outNBElement > 0 && i < _outputArraysParameters.Count; i++)
                {
                    int index = beginIdxPosition + 2 + i;
                    if (parametersArray[index].GetType() == typeof(double[]))
                    {// Double output.
                        Results.AddSetValues(_outputArraysParameters[i].Name, actualStartingIndex + outBeginIdx, outNBElement, true, (double[])parametersArray[index]);
                    }
                    else if (parametersArray[index].GetType() == typeof(int[]))
                    {// Int output.
                        Results.AddSetValues(_outputArraysParameters[i].Name, actualStartingIndex + outBeginIdx, outNBElement, true, GeneralHelper.IntsToDoubles((int[])parametersArray[index]));
                    }
                }
            }
        }
Example #19
0
 private void button1_Click(object sender, EventArgs e)
 {
     GeneralHelper.ProcessStart("http://osu.ppy.sh/forum/viewtopic.php?f=5&t=576");
 }
Example #20
0
        public ActionResult Read(string userName) //periodic check for new messages
        {
            var newMessages = GeneralHelper.TakeNewMessages(userName);

            return(Json(newMessages));
        }
Example #21
0
 private void btnExcel_Click(object sender, EventArgs e)
 {
     GeneralHelper.ExportExcel(dgvDuLieu);
 }
        public IHttpActionResult GetCurrentUser()
        {
            //Get the user information from AD
            var userDto = User.GetUserBySamAccountName(User.GetUsernameWithoutDomain());

            //Does the user exist in the clinical guidance app?
            var clinicalUser = _db.Users
                               .Include(x => x.Department)
                               .Include(x => x.AdministationDepartments)
                               .SingleOrDefault(x => x.UserName == userDto.SamAccountName);

            if (clinicalUser == null)
            {
                //create new
                var user = new User
                {
                    _id             = Guid.NewGuid(),
                    UserName        = userDto.SamAccountName,
                    Forename        = userDto.Forename,
                    Surname         = userDto.Surname,
                    JobTitle        = userDto.JobTitle,
                    PhoneNumber     = userDto.PhoneNumber,
                    EmailAddress    = userDto.EmailAddress,
                    SiteAdmin       = userDto.SiteAdmin,
                    LeadClinician   = userDto.LeadClinician,
                    ContentApprover = userDto.ContentApprover,
                    ContentEditor   = userDto.ContentEditor,
                    Contact         = userDto.Contact
                };

                _db.Logs.Add(
                    _logHelper.CreateUserApiControllerLog(
                        LogHelper.LogType.Create,
                        "UserApiController.GetCurrentUser",
                        "api/user/get/current",
                        user,
                        User.GetUsernameWithoutDomain()
                        )
                    );

                _db.Users.Add(user);
                _db.SaveChanges();

                userDto.Id = user.Id;
            }
            else
            {
                //overwrite dto with app information
                userDto.Id              = clinicalUser.Id;
                userDto._id             = clinicalUser._id;
                userDto.DisplayName     = clinicalUser.Surname + " " + clinicalUser.Forename + ", " + clinicalUser.JobTitle;
                userDto.Forename        = clinicalUser.Forename;
                userDto.Surname         = clinicalUser.Surname;
                userDto.JobTitle        = clinicalUser.JobTitle;
                userDto.PhoneNumber     = clinicalUser.PhoneNumber;
                userDto.EmailAddress    = clinicalUser.EmailAddress;
                userDto.SiteAdmin       = clinicalUser.SiteAdmin;
                userDto.LeadClinician   = clinicalUser.LeadClinician;
                userDto.ContentApprover = clinicalUser.ContentApprover;
                userDto.ContentEditor   = clinicalUser.ContentEditor;
                userDto.Contact         = clinicalUser.Contact;
                userDto.DepartmentId    = clinicalUser.DepartmentId;
                userDto.DepartmentName  = (clinicalUser.Department != null) ? clinicalUser.Department.Name : "";

                var administrationDepartments = clinicalUser
                                                .AdministationDepartments
                                                .Select(clinicalUserAdministrationDepartment => new DepartmentDto()
                {
                    Id = clinicalUserAdministrationDepartment.Id
                }
                                                        )
                                                .ToList();

                userDto.AdministationDepartments = administrationDepartments;
            }

            userDto.CurrentServer = GeneralHelper.GetCurrentHostServer();

            return(Ok(userDto));
        }
 /// <summary>
 /// Will perform managed invoke if needed, or a direct one if not.
 /// </summary>
 public static void DirectOrManagedInvoke(Control invocationControl, GeneralHelper.DefaultDelegate d)
 {
     if (invocationControl.InvokeRequired)
     {
         BeginManagedInvoke(invocationControl, d);
     }
     else
     {
         d.Invoke();
     }
 }
        // >>
        public void OrderOpened(string symbol, int operationID, int orderTicket, decimal openingPrice,
                                int orderOpenTime, bool operationResult, string operationResultMessage)
        {
            TracerHelper.Trace(symbol);

            try
            {
                OperationInformation operation = base.GetOperationById(operationID);

                DateTime?time = GeneralHelper.GenerateDateTimeSecondsFrom1970(orderOpenTime);
                if (time.HasValue == false)
                {
                    if (operation != null)
                    {
                        base.CompleteOperation(operationID, new ResponseMessage(false, "Failed to convert time for order."));
                    }

                    SystemMonitor.Error("Failed to convert time for order.");
                    return;
                }

                string orderId = orderTicket.ToString();
                if (orderTicket < 0)
                {// The system needs orderId empty to recognize the result as failure.
                    orderId         = string.Empty;
                    operationResult = false;
                }

                if (operation != null)
                {
                    ResponseMessage message = null;

                    lock (this)
                    {
                        if (operation.Request is SubmitOrderMessage)
                        {
                            message = new SubmitOrderResponseMessage(_accountInfo, orderId, true);
                            message.OperationResultMessage = operationResultMessage;
                            message.OperationResult        = operationResult;
                        }
                        else if (operation.Request is ExecuteMarketOrderMessage)
                        {
                            OrderInfo info = new OrderInfo(orderId, CreateSymbol(symbol), OrderTypeEnum.UNKNOWN, OrderStateEnum.Executed, int.MinValue);
                            info.OpenTime  = time;
                            info.OpenPrice = openingPrice;

                            message = new ExecuteMarketOrderResponseMessage(_accountInfo, info, operationResult);
                            message.OperationResultMessage = operationResultMessage;
                        }
                        else
                        {
                            SystemMonitor.Error("Failed to establish placed order request type.");
                            message = new ResponseMessage(false);
                        }
                    }

                    base.CompleteOperation(operationID, message);
                }

                if (string.IsNullOrEmpty(orderId) == false)
                {
                    // Do an update of this order.
                    lock (this)
                    {
                        _pendingOrdersInformations.Add(orderId);
                    }
                }
            }
            catch (Exception ex)
            {// Make sure we handle any possible unexpected exceptions, as otherwise
                // they bring the entire package (MT4 included) down with a bad error.
                SystemMonitor.Error(ex.Message);
            }
        }
 /// <summary>
 /// Helper.
 /// </summary>
 /// <param name="assurePending">Makes sure at least one call is still pending on the call.</param>
 public static bool BeginFilteredManagedInvoke(Control control, GeneralHelper.DefaultDelegate d)
 {
     return BeginFilteredManagedInvoke(control, TimeSpan.FromMilliseconds(250), (Delegate)d);
 }
        // >>
        public void OrderInformation(int orderTicket, int operationID, string orderSymbol, int orderType, decimal volume,
                                     decimal inputOpenPrice, decimal inputClosePrice, decimal inputOrderStopLoss, decimal inputOrderTakeProfit,
                                     decimal currentProfit, decimal orderSwap, int inputOrderPlatformOpenTime,
                                     int inputOrderPlatformCloseTime, int inputOrderExpiration, decimal orderCommission,
                                     string orderComment, int orderCustomID, bool operationResult, string operationResultMessage)
        {
            TracerHelper.TraceEntry(string.Format("ticketId[{0}], customId[{1}], operationId[{2}], symbol[{3}], SL[{4}, TP[{5}]", orderTicket.ToString(),
                                                  orderCustomID.ToString(), operationID.ToString(), orderSymbol, inputOrderStopLoss.ToString(), inputOrderTakeProfit.ToString()));

            try
            {
                #region Preprocess Data

                decimal?openPrice              = Convert(inputOpenPrice);
                decimal?closePrice             = Convert(inputClosePrice);
                decimal?orderStopLoss          = Convert(inputOrderStopLoss);
                decimal?orderTakeProfit        = Convert(inputOrderTakeProfit);
                int?    orderPlatformOpenTime  = Convert(inputOrderPlatformOpenTime);
                int?    orderPlatformCloseTime = Convert(inputOrderPlatformCloseTime);
                int?    orderExpiration        = Convert(inputOrderExpiration);

                // Perform dataDelivery fixes to convert to proper cases.
                bool isOpen = orderPlatformCloseTime.HasValue == false || orderPlatformCloseTime == 0;

                OrderStateEnum orderState = OrderStateEnum.Unknown;
                // According to documentataion this is the way to establish if order is closed, see here : http://docs.mql4.com/trading/OrderSelect
                if (isOpen)
                {
                    if (CommonFinancial.OrderInfo.TypeIsDelayed((OrderTypeEnum)orderType) == false &&
                        orderPlatformOpenTime > 0)
                    {
                        orderState = OrderStateEnum.Executed;
                    }
                    else
                    {
                        orderState = OrderStateEnum.Submitted;
                    }
                }
                else
                {
                    orderState = OrderStateEnum.Closed;
                }

                if (orderState == OrderStateEnum.Executed)
                {// Since the integration might report close price for opened orders, at the current closing price.
                    closePrice = null;
                }

                DateTime?openTime       = GeneralHelper.GenerateDateTimeSecondsFrom1970(orderPlatformOpenTime);
                DateTime?closeTime      = GeneralHelper.GenerateDateTimeSecondsFrom1970(orderPlatformCloseTime);
                DateTime?expirationTime = GeneralHelper.GenerateDateTimeSecondsFrom1970(orderExpiration);

                CombinedDataSubscriptionInformation sessionSubscriptionInfo = GetDataSession(orderSymbol);

                if (sessionSubscriptionInfo == null)
                {
                    SystemMonitor.Error("Corresponding symbol [" + orderSymbol + "] session info not found.");
                    return;
                }

                #endregion

                bool      isNewlyAcquired  = false;
                OrderInfo?orderInformation = null;

                if (orderTicket > -1)
                {// Store call information for later use.
                    orderInformation = new OrderInfo(
                        orderTicket.ToString(), sessionSubscriptionInfo.SessionInformation.Info.Symbol, ConvertOrderType(orderType), orderState,
                        ConvertVolume(sessionSubscriptionInfo.SessionInformation.Info.LotSize, volume), openPrice, closePrice,
                        orderStopLoss, orderTakeProfit, currentProfit,
                        orderSwap, openTime, closeTime, openTime,
                        expirationTime, orderCommission, orderComment, orderCustomID.ToString());

                    lock (this)
                    {
                        isNewlyAcquired = _orders.ContainsKey(orderTicket.ToString()) == false || _orders[orderTicket.ToString()].HasValue == false;
                        _orders[orderTicket.ToString()] = orderInformation;
                    }

                    TracerHelper.TraceEntry(string.Format("Storing information, id[{0}], symb[{1}], customId[{2}], operationId[{3}].", orderTicket.ToString(), orderSymbol, orderCustomID.ToString(), operationID));
                }
                else
                {// This used to be flush call (send all stored to user), but currently not used.
                    SystemMonitor.NotImplementedError("Case not implemented.");
                }

                //if (isNewlyAcquired)
                {// Send a notification to subscribers, an order orderInfo was acquired.
                    OrdersInformationUpdateResponseMessage message = new OrdersInformationUpdateResponseMessage(_accountInfo,
                                                                                                                new OrderInfo[] { orderInformation.Value }, true);

                    SendToSubscribers(message);
                }
            }
            catch (Exception ex)
            {// Make sure we handle any possible unexpected exceptions, as otherwise they bring the
                // entire package (MT4 included) down with a bad error.
                SystemMonitor.Error(ex.Message);
            }
        }
 /// <summary>
 /// 
 /// </summary>
 public bool Invoke(GeneralHelper.DefaultDelegate delegateInstance, out object result, TimeSpan timeOut)
 {
     return Invoke((Delegate)delegateInstance, timeOut, out result);
 }
Example #28
0
        public static DataBar[] GenerateTestSeries(int length)
        {
            DataBar[] result = new DataBar[length];
            for (int i = 0; i < result.Length; i++)
            {
                if (i == 0)
                {
                    result[i] = new DataBar(DateTime.Now, GeneralHelper.Random(50), GeneralHelper.Random(50), GeneralHelper.Random(50), GeneralHelper.Random(50), 10);
                }
                else
                {
                    decimal open  = result[i - 1].Close + GeneralHelper.Random(-2, 3);
                    decimal close = open + GeneralHelper.Random(-30, 31);
                    result[i] = new DataBar(result[i - 1].DateTime + TimeSpan.FromSeconds(1), open, Math.Max(open, close) + GeneralHelper.Random(10), Math.Min(open, close) - GeneralHelper.Random(15), close, 10);
                }
            }

            return(result);
        }
 /// <summary>
 /// Helper, to allow the usage of anonymous delegates.
 /// </summary>
 /// <param name="delegateInstance"></param>
 /// <param name="parameters"></param>
 public void BeginInvoke(GeneralHelper.DefaultDelegate delegateInstance)
 {
     BeginInvoke((Delegate)delegateInstance);
 }
Example #30
0
        private static bool handleNewFiles()
        {
            //todo: this method is going to become horribly inefficient with a lot of osz2 files being stored in this directory.

            //BeatmapManager.SongWatcher.EnableRaisingEvents = false;

            bool foundNew = false;

            string songsDir = BeatmapManager.SongsDirectory;

            //todo: could cache the number of files present now
            foreach (string f in Directory.GetFiles(BeatmapManager.SongsDirectory))
            {
                FileType ext = GeneralHelper.GetFileType(f);

                switch (ext)
                {
                case FileType.Database:
                    //Handle thumbs.db files
                    GeneralHelper.FileDelete(f);
                    break;

                case FileType.AudioTrack:
                case FileType.Beatmap:
                {
                    string filename = Path.GetFileName(f);

                    if (status != null)
                    {
                        status.SetStatus(string.Format(LocalisationManager.GetString(OsuString.BeatmapImport_Importing), (filename.Length > 50 ? filename.Remove(50) + @"..." : filename)));
                    }

                    BeatmapManager.SongWatcher.EnableRaisingEvents = false;

                    try
                    {
                        //name of .osu or .mp3 is used to identify containing folder
                        string newFolder = Path.Combine(songsDir, Path.GetFileNameWithoutExtension(f));
                        if (!Directory.Exists(newFolder))
                        {
                            Directory.CreateDirectory(newFolder);
                            BeatmapManager.ChangedFolders.Add(newFolder);
                            BeatmapManager.FolderFileCount++;
                        }

                        newFolder = Path.Combine(newFolder, filename);
                        if (!GeneralHelper.FileMove(f, newFolder, true))
                        {
                            try
                            {
                                File.Copy(f, newFolder);
                            }
                            catch
                            {
                                NotificationManager.ShowMessage(string.Format(LocalisationManager.GetString(OsuString.BeatmapImport_FileInUse), filename));
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        handleCorruptFile(e, f);
                    }

                    BeatmapManager.SongWatcher.EnableRaisingEvents = true;
                    foundNew = true;
                }
                break;

                case FileType.Zip:
                case FileType.BeatmapPackage:
                {
                    //todo: instant osz2 conversion maybe?

                    string filename      = Path.GetFileName(f);
                    string filenameNoExt = Path.GetFileNameWithoutExtension(f).Replace(@"-novid", string.Empty);

                    //Remove invalid characters
                    filenameNoExt = GeneralHelper.WindowsPathStrip(filenameNoExt);

                    if (status != null)
                    {
                        status.SetStatus(string.Format(LocalisationManager.GetString(OsuString.BeatmapImport_Importing), (filename.Length > 50 ? filename.Remove(50) + @"..." : filename)));
                    }

                    short difficultyCharSpace = 36;         //Most difficulty names with brackets + extension will fall within this value
                    int   allowedPathLength   = GeneralHelper.MAX_PATH_LENGTH - difficultyCharSpace;

                    string tempFolder = GeneralHelper.GetTempPath(@"_beatmaps");

                    GeneralHelper.FileDelete(tempFolder);

                    List <string> failedFiles       = new List <string>();
                    List <string> failedDirectories = new List <string>();

                    try
                    {
                        FastZipEvents zipEvents = new FastZipEvents();

                        zipEvents.DirectoryFailure += (events, args) =>
                        {
                            if (args == null)
                            {
                                return;
                            }

                            failedDirectories.Add(Path.GetDirectoryName(args.Name));
                        };

                        zipEvents.FileFailure += (events, args) =>
                        {
                            if (args == null)
                            {
                                return;
                            }

                            failedFiles.Add(Path.GetFileName(args.Name));
                        };

                        FastZip fz = new FastZip(zipEvents);

                        fz.ExtractZip(f, tempFolder, @".*");

                        int failedCount = failedFiles.Count + failedDirectories.Count;

                        if (failedCount > 0)
                        {
                            handleExtractFailure(failedFiles, failedDirectories);
                            bool validBeatmap = checkRequiredFiles(tempFolder);

                            if (!validBeatmap)
                            {
                                throw new Exception("Beatmap missing required files");
                            }
                        }

                        int songsDirLength   = Path.GetFullPath(songsDir).Length;
                        int highestDirLength = filenameNoExt.Length;
                        if (songsDirLength + (filenameNoExt.Length * 2) >= allowedPathLength)
                        {
                            highestDirLength = (GeneralHelper.GetMaxPathLength(tempFolder) - tempFolder.Length);
                        }

                        int charsOver = songsDirLength + filenameNoExt.Length + highestDirLength - GeneralHelper.MAX_PATH_LENGTH;

                        if (charsOver > 0)
                        {
                            if (charsOver < filenameNoExt.Length - 1)
                            {
                                filenameNoExt = filenameNoExt.Remove(filenameNoExt.Length - charsOver);
                            }
                            else
                            {
                                throw new PathTooLongException();
                            }
                        }

                        //Force removal of readonly flag.
                        FileInfo myFile = new FileInfo(f);
                        if ((myFile.Attributes & FileAttributes.ReadOnly) > 0)
                        {
                            myFile.Attributes &= ~FileAttributes.ReadOnly;
                        }

                        string dir = Path.Combine(songsDir, filenameNoExt);

                        GeneralHelper.RecursiveMove(tempFolder, dir);
                        BeatmapManager.FolderFileCount++;
                        if (!BeatmapManager.ChangedFolders.Contains(dir))
                        {
                            BeatmapManager.ChangedFolders.Add(dir);
                        }

                        GeneralHelper.FileDelete(f);
                    }
                    catch (Exception e)
                    {
                        if (!(e is PathTooLongException))
                        {
                            int failedCount = failedFiles.Count + failedDirectories.Count;

                            if (failedCount > 0)
                            {
                                handleExtractFailure(failedFiles, failedDirectories);
                            }
                        }

                        handleCorruptFile(e, f);

                        try
                        {
                            Directory.Delete(tempFolder, true);
                        }
                        catch { }
                    }

                    foundNew = true;
                    break;
                }
                }
            }

            return(foundNew);
        }