示例#1
0
        public void TestReadonlyField()
        {
            var c = new CodeDomGenerator();

            c.AddNamespace("Samples").AddClass(Define.Class("ee", TypeAttributes.Public)
                                               .AddMember(Define.ReadOnlyField(MemberAttributes.Family, new CodeTypeReference(typeof(int)), "fld1"))
                                               .AddMember(Define.ReadOnlyField(MemberAttributes.Private | MemberAttributes.Static, new CodeTypeReference(typeof(int)), "fld2"))
                                               .AddMember(Define.Const(MemberAttributes.Private, "cns1", () => 1))
                                               .AddMember(Define.Const(MemberAttributes.Public, "cns2", () => "hi!"))
                                               );

            Console.WriteLine(c.GenerateCode(CodeDomGenerator.Language.VB));

            Console.WriteLine(c.GenerateCode(CodeDomGenerator.Language.CSharp));

            var ass = c.Compile(null, CodeDomGenerator.Language.VB);

            Assert.IsNotNull(ass);

            Type eeClass = ass.GetType("Samples.ee");

            Assert.IsNotNull(eeClass);

            ass = c.Compile(null, CodeDomGenerator.Language.CSharp);

            Assert.IsNotNull(ass);

            eeClass = ass.GetType("Samples.ee");

            Assert.IsNotNull(eeClass);
        }
示例#2
0
        public void TestDefaultProperty()
        {
            var c = new CodeDomGenerator();

            c.AddNamespace("Samples").AddClass(Define.Class("ee", TypeAttributes.Public, true)
                                               .AddMember(Define.GetProperty(new CodeTypeReference(typeof(string)), MemberAttributes.Family,
                                                                             (int idx) => "prop", true,
                                                                             Emit.@return((int idx) => idx.ToString())
                                                                             ))
                                               .AddMember(Define.Property(new CodeTypeReference(typeof(string)), MemberAttributes.Family,
                                                                          (int idx) => "prop2", false,
                                                                          CodeDom.CombineStmts(Emit.@return((int idx) => idx.ToString())),
                                                                          Emit.declare("i", (int idx) => idx)
                                                                          ))
                                               );

            Console.WriteLine(c.GenerateCode(CodeDomGenerator.Language.VB));

            Console.WriteLine(c.GenerateCode(CodeDomGenerator.Language.CSharp));

            var ass = c.Compile(null, CodeDomGenerator.Language.VB);

            Assert.IsNotNull(ass);

            Type eeClass = ass.GetType("Samples.ee");

            Assert.IsNotNull(eeClass);
        }
示例#3
0
        public void TestPropertyInterface()
        {
            var c = new CodeDomGenerator();

            c.AddNamespace("Samples")
            .AddClass(Define.Class("ee", TypeAttributes.Public, true).Implements(new CodeTypeReference("Ixxx"))
                      .AddMember(Define.Property(new CodeTypeReference(typeof(string)), MemberAttributes.Public,
                                                 "prop",
                                                 new CodeStatement[] { Emit.@return(() => "sdfsf") },
                                                 new CodeStatement[] { Emit.assignVar("value", () => "sadfaf") }
                                                 ).Implements(new CodeTypeReference("Ixxx"), "dsf"))
                      ).AddInterface(Define.Interface("Ixxx")
                                     .AddProperty(new CodeTypeReference(typeof(string)), MemberAttributes.Public, "dsf")
                                     );

            Console.WriteLine(c.GenerateCode(CodeDomGenerator.Language.VB));

            Console.WriteLine(c.GenerateCode(CodeDomGenerator.Language.CSharp));

            var ass = c.Compile(null, CodeDomGenerator.Language.VB);

            Assert.IsNotNull(ass);

            Type eeClass = ass.GetType("Samples.ee");

            Assert.IsNotNull(eeClass);

            ass = c.Compile(null, CodeDomGenerator.Language.CSharp);

            Assert.IsNotNull(ass);
        }
示例#4
0
        public void Builder_Operator()
        {
            var c = new CodeDomGenerator();

            c.AddNamespace("Samples").AddClass("ee")
            .AddOperators(
                Define.Operator(new CodeTypeReference(typeof(int)),
                                (DynType t) => CodeDom.TypedSeq(OperatorType.Implicit, t.SetType("ee")),
                                Emit.@return(() => 10)
                                )
                )
            ;

            Console.WriteLine(c.GenerateCode(CodeDomGenerator.Language.CSharp));

            Console.WriteLine(c.GenerateCode(CodeDomGenerator.Language.VB));

            var ass = c.Compile();

            Assert.IsNotNull(ass);

            Type eeClass = ass.GetType("Samples.ee");

            Assert.IsNotNull(eeClass);
        }
示例#5
0
        public void TestPartialMethodsVB()
        {
            var c = new CodeDomGenerator();

            c.AddNamespace("Samples").AddClass(Define.Class("ee", TypeAttributes.Public, true)
                                               .AddMember(new CodePartialMethod(Define.Method(MemberAttributes.Public,
                                                                                              () => "foo"
                                                                                              )))
                                               //.AddMember(new CodePartialMethod(Define.Method(MemberAttributes.Public, typeof(string),
                                               //    () => "foo2"
                                               //)))
                                               )
            .AddClass(Define.Class("ee", TypeAttributes.Public, true)
                      .AddMember(new CodePartialMethod(Define.Method(MemberAttributes.Public,
                                                                     () => "foo", Emit.stmt(() => Console.WriteLine())
                                                                     )))
                      )
            ;

            Console.WriteLine(c.GenerateCode(CodeDomGenerator.Language.VB));

            var ass = c.Compile(null, CodeDomGenerator.Language.VB);

            Assert.IsNotNull(ass);

            Type eeClass = ass.GetType("Samples.ee");

            Assert.IsNotNull(eeClass);
        }
示例#6
0
        public void Builder_GetProperty()
        {
            var c = new CodeDomGenerator();

            c.AddNamespace("Samples").AddClass(Define.Class("TestClass")
                                               .AddGetProperty(typeof(int), MemberAttributes.Public, "Test",
                                                               Emit.@return(() => 100)
                                                               )
                                               .AddMethod(MemberAttributes.Public, typeof(int), (int a) => "Test1", Emit.@return((int a) =>
                                                                                                                                 a + [email protected] <int>("Test")))
                                               );

            Console.WriteLine(c.GenerateCode(CodeDomGenerator.Language.CSharp));

            Console.WriteLine(c.GenerateCode(CodeDomGenerator.Language.VB));

            var ass = c.Compile();

            Assert.IsNotNull(ass);

            Type TestClass = ass.GetType("Samples.TestClass");

            Assert.IsNotNull(TestClass);

            object t = TestClass.InvokeMember(null, System.Reflection.BindingFlags.CreateInstance, null, null, null);

            Assert.IsNotNull(t);

            Assert.AreEqual(104, TestClass.InvokeMember("Test1", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.InvokeMethod, null, t,
                                                        new object[] { 4 }));
        }
