private void WindowLoaded(object sender, RoutedEventArgs e)
 {
     var v = new EnumUtil<StoryTypeEnum>();
     cmbTipo.ItemsSource = v.ReturnAsDictionary<int>().Select(x => new
     {
         x.Key,
         x.Value,
         ImageValue = string.Format("/Images/{0}.png", x.Value)
     });
     cmbTipo.DisplayMemberPath = "Key";
     cmbTipo.SelectedValuePath = "Value";
     cmbTipo.SelectedIndex = 1;
 }
        public void TestEnumUtil_GetValues()
        {
            var planets = EnumUtil.GetValues <Planet>();

            Assert.Equal(Planet.EARTH, planets[3]);
        }
Beispiel #3
0
        public override NameValueCollection GetParameters()
        {
            var nvc = base.GetParameters();

            // Basic params
            ParameterValidator.IsNotNull(Amount, "Amount");
            nvc.Add("amount", Amount.ToString());

            ParameterValidator.IsNotNull(IPAddress, "IPAddress");
            nvc.Add("ipAddress", IPAddress);

            ParameterValidator.IsNotNull(ReturnUrl, "ReturnUrl");
            nvc.Add("finishUrl", ReturnUrl);

            if (ParameterValidator.IsNonEmptyInt(PaymentOptionId))
            {
                nvc.Add("paymentOptionId", PaymentOptionId.ToString());
            }

            if (ParameterValidator.IsNonEmptyInt(PaymentOptionSubId))
            {
                nvc.Add("paymentOptionSubId", PaymentOptionSubId.ToString());
            }

            if (!ParameterValidator.IsEmpty(TransferValue))
            {
                if (TransferType == "transaction" || TransferType == "merchant")
                {
                    nvc.Add("transferType", TransferType);
                    nvc.Add("transferValue", TransferValue);
                }
                else
                {
                    throw new Exception("TransferValue cannot be set, without valid TransferType, please fix this.");
                }
            }

            // Transaction
            if (Transaction != null)
            {
                if (!ParameterValidator.IsNull(Transaction.Currency))
                {
                    nvc.Add("transaction[currency]", Transaction.Currency);
                }
                if (ParameterValidator.IsNonEmptyInt(Transaction.CostsVat))
                {
                    nvc.Add("transaction[costsVat]", Transaction.CostsVat.ToString());
                }
                // TODO: exclude cost?
                if (!ParameterValidator.IsEmpty(Transaction.OrderExchangeUrl))
                {
                    nvc.Add("transaction[orderExchangeUrl]", Transaction.OrderExchangeUrl);
                }
                if (!ParameterValidator.IsEmpty(Transaction.Description))
                {
                    nvc.Add("transaction[description]", Transaction.Description);
                }

                /*
                 * if (!ParameterValidator.IsNonEmptyInt(Transaction.EnduserId))
                 * {
                 *  nvc.Add("transaction[enduserId]", Transaction.EnduserId.ToString());
                 * }
                 * */
                if (!ParameterValidator.IsNull(Transaction.ExpireDate))
                {
                    nvc.Add("transaction[expireDate]", ((DateTime)Transaction.ExpireDate).ToString("dd-MM-yyyy hh:mm:ss"));
                }
                // TODO: Are these right? SHouldn't this be BOOL / INT?

                /*
                 * if (!ParameterValidator.IsEmpty(Transaction.SendReminderEmail))
                 * {
                 *  nvc.Add("transaction[sendReminderEmail]", Transaction.SendReminderEmail);
                 * }
                 * if (!ParameterValidator.IsEmpty(Transaction.ReminderMailTemplateId))
                 * {
                 *  nvc.Add("transaction[reminderMailTemplateId]", Transaction.ReminderMailTemplateId);
                 * }
                 */
                if (!ParameterValidator.IsNull(Transaction.OrderNumber))
                {
                    nvc.Add("transaction[orderNumber]", Transaction.OrderNumber);
                }
            }

            // StatsData
            if (StatsData != null)
            {
                if (ParameterValidator.IsNonEmptyInt(StatsData.PromotorId))
                {
                    nvc.Add("statsData[promotorId]", StatsData.PromotorId.ToString());
                }
                if (!ParameterValidator.IsEmpty(StatsData.Info))
                {
                    nvc.Add("statsData[info]", StatsData.Info);
                }
                if (!ParameterValidator.IsEmpty(StatsData.Tool))
                {
                    nvc.Add("statsData[tool]", StatsData.Tool);
                }
                if (!ParameterValidator.IsEmpty(StatsData.Extra1))
                {
                    nvc.Add("statsData[extra1]", StatsData.Extra1);
                }
                if (!ParameterValidator.IsEmpty(StatsData.Extra2))
                {
                    nvc.Add("statsData[extra2]", StatsData.Extra2);
                }
                if (!ParameterValidator.IsEmpty(StatsData.Extra3))
                {
                    nvc.Add("statsData[extra3]", StatsData.Extra3);
                }
                //if (!ParameterValidator.IsEmpty(StatsData.TransferData))
                //{
                //    nvc.Add("statsData[transferData]", StatsData.TransferData);
                //}
            }

            // End user
            if (Enduser != null)
            {
                /*
                 * if (!ParameterValidator.IsEmpty(Enduser.AccessCode))
                 * {
                 *  nvc.Add("enduser[accessCode]", Enduser.AccessCode);
                 * }
                 * */
                if (!ParameterValidator.IsEmpty(Enduser.Language))
                {
                    nvc.Add("enduser[language]", Enduser.Language);
                }
                if (!ParameterValidator.IsEmpty(Enduser.Initials))
                {
                    nvc.Add("enduser[initials]", Enduser.Initials);
                }
                if (!ParameterValidator.IsEmpty(Enduser.Lastname))
                {
                    nvc.Add("enduser[lastName]", Enduser.Lastname);
                }
                if (!ParameterValidator.IsNull(Enduser.Gender))
                {
                    nvc.Add("enduser[gender]", EnumUtil.ToEnumString((Gender)Enduser.Gender));
                }
                if (!ParameterValidator.IsNull(Enduser.BirthDate))
                {
                    nvc.Add("enduser[dob]", ((DateTime)Enduser.BirthDate).ToString("dd-MM-yyyy"));
                }
                if (!ParameterValidator.IsEmpty(Enduser.PhoneNumber))
                {
                    nvc.Add("enduser[phoneNumber]", Enduser.PhoneNumber);
                }
                if (!ParameterValidator.IsEmpty(Enduser.EmailAddress))
                {
                    nvc.Add("enduser[emailAddress]", Enduser.EmailAddress);
                }
                if (!ParameterValidator.IsEmpty(Enduser.BankAccount))
                {
                    nvc.Add("enduser[bankAccount]", Enduser.BankAccount);
                }
                if (!ParameterValidator.IsEmpty(Enduser.IBAN))
                {
                    nvc.Add("enduser[iban]", Enduser.IBAN);
                }

                /*
                 * if (!ParameterValidator.IsNull(Enduser.SendConfirmMail))
                 * {
                 *  nvc.Add("enduser[sendConfirmMail]", ((bool)Enduser.SendConfirmMail) ? "1" : "0");
                 * }
                 * if (!ParameterValidator.IsEmpty(Enduser.ConfirmMailTemplate))
                 * {
                 *  nvc.Add("enduser[confirmMailTemplate]", Enduser.ConfirmMailTemplate);
                 * }
                 * */
                if (!ParameterValidator.IsEmpty(Enduser.CustomerReference))
                {
                    nvc.Add("enduser[customerReference]", Enduser.CustomerReference);
                }
                // Address
                if (Enduser.Address != null)
                {
                    if (!ParameterValidator.IsEmpty(Enduser.Address.StreetName))
                    {
                        nvc.Add("enduser[address][streetName]", Enduser.Address.StreetName);
                    }
                    if (!ParameterValidator.IsEmpty(Enduser.Address.StreetNumber))
                    {
                        nvc.Add("enduser[address][streetNumber]", Enduser.Address.StreetNumber);
                    }
                    if (!ParameterValidator.IsEmpty(Enduser.Address.ZipCode))
                    {
                        nvc.Add("enduser[address][zipCode]", Enduser.Address.ZipCode);
                    }
                    if (!ParameterValidator.IsEmpty(Enduser.Address.City))
                    {
                        nvc.Add("enduser[address][city]", Enduser.Address.City);
                    }
                    if (!ParameterValidator.IsEmpty(Enduser.Address.CountryCode))
                    {
                        nvc.Add("enduser[address][countryCode]", Enduser.Address.CountryCode);
                    }
                }

                // InvoiceAddress
                if (Enduser.InvoiceAddress != null)
                {
                    if (!ParameterValidator.IsEmpty(Enduser.InvoiceAddress.Initials))
                    {
                        nvc.Add("enduser[invoiceAddress][initials]", Enduser.InvoiceAddress.Initials);
                    }
                    if (!ParameterValidator.IsEmpty(Enduser.InvoiceAddress.LastName))
                    {
                        nvc.Add("enduser[invoiceAddress][lastName]", Enduser.InvoiceAddress.LastName);
                    }
                    if (!ParameterValidator.IsNull(Enduser.InvoiceAddress.Gender))
                    {
                        var gender = EnumUtil.ToEnumString((Gender)Enduser.InvoiceAddress.Gender);
                        nvc.Add("enduser[invoiceAddress][gender]", gender);
                    }
                    if (!ParameterValidator.IsEmpty(Enduser.InvoiceAddress.StreetName))
                    {
                        nvc.Add("enduser[invoiceAddress][streetName]", Enduser.InvoiceAddress.StreetName);
                    }
                    if (!ParameterValidator.IsEmpty(Enduser.InvoiceAddress.StreetNumber))
                    {
                        nvc.Add("enduser[invoiceAddress][streetNumber]", Enduser.InvoiceAddress.StreetNumber);
                    }
                    if (!ParameterValidator.IsEmpty(Enduser.InvoiceAddress.ZipCode))
                    {
                        nvc.Add("enduser[invoiceAddress][zipCode]", Enduser.InvoiceAddress.ZipCode);
                    }
                    if (!ParameterValidator.IsEmpty(Enduser.InvoiceAddress.City))
                    {
                        nvc.Add("enduser[invoiceAddress][city]", Enduser.InvoiceAddress.City);
                    }
                    if (!ParameterValidator.IsEmpty(Enduser.InvoiceAddress.CountryCode))
                    {
                        nvc.Add("enduser[invoiceAddress][countryCode]", Enduser.InvoiceAddress.CountryCode);
                    }
                }

                //Company info
                if (Enduser.Company != null)
                {
                    if (!ParameterValidator.IsEmpty(Enduser.Company.CocNumber))
                    {
                        nvc.Add("enduser[company][cocNumber]", Enduser.Company.CocNumber);
                    }
                    if (!ParameterValidator.IsEmpty(Enduser.Company.CountryCode))
                    {
                        nvc.Add("enduser[company][countryCode]", Enduser.Company.CountryCode);
                    }
                    if (!ParameterValidator.IsEmpty(Enduser.Company.Name))
                    {
                        nvc.Add("enduser[company][name]", Enduser.Company.Name);
                    }
                    if (!ParameterValidator.IsEmpty(Enduser.Company.VatNumber))
                    {
                        nvc.Add("enduser[company][vatNumber]", Enduser.Company.VatNumber);
                    }
                }
            }

            // SaleData
            if (SalesData != null)
            {
                if (!ParameterValidator.IsNull(SalesData.DeliveryDate))
                {
                    nvc.Add("saleData[deliveryDate]", SalesData.DeliveryDate.ToString("dd-MM-yyyy"));
                }
                if (!ParameterValidator.IsNull(SalesData.InvoiceDate))
                {
                    nvc.Add("saleData[invoiceDate]", SalesData.InvoiceDate.ToString("dd-MM-yyyy"));
                }
                if (!ParameterValidator.IsNull(SalesData.OrderData))
                {
                    var i = 0;
                    foreach (var data in SalesData.OrderData)
                    {
                        ParameterValidator.IsNotNull(data.ProductId, "SalesData.OrderData.ProductId");
                        nvc.Add(string.Format("saleData[orderData][{0}][productId]", i), data.ProductId);

                        if (!ParameterValidator.IsNull(data.Description))
                        {
                            nvc.Add(string.Format("saleData[orderData][{0}][description]", i), data.Description);
                        }

                        ParameterValidator.IsNotNull(data.Price, "SalesData.OrderData.Price");
                        nvc.Add(string.Format("saleData[orderData][{0}][price]", i), data.Price.ToString());

                        ParameterValidator.IsNotNull(data.Quantity, "SalesData.OrderData.Quantity");
                        nvc.Add(string.Format("saleData[orderData][{0}][quantity]", i), data.Quantity.ToString());

                        if (!ParameterValidator.IsNull(data.VatCode))
                        {
                            nvc.Add(string.Format("saleData[orderData][{0}][vatCode]", i), EnumUtil.ToEnumString((TaxClass)data.VatCode));
                        }
                        if (!ParameterValidator.IsNull(data.ProductType))
                        {
                            nvc.Add(string.Format("saleData[orderData][{0}][productType]", i), EnumUtil.ToEnumString((ProductType)data.ProductType));
                        }
                        i++;
                    }
                }
            }

            // TestMode
            if (!ParameterValidator.IsNull(TestMode))
            {
                nvc.Add("testMode", ((bool)TestMode) ? "1" : "0");
            }

            return(nvc);
        }
