示例#1
0
        //also reference to Algorithm.TreeAndGraph.Floyd and Algorithm.TreeAndGraph.Dijkstra
        public static int getShortestDistance(TreeAndGraph.GraphNode start, TreeAndGraph.GraphNode end)
        {
            System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<TreeAndGraph.GraphNode>> tab
                = new System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<TreeAndGraph.GraphNode>>();
            System.Collections.Generic.List<TreeAndGraph.GraphNode> list = new System.Collections.Generic.List<TreeAndGraph.GraphNode>();
            int count = 1;
            list.Add(start);
            tab.Add(count, list);
            while (true)
            {
                System.Collections.Generic.List<TreeAndGraph.GraphNode> gn_list = tab[count];
                ++count;
                if (!tab.ContainsKey(count))
                {
                    list = new System.Collections.Generic.List<TreeAndGraph.GraphNode>();
                    tab.Add(count, list);
                }
                foreach (TreeAndGraph.GraphNode gn in gn_list)
                {

                    foreach (TreeAndGraph.GraphNode node in gn.Nodes)
                    {
                        if (node == end)
                        {
                            return count;
                        }

                        tab[count].Add(node);
                    }
                }
            }
        }
示例#2
0
 protected override bool DecodePacket(MessageStructure reader, MessageHead head)
 {
     responsePack = ProtoBufUtils.Deserialize<Response1010Pack>(netReader.Buffer);
     string responseDataInfo = "";
     responseDataInfo = "request :" + Game.Utils.JsonHelper.prettyJson<Request1010Pack>(req) + "\n";
     responseDataInfo += "response:" + Game.Utils.JsonHelper.prettyJson<Response1010Pack>(responsePack) + "\n";
     DecodePacketInfo = responseDataInfo;
     int childStepId = getChild(1010);
     System.Console.WriteLine("childStepID:" + childStepId);
     if (childStepId > 0)
     {
         System.Collections.Generic.Dictionary<string, string> dic = new System.Collections.Generic.Dictionary<string, string>();
         /*
           req.UserID = GetParamsData("UserID", req.UserID);
         req.identify = GetParamsData("identify", req.identify);
         req.version = GetParamsData("version", req.version);
         req.the3rdUserID = GetParamsData("the3rdUserID", req.the3rdUserID);
         req.happyPoint = GetParamsData("happyPoint", req.happyPoint);
         req.Rate = GetParamsData("Rate", req.Rate);
         req.index = GetParamsData("index", req.index);
         req.strThe3rdUserID = GetParamsData("strThe3rdUserID", req.strThe3rdUserID);
         req.typeUser = GetParamsData("typeUser", req.typeUser);
          */
         dic.Add("UserID", req.UserID.ToString());
         dic.Add("index", responsePack.index.ToString());
         dic.Add("the3rdUserID", req.the3rdUserID.ToString());
         dic.Add("strThe3rdUserID", req.strThe3rdUserID);
        SetChildStep(childStepId.ToString(), _setting,dic);
     }
     return true;
 }
示例#3
0
        public static System.Collections.Generic.Dictionary<System.Int16, System.Collections.Generic.List<BinaryTreeNode>> getLevelLinkedList(BinaryTreeNode head)
        {
            System.Collections.Generic.Dictionary<System.Int16, System.Collections.Generic.List<BinaryTreeNode>> result
                = new System.Collections.Generic.Dictionary<System.Int16, System.Collections.Generic.List<BinaryTreeNode>>();
            short level = 0;
            System.Collections.Generic.List<BinaryTreeNode> list = new System.Collections.Generic.List<BinaryTreeNode>();
            list.Add(head);
            result.Add(level, list);

            while (true)
            {
                System.Collections.Generic.List<BinaryTreeNode> list_loop = result[level];
                list = new System.Collections.Generic.List<BinaryTreeNode>();
                result.Add(++level, list);
                foreach (BinaryTreeNode btn in list_loop)
                {
                    if (btn.LeftNode != null)
                    {
                        list.Add(btn.LeftNode);
                    }
                    if (btn.RightNode != null)
                    {
                        list.Add(btn.RightNode);
                    }
                }
                if (list.Count == 0)
                {
                    break;
                }
            }
            return result;
        }
示例#4
0
 /// <summary>
 /// Serialises the keys object as a media-storage-query-compatible, JSON-friendly data-structure.
 /// </summary>
 /// <returns>
 /// A JSON-friendly dictionary representation of the keys object in its current state.
 /// </returns>
 internal virtual System.Collections.Generic.IDictionary<string, object> ToDictionary()
 {
     System.Collections.Generic.IDictionary<string, object> dictionary = new System.Collections.Generic.Dictionary<string, object>();
     dictionary.Add("read", this.Read);
     dictionary.Add("write", this.Write);
     return dictionary;
 }
 //Add attack's with their related game object here as below. The key is a string of the attack's name.
 void Start()
 {
     bounceOrbName = "blackOrbAttack";
     unblockAbleOrbName = "unblockableAttack";
     projectiles = new System.Collections.Generic.Dictionary<string, Rigidbody2D>();
     projectiles.Add(bounceOrbName, bounceOrb);
     projectiles.Add(unblockAbleOrbName, unblockableOrb);
 }
示例#6
0
        // Local output parameter s must not be initialized
        public void test657()
        {
			var dict2 = new System.Collections.Generic.Dictionary<NUMBER, string>(); 
			dict2.Add(NUMBER.ONE, "One"); 
			dict2.Add(NUMBER.TWO, "Two"); 
			string s = "-"; 
			dict2.TryGetValue(NUMBER.TWO, out s); 
			AssertEquals(s, "Two");
        }
示例#7
0
		// Local output parameter s must not be initialized
		public void test656_int() 
		{
			var dict2 = new System.Collections.Generic.Dictionary<int, int>(); 
			dict2.Add(1, 100); 
			dict2.Add(2, 200); 
			int s;
			dict2.TryGetValue(2, out s); 
			AssertEquals(s, 200);
		}
示例#8
0
		// Local output parameter s must not be initialized
		public void test656() 
		{
			var dict2 = new System.Collections.Generic.Dictionary<int, string>(); 
			dict2.Add(1, "One"); 
			dict2.Add(2, "Two"); 
			string s; // = "-"; 
			dict2.TryGetValue(2, out s); 
			AssertEquals(s, "Two");
		}
示例#9
0
        public string ToRelative(string DateString)
        {
            DateTime theDate = Convert.ToDateTime(DateString);
            System.Collections.Generic.Dictionary<long, string> thresholds = new System.Collections.Generic.Dictionary<long, string>();
            int minute = 60;
            int hour = 60 * minute;
            int day = 24 * hour;
            thresholds.Add(60, "{0} seconds ago");
            thresholds.Add(minute * 2, "a minute ago");
            thresholds.Add(45 * minute, "{0} minutes ago");
            thresholds.Add(120 * minute, "an hour ago");
            thresholds.Add(day, "{0} hours ago");
            thresholds.Add(day * 2, "yesterday");
            // thresholds.Add(day * 30, "{0} days ago");
            thresholds.Add(day * 365, "{0} days ago");
            thresholds.Add(long.MaxValue, "{0} years ago");

            long since = (DateTime.Now.Ticks - theDate.Ticks) / 10000000;
            foreach (long threshold in thresholds.Keys)
            {
                if (since < threshold)
                {
                    TimeSpan t = new TimeSpan((DateTime.Now.Ticks - theDate.Ticks));
                    return string.Format(thresholds[threshold], (t.Days > 365 ? t.Days / 365 : (t.Days > 0 ? t.Days : (t.Hours > 0 ? t.Hours : (t.Minutes > 0 ? t.Minutes : (t.Seconds > 0 ? t.Seconds : 0))))).ToString());
                }
            }
            return "";
        }
示例#10
0
        private static System.Collections.Generic.Dictionary<IJobDetail, ISet<ITrigger>> CreateJobs(int[] intervals)
        {
            Log.Info("Building jobs");

            var jobDictionary = new System.Collections.Generic.Dictionary<IJobDetail, ISet<ITrigger>>();

            for (var index = 0; index < intervals.Length; index++)
            {
                var interval = intervals[index];
                Log.InfoFormat("Creating Job {0} with interval {1}...", index, interval);

                var job =
                    JobBuilder.Create<SendMessageJob>()
                        .WithIdentity("sendMessageJob" + index)
                        .UsingJobData("message", $"Job {index} with interval {interval} from process {Process.GetCurrentProcess().Id}")
                        .Build();

                var trigger =
                    TriggerBuilder.Create()
                        .WithIdentity("trigger" + index)
                        .StartNow()
                        .WithSimpleSchedule(x => x.WithIntervalInSeconds(interval).RepeatForever())
                        .Build();

                var set = new HashSet<ITrigger> { trigger };

                jobDictionary.Add(job, set);
            }

            return jobDictionary;
        }
        private void SetHourData(Models.Student student, ExcelWorksheet worksheet)
        {
            var collector = new System.Collections.Generic.Dictionary<SpreadsheetExport.Key, int>();
            foreach (var b in student.Behaviors) {
                var key = new SpreadsheetExport.Key { DayOfWeek = b.TimeRecorded.DayOfWeek.ToString(), Hour = b.TimeRecorded.Hour };
                if (collector.ContainsKey(key))
                    collector[key] += 1;
                else
                    collector.Add(key, 1);

            }
            foreach (var key in collector.Keys) {
                var value = key.Hour - 2;
                switch (key.DayOfWeek.ToString()) {
                    case "Monday": worksheet.Cells[5, value].Value = collector[key];
                        break;
                    case "Tuesday": worksheet.Cells[6, value].Value = collector[key];
                        break;
                    case "Wednesday": worksheet.Cells[7, value].Value = collector[key];
                        break;
                    case "Thursday": worksheet.Cells[8, value].Value = collector[key];
                        break;
                    case "Friday": worksheet.Cells[9, value].Value = collector[key];
                        break;
                    default:
                        break;
                }
            }
        }
示例#12
0
文件: GameControl.cs 项目: Janin-K/SG
 private void saveInitialPositions()
 {
     initialPositions = new System.Collections.Generic.Dictionary<int, Vector3>();
     foreach(GameObject obj in GameObject.FindGameObjectsWithTag("respawn")) {
         initialPositions.Add(obj.GetInstanceID(), obj.rigidbody.position);
     }
 }
示例#13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            CommandParameters cp = new CommandParameters();
            cp.CommandName = "MC_Workspace_AddControl";

            System.Collections.Generic.Dictionary<string, string> dic = new System.Collections.Generic.Dictionary<string, string>();
            dic.Add("ColumnId", "%columnId%");
            dic.Add("PageUid", "%pageUid%");

            cp.CommandArguments = dic;
            if (this.IsAdmin)
                this.OnClickCommandScript = CommandManager.GetCurrent(this.Page).AddCommand(string.Empty, string.Empty, "WorkspaceAdmin", cp);
            else
                this.OnClickCommandScript = CommandManager.GetCurrent(this.Page).AddCommand(string.Empty, string.Empty, "Workspace", cp);
            //clickDiv.Attributes.Add("onclick", this.OnClickCommandScript);
        }
        // CONSTRUCTOR ---------------------------------------------------------------------------------------
        public AnimationGlitchSpriteSingleton()
        {
            if(!isOkToCreate) Console.WriteLine (this + "is a singleton. Use get instance");
            if(isOkToCreate){
                FileStream fileStream = File.OpenRead("/Application/assets/animation/leftGlitch/leftOneLine.xml");
                StreamReader fileStreamReader = new StreamReader(fileStream);
                string xml = fileStreamReader.ReadToEnd();
                fileStreamReader.Close();
                fileStream.Close();
                XDocument doc = XDocument.Parse(xml);

                var lines = from sprite in doc.Root.Elements("sprite")
                    select new {
                        Name = sprite.Attribute("n").Value,
                        X1 = (int)sprite.Attribute ("x"),
                        Y1 = (int)sprite.Attribute ("y"),
              			Height = (int)sprite.Attribute ("h"),
              			Width = (int)sprite.Attribute("w"),
            };

               				_sprites = new Dictionary<string,Sce.PlayStation.HighLevel.GameEngine2D.Base.Vector2i>();
                foreach(var curLine in lines)
                {
                    _sprites.Add(curLine.Name,new Vector2i((curLine.X1/curLine.Width),(curLine.Y1/curLine.Height)));
                //note if you add more than one line of sprites you must do this
                // _sprites.Add(curLine.Name,new Vector2i((curLine.X1/curLine.Width),1-(curLine.Y1/curLine.Height)));
                //where 9 is the num of rows minus 1 to reverse the order :/
               			}
               				_texture = new Texture2D("/Application/assets/animation/leftGlitch/leftOneLine.png", false);
               				_textureInfo = new TextureInfo(_texture,new Vector2i(5,1));
            }
              		if(!isOkToCreate) {
                Console.WriteLine("this is a singleton. access via get Instance");
            }
        }
        public string GetSystemData()
        {
            string str;
            UserInfo user;
            if (IsAuthenticated(out str) && GetUser(out user, ref str))
            {
                str += string.Format(", \"profile\": {{ \"userid\":{0}, \"displayname\":\"{1}\", \"image\":\"{2}\", \"IsSuperuser\":{3} }}, \"contacts\":[",
                    user.UserID, user.DisplayName, user.Image, user.IsSuperuser.ToString().ToLower());
                System.Collections.Generic.Dictionary<int, string> contacts = new System.Collections.Generic.Dictionary<int, string>();
                foreach (ContactInfo info in ContactInfo.GetContacts(user.UserID))
                {
                    UserInfo contactuser = UserInfo.Get(info.ContactID);
                    if (!contacts.ContainsKey(info.GroupID))
                        contacts.Add(info.GroupID, "{ \"groupid\": " + info.GroupID + ", \"groupname\": \"" + info.GroupName + "\", \"users\":[");
                    contacts[info.GroupID] += contactuser.ToJSON() + ",";
                }
                foreach (System.Collections.Generic.KeyValuePair<int, string> g in contacts)
                    str += g.Value.Remove(g.Value.Length - 1) + "] },";

                str = str.Remove(str.Length - 1) + "], \"topics\": [ ";
                foreach (TopicInfo info in TopicInfo.GetByUser(user.UserID))
                    str += string.Format("{{ \"id\":{0}, \"title\":\"{1}\" }},", info.TopicID, info.GetTitle());

                str = str.Remove(str.Length - 1) + "]";
            }
            return str;
        }
示例#16
0
        public void TestCompression()
        {
            System.Collections.Generic.Dictionary<string, string> dic = new System.Collections.Generic.Dictionary<string, string>();

            for (int i = 0; i < 10001; i++)
            {
                dic.Add(Guid.NewGuid().ToString(), Guid.NewGuid().ToString() + "::" + Properties.Settings.Default.Value_Text + "::" + Guid.NewGuid().ToString());
            }

            byte[] source_byte = Utility.Serialize(dic);
            byte[] dest_byte = Utility.Deflate(source_byte, System.IO.Compression.CompressionMode.Compress);


            byte[] dest_byte_2 = Utility.Deflate(dest_byte, System.IO.Compression.CompressionMode.Decompress);

            for (int i = 0; i < source_byte.Length; i++)
            {
                if (source_byte[i] != dest_byte_2[i])
                {
                    Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Fail("Byte Array Error...");
                    break;
                }
            }

        }