示例#7
0
        public void Builder_Struct()
        {
            var c = new CodeDomGenerator();

            c.AddNamespace("Samples").AddStruct(Define.Struct("xxx")
                                                .AddField(typeof(bool), "_x")
                                                .AddField(typeof(int), "_y")
                                                .AddCtor((bool x) => MemberAttributes.Public,
                                                         Emit.assignField("_x", (bool x) => x),
                                                         Emit.assignField("_y", () => 100)
                                                         )
                                                .AddGetProperty(typeof(int), MemberAttributes.Public, "Z", "_y")
                                                );

            Console.WriteLine(c.GenerateCode(CodeDomGenerator.Language.CSharp));

            Console.WriteLine(c.GenerateCode(CodeDomGenerator.Language.VB));

            var ass = c.Compile();

            Assert.IsNotNull(ass);

            Type TestClass = ass.GetType("Samples.xxx");

            Assert.IsNotNull(TestClass);

            object t = TestClass.InvokeMember(null, BindingFlags.CreateInstance, null, null,
                                              new object[] { false });

            Assert.IsNotNull(t);

            Assert.AreEqual(100, TestClass.InvokeMember("Z", BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty, null, t, null));
        }
示例#8
0
        public static RequestResult GetCopyFormModel(string abnormalReasonId)
        {
            RequestResult result = new RequestResult();

            try
            {
                using (CFContext context = new CFContext())
                {
                    var abnormalReason = context.AbnormalReasons.Include("Solutions").First(x => x.AbnormalReasonId == new Guid(abnormalReasonId));

                    var model = new CreateFormModel()
                    {
                        OrganizationId             = abnormalReason.OrganizationId.ToString(),
                        ParentOrganizationFullName = OrganizationDataAccessor.GetOrganizationFullName(abnormalReason.OrganizationId),
                        Types = new List <SelectListItem>()
                        {
                            Define.DefaultSelectListItem(Resources.Resource.Select),
                            new SelectListItem()
                            {
                                Text  = Resources.Resource.Create + "...",
                                Value = Define.New
                            }
                        },
                        SolutionModels = abnormalReason.Solutions.Select(x => new SolutionModel
                        {
                            SolutionId = x.SolutionId.ToString(),
                            Type       = x.Type,
                            SId        = x.SId,
                            Name       = x.Name,
                        }).OrderBy(x => x.Type).ThenBy(x => x.SId).ToList(),
                        FormInput = new FormInput()
                        {
                            Type = abnormalReason.Type
                        }
                    };

                    var upStreamOrganizationIds = OrganizationDataAccessor.GetUpStreamOrganizationIds(abnormalReason.OrganizationId, true);

                    model.Types.AddRange(context.AbnormalReasons.Where(x => upStreamOrganizationIds.Contains(x.OrganizationId)).Select(x => x.Type).Distinct().OrderBy(x => x).Select(x => new SelectListItem
                    {
                        Value = x,
                        Text  = x
                    }).ToList());

                    model.Types.First(x => x.Value == abnormalReason.Type).Selected = true;

                    result.ReturnData(model);
                }
            }
            catch (Exception ex)
            {
                var err = new Error(MethodBase.GetCurrentMethod(), ex);

                Logger.Log(err);

                result.ReturnError(err);
            }

            return(result);
        }
示例#9
0
        private void GenerateCS()
        {
            using (Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider())
            {
                CodeGeneratorOptions     opts      = new CodeGeneratorOptions();
                StringWriter             sw        = new StringWriter();
                List <CodeTypeReference> implTypes = new List <CodeTypeReference>();
                if (_property.ImplementationTypes != null)
                {
                    var arr = new CodeTypeReference[_property.ImplementationTypes.Count];
                    _property.ImplementationTypes.CopyTo(arr, 0);
                    _property.ImplementationTypes.Clear();
                    _property.PrivateImplementationType = null;
                    implTypes.AddRange(arr);
                }
                provider.GenerateCodeFromMember(_property, sw, opts);
                foreach (CodeTypeReference tr in implTypes)
                {
                    _property.ImplementationTypes.Add(tr);
                }
                //StringReader sr = new StringReader(sw.GetStringBuilder().ToString());
                //string line = sr.ReadLine();
                //while (string.IsNullOrEmpty(line) || line.StartsWith("/") || line.StartsWith("["))
                //    line = sr.ReadLine();

                StringBuilder sb = new StringBuilder();

                if (InterfaceProperties != null)
                {
                    foreach (CodeTypeReference tr in implTypes)
                    {
                        string prop;
                        if (InterfaceProperties.TryGetValue(tr, out prop))
                        {
                            var newProp = Define.Property(_property.Type, MemberAttributes.Private, prop).Implements(tr);
                            if (_property.HasGet)
                            {
                                newProp.GetStatements.Add(Emit.@return(() => [email protected](_property.Name)));
                                newProp.HasGet = true;
                            }
                            if (_property.HasSet)
                            {
                                newProp.SetStatements.Add(Emit.assignProperty(_property.Name, () => CodeDom.VarRef("value")));
                                newProp.HasSet = true;
                            }

                            StringWriter swNew = new StringWriter();
                            provider.GenerateCodeFromMember(CodeDomTreeProcessor.ProcessMember(newProp, CodeDomGenerator.Language.CSharp),
                                                            swNew, opts);
                            sb.Append(swNew.ToString());
                        }
                    }
                    if (sb.Length > 0)
                    {
                        sb.Insert(0, Environment.NewLine);
                    }
                }
                Text = sw.GetStringBuilder().ToString() + sb.ToString();
            }
        }
示例#10
0
    void SetResult()
    {
        myCanvas.sortingOrder = originOrder;
        GameManager.UI.TryClosePopupUI <CocktailMaking>();

        myCocktail = GameManager.Game.CurrentCocktail;
        if (myCocktail == null)
        {
            return;
        }

        GetImage((int)Images.CocktailImage).sprite = myCocktail.image;
        GetText((int)Texts.CocktailName).text      = $"{myCocktail.Name_kr}\n({myCocktail.Name_en})";

        float proofNormalize = myCocktail.Proof / Define.CocktailMaxProof;

        Get <Slider>((int)Sliders.ProofSlider).DOValue(proofNormalize, 0.7f).
        OnComplete(() =>
        {
            GetText((int)Texts.CocktailProof).text = $"{myCocktail.Proof}%";
        });
        GetImage((int)Images.ProofSliderColor).DOColor(Define.ProofToColor(proofNormalize), 0.7f);

        GetText((int)Texts.CocktailInfo).text = myCocktail.Info;
    }
示例#11
0
        public void Builder_Loop()
        {
            var c = new CodeDomGenerator();

            c.AddNamespace("Samples").AddClass(Define.Class("TestClass")
                                               .AddMethod(
                                                   Define.Method(MemberAttributes.Public | MemberAttributes.Static, typeof(int), (int a) => "Test",
                                                                 Emit.declare("res", () => 0),
                                                                 Emit.@for(
                                                                     "i",               //int i
                                                                     (int a) => a,      // = a
                                                                     (int i) => i < 10, //i<10
                                                                     (int i) => i + 1,  //i+=1
                                                                     Emit.assignVar("res", (int res) => res + 1)
                                                                     ), Emit.@return((int res) => res))
                                                   )
                                               .AddMethod(
                                                   Define.Method(MemberAttributes.Public | MemberAttributes.Static, typeof(int), (int a) => "Test1",
                                                                 Emit.declare("res", () => 0),
                                                                 Emit.@for("i", (int a) => a, (int i) => i < 10, () => CodeDom.VarRef <int>("i") + 2,
                                                                           Emit.assignVar("res", () => CodeDom.VarRef <int>("res") + 1)
                                                                           ), Emit.@return(() => CodeDom.VarRef <int>("res") + 100))
                                                   )
                                               );

            Console.WriteLine(c.GenerateCode(CodeDomGenerator.Language.CSharp));

            Console.WriteLine(c.GenerateCode(CodeDomGenerator.Language.VB));

            Assert.AreEqual(5, c.Compile().GetType("Samples.TestClass").GetMethod("Test")
                            .Invoke(null, new object[] { 5 }));

            Assert.AreEqual(103, c.Compile().GetType("Samples.TestClass").GetMethod("Test1")
                            .Invoke(null, new object[] { 5 }));
        }