Beispiel #4
0
 public UserImageMassMessage(string user, string mediaId)
     : this(EnumUtil.Convert(user), mediaId)
 {
 }
Beispiel #5
0
 public string AddOrUpdateModel(string json)
 {
     try
     {
         JObject jo = JsonConvert.DeserializeObject(json) as JObject;
         //声明更新用的sql
         StringBuilder sql   = new StringBuilder();
         StringBuilder sqlmy = new StringBuilder(@"SELECT * FROM `model`");
         //查询所有字段的字段名dt2,sqlmy
         //存在id则update否则insert dtr,dt,sql2
         DataTable dt2 = ResultUtil.getDataTable(sqlmy.ToString());
         JToken    jid = jo["id"];
         if (jid != null)
         {
             string id = jo["id"].ToString();
             sql.Append(string.Format(@"update `model` set "));
             foreach (KeyValuePair <string, JToken> kyp in jo)
             {
                 foreach (DataColumn dc in dt2.Columns)
                 {
                     if (kyp.Key.Equals(dc.ColumnName) && !string.IsNullOrEmpty(kyp.Value.ToString()))
                     {
                         sql.Append(string.Format(@"{0}={1},", kyp.Key, string.Format(@"'{0}'", kyp.Value)));
                     }
                 }
             }
             string sqls    = sql.ToString();
             string sqlsnew = sqls.Remove(sqls.Length - 1);
             sqlsnew = sqlsnew + " where id=" + id + ";";
             //执行sql
             ResultUtil.insOrUpdOrDel(sqlsnew);
             result = ResultUtil.getStandardResult((int)Status.Normal, EnumUtil.getMessageStr((int)Message.Update), @"success,SQL" + sqlsnew);
         }
         else
         {
             sql.Append(string.Format(@"insert into `model` set "));
             foreach (KeyValuePair <string, JToken> kyp in jo)
             {
                 foreach (DataColumn dc in dt2.Columns)
                 {
                     if (kyp.Key.Equals(dc.ColumnName) && !string.IsNullOrEmpty(kyp.Value.ToString()))
                     {
                         sql.Append(string.Format(@"{0}={1},", kyp.Key, string.Format(@"'{0}'", kyp.Value)));
                     }
                 }
             }
             string sqls    = sql.ToString();
             string sqlsnew = sqls.Remove(sqls.Length - 1);
             //执行sql
             ResultUtil.insOrUpdOrDel(sqlsnew);
             result = ResultUtil.getStandardResult((int)Status.Normal, EnumUtil.getMessageStr((int)Message.Insert), @"success,SQL" + sqlsnew);
         }
     }
     catch (Exception ex)
     {
         //异常日志
         LogHelper.WriteError("注册异常:" + ex.Message);
         //异常结果
         result = ResultUtil.getStandardResult((int)Status.Error, EnumUtil.getMessageStr((int)Message.InsertFailure), ex.Message);
     }
     return(result);
 }
Beispiel #6
0
        static ReturnCode ParseOptions([NotNull] string[] args)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }
            string jpegQualityString = null,
                   imageFormatName   = null,
                   importerName      = null,
                   angleString       = null,
                   isoCatModeName    = null,
                   regionString      = null;

            string importerList = MapUtility.GetImporters().JoinToString(c => c.Format.ToString());

            bool printHelp = false;

            opts = new OptionSet()
                   .Add("a=|angle=",
                        "Angle (orientation) from which the map is drawn. May be -90, 0, 90, 180, or 270. Default is 0.",
                        o => angleString = o)

                   .Add("f=|filter=",
                        "Pattern to filter input filenames, e.g. \"*.dat\" or \"builder*\". " +
                        "Applicable only when a directory name is given as input.",
                        o => inputFilter = o)

                   .Add("i=|importer=",
                        "Optional: Converter used for importing/loading maps. " +
                        "Available importers: Auto (default), " + importerList,
                        o => importerName = o)

                   .Add("e=|export=",
                        "Image format to use for exporting. " +
                        "Supported formats: PNG (default), BMP, GIF, JPEG, TIFF.",
                        o => imageFormatName = o)

                   .Add("m=|mode=",
                        "Rendering mode. May be \"normal\" (default), \"cut\" (cuts out a quarter of the map, revealing inside), " +
                        "\"peeled\" (strips the outer-most layer of blocks), \"chunk\" (renders only a specified region of the map).",
                        o => isoCatModeName = o)

                   .Add("g|nogradient",
                        "Disables altitude-based gradient/shading on terrain.",
                        o => noGradient = (o != null))

                   .Add("s|noshadows",
                        "Disables rendering of shadows.",
                        o => noShadows = (o != null))

                   .Add("o=|output=",
                        "Path to save images to. " +
                        "If not specified, images will be saved to the maps' directories.",
                        o => outputDirName = o)

                   .Add("y|overwrite",
                        "Do not ask for confirmation to overwrite existing files.",
                        o => overwrite = (o != null))

                   .Add("q=|quality=",
                        "Sets JPEG compression quality. Between 0 and 100. Default is 80. " +
                        "Applicable only when exporting images to .jpg or .jpeg.",
                        o => jpegQualityString = o)

                   .Add("r|recursive",
                        "Look through all subdirectories for map files. " +
                        "Applicable only when a directory name is given as input.",
                        o => recursive = (o != null))

                   .Add("region=",
                        "Region of the map to render. Should be given in following format: \"region=x1,y1,z1,x2,y2,z2\" " +
                        "Applicable only when rendering mode is set to \"chunk\".",
                        o => regionString = o)

                   .Add("w|seethroughwater",
                        "Makes all water see-through, instead of mostly opaque.",
                        o => seeThroughWater = (o != null))

                   .Add("l|seethroughlava",
                        "Makes all lava partially see-through, instead of opaque.",
                        o => seeThroughLava = (o != null))

                   .Add("u|uncropped",
                        "Does not crop the finished map image, leaving some empty space around the edges.",
                        o => uncropped = (o != null))

                   .Add("?|h|help",
                        "Prints out the options.",
                        o => printHelp = (o != null));

            List <string> pathList;

            try {
                pathList = opts.Parse(args);
            } catch (OptionException ex) {
                Console.Error.Write("MapRenderer: ");
                Console.Error.WriteLine(ex.Message);
                PrintHelp();
                return(ReturnCode.ArgumentError);
            }

            if (printHelp)
            {
                PrintHelp();
                Environment.Exit((int)ReturnCode.Success);
            }

            if (pathList.Count != 1)
            {
                Console.Error.WriteLine("MapRenderer: At least one file or directory name required.");
                PrintUsage();
                return(ReturnCode.ArgumentError);
            }
            inputPath = pathList[0];

            // Parse angle
            if (angleString != null && (!Int32.TryParse(angleString, out angle) ||
                                        angle != -90 && angle != 0 && angle != 180 && angle != 270))
            {
                Console.Error.WriteLine("MapRenderer: Angle must be a number: -90, 0, 90, 180, or 270");
                return(ReturnCode.ArgumentError);
            }

            // Parse mode
            if (isoCatModeName != null && !EnumUtil.TryParse(isoCatModeName, out mode, true))
            {
                Console.Error.WriteLine(
                    "MapRenderer: Rendering mode should be: \"normal\", \"cut\", \"peeled\", or \"chunk\".");
                return(ReturnCode.ArgumentError);
            }

            // Parse region (if in chunk mode)
            if (mode == IsoCatMode.Chunk)
            {
                if (regionString == null)
                {
                    Console.Error.WriteLine("MapRenderer: Region parameter is required when mode is set to \"chunk\"");
                    return(ReturnCode.ArgumentError);
                }
                try {
                    string[] regionParts = regionString.Split(',');
                    region = new BoundingBox(Int32.Parse(regionParts[0]), Int32.Parse(regionParts[1]),
                                             Int32.Parse(regionParts[2]),
                                             Int32.Parse(regionParts[3]), Int32.Parse(regionParts[4]),
                                             Int32.Parse(regionParts[5]));
                } catch {
                    Console.Error.WriteLine(
                        "MapRenderer: Region should be specified in the following format: \"--region=x1,y1,z1,x2,y2,z2\"");
                }
            }
            else if (regionString != null)
            {
                Console.Error.WriteLine(
                    "MapRenderer: Region parameter is given, but rendering mode was not set to \"chunk\"");
            }

            // Parse given image format
            if (imageFormatName != null)
            {
                if (imageFormatName.Equals("BMP", StringComparison.OrdinalIgnoreCase))
                {
                    exportFormat       = ImageFormat.Bmp;
                    imageFileExtension = ".bmp";
                }
                else if (imageFormatName.Equals("GIF", StringComparison.OrdinalIgnoreCase))
                {
                    exportFormat       = ImageFormat.Gif;
                    imageFileExtension = ".gif";
                }
                else if (imageFormatName.Equals("JPEG", StringComparison.OrdinalIgnoreCase) ||
                         imageFormatName.Equals("JPG", StringComparison.OrdinalIgnoreCase))
                {
                    exportFormat       = ImageFormat.Jpeg;
                    imageFileExtension = ".jpg";
                }
                else if (imageFormatName.Equals("PNG", StringComparison.OrdinalIgnoreCase))
                {
                    exportFormat       = ImageFormat.Png;
                    imageFileExtension = ".png";
                }
                else if (imageFormatName.Equals("TIFF", StringComparison.OrdinalIgnoreCase) ||
                         imageFormatName.Equals("TIF", StringComparison.OrdinalIgnoreCase))
                {
                    exportFormat       = ImageFormat.Tiff;
                    imageFileExtension = ".tif";
                }
                else
                {
                    Console.Error.WriteLine(
                        "MapRenderer: Image file format should be: BMP, GIF, JPEG, PNG, or TIFF");
                    return(ReturnCode.ArgumentError);
                }
            }

            // Parse JPEG quality
            if (jpegQualityString != null)
            {
                if (exportFormat == ImageFormat.Jpeg)
                {
                    if (!Int32.TryParse(jpegQualityString, out jpegQuality) || jpegQuality < 0 || jpegQuality > 100)
                    {
                        Console.Error.WriteLine(
                            "MapRenderer: JpegQuality parameter should be a number between 0 and 100");
                        return(ReturnCode.ArgumentError);
                    }
                }
                else
                {
                    Console.Error.WriteLine(
                        "MapRenderer: JpegQuality parameter given, but image export format was not set to \"JPEG\".");
                }
            }

            // parse importer name
            if (importerName != null && !importerName.Equals("auto", StringComparison.OrdinalIgnoreCase))
            {
                MapFormat importFormat;
                if (!EnumUtil.TryParse(importerName, out importFormat, true) ||
                    (mapImporter = MapUtility.GetImporter(importFormat)) == null)
                {
                    Console.Error.WriteLine("Unsupported importer \"{0}\"", importerName);
                    PrintUsage();
                    return(ReturnCode.UnrecognizedImporter);
                }
            }

            return(ReturnCode.Success);
        }
