示例#1
1
文件: HUD.cs 项目: Phelisse/Elynium
     void Start ()
    {
        player = transform.root.GetComponent<Player>();
        SetCursorState(CursorState.Default);

        resourceValues = new Dictionary<ResourceType, int>();
        resourceLimits = new Dictionary<ResourceType, int>();

        resourceValues.Add(ResourceType.Gold, 0);
        resourceLimits.Add(ResourceType.Gold, 0);
        resourceValues.Add(ResourceType.Nelther, 0);
        resourceLimits.Add(ResourceType.Nelther, 0);
        resourceValues.Add(ResourceType.Elynium, 0);
        resourceLimits.Add(ResourceType.Elynium, 0);
        resourceValues.Add(ResourceType.Population, 0);
        resourceLimits.Add(ResourceType.Population, 0);

        posBar = transform.FindChild("Frame1").FindChild("Frame").FindChild("BackGround").FindChild("Production").gameObject.transform.position;

        transform.FindChild("Frame1").FindChild("UnitNameProduct").GetComponent<Text>().text = "";
        transform.FindChild("Frame1").FindChild("HitText").GetComponent<Text>().text = "";
        transform.FindChild("Frame1").FindChild("Object").gameObject.SetActive(false);

        transform.FindChild("Frame1").FindChild("Frame").gameObject.SetActive(false);
        transform.FindChild("Frame1").FindChild("UnitNameProduct").gameObject.SetActive(false);
        for (int j = 1; j < 6; j++)
        {
            transform.FindChild("Frame1").FindChild("FrameUnit" + j.ToString()).gameObject.SetActive(false);
        }
    }
示例#2
1
        private void btnSaveAsNew_Click(object sender, EventArgs e)
        {
            try
            {
                string query;
                Dictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.Add("@Name", txtName.Text);
                parameters.Add("@StartTime", dtpStart.Value.TimeOfDay);
                parameters.Add("@EndTime", dtpEnd.Value.TimeOfDay);
                query = @"INSERT INTO Periods (Name, StartTime, EndTime) VALUES (@Name, @StartTime, @EndTime);";

                _PeriodID = SqlHelper.ExecteNonQuery(query, parameters);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            this.Close();
            Central.MainForm.Focus();
            foreach (DockContent item in Central.MainForm.Contents)
            {
                if (item is Periods)
                {
                    ((Periods)item).RefreshPeriods();
                    continue;
                }
            }

            this.TabText = txtName.Text + " Details";
        }
        public static IncomingTransportMessage Deserialize(string messageId, Stream inputStream)
        {
            var headers = new Dictionary<string, string>();
            var serializedMessageData = "";
            using (var reader = new XmlTextReader(inputStream))
            {
                reader.WhitespaceHandling = WhitespaceHandling.None;
                reader.Read(); // read <root>
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        var elementName = reader.Name;
                        reader.Read(); // read the child;
                        while (reader.NodeType == XmlNodeType.Element)
                        {
                            // likely an empty header element node
                            headers.Add(elementName, reader.Value);

                            elementName = reader.Name;
                            reader.Read(); // read the child;
                        }
                        if (string.Equals(elementName, "body", StringComparison.InvariantCultureIgnoreCase) && reader.NodeType == XmlNodeType.CDATA)
                        {
                            serializedMessageData = reader.Value;
                        }
                        else if (reader.NodeType == XmlNodeType.Text)
                        {
                            headers.Add(elementName, reader.Value);
                        }
                    }
                }
            }
            return new IncomingTransportMessage(messageId, headers, serializedMessageData);
        }
示例#4
0
文件: GenText.cs 项目: potsh/RimWorld
        public static string Truncate(this string str, float width, Dictionary <string, string> cache = null)
        {
            if (cache != null && cache.TryGetValue(str, out string value))
            {
                return(value);
            }
            Vector2 vector = Text.CalcSize(str);

            if (vector.x <= width)
            {
                cache?.Add(str, str);
                return(str);
            }
            value = str;
            Vector2 vector2;

            do
            {
                value = value.Substring(0, value.Length - 1);
                if (value.Length <= 0)
                {
                    break;
                }
                vector2 = Text.CalcSize(value + "...");
            }while (vector2.x > width);
            value += "...";
            cache?.Add(str, value);
            return(value);
        }
示例#5
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string query;
                Dictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.Add("@Name", txtName.Text);
                parameters.Add("@StartTime", dtpStart.Value.TimeOfDay);
                parameters.Add("@EndTime", dtpEnd.Value.TimeOfDay);
                parameters.Add("@PeriodID", _PeriodID);
                if (_PeriodID < 0)
                    query = @"INSERT INTO Periods (Name, StartTime, EndTime) VALUES (@Name, @StartTime, @EndTime);";
                else
                    query = @"UPDATE Periods SET Name = @Name, StartTime = @StartTime, EndTime = @EndTime WHERE PeriodID = @PeriodID";

                _PeriodID = SqlHelper.ExecteNonQuery(query, parameters);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            this.Close();
            Central.MainForm.Focus();
            foreach (DockContent item in Central.MainForm.Contents)
            {
                if (item is Periods)
                    ((Periods)item).RefreshPeriods();
            }
        }
    void Test_diclist()
    {
        Dictionary <string, List<string>> myDic
            = new Dictionary<string, List<string>> ();
        string keystr;

        // command 1
        keystr = "hello";
        var res1ls = new List<string> ();
        res1ls.Add ("hello, Mike");
        res1ls.Add ("tadano shikabane no youda");
        res1ls.Add ("This number is not currently registered");
        myDic.Add (keystr, res1ls);

        // command 2
        keystr = "Ca va bien?";
        var res2ls = new List<string> ();
        res2ls.Add ("Merci, beaucoup");
        res2ls.Add ("honjitsu wa sentenn nari");
        res2ls.Add ("Je nous peut pas parler Francaise.");
        myDic.Add (keystr, res2ls);

        //		displayAllElementWithKey (ref myDic, /* searchKey=*/"hello");
        for (int loop=0; loop<10; loop++) {
            findElementWithKey (ref myDic, /* searchKey=*/"hello");
        }
    }
        /// <summary>
        /// 11、	添加指标
        /// </summary>
        /// <param name="name">指标名称</param>
        /// <param name="itype">输入方式</param>
        /// <param name="vtype">值类型</param>
        /// <param name="editbypat">是否可由病人编辑</param>
        /// <param name="hospitalid">医院id</param>
        /// <param name="cateid">病例分类id</param>
        /// <param name="val">值序列,以数组形式传递,可为空</param>
        /// <returns></returns>
        /// Jack Ding
        public TermAddResponse Add(string name, int itype, int vtype, int editbypat, int hospitalid, int cateid, double[] val)
        {
            string strResponse = string.Empty;
            TermAddResponse response = new TermAddResponse();

            try
            {
                Dictionary<string, string> sPara = new Dictionary<string, string>();

                sPara.Add("name", name);
                sPara.Add("itype", itype.ToString());
                sPara.Add("vtype", vtype.ToString());
                sPara.Add("editbypat", editbypat.ToString());
                sPara.Add("hospitalid", hospitalid.ToString());
                //val参数不知道如何添加

                strResponse = F8YLSubmit.BuildRequest(sPara, "term/add");

                response = JsonHelper.DeserializeJsonToObject<TermAddResponse>(strResponse);

                return response;
            }
            catch
            {
                throw;
            }
        }
        internal DatabaseGenerationAssemblyLoader(Project project, string vsInstallPath)
        {
            _assembliesInstalledUnderVisualStudio = new Dictionary<string, string>();
            // For these DLLs we should use the version pre-installed under the VS directory,
            // not whatever reference the project may have
            _assembliesInstalledUnderVisualStudio.Add(
                "ENTITYFRAMEWORK", Path.Combine(vsInstallPath, "EntityFramework.dll"));
            _assembliesInstalledUnderVisualStudio.Add(
                "ENTITYFRAMEWORK.SQLSERVER", Path.Combine(vsInstallPath, "EntityFramework.SqlServer.dll"));
            _assembliesInstalledUnderVisualStudio.Add(
                "ENTITYFRAMEWORK.SQLSERVERCOMPACT", Path.Combine(vsInstallPath, "EntityFramework.SqlServerCompact.dll"));

            _projectReferenceLookup = new Dictionary<string, Reference3>();
            _websiteReferenceLookup = new Dictionary<string, AssemblyReference>();
            if (project != null)
            {
                var vsProject = project.Object as VSProject2;
                var vsWebSite = project.Object as VSWebSite;
                if (vsProject != null)
                {
                    _isWebsite = false;
                    CacheProjectReferences(vsProject);
                }
                else if (vsWebSite != null)
                {
                    _isWebsite = true;
                    CacheWebsiteReferences(vsWebSite);
                }
            }
        }