示例#17
0
    static void Main(string[] args)
    {
        var env = new System.Collections.Generic.Dictionary<string, int>();
        env.Add("z",5);
        env.Add("x",2);

        Expr e1 = new Add(new CstI(17), new Var("z")).Simplify();
        Expr e2 = new Mul(new Var("x"), new Var("z")).Simplify();
        Expr e3 = new Sub(new Mul(new CstI(17), new CstI(5)), new Var("z")).Simplify();
        Expr e4 = new Add(new CstI(17), new CstI(0)).Simplify();

        System.Console.Out.WriteLine(e1.ToString() + " = " + e1.Eval(env));
        System.Console.Out.WriteLine(e2.ToString() + " = " + e2.Eval(env));
        System.Console.Out.WriteLine(e3.ToString() + " = " + e3.Eval(env));
        System.Console.Out.WriteLine(e4.ToString() + " = " + e4.Eval(env));
        System.Console.ReadLine();
    }
        internal static System.Collections.Generic.Dictionary<string, string> ToDictionary(DatasetSurfaceAnalystParameters datasetSurfaceAnalystParams)
        {
            var dict = new System.Collections.Generic.Dictionary<string, string>();

            if (datasetSurfaceAnalystParams.ParametersSetting != null)
            {
                dict.Add("extractParameter", SurfaceAnalystParametersSetting.ToJson(datasetSurfaceAnalystParams.ParametersSetting));
            }
            else
            {
                dict.Add("extractParameter", SurfaceAnalystParametersSetting.ToJson(new SurfaceAnalystParametersSetting()));
            }

            string resultSetting = string.Format("\"dataReturnMode\":\"RECORDSET_ONLY\",\"expectCount\":{0}", datasetSurfaceAnalystParams.MaxReturnRecordCount);
            resultSetting = "{" + resultSetting + "}";
            dict.Add("resultSetting", resultSetting);

            if (datasetSurfaceAnalystParams.FilterQueryParam != null)
            {
                dict.Add("filterQueryParameter", FilterParameter.ToJson(datasetSurfaceAnalystParams.FilterQueryParam));
            }

            if (!string.IsNullOrEmpty(datasetSurfaceAnalystParams.ZValueFieldName) && !string.IsNullOrWhiteSpace(datasetSurfaceAnalystParams.ZValueFieldName))
            {
                dict.Add("zValueFieldName", "\"" + datasetSurfaceAnalystParams.ZValueFieldName + "\"");
            }
            else
            {
                dict.Add("zValueFieldName","\"\"");
            }

            dict.Add("resolution", datasetSurfaceAnalystParams.Resolution.ToString());
            return dict;
        }
        internal static System.Collections.Generic.Dictionary<string, string> ToDictionary(DatasetBufferAnalystParameters datasetBufferParams)
        {
            System.Collections.Generic.Dictionary<string, string> dict = new System.Collections.Generic.Dictionary<string, string>();
            dict.Add("isAttributeRetained", datasetBufferParams.IsAttributeRetained.ToString().ToLower());
            dict.Add("isUnion", datasetBufferParams.IsUnion.ToString().ToLower());

            string dataReturnOption = "{\"dataReturnMode\": \"RECORDSET_ONLY\",\"deleteExistResultDataset\": true,";
            dataReturnOption += string.Format("\"expectCount\":{0}", datasetBufferParams.MaxReturnRecordCount);
            dataReturnOption += "}";
            dict.Add("dataReturnOption", dataReturnOption);

            if (datasetBufferParams.FilterQueryParameter != null)
            {
                dict.Add("filterQueryParameter", FilterParameter.ToJson(datasetBufferParams.FilterQueryParameter));
            }
            else
            {
                dict.Add("filterQueryParameter", FilterParameter.ToJson(new FilterParameter()));
            }

            if (datasetBufferParams.BufferSetting != null)
            {
                dict.Add("bufferAnalystParameter", BufferSetting.ToJson(datasetBufferParams.BufferSetting));
            }
            else
            {
                dict.Add("bufferAnalystParameter", BufferSetting.ToJson(new BufferSetting()));
            }

            return dict;
        }
        public void GenerateUrl_should_return_correct_url_for_controller_and_action_with_specific_Area()
        {
            Mock<INavigatable> navigationItem = new Mock<INavigatable>();

            System.Collections.Generic.Dictionary<string, object> dictionary = new System.Collections.Generic.Dictionary<string,object>();
            dictionary.Add("id", 1);
            dictionary.Add("Area", "Test");

            var routeValues = new RouteValueDictionary(dictionary);

            navigationItem.SetupGet(item => item.ControllerName).Returns("Product");
            navigationItem.SetupGet(item => item.ActionName).Returns("Detail");
            navigationItem.SetupGet(item => item.RouteValues).Returns(routeValues);

            string url = _urlGenerator.Generate(TestHelper.CreateRequestContext(), navigationItem.Object);

            Assert.Contains("Products/Detail/1?Area=Test", url);
        }
示例#21
0
        public void ForceBuildShouldNotWorkWhenProjectIsStopped()
        {
            const string projectName1 = "test02";

            IntegrationCompleted = new System.Collections.Generic.Dictionary<string, bool>();

            string IntegrationFolder = System.IO.Path.Combine("scenarioTests", projectName1);
            string CCNetConfigFile = System.IO.Path.Combine("IntegrationScenarios", "Simple.xml");
            string Project1StateFile = new System.IO.FileInfo(projectName1 + ".state").FullName;

            IntegrationCompleted.Add(projectName1, false);

            Log("Clear existing state file, to simulate first run : " + Project1StateFile);
            System.IO.File.Delete(Project1StateFile);

            Log("Clear integration folder to simulate first run");
            if (System.IO.Directory.Exists(IntegrationFolder)) System.IO.Directory.Delete(IntegrationFolder, true);


            CCNet.Remote.Messages.ProjectRequest pr1 = new CCNet.Remote.Messages.ProjectRequest(null, projectName1);


            Log("Making CruiseServerFactory");
            CCNet.Core.CruiseServerFactory csf = new CCNet.Core.CruiseServerFactory();
            bool ErrorOccured = false;
            Log("Making cruiseServer with config from :" + CCNetConfigFile);
            using (var cruiseServer = csf.Create(true, CCNetConfigFile))
            {
                cruiseServer.ProjectStarting += new EventHandler<ThoughtWorks.CruiseControl.Remote.Events.CancelProjectEventArgs>(cruiseServer_ProjectStarting);

                Log("Starting cruiseServer");
                cruiseServer.Start();

                cruiseServer.ProjectStarting -= new EventHandler<ThoughtWorks.CruiseControl.Remote.Events.CancelProjectEventArgs>(cruiseServer_ProjectStarting);


                Log("Stopping project " + projectName1);
                cruiseServer.Stop(pr1);

                System.Threading.Thread.Sleep(250); // give time to stop the build

                Log("Forcing build on project " + projectName1);
                try
                {
                    CheckResponse(cruiseServer.ForceBuild(pr1));
                }
                catch (Exception e)
                {
                    ErrorOccured = true;

                    Assert.AreEqual(e.Message, "Project is stopping / stopped - unable to start integration");
                }

                Assert.IsTrue(ErrorOccured, "Force build should raise exception when forcing build and project is stopping or stopped");
            }

        }
示例#22
0
        public void ProcessRequest(HttpContext context)
        {
            NFMT.Common.UserModel user = Utility.UserUtility.CurrentUser;

            int status = -1;
            int pageIndex = 1, pageSize = 10;
            string orderStr = string.Empty, whereStr = string.Empty;

            string key = context.Request["k"];//模糊搜索

            if (!string.IsNullOrEmpty(context.Request["s"]))
                int.TryParse(context.Request["s"], out status);//状态查询条件

            if (!string.IsNullOrEmpty(context.Request.QueryString["pagenum"]))
                int.TryParse(context.Request.QueryString["pagenum"], out pageIndex);
            pageIndex++;
            if (!string.IsNullOrEmpty(context.Request.QueryString["pagesize"]))
                int.TryParse(context.Request.QueryString["pagesize"], out pageSize);

            if (!string.IsNullOrEmpty(context.Request.QueryString["sortdatafield"]) && !string.IsNullOrEmpty(context.Request.QueryString["sortorder"]))
                orderStr = string.Format("{0} {1}", context.Request.QueryString["sortdatafield"].Trim(), context.Request.QueryString["sortorder"].Trim());

            NFMT.User.BLL.BlocBLL blocBLL = new NFMT.User.BLL.BlocBLL();
            NFMT.Common.SelectModel select = blocBLL.GetSelectModel(pageIndex, pageSize, orderStr, status, key);
            NFMT.Common.ResultModel result = blocBLL.Load(user, select);

            context.Response.ContentType = "application/json; charset=utf-8";
            if (result.ResultStatus != 0)
            {
                context.Response.Write(result.Message);
                context.Response.End();
            }

            System.Data.DataTable dt = result.ReturnValue as System.Data.DataTable;
            System.Collections.Generic.Dictionary<string, object> dic = new System.Collections.Generic.Dictionary<string, object>();

            dic.Add("count", result.AffectCount);
            dic.Add("data", dt);

            string postData = Newtonsoft.Json.JsonConvert.SerializeObject(dic);

            context.Response.Write(postData);
        }