Beispiel #7
0
 public T?GetEnum <T>(string name) where T : struct
 {
     return(EnumUtil.TryParse <T>(Get(name)));
 }
Beispiel #8
0
        public override void Execute()
        {
            IStat   stat;
            RetCode rc;
            long    ap = 0;
            long    i;

            gOut.Print("{0}", Globals.LineSep);

            /*
             *      Full Credit:  Derived wholly from Donald Brown's Classic Eamon
             *
             *      File: MAIN HALL
             *      Line: 3010
             */

            if (Rtio == null)
            {
                var c2 = Globals.Character.GetMerchantAdjustedCharisma();

                Rtio = gEngine.GetMerchantRtio(c2);
            }

            gOut.Print("A lovely young woman says, \"Good day, {0}.  Ah, you're surprised that I know your name?  I also know the extent of your intellect, hardiness, agility, and charisma.  If you wish, I can magically raise your attributes.  Which one would you like me to focus on?\"", Globals.Character.Name);

            gOut.Print("{0}", Globals.LineSep);

            Buf.Clear();

            var statValues = EnumUtil.GetValues <Stat>();

            for (i = 0; i < statValues.Count; i++)
            {
                stat = gEngine.GetStats(statValues[(int)i]);

                Debug.Assert(stat != null);

                Buf.AppendFormat("{0}{1}{2}={3}{4}",
                                 i == 0 ? Environment.NewLine : "",
                                 i != 0 ? ", " : "",
                                 (long)statValues[(int)i],
                                 stat.Name,
                                 i == statValues.Count - 1 ? ": " : "");
            }

            gOut.Write("{0}", Buf);

            Buf.Clear();

            rc = Globals.In.ReadField(Buf, Constants.BufSize02, null, ' ', '\0', false, null, null, gEngine.IsCharStat, gEngine.IsCharStat);

            Debug.Assert(gEngine.IsSuccess(rc));

            Globals.Thread.Sleep(150);

            gOut.Print("{0}", Globals.LineSep);

            Debug.Assert(Buf.Length > 0);

            i = Convert.ToInt64(Buf.Trim().ToString());

            stat = gEngine.GetStats((Stat)i);

            Debug.Assert(stat != null);

            ap = gEngine.GetMerchantAskPrice(Constants.StatGainPrice, (double)Rtio);

            gOut.Print("\"My standard price is {0} gold piece{1} per attribute point.\"", ap, ap != 1 ? "s" : "");

            while (true)
            {
                ap = gEngine.GetMerchantAskPrice(Constants.StatGainPrice, (double)Rtio);

                Globals.In.KeyPress(Buf);

                gOut.Print("{0}", Globals.LineSep);

                gOut.Print("Attribute: {0}        Gold: {1}        Cost: {2}", Globals.Character.GetStats(i), Globals.Character.HeldGold, ap);

                if (Globals.Character.HeldGold >= ap)
                {
                    gOut.Write("{0}1=Raise, X=Exit: ", Environment.NewLine);

                    Buf.Clear();

                    rc = Globals.In.ReadField(Buf, Constants.BufSize02, null, ' ', '\0', false, null, gEngine.ModifyCharToUpper, gEngine.IsChar1OrX, gEngine.IsChar1OrX);

                    Debug.Assert(gEngine.IsSuccess(rc));

                    Globals.Thread.Sleep(150);

                    gOut.Print("{0}", Globals.LineSep);

                    if (Buf.Length == 0 || Buf[0] == 'X')
                    {
                        break;
                    }
                    else
                    {
                        gOut.Print("The witch begins an incantation and you are enveloped by a hazy white cloud.");

                        var rl = gEngine.RollDice(1, 24, 0);

                        if (rl >= Globals.Character.GetStats(Stat.Charisma))
                        {
                            gOut.Print("\"It is done!\" she exclaims.");

                            Globals.Character.ModStats(i, 1);
                        }
                        else
                        {
                            gOut.Print("\"Because of your powerful adventurer's aura, my spells will sometimes fail.  Unfortunately, this was one of those times.\"");
                        }

                        if (Globals.Character.GetStats(i) > stat.MaxValue)
                        {
                            Globals.Character.SetStats(i, stat.MaxValue);
                        }

                        Globals.Character.HeldGold -= ap;

                        Globals.CharactersModified = true;
                    }
                }
                else
                {
                    gOut.Print("\"Ah, but I see you can't afford my modest fee.\"");

                    break;
                }
            }

            gOut.Print("\"Good faring, {0}!\"", Globals.Character.Name);

            Globals.In.KeyPress(Buf);
        }
 /// <summary>
 /// Defines the flag names and values</summary>
 /// <param name="definitions">Flag definitions array</param>
 /// <remarks>Flag values default to successive powers of 2, starting with 1. Flag names
 /// with the format "FlagName=X" are parsed so that FlagName gets the value X, where X is
 /// an int.</remarks>
 public void DefineFlags(string[] definitions)
 {
     EnumUtil.ParseFlagDefinitions(definitions, out m_names, out m_displayNames, out m_values);
 }
Beispiel #10
0
        /// <summary>
        /// TargetGridのヘッダ行作成
        /// </summary>
        private void CreateHeader()
        {
            //データクリア
            this.TargetGrid.Rows.Count = RowHeaderCount;
            this.TargetGrid.Cols.Count = Enum.GetValues(typeof(ColIndex)).Length + 1;

            this.TargetGrid[0, (int)ColIndex.TargetCheck]                = EnumUtil.GetLabel(ColIndex.TargetCheck);
            this.TargetGrid.Cols[(int)ColIndex.TargetCheck].Width        = 30;
            this.TargetGrid.Cols[(int)ColIndex.TargetCheck].DataType     = typeof(bool);
            this.TargetGrid.Cols[(int)ColIndex.TargetCheck].AllowEditing = true;
            this.TargetGrid[0, (int)ColIndex.Status]                    = EnumUtil.GetLabel(ColIndex.Status);
            this.TargetGrid.Cols[(int)ColIndex.Status].Width            = 70;
            this.TargetGrid.Cols[(int)ColIndex.Status].AllowEditing     = false;
            this.TargetGrid[0, (int)ColIndex.FileIcon]                  = EnumUtil.GetLabel(ColIndex.FileIcon);
            this.TargetGrid.Cols[(int)ColIndex.FileIcon].Width          = 30;
            this.TargetGrid.Cols[(int)ColIndex.FileIcon].ImageAlign     = ImageAlignEnum.CenterCenter;
            this.TargetGrid.Cols[(int)ColIndex.FileIcon].AllowEditing   = false;
            this.TargetGrid[0, (int)ColIndex.FileName]                  = EnumUtil.GetLabel(ColIndex.FileName);
            this.TargetGrid.Cols[(int)ColIndex.FileName].Width          = 200;
            this.TargetGrid.Cols[(int)ColIndex.FileName].AllowEditing   = false;
            this.TargetGrid[0, (int)ColIndex.FullPath]                  = EnumUtil.GetLabel(ColIndex.FullPath);
            this.TargetGrid.Cols[(int)ColIndex.FullPath].Width          = 100;
            this.TargetGrid.Cols[(int)ColIndex.FullPath].AllowEditing   = false;
            this.TargetGrid[0, (int)ColIndex.Extension]                 = EnumUtil.GetLabel(ColIndex.Extension);
            this.TargetGrid.Cols[(int)ColIndex.Extension].Width         = 40;
            this.TargetGrid.Cols[(int)ColIndex.Extension].AllowEditing  = false;
            this.TargetGrid[0, (int)ColIndex.UpdateDate]                = EnumUtil.GetLabel(ColIndex.UpdateDate);
            this.TargetGrid.Cols[(int)ColIndex.UpdateDate].Width        = 100;
            this.TargetGrid.Cols[(int)ColIndex.UpdateDate].AllowEditing = false;
            this.TargetGrid[0, (int)ColIndex.Title]                      = EnumUtil.GetLabel(ColIndex.Title);
            this.TargetGrid.Cols[(int)ColIndex.Title].Width              = 80;
            this.TargetGrid.Cols[(int)ColIndex.Title].AllowEditing       = false;
            this.TargetGrid[0, (int)ColIndex.ReleaseDate]                = EnumUtil.GetLabel(ColIndex.ReleaseDate);
            this.TargetGrid.Cols[(int)ColIndex.ReleaseDate].Width        = 80;
            this.TargetGrid.Cols[(int)ColIndex.ReleaseDate].AllowEditing = false;
            this.TargetGrid[0, (int)ColIndex.Artist]                     = EnumUtil.GetLabel(ColIndex.Artist);
            this.TargetGrid.Cols[(int)ColIndex.Artist].Width             = 40;
            this.TargetGrid.Cols[(int)ColIndex.Artist].AllowEditing      = false;
            this.TargetGrid[0, (int)ColIndex.Genres]                     = EnumUtil.GetLabel(ColIndex.Genres);
            this.TargetGrid.Cols[(int)ColIndex.Genres].Width             = 100;
            this.TargetGrid.Cols[(int)ColIndex.Genres].AllowEditing      = false;
            this.TargetGrid[0, (int)ColIndex.Maker]                      = EnumUtil.GetLabel(ColIndex.Maker);
            this.TargetGrid.Cols[(int)ColIndex.Maker].Width              = 80;
            this.TargetGrid.Cols[(int)ColIndex.Maker].AllowEditing       = false;
            this.TargetGrid[0, (int)ColIndex.Director]                   = EnumUtil.GetLabel(ColIndex.Director);
            this.TargetGrid.Cols[(int)ColIndex.Director].Width           = 100;
            this.TargetGrid.Cols[(int)ColIndex.Director].AllowEditing    = false;
            this.TargetGrid[0, (int)ColIndex.Comment]                    = EnumUtil.GetLabel(ColIndex.Comment);
            this.TargetGrid.Cols[(int)ColIndex.Comment].Width            = 100;
            this.TargetGrid.Cols[(int)ColIndex.Comment].AllowEditing     = false;
            this.TargetGrid[0, (int)ColIndex.PageUrl]                    = EnumUtil.GetLabel(ColIndex.PageUrl);
            this.TargetGrid.Cols[(int)ColIndex.PageUrl].Width            = 1;
            this.TargetGrid.Cols[(int)ColIndex.PageUrl].AllowEditing     = false;
            this.TargetGrid[0, (int)ColIndex.ImageUrl]                   = EnumUtil.GetLabel(ColIndex.ImageUrl);
            this.TargetGrid.Cols[(int)ColIndex.ImageUrl].Width           = 1;
            this.TargetGrid.Cols[(int)ColIndex.ImageUrl].AllowEditing    = false;
            this.TargetGrid[0, (int)ColIndex.Image]                      = EnumUtil.GetLabel(ColIndex.Image);
            this.TargetGrid.Cols[(int)ColIndex.Image].Width              = 100;
            this.TargetGrid.Cols[(int)ColIndex.Image].AllowEditing       = false;

            this.TargetGrid.Cols.Frozen = (int)ColIndex.FileName;
        }