示例#9
0
        //
        // GET: /Home/
        public ActionResult Index()
        {
            var beneficiaries = _unitOfWork.Beneficiaries.GetAll();

            Dictionary<string, decimal> totals = new Dictionary<string, decimal>();
            const decimal TARGET = 600000;
            totals.Add("Target", TARGET);

            List<Payment> payments = _unitOfWork.Payments.GetPaymentWithCurrency().ToList();

            var posted = payments.Where(p => p.Locked).Sum(p => p.Amount * p.Currency.ExchangeRate);

            totals.Add("Posted", posted);

            var total = payments.Sum(p => p.Amount * p.Currency.ExchangeRate);

            totals.Add("Total", total);

            ViewBag.Posted = totals["Posted"];
            ViewBag.Total = totals["Total"];
            ViewBag.Target = totals["Target"];
            ViewBag.Percentage = Convert.ToInt32((ViewBag.Total / ViewBag.Target) * 100);

            return View(beneficiaries);
        }
示例#10
0
 public override Dictionary<string, object> feed(
     Dictionary<string, object> data)
 {
     data.Add("text", Text);
     data.Add("link", Link);
     return data;
 }
    public ObjectFactory()
    {
        instance = this;

        creationTable = new Dictionary<string, System.Func<GameObject>>();
        creationTable.Add("factory", createFactory);
        creationTable.Add ("city", createCity);
        creationTable.Add ("fort", createFort);
        creationTable.Add ("barracks", createBarracks);
        creationTable.Add ("tree", createTree);

        team1 = new Dictionary<string, string>();
        team2 = new Dictionary<string, string>();

        team1.Add ("scout", "lambo");
        team1.Add ("ranged", "archer");
        team1.Add ("healer", "healer");
        team1.Add ("medium", "construction");
        team1.Add ("heavy", "predator");

        team2.Add ("scout", "normandy");
        team2.Add ("ranged", "wizard");
        team2.Add ("healer", "healer");
        team2.Add ("medium", "construction");
        team2.Add ("heavy", "centurion");
    }
示例#12
0
        public override UploadResult ShortenURL(string url)
        {
            UploadResult result = new UploadResult { URL = url };

            if (string.IsNullOrEmpty(API_HOST))
            {
                API_HOST = "https://polr.me/publicapi.php";
                API_KEY = null;
            }
            else
            {
                API_HOST = URLHelpers.FixPrefix(API_HOST);
            }

            Dictionary<string, string> args = new Dictionary<string, string>();

            if (!string.IsNullOrEmpty(API_KEY))
            {
                args.Add("apikey", API_KEY);
            }

            args.Add("action", "shorten");
            args.Add("url", url);

            string response = SendRequest(HttpMethod.GET, API_HOST, args);

            if (!string.IsNullOrEmpty(response))
            {
                result.ShortenedURL = response;
            }

            return result;
        }
 public bool PosTest1()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest1:Invoke the method GetEnumerator in ValueCollection Generic IEnumerable 1");
     try
     {
         Dictionary<string, string> dic = new Dictionary<string, string>();
         dic.Add("str1", "Test1");
         dic.Add("str2", "Test2");
         IEnumerable<string> ienumer = (IEnumerable<string>)new Dictionary<string, string>.ValueCollection(dic);
         IEnumerator<string> ienumerator = ienumer.GetEnumerator();
         Dictionary<string, string>.Enumerator dicEnumer = dic.GetEnumerator();
         while (ienumerator.MoveNext() && dicEnumer.MoveNext())
         {
             if (!ienumerator.Current.Equals(dicEnumer.Current.Value))
             {
                 TestLibrary.TestFramework.LogError("001", "the ExpecResult is not the ActualResult");
                 retVal = false;
             }
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
         retVal = false;
     }
     return retVal;
 }
示例#14
0
        public Dictionary<string, object> Fill(WebInterface webInterface, string filename, OSHttpRequest httpRequest,
            OSHttpResponse httpResponse, Dictionary<string, object> requestParameters,
            ITranslator translator, out string response)
        {
            response = null;
            var vars = new Dictionary<string, object>();
            if (requestParameters.ContainsKey("Submit"))
            {
                string title = requestParameters["NewsTitle"].ToString();
                string text = requestParameters["NewsText"].ToString();
                IGenericsConnector connector = Framework.Utilities.DataManager.RequestPlugin<IGenericsConnector>();
                GridNewsItem item = new GridNewsItem {Text = text, Time = DateTime.Now, Title = title};
                item.ID = connector.GetGenericCount(UUID.Zero, "WebGridNews") + 1;
                connector.AddGeneric(UUID.Zero, "WebGridNews", item.ID.ToString(), item.ToOSD());
                response = "<h3>News item added successfully, redirecting to main page</h3>" +
                           "<script language=\"javascript\">" +
                           "setTimeout(function() {window.location.href = \"index.html?page=news_manager\";}, 0);" +
                           "</script>";
                return null;
            }

            vars.Add("NewsItemTitle", translator.GetTranslatedString("NewsItemTitle"));
            vars.Add("NewsItemText", translator.GetTranslatedString("NewsItemText"));
            vars.Add("AddNewsText", translator.GetTranslatedString("AddNewsText"));
            vars.Add("Submit", translator.GetTranslatedString("Submit"));

            return vars;
        }
 public void Claims_Roundtrip()
 {
     Dictionary<string, string> claims = new Dictionary<string, string>();
     claims.Add("foo", "value1");
     claims.Add("bar", "value2");
     PropertyAssert.Roundtrips(this.creds, c => c.Claims, PropertySetter.NullRoundtrips, roundtripValue: claims);
 }
        public PartialCountBolt(Context ctx)
        {
            this.ctx = ctx;

            // set input schemas
            Dictionary<string, List<Type>> inputSchema = new Dictionary<string, List<Type>>();
            inputSchema.Add(Constants.DEFAULT_STREAM_ID, new List<Type>() { typeof(string) });

            //Add the Tick tuple Stream in input streams - A tick tuple has only one field of type long
            inputSchema.Add(Constants.SYSTEM_TICK_STREAM_ID, new List<Type>() { typeof(long) });

            // set output schemas
            Dictionary<string, List<Type>> outputSchema = new Dictionary<string, List<Type>>();
            outputSchema.Add(Constants.DEFAULT_STREAM_ID, new List<Type>() { typeof(long) });

            // Declare input and output schemas
            this.ctx.DeclareComponentSchema(new ComponentStreamSchema(inputSchema, outputSchema));

            this.ctx.DeclareCustomizedDeserializer(new CustomizedInteropJSONDeserializer());

            if (Context.Config.pluginConf.ContainsKey(Constants.NONTRANSACTIONAL_ENABLE_ACK))
            {
                enableAck = (bool)(Context.Config.pluginConf[Constants.NONTRANSACTIONAL_ENABLE_ACK]);
            }

            partialCount = 0L;
            totalCount = 0L;
        }
    /// <summary>
    /// Start is called once on object creation
    /// </summary>
    protected override void Start()
    {
        instance = this;
        previewObjects = new Dictionary<CharacterType, GameObject>();
        previewObjects.Add(CharacterType.Ranger, ranger);
        previewObjects.Add(CharacterType.Mage, mage);
        previewObjects.Add(CharacterType.Warrior, warrior);
        abilityTexts = new Dictionary<InputType, Text[]>();
        abilityTexts.Add(InputType.Main, mainTexts);
        abilityTexts.Add(InputType.Secondary, secondTexts);
        abilityTexts.Add(InputType.Power, powerTexts);
        abilityTexts.Add(InputType.Special, specialTexts);
        classNames = new Dictionary<CharacterType, string>();
        classNames.Add(CharacterType.Ranger, "RANGER");
        classNames.Add(CharacterType.Mage, "MAGE");
        classNames.Add(CharacterType.Warrior, "WARRIOR");
        UpdateMapping();

        if (autoShow)
        {
            previewObjects[GameManager.Instance.CurrentSave.PlayerType].SetActive(true);
            title.text = classNames[GameManager.Instance.CurrentSave.PlayerType];
        }
        base.Start();
    }