示例#12
0
 /// <summary>
 /// 리더보드 열기
 /// </summary>
 public void OnLeaderboardClicked()
 {
     if (EGSocial._IsAuthenticated)
     {
         Define.OpenSongLeaderboard(_beatInfo);
     }
 }
        static void Main(string[] args)
        {
            Define floats = x, y, dx, dy, step;
            Input  floats = x1, y, x2, y2;

            dx = x2 - x1;
            dy = y2 - y1;
示例#14
0
        //データオブジェクトの追加
        override public void Add(OneObj oneObj)
        {
            //オプション指定によるヘッダの追加処理
            if (!(bool)_conf.Get("useBrowserHedaer"))
            {
                if ((bool)_conf.Get("addHeaderRemoteHost"))
                {
                    //    oneObj.Header[cs].Append(key,val);
                    oneObj.Header[CS.Client].Append("Remote-Host-Wp", Encoding.ASCII.GetBytes(Define.ServerAddress()));
                }
                if ((bool)_conf.Get("addHeaderXForwardedFor"))
                {
                    oneObj.Header[CS.Client].Append("X-Forwarded-For", Encoding.ASCII.GetBytes(Define.ServerAddress()));
                }
                if ((bool)_conf.Get("addHeaderForwarded"))
                {
                    string str = string.Format("by {0} (Version {1}) for {2}", Define.ApplicationName(), _kernel.Ver.Version(), Define.ServerAddress());
                    oneObj.Header[CS.Client].Append("Forwarded", Encoding.ASCII.GetBytes(str));
                }
            }

            if (_ar.Count == 0)
            {
                if (oneObj.Request.HttpVer != "HTTP/1.1")
                {
                    KeepAlive = false;//非継続型
                }
            }

            var oneProxyHttp = new OneProxyHttp(Proxy, this, oneObj);

            //キャッシュの確認
            oneProxyHttp.CacheConform(_cache);
            _ar.Add(oneProxyHttp);
        }
示例#15
0
    void Start()
    {
        // 获取设置选项
        isOptionShowcaseOn = Define.IsShowcaseOn;
        colorChangeMode    = Define.ColorChangeMode;
        if (int.TryParse(Define.ColorChangeFreq, out colorChangeFreq))
        {
            colorChangeFreq -= 1;
        }
        else
        {
            colorChangeFreq = 9;
        }

        // 单色模式下的颜色设定,未取得时设置初始值
        if (Define.ColorSingleMode == "")
        {
            Color defaultColor = new Color(243f / 255f, 78f / 255f, 108f / 255f);
            SetColor(defaultColor);
            Define.SetColorSingle(defaultColor);
        }

        // 多背景色模式的背景色列表取得,未取得时设置初始值
        colorList = Define.GetColorList();
        if (colorList == null || colorList.Count == 0)
        {
            colorList.Add(new Color(243f / 255f, 78f / 255f, 108f / 255f));
            colorList.Add(new Color(37f / 255f, 129f / 255f, 199f / 255f));
            colorList.Add(new Color(1f, 194f / 255f, 11f / 255f));
            colorList.Add(new Color(17f / 255f, 190f / 255f, 147f / 255f));
            colorList.Add(new Color(141f / 255f, 186f / 255f, 1f));
        }
        Define.SetColorList(colorList);

        // 设置选项:单色模式
        if (!Define.IsColorChange)
        {
            SetColor(Define.GetColorSingle());
        }
        // 设置选项:多色模式
        else
        {
            SetColor(colorList[0]);
        }

        // 将前景图片的尺寸设为当前屏幕高和宽
        imageObject.GetComponent <RectTransform>().sizeDelta = new Vector2(Screen.width, Screen.height);
        rectTransform           = GetComponent <RectTransform>();
        rectTransform.sizeDelta = new Vector2(Screen.width, Screen.height);

        currentColor = imageObject.GetComponent <Image>().color;

        // 夜间模式初始化
        if (Define.IsNightMode)
        {
            layerFixedImage.color = new Color(30 / 255f, 30 / 255f, 30 / 255f);
            textAnimClock.color   = new Color(30 / 255f, 30 / 255f, 30 / 255f);
            textAnimLoc.color     = new Color(30 / 255f, 30 / 255f, 30 / 255f);
        }
    }
        private async Task LoadContent(DataItem _item)
        {
            string contentStr = string.Empty;

            try
            {
                contentStr = await Define.DownloadStringAsync(_item.Link);
            }
            catch (Exception ex)
            {
                //throw;
            }

            if (contentStr != string.Empty)
            {
                HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
                htmlDoc.LoadHtml(contentStr);

                HtmlAgilityPack.HtmlNode htmlNode = htmlDoc.GetElementbyId("ContentContainer");
                while (htmlNode.Descendants("script").Count() > 0)
                {
                    htmlNode.Descendants("script").ElementAt(0).Remove();
                }
                while (htmlNode.Descendants("meta").Count() > 0)
                {
                    htmlNode.Descendants("meta").ElementAt(0).Remove();
                }

                //contentStr = "<p><i>This blog post was authored by Andrew Byrne (<a href=\"http://twitter.com/AndrewJByrne\" target=\"_blank\">@AndrewJByrne</a>), a Senior Content Developer on the Windows Phone Developer Content team.</i> <p><i></i> <p><i>- Adam</i></p> <hr>  <p> <table cellspacing=\"1\" cellpadding=\"2\" width=\"722\" border=\"0\"> <tbody> <tr> <td valign=\"top\" width=\"397\"> <p>The Windows Phone Developer Content team is continually adding new code samples that you can download from MSDN. In this post, we introduce you to the 10 latest samples that we’ve posted on MSDN. Each sample includes a readme file that walks you through building and running the sample, and includes links to relevant, related documentation. We hope these samples help you with your app development and we look forward to providing more samples as we move forward. You can check out all of our <a href=\"http://code.msdn.microsoft.com/wpapps/site/search?f%5B0%5D.Type=Contributors&amp;f%5B0%5D.Value=Windows%20Phone%20SDK%20Team&amp;f%5B0%5D.Text=Windows%20Phone%20SDK&amp;sortBy=Date\" target=\"_blank\">samples on MSDN</a>.</p></td> <td valign=\"top\" width=\"320\"> <p><a href=\"http://blogs.windows.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-53-84-metablogapi/clip_5F00_image002_5F00_1765A66A.png\"><img title=\"clip_image002\" style=\"border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; float: none; padding-top: 0px; padding-left: 0px; margin-left: auto; border-left: 0px; display: block; padding-right: 0px; margin-right: auto\" border=\"0\" alt=\"clip_image002\" src=\"http://blogs.windows.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-53-84-metablogapi/clip_5F00_image002_5F00_thumb_5F00_7B083E7C.png\" width=\"121\" height=\"213\"></a></p></td></tr></tbody></table></p> <h3><a href=\"http://go.microsoft.com/fwlink/?LinkId=306704\" target=\"_blank\">Stored Contacts Sample</a></h3> <p>This sample illustrates how to use the <a href=\"http://msdn.microsoft.com/en-us/library/windowsphone/develop/windows.phone.personalinformation.contactstore(v=vs.105).aspx\" target=\"_blank\">ContactStore</a> class and related APIs to create a contact store for your app. This feature is useful if your app uses an existing cloud-based contact store. You can use the APIs you to create contacts on the phone that represent the contacts in your remote store. You can display and modify the contacts in the People Hub on your phone, just like contacts that are added through the built-in experience. You can use the APIs to update and delete contacts you have created on the phone and also to query for any changes the user has made to the contacts locally so you can sync those changes to your remote store. <h3><a href=\"http://go.microsoft.com/fwlink/?LinkId=306701\" target=\"_blank\">Basic Storage Recipes</a></h3> <p>This is a “Windows Runtime Storage 101” sample for Windows Phone developers moving from isolated storage and <b>System.IO</b> to <a href=\"http://msdn.microsoft.com/en-us/library/windowsphone/develop/windows.storage.aspx\" target=\"_blank\">Windows.Storage</a> and <a href=\"http://msdn.microsoft.com/en-us/library/windowsphone/develop/windows.storage.streams.aspx\" target=\"_blank\">Windows.Storage.Streams</a>. The sample demonstrates how to write to and read files, in addition to how to enumerate directory trees. It also demonstrates how to pass data from one page to the next, and how to persist application state when the app is deactivated. <h3><a href=\"http://go.microsoft.com/fwlink/?LinkId=301509\" target=\"_blank\">Trial Experience Sample</a></h3> <p>This sample shows you how to design your app to detect its license state when the app launches, and how to detect changes to the license state while running. It comes with a helper class that you can use in your app to wrap <a href=\"http://msdn.microsoft.com/en-us/library/windowsphone/develop/windows.applicationmodel.store.licenseinformation.aspx\" target=\"_blank\">LicenseInformation</a> functionality. <h3><a href=\"http://go.microsoft.com/fwlink/?LinkId=302059\" target=\"_blank\">Windows Runtime Component Sample</a></h3> <p>This sample demonstrates the basics of creating a Windows Phone Runtime component in C++ and consuming it in a XAML app. The sample demonstrates three scenarios: the first scenario illustrates how to call synchronous and asynchronous methods to perform a computation. The second scenario uses the same computation component to demonstrate progress reporting and cancellation of long-running tasks. Finally, the third scenario shows how to use a component to wrap logic that uses <a href=\"http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206944(v=vs.105).aspx\" target=\"_blank\">XAudio2 APIs</a> to play a sound. <h3><a href=\"http://go.microsoft.com/fwlink/?LinkId=306097\" target=\"_blank\">Company Hub Sample</a></h3> <p>This sample demonstrates the construction of an app that is capable of deploying line-of-business (LOB) apps to employees of a corporation. The sample uses an example XML file to define the company XAPs that are available to employees for secure download, and shows you how to dynamically access that file at run time. Then it shows you how to install company apps, enumerate the apps, and then launch the installed company apps. This app is just an example framework and requires additional work beyond the sample to be functional. <h3><a href=\"http://go.microsoft.com/fwlink/?LinkId=306702\" target=\"_blank\">Image Recipes</a></h3> <p>This sample illustrates how to use images in your app efficiently, while giving your users a great experience. It tackles downsampling images, implementing pinch and zoom, and downloading images with a progress display and an option to cancel the download. We’ve taken a recipe approach: each recipe is delivered in a self-contained page in the app so you can focus your attention on the particular part of the sample you are most interested in.  <h3><a href=\"http://go.microsoft.com/fwlink/?LinkId=306026\" target=\"_blank\">Azure Voice Notes</a></h3> <p>This sample uses Windows Phone speech recognition APIs and Windows Azure Mobile Services to record voice notes as text and store the notes in the cloud. It shows how Mobile Services can be used to authenticate a user with their Microsoft Account. It also demonstrates how to use Mobile Services to store, retrieve, and delete data from an Azure database table. The app generates text from speech using the Windows Phone speech recognition APIs and the phone’s predefined dictation grammar. <h3><a href=\"http://go.microsoft.com/fwlink/?LinkId=299241\" target=\"_blank\">Kid's Corner Sample</a></h3> <p>This sample illustrates how to use the <a href=\"http://msdn.microsoft.com/en-us/library/windowsphone/develop/windows.phone.applicationmodel.applicationprofile.modes(v=vs.105).aspx\" target=\"_blank\">ApplicationProfile.Modes</a> property to recognize Kid’s Corner mode. When the app runs, it checks the <a href=\"http://msdn.microsoft.com/en-us/library/windowsphone/develop/windows.phone.applicationmodel.applicationprofile.modes(v=vs.105).aspx\" target=\"_blank\">ApplicationProfile.Modes</a> property. If the value is <b>ApplicationProfileModes.Alternate</b>, you’ll know that the app is running in Kid’s Corner mode. Depending on the content of your app, you may want to change its appearance or features when it runs in Kid’s Corner mode. Some features that you should consider disabling when running in Kid’s Corner mode include in-app purchases, launching the web browser, and the ad control. <h3><a href=\"http://go.microsoft.com/fwlink/?LinkId=267468\" target=\"_blank\">URI Association Sample</a></h3> <p>Use this sample to learn how to automatically launch your app via URI association. This sample includes three apps: a URI launcher, and two apps that handle the URI schemes that are built in to the launcher app. You can launch an app that is included with the sample or edit the URI and launch a different app. There is also a button for launching a URI on another phone using Near Field Communication (NFC).  <h3><a href=\"http://go.microsoft.com/fwlink/?LinkId=275007\" target=\"_blank\">Speech for Windows Phone: Speech recognition using a custom grammar</a></h3> <p>A grammar defines the words and phrases that an app will recognize in speech input. This sample shows you how to go beyond the basics to create a powerful grammar (based on the grammar schema) with which your app can recognize commands and phrases constructed in different ways. <p>&nbsp; <p>This post is just a glimpse of the latest Windows Phone samples we’ve added to the MSDN code gallery. From launching apps with URI associations, to dictating notes and storing them in the cloud, we hope that there’s something for everyone. We’ll be sure to keep you posted as new samples are added to the collection, so stay tuned. In the meantime, grab the samples, experiment with them, and use the code to light up your apps. You can download all Windows Phone samples at <a href=\"http://code.msdn.microsoft.com/wpapps\" target=\"_blank\">http://code.msdn.microsoft.com/wpapps</a>. <div style=\"clear:both;\"></div><img src=\"http://blogs.windows.com/aggbug.aspx?PostID=588575&AppID=5384&AppType=Weblog&ContentType=0\" width=\"1\" height=\"1\">";
                Items[Items.IndexOf(_item)].Content = htmlNode.InnerHtml.Replace("\r", "").Replace("\n", "");
            }
        }
 public void Cleanup()
 {
     definition = null;
     build1Executed = 0;
     build2Executed = 0;
     build3Executed = 0;
 }
示例#18
0
        public static CodeTypeDeclaration AddDelegate <T>(this CodeTypeDeclaration classCode,
                                                          string returnType, MemberAttributes ma, Expression <Func <T, string> > paramsAndName)
        {
            classCode.Members_Add(Define.Delegate(returnType, CorrectAttributes(classCode, ma), paramsAndName));

            return(classCode);
        }
示例#19
0
 private void Create(BaseClass baseClass, Write write)
 {
     BaseClass = baseClass;
     Define = new Define();
     Init = new Init(this);
     Write = write;
 }
示例#20
0
        public void EqualsDifferentOnjectsTest()
        {
            var def1 = new Define(Variable.X, new Number(1));
            var def2 = new Define(new Variable("y"), new Number(2));

            Assert.False(def1.Equals(def2));
        }
示例#21
0
        public async Task <string> MakePostRequest(string id, string apiName,
                                                   ProgressMessageHandler progressMessageHandler, bool save = false)
        {
            return(await Task.Run(async() =>
            {
                var makeParams = new MakeParams();
                makeParams.AddSignatureParam(id, apiName);
                HttpContent httpContent = new StringContent(makeParams.GetParam());
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded")
                {
                    CharSet = "utf-8"
                };

                using (var client = new HttpClient(progressMessageHandler)
                {
                    BaseAddress = new Uri(Define.BaseUrl)
                })
                {
                    client.DefaultRequestHeaders.Add("Expect", "100-continue");
                    client.DefaultRequestHeaders.Add("X-Unity-Version", "2018.2.6f1");
                    client.DefaultRequestHeaders.Add("UserAgent",
                                                     "Dalvik/2.1.0 (Linux; U; Android 5.1.1; xiaomi 8 Build/LMY49I)");
                    client.DefaultRequestHeaders.Add("Host", "api.t7s.jp");
                    client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
                    client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip");

                    var httpResponse = client.PostAsync(Define.GetApiName(Define.APINAME_TYPE.result)
                                                        , httpContent).Result;
                    httpResponse.EnsureSuccessStatusCode();
                    //ManualResetEvent.WaitOne(100);
                    return await httpResponse.Content.ReadAsStringAsync();
                }
            }));
        }
示例#22
0
        public Folder(eFolder a_eFolder, int a_nData = 0, int a_nDateOffset = 0)
        {
            m_eFolder     = a_eFolder;
            m_nData       = a_nData;
            m_nDateOffset = a_nDateOffset;

            m_sName = Global.Path.FolderName(m_eFolder, m_nData);
            m_sName_withFullPath = System.IO.Path.Combine(Config.sFolderPath, m_sName);

            if (string.IsNullOrEmpty(m_sName_withFullPath) == true)
            {
                Define.LogError("logic error"); return;
            }

            if (System.IO.Directory.Exists(m_sName_withFullPath) == true) // 폴더가 있다면 안의 파일, 폴더를 취합
            {
                var arName = System.IO.Directory.GetFiles(m_sName_withFullPath);

                for (int i = 0; i < arName.Length; ++i)
                {
                    arName[i] = System.IO.Path.GetFileName(arName[i]);
                    m_liChild.AddLast(new File(arName[i], this));
                }
            }
            else // 폴더가 없었다면 ~일 폴더들을 만듬
            {
                System.IO.Directory.CreateDirectory(sFolderName);
            }
        }
示例#23
0
        public void GenericObjectCreate()
        {
            var c = new CodeDomGenerator();

            c.AddNamespace("Samples")
            .AddClass(Define.Class("TestClass").Generic("T")
                      .AddFields(
                          Define.Field(MemberAttributes.Private, "T", "_s")
                          )
                      .AddProperty("T", MemberAttributes.Public, "S", "_s")
                      ).AddClass(Define.Class("cls")
                                 .AddMethod(MemberAttributes.Public | MemberAttributes.Static, CodeDom.TypeRef("TestClass", "T"), () => "foo",
                                            Emit.declare(CodeDom.TypeRef("TestClass", "T"), "cc",
                                                         () => CodeDom.@new(CodeDom.TypeRef("TestClass", "T"))),
                                            Emit.@return((Var cc) => cc))
                                 .Generic("T")
                                 );

            Console.WriteLine(c.GenerateCode(CodeDomGenerator.Language.CSharp));

            Console.WriteLine(c.GenerateCode(CodeDomGenerator.Language.VB));

            var ass = c.Compile();

            Assert.IsNotNull(ass);

            Type TestClass = ass.GetType("Samples.TestClass`1");

            Assert.IsNotNull(TestClass);
        }
示例#24
0
文件: Form1.cs 项目: GA23187/rpg
        public int mc_mod = 0;                //0—nomal,1—event
        private void Form1_Load(object sender, EventArgs e)
        {
            //光标
            mc_nomal = new Bitmap(@"ui/mc_1.png");
            mc_nomal.SetResolution(96, 96);
            mc_event = new Bitmap(@"ui/mc_2.png");
            mc_event.SetResolution(96, 96);

            Define.define(player, npc, map);
            Map.change_map(map, player, npc, 0, 30, 500, 1, music_player);

            /*           Button b = new Button();
             *         b.click_event += new Button.Click_event(tryevent);
             *         b.click();
             */

            Title.init();
            Title.show();

            Message.init();
            StatusMenu.init();

            Shop.init();

            // Fight.start(new int[] {0,0,-1},"fight/f_scene.png",1,0,1,1,100);            //指定2个id=0的敌人
            Fight.init();
            Save.init();
        }
示例#25
0
        public void CloneTest()
        {
            var exp   = new Define(Variable.X, new Number(0));
            var clone = exp.Clone();

            Assert.Equal(exp, clone);
        }
 private void Start()
 {
     ObservableExtensions.Subscribe <int>(Observable.Where <int>((IObservable <M0>) this.SelectedID, (Func <M0, bool>)(x => x >= 0 && x < this.lstCoordinates.Count)), (Action <M0>)(x =>
     {
         for (int index = 0; index < this.lstCoordinates.Count; ++index)
         {
             if (this.lstCoordinates[index].id == x)
             {
                 this.SelectedLabel.set_text(this.lstCoordinates[index].coodeName.get_text());
                 this.filename = this.lstCoordinates[index].fileName;
                 this.CardImage.set_texture((Texture)PngAssist.ChangeTextureFromByte(this.lstCoordinatesBase[x].pngData == null ? PngFile.LoadPngBytes(this.lstCoordinatesBase[x].FullPath) : this.lstCoordinatesBase[x].pngData, 0, 0, (TextureFormat)5, false));
             }
         }
         if (!((Component)this.CardImage).get_gameObject().get_activeSelf())
         {
             ((Component)this.CardImage).get_gameObject().SetActive(true);
         }
         for (int index = 0; index < this.lstCoordinates.Count; ++index)
         {
             if (this.lstCoordinates[index].id != x)
             {
                 ((Graphic)this.lstCoordinates[index].image).set_color(Color.get_white());
             }
             else
             {
                 ((Graphic)this.lstCoordinates[index].image).set_color(Define.Get(Colors.Yellow));
             }
         }
     }));
 }
示例#27
0
        public void DefineParser()
        {
            Define def1 = new Define("INCLUDE_L3");

            Assert.AreEqual("INCLUDE_L3", def1.Name);
            Assert.AreEqual(Define.DefaultValue, def1.Value);
            Assert.AreEqual("INCLUDE_L3", def1.ToString());

            Define def2 = new Define("INCLUDE_L3=1");

            Assert.AreEqual("INCLUDE_L3", def2.Name);
            Assert.AreEqual("1", def2.Value);
            Assert.AreEqual("INCLUDE_L3=1", def2.ToString());

            Define def3 = new Define("INCLUDE_L3=YES");

            Assert.AreEqual("INCLUDE_L3", def3.Name);
            Assert.AreEqual("YES", def3.Value);
            Assert.AreEqual("INCLUDE_L3=YES", def3.ToString());

            Define def4 = new Define("INCLUDE_L3=\"YES\"");

            Assert.AreEqual("INCLUDE_L3", def4.Name);
            Assert.AreEqual("YES", def4.Value);
            Assert.AreEqual("INCLUDE_L3=YES", def4.ToString());
        }
示例#28
0
        public void SolveStringTest()
        {
            var lexer      = new Mock <ILexer>();
            var parser     = new Mock <IParser>();
            var simplifier = new Mock <ISimplifier>();

            var strExp = "x := 1";
            var exp    = new Define(new Variable("x"), new Number(1));

            var tokens = new List <IToken>
            {
                new FunctionToken(Functions.Define, 2),
                new SymbolToken(Symbols.OpenBracket),
                new VariableToken("x"),
                new SymbolToken(Symbols.Comma),
                new NumberToken(1),
                new SymbolToken(Symbols.CloseBracket)
            };

            lexer.Setup(l => l.Tokenize(strExp)).Returns(() => tokens);
            parser.Setup(p => p.Parse(tokens)).Returns(() => exp);

            simplifier.Setup(s => s.Analyze(It.IsAny <Define>())).Returns <Define>(e => e);

            var processor = new Processor(lexer.Object, parser.Object, simplifier.Object, null);
            var result    = processor.Solve <StringResult>(strExp);

            lexer.Verify(l => l.Tokenize(It.IsAny <string>()), Times.Once());
            parser.Verify(p => p.Parse(It.IsAny <IEnumerable <IToken> >()), Times.Once());

            Assert.Equal("The value '1' was assigned to the variable 'x'.", result.Result);
        }
示例#29
0
        static void Main2()
        {
            var c = new CodeDomGenerator();

            c.AddNamespace("Samples").AddClass("cls")
            .AddMethod(MemberAttributes.Public | MemberAttributes.Static, typeof(string), (int i) => "Print",
                       Emit.@if((int i) => i < 10,
                                Emit.@return(() => "i less than 10")
                                ),
                       Emit.@return(() => "i greater than 10")
                       );

            Console.WriteLine(c.GenerateCode(LinqToCodedom.CodeDomGenerator.Language.CSharp));

            var c2 = new CodeDomGenerator();

            CodeMemberMethod method = Define.Method(MemberAttributes.Public, () => "foo");

            c2.AddNamespace("TestNS").AddClass("Fibonacci")
            .AddMethod(MemberAttributes.Public | MemberAttributes.Static, (int x) => "Calc",
                       Emit.@if((int x) => x <= 1,
                                Emit.@return(() => 1)),
                       Emit.@return((int x) =>
                                    CodeDom.Call <int>("Calc")(x - 1) + CodeDom.Call <int>("Calc")(x - 2))
                       )
            ;

            Console.WriteLine(c2.GenerateCode(LinqToCodedom.CodeDomGenerator.Language.CSharp));

            Console.WriteLine(c2.GenerateCode(LinqToCodedom.CodeDomGenerator.Language.VB));
        }
示例#30
0
        public async void SaveUrlIndex(Task <string> data)
        {
            if (!Directory.Exists(Define.LocalPath + @"\Asset\Index\Temp"))
            {
                Directory.CreateDirectory(Define.LocalPath + @"\Asset\Index\Temp");
            }

            ResultJsonObject = null;

            await ParseResultJsonAsync(data);

            ParseModify();
            ParseModify(true);

            var urlIndex =
                JsonConvert.SerializeObject(FileUrls.OrderBy(e => e.Name, StringComparer.Ordinal));

            using (var streamWriter = new StreamWriter(Define.GetAdvanceIndexPath()))
            {
                streamWriter.Write(urlIndex);
                streamWriter.Close();
            }

            FileUrls.Clear();
            OnGetComplete();
        }
示例#31
0
        public void ObjectCreate()
        {
            var c = new CodeDomGenerator();

            c.AddNamespace("Samples").AddClass(Define.Class("TestClass")
                                               .AddFields(
                                                   Define.Field(MemberAttributes.Private, typeof(string), "_s"),
                                                   Define.Field(MemberAttributes.Private, typeof(int), "_i")
                                                   )
                                               .AddCtor(
                                                   Define.Ctor((int i, string s) => MemberAttributes.Public,
                                                               Emit.assignField("_s", (string s) => s),
                                                               Emit.assignField("_i", (int i) => i)
                                                               )
                                                   )
                                               .AddMethod(MemberAttributes.Static | MemberAttributes.Public, "TestClass", () => "Create", Emit.@return(() => CodeDom.@new("TestClass", 100, "yyy")))
                                               );

            Console.WriteLine(c.GenerateCode(CodeDomGenerator.Language.CSharp));

            Console.WriteLine(c.GenerateCode(CodeDomGenerator.Language.VB));

            var ass = c.Compile();

            Assert.IsNotNull(ass);

            Type TestClass = ass.GetType("Samples.TestClass");

            Assert.IsNotNull(TestClass);
        }
示例#32
0
        public void EqualsDifferentTypesTest()
        {
            var def    = new Define(Variable.X, new Number(1));
            var number = new Number(1);

            Assert.False(def.Equals(number));
        }
示例#33
0
 /// <summary>
 /// 移動処理.
 /// </summary>
 /// <param name='type'>
 /// Type.
 /// </param>
 private void Move( Define.RotateType type )
 {
     int horizontal = type == Define.RotateType.Left ? -1 : type == Define.RotateType.Right ? 1 : 0;
     int vertical = type == Define.RotateType.Forward ? 1 : type == Define.RotateType.Back ? -1 : 0;
     WorldMapData.AddWorldPosition( horizontal, vertical );
     StartMove();
     SetRotate( type );
 }
 public void Three_tasks_where_two_depend_on_one()
 {
     definition = Define.It(d =>
     {
         d.Task("build1", t => build1Executed++, "build2", "build3");
         d.Task("build2", t => build2Executed++, "build3");
         d.Task("build3", t => build3Executed++);
     });
     definition.ExecuteTasksWithName("build1");
 }
示例#35
0
文件: Log.cs 项目: hy1314200/HyDM
 /// <summary>
 /// 添加“消息”
 /// </summary>
 /// <param name="logType"></param>
 /// <param name="strMsg"></param>
 public static void AppendMessage(Define.enumLogType logType, string strMsg)
 {
     Validate();
     if (logType == Define.enumLogType.Operate)
     {
         m_OperationalLogger.AppendMessage(strMsg);
     }
     else
     {
         m_ExceptionLogger.AppendMessage("[" + logType.ToString() + "]" + strMsg);
     }
 }
示例#36
0
		/// <summary>
		/// 获得消息包的字节流
		/// </summary>
		/// <param name="remoteIp">远程主机地址</param>
		/// <param name="packageNo">包编号</param>
		/// <param name="command">命令</param>
		/// <param name="options">参数</param>
		/// <param name="userName">用户名</param>
		/// <param name="hostName">主机名</param>
		/// <param name="content">正文消息</param>
		/// <param name="extendContents">扩展消息</param>
		/// <returns></returns>
		public static Entity.PackedNetworkMessage BuildNetworkMessage(IPEndPoint remoteIp, ulong packageNo, Define.Consts.Commands command, ulong options, string userName, string hostName, byte[] content, byte[] extendContents)
		{
			using (System.IO.MemoryStream bufferStream = new System.IO.MemoryStream())
			{
				int maxLength = Consts.MAX_UDP_PACKAGE_LENGTH;
				byte[] buffer;
				/*
							 * 注意:
							 * 1.优先保证扩展信息,如果不能保证则返回失败
							 * 2.保证扩展消息的前提下,文本消息可以截取
							 * */
				//写入消息头
				ulong cmdInfo = (ulong)command | options;
				buffer = System.Text.Encoding.Default.GetBytes(string.Format("{0}:{1}:{2}:{3}:{4}:", (char)Consts.VersionNumber, packageNo, userName, hostName, cmdInfo));
				bufferStream.Write(buffer, 0, buffer.Length);
				//计算扩展消息
				int extendMessageLength = extendContents == null ? 0 : extendContents.Length;
				if (extendMessageLength + bufferStream.Length > maxLength)
				{
					extendContents = null;
				}
				extendMessageLength = extendContents == null ? 0 : extendContents.Length + 1;
				//写入文本消息
				if (content != null)
				{
					if (content.Length <= maxLength - extendMessageLength - bufferStream.Length)
						bufferStream.Write(content, 0, content.Length);
					else
						bufferStream.Write(content, 0, maxLength - extendMessageLength - (int)bufferStream.Length);
				}
				//写入扩展消息?
				if (extendMessageLength > 0)
				{
					bufferStream.WriteByte(0);
					bufferStream.Write(extendContents, 0, extendMessageLength - 1);
				}
				bufferStream.Seek(0, System.IO.SeekOrigin.Begin);
				buffer = bufferStream.ToArray();

				return new Entity.PackedNetworkMessage()
				{
					PackageCount = 1,
					PackageIndex = 0,
					Data = buffer,
					SendTimes = 0,
					PackageNo = packageNo,
					RemoteIP = remoteIp,
					//回避BUG:全局参数里面,Absence 选项和 SendCheck 是一样的
					IsReceiveSignalRequired = command != Consts.Commands.Br_Absence && Define.Consts.Check(options, Consts.Cmd_Send_Option.SendCheck) && remoteIp.Address != IPAddress.Broadcast,
					Version = 0
				};
			}
		}
示例#37
0
        public void AddsSymbol()
        {
            Func<Context, SimpleExpression> expression = (context) => new SimpleExpression(context.Address + 3);

            var instr = new Define("test", expression);
            Assert.AreEqual("test", instr.DefinedSymbol.Identifier);
            Assert.AreEqual(LabelType.Private, instr.DefinedSymbol.SymbolType);
            Assert.AreEqual(expression, instr.Expression);

            Context.Address = 5;

            Assert.IsEmpty(instr.Construct(Context).ToList());
            Assert.AreEqual((Int128)8, Context.SymbolTable["test"].Value);
        }
        public void Two_tasks_where_one_depend_on_the_other()
        {
            definition = Define.It(d =>
            {
                d.Task("Check", t => checkExecuted=true);

                d.Task("Build", () => {
                    buildExecuted = true;
                    return new FakeMsBuild
                    {
                        Solution = @"C:\project\somesolution.sln",
                        MaxCpuCount = 2,
                        Properties = new { },
                        Targets = new[] { "Clean", "Build" }
                    };
                }, "Check");
            });
        }
示例#39
0
        public void AddComponentWithExistingDefine()
        {
            Game game = new Game("Test Game");

            Using use = new Using() { File = Path.GetFileName(typeof(TransformComponent).Assembly.Location) };
            game.AddUsing(use);

            Define define = new Define(TransformComponentShort, TransformComponentType);
            use.AddDefine(define);

            Entity entity = new Entity() { Name = "entity" };

            Component component = new Component(game.GetPlugin(TransformComponentShort));
            entity.AddComponent(component);
            game.AddPrototype(entity);

            Assert.AreEqual(1, game.Usings.Count);
            Assert.AreEqual(1, game.Usings.Single().Defines.Count(x => x.Name == TransformComponentShort && x.Class == TransformComponentType));
            Assert.AreEqual(TransformComponentShort, component.Type);
        }
示例#40
0
 /// <summary>
 /// Gets or set an attribute
 /// </summary>
 /// <param name="_key">Attribute key</param>
 /// <returns></returns>
 public Int32 this[Define _key]
 {
     get
     {
         if (this.AttrbitutesData.ContainsKey((UInt32)_key) == true)
         {
             return this.AttrbitutesData[(UInt32)_key];
         }
         return 0;
     }
     set
     {
         if (this.AttrbitutesData.ContainsKey((UInt32)_key) == false)
         {
             this.AttrbitutesData.Add((UInt32)_key, value);
         }
         else
         {
             this.AttrbitutesData[(UInt32)_key] = value;
         }
     }
 }
示例#41
0
 public DefineAdded(Define define)
     : base(NotificationMode.Children)
 {
     Define = define;
 }
示例#42
0
        public void Defines_Can_Be_Retrieved_When_Present()
        {
            var element = new ImmlElement();
            var define = new Define();
            define.Key = Guid.NewGuid().ToString();
            define.Value = Guid.NewGuid().ToString();

            element.Add(define);

            Assert.Equal(1, element.GetDefines().Count);
            Assert.Equal(define.Key, element.GetDefines().First().Key);
            Assert.Equal(define.Value, element.GetDefines().First().Value);
        }
示例#43
0
 /// <summary>
 /// 向きの設定.
 /// </summary>
 /// <param name='type'>
 /// Type.
 /// </param>
 private void SetRotate( Define.RotateType type )
 {
     float angle = (int)type * 90.0f;
     transform.rotation = Quaternion.AngleAxis( angle, Vector3.up );
 }
示例#44
0
		/// <summary>
		/// 发送消息
		/// </summary>
		/// <param name="host">远程主机</param>
		/// <param name="cmd">命令</param>
		/// <param name="options">参数</param>
		/// <param name="normalMsg">常规信息</param>
		/// <param name="extendMessage">扩展消息</param>
		/// <param name="sendCheck">是否检查发送到</param>
		/// <returns>返回发出的消息包编号</returns>
		public ulong SendWithNoCheck(Host host, Define.Consts.Commands cmd, ulong options, string normalMsg, string extendMessage)
		{
			return Send(host, host == null ? broadcastEndPoint : host.HostSub.Ipv4Address, cmd, options, normalMsg, extendMessage, false);
		}
示例#45
0
		/// <summary>
		/// 直接向目标IP发送信息
		/// </summary>
		/// <param name="host">远程主机</param>
		/// <param name="cmd">命令</param>
		/// <param name="options">参数</param>
		/// <param name="normalMsg">常规信息</param>
		/// <param name="extendMessage">扩展消息</param>
		/// <param name="sendCheck">是否检查发送到</param>
		/// <returns>返回发出的消息包编号</returns>
		public ulong SendByIp(IPEndPoint remoteEndPoint, Define.Consts.Commands cmd, ulong options, string normalMsg, string extendMessage)
		{
			return Send(null, remoteEndPoint ?? broadcastEndPoint, cmd, options, normalMsg, extendMessage, false);
		}
示例#46
0
    public Define.EMGameProcess SetProcess( Define.EMGameProcess p_ProcessState )
    {
        m_ProcessState = (int)p_ProcessState;

        return GetProcess();
    }
示例#47
0
		/// <summary>
		/// 通过广播发送消息
		/// </summary>
		/// <param name="cmd">命令</param>
		/// <param name="options">参数</param>
		/// <param name="normalMsg">常规信息</param>
		/// <param name="extendMessage">扩展消息</param>
		/// <param name="sendCheck">是否检查发送到</param>
		/// <returns>返回发出的消息包编号</returns>
		public void Send(Define.Consts.Commands cmd, ulong options, string normalMsg, string extendMessage)
		{
			if (!Client.IsInitialized) return;

			SendWithNoCheck(null, cmd, options, normalMsg, extendMessage);
		}
示例#48
0
		/// <summary>
		/// 发送消息
		/// </summary>
		/// <param name="remoteEndPoint">远程主机地址</param>
		/// <param name="cmd">命令</param>
		/// <param name="options">参数</param>
		/// <param name="normalMsg">常规信息</param>
		/// <param name="extendMessage">扩展消息</param>
		/// <param name="sendCheck">是否检查发送到</param>
		/// <returns>返回发出的消息包编号</returns>
		public ulong Send(Host host, IPEndPoint remoteEndPoint, Define.Consts.Commands cmd, ulong options, string normalMsg, string extendMessage, bool sendCheck)
		{
			Message cm = Message.Create(host, remoteEndPoint, Config.GetRandomTick(), Config.HostName, Config.HostUserName,
				 cmd, options, normalMsg, extendMessage);
			if (sendCheck) cm.IsRequireReceiveCheck = sendCheck;

			return Send(cm);
		}
示例#49
0
		/// <summary>
		/// 发送消息并且要求对方返回已接收消息
		/// </summary>
		/// <param name="host">远程主机.如果为null则会抛出异常</param>
		/// <param name="cmd">命令</param>
		/// <param name="options">参数</param>
		/// <param name="normalMsg">常规信息</param>
		/// <param name="extendMessage">扩展消息</param>
		/// <param name="sendCheck">是否检查发送到</param>
		/// <returns>返回发出的消息包编号</returns>
		public ulong SendWithCheck(Host host, Define.Consts.Commands cmd, ulong options, byte[] normalMsg, byte[] extendMessage)
		{
			if (host == null) throw new ArgumentNullException("host");

			return Send(host, host.HostSub.Ipv4Address, cmd, options, normalMsg, extendMessage, true);
		}
示例#50
0
		/// <summary>
		/// 以二进制模式发送消息
		/// </summary>
		/// <param name="host">关联的远程主机,不可以为null</param>
		/// <param name="remoteEndPoint">远程主机地址</param>
		/// <param name="cmd">命令</param>
		/// <param name="options">参数</param>
		/// <param name="normalMsg">常规信息</param>
		/// <param name="extendMessage">扩展消息</param>
		/// <param name="sendCheck">是否检查发送到</param>
		/// <exception cref="InvalidOperationException">如果对方主机不在列表中,或未知是否支持增强协议,则会抛出此异常</exception>
		/// <returns>返回发出的消息包编号</returns>
		public ulong Send(Host host, IPEndPoint remoteEndPoint, Define.Consts.Commands cmd, ulong options, byte[] normalMsg, byte[] extendMessage, bool sendCheck)
		{
			if (!Client.IsInitialized) return 0ul;

			//判断远程主机是否支持这个模式
			if (host == null || !host.IsEnhancedContractEnabled) throw new InvalidOperationException("尚不知道主机是否支持增强协议模式,无法以二进制模式发送消息!");

			Message cm = Message.Create(host, remoteEndPoint, Config.GetRandomTick(), Config.HostName, Config.NickName,
				 cmd, options, "", "");
			cm.ExtendMessageBytes = extendMessage;
			cm.NormalMsgBytes = normalMsg;
			cm.IsRequireReceiveCheck = sendCheck;

			//设置选项
			if (sendCheck)
			{
				cm.Options |= (ulong)Define.Consts.Cmd_All_Option.RequireReceiveCheck;
			}
			cm.Options |= (ulong)Define.Consts.Cmd_All_Option.EnableNewDataContract | (ulong)Define.Consts.Cmd_All_Option.BinaryMessage;

			MessageEventArgs mea = new MessageEventArgs(cm) { Message = cm, IsHandled = false, Host = host };
			OnMessageSending(mea);
			if (mea.IsHandled) return mea.Message.PackageNo;

			Entity.PackedNetworkMessage[] pnm = MessagePackerV2.BuildNetworkMessage(cm);
			PackageEventArgs pea = new PackageEventArgs(pnm.Length > 1, pnm[0], pnm);
			OnPckageSending(pea);
			if (!pea.IsHandled)
			{
				Array.ForEach(pnm, s => { Client.Send(s); });
				OnPackageSended(pea);
			}
			OnMessageSended(mea);

			return cm.PackageNo;
		}
示例#51
0
 public CmPlus(Define define)
 {
     _cm = define;
 }
 public void Cleanup()
 {
     definition = null;
     checkExecuted = false;
     buildExecuted = false;
 }
示例#53
0
		/// <summary>
		/// 获得消息包的字节流
		/// </summary>
		/// <param name="remoteIp">远程主机地址</param>
		/// <param name="packageNo">包编号</param>
		/// <param name="command">命令</param>
		/// <param name="options">参数</param>
		/// <param name="userName">用户名</param>
		/// <param name="hostName">主机名</param>
		/// <param name="content">正文消息</param>
		/// <param name="extendContents">扩展消息</param>
		/// <returns></returns>
		public static Entity.PackedNetworkMessage[] BuildNetworkMessage(IPEndPoint remoteIp, ulong packageNo, Define.Consts.Commands command, ulong options, string userName, string hostName, byte[] content, byte[] extendContents)
		{
			options |= (ulong)Define.Consts.Cmd_Send_Option.Content_Unicode;

			//每次发送所能容下的数据量
			var maxBytesPerPackage = Define.Consts.MAX_UDP_PACKAGE_LENGTH - PackageHeaderLength;
			//压缩数据流
			var ms = new System.IO.MemoryStream();
			var zip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress);
			var bw = new System.IO.BinaryWriter(zip, System.Text.Encoding.Unicode);
			//写入头部数据
			bw.Write(packageNo);						//包编号
			bw.Write(((ulong)command) | options);		//命令|选项

			bw.Write(userName);				//用户名
			bw.Write(hostName);				//主机名

			bw.Write(content == null ? 0 : content.Length);					//数据长度

			//写入消息数据
			if (content != null) bw.Write(content);
			bw.Write(extendContents == null ? 0 : extendContents.Length);	//补充数据长度
			if (extendContents != null) bw.Write(extendContents);
			bw.Close();
			zip.Close();
			ms.Flush();
			ms.Seek(0, System.IO.SeekOrigin.Begin);

			//打包数据总量
			var dataLength = (int)ms.Length;

			var packageCount = (int)Math.Ceiling(dataLength * 1.0 / maxBytesPerPackage);
			var pnma = new PackedNetworkMessage[packageCount];
			for (var i = 0; i < packageCount; i++)
			{
				var count = i == packageCount - 1 ? dataLength - maxBytesPerPackage * (packageCount - 1) : maxBytesPerPackage;

				var buf = new byte[count + PackageHeaderLength];
				buf[0] = VersionHeader;
				BitConverter.GetBytes(packageNo).CopyTo(buf, 1);
				BitConverter.GetBytes(dataLength).CopyTo(buf, 9);
				BitConverter.GetBytes(packageCount).CopyTo(buf, 13);
				BitConverter.GetBytes(i).CopyTo(buf, 17);
				buf[21] = Define.Consts.Check(options, Define.Consts.Cmd_All_Option.RequireReceiveCheck) ? (byte)1 : (byte)0;	//包确认标志?

				ms.Read(buf, 32, buf.Length - 32);

				pnma[i] = new Entity.PackedNetworkMessage()
				{
					Data = buf,
					PackageCount = packageCount,
					PackageIndex = i,
					PackageNo = packageNo,
					RemoteIP = remoteIp,
					SendTimes = 0,
					Version = 2,
					IsReceiveSignalRequired = buf[21] == 1
				};
			}
			ms.Close();

			return pnma;
		}