Beispiel #11
0
        /// <summary>
        /// 動画ファイル検索&タグ情報取得
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SearchTarget_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = (BackgroundWorker)sender;
            var targetDir       = (string)e.Argument;

            var mp4wd      = new MP4WebDriver();
            var resultList = mp4wd.GetTagInfo(targetDir, bw);

            //グリッドに表示
            _dispatcher.BeginInvoke(new Action(() => {
                this.TargetGrid.Rows.Count = RowHeaderCount;

                var bu = new BitmapUtil();
                this.TargetGrid.Rows.Count = resultList.Count + RowHeaderCount;
                this.DenominatorLabel.Text = resultList.Count.ToString() + "件";
                int i = RowHeaderCount;
                foreach (var row in resultList)
                {
                    var fi = row.Key;
                    var ti = row.Value;

                    //対象
                    if (StringUtil.NullToBlank(ti.Title) != "")
                    {
                        this.TargetGrid[i, (int)ColIndex.TargetCheck] = true;
                        this.TargetGrid.Rows[i].AllowEditing          = true;
                        this.TargetGrid[i, (int)ColIndex.Status]      = EnumUtil.GetLabel(StatusEnum.Avairable);
                    }
                    else
                    {
                        this.TargetGrid[i, (int)ColIndex.TargetCheck] = false;
                        this.TargetGrid.Rows[i].AllowEditing          = false;
                        this.TargetGrid.Rows[i].StyleNew.BackColor    = Color.Gainsboro;
                        this.TargetGrid[i, (int)ColIndex.Status]      = EnumUtil.GetLabel(StatusEnum.UnAvairable);
                    }
                    //ファイルアイコン
                    Bitmap bmp = null;
                    bmp        = Properties.Resources.File16;
                    try {
                        bmp = Icon.ExtractAssociatedIcon(fi.FullName).ToBitmap();
                    } catch {
                        //プレビューを取得できない場合は、デフォルトアイコンを表示
                    }
                    bmp.MakeTransparent();
                    this.TargetGrid.SetCellImage(i, (int)ColIndex.FileIcon, bu.Resize(bmp, 16, 16));
                    //ファイル名
                    this.TargetGrid[i, (int)ColIndex.FileName]   = fi.Name;
                    this.TargetGrid[i, (int)ColIndex.FullPath]   = fi.FullName;
                    this.TargetGrid[i, (int)ColIndex.Extension]  = fi.Extension;
                    this.TargetGrid[i, (int)ColIndex.UpdateDate] = fi.LastWriteTime;
                    //タグ情報
                    this.TargetGrid[i, (int)ColIndex.Title]       = StringUtil.NullToBlank(ti.Title);
                    this.TargetGrid[i, (int)ColIndex.ReleaseDate] = StringUtil.NullToBlank(ti.ReleaseDate);
                    this.TargetGrid[i, (int)ColIndex.Artist]      = StringUtil.NullToBlank(ti.Performers);
                    this.TargetGrid[i, (int)ColIndex.Genres]      = StringUtil.NullToBlank(ti.Genres);
                    this.TargetGrid[i, (int)ColIndex.Maker]       = StringUtil.NullToBlank(ti.Maker);
                    this.TargetGrid[i, (int)ColIndex.Director]    = StringUtil.NullToBlank(ti.Director);
                    this.TargetGrid[i, (int)ColIndex.Comment]     = StringUtil.NullToBlank(ti.Comment);
                    this.TargetGrid[i, (int)ColIndex.PageUrl]     = StringUtil.NullToBlank(ti.PageUrl);
                    this.TargetGrid[i, (int)ColIndex.ImageUrl]    = StringUtil.NullToBlank(ti.ImageUrl);
                    this.TargetGrid.SetCellImage(i, (int)ColIndex.Image, bu.GetBitmapFromURL(ti.ImageUrl));

                    i++;
                }
                //先頭行を選択
                if (this.TargetGrid.Rows.Count > RowHeaderCount)
                {
                    this.TargetGrid.Select(RowHeaderCount, (int)ColIndex.TargetCheck);
                }
            }));
        }