示例#18
0
		private static void SetCellDictionaries()
		{
			var bottomDict = new Dictionary<int, Edge>();
			bottomDict.Add((int)CellBitmask.RightBottom, Edge.Right);
			bottomDict.Add(Edge.Left,
				CellBitmask.LeftTop,
				CellBitmask.LeftBottom | CellBitmask.RightBottom | CellBitmask.RightTop,
				CellBitmask.LeftTop | CellBitmask.RightBottom | CellBitmask.RightTop,
				CellBitmask.LeftBottom);
			bottomDict.Add(Edge.Right,
				CellBitmask.RightTop,
				CellBitmask.LeftBottom | CellBitmask.RightBottom | CellBitmask.LeftTop,
				CellBitmask.LeftBottom | CellBitmask.LeftTop | CellBitmask.RightTop);
			bottomDict.Add(Edge.Top,
				CellBitmask.RightBottom | CellBitmask.RightTop,
				CellBitmask.LeftBottom | CellBitmask.LeftTop);

			var leftDict = new Dictionary<int, Edge>();
			leftDict.Add(Edge.Top,
				CellBitmask.LeftTop,
				CellBitmask.LeftBottom | CellBitmask.RightBottom | CellBitmask.RightTop);
			leftDict.Add(Edge.Right,
				CellBitmask.LeftTop | CellBitmask.RightTop,
				CellBitmask.LeftBottom | CellBitmask.RightBottom);
			leftDict.Add(Edge.Bottom,
				CellBitmask.RightBottom | CellBitmask.RightTop | CellBitmask.LeftTop,
				CellBitmask.LeftBottom);

			var topDict = new Dictionary<int, Edge>();
			topDict.Add(Edge.Right,
				CellBitmask.RightTop,
				CellBitmask.LeftTop | CellBitmask.LeftBottom | CellBitmask.RightBottom);
			topDict.Add(Edge.Right,
				CellBitmask.RightBottom,
				CellBitmask.LeftTop | CellBitmask.LeftBottom | CellBitmask.RightTop);
			topDict.Add(Edge.Left,
				CellBitmask.RightBottom | CellBitmask.RightTop | CellBitmask.LeftTop,
				CellBitmask.LeftBottom,
				CellBitmask.LeftTop,
				CellBitmask.LeftBottom | CellBitmask.RightBottom | CellBitmask.RightTop);
			topDict.Add(Edge.Bottom,
				CellBitmask.RightBottom | CellBitmask.RightTop,
				CellBitmask.LeftTop | CellBitmask.LeftBottom);

			var rightDict = new Dictionary<int, Edge>();
			rightDict.Add(Edge.Top,
				CellBitmask.RightTop,
				CellBitmask.LeftBottom | CellBitmask.RightBottom | CellBitmask.LeftTop);
			rightDict.Add(Edge.Left,
				CellBitmask.LeftTop | CellBitmask.RightTop,
				CellBitmask.LeftBottom | CellBitmask.RightBottom);
			rightDict.Add(Edge.Bottom,
				CellBitmask.RightBottom,
				CellBitmask.LeftTop | CellBitmask.LeftBottom | CellBitmask.RightTop);

			dictChooser.Add((int)Edge.Left, leftDict);
			dictChooser.Add((int)Edge.Right, rightDict);
			dictChooser.Add((int)Edge.Bottom, bottomDict);
			dictChooser.Add((int)Edge.Top, topDict);
		}
        private void CreateMenu()
        {
            Sites = new Dictionary<string, string>();
            var root = "../Form/";
            Sites.Add(root + "Start.aspx", Resources.Default.home);
            Sites.Add(root + "Uebersicht.aspx", Resources.Default.accountMovements);
            Sites.Add(root + "Kategorie.aspx", Resources.Default.Overview);

            if (SessionManager.CurrentUser.ISADMIN == true)
            {
                Sites.Add(root + "Admin/Admin.aspx", Resources.Default.admin);
            }

            var script = string.Empty;
            foreach (var str in Sites)
            {
                script = string.Concat(script,
                    "haushaltsRechner.client.menuPoint('",
                    str.Key,
                    "','",
                    str.Value,
                    "','",
                    MainMenu.ClientID,
                    "');");
            }

            ScriptManager.RegisterStartupScript(this, GetType(), "STARTUPSCRIPTCONTENTMASTER_" + ClientID, script, true);
        }
示例#20
0
        public bool GetAccessToken(string code)
        {
            Dictionary<string, string> args = new Dictionary<string, string>();
            args.Add("code", code);
            args.Add("client_id", AuthInfo.Client_ID);
            args.Add("client_secret", AuthInfo.Client_Secret);
            args.Add("redirect_uri", "urn:ietf:wg:oauth:2.0:oob");
            args.Add("grant_type", "authorization_code");

            string response = SendRequest(HttpMethod.POST, "https://accounts.google.com/o/oauth2/token", args);

            if (!string.IsNullOrEmpty(response))
            {
                OAuth2Token token = JsonConvert.DeserializeObject<OAuth2Token>(response);

                if (token != null && !string.IsNullOrEmpty(token.access_token))
                {
                    token.UpdateExpireDate();
                    AuthInfo.Token = token;
                    return true;
                }
            }

            return false;
        }
		/// <summary>
		/// A simple construtor that initializes the object with the given dependencies.
		/// </summary>
		/// <param name="p_msfFunctions">The object that proxies the script function calls
		/// out of the sandbox.</param>
		public ModScriptInterpreterContext(ModScriptFunctionProxy p_msfFunctions)
		{
			Variables = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
			FunctionProxy = p_msfFunctions;
			Variables.Add("NewLine", Environment.NewLine);
			Variables.Add("Tab", "\t");
		}
        public void Configure()
        {
            if (ShouldAddPackageExecutablePath())
            {
                Stopwatch beforeAddPackageExecutablePath = Stopwatch.StartNew();
                AddPackageExecutablePath();
                _performanceMeasurements?.Add("AddPackageExecutablePath Time", beforeAddPackageExecutablePath.Elapsed.TotalMilliseconds);
            }

            if (ShouldPrintFirstTimeUseNotice())
            {
                Stopwatch beforeFirstTimeUseNotice = Stopwatch.StartNew();
                if (!_dotnetFirstRunConfiguration.NoLogo)
                {
                    PrintFirstTimeMessageWelcome();
                    if (ShouldPrintTelemetryMessageWhenFirstTimeUseNoticeIsEnabled())
                    {
                        PrintTelemetryMessage();
                    }

                    PrintFirstTimeMessageMoreInformation();
                }

                _firstTimeUseNoticeSentinel.CreateIfNotExists();
                _performanceMeasurements?.Add("FirstTimeUseNotice Time", beforeFirstTimeUseNotice.Elapsed.TotalMilliseconds);
            }

            if (ShouldGenerateAspNetCertificate())
            {
                Stopwatch beforeGenerateAspNetCertificate = Stopwatch.StartNew();
                GenerateAspNetCertificate();
                _performanceMeasurements?.Add("GenerateAspNetCertificate Time", beforeGenerateAspNetCertificate.Elapsed.TotalMilliseconds);
            }
        }
        //// GET api/<controller>
        //public IEnumerable<string> Get()
        //{
        //    return new string[] { "value1", "value2" };
        //}
        //// GET api/<controller>/5
        //public string Get(int id)
        //{
        //    return "value";
        //}
        //// POST api/<controller>
        //public void Post([FromBody]string value)
        //{
        //}
        //// PUT api/<controller>/5
        //public void Put(int id, [FromBody]string value)
        //{
        //}
        //// DELETE api/<controller>/5
        //public void Delete(int id)
        //{
        //}
        public Dictionary<string, Boolean> Get()
        {
            Dictionary<string, Boolean> perms = new Dictionary<string, Boolean>();

            using (ServerApplicationContext ctx = ServerApplicationContext.CreateContext())
            {
                var currentUser = ctx.Application.User;
                if (currentUser.IsAuthenticated)
                {
                    perms.Add(Permissions.SecurityAdministration,
                        currentUser.HasPermission(Permissions.SecurityAdministration));

                    currentUser.AddPermissions(Permissions.SecurityAdministration);

                    foreach (Permission perm in ctx.DataWorkspace.SecurityData.Permissions)
                    {
                        if (perm.Id != Permissions.SecurityAdministration)
                        {
                            perms.Add(perm.Id, currentUser.HasPermission(perm.Id));
                        }
                    }
                }
            }
            return perms;
        }