示例#23
0
        public static string HtmlDecode(string text)
        {
            if (decodeRegex == null)
            {                
                replacements = new System.Collections.Generic.Dictionary<string, string>(4);
                replacements.Add("&quot;", @"""");
                replacements.Add("&lt;", "<");
                replacements.Add("&gt;", ">");
                replacements.Add("&amp;", "&");

                decodeRegex = new Regex("(" + String.Join("|", replacements.Keys.ToArray()) + ")", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.Multiline);
            }

            return decodeRegex.Replace
                (
                    text,                                    
                    delegate(Match m) { return replacements[m.Value]; }
                );            
        }
示例#24
0
        public void ShouldBeRandom()
        {
            System.Collections.Generic.Dictionary<String, String> dict = new System.Collections.Generic.Dictionary<string, string>();
            for (int i = 0; i < 9999; i++)
            {
                String gen = RandomString.Generate();
                dict.Add(gen, gen);
            }

            Assert.AreEqual(9999, dict.Count);
        }
示例#25
0
        public void TestCompareBetweenDifferentTypes()
        {
            var row = new System.Collections.Generic.Dictionary<string, object>();

            short id = 1;
            row.Add("MyID", id);

            var current = "MyID is {% if MyID == 1 %}1{%endif%}";
            var parse = DotLiquid.Template.Parse(current);
            var parsedOutput = parse.Render(new RenderParameters() { LocalVariables = Hash.FromDictionary(row) });
            Assert.AreEqual("MyID is 1", parsedOutput);
        }
示例#26
0
        public frmItems()
        {
            InitializeComponent();

            listEditors = new System.Collections.Generic.Dictionary<EditorType, TableIO>();

            listEditors.Add(EditorType.Items, initializeItems());
            // TODO: Add other editors here
            setEditor(EditorType.Items);

            // TODO: Checksum the current DB schema and if need-be call: generateDatabaseEnumerations();
        }
 internal static System.Collections.Generic.Dictionary<string, string> ToDictionary(GeometryThiessenAnalystParameters geometryThiessenParams)
 {
     System.Collections.Generic.Dictionary<string, string> dict = new System.Collections.Generic.Dictionary<string, string>();
     if (geometryThiessenParams.ClipRegion != null)
     {
         dict.Add("clipRegion", ServerGeometry.ToJson(geometryThiessenParams.ClipRegion));
     }
     dict.Add("createResultDataset", geometryThiessenParams.CreateResultDataset.ToString(System.Globalization.CultureInfo.InvariantCulture).ToLower());
     dict.Add("resultDatasetName", geometryThiessenParams.ResultDatasetName.ToString(System.Globalization.CultureInfo.InvariantCulture));
     dict.Add("resultDatasourceName", geometryThiessenParams.ResultDatasourceName.ToString(System.Globalization.CultureInfo.InvariantCulture));
     dict.Add("returnResultRegion", geometryThiessenParams.ReturnResultRegion.ToString(System.Globalization.CultureInfo.InvariantCulture).ToLower());
     if (geometryThiessenParams.Points.Count > 0)
     {
         string points_str = "[";
         int count = geometryThiessenParams.Points.Count;
         for (int i = 0; i < count; i++)
         {
             Point2D point = geometryThiessenParams.Points[i];
             var point_str = "{";
             point_str+=String.Format("\"y\":{0},\"x\":{1}", point.Y, point.X);
             point_str += "}";
             points_str += point_str;
             if (i == count - 1)
             {
                 points_str += "]";                    }
             else
             {
                 points_str+=",";
             }
         }
         dict.Add("points", points_str);
     }
     return dict;
 }
        internal static System.Collections.Generic.Dictionary<string, string> ToDictionary(GeometryBufferAnalystParameters geometryBufferParams)
        {
            var dict = new System.Collections.Generic.Dictionary<string, string>();
            if (geometryBufferParams.BufferSetting != null)
            {
                dict.Add("analystParameter", BufferSetting.ToJson(geometryBufferParams.BufferSetting));
            }
            else
            {
                dict.Add("analystParameter", BufferSetting.ToJson(new BufferSetting()));
            }

            if (geometryBufferParams.SourceGeometry != null)
            {
                dict.Add("sourceGeometry", ServerGeometry.ToJson(geometryBufferParams.SourceGeometry.ToServerGeometry()));
            }
            else
            {
                dict.Add("sourceGeometry", ServerGeometry.ToJson(new ServerGeometry()));
            }
            return dict;
        }
示例#29
0
        /// <summary>
        /// 动态编译代码到dll
        /// </summary>
        /// <param name="reference">要引用的程序集(文件形式,如:System.dll)</param>
        /// <param name="outputAssembly">程序集的输出目录</param>
        /// <param name="codeSource">要编译的代码</param>
        /// <returns></returns>
        public bool Complier(string[] reference, string outputAssembly, string codeSource)
        {
            // 创建代码编译引擎参数
            System.Collections.Generic.IDictionary<string, string> dic = new System.Collections.Generic.Dictionary<string, string>();

            dic.Add("CompilerVersion", "v4.0");

            // 创建代码编译引擎
            CSharpCodeProvider cSCP = new CSharpCodeProvider(dic);

            // 代码编译参数
            CompilerParameters cPS = new CompilerParameters();


            cPS.ReferencedAssemblies.Add("system.dll");
            cPS.ReferencedAssemblies.Add("system.data.dll");
            cPS.ReferencedAssemblies.Add("system.Xml.dll");
            cPS.ReferencedAssemblies.Add((AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory) + @"\DKD.Framework.dll");
            cPS.ReferencedAssemblies.Add((AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory) + @"\DKD.Mappings.dll");
            cPS.ReferencedAssemblies.Add((AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory) + @"\DKD.SearchModel.dll");
            cPS.ReferencedAssemblies.Add((AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory) + @"\DKD.Querying.dll");


            if (reference != null)
                foreach (string s in reference)
                {
                    cPS.ReferencedAssemblies.Add(s);
                }

            cPS.GenerateExecutable = false;
            cPS.GenerateInMemory = false;
            cPS.OutputAssembly = outputAssembly;
            cPS.CompilerOptions = "/target:library /optimize";
            cPS.IncludeDebugInformation = false;
            

            // 代码编译结果
            CompilerResults cr = cSCP.CompileAssemblyFromSource(cPS, codeSource);


            if (cr.Errors.HasErrors)
            {
                return false;
            }
            else
            {
                return true;
            }

        }
        internal static System.Collections.Generic.Dictionary<string, string> ToDictionary(GeometryOverlayAnalystParameters geometryOverlayParams)
        {
            var dict = new System.Collections.Generic.Dictionary<string, string>();
            if (geometryOverlayParams.SourceGeometry != null)
            {
                dict.Add("sourceGeometry", ServerGeometry.ToJson(geometryOverlayParams.SourceGeometry.ToServerGeometry()));
            }
            else
            {
                dict.Add("sourceGeometry", ServerGeometry.ToJson(new ServerGeometry()));
            }

            if (geometryOverlayParams.OperateGeometry != null)
            {
                dict.Add("operateGeometry", ServerGeometry.ToJson(geometryOverlayParams.OperateGeometry.ToServerGeometry()));
            }
            else
            {
                dict.Add("operateGeometry", ServerGeometry.ToJson(new ServerGeometry()));
            }

            dict.Add("operation", "\"" + geometryOverlayParams.Operation.ToString() + "\"");
            return dict;
        }
 public MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple8LastPolymorphicPrivateSetterPropertyAndConstructorSerializer(MsgPack.Serialization.SerializationContext context) :
     base(context)
 {
     MsgPack.Serialization.PolymorphismSchema   schema0           = default(MsgPack.Serialization.PolymorphismSchema);
     MsgPack.Serialization.PolymorphismSchema[] tupleItemsSchema0 = default(MsgPack.Serialization.PolymorphismSchema[]);
     tupleItemsSchema0 = new MsgPack.Serialization.PolymorphismSchema[8];
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema0 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema0     = null;
     tupleItemsSchema0[0] = tupleItemSchema0;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema1 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema1     = null;
     tupleItemsSchema0[1] = tupleItemSchema1;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema2 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema2     = null;
     tupleItemsSchema0[2] = tupleItemSchema2;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema3 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema3     = null;
     tupleItemsSchema0[3] = tupleItemSchema3;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema4 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema4     = null;
     tupleItemsSchema0[4] = tupleItemSchema4;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema5 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema5     = null;
     tupleItemsSchema0[5] = tupleItemSchema5;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema6 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema6     = null;
     tupleItemsSchema0[6] = tupleItemSchema6;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema7 = default(MsgPack.Serialization.PolymorphismSchema);
     System.Collections.Generic.Dictionary <byte, System.Type> tupleItemSchema7TypeMap0 = default(System.Collections.Generic.Dictionary <byte, System.Type>);
     tupleItemSchema7TypeMap0 = new System.Collections.Generic.Dictionary <byte, System.Type>(2);
     tupleItemSchema7TypeMap0.Add(1, typeof(MsgPack.Serialization.DirectoryEntry));
     tupleItemSchema7TypeMap0.Add(0, typeof(MsgPack.Serialization.FileEntry));
     tupleItemSchema7     = MsgPack.Serialization.PolymorphismSchema.ForPolymorphicObject(typeof(MsgPack.Serialization.FileSystemEntry), tupleItemSchema7TypeMap0);
     tupleItemsSchema0[7] = tupleItemSchema7;
     schema0           = MsgPack.Serialization.PolymorphismSchema.ForPolymorphicTuple(typeof(System.Tuple <string, string, string, string, string, string, string, System.Tuple <MsgPack.Serialization.FileSystemEntry> >), tupleItemsSchema0);
     this._serializer0 = context.GetSerializer <string>(schema0);
     MsgPack.Serialization.PolymorphismSchema   schema1           = default(MsgPack.Serialization.PolymorphismSchema);
     MsgPack.Serialization.PolymorphismSchema[] tupleItemsSchema1 = default(MsgPack.Serialization.PolymorphismSchema[]);
     tupleItemsSchema1 = new MsgPack.Serialization.PolymorphismSchema[8];
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema8 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema8     = null;
     tupleItemsSchema1[0] = tupleItemSchema8;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema9 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema9     = null;
     tupleItemsSchema1[1] = tupleItemSchema9;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema10 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema10    = null;
     tupleItemsSchema1[2] = tupleItemSchema10;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema11 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema11    = null;
     tupleItemsSchema1[3] = tupleItemSchema11;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema12 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema12    = null;
     tupleItemsSchema1[4] = tupleItemSchema12;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema13 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema13    = null;
     tupleItemsSchema1[5] = tupleItemSchema13;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema14 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema14    = null;
     tupleItemsSchema1[6] = tupleItemSchema14;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema15 = default(MsgPack.Serialization.PolymorphismSchema);
     System.Collections.Generic.Dictionary <byte, System.Type> tupleItemSchema15TypeMap0 = default(System.Collections.Generic.Dictionary <byte, System.Type>);
     tupleItemSchema15TypeMap0 = new System.Collections.Generic.Dictionary <byte, System.Type>(2);
     tupleItemSchema15TypeMap0.Add(1, typeof(MsgPack.Serialization.DirectoryEntry));
     tupleItemSchema15TypeMap0.Add(0, typeof(MsgPack.Serialization.FileEntry));
     tupleItemSchema15    = MsgPack.Serialization.PolymorphismSchema.ForPolymorphicObject(typeof(MsgPack.Serialization.FileSystemEntry), tupleItemSchema15TypeMap0);
     tupleItemsSchema1[7] = tupleItemSchema15;
     schema1           = MsgPack.Serialization.PolymorphismSchema.ForPolymorphicTuple(typeof(System.Tuple <string, string, string, string, string, string, string, System.Tuple <MsgPack.Serialization.FileSystemEntry> >), tupleItemsSchema1);
     this._serializer1 = context.GetSerializer <System.Tuple <string, string, string, string, string, string, string, System.Tuple <MsgPack.Serialization.FileSystemEntry> > >(schema1);
     this._methodBasePolymorphicMemberTypeKnownType_Tuple_Tuple8LastPolymorphicPrivateSetterPropertyAndConstructor_set_Tuple8LastPolymorphic0 = typeof(MsgPack.Serialization.PolymorphicMemberTypeKnownType_Tuple_Tuple8LastPolymorphicPrivateSetterPropertyAndConstructor).GetMethod("set_Tuple8LastPolymorphic", (System.Reflection.BindingFlags.Instance
                                                                                                                                                                                                                                                                                                                    | (System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic)), null, new System.Type[] {
         typeof(System.Tuple <string, string, string, string, string, string, string, System.Tuple <MsgPack.Serialization.FileSystemEntry> >)
     }, null);
 }
示例#32
0
        /// <param name='pet'>
        /// The pet JSON you want to post
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.HttpOperationResponse> PetsWithHttpMessagesAsync(Pet pet, System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (pet == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "pet");
            }
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("pet", pet);
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Pets", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "").ToString();

            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (pet != null)
            {
                _requestContent      = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(pet, this.Client.SerializationSettings);
                _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.HttpOperationResponse();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
示例#33
0
 static void Add(System.Type type, byte flag)
 {
     baseType2Flag.Add(type, flag);
     flag2BaseType.Add(flag, type);
 }
示例#34
0
        public Updater()
        {
            InitializeComponent();

            if (!IsPortable)
            {
                radioPortable.Visibility = Visibility.Collapsed;
            }
            if (!IsInstaller)
            {
                radioInstaller.Visibility = Visibility.Collapsed;
            }

            #region Lang
            switch (Data.Lang)
            {
            case "de":
                L.Add("Ready", "Bereit");
                L.Add("LoadChangelog", "Lade Changelog");
                L.Add("SearchUpdates", "Suche Updates");
                L.Add("CheckConnection", "Überprüfe Internetverbindung");
                L.Add("NoConnection", "Keine Internetverbindung");
                L.Add("UpdateAvaiable", "Update verfügbar");
                L.Add("NoUpdateAvaiable", "Kein Update verfügbar");
                L.Add("DownloadUpdate", "Lade Update herunter");
                L.Add("DownloadHelper", "Lade Helper");
                L.Add("DownloadComplete", "Erfolgreich heruntergeladen");
                L.Add("Install", "Installieren");
                L.Add("ErrFileMissing", "Fehler: Datei wurde nicht gefunden");
                break;

            default:
                L.Add("Ready", "Ready");
                L.Add("LoadChangelog", "Load changelog");
                L.Add("SearchUpdates", "Search Updates");
                L.Add("CheckConnection", "Check internet-connection");
                L.Add("NoConnection", "No internet-connection");
                L.Add("UpdateAvaiable", "Update avaiable");
                L.Add("NoUpdateAvaiable", "No update avaiable");
                L.Add("DownloadUpdate", "Download update");
                L.Add("DownloadHelper", "Download helper");
                L.Add("DownloadComplete", "Download complete");
                L.Add("Install", "Install");
                L.Add("ErrFileMissing", "Error: File not found");
                break;
            }

            label1.Content  = L["Ready"];
            button1.Content = L["SearchUpdates"];

            #endregion
        }
示例#35
0
 /// <summary>
 /// Wrapper for the action GetPhonebook.
 /// </summary>
 /// <param name="newPhonebookID">The SOAP parameter NewPhonebookID.</param>
 /// <returns>The result (X_AVM_DE_OnTelGetPhonebookResult) of the action.</returns>
 public X_AVM_DE_OnTelGetPhonebookResult GetPhonebook(ushort newPhonebookID)
 {
     System.Collections.Generic.Dictionary <string, object> arguments = new System.Collections.Generic.Dictionary <string, object>();
     arguments.Add("NewPhonebookID", newPhonebookID);
     return(this.SendRequest <X_AVM_DE_OnTelGetPhonebookResult>("GetPhonebook", arguments));
 }
示例#36
0
        private void butOff_Click(object sender, System.EventArgs e)
        {
            DataTable dataTable = (DataTable)this.dgvInfo.DataSource;

            System.Collections.Generic.List <DevSnmpConfig> list = new System.Collections.Generic.List <DevSnmpConfig>();
            System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <int> > dictionary = new System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <int> >();
            this.m_parent.endTimer();
            DialogResult dialogResult;

            if (this.cbDReboot.Checked)
            {
                dialogResult = EcoMessageBox.ShowWarning(EcoLanguage.getMsg(LangRes.OPCrm_reboot, new string[0]), MessageBoxButtons.OKCancel);
            }
            else
            {
                dialogResult = EcoMessageBox.ShowWarning(EcoLanguage.getMsg(LangRes.OPCrm_off, new string[0]), MessageBoxButtons.OKCancel);
            }
            if (dialogResult == DialogResult.Cancel)
            {
                this.m_parent.starTimer();
                return;
            }
            foreach (DataRow dataRow in dataTable.Rows)
            {
                string text  = dataRow[0].ToString();
                string value = dataRow[3].ToString();
                if (dictionary.ContainsKey(text))
                {
                    System.Collections.Generic.List <int> list2 = dictionary[text];
                    list2.Add(System.Convert.ToInt32(value));
                }
                else
                {
                    dictionary.Add(text, new System.Collections.Generic.List <int>
                    {
                        System.Convert.ToInt32(value)
                    });
                }
            }
            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
            foreach (System.Collections.Generic.KeyValuePair <string, System.Collections.Generic.List <int> > current in dictionary)
            {
                string text = current.Key;
                stringBuilder.Append(text + ",");
            }
            string text2 = stringBuilder.ToString();

            if (text2.Length > 1)
            {
                text2 = text2.Substring(0, text2.Length - 1);
            }
            System.Collections.Generic.List <DeviceInfo> list3 = (System.Collections.Generic.List <DeviceInfo>)ClientAPI.RemoteCall(7, 1, text2, 10000);
            if (list3 == null)
            {
                list3 = new System.Collections.Generic.List <DeviceInfo>();
            }
            foreach (DeviceInfo current2 in list3)
            {
                string        text     = current2.DeviceID.ToString();
                DevSnmpConfig sNMPpara = commUtil.getSNMPpara(current2);
                sNMPpara.groupOutlets = dictionary[text];
                list.Add(sNMPpara);
            }
            DevPortGroupAPI devPortGroupAPI = new DevPortGroupAPI(list);
            bool            flag;

            if (this.cbDReboot.Checked)
            {
                flag = devPortGroupAPI.RebootGroupOutlets();
            }
            else
            {
                flag = devPortGroupAPI.TurnOffGroupOutlets();
            }
            if (flag)
            {
                EcoMessageBox.ShowInfo(EcoLanguage.getMsg(LangRes.OPsucc, new string[0]));
            }
            else
            {
                EcoMessageBox.ShowError(EcoLanguage.getMsg(LangRes.OPfail, new string[0]));
            }
            this.m_parent.starTimer();
        }
示例#37
0
 static UserService()
 {
     UsersandRoles = new System.Collections.Generic.Dictionary <string, string>();
     UsersandRoles.Add("admin", "admin");
     UsersandRoles.Add("user", "user");
 }
        public override void OnWindowActivated(Window GotFocus, Window LostFocus)
        {
            try
            {
                package.Log.Debug("CalcHelpersPlugin OnWindowActivated Fired");
                if (GotFocus == null)
                {
                    return;
                }
                IDesignerHost designer = GotFocus.Object as IDesignerHost;
                if (designer == null)
                {
                    return;
                }
                ProjectItem pi = GotFocus.ProjectItem;
                if ((pi == null) || (!(pi.Object is Cube)))
                {
                    return;
                }
                EditorWindow   win     = (EditorWindow)designer.GetService(typeof(IComponentNavigator));
                VsStyleToolBar toolbar = (VsStyleToolBar)win.SelectedView.GetType().InvokeMember("ToolBar", getflags, null, win.SelectedView, null);

                IntPtr ptr     = win.Handle;
                string sHandle = ptr.ToInt64().ToString();

                if (!windowHandlesFixedForCalcProperties.ContainsKey(sHandle))
                {
                    windowHandlesFixedForCalcProperties.Add(sHandle, win);
                    win.ActiveViewChanged += new EventHandler(win_ActiveViewChanged);
                }

                if (win.SelectedView.MenuItemCommandID.ID == (int)BIDSViewMenuItemCommandID.Calculations)
                //if (win.SelectedView.Caption == "Calculations")
                {
                    int  iMicrosoftCalcPropertiesIndex = 0;
                    bool bFlipScriptViewButton         = false;
                    foreach (ToolBarButton b in toolbar.Buttons)
                    {
                        MenuCommandToolBarButton tbb = b as MenuCommandToolBarButton;
                        if (tbb != null && tbb.AssociatedCommandID.ID == (int)BIDSToolbarButtonID.CalculationProperties)
                        //if (b.ToolTipText.StartsWith("Calculation Properties"))
                        {
                            if (b.Tag == null || b.Tag.ToString() != this.FullName + ".CommandProperties")
                            {
                                if (!toolbar.Buttons.ContainsKey(this.FullName + ".CommandProperties"))
                                {
                                    //if we haven't created it yet
                                    iMicrosoftCalcPropertiesIndex = toolbar.Buttons.IndexOf(b);
                                    b.Visible = false;

                                    newCalcPropButton             = new ToolBarButton();
                                    newCalcPropButton.ToolTipText = "Calculation Properties (BIDS Helper)";
                                    newCalcPropButton.Name        = this.FullName + ".CommandProperties";
                                    newCalcPropButton.Tag         = newCalcPropButton.Name;

                                    newCalcPropButton.ImageIndex = 12;
                                    newCalcPropButton.Enabled    = true;
                                    newCalcPropButton.Style      = ToolBarButtonStyle.PushButton;

                                    toolbar.ImageList.Images.Add(BIDSHelper.Resources.Common.DeployMdxScriptIcon);

                                    if (pi.Name.ToLower().EndsWith(".cube")) //only show feature if we're in offline mode
                                    {
                                        // TODO - does not disable if Deploy plugin is disabled after the button has been added
                                        if (BIDSHelperPackage.Plugins[DeployMdxScriptPlugin.BaseName + typeof(DeployMdxScriptPlugin).Name].Enabled)
                                        {
                                            newDeployMdxScriptButton             = new ToolBarButton();
                                            newDeployMdxScriptButton.ToolTipText = "Deploy MDX Script (BIDS Helper)";
                                            newDeployMdxScriptButton.Name        = this.FullName + ".DeployMdxScript";
                                            newDeployMdxScriptButton.Tag         = newDeployMdxScriptButton.Name;
                                            newDeployMdxScriptButton.ImageIndex  = toolbar.ImageList.Images.Count - 1;
                                            newDeployMdxScriptButton.Enabled     = true;
                                            newDeployMdxScriptButton.Style       = ToolBarButtonStyle.PushButton;
                                        }
                                    }

                                    //catch the button clicks of the new buttons we just added
                                    toolbar.ButtonClick += new ToolBarButtonClickEventHandler(toolbar_ButtonClick);

                                    //catch the mouse clicks... the only way to catch the button click for the Microsoft buttons
                                    toolbar.Click += new EventHandler(toolbar_Click);
                                }
                            }
                        }
                        else if (tbb != null && tbb.AssociatedCommandID.ID == 12854 && ScriptViewDefault && !windowHandlesFixedDefaultCalcScriptView.ContainsKey(sHandle))
                        //else if (b.ToolTipText == "Form View" && ScriptViewDefault && !windowHandlesFixedDefaultCalcScriptView.ContainsKey(sHandle)) //12854
                        {
                            Control control = (Control)win.SelectedView.GetType().InvokeMember("ViewControl", getflags, null, win.SelectedView, null);
                            System.Reflection.BindingFlags getfieldflags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance;
                            object controlMgr = control.GetType().InvokeMember("calcControlMgr", getfieldflags, null, control, null);
                            System.Reflection.BindingFlags getmethodflags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance;
                            controlMgr.GetType().InvokeMember("ViewScript", getmethodflags, null, controlMgr, new object[] { });
                            bFlipScriptViewButton = true;
                            b.Pushed = false;
                            windowHandlesFixedDefaultCalcScriptView.Add(sHandle, win);
                        }
                        else if (tbb != null && tbb.AssociatedCommandID.ID == (int)BIDSHelper.BIDSToolbarButtonID.ScriptView && bFlipScriptViewButton)  //12853
                        //else if (b.ToolTipText == "Script View" && bFlipScriptViewButton) //12853
                        {
                            b.Pushed = true;
                        }
                    }
                    if (newDeployMdxScriptButton != null && !toolbar.Buttons.Contains(newDeployMdxScriptButton))
                    {
                        toolbar.Buttons.Insert(iMicrosoftCalcPropertiesIndex, newDeployMdxScriptButton);
                    }
                    if (newCalcPropButton != null && !toolbar.Buttons.Contains(newCalcPropButton))
                    {
                        toolbar.Buttons.Insert(iMicrosoftCalcPropertiesIndex, newCalcPropButton);
                    }
                }
            }
            catch (Exception ex) {
                package.Log.Error("CalcHelpersPlugin Exception: " + ex.Message);
            }
        }
示例#39
0
        /// <summary>
        /// Get invalid Boolean value
        /// </summary>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.HttpOperationResponse <bool?> > GetInvalidWithHttpMessagesAsync(System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bool/invalid").ToString();

            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.HttpOperationResponse <bool?>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <bool?>(_responseContent, this.Client.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
示例#40
0
        /// <summary>
        /// Constructor that instantiates FFACE
        /// </summary>
        /// <param name="processID">The Process ID of the POL Process you want to interface with.</param>
        public FFACE(int processID)
        {
            // create our FFACE instance
            _InstanceID = CreateInstance((UInt32)processID);

            if (!System.IO.Directory.Exists(WindowerPath) && !ParseResources.UseFFXIDatFiles)
            {
                ParseResources.UseFFXIDatFiles = true;
            }

            //#region Find Windower Plugin Path

            //System.Diagnostics.Process[] Processes = System.Diagnostics.Process.GetProcessesByName("pol");
            //if (Processes.Length > 0)
            //	foreach (System.Diagnostics.ProcessModule mod in Processes[0].Modules)
            //	{
            //		if (mod.ModuleName.ToLower() == "hook.dll")
            //		{
            //			WindowerPath = mod.FileName.Substring(0, mod.FileName.Length - 8) + @"\plugins\";
            //			break;
            //		}
            //	}

            //if (String.IsNullOrEmpty(WindowerPath))
            //	WindowerPath = "Windower path could not be found";

            //#endregion

            // Find out if we should be using structs or not
            System.Diagnostics.FileVersionInfo fileInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(FFACE_LIBRARY);

            // Need 4, 1, 0, 14 or later.  Adjust these settings as needed.
            UInt64 version = ((UInt64)fileInfo.FileMajorPart << 48) + ((UInt64)fileInfo.FileMinorPart << 32) + ((UInt64)fileInfo.FileBuildPart << 16) + (UInt64)fileInfo.FilePrivatePart;

            if (fileInfo.FileMajorPart != 4)
            {
                throw new Exception(NEED_v410_14_OR_HIGHER);
            }
            else if (version < 0x000400010000000EUL)                                    // 0004 0001 0000 000E (4, 1, 0, 14)
            {
                throw new Exception(NEED_v410_14_OR_HIGHER);
            }

            /*if (fileInfo.FileMajorPart != 4)
             *      throw new Exception(NEED_v410_14_OR_HIGHER);
             * else if (fileInfo.FileMinorPart < 1)
             *      throw new Exception(NEED_v410_14_OR_HIGHER);
             * else if (fileInfo.FileBuildPart < 0)
             *      throw new Exception(NEED_v410_14_OR_HIGHER);
             * else if (fileInfo.FilePrivatePart < 14)
             *      throw new Exception(NEED_v410_14_OR_HIGHER);*/


            // instantiate our classes
            Player    = new PlayerTools(_InstanceID);
            Target    = new TargetTools(_InstanceID);
            Party     = new PartyTools(_InstanceID);
            Fish      = new FishTools(_InstanceID);
            Windower  = new WindowerTools(_InstanceID);
            Timer     = new TimerTools(_InstanceID);
            Chat      = new ChatTools(_InstanceID);
            Item      = new ItemTools(this);
            NPC       = new NPCTools(_InstanceID);
            Menu      = new MenuTools(this);
            Search    = new SearchTools(_InstanceID);
            Navigator = new NavigatorTools(this);
            //Resources = ParseResources.Instance;

            #region Party Members

            // instantiate our party members
            PartyMember = new System.Collections.Generic.Dictionary <byte, PartyMemberTools>();
            PartyMember.Add(0, new PartyMemberTools(_InstanceID, 0));
            PartyMember.Add(1, new PartyMemberTools(_InstanceID, 1));
            PartyMember.Add(2, new PartyMemberTools(_InstanceID, 2));
            PartyMember.Add(3, new PartyMemberTools(_InstanceID, 3));
            PartyMember.Add(4, new PartyMemberTools(_InstanceID, 4));
            PartyMember.Add(5, new PartyMemberTools(_InstanceID, 5));
            PartyMember.Add(6, new PartyMemberTools(_InstanceID, 6));
            PartyMember.Add(7, new PartyMemberTools(_InstanceID, 7));
            PartyMember.Add(8, new PartyMemberTools(_InstanceID, 8));
            PartyMember.Add(9, new PartyMemberTools(_InstanceID, 9));
            PartyMember.Add(10, new PartyMemberTools(_InstanceID, 10));
            PartyMember.Add(11, new PartyMemberTools(_InstanceID, 11));
            PartyMember.Add(12, new PartyMemberTools(_InstanceID, 12));
            PartyMember.Add(13, new PartyMemberTools(_InstanceID, 13));
            PartyMember.Add(14, new PartyMemberTools(_InstanceID, 14));
            PartyMember.Add(15, new PartyMemberTools(_InstanceID, 15));
            PartyMember.Add(16, new PartyMemberTools(_InstanceID, 16));
            PartyMember.Add(17, new PartyMemberTools(_InstanceID, 17));

            #endregion
        }         // @ public FFACEWrapper(uint processID)
示例#41
0
        /// <summary>
        /// Load a game object prefab at the specified path. This is equivalent to Resources.Load, but it will
        /// also consider DataNode-exported binary assets as well, automatically loading them as if they were
        /// regular prefabs.
        /// </summary>

        static public GameObject LoadPrefab(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return(null);
            }
            if (!Application.isPlaying)
            {
                return(Resources.Load(path, typeof(GameObject)) as GameObject);
            }

            GameObject prefab = null;

            // Try to get it from cache
            if (mPrefabs.TryGetValue(path, out prefab))
            {
                return(prefab);
            }

            if (prefab == null)
            {
                // Try the custom function first
                if (onLoadPrefab != null)
                {
                    prefab = onLoadPrefab(path);
                }

                // Load it from resources as a Game Object
                if (prefab == null)
                {
                    prefab = Resources.Load(path, typeof(GameObject)) as GameObject;

                    if (prefab == null)
                    {
                        // Load it from resources as a binary asset
                        var bytes = UnityTools.LoadBinary(path);

                        if (bytes != null)
                        {
                            // Parse the DataNode hierarchy
                            var data = DataNode.Read(bytes);

                            if (data != null)
                            {
                                // Instantiate and immediately disable the object
                                prefab = data.Instantiate(null, false);

                                if (prefab != null)
                                {
                                    mPrefabs.Add(path, prefab);
                                    Object.DontDestroyOnLoad(prefab);
                                    prefab.transform.parent = prefabRoot;
                                    return(prefab);
                                }
                            }
                        }
                    }
                }
            }

            if (prefab == null)
            {
#if UNITY_EDITOR
                Debug.LogError("[TNet] Attempting to create a game object that can't be found in the Resources folder: [" + path + "]");
#endif
                prefab = GetDummyObject();
            }

            mPrefabs.Add(path, prefab);
            return(prefab);
        }
示例#42
0
        /// <summary>
        /// Lists all node agent SKUs supported by the Azure Batch service.
        /// </summary>
        /// <param name='accountListNodeAgentSkusOptions'>
        /// Additional parameters for the operation
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="BatchErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.Azure.AzureOperationResponse <Microsoft.Rest.Azure.IPage <NodeAgentSku>, AccountListNodeAgentSkusHeaders> > ListNodeAgentSkusWithHttpMessagesAsync(AccountListNodeAgentSkusOptions accountListNodeAgentSkusOptions = default(AccountListNodeAgentSkusOptions), System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (this.Client.ApiVersion == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            string filter = default(string);

            if (accountListNodeAgentSkusOptions != null)
            {
                filter = accountListNodeAgentSkusOptions.Filter;
            }
            int?maxResults = default(int?);

            if (accountListNodeAgentSkusOptions != null)
            {
                maxResults = accountListNodeAgentSkusOptions.MaxResults;
            }
            int?timeout = default(int?);

            if (accountListNodeAgentSkusOptions != null)
            {
                timeout = accountListNodeAgentSkusOptions.Timeout;
            }
            string clientRequestId = default(string);

            if (accountListNodeAgentSkusOptions != null)
            {
                clientRequestId = accountListNodeAgentSkusOptions.ClientRequestId;
            }
            bool?returnClientRequestId = default(bool?);

            if (accountListNodeAgentSkusOptions != null)
            {
                returnClientRequestId = accountListNodeAgentSkusOptions.ReturnClientRequestId;
            }
            System.DateTime?ocpDate = default(System.DateTime?);
            if (accountListNodeAgentSkusOptions != null)
            {
                ocpDate = accountListNodeAgentSkusOptions.OcpDate;
            }
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("filter", filter);
                tracingParameters.Add("maxResults", maxResults);
                tracingParameters.Add("timeout", timeout);
                tracingParameters.Add("clientRequestId", clientRequestId);
                tracingParameters.Add("returnClientRequestId", returnClientRequestId);
                tracingParameters.Add("ocpDate", ocpDate);
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNodeAgentSkus", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "nodeagentskus").ToString();

            System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>();
            if (this.Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
            }
            if (filter != null)
            {
                _queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
            }
            if (maxResults != null)
            {
                _queryParameters.Add(string.Format("maxresults={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(maxResults, this.Client.SerializationSettings).Trim('"'))));
            }
            if (timeout != null)
            {
                _queryParameters.Add(string.Format("timeout={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", System.Guid.NewGuid().ToString());
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (clientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("client-request-id"))
                {
                    _httpRequest.Headers.Remove("client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
            }
            if (returnClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("return-client-request-id"))
                {
                    _httpRequest.Headers.Remove("return-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
            }
            if (ocpDate != null)
            {
                if (_httpRequest.Headers.Contains("ocp-date"))
                {
                    _httpRequest.Headers.Remove("ocp-date");
                }
                _httpRequest.Headers.TryAddWithoutValidation("ocp-date", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(ocpDate, new Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter()).Trim('"'));
            }
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    BatchError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <BatchError>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.Azure.AzureOperationResponse <Microsoft.Rest.Azure.IPage <NodeAgentSku>, AccountListNodeAgentSkusHeaders>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Page <NodeAgentSku> >(_responseContent, this.Client.DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject <AccountListNodeAgentSkusHeaders>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (Newtonsoft.Json.JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
示例#43
0
        private static async Task executeEC2(string[] args, Credentials credentials)
        {
            var nArgs = CLIHelper.GetNamedArguments(args);

            var ec2 = new EC2Helper();
            var iam = new IAMHelper(credentials);

            switch (args[1])
            {
            case "create-instance":
            {
                var imageId             = nArgs["image"];
                var keyName             = nArgs["key"];
                var instanceType        = nArgs["instance-type"].ToEnum <InstanceModel>().ToInstanceType();
                var securityGroupId     = nArgs["security-group"];
                var subnet              = nArgs["subnet"];
                var role                = nArgs["role"];
                var shutdownTermination = nArgs.GetValueOrDefault("on-shutdown-termination").ToBoolOrDefault(false);
                var publicIp            = nArgs.GetValueOrDefault("public-ip").ToBoolOrDefault(true);
                var name                = nArgs["name"];
                var autoKill            = nArgs.GetValueOrDefault("auto-kill").ToIntOrDefault(100 * 365 * 24 * 60);

                var tt   = DateTime.UtcNow.AddMinutes(autoKill);
                var tt2  = tt.AddMinutes(15);
                var tags = new System.Collections.Generic.Dictionary <string, string>()
                {
                    { "Name", name },
                    { "Auto Kill", $"{tt.Minute}-{tt2.Minute} {tt.Hour}-{tt2.Hour} {tt.Day}-{tt2.Day} {tt.Month}-{tt2.Month} * {tt.Year}-{tt2.Year}" },
                };

                var cname = nArgs.GetValueOrDefault("cname");
                var zones = nArgs.GetValueOrDefault("zones")?.Split(',')?.ToArray();

                if (cname != null && zones != null)
                {
                    for (int i = 0; i < zones.Length; i++)
                    {
                        var suffix = i > 0 ? $" {i + 1}" : "";
                        tags.Add($"Route53 Enable{suffix}", "true");
                        tags.Add($"Route53 Name{suffix}", cname);
                        tags.Add($"Route53 Zone{suffix}", zones[i]);
                    }
                }

                string instanceId;
                var    ebsOptymalized = nArgs.GetValueOrDefault("ebs-optymalized").ToBoolOrDefault();

                if (nArgs.Any(x => x.Key.IsWildcardMatch("ebs-root-")))
                {
                    Console.WriteLine("Advanced Instance Creation Initiated...");
                    var rootDeviceName = nArgs["ebs-root-dev-name"];
                    var rootSnapshotId = nArgs.GetValueOrDefault("ebs-root-snapshot-id");
                    var rootVolumeSize = nArgs["ebs-root-volume-size"].ToInt32();
                    var rootIOPS       = nArgs["ebs-root-iops"].ToIntOrDefault(0);
                    var rootVolumeType = nArgs["ebs-root-volume-type"];

                    instanceId = ec2.CreateInstanceAsync(
                        imageId: imageId,
                        instanceType: instanceType,
                        keyName: keyName,
                        securityGroupIDs: new string[] { securityGroupId },
                        subnetId: subnet,
                        roleName: role,
                        shutdownBehavior: shutdownTermination ? ShutdownBehavior.Terminate : ShutdownBehavior.Stop,
                        associatePublicIpAddress: publicIp,
                        ebsOptymalized: ebsOptymalized,
                        rootDeviceName: rootDeviceName,
                        rootSnapshotId: rootSnapshotId,
                        rootVolumeSize: rootVolumeSize,
                        rootIOPS: rootIOPS,
                        rootVolumeType: rootVolumeType,
                        tags: tags
                        ).Result.Reservation.Instances.Single().InstanceId;
                }
                else
                {
                    Console.WriteLine("Basic Instance Creation Initiated...");
                    instanceId = ec2.CreateInstanceAsync(
                        imageId: imageId,
                        instanceType: instanceType,
                        keyName: keyName,
                        securityGroupId: securityGroupId,
                        subnetId: subnet,
                        roleName: role,
                        shutdownBehavior: shutdownTermination ? ShutdownBehavior.Terminate : ShutdownBehavior.Stop,
                        associatePublicIpAddress: publicIp,
                        ebsOptymalized: ebsOptymalized,
                        tags: tags).Result.Reservation.Instances.Single().InstanceId;
                }

                if (nArgs.GetValueOrDefault("await-start").ToBoolOrDefault(false))
                {
                    var timeout_ms = nArgs.GetValueOrDefault("await-start-timeout").ToIntOrDefault(5 * 60 * 1000);

                    Console.WriteLine($"Awaiting up to {timeout_ms} [ms] for instance '{instanceId}' to start...");

                    ec2.AwaitInstanceStateCode(instanceId,
                                               EC2Helper.InstanceStateCode.running, timeout_ms: timeout_ms).Wait();
                }

                if (nArgs.GetValueOrDefault("await-system-start").ToBoolOrDefault(false))
                {
                    var timeout_ms = nArgs.GetValueOrDefault("await-system-start-timeout").ToIntOrDefault(5 * 60 * 1000);

                    Console.WriteLine($"Awaiting up to {timeout_ms} [ms] for instance '{instanceId}' OS to start...");

                    ec2.AwaitInstanceStatus(instanceId,
                                            EC2Helper.InstanceSummaryStatus.Ok, timeout_ms: timeout_ms).Wait();
                }

                Console.WriteLine($"SUCCESS, Instance '{instanceId}' was created.");
            }
                ; break;

            case "terminate-instance":
            {
                var        name      = nArgs.GetValueOrDefault("name");
                Instance[] instances = null;
                if (!name.IsNullOrEmpty())
                {
                    instances = ec2.ListInstancesByName(name).Result;
                    Console.WriteLine($"Found {instances?.Length ?? 0} instances with name: '{name}'.");
                }
                else
                {
                    throw new Exception("Not Supported Arguments");
                }

                instances.ParallelForEach(i =>
                    {
                        void TryRemoveTags()
                        {
                            if (!nArgs.GetValueOrDefault("try-delete-tags").ToBoolOrDefault(false))
                            {
                                return;
                            }

                            var err = ec2.DeleteAllInstanceTags(i.InstanceId).CatchExceptionAsync().Result;

                            if (err == null)
                            {
                                Console.WriteLine("Removed instance tags.");
                            }
                            else
                            {
                                Console.WriteLine($"Failed to remove instance tags, Error: {err.JsonSerializeAsPrettyException()}");
                            }
                        }

                        if (i.State.Code == (int)InstanceStateCode.terminating ||
                            i.State.Code == (int)InstanceStateCode.terminated)
                        {
                            Console.WriteLine($"Instance {i.InstanceId} is already terminating or terminated.");
                            TryRemoveTags();
                            return;
                        }

                        Console.WriteLine($"Terminating {i.InstanceId}...");
                        var result = ec2.TerminateInstance(i.InstanceId).Result;
                        Console.WriteLine($"Instance {i.InstanceId} state changed {result.PreviousState.Name} -> {result.CurrentState.Name}");
                        TryRemoveTags();
                    });

                Console.WriteLine($"SUCCESS, All Instances Are Terminated.");
            }
                ; break;

            case "describe-instance":
            {
                var      name     = nArgs.GetValueOrDefault("name");
                Instance instance = null;
                if (name != null)
                {
                    instance = ec2.ListInstancesByName(name: name).Result
                               .SingleOrDefault(x => (x.State.Name != InstanceStateName.Terminated) && (x.State.Name != InstanceStateName.ShuttingDown));

                    if (instance == null)
                    {
                        throw new Exception($"No non terminated instance with name '{name}' was found.");
                    }

                    var property = nArgs.GetValueOrDefault("property");
                    var output   = nArgs.GetValueOrDefault("output");

                    if (!property.IsNullOrEmpty())
                    {
                        var value    = instance.GetType().GetProperty(property).GetValue(instance, null);
                        var strValue = TypeEx.IsSimple(value.GetType().GetTypeInfo()) ?
                                       value.ToString() :
                                       value.JsonSerialize(Newtonsoft.Json.Formatting.Indented);

                        Console.WriteLine($"Instance '{instance.InstanceId}' Property '{property}', Value: '{strValue}'.");

                        if (!output.IsNullOrEmpty())
                        {
                            Console.WriteLine($"Saving Property Value into output file: '{output}'...");
                            output.ToFileInfo().WriteAllText(strValue);
                        }
                    }
                    else
                    {
                        Console.WriteLine($"Instance '{instance.InstanceId}' properties: {instance.JsonSerialize(Newtonsoft.Json.Formatting.Indented)}");
                        if (!output.IsNullOrEmpty())
                        {
                            Console.WriteLine($"Saving Properties into output file: '{output}'...");
                            output.ToFileInfo().WriteAllText(instance.JsonSerialize(Newtonsoft.Json.Formatting.Indented));
                        }
                    }
                }
                else
                {
                    throw new Exception("Only describe property by name option is available.");
                }

                Console.WriteLine($"SUCCESS, instance '{instance.InstanceId}' properties were found.");
            }
                ; break;

            case "help":
            case "--help":
            case "-help":
            case "-h":
            case "h":
                HelpPrinter($"{args[0]}", "Amazon Elastic Compute Cloud",
                            ("create-instance", "Accepts params: "),
                            ("terminate-instance", "Accepts params: name"));
                break;

            default:
            {
                Console.WriteLine($"Try '{args[0]} help' to find out list of available commands.");
                throw new Exception($"Unknown EC2 command: '{args[0]} {args[1]}'");
            }
            }
        }
示例#44
0
 /// <summary>
 /// Wrapper for the action GetDECTHandsetInfo.
 /// </summary>
 /// <param name="newDectID">The SOAP parameter NewDectID.</param>
 /// <returns>The result (X_AVM_DE_OnTelGetDECTHandsetInfoResult) of the action.</returns>
 public X_AVM_DE_OnTelGetDECTHandsetInfoResult GetDECTHandsetInfo(ushort newDectID)
 {
     System.Collections.Generic.Dictionary <string, object> arguments = new System.Collections.Generic.Dictionary <string, object>();
     arguments.Add("NewDectID", newDectID);
     return(this.SendRequest <X_AVM_DE_OnTelGetDECTHandsetInfoResult>("GetDECTHandsetInfo", arguments));
 }
示例#45
0
        public static void Load(System.Collections.Generic.List <string> addInFiles, List <string> disabledAddIns)
        {
            System.Collections.Generic.List <AddIn> list = new System.Collections.Generic.List <AddIn>();
            System.Collections.Generic.Dictionary <string, System.Version> dictionary  = new System.Collections.Generic.Dictionary <string, System.Version>();
            System.Collections.Generic.Dictionary <string, AddIn>          dictionary2 = new System.Collections.Generic.Dictionary <string, AddIn>();
            foreach (string current in addInFiles)
            {
                AddIn addIn;
                try
                {
                    addIn = AddIn.Load(current);
                }
                catch (System.Exception ex)
                {
                    addIn = new AddIn();
                    addIn.addInFileName      = current;
                    addIn.CustomErrorMessage = ex.Message;
                }
                if (addIn.Action == AddInAction.CustomError)
                {
                    list.Add(addIn);
                }
                else
                {
                    addIn.Enabled = true;
                    if (disabledAddIns != null && disabledAddIns.Count > 0)
                    {
                        foreach (string current2 in addIn.Manifest.Identities.Keys)
                        {
                            if (disabledAddIns.Contains(current2))
                            {
                                addIn.Enabled = false;
                                break;
                            }
                        }
                    }
                    if (addIn.Enabled)
                    {
                        foreach (System.Collections.Generic.KeyValuePair <string, System.Version> current3 in addIn.Manifest.Identities)
                        {
                            if (dictionary.ContainsKey(current3.Key))
                            {
                                addIn.Enabled = false;
                                addIn.Action  = AddInAction.InstalledTwice;
                                break;
                            }
                            dictionary.Add(current3.Key, current3.Value);
                            dictionary2.Add(current3.Key, addIn);
                        }
                    }
                    list.Add(addIn);
                }
            }
            while (true)
            {
IL_175:
                for (int i = 0; i < list.Count; i++)
                {
                    AddIn addIn2 = list[i];
                    if (addIn2.Enabled)
                    {
                        foreach (AddInReference current4 in addIn2.Manifest.Conflicts)
                        {
                            System.Version version;
                            if (current4.Check(dictionary, out version))
                            {
                                AddInTree.DisableAddin(addIn2, dictionary, dictionary2);
                                goto IL_175;
                            }
                        }
                        foreach (AddInReference current5 in addIn2.Manifest.Dependencies)
                        {
                            System.Version version;
                            if (!current5.Check(dictionary, out version))
                            {
                                AddInTree.DisableAddin(addIn2, dictionary, dictionary2);
                                goto IL_175;
                            }
                        }
                    }
                }
                break;
            }
            foreach (AddIn current6 in list)
            {
                try
                {
                    AddInTree.InsertAddIn(current6);
                }
                catch (System.Exception ex2)
                {
                    MessageBox.Show(ex2.Message);
                }
            }
        }
示例#46
0
    }   // read the fasta file

    public static int Main(System.String[] args)
    {
        if (args.Length < 1)
        {
            System.Console.WriteLine("require: output"); return(0);
        }   // check the required parameters

        System.String of = args[0] + ".fna";
        System.String ot = args[0] + ".csv";

        System.IO.DirectoryInfo[] dir = new System.IO.DirectoryInfo(@".").GetDirectories();
        System.Collections.Generic.Dictionary <System.Int32, xlt> csv =
            new System.Collections.Generic.Dictionary <System.Int32, xlt>();

        try
        {
            using (System.IO.StreamWriter w = new System.IO.StreamWriter(of, false))
            {
                foreach (System.IO.DirectoryInfo d in dir)
                {
                    System.Collections.Generic.Dictionary <System.String, System.String> list =
                        new System.Collections.Generic.Dictionary <System.String, System.String>();

                    System.Console.WriteLine("directory: {0}", d.Name);
                    System.String[] fna = System.IO.Directory.GetFiles(
                        d.Name, "*.fna", System.IO.SearchOption.AllDirectories);

                    foreach (System.String f in fna)
                    {
                        System.Console.Write("file: {0} ", f.Split(new System.Char[] { '\\', '/' })[1]);
                        fasta(list, f); System.Console.WriteLine("completed");
                    }   // process each file

                    foreach (System.Collections.Generic.KeyValuePair <System.String, System.String> a in list)
                    {
                        if ((a.Key).Contains("plasmid"))
                        {
                            continue;
                        }   // skip plasmid sequences

                        w.Write(">{0}\n{1}\n", a.Key, a.Value);
                        csv.Add(System.Convert.ToInt32(((a.Key).Split('|'))[1]),
                                new xlt(a.Key, (System.UInt32)((a.Value).Length)));
                    } // write the fasta file
                }     // process each directory
            }         // export the sequence into a file
        }
        catch (System.Exception e)
        {
            System.Console.WriteLine("Exception: {0}", e.Message);
        }   // an exception has occurred

        System.Console.Write("processing {0} ... ", NCBI_TAXID);
        set_tid(ref csv); System.Console.WriteLine("completed");

        System.Console.Write("processing {0} ... ", NCBI_NODES);
        set_rank(ref csv); System.Console.WriteLine("completed");

        System.Console.Write("processing {0} ... ", NCBI_NAMES);
        set_name(ref csv); System.Console.WriteLine("completed");

        try
        {
            using (System.IO.StreamWriter w = new System.IO.StreamWriter(ot, false))
            {
                w.WriteLine("\"GID\",\"TID\",\"Size\",\"Start\",\"End\",\"Strain\",\"Species\"");

                foreach (System.Collections.Generic.KeyValuePair <System.Int32, xlt> i in csv)
                {
                    if ((i.Value).tid < 0)
                    {
                        continue;
                    }   // skip incomplete record

                    w.WriteLine("{0},{1},{2},0,{3},\"{4}\",\"{5}\"",
                                i.Key, (i.Value).tid, (i.Value).length,
                                System.Math.Round((i.Value).length / WMGS_BLOCK),
                                (i.Value).strain, (i.Value).species);
                } // dump the contents
            }     // write the translation table
        }
        catch (System.Exception e)
        {
            System.Console.WriteLine("Exception: {0}", e.Message);
        }   // an exception has occurred

        return(1);
    }   // main procedure
        public void Execute(IServiceProvider serviceProvider)
        {
            this.context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            var  serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var  tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            Guid?userId         = null;

            if (!RunWithSystemPriviliges)
            {
                userId = context.UserId;
            }

            var service = serviceFactory.CreateOrganizationService(userId);

            var et = CrmEventType.Other;

            Enum.TryParse <CrmEventType>(context.MessageName, out et);
            var di = new System.Collections.Generic.Dictionary <Type, object>();

            try
            {
                var pc = new DI.PluginContext(this.UnsecureConfig, this.SecureConfig, context, tracingService, service, et, context.UserId, di);
                di.Add(typeof(IServiceProvider), serviceProvider);
                di.Add(typeof(IOrganizationServiceFactory), serviceFactory);
                di.Add(typeof(IPluginExecutionContext), context);
                di.Add(typeof(ITracingService), tracingService);
                di.Add(typeof(IOrganizationService), service);
                di.Add(typeof(DI.IPluginContext), pc);

                this.Execute(pc);
            }
            catch (Microsoft.Xrm.Sdk.SaveChangesException ste)
            {
                var sb = new System.Text.StringBuilder();
                if (ste.Results != null)
                {
                    sb.Append("Deep: ");
                    foreach (SaveChangesResult res in ste.Results)
                    {
                        if (res.Error != null)
                        {
                            sb.Append(res.Error.Message);
                            if (res.Error.InnerException != null)
                            {
                                sb.Append(res.Error.InnerException.StackTrace);
                                sb.Append("/");
                            }
                        }
                    }
                }
                else
                {
                    sb.Append("Plain: " + ste.Message);
                }
                throw new InvalidPluginExecutionException("USC: " + sb.ToString() + " " + ste.StackTrace, ste);
            }
            catch (Exception ex)
            {
                if (ex is InvalidPluginExecutionException)
                {
                    // just throw it on, we already have a valid exception type
                    throw;
                }
                else
                {
                    // Unexpected error, we log and transform it into a valid exception
                    var mess = this.Log(tracingService, ex);
                    throw new InvalidPluginExecutionException(ex.GetType().FullName + " " + ex.Message, ex);
                }
            }
            finally
            {
                foreach (var s in di.Keys)
                {
                    try
                    {
                        var o = di[s] as IDisposable;
                        if (o != null)
                        {
                            o.Dispose();
                        }
                    } catch (Exception)
                    {
                        // if a cleanup fails, just continue with other cleanups.
                    }
                }
            }
        }
示例#48
0
        Execute(
            Bam.Core.ExecutionContext context,
            string executablePath,
            Bam.Core.StringArray commandLineArguments = null,
            string workingDirectory = null,
            Bam.Core.StringArray inheritedEnvironmentVariables = null,
            System.Collections.Generic.Dictionary <string, Bam.Core.TokenizedStringArray> addedEnvironmentVariables = null,
            string useResponseFileOption = null)
        {
            var processStartInfo = new System.Diagnostics.ProcessStartInfo();

            processStartInfo.FileName    = executablePath;
            processStartInfo.ErrorDialog = true;
            if (null != workingDirectory)
            {
                processStartInfo.WorkingDirectory = workingDirectory;
            }

            var cachedEnvVars = new System.Collections.Generic.Dictionary <string, string>();

            // first get the inherited environment variables from the system environment
            if (null != inheritedEnvironmentVariables)
            {
                int envVarCount;
                if (inheritedEnvironmentVariables.Count == 1 &&
                    inheritedEnvironmentVariables[0] == "*")
                {
                    foreach (System.Collections.DictionaryEntry envVar in processStartInfo.EnvironmentVariables)
                    {
                        cachedEnvVars.Add(envVar.Key as string, envVar.Value as string);
                    }
                }
                else if (inheritedEnvironmentVariables.Count == 1 &&
                         System.Int32.TryParse(inheritedEnvironmentVariables[0], out envVarCount) &&
                         envVarCount < 0)
                {
                    envVarCount += processStartInfo.EnvironmentVariables.Count;
                    foreach (var envVar in processStartInfo.EnvironmentVariables.Cast <System.Collections.DictionaryEntry>().OrderBy(item => item.Key))
                    {
                        cachedEnvVars.Add(envVar.Key as string, envVar.Value as string);
                        --envVarCount;
                        if (0 == envVarCount)
                        {
                            break;
                        }
                    }
                }
                else
                {
                    foreach (var envVar in inheritedEnvironmentVariables)
                    {
                        if (!processStartInfo.EnvironmentVariables.ContainsKey(envVar))
                        {
                            Bam.Core.Log.Info("Environment variable '{0}' does not exist", envVar);
                            continue;
                        }
                        cachedEnvVars.Add(envVar, processStartInfo.EnvironmentVariables[envVar]);
                    }
                }
            }
            processStartInfo.EnvironmentVariables.Clear();
            if (null != inheritedEnvironmentVariables)
            {
                foreach (var envVar in cachedEnvVars)
                {
                    processStartInfo.EnvironmentVariables[envVar.Key] = envVar.Value;
                }
            }
            if (null != addedEnvironmentVariables)
            {
                foreach (var envVar in addedEnvironmentVariables)
                {
                    processStartInfo.EnvironmentVariables[envVar.Key] = envVar.Value.ToString(System.IO.Path.PathSeparator);
                }
            }

            processStartInfo.UseShellExecute        = false;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError  = true;
            processStartInfo.RedirectStandardInput  = true;

            var arguments = commandLineArguments != null?commandLineArguments.ToString(' ') : string.Empty;

            if (Bam.Core.OSUtilities.IsWindowsHosting)
            {
                //TODO: should this include the length of the executable path too?
                if (arguments.Length >= 32767)
                {
                    if (null == useResponseFileOption)
                    {
                        throw new Bam.Core.Exception("Command line is {0} characters long, but response files are not supported by the tool {1}", arguments.Length, executablePath);
                    }

                    var responseFilePath = System.IO.Path.GetTempFileName();
                    using (System.IO.StreamWriter writer = new System.IO.StreamWriter(responseFilePath))
                    {
                        Bam.Core.Log.DebugMessage("Written response file {0} containing:\n{1}", responseFilePath, arguments);
                        // escape any back slashes
                        writer.WriteLine(arguments.Replace(@"\", @"\\"));
                    }

                    arguments = System.String.Format("{0}{1}", useResponseFileOption, responseFilePath);
                }
            }
            processStartInfo.Arguments = arguments;

            Bam.Core.Log.Detail("{0} {1}", processStartInfo.FileName, processStartInfo.Arguments);

            // useful debugging of the command line processor
            Bam.Core.Log.DebugMessage("Working directory: '{0}'", processStartInfo.WorkingDirectory);
            if (processStartInfo.EnvironmentVariables.Count > 0)
            {
                Bam.Core.Log.DebugMessage("Environment variables:");
                foreach (var envVar in processStartInfo.EnvironmentVariables.Cast <System.Collections.DictionaryEntry>().OrderBy(item => item.Key))
                {
                    Bam.Core.Log.DebugMessage("\t{0} = {1}", envVar.Key, envVar.Value);
                }
            }

            System.Diagnostics.Process process = null;
            int exitCode = -1;

            try
            {
                process                     = new System.Diagnostics.Process();
                process.StartInfo           = processStartInfo;
                process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(context.OutputDataReceived);
                process.ErrorDataReceived  += new System.Diagnostics.DataReceivedEventHandler(context.ErrorDataReceived);
                process.Start();
                process.StandardInput.Close();
            }
            catch (System.ComponentModel.Win32Exception ex)
            {
                throw new Bam.Core.Exception("'{0}': process filename '{1}'", ex.Message, processStartInfo.FileName);
            }
            if (null != process)
            {
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                // TODO: need to poll for an external cancel op?
                // poll for the process to exit, as some processes seem to get stuck (hdiutil attach, for example)
                while (!process.HasExited)
                {
                    process.WaitForExit(2000);
                }
                // this additional WaitForExit appears to be needed in order to finish reading the output and error streams asynchronously
                // without it, output is missing from a Native build when executed in many threads
                process.WaitForExit();

                exitCode = process.ExitCode;
                //Bam.Core.Log.DebugMessage("Tool exit code: {0}", exitCode);
                process.Close();
            }

            if (exitCode != 0)
            {
                var message = new System.Text.StringBuilder();
                message.AppendFormat("Command failed: {0} {1}", processStartInfo.FileName, processStartInfo.Arguments);
                message.AppendLine();
                message.AppendFormat("Command exit code: {0}", exitCode);
                message.AppendLine();
                throw new Bam.Core.Exception(message.ToString());
            }
        }
示例#49
0
 public MsgPack_Serialization_PolymorphicMemberTypeKnownType_Tuple_Tuple7FirstPolymorphicReadWriteFieldSerializer(MsgPack.Serialization.SerializationContext context) :
     base(context)
 {
     MsgPack.Serialization.PolymorphismSchema   schema0           = default(MsgPack.Serialization.PolymorphismSchema);
     MsgPack.Serialization.PolymorphismSchema[] tupleItemsSchema0 = default(MsgPack.Serialization.PolymorphismSchema[]);
     tupleItemsSchema0 = new MsgPack.Serialization.PolymorphismSchema[7];
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema0 = default(MsgPack.Serialization.PolymorphismSchema);
     System.Collections.Generic.Dictionary <string, System.Type> tupleItemSchemaTypeMap0 = default(System.Collections.Generic.Dictionary <string, System.Type>);
     tupleItemSchemaTypeMap0 = new System.Collections.Generic.Dictionary <string, System.Type>(2);
     tupleItemSchemaTypeMap0.Add("1", typeof(MsgPack.Serialization.DirectoryEntry));
     tupleItemSchemaTypeMap0.Add("0", typeof(MsgPack.Serialization.FileEntry));
     tupleItemSchema0     = MsgPack.Serialization.PolymorphismSchema.ForPolymorphicObject(typeof(MsgPack.Serialization.FileSystemEntry), tupleItemSchemaTypeMap0);
     tupleItemsSchema0[0] = tupleItemSchema0;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema1 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema1     = null;
     tupleItemsSchema0[1] = tupleItemSchema1;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema2 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema2     = null;
     tupleItemsSchema0[2] = tupleItemSchema2;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema3 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema3     = null;
     tupleItemsSchema0[3] = tupleItemSchema3;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema4 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema4     = null;
     tupleItemsSchema0[4] = tupleItemSchema4;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema5 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema5     = null;
     tupleItemsSchema0[5] = tupleItemSchema5;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema6 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema6     = null;
     tupleItemsSchema0[6] = tupleItemSchema6;
     schema0           = MsgPack.Serialization.PolymorphismSchema.ForPolymorphicTuple(typeof(System.Tuple <MsgPack.Serialization.FileSystemEntry, string, string, string, string, string, string>), tupleItemsSchema0);
     this._serializer0 = context.GetSerializer <string>(schema0);
     MsgPack.Serialization.PolymorphismSchema   schema1           = default(MsgPack.Serialization.PolymorphismSchema);
     MsgPack.Serialization.PolymorphismSchema[] tupleItemsSchema1 = default(MsgPack.Serialization.PolymorphismSchema[]);
     tupleItemsSchema1 = new MsgPack.Serialization.PolymorphismSchema[7];
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema7 = default(MsgPack.Serialization.PolymorphismSchema);
     System.Collections.Generic.Dictionary <string, System.Type> tupleItemSchema7TypeMap0 = default(System.Collections.Generic.Dictionary <string, System.Type>);
     tupleItemSchema7TypeMap0 = new System.Collections.Generic.Dictionary <string, System.Type>(2);
     tupleItemSchema7TypeMap0.Add("1", typeof(MsgPack.Serialization.DirectoryEntry));
     tupleItemSchema7TypeMap0.Add("0", typeof(MsgPack.Serialization.FileEntry));
     tupleItemSchema7     = MsgPack.Serialization.PolymorphismSchema.ForPolymorphicObject(typeof(MsgPack.Serialization.FileSystemEntry), tupleItemSchema7TypeMap0);
     tupleItemsSchema1[0] = tupleItemSchema7;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema8 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema8     = null;
     tupleItemsSchema1[1] = tupleItemSchema8;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema9 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema9     = null;
     tupleItemsSchema1[2] = tupleItemSchema9;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema10 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema10    = null;
     tupleItemsSchema1[3] = tupleItemSchema10;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema11 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema11    = null;
     tupleItemsSchema1[4] = tupleItemSchema11;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema12 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema12    = null;
     tupleItemsSchema1[5] = tupleItemSchema12;
     MsgPack.Serialization.PolymorphismSchema tupleItemSchema13 = default(MsgPack.Serialization.PolymorphismSchema);
     tupleItemSchema13    = null;
     tupleItemsSchema1[6] = tupleItemSchema13;
     schema1           = MsgPack.Serialization.PolymorphismSchema.ForPolymorphicTuple(typeof(System.Tuple <MsgPack.Serialization.FileSystemEntry, string, string, string, string, string, string>), tupleItemsSchema1);
     this._serializer1 = context.GetSerializer <System.Tuple <MsgPack.Serialization.FileSystemEntry, string, string, string, string, string, string> >(schema1);
 }
示例#50
0
        /// <summary>
        /// Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the
        /// header of the request
        /// </summary>
        /// <param name='fooClientRequestId'>
        /// The fooRequestId
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.Azure.AzureOperationHeaderResponse <HeaderCustomNamedRequestIdHeadersInner> > CustomNamedRequestIdWithHttpMessagesAsync(string fooClientRequestId, System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (fooClientRequestId == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fooClientRequestId");
            }
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("fooClientRequestId", fooClientRequestId);
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CustomNamedRequestId", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/customNamedRequestId").ToString();

            System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>();
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (fooClientRequestId != null)
            {
                if (_httpRequest.Headers.Contains("foo-client-request-id"))
                {
                    _httpRequest.Headers.Remove("foo-client-request-id");
                }
                _httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", fooClientRequestId);
            }
            if (this.Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
            }
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.Azure.AzureOperationHeaderResponse <HeaderCustomNamedRequestIdHeadersInner>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("foo-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("foo-request-id").FirstOrDefault();
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject <HeaderCustomNamedRequestIdHeadersInner>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings));
            }
            catch (Newtonsoft.Json.JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
示例#51
0
        static name_reflector()
        {
            ht.Add(((int)(SyntaxTree.Operators.LogicalAND)), compiler_string_consts.and_name);
            ht.Add(((int)(SyntaxTree.Operators.Division)), compiler_string_consts.div_name);
            ht.Add(((int)(SyntaxTree.Operators.IntegerDivision)), compiler_string_consts.idiv_name);
            ht.Add(((int)(SyntaxTree.Operators.Equal)), compiler_string_consts.eq_name);
            ht.Add(((int)(SyntaxTree.Operators.Greater)), compiler_string_consts.gr_name);
            ht.Add(((int)(SyntaxTree.Operators.GreaterEqual)), compiler_string_consts.greq_name);
            ht.Add(((int)(SyntaxTree.Operators.ModulusRemainder)), compiler_string_consts.mod_name);
            ht.Add(((int)(SyntaxTree.Operators.Multiplication)), compiler_string_consts.mul_name);
            ht.Add(((int)(SyntaxTree.Operators.LogicalNOT)), compiler_string_consts.not_name);
            ht.Add(((int)(SyntaxTree.Operators.NotEqual)), compiler_string_consts.noteq_name);
            ht.Add(((int)(SyntaxTree.Operators.LogicalOR)), compiler_string_consts.or_name);
            ht.Add(((int)(SyntaxTree.Operators.Plus)), compiler_string_consts.plus_name);
            ht.Add(((int)(SyntaxTree.Operators.BitwiseLeftShift)), compiler_string_consts.shl_name);
            ht.Add(((int)(SyntaxTree.Operators.BitwiseRightShift)), compiler_string_consts.shr_name);
            ht.Add(((int)(SyntaxTree.Operators.Less)), compiler_string_consts.sm_name);
            ht.Add(((int)(SyntaxTree.Operators.LessEqual)), compiler_string_consts.smeq_name);
            ht.Add(((int)(SyntaxTree.Operators.Minus)), compiler_string_consts.minus_name);
            ht.Add(((int)(SyntaxTree.Operators.BitwiseXOR)), compiler_string_consts.xor_name);
            ht.Add(((int)(SyntaxTree.Operators.AssignmentAddition)), compiler_string_consts.plusassign_name);
            ht.Add(((int)(SyntaxTree.Operators.AssignmentSubtraction)), compiler_string_consts.minusassign_name);
            ht.Add(((int)(SyntaxTree.Operators.AssignmentMultiplication)), compiler_string_consts.multassign_name);
            ht.Add(((int)(SyntaxTree.Operators.AssignmentDivision)), compiler_string_consts.divassign_name);
            ht.Add(((int)(SyntaxTree.Operators.Assignment)), compiler_string_consts.assign_name);
            ht.Add(((int)(SyntaxTree.Operators.In)), compiler_string_consts.in_name);
            ht.Add(((int)(SyntaxTree.Operators.Implicit)), compiler_string_consts.implicit_operator_name);
            ht.Add(((int)(SyntaxTree.Operators.Explicit)), compiler_string_consts.explicit_operator_name);

            pc.Add(compiler_string_consts.and_name, 2);
            pc.Add(compiler_string_consts.div_name, 2);
            pc.Add(compiler_string_consts.idiv_name, 2);
            pc.Add(compiler_string_consts.eq_name, 2);
            pc.Add(compiler_string_consts.gr_name, 2);
            pc.Add(compiler_string_consts.greq_name, 2);
            pc.Add(compiler_string_consts.mod_name, 2);
            pc.Add(compiler_string_consts.mul_name, 2);
            pc.Add(compiler_string_consts.not_name, 1);
            pc.Add(compiler_string_consts.noteq_name, 2);
            pc.Add(compiler_string_consts.or_name, 2);
            pc.Add(compiler_string_consts.plus_name, 2);
            pc.Add(compiler_string_consts.shl_name, 2);
            pc.Add(compiler_string_consts.shr_name, 2);
            pc.Add(compiler_string_consts.sm_name, 2);
            pc.Add(compiler_string_consts.smeq_name, 2);
            pc.Add(compiler_string_consts.minus_name, 2);
            pc.Add(compiler_string_consts.xor_name, 2);
            pc.Add(compiler_string_consts.plusassign_name, 2);
            pc.Add(compiler_string_consts.minusassign_name, 2);
            pc.Add(compiler_string_consts.multassign_name, 2);
            pc.Add(compiler_string_consts.divassign_name, 2);
            pc.Add(compiler_string_consts.assign_name, 2);
            pc.Add(compiler_string_consts.in_name, 2);
            pc.Add(compiler_string_consts.implicit_operator_name, 1);
            pc.Add(compiler_string_consts.explicit_operator_name, 1);
        }
示例#52
0
        private static void WriteDeclareParametersToFile(Utilities.TaskLoggingHelper loggingHelper,
                                                         Framework.ITaskItem[] parameters,
                                                         string[] parameterAttributes,
                                                         string outputFileName,
                                                         bool foptimisticParameterDefaultValue,
                                                         string optimisticParameterMetadata)
        {
            Xml.XmlDocument document          = new System.Xml.XmlDocument();
            Xml.XmlElement  parametersElement = document.CreateElement("parameters");
            document.AppendChild(parametersElement);

            if (parameters != null)
            {
                System.Collections.Generic.Dictionary <string, Xml.XmlElement> dictionaryLookup
                    = new System.Collections.Generic.Dictionary <string, Xml.XmlElement>(parameters.GetLength(0), System.StringComparer.OrdinalIgnoreCase);

                // we are on purpose to keep the order without optimistic change the Value/Default base on the non-null optimistic
                System.Collections.Generic.IList <Framework.ITaskItem> items
                    = Utility.SortParametersTaskItems(parameters, foptimisticParameterDefaultValue, optimisticParameterMetadata);

                foreach (Framework.ITaskItem item in items)
                {
                    string         name             = item.ItemSpec;
                    Xml.XmlElement parameterElement = null;
                    bool           fCreateNew       = false;
                    if (!dictionaryLookup.TryGetValue(name, out parameterElement))
                    {
                        fCreateNew       = true;
                        parameterElement = document.CreateElement("parameter");
                        parameterElement.SetAttribute("name", name);
                        foreach (string attributeName in parameterAttributes)
                        {
                            string value = item.GetMetadata(attributeName);
                            parameterElement.SetAttribute(attributeName, value);
                        }
                        dictionaryLookup.Add(name, parameterElement);
                        parametersElement.AppendChild(parameterElement);
                    }
                    if (parameterElement != null)
                    {
                        string elementValue = item.GetMetadata(ExistingParameterValiationMetadata.Element.ToString());
                        if (string.IsNullOrEmpty(elementValue))
                        {
                            elementValue = "parameterEntry";
                        }

                        string[] parameterIdentities = s_parameterEntryIdentities;

                        if (string.Compare(elementValue, "parameterEntry", System.StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            parameterIdentities = s_parameterEntryIdentities;
                        }
                        else if (string.Compare(elementValue, "parameterValidation", System.StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            parameterIdentities = s_parameterValidationIdentities;
                        }

                        // from all existing node, if the parameter Entry is identical, we should not create a new one
                        int      parameterIdentitiesCount = parameterIdentities.GetLength(0);
                        string[] identityValues           = new string[parameterIdentitiesCount];
                        identityValues[0] = elementValue;

                        for (int i = 1; i < parameterIdentitiesCount; i++)
                        {
                            identityValues[i] = item.GetMetadata(parameterIdentities[i]);
                            if (string.Equals(parameterIdentities[i], ExistingDeclareParameterMetadata.Match.ToString().ToLowerInvariant()))
                            {
                                string unEscapedString = item.GetMetadata(parameterIdentities[i]);

                                string escapedString = Regex.Escape(unEscapedString);
                                if (!string.IsNullOrEmpty(unEscapedString) &&
                                    (Directory.Exists(unEscapedString) ||
                                     File.Exists(unEscapedString)))
                                {
                                    escapedString = $"^{escapedString}$";
                                }

                                identityValues[i] = escapedString;
                            }
                        }

                        if (!fCreateNew)
                        {
                            bool fIdentical = false;
                            foreach (Xml.XmlNode childNode in parameterElement.ChildNodes)
                            {
                                Xml.XmlElement childElement = childNode as Xml.XmlElement;
                                if (childElement != null)
                                {
                                    if (string.Compare(childElement.Name, identityValues[0], System.StringComparison.OrdinalIgnoreCase) == 0)
                                    {
                                        fIdentical = true;
                                        for (int i = 1; i < parameterIdentitiesCount; i++)
                                        {
                                            // case sensitive comparesion  should be O.K.
                                            if (string.CompareOrdinal(identityValues[i], childElement.GetAttribute(parameterIdentities[i])) != 0)
                                            {
                                                fIdentical = false;
                                                break;
                                            }
                                        }
                                        if (fIdentical)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                            if (fIdentical)
                            {
                                // same ParameterEntry, skip this item
                                continue;
                            }
                        }

                        bool fAddEntry = false;
                        for (int i = 1; i < parameterIdentitiesCount; i++)
                        {
                            fAddEntry |= !string.IsNullOrEmpty(identityValues[i]);
                        }
                        if (fAddEntry)
                        {
                            Xml.XmlElement parameterEntry = document.CreateElement(identityValues[0]);
                            for (int i = 1; i < parameterIdentitiesCount; i++)
                            {
                                string attributeName = parameterIdentities[i];
                                string value         = identityValues[i];
                                if (!string.IsNullOrEmpty(value))
                                {
                                    parameterEntry.SetAttribute(attributeName, value);
                                }
                            }
                            parameterElement.AppendChild(parameterEntry);
                        }
                    }
                }
            }

            // Save the UTF8 and Indented
            Utility.SaveDocument(document, outputFileName, System.Text.Encoding.UTF8);
        }
 private static System.Collections.Generic.Dictionary<string, string> GetAddressComponentsFromResult(System.Collections.ArrayList result)
 {
     System.Collections.Generic.Dictionary<string, string> dictionary = new System.Collections.Generic.Dictionary<string, string>();
     dictionary.Add("formatted", "");
     dictionary.Add("formatted-multiline", "");
     dictionary.Add("streetnumber", "");
     dictionary.Add("street", "");
     dictionary.Add("suburb", "");
     dictionary.Add("state", "");
     dictionary.Add("postcode", "");
     dictionary.Add("country", "");
     dictionary.Add("latitude", "");
     dictionary.Add("longitude", "");
     System.Collections.ArrayList arrayList = null;
     if (result.Count > 0)
     {
         dictionary["formatted"] = Conversions.ToString(NewLateBinding.LateIndexGet(result[0], new object[]
         {
                 "formatted_address"
         }, null));
         dictionary["formatted-multiline"] = dictionary["formatted"].Replace(", ", System.Environment.NewLine);
         arrayList = (System.Collections.ArrayList)NewLateBinding.LateIndexGet(result[0], new object[]
         {
                 "address_components"
         }, null);
         dictionary["latitude"] = Conversions.ToString(NewLateBinding.LateIndexGet(NewLateBinding.LateIndexGet(NewLateBinding.LateIndexGet(result[0], new object[]
         {
                 "geometry"
         }, null), new object[]
         {
                 "location"
         }, null), new object[]
         {
                 "lat"
         }, null));
         dictionary["longitude"] = Conversions.ToString(NewLateBinding.LateIndexGet(NewLateBinding.LateIndexGet(NewLateBinding.LateIndexGet(result[0], new object[]
         {
                 "geometry"
         }, null), new object[]
         {
                 "location"
         }, null), new object[]
         {
                 "lng"
         }, null));
     }
     if (arrayList != null)
     {
         try
         {
             System.Collections.IEnumerator enumerator = arrayList.GetEnumerator();
             while (enumerator.MoveNext())
             {
                 object objectValue = System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(enumerator.Current);
                 System.Collections.Generic.Dictionary<string, object> dictionary2 = (System.Collections.Generic.Dictionary<string, object>)objectValue;
                 string value = Conversions.ToString(dictionary2["long_name"]);
                 System.Collections.ArrayList arrayList2 = (System.Collections.ArrayList)dictionary2["types"];
                 try
                 {
                     System.Collections.IEnumerator enumerator2 = arrayList2.GetEnumerator();
                     while (enumerator2.MoveNext())
                     {
                         object objectValue2 = System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(enumerator2.Current);
                         object left = objectValue2;
                         if (Operators.ConditionalCompareObjectEqual(left, "street_number", false))
                         {
                             dictionary["streetnumber"] = value;
                         }
                         else if (Operators.ConditionalCompareObjectEqual(left, "route", false))
                         {
                             dictionary["street"] = value;
                         }
                         else if (Operators.ConditionalCompareObjectEqual(left, "locality", false))
                         {
                             dictionary["suburb"] = value;
                         }
                         else if (Operators.ConditionalCompareObjectEqual(left, "administrative_area_level_1", false))
                         {
                             dictionary["state"] = value;
                         }
                         else if (Operators.ConditionalCompareObjectEqual(left, "postal_code", false))
                         {
                             dictionary["postcode"] = value;
                         }
                         else if (Operators.ConditionalCompareObjectEqual(left, "country", false))
                         {
                             dictionary["country"] = value;
                         }
                     }
                 }
                 finally
                 {
                     System.Collections.IEnumerator enumerator2;
                     if (enumerator2 is System.IDisposable)
                     {
                         (enumerator2 as System.IDisposable).Dispose();
                     }
                 }
             }
         }
         finally
         {
             System.Collections.IEnumerator enumerator;
             if (enumerator is System.IDisposable)
             {
                 (enumerator as System.IDisposable).Dispose();
             }
         }
     }
     return dictionary;
 }
示例#54
0
        public void TestExcel2DataSetStepByStep_With_ExcelReaderConfig()
        {
            var path = System.IO.Path.Combine(Environment.CurrentDirectory, "Util.Excel.Aspose", "Excel2DataSetWithExcelReaderConfig.xlsx");

            var excelReaderConfig = new Util.Excel.ExcelReaderConfig();

            excelReaderConfig.Config = new System.Collections.Generic.List <Util.Excel.SheetReadConfig>();

            // 读取Sheet2
            var cellReadRuleDict_2 = new System.Collections.Generic.Dictionary <int, Util.Excel.CellType>();

            cellReadRuleDict_2.Add(0, Util.Excel.CellType.Blank);
            cellReadRuleDict_2.Add(1, Util.Excel.CellType.Formula);
            cellReadRuleDict_2.Add(2, Util.Excel.CellType.DateTime);

            var toAdd_2 = new Util.Excel.SheetReadConfig()
            {
                SheetName    = "Sheet2",
                CellReadRule = cellReadRuleDict_2
            };

            excelReaderConfig.Config.Add(toAdd_2);


            // 读取sheetIndex=2的工作表
            var cellReadRuleDict_3 = new System.Collections.Generic.Dictionary <int, Util.Excel.CellType>();

            cellReadRuleDict_3.Add(2, Util.Excel.CellType.Blank);
            cellReadRuleDict_3.Add(3, Util.Excel.CellType.Formula);
            cellReadRuleDict_3.Add(4, Util.Excel.CellType.DateTime);


            var toAdd_3 = new Util.Excel.SheetReadConfig()
            {
                SheetIndex           = 2,
                StartCellRowIndex    = 2,
                StartCellColumnIndex = 2,
                CellReadRule         = cellReadRuleDict_3
            };

            excelReaderConfig.Config.Add(toAdd_3);

            var toAdd_4 = new Util.Excel.SheetReadConfig()
            {
                SheetIndex            = 3,
                IsContainColumnHeader = false
            };

            excelReaderConfig.Config.Add(toAdd_4);


            var ds = new Util.Excel.ExcelUtils_Aspose().Excel2DataSetStepByStep(path, excelReaderConfig);

            // 由于加上读取配置, 故ds只有 3 个 Sheet
            Assert.AreEqual <int>(3, ds.Tables.Count);

            // 测试 Sheet2
            DataTable dt_Sheet2 = ds.Tables[0];

            Assert.AreEqual <string>("读取空", dt_Sheet2.Columns[0].ColumnName);
            Assert.AreEqual <string>("读取公式", dt_Sheet2.Columns[1].ColumnName);
            Assert.AreEqual <string>("读取时间", dt_Sheet2.Columns[2].ColumnName);
            Assert.AreEqual <string>("读取数值", dt_Sheet2.Columns[3].ColumnName);

            DataRow dr = dt_Sheet2.Rows[0];

            Assert.AreEqual <string>(string.Empty, dr["读取空"].ToString());
            Assert.AreEqual <string>("=A2+2", dr["读取公式"].ToString());
            Assert.AreEqual <string>("2018-12-06 17:30:26", Util.CommonDal.ReadDateTime(dr["读取时间"]).ToString("yyyy-MM-dd HH:mm:ss"));
            Assert.AreEqual <decimal>(32.123M, Util.CommonDal.ReadDecimal(dr["读取数值"].ToString()));

            dr = dt_Sheet2.Rows[1];
            Assert.AreEqual <string>(string.Empty, dr["读取空"].ToString());
            Assert.AreEqual <string>("=A3+2", dr["读取公式"].ToString());
            Assert.AreEqual <string>("2018-12-06 17:30:28", Util.CommonDal.ReadDateTime(dr["读取时间"]).ToString("yyyy-MM-dd HH:mm:ss"));
            Assert.AreEqual <decimal>(123.456M, Util.CommonDal.ReadDecimal(dr["读取数值"].ToString()));


            // 测试 Sheet3
            DataTable dt_Sheet3 = ds.Tables[1];

            Assert.AreEqual <string>("读取空", dt_Sheet3.Columns[0].ColumnName);
            Assert.AreEqual <string>("读取公式", dt_Sheet3.Columns[1].ColumnName);
            Assert.AreEqual <string>("读取时间", dt_Sheet3.Columns[2].ColumnName);
            Assert.AreEqual <string>("读取数值", dt_Sheet3.Columns[3].ColumnName);

            dr = dt_Sheet3.Rows[0];
            Assert.AreEqual <string>(string.Empty, dr["读取空"].ToString());
            Assert.AreEqual <string>("=C4+2", dr["读取公式"].ToString());
            Assert.AreEqual <string>("2018-12-06 17:30:26", Util.CommonDal.ReadDateTime(dr["读取时间"]).ToString("yyyy-MM-dd HH:mm:ss"));
            Assert.AreEqual <decimal>(32.123M, Util.CommonDal.ReadDecimal(dr["读取数值"].ToString()));

            dr = dt_Sheet3.Rows[1];
            Assert.AreEqual <string>(string.Empty, dr["读取空"].ToString());
            Assert.AreEqual <string>("=C5+2", dr["读取公式"].ToString());
            Assert.AreEqual <string>("2018-12-06 17:30:28", Util.CommonDal.ReadDateTime(dr["读取时间"]).ToString("yyyy-MM-dd HH:mm:ss"));
            Assert.AreEqual <decimal>(123.456M, Util.CommonDal.ReadDecimal(dr["读取数值"].ToString()));

            // 测试 Sheet4 - 测试200格空行仍然能读取信息
            DataTable dt_Sheet4 = ds.Tables[2];

            Assert.AreEqual <int>(2, dt_Sheet4.Rows.Count);


            Assert.AreEqual <string>("Column1", dt_Sheet4.Columns[0].ColumnName);
            Assert.AreEqual <string>("Column2", dt_Sheet4.Columns[1].ColumnName);


            dr = dt_Sheet4.Rows[0];
            Assert.AreEqual <int>(300, Util.CommonDal.ReadInt(dr["ExcelRowNumber"])); // 测试Excel行号
            Assert.AreEqual <string>("300A", Util.CommonDal.ReadString(dr["Column1"]));
            Assert.AreEqual <string>("300B", Util.CommonDal.ReadString(dr["Column2"]));

            dr = dt_Sheet4.Rows[1];
            Assert.AreEqual <int>(304, Util.CommonDal.ReadInt(dr["ExcelRowNumber"])); // 测试Excel行号
            Assert.AreEqual <string>("300", Util.CommonDal.ReadString(dr["Column1"]));
            Assert.AreEqual <string>("301", Util.CommonDal.ReadString(dr["Column2"]));
        }
示例#55
0
 public TestAgent()
 {
     _Providers = new System.Collections.Generic.Dictionary <Type, IProvider>();
     _Providers.Add(typeof(IType), new TProvider <IType>());
 }
 private static System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, string>> GetUserLatestPostsFromResult(System.Collections.ArrayList result)
 {
     System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, string>> list = new System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, string>>();
     try
     {
         try
         {
             System.Collections.IEnumerator enumerator = result.GetEnumerator();
             while (enumerator.MoveNext())
             {
                 object objectValue = System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(enumerator.Current);
                 System.Collections.Generic.Dictionary<string, string> dictionary = new System.Collections.Generic.Dictionary<string, string>();
                 dictionary.Add("id", "");
                 dictionary.Add("link", "");
                 dictionary.Add("thumbnail-image", "");
                 dictionary.Add("lowres-image", "");
                 dictionary.Add("highres-image", "");
                 dictionary.Add("lowres-video", "");
                 dictionary.Add("highres-video", "");
                 dictionary.Add("description", "");
                 dictionary.Add("description-notags", "");
                 dictionary.Add("tags", "");
                 dictionary.Add("latitude", "");
                 dictionary.Add("longitude", "");
                 dictionary.Add("location", "");
                 if (Conversions.ToBoolean(NewLateBinding.LateGet(objectValue, null, "containskey", new object[]
                 {
                         "id"
                 }, null, null, null)))
                 {
                     dictionary["id"] = Conversions.ToString(NewLateBinding.LateIndexGet(objectValue, new object[]
                     {
                             "id"
                     }, null));
                 }
                 if (Conversions.ToBoolean(NewLateBinding.LateGet(objectValue, null, "containskey", new object[]
                 {
                         "link"
                 }, null, null, null)))
                 {
                     dictionary["link"] = Conversions.ToString(NewLateBinding.LateIndexGet(objectValue, new object[]
                     {
                             "link"
                     }, null));
                 }
                 if (Conversions.ToBoolean(NewLateBinding.LateGet(objectValue, null, "containskey", new object[]
                 {
                         "videos"
                 }, null, null, null)))
                 {
                     dictionary.Add("video", "");
                     System.Collections.Generic.Dictionary<string, object> dictionary2 = (System.Collections.Generic.Dictionary<string, object>)NewLateBinding.LateIndexGet(objectValue, new object[]
                     {
                             "videos"
                     }, null);
                     try
                     {
                         System.Collections.Generic.Dictionary<string, object>.Enumerator enumerator2 = dictionary2.GetEnumerator();
                         while (enumerator2.MoveNext())
                         {
                             System.Collections.Generic.KeyValuePair<string, object> current = enumerator2.Current;
                             string key = current.Key;
                             if (Operators.CompareString(key, "low_bandwidth", false) == 0)
                             {
                                 System.Collections.Generic.Dictionary<string, object> dictionary3 = (System.Collections.Generic.Dictionary<string, object>)current.Value;
                                 dictionary["lowres-video"] = Conversions.ToString(dictionary3["url"]);
                             }
                             else if (Operators.CompareString(key, "standard_resolution", false) == 0)
                             {
                                 System.Collections.Generic.Dictionary<string, object> dictionary4 = (System.Collections.Generic.Dictionary<string, object>)current.Value;
                                 dictionary["highres-video"] = Conversions.ToString(dictionary4["url"]);
                             }
                         }
                     }
                     finally
                     {
                         System.Collections.Generic.Dictionary<string, object>.Enumerator enumerator2;
                         ((System.IDisposable)enumerator2).Dispose();
                     }
                 }
                 if (Conversions.ToBoolean((!Conversions.ToBoolean(NewLateBinding.LateGet(objectValue, null, "containskey", new object[]
                 {
                         "location"
                 }, null, null, null)) || !Conversions.ToBoolean(NewLateBinding.LateIndexGet(objectValue, new object[]
                 {
                         "location"
                 }, null) != null)) ? false : true))
                 {
                     System.Collections.Generic.Dictionary<string, object> dictionary5 = (System.Collections.Generic.Dictionary<string, object>)NewLateBinding.LateIndexGet(objectValue, new object[]
                     {
                             "location"
                     }, null);
                     try
                     {
                         System.Collections.Generic.Dictionary<string, object>.Enumerator enumerator3 = dictionary5.GetEnumerator();
                         while (enumerator3.MoveNext())
                         {
                             System.Collections.Generic.KeyValuePair<string, object> current2 = enumerator3.Current;
                             string key2 = current2.Key;
                             if (Operators.CompareString(key2, "latitude", false) == 0)
                             {
                                 dictionary["latitude"] = Conversions.ToString(current2.Value);
                             }
                             else if (Operators.CompareString(key2, "longitude", false) == 0)
                             {
                                 dictionary["longitude"] = Conversions.ToString(current2.Value);
                             }
                             else if (Operators.CompareString(key2, "name", false) == 0)
                             {
                                 dictionary["location"] = Conversions.ToString(current2.Value);
                             }
                         }
                     }
                     finally
                     {
                         System.Collections.Generic.Dictionary<string, object>.Enumerator enumerator3;
                         ((System.IDisposable)enumerator3).Dispose();
                     }
                 }
                 if (NewLateBinding.LateGet(objectValue, null, "containskey", new object[]
                 {
                         "images"
                 }, null, null, null) != null)
                 {
                     System.Collections.Generic.Dictionary<string, object> dictionary6 = (System.Collections.Generic.Dictionary<string, object>)NewLateBinding.LateIndexGet(objectValue, new object[]
                     {
                             "images"
                     }, null);
                     try
                     {
                         System.Collections.Generic.Dictionary<string, object>.Enumerator enumerator4 = dictionary6.GetEnumerator();
                         while (enumerator4.MoveNext())
                         {
                             System.Collections.Generic.KeyValuePair<string, object> current3 = enumerator4.Current;
                             string key3 = current3.Key;
                             if (Operators.CompareString(key3, "thumbnail", false) == 0)
                             {
                                 System.Collections.Generic.Dictionary<string, object> dictionary7 = (System.Collections.Generic.Dictionary<string, object>)current3.Value;
                                 dictionary["thumbnail-image"] = Conversions.ToString(dictionary7["url"]);
                             }
                             else if (Operators.CompareString(key3, "low_resolution", false) == 0)
                             {
                                 System.Collections.Generic.Dictionary<string, object> dictionary8 = (System.Collections.Generic.Dictionary<string, object>)current3.Value;
                                 dictionary["lowres-image"] = Conversions.ToString(dictionary8["url"]);
                             }
                             else if (Operators.CompareString(key3, "standard_resolution", false) == 0)
                             {
                                 System.Collections.Generic.Dictionary<string, object> dictionary9 = (System.Collections.Generic.Dictionary<string, object>)current3.Value;
                                 dictionary["highres-image"] = Conversions.ToString(dictionary9["url"]);
                             }
                         }
                     }
                     finally
                     {
                         System.Collections.Generic.Dictionary<string, object>.Enumerator enumerator4;
                         ((System.IDisposable)enumerator4).Dispose();
                     }
                 }
                 if (NewLateBinding.LateGet(objectValue, null, "containskey", new object[]
                 {
                         "caption"
                 }, null, null, null) != null)
                 {
                     System.Collections.Generic.Dictionary<string, object> dictionary10 = (System.Collections.Generic.Dictionary<string, object>)NewLateBinding.LateIndexGet(objectValue, new object[]
                     {
                             "caption"
                     }, null);
                     try
                     {
                         System.Collections.Generic.Dictionary<string, object>.Enumerator enumerator5 = dictionary10.GetEnumerator();
                         while (enumerator5.MoveNext())
                         {
                             System.Collections.Generic.KeyValuePair<string, object> current4 = enumerator5.Current;
                             string key4 = current4.Key;
                             if (Operators.CompareString(key4, "text", false) == 0)
                             {
                                 dictionary["description"] = Conversions.ToString(current4.Value);
                                 dictionary["description-notags"] = Conversions.ToString(current4.Value);
                             }
                         }
                     }
                     finally
                     {
                         System.Collections.Generic.Dictionary<string, object>.Enumerator enumerator5;
                         ((System.IDisposable)enumerator5).Dispose();
                     }
                 }
                 if (NewLateBinding.LateGet(objectValue, null, "containskey", new object[]
                 {
                         "tags"
                 }, null, null, null) != null)
                 {
                     System.Collections.ArrayList arrayList = (System.Collections.ArrayList)NewLateBinding.LateIndexGet(objectValue, new object[]
                     {
                             "tags"
                     }, null);
                     bool flag = false;
                     try
                     {
                         System.Collections.Generic.IEnumerator<object> enumerator6 = (from f in arrayList.ToArray().ToList<object>()
                                                                                       orderby f.ToString().Length descending
                                                                                       select f).GetEnumerator();
                         while (enumerator6.MoveNext())
                         {
                             object objectValue2 = System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(enumerator6.Current);
                             dictionary["tags"] = Conversions.ToString(Operators.AddObject(Operators.AddObject(dictionary["tags"] + "#", objectValue2), ","));
                             dictionary["description-notags"] = dictionary["description-notags"].Replace(Conversions.ToString(Operators.AddObject(" #", objectValue2)), "", System.StringComparison.OrdinalIgnoreCase);
                             flag = true;
                         }
                     }
                     finally
                     {
                         System.Collections.Generic.IEnumerator<object> enumerator6;
                         if (enumerator6 != null)
                         {
                             enumerator6.Dispose();
                         }
                     }
                     if (flag)
                     {
                         dictionary["tags"] = dictionary["tags"].Substring(0, checked(dictionary["tags"].Length - 1));
                     }
                 }
                 list.Add(dictionary);
             }
         }
         finally
         {
             System.Collections.IEnumerator enumerator;
             if (enumerator is System.IDisposable)
             {
                 (enumerator as System.IDisposable).Dispose();
             }
         }
     }
     catch (System.Exception expr_743)
     {
         ProjectData.SetProjectError(expr_743);
         ProjectData.ClearProjectError();
     }
     return list;
 }
        public void Simulate()
        {
            const string projectName1 = "Test01";

            var integrationFolder = System.IO.Path.Combine("scenarioTests", projectName1);
            var ccNetConfigFile   = System.IO.Path.Combine("IntegrationScenarios", "CCNetConfigWithPreProcessor.xml");
            var project1StateFile = new System.IO.FileInfo(projectName1 + ".state").FullName;

            IntegrationCompleted.Clear();
            IntegrationCompleted.Add(projectName1, false);

            Log("Clear existing state file, to simulate first run : " + project1StateFile);
            System.IO.File.Delete(project1StateFile);

            Log("Clear integration folder to simulate first run");
            if (System.IO.Directory.Exists(integrationFolder))
            {
                System.IO.Directory.Delete(integrationFolder, true);
            }


            CCNet.Remote.Messages.ProjectStatusResponse psr;
            var pr1 = new CCNet.Remote.Messages.ProjectRequest(null, projectName1);

            Log("Making CruiseServerFactory");
            var csf = new CCNet.Core.CruiseServerFactory();

            Log("Making cruiseServer with config from :" + ccNetConfigFile);
            using (var cruiseServer = csf.Create(true, ccNetConfigFile))
            {
                // subscribe to integration complete to be able to wait for completion of a build
                cruiseServer.IntegrationCompleted += new EventHandler <ThoughtWorks.CruiseControl.Remote.Events.IntegrationCompletedEventArgs>(CruiseServerIntegrationCompleted);

                Log("Starting cruiseServer");
                cruiseServer.Start();

                Log("Forcing build on project " + projectName1 + " to test the innertrigger");
                CheckResponse(cruiseServer.ForceBuild(pr1));

                System.Threading.Thread.Sleep(250); // give time to start the build

                Log("Waiting for integration to complete of : " + projectName1);
                while (!IntegrationCompleted[projectName1])
                {
                    for (int i = 1; i <= 4; i++)
                    {
                        System.Threading.Thread.Sleep(250);
                    }
                    Log(" waiting ...");
                }


                // un-subscribe to integration complete
                cruiseServer.IntegrationCompleted -= new EventHandler <ThoughtWorks.CruiseControl.Remote.Events.IntegrationCompletedEventArgs>(CruiseServerIntegrationCompleted);

                Log("getting project status");
                psr = cruiseServer.GetProjectStatus(pr1);
                CheckResponse(psr);

                Log("Stopping cruiseServer");
                cruiseServer.Stop();

                Log("waiting for cruiseServer to stop");
                cruiseServer.WaitForExit(pr1);
                Log("cruiseServer stopped");
            }

            Log("Checking the data");
            Assert.AreEqual(1, psr.Projects.Count, "Amount of projects in configfile is not correct." + ccNetConfigFile);

            CCNet.Remote.ProjectStatus ps = null;

            // checking data of project 1
            foreach (var p in psr.Projects)
            {
                if (p.Name == projectName1)
                {
                    ps = p;
                }
            }

            Assert.AreEqual(projectName1, ps.Name);
            Assert.AreEqual(CCNet.Remote.IntegrationStatus.Success, ps.BuildStatus, "wrong build state for project " + projectName1);
        }
 //public int snake = 0;
 //public int centipede = 0;
 //constructor initializes your set
 public QuizScript()
 {
     characteristic.Add("snake", 0);
     characteristic.Add("centipede", 0);
 }
示例#59
0
 /// <summary>
 /// Wrapper for the action DeleteByIndex.
 /// </summary>
 /// <param name="newIndex">The SOAP parameter NewIndex.</param>
 public void DeleteByIndex(ushort newIndex)
 {
     System.Collections.Generic.Dictionary <string, object> arguments = new System.Collections.Generic.Dictionary <string, object>();
     arguments.Add("NewIndex", newIndex);
     this.SendRequest("DeleteByIndex", arguments);
 }
 public MsgPack_Serialization_PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionPropertySerializer(MsgPack.Serialization.SerializationContext context) :
     base(context, (MsgPack.Serialization.SerializerCapabilities.PackTo | MsgPack.Serialization.SerializerCapabilities.UnpackFrom))
 {
     MsgPack.Serialization.PolymorphismSchema schema0     = default(MsgPack.Serialization.PolymorphismSchema);
     MsgPack.Serialization.PolymorphismSchema keysSchema0 = default(MsgPack.Serialization.PolymorphismSchema);
     System.Collections.Generic.Dictionary <string, System.Type> keysSchemaTypeMap0 = default(System.Collections.Generic.Dictionary <string, System.Type>);
     keysSchemaTypeMap0 = new System.Collections.Generic.Dictionary <string, System.Type>(2);
     keysSchemaTypeMap0.Add("0", typeof(MsgPack.Serialization.FileEntry));
     keysSchemaTypeMap0.Add("1", typeof(MsgPack.Serialization.DirectoryEntry));
     keysSchema0 = MsgPack.Serialization.PolymorphismSchema.ForPolymorphicObject(typeof(MsgPack.Serialization.FileSystemEntry), keysSchemaTypeMap0);
     MsgPack.Serialization.PolymorphismSchema valuesSchema0 = default(MsgPack.Serialization.PolymorphismSchema);
     System.Collections.Generic.Dictionary <string, System.Type> valuesSchemaTypeMap0 = default(System.Collections.Generic.Dictionary <string, System.Type>);
     valuesSchemaTypeMap0 = new System.Collections.Generic.Dictionary <string, System.Type>(2);
     valuesSchemaTypeMap0.Add("0", typeof(MsgPack.Serialization.FileEntry));
     valuesSchemaTypeMap0.Add("1", typeof(MsgPack.Serialization.DirectoryEntry));
     valuesSchema0     = MsgPack.Serialization.PolymorphismSchema.ForPolymorphicObject(typeof(MsgPack.Serialization.FileSystemEntry), valuesSchemaTypeMap0);
     schema0           = MsgPack.Serialization.PolymorphismSchema.ForContextSpecifiedDictionary(typeof(System.Collections.Generic.IDictionary <MsgPack.Serialization.FileSystemEntry, MsgPack.Serialization.FileSystemEntry>), keysSchema0, valuesSchema0);
     this._serializer0 = context.GetSerializer <System.Collections.Generic.IDictionary <MsgPack.Serialization.FileSystemEntry, MsgPack.Serialization.FileSystemEntry> >(schema0);
     this._methodBasePolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty_set_DictPolymorphicKeyAndItem0 = MsgPack.Serialization.ReflectionHelpers.GetMethod(typeof(MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty), "set_DictPolymorphicKeyAndItem", new System.Type[] {
         typeof(System.Collections.Generic.IDictionary <MsgPack.Serialization.FileSystemEntry, MsgPack.Serialization.FileSystemEntry>)
     });
     System.Action <MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty>[] packOperationList = default(System.Action <MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty>[]);
     packOperationList       = new System.Action <MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty> [1];
     packOperationList[0]    = new System.Action <MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty>(this.PackValueOfDictPolymorphicKeyAndItem);
     this._packOperationList = packOperationList;
     System.Func <MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, System.Threading.CancellationToken, System.Threading.Tasks.Task>[] packOperationListAsync = default(System.Func <MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, System.Threading.CancellationToken, System.Threading.Tasks.Task>[]);
     packOperationListAsync       = new System.Func <MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, System.Threading.CancellationToken, System.Threading.Tasks.Task> [1];
     packOperationListAsync[0]    = new System.Func <MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, System.Threading.CancellationToken, System.Threading.Tasks.Task>(this.PackValueOfDictPolymorphicKeyAndItemAsync);
     this._packOperationListAsync = packOperationListAsync;
     System.Collections.Generic.Dictionary <string, System.Action <MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty> > packOperationTable = default(System.Collections.Generic.Dictionary <string, System.Action <MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty> >);
     packOperationTable = new System.Collections.Generic.Dictionary <string, System.Action <MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty> >(1);
     packOperationTable["DictPolymorphicKeyAndItem"] = new System.Action <MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty>(this.PackValueOfDictPolymorphicKeyAndItem);
     this._packOperationTable = packOperationTable;
     System.Collections.Generic.Dictionary <string, System.Func <MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, System.Threading.CancellationToken, System.Threading.Tasks.Task> > packOperationTableAsync = default(System.Collections.Generic.Dictionary <string, System.Func <MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, System.Threading.CancellationToken, System.Threading.Tasks.Task> >);
     packOperationTableAsync = new System.Collections.Generic.Dictionary <string, System.Func <MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, System.Threading.CancellationToken, System.Threading.Tasks.Task> >(1);
     packOperationTableAsync["DictPolymorphicKeyAndItem"] = new System.Func <MsgPack.Packer, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, System.Threading.CancellationToken, System.Threading.Tasks.Task>(this.PackValueOfDictPolymorphicKeyAndItemAsync);
     this._packOperationTableAsync = packOperationTableAsync;
     System.Collections.Generic.Dictionary <string, System.Func <MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, bool> > nullCheckerTable = default(System.Collections.Generic.Dictionary <string, System.Func <MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, bool> >);
     nullCheckerTable = new System.Collections.Generic.Dictionary <string, System.Func <MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, bool> >(1);
     nullCheckerTable["DictPolymorphicKeyAndItem"] = new System.Func <MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, bool>(this.IsDictPolymorphicKeyAndItemNull);
     this._nullCheckersTable = nullCheckerTable;
     System.Action <MsgPack.Unpacker, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, int, int>[] unpackOperationList = default(System.Action <MsgPack.Unpacker, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, int, int>[]);
     unpackOperationList       = new System.Action <MsgPack.Unpacker, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, int, int> [1];
     unpackOperationList[0]    = new System.Action <MsgPack.Unpacker, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, int, int>(this.UnpackValueOfDictPolymorphicKeyAndItem);
     this._unpackOperationList = unpackOperationList;
     System.Func <MsgPack.Unpacker, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, int, int, System.Threading.CancellationToken, System.Threading.Tasks.Task>[] unpackOperationListAsync = default(System.Func <MsgPack.Unpacker, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, int, int, System.Threading.CancellationToken, System.Threading.Tasks.Task>[]);
     unpackOperationListAsync       = new System.Func <MsgPack.Unpacker, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, int, int, System.Threading.CancellationToken, System.Threading.Tasks.Task> [1];
     unpackOperationListAsync[0]    = new System.Func <MsgPack.Unpacker, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, int, int, System.Threading.CancellationToken, System.Threading.Tasks.Task>(this.UnpackValueOfDictPolymorphicKeyAndItemAsync);
     this._unpackOperationListAsync = unpackOperationListAsync;
     System.Collections.Generic.Dictionary <string, System.Action <MsgPack.Unpacker, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, int, int> > unpackOperationTable = default(System.Collections.Generic.Dictionary <string, System.Action <MsgPack.Unpacker, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, int, int> >);
     unpackOperationTable = new System.Collections.Generic.Dictionary <string, System.Action <MsgPack.Unpacker, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, int, int> >(1);
     unpackOperationTable["DictPolymorphicKeyAndItem"] = new System.Action <MsgPack.Unpacker, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, int, int>(this.UnpackValueOfDictPolymorphicKeyAndItem);
     this._unpackOperationTable = unpackOperationTable;
     System.Collections.Generic.Dictionary <string, System.Func <MsgPack.Unpacker, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, int, int, System.Threading.CancellationToken, System.Threading.Tasks.Task> > unpackOperationTableAsync = default(System.Collections.Generic.Dictionary <string, System.Func <MsgPack.Unpacker, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, int, int, System.Threading.CancellationToken, System.Threading.Tasks.Task> >);
     unpackOperationTableAsync = new System.Collections.Generic.Dictionary <string, System.Func <MsgPack.Unpacker, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, int, int, System.Threading.CancellationToken, System.Threading.Tasks.Task> >(1);
     unpackOperationTableAsync["DictPolymorphicKeyAndItem"] = new System.Func <MsgPack.Unpacker, MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, int, int, System.Threading.CancellationToken, System.Threading.Tasks.Task>(this.UnpackValueOfDictPolymorphicKeyAndItemAsync);
     this._unpackOperationTableAsync = unpackOperationTableAsync;
     this._memberNames = new string[] {
         "DictPolymorphicKeyAndItem"
     };
     this.this_SetUnpackedValueOfDictPolymorphicKeyAndItemDelegate = new System.Action <MsgPack.Serialization.PolymorphicMemberTypeKnownType_Dict_DictPolymorphicKeyAndItemPrivateSetterCollectionProperty, System.Collections.Generic.IDictionary <MsgPack.Serialization.FileSystemEntry, MsgPack.Serialization.FileSystemEntry> >(this.SetUnpackedValueOfDictPolymorphicKeyAndItem);
 }