Beispiel #12
0
        /// <summary>
        /// Signs out of the device using the provided sign out method
        /// </summary>
        /// <param name="signOutMethod">The sign out method.</param>
        /// <exception cref="HP.ScalableTest.DeviceAutomation.DeviceWorkflowException">SiriusUIv3 devices do not support  + EnumUtil.GetDescription(signOutMethod)</exception>
        public void SignOut(DeviceSignOutMethod signOutMethod)
        {
            RecordInfo(DeviceWorkflowMarker.SignOutType, signOutMethod.ToString());
            RecordEvent(DeviceWorkflowMarker.DeviceSignOutBegin);

            switch (signOutMethod)
            {
            case DeviceSignOutMethod.PressSignOut:
                NavigateHome();
                PressSignOutButton();
                break;

            case DeviceSignOutMethod.Timeout:
                SignOutByTimeout();
                break;

            case DeviceSignOutMethod.PressResetHardKey:
                Reset();
                break;

            default:
                throw new DeviceWorkflowException("SiriusUIv3 devices do not support " + EnumUtil.GetDescription(signOutMethod));
            }
            RecordEvent(DeviceWorkflowMarker.DeviceSignOutEnd);
        }
        private void ImportScenarios(string fileName, Guid folderId)
        {
            int totalActivities = 0;
            List <Database.EnterpriseScenario> exportedScenarios;

            using (FileStream fs = File.OpenRead(fileName))
            {
                StreamReader sReader        = new StreamReader(fs);
                var          scenarioString = sReader.ReadToEnd();
                exportedScenarios = (List <Database.EnterpriseScenario>)JsonConvert.DeserializeObject(scenarioString, typeof(List <Database.EnterpriseScenario>));
            }

            using (EnterpriseTestContext context = new EnterpriseTestContext(_currentDatabase))
            {
                foreach (var sourceScenario in exportedScenarios)
                {
                    EnterpriseScenario targetScenario = new EnterpriseScenario
                    {
                        Name = sourceScenario.Name,
                        EnterpriseScenarioId = SequentialGuid.NewGuid(),
                        FolderId             = folderId,
                        Company          = sourceScenario.Company,
                        Deleted          = false,
                        Description      = sourceScenario.Description,
                        Owner            = UserManager.CurrentUserName,
                        ScenarioSettings = sourceScenario.ScenarioSettings,
                        Vertical         = sourceScenario.Vertical
                    };
                    //if (context.EnterpriseScenarios.FirstOrDefault(x =>
                    //        x.EnterpriseScenarioId == sourceScenario.EnterpriseScenarioId) != null)
                    //{
                    //    targetScenario.EnterpriseScenarioId = SequentialGuid.NewGuid();
                    //}

                    foreach (var sourceScenarioVirtualResource in sourceScenario.VirtualResources)
                    {
                        SolutionTester targetVirtualResource = new SolutionTester("SolutionTester")
                        {
                            Description          = sourceScenarioVirtualResource.Description,
                            Enabled              = true,
                            EnterpriseScenarioId = targetScenario.EnterpriseScenarioId,
                            Name                   = sourceScenarioVirtualResource.Name,
                            InstanceCount          = sourceScenarioVirtualResource.InstanceCount,
                            Platform               = sourceScenarioVirtualResource.Platform,
                            ResourceType           = sourceScenarioVirtualResource.ResourceType,
                            ResourcesPerVM         = sourceScenarioVirtualResource.ResourcePerVM,
                            TestCaseId             = sourceScenarioVirtualResource.TestCaseId,
                            VirtualResourceId      = SequentialGuid.NewGuid(),
                            DurationTime           = sourceScenarioVirtualResource.DurationTime,
                            MaxActivityDelay       = sourceScenarioVirtualResource.MaxActivityDelay,
                            MinActivityDelay       = sourceScenarioVirtualResource.MinActivityDelay,
                            RandomizeActivities    = sourceScenarioVirtualResource.RandomizeActivities,
                            RandomizeActivityDelay = sourceScenarioVirtualResource.RandomizeActivityDelay,
                            ExecutionMode          = EnumUtil.Parse <ExecutionMode>(sourceScenarioVirtualResource.RunMode),
                            MaxStartupDelay        = sourceScenarioVirtualResource.MaxStartupDelay,
                            MinStartupDelay        = sourceScenarioVirtualResource.MinStartupDelay,
                            RandomizeStartupDelay  = sourceScenarioVirtualResource.RandomizeStartupDelay,
                            RepeatCount            = sourceScenarioVirtualResource.RepeatCount,
                            AccountType            = SolutionTesterCredentialType.DefaultDesktop,
                            UseCredential          = false
                        };

                        //if (context.VirtualResources.FirstOrDefault(x =>
                        //        x.VirtualResourceId == sourceScenarioVirtualResource.VirtualResourceId) != null)
                        //{
                        //    targetVirtualResource.VirtualResourceId = SequentialGuid.NewGuid();
                        //}

                        foreach (var virtualResourceMetadata in sourceScenarioVirtualResource.VirtualResourceMetadata)
                        {
                            VirtualResourceMetadata targetVirtualResourceMetadata =
                                new VirtualResourceMetadata(virtualResourceMetadata.ResourceType,
                                                            virtualResourceMetadata.MetadataType)
                            {
                                VirtualResourceId = targetVirtualResource.VirtualResourceId,
                                Deleted           = false,
                                Enabled           = true,
                                ExecutionPlan     = virtualResourceMetadata.ExecutionPlan,
                                Metadata          = virtualResourceMetadata.Metadata,
                                MetadataVersion   = virtualResourceMetadata.MetadataVersion,
                                MetadataType      = virtualResourceMetadata.MetadataType,
                                Name         = virtualResourceMetadata.Name,
                                ResourceType = virtualResourceMetadata.ResourceType,
                                VirtualResourceMetadataId = SequentialGuid.NewGuid(),
                            };
                            //if (context.VirtualResourceMetadataSet.FirstOrDefault(x =>
                            //        x.VirtualResourceMetadataId ==
                            //        targetVirtualResourceMetadata.VirtualResourceMetadataId) != null)
                            //{
                            //    targetVirtualResourceMetadata.VirtualResourceMetadataId = SequentialGuid.NewGuid();
                            //}

                            targetVirtualResourceMetadata.AssetUsage = VirtualResourceMetadataAssetUsage
                                                                       .CreateVirtualResourceMetadataAssetUsage(
                                targetVirtualResourceMetadata.VirtualResourceMetadataId,
                                Serializer.Serialize(_edtAssetSelectionControl.AssetSelectionData).ToString());
                            targetVirtualResource.VirtualResourceMetadataSet.Add(targetVirtualResourceMetadata);
                            totalActivities++;
                        }
                        targetScenario.VirtualResources.Add(targetVirtualResource);
                    }
                    context.EnterpriseScenarios.AddObject(targetScenario);
                }

                try
                {
                    MessageBox.Show(
                        $"Found {totalActivities} activities to import. This might take few minutes to complete. Please be patient. Press OK to proceed.",
                        ApplicationName, MessageBoxButton.OK, MessageBoxImage.Information);
                    context.SaveChanges();
                    MessageBox.Show($"{exportedScenarios.Count} scenarios successfully imported.", ApplicationName,
                                    MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (SqlException sqlException)
                {
                    MessageBox.Show($"Error occurred while importing the scenario. {ScalableTest.Extension.JoinAllErrorMessages(sqlException)}",
                                    ApplicationName, MessageBoxButton.OK, MessageBoxImage.Error);
                }
                catch (UpdateException updateException)
                {
                    MessageBox.Show($"Error occurred while importing the scenario. {ScalableTest.Extension.JoinAllErrorMessages(updateException)}",
                                    ApplicationName, MessageBoxButton.OK, MessageBoxImage.Error);
                }
                catch (Exception e)
                {
                    MessageBox.Show($"An unknown error occurred while importing scenario. {ScalableTest.Extension.JoinAllErrorMessages(e)}", ApplicationName, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
Beispiel #14
0
        /// <summary>
        /// Deserialize Chart Properties
        /// </summary>
        /// <param name="q"></param>
        /// <param name="tr"></param>
        /// <param name="view"></param>

        public static bool DeserializeChartProperties(
            Query q,
            XmlTextReader tr,
            ResultsViewProps view)
        {
            AxisMx ax;
            Enum   iEnum = null;
            string txt;

            if (!Lex.Eq(tr.Name, "ChartProperties"))
            {
                return(false);
            }

            if (XmlUtil.GetEnumAttribute(tr, "ShapeRenderingMode", typeof(ShapeRenderingMode), ref iEnum))
            {
                view.ShapeRenderingMode = (ShapeRenderingMode)iEnum;
            }

            //XmlUtil.GetStringAttribute(tr, "BackgroundImageFile", ref view.BackgroundImageFile);
            XmlUtil.GetIntAttribute(tr, "Jitter", ref view.JitterX);
            XmlUtil.GetBoolAttribute(tr, "ChartStretch", ref view.JitterTheSameForXandY);

            XmlUtil.GetBoolAttribute(tr, "ShowLegend", ref view.ShowLegend);

            if (tr.GetAttribute("LegendAlignmentHorizontal") != null)
            {
                view.LegendAlignmentHorizontal =
                    (LegendAlignmentHorizontal)EnumUtil.Parse(typeof(LegendAlignmentHorizontal), tr.GetAttribute("LegendAlignmentHorizontal"));
            }

            if (tr.GetAttribute("LegendAlignmentVertical") != null)
            {
                view.LegendAlignmentVertical =
                    (LegendAlignmentVertical)EnumUtil.Parse(typeof(LegendAlignmentVertical), tr.GetAttribute("LegendAlignmentVertical"));
            }

            XmlUtil.GetIntAttribute(tr, "LegendMaxHorizontalPercentage", ref view.LegendMaxHorizontalPercentage);
            XmlUtil.GetIntAttribute(tr, "LegendMaxVerticalPercentage", ref view.LegendMaxVerticalPercentage);

            if (tr.GetAttribute("LegendItemOrder") != null)
            {
                view.LegendItemOrder =
                    (LegendDirection)EnumUtil.Parse(typeof(LegendDirection), tr.GetAttribute("LegendItemOrder"));
            }

            XmlUtil.GetBoolAttribute(tr, "MainChartAreaMaximized", ref view.MainViewPanelMaximized);
            XmlUtil.GetBoolAttribute(tr, "ShowFilters", ref view.ShowFilters);
            XmlUtil.GetBoolAttribute(tr, "ShowSelectedDataRows", ref view.ShowSelectedDataRows);

            XmlUtil.GetBoolAttribute(tr, "ShowAxesTitles", ref view.ShowAxesTitles);
            XmlUtil.GetBoolAttribute(tr, "ShowAxesScaleLabels", ref view.ShowAxesScaleLabels);
            XmlUtil.GetBoolAttribute(tr, "RotateAxes", ref view.RotateAxes);

            XmlUtil.GetBoolAttribute(tr, "UseExistingCondFormatting", ref view.UseExistingCondFormatting);
            XmlUtil.GetBoolAttribute(tr, "PivotedData", ref view.PivotedData);

            while (true)             // loop through elements of chart
            {
                tr.Read(); tr.MoveToContent();

                if (Lex.Eq(tr.Name, "XAxis"))
                {
                    view.XAxisMx = AxisMx.DeserializeAxis("XAxis", q, tr);
                }

                else if (Lex.Eq(tr.Name, "YAxis"))
                {
                    view.YAxisMx = AxisMx.DeserializeAxis("YAxis", q, tr);
                }

                else if (Lex.Eq(tr.Name, "ZAxis"))
                {
                    view.ZAxisMx = AxisMx.DeserializeAxis("ZAxis", q, tr);
                }

                else if (Lex.Eq(tr.Name, "Axis"))
                {
                    ax = AxisMx.DeserializeAxis("Axis", q, tr);
                    view.AxesMx.Add(ax);
                }

                else if (Lex.Eq(tr.Name, "MarkerColor"))
                {
                    view.MarkerColor = ColorDimension.Deserialize("MarkerColor", q, tr);
                }

                else if (Lex.Eq(tr.Name, "MarkerSize"))
                {
                    view.MarkerSize = SizeDimension.Deserialize("MarkerSize", q, tr);
                }

                else if (Lex.Eq(tr.Name, "MarkerShape"))
                {
                    view.MarkerShape = ShapeDimension.Deserialize("MarkerShape", q, tr);
                }

                else if (Lex.Eq(tr.Name, "MarkerLabel"))
                {
                    view.MarkerLabel = LabelDimensionDef.Deserialize("MarkerLabel", q, tr);
                }

                else if (Lex.Eq(tr.Name, "Labels"))                 // obsolete label tag
                {
                    view.MarkerLabel = LabelDimensionDef.Deserialize("Labels", q, tr);
                }

                else if (Lex.Eq(tr.Name, "TooltipFields"))
                {
                    view.MarkerTooltip = TooltipDimensionDef.Deserialize("TooltipFields", q, tr);
                }

                else if (Lex.Eq(tr.Name, "Surface"))
                {
                    txt = tr.GetAttribute("FillMode");
                    if (txt != null)
                    {
                        view.SurfaceFillMode = (SurfaceFillMode)EnumUtil.Parse(typeof(SurfaceFillMode), txt);
                    }

                    XmlUtil.GetBoolAttribute(tr, "SmoothPalette", ref view.SmoothPalette);
                    XmlUtil.GetBoolAttribute(tr, "SmoothShading", ref view.SmoothShading);
                    XmlUtil.GetBoolAttribute(tr, "SemiTransparent", ref view.SemiTransparent);
                    XmlUtil.GetBoolAttribute(tr, "DrawFlat", ref view.DrawFlat);

                    txt = tr.GetAttribute("FrameMode");
                    if (txt != null)
                    {
                        view.SurfaceFrameMode = (SurfaceFrameMode)EnumUtil.Parse(typeof(SurfaceFrameMode), txt);
                    }

                    if (tr.IsEmptyElement)
                    {
                        continue;                                        // may be just attributes
                    }
                    tr.Read(); tr.MoveToContent();
                    if (!Lex.Eq(tr.Name, "Surface"))
                    {
                        throw new Exception("Expected Surface end element");
                    }
                }

                else if (Lex.Eq(tr.Name, "Trellis"))
                {
                    if (tr.IsEmptyElement)
                    {
                        continue;                                        // may be just attributes
                    }
                    XmlUtil.GetBoolAttribute(tr, "ByRowCol", ref view.TrellisByRowCol);

                    XmlUtil.GetBoolAttribute(tr, "Manual", ref view.TrellisManual);
                    XmlUtil.GetIntAttribute(tr, "MaxRows", ref view.TrellisMaxRows);
                    XmlUtil.GetIntAttribute(tr, "MaxCols", ref view.TrellisMaxCols);

                    while (true)
                    {
                        tr.Read(); tr.MoveToContent();

                        if (Lex.Eq(tr.Name, "ColumnQc"))
                        {
                            view.TrellisColQc = DeserializeQueryColumnRef(q, tr);
                        }

                        else if (Lex.Eq(tr.Name, "RowQc"))
                        {
                            view.TrellisRowQc = DeserializeQueryColumnRef(q, tr);
                        }

                        else if (Lex.Eq(tr.Name, "PageQc"))
                        {
                            view.TrellisPageQc = DeserializeQueryColumnRef(q, tr);
                        }

                        else if (Lex.Eq(tr.Name, "FlowQc"))
                        {
                            view.TrellisFlowQc = DeserializeQueryColumnRef(q, tr);
                        }

                        else if (tr.NodeType == XmlNodeType.EndElement &&                         // end of trellis definition
                                 Lex.Eq(tr.Name, "Trellis"))
                        {
                            break;
                        }

                        else
                        {
                            throw new Exception("Unexpected element: " + tr.Name);
                        }
                    }
                }

                else if (tr.NodeType == XmlNodeType.EndElement &&                 // end of chart props
                         Lex.Eq(tr.Name, "ChartProperties"))
                {
                    break;
                }

                else
                {
                    throw new Exception("Unexpected element: " + tr.Name);
                }
            }

            return(true);
        }
Beispiel #15
0
        public void Execute(IExecutionContext context, Command command)
        {
            ArgUtil.NotNull(context, nameof(context));
            ArgUtil.NotNull(command, nameof(command));

            var eventProperties = command.Properties;
            var data            = command.Data;

            TimelineRecord record = new TimelineRecord();

            String timelineRecord;

            if (!eventProperties.TryGetValue(TaskDetailEventProperties.TimelineRecordId, out timelineRecord) ||
                string.IsNullOrEmpty(timelineRecord) ||
                new Guid(timelineRecord).Equals(Guid.Empty))
            {
                throw new Exception(StringUtil.Loc("MissingTimelineRecordId"));
            }
            else
            {
                record.Id = new Guid(timelineRecord);
            }

            string parentTimlineRecord;

            if (eventProperties.TryGetValue(TaskDetailEventProperties.ParentTimelineRecordId, out parentTimlineRecord))
            {
                record.ParentId = new Guid(parentTimlineRecord);
            }

            String name;

            if (eventProperties.TryGetValue(TaskDetailEventProperties.Name, out name))
            {
                record.Name = name;
            }

            String recordType;

            if (eventProperties.TryGetValue(TaskDetailEventProperties.Type, out recordType))
            {
                record.RecordType = recordType;
            }

            String order;

            if (eventProperties.TryGetValue(TaskDetailEventProperties.Order, out order))
            {
                int orderInt = 0;
                if (int.TryParse(order, out orderInt))
                {
                    record.Order = orderInt;
                }
            }

            String percentCompleteValue;

            if (eventProperties.TryGetValue(TaskDetailEventProperties.Progress, out percentCompleteValue))
            {
                Int32 progress;
                if (Int32.TryParse(percentCompleteValue, out progress))
                {
                    record.PercentComplete = (Int32)Math.Min(Math.Max(progress, 0), 100);
                }
            }

            if (!String.IsNullOrEmpty(data))
            {
                record.CurrentOperation = data;
            }

            string result;

            if (eventProperties.TryGetValue(TaskDetailEventProperties.Result, out result))
            {
                record.Result = EnumUtil.TryParse <TaskResult>(result) ?? TaskResult.Succeeded;
            }

            String startTime;

            if (eventProperties.TryGetValue(TaskDetailEventProperties.StartTime, out startTime))
            {
                record.StartTime = ParseDateTime(startTime, DateTime.UtcNow);
            }

            String finishtime;

            if (eventProperties.TryGetValue(TaskDetailEventProperties.FinishTime, out finishtime))
            {
                record.FinishTime = ParseDateTime(finishtime, DateTime.UtcNow);
            }

            String state;

            if (eventProperties.TryGetValue(TaskDetailEventProperties.State, out state))
            {
                record.State = ParseTimelineRecordState(state, TimelineRecordState.Pending);
            }


            TimelineRecord trackingRecord;

            // in front validation as much as possible.
            // timeline record is happened in back end queue, user will not receive result of the timeline record updates.
            // front validation will provide user better understanding when things went wrong.
            if (_timelineRecordsTracker.TryGetValue(record.Id, out trackingRecord))
            {
                // we already created this timeline record
                // make sure parentid does not changed.
                if (record.ParentId != null &&
                    record.ParentId != trackingRecord.ParentId)
                {
                    throw new Exception(StringUtil.Loc("CannotChangeParentTimelineRecord"));
                }
                else if (record.ParentId == null)
                {
                    record.ParentId = trackingRecord.ParentId;
                }

                // populate default value for empty field.
                if (record.State == TimelineRecordState.Completed)
                {
                    if (record.PercentComplete == null)
                    {
                        record.PercentComplete = 100;
                    }

                    if (record.FinishTime == null)
                    {
                        record.FinishTime = DateTime.UtcNow;
                    }
                }
            }
            else
            {
                // we haven't created this timeline record
                // make sure we have name/type and parent record has created.
                if (string.IsNullOrEmpty(record.Name))
                {
                    throw new Exception(StringUtil.Loc("NameRequiredForTimelineRecord"));
                }

                if (string.IsNullOrEmpty(record.RecordType))
                {
                    throw new Exception(StringUtil.Loc("TypeRequiredForTimelineRecord"));
                }

                if (record.ParentId != null && record.ParentId != Guid.Empty)
                {
                    if (!_timelineRecordsTracker.ContainsKey(record.ParentId.Value))
                    {
                        throw new Exception(StringUtil.Loc("ParentTimelineNotCreated"));
                    }
                }

                // populate default value for empty field.
                if (record.StartTime == null)
                {
                    record.StartTime = DateTime.UtcNow;
                }

                if (record.State == null)
                {
                    record.State = TimelineRecordState.InProgress;
                }
            }

            context.UpdateDetailTimelineRecord(record);

            _timelineRecordsTracker[record.Id] = record;
        }
Beispiel #16
0
        private void Classify(ref GameObject root)
        {
            /*  root가 없을 경우 하나를 선택한다. */
            if (Camera.main == null || Camera.main.transform.parent == null)
            {
                return;
            }
            UIRoot uiRoot = Camera.main.transform.parent.GetComponent <UIRoot>();

            if (uiRoot == null)
            {
                return;
            }
            root = uiRoot.gameObject;

            classifier.SetRoot(root);
            panels.Clear();
            foreach (Object o in Object.FindObjectsOfType(typeof(UIPanel)))
            {
                panels.Add(((UIPanel)o).gameObject);
            }

            dups.Clear();
            foreach (UIWidgetClassifier.WidgetType widgetType in EnumUtil.Values <UIWidgetClassifier.WidgetType>())
            {
                MultiMap <string, DupEntry> slot = new MultiMap <string, DupEntry>();
                dups[widgetType] = slot;
                foreach (GameObject o in classifier.GetWidgets(widgetType))
                {
                    if (widgetType == UIWidgetClassifier.WidgetType.Label)
                    {
                        UILabel labelScript = o.GetComponentInChildren <UILabel>();
                        if (labelScript != null)
                        {
                            string name = labelScript.text;
                            slot.Add(o.name, new DupEntry(o, name));
                        }
                    }
                    else if (widgetType == UIWidgetClassifier.WidgetType.Button)
                    {
                        UILabel labelScript = o.GetComponentInChildren <UILabel>();
                        if (labelScript != null)
                        {
                            string name = labelScript.text;
                            slot.Add(o.name, new DupEntry(o, name));
                        }
                    }
                    else if (widgetType == UIWidgetClassifier.WidgetType.Input)
                    {
                        UILabel labelScript = o.GetComponentInChildren <UILabel>();
                        if (labelScript != null)
                        {
                            string name = labelScript.text;
                            slot.Add(o.name, new DupEntry(o, name));
                        }
                    }
                    else if (widgetType == UIWidgetClassifier.WidgetType.Slider)
                    {
                        slot.Add(o.name, new DupEntry(o, o.name));
                    }
                    else if (widgetType == UIWidgetClassifier.WidgetType.ProgressBar)
                    {
                        slot.Add(o.name, new DupEntry(o, o.name));
                    }
                }
            }

            RemoveSingle();
        }
Beispiel #17
0
        CreateKinectJoints(
            IReadOnlyDictionary <Microsoft.Kinect.JointType, Microsoft.Kinect.Joint>
            baseJoints,
            Z3Target target)
        {
            // Calc base rotation matrix
            var rotationMatrix = new Matrix3D();

            InitMatrix(out rotationMatrix, baseJoints);

            // Acquire all vectors from Z3 target
            var jointVectors = new Dictionary <Microsoft.Kinect.JointType, Vector3D>();

            // Spine base is the root of the system, as it has no direction to store, it stores its own position
            jointVectors.Add(
                Microsoft.Kinect.JointType.SpineBase,
                new Vector3D(
                    baseJoints[Microsoft.Kinect.JointType.SpineBase].Position.X,
                    baseJoints[Microsoft.Kinect.JointType.SpineBase].Position.Y,
                    baseJoints[Microsoft.Kinect.JointType.SpineBase].Position.Z));

            var z3JointTypes = EnumUtil.GetValues <PreposeGestures.JointType>();
            var targetJoints = target.TransformedJoints;

            foreach (var jointType in z3JointTypes)
            {
                if (jointType != PreposeGestures.JointType.SpineBase)
                {
                    // If target has calculated the joint add target jointType
                    if (targetJoints.Contains(jointType))
                    {
                        AddZ3JointToVectors3D(target.Body, baseJoints, jointVectors, jointType);
                    }
                    // Or else use the joint from current Kinect data (baseJoints)
                    else
                    {
                        jointVectors.Add(
                            (Microsoft.Kinect.JointType)jointType,
                            new Vector3D(
                                baseJoints[(Microsoft.Kinect.JointType)jointType].Position.X,
                                baseJoints[(Microsoft.Kinect.JointType)jointType].Position.Y,
                                baseJoints[(Microsoft.Kinect.JointType)jointType].Position.Z));
                    }
                }
            }

            // Rotate all vectors to the current base body coordinate system
            var kinectJointTypes = EnumUtil.GetValues <Microsoft.Kinect.JointType>();

            foreach (var jointType in kinectJointTypes)
            {
                if (jointType != Microsoft.Kinect.JointType.SpineBase &&
                    targetJoints.Contains((PreposeGestures.JointType)jointType))
                {
                    jointVectors[jointType] *= rotationMatrix;
                }
            }

            // Add base body position (spineBase position) to translate result
            // The operations order matter in this case
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.SpineMid);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.SpineShoulder);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.Neck);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.Head);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.ShoulderLeft);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.ElbowLeft);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.WristLeft);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.HandLeft);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.HandTipLeft);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.ThumbLeft);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.ShoulderRight);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.ElbowRight);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.WristRight);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.HandRight);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.HandTipRight);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.ThumbRight);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.HipLeft);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.KneeLeft);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.AnkleLeft);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.FootLeft);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.HipRight);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.KneeRight);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.AnkleRight);
            SumWithFatherPosition(jointVectors, targetJoints, Microsoft.Kinect.JointType.FootRight);

            // Filling the results
            var result = new Dictionary <Microsoft.Kinect.JointType, Microsoft.Kinect.Joint>();

            foreach (var jointType in kinectJointTypes)
            {
                var joint    = new Joint();
                var position = new CameraSpacePoint();
                position.X = (float)jointVectors[jointType].X;
                position.Y = (float)jointVectors[jointType].Y;
                position.Z = (float)jointVectors[jointType].Z;

                joint.Position      = position;
                joint.TrackingState = TrackingState.Tracked;

                result.Add(jointType, joint);
            }

            return(result);
        }