示例#24
0
        /// <summary>
        /// Creates a DotLiquid compatible dictionary that represents the current store model.
        /// </summary>
        /// <param name="debug">if set to <c>true</c> the entire object tree will be parsed immediately.</param>
        /// <returns>
        /// DotLiquid compatible dictionary.
        /// </returns>
        public virtual object ToLiquid( bool debug )
        {
            var dictionary = new Dictionary<string, object>();

            Type entityType = this.GetType();

            foreach ( var propInfo in entityType.GetProperties() )
            {

                object propValue = propInfo.GetValue( this, null );

                if ( propValue is Guid )
                {
                    propValue = ((Guid)propValue).ToString();
                }

                if ( debug && propValue is DotLiquid.ILiquidizable )
                {
                    dictionary.Add( propInfo.Name, ((DotLiquid.ILiquidizable)propValue).ToLiquid() );
                }
                else
                {
                    dictionary.Add( propInfo.Name, propValue );
                }

            }

            return dictionary;
        }
示例#25
0
        public void SendLetter(UpdateLetter updateLetter)
        {
            var letter = updateLetter.CreateLetter();
            letter.ReplyTime = SqlDateTime.MinValue.Value;
            using (var content = new DefaultContext())
            {
                content.Letters.Add(letter);
                content.SaveChanges();
            }
            var dic = new Dictionary<string, string>();
            dic.Add("ActionName", "Reply");
            dic.Add("letter", letter.ToJson());

            var resString = HttpWebResponseUtility.CreatePostHttpResponse("http://second.eagle.com/api/Message", dic.ToJson(), 30000);
            if (string.IsNullOrEmpty(resString) || resString == "0")
            {
                Flag = false;
                Message = "消息无响应";
                return;
            }
            var result = resString.ToDeserialize<Cells>();
            if (!result.Flag)
            {
                Flag = false;
                Message = result.Message;
                return;
            }
            Flag = true;
        }
示例#26
0
        public DetectorsStatusManager(DetectorsDataAccess dataAccess, EventLoggerAccess logger) :
            base(dataAccess, logger)
        {
            _logger = logger;
            Dictionary<int, string> ConnectionValueMapping = new Dictionary<int, string>();
            ConnectionValueMapping.Add(0, TagValueTypes.Error);
            ConnectionValueMapping.Add(1, TagValueTypes.Clear);

            StatusElement detectorConnect = new StatusElement(_DetectorConnectTag, 0, TagTypes.Status, ConnectionValueMapping);
            //detectorConnect.Value = 
            _Statuses.Add(detectorConnect);


            StatusElement apcsConnect = new StatusElement(_APCSConnectTag, 0, TagTypes.Status, ConnectionValueMapping);
            _Statuses.Add(apcsConnect);

            dataAccess.DetectorConnectionStateUpdate +=
                    new ConnectionStateChangeHandler(OnDetectorsConnectionChange);
            dataAccess.APCSConnectionStateUpdate +=
                    new ConnectionStateChangeHandler(OnApcsConnectionChange);

            Dictionary<int, string> DetectorsValueMapping = new Dictionary<int, string>();
            DetectorsValueMapping.Add(0, TagValueTypes.Clear);
            DetectorsValueMapping.Add(1, TagValueTypes.Warning);
            DetectorsValueMapping.Add(2, TagValueTypes.Error);
            DetectorsValueMapping.Add(3, TagValueTypes.Warning);

            StatusElement detectorStatus = new StatusElement(_DetectorStatusTag, 0, TagTypes.Status, DetectorsValueMapping);
            _Statuses.Add(detectorStatus);
        }
示例#27
0
 /// <summary>
 /// 取得临时的Access Token
 /// </summary>
 /// <param name="code">临时Authorization Code,官方提示10分钟过期</param>
 /// <param name="state">防止CSRF攻击,成功授权后回调时会原样带回</param>
 /// <returns>Dictionary</returns>
 public static Dictionary<string, object> get_access_token(string code, string state)
 {
     //获得配置信息
     oauth_config config = oauth_helper.get_config("qq");
     string send_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=" + config.oauth_app_id + "&client_secret=" + config.oauth_app_key + "&code=" + code + "&state=" + state + "&redirect_uri=" + Utils.UrlEncode(config.return_uri);
     //发送并接受返回值
     string result = Utils.HttpGet(send_url);
     if (result.Contains("error"))
     {
         return null;
     }
     try
     {
         string[] parm = result.Split('&');
         string access_token = parm[0].Split('=')[1];    //取得access_token
         string expires_in = parm[1].Split('=')[1];      //Access Token的有效期,单位为秒
         Dictionary<string, object> dic = new Dictionary<string, object>();
         dic.Add("access_token", access_token);
         dic.Add("expires_in", expires_in);
         return dic;
     }
     catch
     {
         return null;
     }
 }
 public bool PosTest2()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest2:Invoke the method CopyTo in the ValueCollection 2");
     try
     {
         Dictionary<string, string> dic = new Dictionary<string, string>();
         dic.Add("str1", "Test1");
         dic.Add("str2", "Test2");
         Dictionary<string, string>.ValueCollection values = new Dictionary<string, string>.ValueCollection(dic);
         string[] TVals = new string[SIZE];
         values.CopyTo(TVals, 5);
         string strVals = null;
         for (int i = 0; i < TVals.Length; i++)
         {
             if (TVals[i] != null)
             {
                 strVals += TVals[i].ToString();
             }
         }
         if (TVals[5].ToString() != "Test1" || TVals[6].ToString() != "Test2" || strVals != "Test1Test2")
         {
             TestLibrary.TestFramework.LogError("003", "the ExpecResult is not the ActualResult");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
         retVal = false;
     }
     return retVal;
 }