Beispiel #18
0
 public OtpGenerationDetail(string systemName, string action)
 {
     SystemName = systemName;
     Action     = EnumUtil.ParseEnum <Action>(action);
 }
Beispiel #19
0
        /// <summary>
        /// This function converts Kinect joints to a Z3 body.
        /// It also changes the basis of body coordinates to make it
        /// invariant to body position in relation to the sensor.
        ///
        /// The origin of the new coordinate system is user hips.
        /// </summary>
        /// <param name="kinectJoints"></param>
        /// <returns></returns>
        public static Z3Body CreateZ3Body(
            IReadOnlyDictionary <Microsoft.Kinect.JointType, Microsoft.Kinect.Joint>
            kinectJoints)
        {
            var jointVectors = new Dictionary <Microsoft.Kinect.JointType, Vector3D>();

            jointVectors.Add(Microsoft.Kinect.JointType.SpineMid, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.SpineMid], kinectJoints[Microsoft.Kinect.JointType.SpineBase]));
            jointVectors.Add(Microsoft.Kinect.JointType.SpineShoulder, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.SpineShoulder], kinectJoints[Microsoft.Kinect.JointType.SpineMid]));
            jointVectors.Add(Microsoft.Kinect.JointType.ShoulderLeft, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.ShoulderLeft], kinectJoints[Microsoft.Kinect.JointType.SpineShoulder]));
            jointVectors.Add(Microsoft.Kinect.JointType.ElbowLeft, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.ElbowLeft], kinectJoints[Microsoft.Kinect.JointType.ShoulderLeft]));
            jointVectors.Add(Microsoft.Kinect.JointType.WristLeft, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.WristLeft], kinectJoints[Microsoft.Kinect.JointType.ElbowLeft]));
            jointVectors.Add(Microsoft.Kinect.JointType.HandLeft, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.HandLeft], kinectJoints[Microsoft.Kinect.JointType.WristLeft]));
            jointVectors.Add(Microsoft.Kinect.JointType.HandTipLeft, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.HandTipLeft], kinectJoints[Microsoft.Kinect.JointType.HandLeft]));
            jointVectors.Add(Microsoft.Kinect.JointType.ThumbLeft, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.ThumbLeft], kinectJoints[Microsoft.Kinect.JointType.HandLeft]));
            jointVectors.Add(Microsoft.Kinect.JointType.Neck, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.Neck], kinectJoints[Microsoft.Kinect.JointType.SpineShoulder]));
            jointVectors.Add(Microsoft.Kinect.JointType.Head, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.Head], kinectJoints[Microsoft.Kinect.JointType.Neck]));
            jointVectors.Add(Microsoft.Kinect.JointType.ShoulderRight, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.ShoulderRight], kinectJoints[Microsoft.Kinect.JointType.SpineShoulder]));
            jointVectors.Add(Microsoft.Kinect.JointType.ElbowRight, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.ElbowRight], kinectJoints[Microsoft.Kinect.JointType.ShoulderRight]));
            jointVectors.Add(Microsoft.Kinect.JointType.WristRight, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.WristRight], kinectJoints[Microsoft.Kinect.JointType.ElbowRight]));
            jointVectors.Add(Microsoft.Kinect.JointType.HandRight, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.HandRight], kinectJoints[Microsoft.Kinect.JointType.WristRight]));
            jointVectors.Add(Microsoft.Kinect.JointType.HandTipRight, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.HandTipRight], kinectJoints[Microsoft.Kinect.JointType.HandRight]));
            jointVectors.Add(Microsoft.Kinect.JointType.ThumbRight, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.ThumbRight], kinectJoints[Microsoft.Kinect.JointType.HandRight]));

            // Spine base is the root of the system, as it has no direction to store, it stores its own position
            jointVectors.Add(Microsoft.Kinect.JointType.SpineBase, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.SpineBase], new Joint()));
            jointVectors.Add(Microsoft.Kinect.JointType.HipLeft, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.HipLeft], kinectJoints[Microsoft.Kinect.JointType.SpineBase]));
            jointVectors.Add(Microsoft.Kinect.JointType.KneeLeft, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.KneeLeft], kinectJoints[Microsoft.Kinect.JointType.HipLeft]));
            jointVectors.Add(Microsoft.Kinect.JointType.AnkleLeft, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.AnkleLeft], kinectJoints[Microsoft.Kinect.JointType.KneeLeft]));
            jointVectors.Add(Microsoft.Kinect.JointType.FootLeft, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.FootLeft], kinectJoints[Microsoft.Kinect.JointType.AnkleLeft]));
            jointVectors.Add(Microsoft.Kinect.JointType.HipRight, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.HipRight], kinectJoints[Microsoft.Kinect.JointType.SpineBase]));
            jointVectors.Add(Microsoft.Kinect.JointType.KneeRight, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.KneeRight], kinectJoints[Microsoft.Kinect.JointType.HipRight]));
            jointVectors.Add(Microsoft.Kinect.JointType.AnkleRight, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.AnkleRight], kinectJoints[Microsoft.Kinect.JointType.KneeRight]));
            jointVectors.Add(Microsoft.Kinect.JointType.FootRight, SubtractJoints(kinectJoints[Microsoft.Kinect.JointType.FootRight], kinectJoints[Microsoft.Kinect.JointType.AnkleRight]));

            var rotationMatrix = new Matrix3D();

            InitMatrix(out rotationMatrix, kinectJoints);

            rotationMatrix.Invert();

            var joints = new Dictionary <PreposeGestures.JointType, Z3Point3D>();
            var norms  = new Dictionary <PreposeGestures.JointType, ArithExpr>();

            norms.Add(PreposeGestures.JointType.SpineBase, Z3Math.Real(jointVectors[Microsoft.Kinect.JointType.SpineBase].Length));
            joints.Add(PreposeGestures.JointType.SpineBase,
                       new Z3Point3D(
                           jointVectors[Microsoft.Kinect.JointType.SpineBase].X,
                           jointVectors[Microsoft.Kinect.JointType.SpineBase].Y,
                           jointVectors[Microsoft.Kinect.JointType.SpineBase].Z));

            var jointTypes = EnumUtil.GetValues <Microsoft.Kinect.JointType>();

            foreach (var jointType in jointTypes)
            {
                if (jointType != Microsoft.Kinect.JointType.SpineBase)
                {
                    jointVectors[jointType] = jointVectors[jointType] * rotationMatrix;

                    var z3Joint = Convert(jointType);

                    norms.Add(z3Joint, Z3Math.Real(jointVectors[jointType].Length));

                    var temp = jointVectors[jointType];
                    temp.Normalize();

                    joints.Add(
                        z3Joint,
                        new Z3Point3D(
                            temp.X,
                            temp.Y,
                            -temp.Z));
                }
            }

            return(new Z3Body(joints, norms));
        }
Beispiel #20
0
 /// <summary>
 /// Defines the enum names and values</summary>
 /// <param name="names">Enum names array</param>
 /// <remarks>Enum values default to successive integers, starting with 0. Enum names
 /// with the format "EnumName=X" are parsed so that EnumName gets the value X, where X is
 /// an int.</remarks>
 public void DefineEnum(string[] names)
 {
     EnumUtil.ParseEnumDefinitions(names, out m_names, out m_values);
 }
Beispiel #21
0
        public void EnumValueFromDescriptionTest()
        {
            DockPosition dock = EnumUtil.EnumValueFromDescription <DockPosition>("Dock to All sides");

            Assert.AreEqual(DockPosition.All, dock);
        }
Beispiel #22
0
        private SettingSection BuildDisplaySection()
        {
            var section = new SettingSection(SystemUtil.GetStringResource("SettingSection_Display"));

            section.Add(new ToggleSetting
            {
                SettingData = new AppSettingData <bool>()
                {
                    Title         = SystemUtil.GetStringResource("DisplayTakeImageButtonSetting"),
                    Guide         = SystemUtil.GetStringResource("Guide_DisplayTakeImageButtonSetting"),
                    StateProvider = () => ApplicationSettings.GetInstance().IsShootButtonDisplayed,
                    StateObserver = enabled => ApplicationSettings.GetInstance().IsShootButtonDisplayed = enabled
                }
            });

            section.Add(new ToggleSetting
            {
                SettingData = new AppSettingData <bool>()
                {
                    Title         = SystemUtil.GetStringResource("DisplayHistogram"),
                    Guide         = SystemUtil.GetStringResource("Guide_Histogram"),
                    StateProvider = () => ApplicationSettings.GetInstance().IsHistogramDisplayed,
                    StateObserver = enabled => ApplicationSettings.GetInstance().IsHistogramDisplayed = enabled
                }
            });

            var FocusFrameSetting = new AppSettingData <bool>()
            {
                Title         = SystemUtil.GetStringResource("FocusFrameDisplay"),
                Guide         = SystemUtil.GetStringResource("Guide_FocusFrameDisplay"),
                StateProvider = () => ApplicationSettings.GetInstance().RequestFocusFrameInfo,
                StateObserver = enabled =>
                {
                    ApplicationSettings.GetInstance().RequestFocusFrameInfo = enabled;
                    // todo: support to show focus frames
                    //await SetupFocusFrame(enabled);
                    //if (!enabled) { _FocusFrameSurface.ClearFrames(); }
                }
            };

            section.Add(new ToggleSetting {
                SettingData = FocusFrameSetting
            });

            section.Add(new ToggleSetting
            {
                SettingData = new AppSettingData <bool>()
                {
                    Title         = SystemUtil.GetStringResource("LiveviewRotation"),
                    Guide         = SystemUtil.GetStringResource("LiveviewRotation_guide"),
                    StateProvider = () => ApplicationSettings.GetInstance().LiveviewRotationEnabled,
                    StateObserver = enabled =>
                    {
                        ApplicationSettings.GetInstance().LiveviewRotationEnabled = enabled;
                        // todo: support to rotate liveview image
                        //if (enabled && target != null && target.Status != null)
                        //{
                        //    RotateLiveviewImage(target.Status.LiveviewOrientationAsDouble);
                        //}
                        //else
                        //{
                        //    RotateLiveviewImage(0);
                        //}
                    }
                }
            });

            section.Add(new ToggleSetting
            {
                SettingData = new AppSettingData <bool>()
                {
                    Title         = SystemUtil.GetStringResource("FramingGrids"),
                    Guide         = SystemUtil.GetStringResource("Guide_FramingGrids"),
                    StateProvider = () => ApplicationSettings.GetInstance().FramingGridEnabled,
                    StateObserver = enabled =>
                    {
                        ApplicationSettings.GetInstance().FramingGridEnabled = enabled;
                        // screen_view_data.FramingGridDisplayed = enabled;
                    }
                }
            });

            var gridTypePanel = new ComboBoxSetting(new AppSettingData <int>()
            {
                Title         = SystemUtil.GetStringResource("AssistPattern"),
                StateProvider = () => (int)ApplicationSettings.GetInstance().GridType - 1,
                StateObserver = setting =>
                {
                    if (setting < 0)
                    {
                        return;
                    }
                    ApplicationSettings.GetInstance().GridType = (FramingGridTypes)(setting + 1);
                },
                Candidates = SettingValueConverter.FromFramingGrid(EnumUtil <FramingGridTypes> .GetValueEnumerable())
            });

            gridTypePanel.SetBinding(VisibilityProperty, new Binding
            {
                Source    = ApplicationSettings.GetInstance(),
                Path      = new PropertyPath(nameof(ApplicationSettings.FramingGridEnabled)),
                Mode      = BindingMode.OneWay,
                Converter = new BoolToVisibilityConverter(),
            });
            section.Add(gridTypePanel);

            var gridColorPanel = new ComboBoxSetting(new AppSettingData <int>()
            {
                Title         = SystemUtil.GetStringResource("FramingGridColor"),
                StateProvider = () => (int)ApplicationSettings.GetInstance().GridColor,
                StateObserver = setting =>
                {
                    if (setting < 0)
                    {
                        return;
                    }
                    ApplicationSettings.GetInstance().GridColor = (FramingGridColors)setting;
                },
                Candidates = SettingValueConverter.FromFramingGridColor(EnumUtil <FramingGridColors> .GetValueEnumerable())
            });

            gridColorPanel.SetBinding(VisibilityProperty, new Binding
            {
                Source    = ApplicationSettings.GetInstance(),
                Path      = new PropertyPath(nameof(ApplicationSettings.FramingGridEnabled)),
                Mode      = BindingMode.OneWay,
                Converter = new BoolToVisibilityConverter(),
            });
            section.Add(gridColorPanel);

            var fibonacciOriginPanel = new ComboBoxSetting(new AppSettingData <int>()
            {
                Title         = SystemUtil.GetStringResource("FibonacciSpiralOrigin"),
                StateProvider = () => (int)ApplicationSettings.GetInstance().FibonacciLineOrigin,
                StateObserver = setting =>
                {
                    if (setting < 0)
                    {
                        return;
                    }
                    ApplicationSettings.GetInstance().FibonacciLineOrigin = (FibonacciLineOrigins)setting;
                },
                Candidates = SettingValueConverter.FromFibonacciLineOrigin(EnumUtil <FibonacciLineOrigins> .GetValueEnumerable())
            });

            fibonacciOriginPanel.SetBinding(VisibilityProperty, new Binding
            {
                Source    = ApplicationSettings.GetInstance(),
                Path      = new PropertyPath(nameof(ApplicationSettings.IsFibonacciSpiralEnabled)),
                Mode      = BindingMode.OneWay,
                Converter = new BoolToVisibilityConverter(),
            });
            section.Add(fibonacciOriginPanel);

            section.Add(new ToggleSetting
            {
                SettingData = new AppSettingData <bool>()
                {
                    Title         = SystemUtil.GetStringResource("ForcePhoneView"),
                    Guide         = SystemUtil.GetStringResource("ForcePhoneView_Guide"),
                    StateProvider = () => ApplicationSettings.GetInstance().ForcePhoneView,
                    StateObserver = enabled => ApplicationSettings.GetInstance().ForcePhoneView = enabled
                }
            });

            section.Add(new ToggleSetting
            {
                SettingData = new AppSettingData <bool>()
                {
                    Title         = SystemUtil.GetStringResource("ShowKeyCheatSheet"),
                    Guide         = SystemUtil.GetStringResource("ShowKeyCheatSheet_Guide"),
                    StateProvider = () => ApplicationSettings.GetInstance().ShowKeyCheatSheet,
                    StateObserver = enabled => ApplicationSettings.GetInstance().ShowKeyCheatSheet = enabled
                }
            });

            section.Add(new ComboBoxSetting(new AppSettingData <int>()
            {
                Title         = "🌏 " + SystemUtil.GetStringResource("LanguageSetting"),
                Guide         = SystemUtil.GetStringResource("LanguageSetting_Guide"),
                StateProvider = () => (int)LocalizationExtensions.FromLang(ApplicationSettings.GetInstance().LanguageOverride),
                StateObserver = async(index) =>
                {
                    if (index == -1)
                    {
                        return;
                    }
                    var lang = ((Localization)index).AsLang();
                    if (ApplicationSettings.GetInstance().LanguageOverride != lang)
                    {
                        ApplicationSettings.GetInstance().LanguageOverride = lang;

                        RestartDialog.DataContext = ExitConfirmationSource;
                        if (await RestartDialog.ShowAsync() == ContentDialogResult.Primary)
                        {
                            Application.Current.Exit();
                        }
                    }
                },
                Candidates = SettingValueConverter.FromLocalization(EnumUtil <Localization> .GetValueEnumerable())
            }
                                            ));

            return(section);
        }
Beispiel #23
0
        public void EnumValueFromDescriptionMissingAttributeFieldTest()
        {
            BadTypes result = EnumUtil.EnumValueFromDescription <BadTypes>("Very Bad");

            Assert.AreEqual(BadTypes.NotSoBad, result);
        }
Beispiel #24
0
        /// <summary>
        /// Gets the un authenticate method.
        /// </summary>
        /// <param name="getSignOutMethod">The un authenticate method.</param>
        /// <returns></returns>
        public static DeviceSignOutMethod GetSignOutMethod(string getSignOutMethod)
        {
            DeviceSignOutMethod dum = EnumUtil.GetByDescription <DeviceSignOutMethod>(getSignOutMethod);

            return(dum);
        }
Beispiel #25
0
        public void EnumCountTest()
        {
            int count = EnumUtil.EnumCount <DivisionLeagTypes>();

            Assert.AreEqual(8, count);
        }
Beispiel #26
0
 public NewsType GetNewsType()
 {
     return(EnumUtil.TryParse(type, NewsType.Unknown));
 }
Beispiel #27
0
        public void EnumListCountTest()
        {
            var items = EnumUtil.EnumList <DivisionLeagTypes>();

            Assert.AreEqual(8, items.Count);
        }