示例#29
0
        public static Dictionary<MarkerType, IMarkerDrawer> CreateDefaultMarkerDrawers()
        {
            Dictionary<MarkerType, IMarkerDrawer> markerDrawers = new Dictionary<MarkerType, IMarkerDrawer>();
              markerDrawers.Add(
            MarkerType.Start,
            new CircleDrawer(Color.FromArgb(192, 255, 0, 64), 12, 3)
              );
              markerDrawers.Add(
            MarkerType.Lap,
            new CircleDrawer(Color.FromArgb(192, 255, 0, 64), 12, 3)
              );
              markerDrawers.Add(
            MarkerType.Stop,
            new CircleDrawer(Color.FromArgb(192, 255, 0, 64), 12, 3)
              );
              markerDrawers.Add(
            MarkerType.MouseHover,
            new DiscAndCircleDrawer(Color.FromArgb(192, Color.Red), 4, Color.FromArgb(192,Color.Black), 6, 2)
              );
              markerDrawers.Add(
            MarkerType.Handle,
            new DiscDrawer(Color.FromArgb(192, Color.Blue), 6)
              );
              markerDrawers.Add(
            MarkerType.ActiveHandle,
            new DiscAndCircleDrawer(Color.FromArgb(192, Color.Blue), 6, Color.FromArgb(192, Color.Blue), 12, 3)
              );
              markerDrawers.Add(
            MarkerType.MovingActiveHandle,
            new CircleDrawer(Color.FromArgb(192, Color.Blue), 12, 3)
              );

              return markerDrawers;
        }
示例#30
0
        public async Task<bool> RegisterDevice(string token, string deviceModel = null, string systemVersion = null, bool noText = false, string subscribe = null)
        {
            if (_vkontakte.AccessToken == null || string.IsNullOrEmpty(_vkontakte.AccessToken.Token) || _vkontakte.AccessToken.HasExpired)
                throw new Exception("Access token is not valid.");

            var parametres = new Dictionary<string, string>();

            parametres.Add("token", token);

            if (!string.IsNullOrEmpty(deviceModel))
                parametres.Add("device_model", deviceModel);

            if (!string.IsNullOrEmpty(systemVersion))
                parametres.Add("system_version", systemVersion);

            if (noText)
                parametres.Add("no_text", "1");

            _vkontakte.SignMethod(parametres);

            var response = await new VkRequest(new Uri(VkConst.MethodBase + "account.registerDevice"), parametres).Execute();

            VkErrorProcessor.ProcessError(response);

            if (response["response"] != null)
            {
                return response["response"].Value<int>() == 1;
            }

            return false;
        }
 public bool PosTest2()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest2:Invoke the method GetEnumerator in ValueCollection Generic IEnumerable 2");
     try
     {
         Dictionary<TestClass, TestClass> dic = new Dictionary<TestClass, TestClass>();
         TestClass TKey1 = new TestClass();
         TestClass TVal1 = new TestClass();
         TestClass TKey2 = new TestClass();
         TestClass TVal2 = new TestClass();
         dic.Add(TKey1, TVal1);
         dic.Add(TKey2, TVal2);
         IEnumerable<TestClass> ienumer = (IEnumerable<TestClass>)new Dictionary<TestClass, TestClass>.ValueCollection(dic);
         IEnumerator<TestClass> ienumerator = ienumer.GetEnumerator();
         Dictionary<TestClass, TestClass>.Enumerator dicEnumer = dic.GetEnumerator();
         while (ienumerator.MoveNext() && dicEnumer.MoveNext())
         {
             if (!ienumerator.Current.Equals(dicEnumer.Current.Value))
             {
                 TestLibrary.TestFramework.LogError("003", "the ExpecResult is not the ActualResult");
                 retVal = false;
             }
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
         retVal = false;
     }
     return retVal;
 }
示例#32
0
        public static void Test_Serialize_Dictionary_02(DictionaryRepresentation dictionaryRepresentation)
        {
            // json Dictionary
            // DictionaryRepresentation.Dynamic or DictionaryRepresentation.Document
            // { "toto1" : "tata1", "toto2" : "tata2" }
            // DictionaryRepresentation.ArrayOfArrays
            // [["toto1", "tata1"], ["toto2", "tata2"]]
            // DictionaryRepresentation.ArrayOfDocuments
            // [{ "k" : "toto1", "v" : "tata1" }, { "k" : "toto2", "v" : "tata2" }]
            Trace.WriteLine();
            Trace.WriteLine("Test_Serialize_Dictionary_02");
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            dictionary.Add("toto1", "tata1");
            dictionary.Add("toto2", "tata2");
            //DictionaryRepresentation dictionaryRepresentation = DictionaryRepresentation.ArrayOfDocuments;
            Trace.WriteLine("DictionaryRepresentation : {0}", dictionaryRepresentation);
            Trace.WriteLine("Dictionary json :");
            string json = dictionary.ToJson(new DictionarySerializationOptions(dictionaryRepresentation));
            Trace.WriteLine(json);

            Trace.WriteLine("Deserialize json :");
            Dictionary<string, string> dictionary2 = BsonSerializer.Deserialize<Dictionary<string, string>>(json);
            string json2 = dictionary2.ToJson(new DictionarySerializationOptions(dictionaryRepresentation));
            Trace.WriteLine(json2);
            Trace.WriteLine("comparison of Dictionary json and Deserialize json : {0}", json == json2 ? "identical" : "different");
        }
示例#33
0
        void Awake()
        {
            instance = this;
            InitRootCavansLoading();
            transformRoot = GameObject.FindGameObjectWithTag(SystemDefine.canvasTag).transform;
            //CanvasScaler canvas = transform.GetComponent<CanvasScaler>();
            //canvas.scaleMode =
            transformNormal    = transformRoot.Find("Normal");
            transformFixed     = transformRoot.Find("Fixed");
            transformPopUp     = transformRoot.Find("PopUp");
            transformUIScripts = transformRoot.Find("ScriptsMgr");

            this.gameObject.transform.SetParent(transformUIScripts, false);
            DontDestroyOnLoad(transformRoot);
            UIPaths?.Add("Demo.BeginGameUI", "UIPrefabs/BeginGameUI");
            UIPaths?.Add("Demo.LoadAsyncScene", "UIPrefabs/LoadingUI");
            UIPaths?.Add("Demo.PauseUI", "UIPrefabs/PauseUI");
            UIPaths?.Add("Demo.SelectLevelUI", "UIPrefabs/SelectLevelUI");
            UIPaths?.Add("Demo.HomeUI", "UIPrefabs/HomeUI");
            UIPaths?.Add("Demo.SettingsUI", "UIPrefabs/SettingsUI");
            UIPaths?.Add("Demo.PlayOneUI", "UIPrefabs/PassLevelOne");
            UIPaths?.Add("Demo.PlayTwoUI", "UIPrefabs/PassLevelTwo");
            UIPaths?.Add("Demo.BeforeLoadingUI", "UIPrefabs/BeforeLoading");
            gameObject.AddComponent <LaunchGameUI>();
        }
        /// <summary>
        /// InitializedAuditables
        /// </summary>
        /// <param name="isReload"></param>
        public virtual void InitializedAuditables(bool isReload = false)
        {
            if (AuditableDictionary != null && AuditableDictionary.Any())
            {
                return;
            }
            if (Auditables == null || isReload)
            {
                Auditables = new List <Auditable>();
            }
            var types = _typeFinder.FindClassesOfType <IAuditable>();

            AuditableDictionary = new Dictionary <EntityState, List <IAuditable> >();

            foreach (var type in types)
            {
                var item = (AuditAttribute)type.GetCustomAttributes(typeof(AuditAttribute), true).FirstOrDefault();
                if (item == null)
                {
                    continue;
                }
                var auditable = new Auditable
                {
                    EntityState   = item.EntityState,
                    AuditableImpl = IocManager.Instance.ResolveName <IAuditable>(type.FullName)
                };
                Auditables.Add(auditable);
            }

            var addAuditables = Auditables.Where(x => x.EntityState == EntityState.Added).
                                Select(x => x.AuditableImpl).ToList();

            if (addAuditables.Any())
            {
                AuditableDictionary?.Add(EntityState.Added, addAuditables);
            }

            var updateAuditables = Auditables.Where(x => x.EntityState == EntityState.Modified).
                                   Select(x => x.AuditableImpl).ToList();

            if (updateAuditables.Any())
            {
                AuditableDictionary?.Add(EntityState.Modified, updateAuditables);
            }

            var deleteAuditables = Auditables.Where(x => x.EntityState == EntityState.Deleted).
                                   Select(x => x.AuditableImpl).ToList();

            if (deleteAuditables.Any())
            {
                AuditableDictionary?.Add(EntityState.Deleted, deleteAuditables);
            }
        }
示例#35
0
        public static int BridgeGaps(Subtitle subtitle, int minMsBetweenLines, bool divideEven, double maxMs, List <int> fixedIndexes, Dictionary <string, string> dic, bool useFrames)
        {
            int fixedCount = 0;

            if (minMsBetweenLines > maxMs)
            {
                string message = $"{nameof(DurationsBridgeGaps)}: {nameof(minMsBetweenLines)} cannot be larger than {nameof(maxMs)}!";
                SeLogger.Error(new InvalidOperationException(message), message);
                return(0);
            }

            int count = subtitle.Paragraphs.Count - 1;

            for (int i = 0; i < count; i++)
            {
                var cur  = subtitle.Paragraphs[i];
                var next = subtitle.Paragraphs[i + 1];

                double currentGap = next.StartTime.TotalMilliseconds - cur.EndTime.TotalMilliseconds;

                // there shouldn't be adjustment if current gaps is shorter or equal than minimum gap or greater than maximum gaps
                if (currentGap <= minMsBetweenLines || currentGap > maxMs)
                {
                    continue;
                }

                // next paragraph start-time will be pull to try to meet the current paragraph
                if (divideEven)
                {
                    next.StartTime.TotalMilliseconds -= currentGap / 2.0;
                }

                cur.EndTime.TotalMilliseconds = next.StartTime.TotalMilliseconds - minMsBetweenLines;
                if (fixedIndexes != null)
                {
                    fixedIndexes.Add(i);
                    fixedIndexes.Add(i + 1);
                }
                fixedCount++;

                double newGap = next.StartTime.TotalMilliseconds - cur.EndTime.TotalMilliseconds;
                if (useFrames)
                {
                    dic?.Add(cur.Id, $"{SubtitleFormat.MillisecondsToFrames(currentGap)} => {SubtitleFormat.MillisecondsToFrames(newGap)}");
                }
                else
                {
                    dic?.Add(cur.Id, $"{currentGap / TimeCode.BaseUnit:0.000} => {newGap / TimeCode.BaseUnit:0.000}");
                }
            }

            return(fixedCount);
        }
示例#36
0
        private static Dictionary <string, string> PopulateLogAttributes(LogEntry logEntry = null)
        {
            var attributes = new Dictionary <string, string>
            {
                { DefaultValues.TypeNameKey, nameof(T) }
            };

            if (logEntry?.CustomLogAttributes != null)
            {
                attributes = logEntry.CustomLogAttributes as Dictionary <string, string>;
                attributes?.Add(DefaultValues.CorrelationId, logEntry.CorrelationId);
                attributes?.Add(DefaultValues.CallerMethodName, logEntry.CallerMethodName);
            }
            return(attributes);
        }
示例#37
0
        public override double Calculate(Dictionary <string, double> categoryDifficulty = null)
        {
            // Fill our custom DifficultyHitObject class, that carries additional information
            difficultyHitObjects.Clear();

            int columnCount = (Beatmap as ManiaBeatmap)?.TotalColumns ?? 7;

            foreach (var hitObject in Beatmap.HitObjects)
            {
                difficultyHitObjects.Add(new ManiaHitObjectDifficulty((ManiaHitObject)hitObject, columnCount));
            }

            // Sort DifficultyHitObjects by StartTime of the HitObjects - just to make sure.
            difficultyHitObjects.Sort((a, b) => a.BaseHitObject.StartTime.CompareTo(b.BaseHitObject.StartTime));

            if (!calculateStrainValues())
            {
                return(0);
            }

            double starRating = calculateDifficulty() * star_scaling_factor;

            categoryDifficulty?.Add("Strain", starRating);

            return(starRating);
        }
示例#38
0
        public void RefreshStall(LeaseDTO lease)
        {
            if (Stalls == null)
            {
                return;
            }
            if (lease == null)
            {
                throw Fault.NullRef("Lease");
            }
            if (lease.Stall == null)
            {
                throw Fault.NullRef("Lease.Stall");
            }

            //lease.Stall = Stalls.Find(lease.Stall.Id, true);
            var stallID = lease.Stall.Id;

            if (_stalls.TryGetValue(stallID, out StallDTO cached))
            {
                lease.Stall = cached;
            }
            else
            {
                lease.Stall = Stalls.Find(stallID, true);
                //_stalls[stallID] = lease.Stall;
                try
                {
                    _stalls?.Add(stallID, lease.Stall);
                }
                catch { }
            }
        }
 private static Dictionary <string, ControlData> OptionCollection(
     Dictionary <string, ControlData> optionCollection = null,
     string selectedValue  = null,
     bool multiple         = false,
     bool addSelectedValue = true,
     bool insertBlank      = false,
     Column column         = null)
 {
     if (insertBlank)
     {
         optionCollection = InsertBlank(optionCollection);
     }
     if (selectedValue == null ||
         selectedValue == string.Empty ||
         optionCollection?.ContainsKey(selectedValue) == true ||
         selectedValue == "0" ||
         multiple ||
         !addSelectedValue)
     {
         return(optionCollection);
     }
     else
     {
         var userId = selectedValue.ToInt();
         optionCollection?.Add(
             selectedValue,
             column != null && column.UserColumn
                 ? new ControlData(SiteInfo.UserName(userId))
                 : new ControlData("? " + selectedValue));
         return(optionCollection);
     }
 }
示例#40
0
        /// <summary>
        /// Asynchronously load data for the provided given key.
        /// </summary>
        /// <param name="key">Key to use for loading data</param>
        /// <returns>
        /// An object representing a pending operation
        /// </returns>
        public virtual IDataLoaderResult <T> LoadAsync(TKey key)
        {
            lock (_sync)
            {
                //once it enters the lock, it is guaranteed to exit the lock, as it does not depend on external code
                if (_cachedList != null)
                {
                    if (_cachedList.TryGetValue(key, out var ret2))
                    {
                        return(ret2);
                    }
                }
                if (_list != null)
                {
                    if (_list.TryGetValue(key, out var ret2))
                    {
                        return(ret2);
                    }

                    if (_list.Count >= MaxBatchSize)
                    {
                        _list = new DataLoaderList(this);
                    }
                }
                else
                {
                    _list = new DataLoaderList(this);
                }
                var ret = new DataLoaderPair <TKey, T>(_list, key);
                _list.Add(key, ret);
                _cachedList?.Add(key, ret);
                return(ret);
            }
        }
示例#41
0
文件: Asset.cs 项目: mrvux/xenko
        /// <summary>
        /// Creates an asset that inherits from this asset.
        /// </summary>
        /// <param name="baseLocation">The location of this asset.</param>
        /// <param name="idRemapping">A dictionary in which will be stored all the <see cref="Guid"/> remapping done for the child asset.</param>
        /// <returns>An asset that inherits this asset instance</returns>
        // TODO: turn internal protected and expose only AssetItem.CreateDerivedAsset()
        public virtual Asset CreateDerivedAsset(string baseLocation, out Dictionary <Guid, Guid> idRemapping)
        {
            if (baseLocation == null)
            {
                throw new ArgumentNullException(nameof(baseLocation));
            }

            // Make sure we have identifiers for all items
            AssetCollectionItemIdHelper.GenerateMissingItemIds(this);

            // Clone this asset without overrides (as we want all parameters to inherit from base)
            var newAsset = AssetCloner.Clone(this, AssetClonerFlags.GenerateNewIdsForIdentifiableObjects, out idRemapping);

            // Create a new identifier for this asset
            var newId = AssetId.New();

            // Register this new identifier in the remapping dictionary
            idRemapping?.Add((Guid)newAsset.Id, (Guid)newId);

            // Write the new id into the new asset.
            newAsset.Id = newId;

            // Create the base of this asset
            newAsset.Archetype = new AssetReference(Id, baseLocation);
            return(newAsset);
        }