Beispiel #28
0
 /// <summary>
 /// Determines whether the value of an object is valid.
 /// </summary>
 /// <param name="value">The object value.</param>
 public override void Validate(object value)
 {
     Enums.ServiceCacheCleanUp t = EnumUtil <Enums.ServiceCacheCleanUp> .Parse(value.ToString());
 }
        protected void GUIHanlder(StageConfig stageConfig)
        {
            scrollPos = EditorGUILayout.BeginScrollView(scrollPos);

            fold_base = EditorGUILayout.Foldout(fold_base, "基本配置");
            if (fold_base)
            {
                EditorGUILayout.BeginVertical(style_box_marginleft);

                if (id == -1 || _stageConfig != stageConfig)
                {
                    sourceId     = id = stageConfig.id;
                    _stageConfig = stageConfig;
                }

                id = EditorGUILayout.IntField("编号", id);
                OnIdChange(stageConfig);



                stageConfig.name = EditorGUILayout.TextField("名称", stageConfig.name);

                GUILayout.Space(5);
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField("描述", GUILayout.Width(100));
                stageConfig.description = EditorGUILayout.TextArea(stageConfig.description, GUILayout.Height(50));
                EditorGUILayout.EndHorizontal();
                GUILayout.Space(5);

                stageConfig.type = (StageType)EditorGUILayout.IntPopup("关卡类型", (int)stageConfig.type, stageType_names, stageType_ids);

                stageConfig.level        = EditorGUILayout.IntField("等级", stageConfig.level);
                stageConfig.nextStageId  = EditorGUILayout.IntField("解锁关卡", stageConfig.nextStageId);
                stageConfig.dropId       = EditorGUILayout.IntField("掉落", stageConfig.dropId);
                stageConfig.costStrength = EditorGUILayout.IntField("消耗体力", stageConfig.costStrength);

                stageConfig.time = EditorGUILayout.IntField("限时", (int)stageConfig.time);
                EditorGUILayout.ToggleLeft("限时", stageConfig.time > 0);

                stageConfig.showHP           = EditorGUILayout.ToggleLeft("血条开关", stageConfig.showHP);
                stageConfig.sos              = EditorGUILayout.ToggleLeft("求救提示", stageConfig.sos);
                stageConfig.neutralRoleLevel = EditorGUILayout.IntField("中立主公等级", stageConfig.neutralRoleLevel);
                stageConfig.winId            = EditorGUILayout.IntPopup("胜利条件", stageConfig.winId, win_names, win_ids);

                GUILayout.Space(10);
                EditorGUILayout.LabelField("星级评价");
                EditorGUILayout.BeginVertical(style_box_marginleft);
                if (stageConfig.stars.Length < 3)
                {
                    int[] tempStarts = stageConfig.stars;
                    stageConfig.stars = new int[3];
                    for (int i = 0; i < tempStarts.Length; i++)
                    {
                        GUILayout.Space(3);
                        stageConfig.stars[i] = tempStarts[i];
                        GUILayout.Space(3);
                    }
                }

                for (int i = 0; i < 3; i++)
                {
                    stageConfig.stars[i] = EditorGUILayout.IntPopup("星级评价1", stageConfig.stars[i], star_names, star_ids);
                }

                EditorGUILayout.EndVertical();
                GUILayout.Space(10);

                EditorGUILayout.EndVertical();
            }



            fold_legionList = EditorGUILayout.Foldout(fold_legionList, "势力列表");
            if (fold_legionList)
            {
                List <StageLegionConfig> legionList = new List <StageLegionConfig>();
                foreach (var legionKVP in stageConfig.legionDict)
                {
                    legionList.Add(legionKVP.Value);
                }

                foreach (StageLegionConfig legionConfig in legionList)
                {
                    GUILayout.Space(10);

                    EditorGUILayout.BeginHorizontal();

                    GUILayout.Space(30);
                    if (GUILayout.Button("删除", style_box_center, GUILayout.Width(50), GUILayout.Height(30)))
                    {
                        stageConfig.legionDict.Remove(legionConfig.legionId);
                    }

                    EditorGUILayout.BeginVertical(style_box_legion);
                    legion_toggles[legionConfig.legionId] = GUILayout.Toggle(legion_toggles[legionConfig.legionId], string.Format("<color={2}>势力{0} [{1}--{3}]</color>", legionConfig.legionId, WarColor.Names[legionConfig.color], WarColor.GetUnitHPColor(legionConfig.color).ToStr32(), EnumUtil.GetName <LegionType>(legionConfig.type)), style_label_toggle, GUILayout.ExpandWidth(true), GUILayout.Height(30));
                    if (legion_toggles[legionConfig.legionId])
                    {
                        legionConfig.color = EditorGUILayout.IntPopup("颜色", legionConfig.color, WarColor.Names, WarColor.IDs, style_label_IntPopup_color);

                        if (legionConfig.color != legionConfig.legionId)
                        {
                            if (stageConfig.legionDict.ContainsKey(legionConfig.color))
                            {
                                EditorGUILayout.HelpBox(string.Format("该颜色以被其他势力使用, 请改回'{0}'", WarColor.Names[legionConfig.legionId]), MessageType.Error);
                            }
                            else
                            {
                                stageConfig.legionDict.Remove(legionConfig.legionId);
                                legionConfig.legionId = legionConfig.color;
                                stageConfig.legionDict.Add(legionConfig.legionId, legionConfig);
                            }
                        }

                        legionConfig.type    = (LegionType)EditorGUILayout.IntPopup("类型", (int)legionConfig.type, legionType_Names, legionType_ids);
                        legionConfig.groupId = EditorGUILayout.IntPopup("联盟", legionConfig.groupId, group_names, group_ids);
//						legionConfig.ai = EditorGUILayout.IntPopup("AI", legionConfig.ai, ai_names, ai_ids);
                        legionConfig.robotId = EditorGUILayout.IntField("机器人", legionConfig.robotId);

                        GUILayout.Space(10);
                        legionConfig.produce      = EditorGUILayout.ToggleLeft("兵营是否产兵", legionConfig.produce);
                        legionConfig.produceLimit = EditorGUILayout.ToggleLeft("兵营生产是否上限(一般只有中立勾选)", legionConfig.produceLimit);
                        GUILayout.Space(10);
                        legionConfig.aiUplevel = EditorGUILayout.ToggleLeft("是否自动升级", legionConfig.aiUplevel);
                        legionConfig.aiSendArm = EditorGUILayout.ToggleLeft("是否自动派兵", legionConfig.aiSendArm);
                        legionConfig.aiSkill   = EditorGUILayout.ToggleLeft("是否自动使用技能", legionConfig.aiSkill);
                        GUILayout.Space(10);


                        // ===========================

//						EditorGUILayout.LabelField("士兵");
//						EditorGUILayout.BeginVertical(style_box_solider);
//						if(legionConfig.soldierMonsterId > 0)
//						{
//							GUI_Solider(legionConfig.soliderMonster);
//
//							if(GUILayout.Button("清除", GUILayout.Height(30)))
//							{
//								legionConfig.soldierMonsterId = 0;
//							}
//						}
//
//						if(GUILayout.Button("选择", GUILayout.Height(30)))
//						{
//							WarEditor_SoliderLibraryWindow.Open(OnSelectSolider, legionConfig);
//						}
//						EditorGUILayout.EndVertical();

                        // ===========================


//						EditorGUILayout.LabelField("英雄");
//						EditorGUILayout.BeginVertical();
//						int heroIndex = 0;
//						for(int i = 0; i < legionConfig.heroIdList.Length; i ++)
//						{
//							int heroId = legionConfig.heroIdList[i];
//							if(heroId <= 0) continue;
//							GUI_Hero(heroId, legionConfig, heroIndex, i);
//							GUILayout.Space(10);
//							heroIndex ++;
//						}
//
//						if(GUILayout.Button("添加", GUILayout.Height(30)))
//						{
//							WarEditor_HeroLibraryWindow.Open(OnSelectAddHero, legionConfig);
//						}
//
//						EditorGUILayout.EndVertical();

                        // ===========================
                    }
                    EditorGUILayout.EndVertical();
                    EditorGUILayout.EndHorizontal();

                    GUILayout.Space(10);
                }
            }



//			fold_legionGroup = EditorGUILayout.Foldout(fold_legionGroup, "势力关系");
//			if (fold_legionGroup)
//			{
//				for(int i = 0; i < stageConfig.legionGroups.Count; i ++)
//				{
//					GUILayout.Box("联盟" + i);
//					EditorGUILayout.BeginHorizontal();
//
//					EditorGUILayout.EndHorizontal();
//
//				}
//			}



            EditorGUILayout.EndScrollView();


            //------------------------

            GUILayout.Space(20);
            EditorGUILayout.BeginHorizontal();


            if (GUILayout.Button("应用", GUILayout.Width(100), GUILayout.Height(30)))
            {
                if (stageConfig.legionDict.Count < 2)
                {
                    this.ShowNotification(new GUIContent("请创建势力,势力至少需要2个"));
                }
                else
                {
                    GenerateGroup(stageConfig);
                    WarEditor_Instance.Open(stageConfig);
                    WarEditor_StageConfigWindow_Modify.Open();
                }
            }

            if (visiable_SaveButton && GUILayout.Button("保存", GUILayout.Width(100), GUILayout.Height(30)))
            {
                GenerateGroup(stageConfig);
                WarEditor_File.SaveStageConfig(stageConfig);
            }

            if (stageConfig.legionDict.Count < WarColor.Names.Length &&
                GUILayout.Button("添加势力", GUILayout.Width(100), GUILayout.Height(30)))
            {
                int legionId = 0;
                for (int i = 0; i < WarColor.Names.Length; i++)
                {
                    if (!stageConfig.legionDict.ContainsKey(i))
                    {
                        legionId = i;
                        break;
                    }
                }

                StageLegionConfig legionConfig = CreateStageLegionConfig(legionId);
                stageConfig.legionDict.Add(legionConfig.legionId, legionConfig);
            }

            EditorGUILayout.EndHorizontal();
        }
        protected void Init()
        {
//			if(_isInit) return;
//			_isInit = true;

            //---------- StageType --------------
            EnumUtil.GetValuesAndNames <StageType>(out stageType_ids, out stageType_names);

            //---------- LegionType --------------
            EnumUtil.GetValuesAndNames <LegionType>(out legionType_ids, out legionType_Names);


            //---------- win --------------
            win_ids   = new int[War.model.winConfigs.Count + 1];
            win_names = new string[War.model.winConfigs.Count + 1];

            win_ids[0]   = 0;
            win_names[0] = "不设置";

            int i = 1;

            foreach (var item in War.model.winConfigs)
            {
                win_ids[i]   = item.Value.id;
                win_names[i] = string.Format("{0}  ({1})  {2}", item.Value.id, EnumUtil.GetName <WinType>(item.Value.winType), item.Value.description);

                i++;
            }


            //---------- star --------------
            star_ids   = new int[War.model.starConfigs.Count + 1];
            star_names = new string[War.model.starConfigs.Count + 1];

            star_ids[0]   = 0;
            star_names[0] = "不设置";

            i = 1;
            foreach (var item in War.model.starConfigs)
            {
                star_ids[i]   = item.Value.id;
                star_names[i] = string.Format("{0}  {1}", item.Value.id, item.Value.Description);

                i++;
            }



            //---------- ai --------------
            ai_ids   = new int[War.model.aiConfigs.Count + 1];
            ai_names = new string[War.model.aiConfigs.Count + 1];

            ai_ids[0]   = 0;
            ai_names[0] = "不设置";

            i = 1;
            foreach (var item in War.model.aiConfigs)
            {
                ai_ids[i]   = item.Value.id;
                ai_names[i] = string.Format("{0}  {1}  检测间隔={2},  出兵百分比={3},  {4}", item.Value.id, item.Value.name, item.Value.interval, Mathf.CeilToInt(item.Value.sendArmPercent * 100), EnumUtil.GetName <AIAttackLevel>(item.Value.attackLevel));

                i++;
            }
        }
Beispiel #31
0
 public void WhenNameNotFoundThenThrows()
 {
     Executing.This(() => EnumUtil.ParseGettingUnderlyingValue(typeof(ShortTypes), "Pizza")).Should().Throw <ArgumentException>();
 }