示例#42
0
        public DataTable ConvertListToDataTable <T>(DataTable dataTable, IEnumerable <T> list, HashSet <string> columns,
                                                    Dictionary <int, T> outputIdentityDic = null)
        {
            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            int counter = 0;

            foreach (T item in list)
            {
                var values = new List <object>();

                foreach (var column in columns.ToList())
                {
                    if (column == Constants.InternalId)
                    {
                        values.Add(counter);
                        outputIdentityDic?.Add(counter, item);
                    }
                    else
                    {
                        for (int i = 0; i < props.Length; i++)
                        {
                            if (props[i].Name == column && item != null &&
                                CheckForValidDataType(props[i].PropertyType, throwIfInvalid: true))
                            {
                                values.Add(props[i].GetValue(item, null));
                            }
                        }
                    }
                }
                counter++;
                dataTable.Rows.Add(values.ToArray());
            }
            return(dataTable);
        }
        public void readEntryIntoDictionary(int dict_val, string val)
        {
            string[] entry = val.Split(ENTRY_SPLIT.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            Dictionary <string, string> dict = getDictionary(dict_val);

            dict?.Add(entry[0], entry[1]);
        }
示例#44
0
        public static IHtmlContent AjaxFkFor<TModel, TResult>(this IHtmlHelper<TModel> target, Expression<Func<TModel, TResult>> expression, string repoName, string tableName, object customFilterData = null, int minSearchLength = 0, Dictionary<string, string> nameBuffer = null, string cascadeFrom = null) where TModel : class
        {
            string dataCallback = null;
            string columnName = target.DisplayNameFor(expression);
            string id = CustomActionHelper.RandomName($"FK_{repoName}_{tableName}_{columnName}");
            nameBuffer?.Add(columnName, id);
            string dataCallbackBody = null;
            var route = target.ViewContext.HttpContext.Request.RouteValues;
            string area = null;
            if (route.ContainsKey("area"))
            {
                area = (string) route["area"];
            }

            if (customFilterData != null)
            {
                dataCallback = $"ITVenture.Tools.ListCallbackHelper.dataCallbacks.{CreateDataScriptFor(repoName, tableName, columnName, customFilterData, out dataCallbackBody)}";
            }
            
            target.Raw($@"<script>
            {dataCallbackBody}
</script>").WriteTo(target.ViewContext.Writer, HtmlEncoder.Default);
            return target.EditorFor(expression, "ApiForeignKey", new Dictionary<string, object>
            {
                {$"{columnName}_RepoName", repoName},
                {$"{columnName}_TableName", tableName},
                {$"{columnName}_ID", id},
                {$"{columnName}_minLength", minSearchLength},
                {$"{columnName}_CascadeTarget", cascadeFrom},
                {$"{columnName}_DataCallback", dataCallback},
                {$"{columnName}_Area", area}
            });
        }
 private static void AddMeasurementUnits(string unit, Dictionary <string, CustomUnitDefinition> measurementUnits)
 {
     if (!string.IsNullOrWhiteSpace(unit))
     {
         measurementUnits?.Add(unit, new CustomUnitDefinition());
     }
 }
示例#46
0
    public static int Add(WebAssemblyRenderer renderer)
    {
        var id = _nextId++;

        _renderers?.Add(id, renderer);
        return(id);
    }
示例#47
0
        public void AddStat(StatType type, Stat stat)
        {
            if (_stats.ContainsKey(type))
            {
                Debug.LogWarning($"Attempt to add resource of type, which is already presented in {GetType().Name}");
                return;
            }

            _stats?.Add(type, stat);
            stat.Initialize();

            if (stat is IPlayerLoop processor)
            {
                _selfDynamicStats.Add(processor);
            }

            var statBarObj = MasterManager.Instance.InstantiateObject(
                MasterManager.Instance.LinksHolder.StatBarPrefab,
                MasterManager.Instance.LinksHolder.StatBarHud.transform);


            BarHandler handler;

            if (!statBarObj.TryGetComponent(out handler))
            {
                handler = statBarObj.AddComponent <BarHandler>();
            }
            handler.Initialize(stat, type);
            _statBars.Add(stat, handler);
        }
示例#48
0
        /// <inheritdoc/>
        public ISmsSendResult SendSms(ISms sms)
        {
            try
            {
                if (!sms?.IsValid(_smsServiceConfig) ?? true)
                {
                    throw new Exception("Invalid SMS request.");
                }

                var paramDict = new Dictionary <string, string>();
                paramDict.Add(_smsServiceConfig.MessageMask, sms.Message);
                paramDict.Add(_smsServiceConfig.RecepientMask, sms.Recepient);
                _smsServiceConfig?.RequestParameters?.ToList()?.ForEach(x => paramDict?.Add(x.Key, x.Value));
                HttpWebRequest request   = null;
                string         postData  = null;
                byte[]         postBytes = null;

                switch (_smsServiceConfig.RequestContentType)
                {
                case RequestContentType.FormData:
                    NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(string.Empty);
                    paramDict?.ToList()?.ForEach(x => outgoingQueryString.Add(x.Key, x.Value));
                    postData            = outgoingQueryString?.ToString();
                    postBytes           = _smsServiceConfig.Encoding.GetBytes(postData);
                    request             = (HttpWebRequest)WebRequest.Create(_smsServiceConfig.BaseUrl);
                    request.ContentType = "application/form-data";
                    break;

                case RequestContentType.JSON:
                    postData            = JsonConvert.SerializeObject(paramDict);
                    postBytes           = _smsServiceConfig.Encoding.GetBytes(postData);
                    request             = (HttpWebRequest)WebRequest.Create(_smsServiceConfig.BaseUrl);
                    request.ContentType = "application/json";
                    break;

                default:    //Handles Enums.RequestContentType.URL too
                    string @params = String.Join("&&", paramDict?.Select(x => $"{x.Key}={x.Value}")?.ToArray());
                    string url     = _smsServiceConfig.BaseUrl + '?' + @params;
                    request = (HttpWebRequest)WebRequest.Create(url);
                    break;
                }

                request.Method = _smsServiceConfig.RequestMethod.Method;
                if (postBytes != null)
                {
                    using (var stream = request.GetRequestStream())
                    {
                        stream.Write(postBytes, 0, postBytes.Length);
                    }
                }

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                return(new SmsSendResult(sms.Recepient, response.StatusCode, response.GetResponseStream()));
            }
            catch (Exception e)
            {
                return(new SmsSendResult(sms.Recepient, e.Message));
            }
        }
示例#49
0
 public void SetupView(string viewName, FrameworkElement view, ViewModelBase viewModel)
 {
     if (!views.Keys.Contains(viewName))
     {
         view.DataContext = viewModel;
         views?.Add(viewName, view);
     }
 }
示例#50
0
 public void Add(T proto)
 {
     if (proto == null || proto.Type == null)
     {
         return;
     }
     _prototypes?.Add(proto.Type, proto);
 }
    //The simple method for performing a SINGLE request as given. The database accesses are timed...
    protected async Task <QueryResultSet> SearchSingle(
        SearchRequest request,
        Dictionary <string, object> parameterValues,
        Dictionary <string, double>?timedic = null)
    {
        await queryLock.WaitAsync();

        try
        {
            //Need to limit the 'limit'!
            var reqplus = queryBuilder.FullParseRequest(request, parameterValues);

            if (config.LogSql)
            {
                logger.LogDebug($"Running SQL for {request.type}({request.name}): {reqplus.computedSql}");
            }

            //Warn: we repeatedly do this because the FullParseRequest CAN modify parameter values
            var dp = new DynamicParameters(parameterValues);

            var timer = new Stopwatch();

            timer.Restart();
            var qresult = await QueryAsyncCast(reqplus.computedSql, dp);

            timer.Stop();

            timedic?.Add(request.name, timer.Elapsed.TotalMilliseconds);

            //We also want to time extra fields
            timer.Restart();
            //Just because we got the qresult doesn't mean we can stop! if it's content, we need
            //to fill in the values, keywords, and permissions!
            await AddExtraFields(reqplus, qresult);

            timer.Stop();

            timedic?.Add($"{request.name}_extras", timer.Elapsed.TotalMilliseconds);

            return(qresult);
        }
        finally
        {
            queryLock.Release();
        }
    }
        public static Rollout[] Winner(Policy policy, Policy adversary, bool storeRollout = false)
        {
            Policy[] teamPolicies = new[] { policy, adversary };

            return(WorldGenerator.AllMatchups().AsParallel().Select(matchup => {
                World current = WorldGenerator.GenerateInitial(matchup.Team0, matchup.Team1);

                // Debug.WriteLine("Simulating " + matchup.ToString());
                List <RolloutTick> ticks = storeRollout ? new List <RolloutTick>() : null;
                int?winner = null;
                while (winner == null)
                {
                    Dictionary <int, Tactic> heroTactics = storeRollout ? new Dictionary <int, Tactic>() : null;

                    Dictionary <int, GameAction> actions = new Dictionary <int, GameAction>();
                    Simulator.AddEnvironmentalActions(current, actions);
                    foreach (Unit unit in current.Units)
                    {
                        if (unit.UnitType == UnitType.Hero)
                        {
                            Tactic tactic = PolicyEvaluator.Evaluate(current, unit, teamPolicies[unit.Team]);
                            actions[unit.UnitId] = PolicyEvaluator.TacticToAction(current, unit, tactic);

                            heroTactics?.Add(unit.UnitId, tactic);
                        }
                    }
                    ticks?.Add(new RolloutTick {
                        HeroTactics = heroTactics,
                        World = current,
                    });

                    current = Simulator.Forward(current, actions);

                    winner = current.Winner();
                }

                double winRate;
                if (winner == 0)
                {
                    winRate = 1.0;
                }
                else if (winner == 1)
                {
                    winRate = 0.0;
                }
                else
                {
                    winRate = 0.5;
                }
                return new Rollout {
                    Matchup = matchup,
                    WinRate = winRate,
                    Ticks = ticks,
                    FinalWorld = storeRollout ? current : null,
                    FinalEvaluation = IntermediateEvaluator.Evaluate(current, 0),
                };
            }).ToArray());
        }
        public override List <XmlReader> GetReaders(
            Dictionary <MetadataArtifactLoader, XmlReader> sourceDictionary)
        {
            List <XmlReader> xmlReaderList = new List <XmlReader>();

            xmlReaderList.Add(this._reader);
            sourceDictionary?.Add((MetadataArtifactLoader)this, this._reader);
            return(xmlReaderList);
        }
示例#54
0
        private bool ParseRouteHelper(string route, Dictionary <string, object> variables)
        {
            int pos = 0;

            for (int i = 0; i < mParts.Count; ++i)
            {
                PathPart pp = mParts[i];
                switch (pp.Kind)
                {
                case PathPartKind.StaticPath:
                {
                    string path = pp.Name;
                    for (int subPos = 0; subPos < path.Length; ++subPos)
                    {
                        if (pos + subPos >= route.Length || route[pos + subPos] != path[subPos])
                        {
                            return(false);
                        }
                    }

                    pos += path.Length;
                }
                break;

                case PathPartKind.UserItem:
                {
                    StringBuilder value = new StringBuilder();
                    while (pos < route.Length && route[pos] != '/')
                    {
                        value.Append(route[pos]);
                        ++pos;
                    }

                    Object arg = CreateArgForType(value.ToString(), pp.Type);
                    if (arg == null)
                    {
                        return(false);
                    }

                    if (variables?.ContainsKey(pp.Name) == true)
                    {
                        throw new ArgumentException($"Duplicately named variable {pp.Name} in route {route}");
                    }

                    variables?.Add(pp.Name, arg);
                }
                break;

                // TODO: implement this
                case PathPartKind.VariablePath:
                default:
                    throw new InvalidOperationException("Unknown type in ParseRouteHelper.");
                }
            }

            return(pos == route.Length);
        }
示例#55
0
        //public static readonly RadioModel Null = new RadioModel() { };
        /// <summary>
        /// 根据虾米ID获取一个新的<see cref="RadioModel"/>实例,如果已经创建过则返回这个实例
        /// </summary>
        /// <param name="xiamiID">标志<see cref="RadioModel"/>的虾米ID</param>
        /// <returns></returns>
        public static RadioModel GetNew(uint xiamiID)
        {
            RadioModel radio = null;

            if (!(_dict?.TryGetValue(xiamiID, out radio) ?? false))
            {
                var type = RadioType.UnKnown;
                var oid  = 0u;
                ExtensionMethods.InvokeAndWait(async() =>
                {
                    var res = await WebApi.Instance.GetRadioType(xiamiID);
                    type    = res.Item1; oid = res.Item2;
                });
                radio = new RadioModel(xiamiID, type, oid);
                _dict?.Add(xiamiID, radio);
            }
            return(radio);
        }
示例#56
0
        //注册
        public void AddListener(TEventType eventType, Handle listener)
        {
            if (_listeners.TryGetValue(eventType, out var temp))
            {
                return;
            }

            _listeners?.Add(eventType, listener);
        }
示例#57
0
        public void SetValues(Dictionary <string, object> propertyNameValuePairs, object objectToBeUpdated, Type propertyType, Dictionary <object, object> objectPropertyNameValuePairs, bool handleComplexTypeCollections = false)
        {
            objectPropertyNameValuePairs?.Add(objectToBeUpdated, propertyNameValuePairs);

            foreach (var propertyNameValuePair in propertyNameValuePairs)
            {
                SetValue(objectToBeUpdated, propertyNameValuePair, objectPropertyNameValuePairs, handleComplexTypeCollections);
            }
        }
        public static bool TryAdd <TKey, TValue>(this Dictionary <TKey, TValue> source, TKey key, TValue value)
        {
            if (source.ContainsKey(key))
            {
                return(false);
            }

            source?.Add(key, value);
            return(true);
        }
示例#59
0
        /// <inheritdoc />
        public async Task <int?> AddNewTravelAsync(CreateTravel newTravel)
        {
            if (newTravel == null)
            {
                throw new ArgumentNullException(nameof(newTravel));
            }

            int?countryId = await GetCountryIdAsync(newTravel.Country).ConfigureAwait(false);

            if (!countryId.HasValue)
            {
                throw new ArgumentException(nameof(newTravel.Country));
            }



            int?townId = await GetTownIdAsync(newTravel.Town, countryId.Value).ConfigureAwait(false);

            if (!townId.HasValue)
            {
                townId = await InsertTownAsync(newTravel.Town, countryId.Value).ConfigureAwait(false);
            }

            using var db = _getDb();
            var results = await db
                          .QueryAsync <int>(InsertNoces,
                                            new
            {
                newTravel.Description,
                newTravel.Name,
                newTravel.Departure,
                newTravel.Price,
                Town = townId,
                newTravel.Picture
            }, commandType : CommandType.StoredProcedure)
                          .ConfigureAwait(false);

            var id = results?.FirstOrDefault();

            if (id.HasValue)
            {
                _travelsCache?.Add(id.Value, new CatalogTravel
                {
                    Name      = newTravel.Name,
                    Departure = newTravel.Departure,
                    Country   = newTravel.Country,
                    Price     = newTravel.Price,
                    Town      = newTravel.Town,
                    Id        = id.Value,
                    Picture   = newTravel.Picture
                });
            }

            return(id);
        }
示例#60
0
 private void ReadDataFile()
 {
     using (var reader = new StreamReader(CreatorDefault.PathAward))
     {
         while (reader.Peek() >= 0)
         {
             var award = JsonConvert.DeserializeObject <Award>(reader.ReadLine());
             awards?.Add(award.ID, award);
         }
     }
 }