/// <summary> /// Visits the ConstantExpression. /// </summary> /// <param name="node"> /// The expression to visit. /// </param> /// <returns> /// The modified expression, if it or any subexpression was modified; otherwise, returns the original expression. /// </returns> protected override Expression VisitConstant(ConstantExpression node) { if (node.Type == typeof(GenericField)) { GenericField value = node.GetValue <GenericField>(); switch (value) { case GenericField.ActualType: sortField = new SortField(Documents.ObjectMappingExtensions.FieldActualType, SortFieldType.STRING, sortDescending); break; case GenericField.StaticType: sortField = new SortField(Documents.ObjectMappingExtensions.FieldStaticType, SortFieldType.STRING, sortDescending); break; case GenericField.Source: sortField = new SortField(Documents.ObjectMappingExtensions.FieldSource, SortFieldType.STRING, sortDescending); break; case GenericField.Timestamp: sortField = new SortField(Documents.ObjectMappingExtensions.FieldTimestamp, SortFieldType.INT64, sortDescending); break; default: Debug.Fail("Unsupported GenericField: " + value); throw new NotSupportedException(String.Format("Unsupported GenericField: {0}.", value)); } return(node); } return(base.VisitConstant(node)); }
/// <summary>Get the data to display for this subject.</summary> /// <param name="metadata">Provides metadata that's not available from the game data directly.</param> public override IEnumerable <ICustomField> GetData(Metadata metadata) { FarmAnimal animal = this.Target; // calculate maturity bool isFullyGrown = animal.age >= animal.ageWhenMature; int daysUntilGrown = 0; GameDate dayOfMaturity = null; if (!isFullyGrown) { daysUntilGrown = animal.ageWhenMature - animal.age; dayOfMaturity = GameHelper.GetDate(metadata.Constants.DaysInSeason).GetDayOffset(daysUntilGrown); } // yield fields yield return(new CharacterFriendshipField("Love", DataParser.GetFriendshipForAnimal(Game1.player, animal, metadata))); yield return(new PercentageBarField("Happiness", animal.happiness, byte.MaxValue, Color.Green, Color.Gray, $"{Math.Round(animal.happiness / (metadata.Constants.AnimalMaxHappiness * 1f) * 100)}%")); yield return(new GenericField("Mood today", animal.getMoodMessage())); yield return(new GenericField("Complaints", this.GetMoodReason(animal))); yield return(new ItemIconField("Produce ready", animal.currentProduce > 0 ? GameHelper.GetObjectBySpriteIndex(animal.currentProduce) : null)); if (!isFullyGrown) { yield return(new GenericField("Growth", $"{daysUntilGrown} {TextHelper.Pluralise(daysUntilGrown, "day")} (on {dayOfMaturity})")); } yield return(new GenericField("Sells for", GenericField.GetSaleValueString(animal.getSellPrice(), 1))); }
/// <summary>Get the data to display for this subject.</summary> /// <param name="metadata">Provides metadata that's not available from the game data directly.</param> public override IEnumerable <ICustomField> GetData(Metadata metadata) { FarmAnimal animal = this.Target; // calculate maturity bool isFullyGrown = animal.age >= animal.ageWhenMature; int daysUntilGrown = 0; GameDate dayOfMaturity = null; if (!isFullyGrown) { daysUntilGrown = animal.ageWhenMature - animal.age; dayOfMaturity = GameHelper.GetDate(metadata.Constants.DaysInSeason).GetDayOffset(daysUntilGrown); } // yield fields yield return(new CharacterFriendshipField(this.Translate(L10n.Animal.Love), DataParser.GetFriendshipForAnimal(Game1.player, animal, metadata), this.Text)); yield return(new PercentageBarField(this.Translate(L10n.Animal.Happiness), animal.happiness, byte.MaxValue, Color.Green, Color.Gray, this.Translate(L10n.Generic.Percent, new { percent = Math.Round(animal.happiness / (metadata.Constants.AnimalMaxHappiness * 1f) * 100) }))); yield return(new GenericField(this.Translate(L10n.Animal.Mood), animal.getMoodMessage())); yield return(new GenericField(this.Translate(L10n.Animal.Complaints), this.GetMoodReason(animal))); yield return(new ItemIconField(this.Translate(L10n.Animal.ProduceReady), animal.currentProduce > 0 ? GameHelper.GetObjectBySpriteIndex(animal.currentProduce) : null)); if (!isFullyGrown) { yield return(new GenericField(this.Translate(L10n.Animal.Growth), $"{this.Translate(L10n.Generic.Days, new { count = daysUntilGrown })} ({this.Stringify(dayOfMaturity)})")); } yield return(new GenericField(this.Translate(L10n.Animal.SellsFor), GenericField.GetSaleValueString(animal.getSellPrice(), 1, this.Text))); }
internal static GenericField CreateAttachment(AttachmentData data, string contentType) { var gfs = new List <GenericField> { CreateGenericField("ContentType", DataTypeEnum.STRING, contentType), // "text/plain", "application/x-zip-compressed" CreateGenericField("FileName", DataTypeEnum.STRING, data.AttachmentName), CreateGenericField("Data", DataTypeEnum.BASE64_BINARY, data.AttachmentContent) }; // add a file attachment var result = new GenericField { name = "FileAttachments", DataValue = new DataValue { ItemsElementName = new [] { ItemsChoiceType.ObjectValueList }, Items = new [] { new GenericObject() { ObjectType = new RNObjectType() { TypeName = "FileAttachment" }, GenericFields = gfs.ToArray() } } } }; return(result); }
public void testGenericFieldAccess() { var myField = new GenericField <int>(); myField.x += 1; AssertEquals(1, myField.x); }
public GenericField createGenericField(RightNowCustomObjectFieldAttribute attribute, object value) { GenericField genericField = new GenericField(); genericField.name = attribute.Name; genericField.DataValue = new DataValue(); ItemsChoiceType fieldType = ItemsChoiceType.StringValue; if (attribute.FieldType != null) { fieldType = attribute.FieldType; } if (fieldType == ItemsChoiceType.NamedIDValue) { NamedID accountID = new NamedID(); accountID.ID = new ID(); long id = 0; Int64.TryParse(value.ToString(), out id); accountID.ID.id = id; accountID.ID.idSpecified = true; genericField.DataValue.Items = new object[] { accountID }; } else { genericField.DataValue.Items = new object[] { value }; } //genericField.dataType = (ConnectService.DataTypeEnum)fieldType; genericField.DataValue.ItemsElementName = new ItemsChoiceType[] { fieldType }; return(genericField); }
private static void DrawPopup <T>(Object target, GenericField <T> field, Rect rect, bool allowNull) where T : ScriptableObject { List <Type> availableTypes = TypeLoader.GetTypes(field.Type); List <string> options = availableTypes.Select(x => x.Name).ToList(); int index = GetIndex(field); if (allowNull) { options.Insert(0, "null"); } if (options.Count == 0) { EditorGUI.HelpBox(rect, $"No options found for {field.Type}", MessageType.Error); return; } int newIndex = EditorGUI.Popup(rect, index, options.ToArray()); if (newIndex != index) { // Since we insert "null" at 0, we have to move the index one value down to match the actual type list if (allowNull) { newIndex--; } Type newType = availableTypes[newIndex]; RemoveInstance(field); AddInstance(target, field, newType); AssetDatabase.SaveAssets(); } }
/// <summary>Get the data to display for this subject.</summary> public override IEnumerable <ICustomField> GetData() { FarmAnimal animal = this.Target; // calculate maturity bool isFullyGrown = animal.age.Value >= animal.ageWhenMature.Value; int daysUntilGrown = 0; SDate dayOfMaturity = null; if (!isFullyGrown) { daysUntilGrown = animal.ageWhenMature.Value - animal.age.Value; dayOfMaturity = SDate.Now().AddDays(daysUntilGrown); } // yield fields yield return(new CharacterFriendshipField(I18n.Animal_Love(), this.GameHelper.GetFriendshipForAnimal(Game1.player, animal))); yield return(new PercentageBarField(I18n.Animal_Happiness(), animal.happiness.Value, byte.MaxValue, Color.Green, Color.Gray, I18n.Generic_Percent(percent: (int)Math.Round(animal.happiness.Value / (this.Constants.AnimalMaxHappiness * 1f) * 100)))); yield return(new GenericField(I18n.Animal_Mood(), animal.getMoodMessage())); yield return(new GenericField(I18n.Animal_Complaints(), this.GetMoodReason(animal))); yield return(new ItemIconField(this.GameHelper, I18n.Animal_ProduceReady(), animal.currentProduce.Value > 0 ? this.GameHelper.GetObjectBySpriteIndex(animal.currentProduce.Value) : null)); if (!isFullyGrown) { yield return(new GenericField(I18n.Animal_Growth(), $"{I18n.Generic_Days(count: daysUntilGrown)} ({this.Stringify(dayOfMaturity)})")); } yield return(new GenericField(I18n.Animal_SellsFor(), GenericField.GetSaleValueString(animal.getSellPrice(), 1))); }
private static int GetIndex <T>(GenericField <T> field) where T : ScriptableObject { if (field.Instance == null) { return(0); } return(TypeLoader.GetTypes(field.Type).IndexOf(field.Instance.GetType())); }
private static void AddInstance <T>(Object target, GenericField <T> field, Type type) where T : ScriptableObject { ScriptableObject newInstance = ScriptableObject.CreateInstance(type); field.Instance = (T)newInstance; AssetDatabase.AddObjectToAsset(newInstance, target); AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(newInstance)); }
/// <summary> /// Create GenericField object /// </summary> /// <param name="name">Name Of Generic Field</param> /// <param name="dataValue">Vlaue of generic field</param> /// <param name="type">Type of generic field</param> /// <returns> GenericField</returns> private GenericField createGenericField(string name, DataValue dataValue, DataTypeEnum type) { GenericField genericField = new GenericField(); genericField.dataType = type; genericField.dataTypeSpecified = true; genericField.name = name; genericField.DataValue = dataValue; return(genericField); }
private GenericField createGenericField(string Name, ItemsChoiceType itemsChoiceType, object Value) { GenericField gf = new GenericField(); gf.name = Name; gf.DataValue = new DataValue(); gf.DataValue.ItemsElementName = new ItemsChoiceType[] { itemsChoiceType }; gf.DataValue.Items = new object[] { Value }; return(gf); }
internal static GenericField CreateGenericField(string genericFieldName, DataTypeEnum dataType, object dataValues) { var result = new GenericField { name = genericFieldName, dataType = dataType, dataTypeSpecified = true, DataValue = CreateDataValue(dataType, dataValues) }; return(result); }
/// <summary> /// Create a generic text field /// </summary> /// <param name="name"></param> /// <param name="value"></param> /// <returns></returns> public static GenericField CreateGenericTextField(string name, string value) { GenericField f = new GenericField(); f.dataType = DataTypeEnum.STRING; f.dataTypeSpecified = true; f.name = name; f.DataValue = new DataValue(); f.DataValue.Items = new object[1]; f.DataValue.Items[0] = value; f.DataValue.ItemsElementName = new ItemsChoiceType[] { ItemsChoiceType.StringValue }; return(f); }
/// <summary> /// Create a generic date/time field /// </summary> /// <param name="name"></param> /// <param name="value"></param> /// <returns></returns> public static GenericField CreateGenericDateTimeField(string name, DateTime value) { GenericField f = new GenericField(); f.dataType = DataTypeEnum.DATETIME; f.dataTypeSpecified = true; f.name = name; f.DataValue = new DataValue(); f.DataValue.Items = new object[1]; f.DataValue.Items[0] = value; f.DataValue.ItemsElementName = new ItemsChoiceType[] { ItemsChoiceType.DateTimeValue }; return(f); }
/// <summary> /// Create a generic bool field /// </summary> /// <param name="name"></param> /// <param name="value"></param> /// <returns></returns> public static GenericField CreateGenericBoolField(string name, bool value) { GenericField f = new GenericField(); f.dataType = DataTypeEnum.BOOLEAN; f.dataTypeSpecified = true; f.name = name; f.DataValue = new DataValue(); f.DataValue.Items = new object[1]; f.DataValue.Items[0] = value; f.DataValue.ItemsElementName = new ItemsChoiceType[] { ItemsChoiceType.BooleanValue }; return(f); }
/// <summary> /// Create a generic int field /// </summary> /// <param name="name"></param> /// <param name="value"></param> /// <returns></returns> public static GenericField CreateGenericIntegerField(string name, int value) { GenericField f = new GenericField(); f.dataType = DataTypeEnum.INTEGER; f.dataTypeSpecified = true; f.name = name; f.DataValue = new DataValue(); f.DataValue.Items = new object[1]; f.DataValue.Items[0] = value; f.DataValue.ItemsElementName = new ItemsChoiceType[] { ItemsChoiceType.IntegerValue }; return(f); }
/// <summary> /// Create a generic namedID field /// </summary> /// <param name="name"></param> /// <param name="value"></param> /// <returns></returns> public static GenericField CreateGenericNamedIDField(string name, NamedID value) { GenericField f = new GenericField(); f.dataType = DataTypeEnum.NAMED_ID; f.dataTypeSpecified = true; f.name = name; f.DataValue = new DataValue(); f.DataValue.Items = new object[1]; f.DataValue.Items[0] = value; f.DataValue.ItemsElementName = new ItemsChoiceType[] { ItemsChoiceType.NamedIDValue }; return(f); }
/// <returns>True if unable to create instance</returns> private static bool EnsureInstanceExists <T>(Object target, GenericField <T> field) where T : ScriptableObject { if (field.Instance == null) { List <Type> availableTypes = TypeLoader.GetTypes(field.Type); if (availableTypes.Count == 0) { return(true); } AddInstance(target, field, availableTypes[0]); } return(false); }
public virtual GenericClass ClassMetaToGenericClass(GenericReflector reflector, ClassInfo classMeta) { if (classMeta.IsSystemClass()) { return((GenericClass)reflector.ForName(classMeta.GetClassName())); } var className = classMeta.GetClassName(); // look up from generic class table. var genericClass = LookupGenericClass(className); if (genericClass != null) { return(genericClass); } var reflectClass = reflector.ForName(className); if (reflectClass != null) { return((GenericClass)reflectClass); } GenericClass genericSuperClass = null; var superClassMeta = classMeta.GetSuperClass(); if (superClassMeta != null) { genericSuperClass = ClassMetaToGenericClass(reflector, superClassMeta); } genericClass = new GenericClass(reflector, null, className, genericSuperClass); RegisterGenericClass(className, genericClass); var fields = classMeta.GetFields(); var genericFields = new GenericField[fields.Length]; for (var i = 0; i < fields.Length; ++i) { var fieldClassMeta = fields[i].GetFieldClass(); var fieldName = fields[i].GetFieldName(); var genericFieldClass = ClassMetaToGenericClass(reflector, fieldClassMeta ); genericFields[i] = new GenericField(fieldName, genericFieldClass, fields[i]._isPrimitive ); } genericClass.InitFields(genericFields); return(genericClass); }
/// <returns>Inspector height</returns> private static float DrawInspector <T>(GenericField <T> field, SerializedObject objectReference, SerializedProperty property, Rect rect) where T : ScriptableObject { if (field.Instance == null) { return(0); } if (PropertyDrawerLoader.Drawers.ContainsKey(field.Type)) { PropertyDrawer customDrawer = PropertyDrawerLoader.Drawers[field.Type]; rect.height = customDrawer.GetPropertyHeight(property, GUIContent.none); customDrawer.OnGUI(rect, property, GUIContent.none); } else { rect.height = GeneralPropertyDrawer.Drawer.GetPropertyHeight(objectReference, property, GUIContent.none); GeneralPropertyDrawer.Drawer.OnGUI(rect, objectReference, property, GUIContent.none); } return(rect.height); }
/// <summary>Get the data to display for this subject.</summary> /// <param name="metadata">Provides metadata that's not available from the game data directly.</param> public override IEnumerable <ICustomField> GetData(Metadata metadata) { // get data Item item = this.Target; SObject obj = item as SObject; bool isObject = obj != null; bool isCrop = this.FromCrop != null; bool isSeed = this.SeedForCrop != null; bool isDeadCrop = this.FromCrop?.dead.Value == true; bool canSell = obj?.canBeShipped() == true || metadata.Shops.Any(shop => shop.BuysCategories.Contains(item.Category)); // get overrides bool showInventoryFields = true; { ObjectData objData = metadata.GetObject(item, this.Context); if (objData != null) { this.Name = objData.NameKey != null?this.Translate(objData.NameKey) : this.Name; this.Description = objData.DescriptionKey != null?this.Translate(objData.DescriptionKey) : this.Description; this.Type = objData.TypeKey != null?this.Translate(objData.TypeKey) : this.Type; showInventoryFields = objData.ShowInventoryFields ?? true; } } // don't show data for dead crop if (isDeadCrop) { yield return(new GenericField(this.Translate(L10n.Crop.Summary), this.Translate(L10n.Crop.SummaryDead))); yield break; } // crop fields if (isCrop || isSeed) { // get crop Crop crop = this.FromCrop ?? this.SeedForCrop; // get harvest schedule int harvestablePhase = crop.phaseDays.Count - 1; bool canHarvestNow = (crop.currentPhase.Value >= harvestablePhase) && (!crop.fullyGrown.Value || crop.dayOfCurrentPhase.Value <= 0); int daysToFirstHarvest = crop.phaseDays.Take(crop.phaseDays.Count - 1).Sum(); // ignore harvestable phase // add next-harvest field if (isCrop) { // calculate next harvest int daysToNextHarvest = 0; SDate dayOfNextHarvest = null; if (!canHarvestNow) { // calculate days until next harvest int daysUntilLastPhase = daysToFirstHarvest - crop.dayOfCurrentPhase.Value - crop.phaseDays.Take(crop.currentPhase.Value).Sum(); { // growing: days until next harvest if (!crop.fullyGrown.Value) { daysToNextHarvest = daysUntilLastPhase; } // regrowable crop harvested today else if (crop.dayOfCurrentPhase.Value >= crop.regrowAfterHarvest.Value) { daysToNextHarvest = crop.regrowAfterHarvest.Value; } // regrowable crop else { daysToNextHarvest = crop.dayOfCurrentPhase.Value; // dayOfCurrentPhase decreases to 0 when fully grown, where <=0 is harvestable } } dayOfNextHarvest = SDate.Now().AddDays(daysToNextHarvest); } // generate field string summary; if (canHarvestNow) { summary = this.Translate(L10n.Crop.HarvestNow); } else if (Game1.currentLocation.Name != Constant.LocationNames.Greenhouse && !crop.seasonsToGrowIn.Contains(dayOfNextHarvest.Season)) { summary = this.Translate(L10n.Crop.HarvestTooLate, new { date = this.Stringify(dayOfNextHarvest) }); } else { summary = $"{this.Stringify(dayOfNextHarvest)} ({this.Text.GetPlural(daysToNextHarvest, L10n.Generic.Tomorrow, L10n.Generic.InXDays).Tokens(new { count = daysToNextHarvest })})"; } yield return(new GenericField(this.Translate(L10n.Crop.Harvest), summary)); } // crop summary { List <string> summary = new List <string>(); // harvest summary.Add(crop.regrowAfterHarvest.Value == -1 ? this.Translate(L10n.Crop.SummaryHarvestOnce, new { daysToFirstHarvest = daysToFirstHarvest }) : this.Translate(L10n.Crop.SummaryHarvestMulti, new { daysToFirstHarvest = daysToFirstHarvest, daysToNextHarvests = crop.regrowAfterHarvest }) ); // seasons summary.Add(this.Translate(L10n.Crop.SummarySeasons, new { seasons = string.Join(", ", this.Text.GetSeasonNames(crop.seasonsToGrowIn)) })); // drops if (crop.minHarvest != crop.maxHarvest && crop.chanceForExtraCrops.Value > 0) { summary.Add(this.Translate(L10n.Crop.SummaryDropsXToY, new { min = crop.minHarvest, max = crop.maxHarvest, percent = Math.Round(crop.chanceForExtraCrops.Value * 100, 2) })); } else if (crop.minHarvest.Value > 1) { summary.Add(this.Translate(L10n.Crop.SummaryDropsX, new { count = crop.minHarvest })); } // crop sale price Item drop = GameHelper.GetObjectBySpriteIndex(crop.indexOfHarvest.Value); summary.Add(this.Translate(L10n.Crop.SummarySellsFor, new { price = GenericField.GetSaleValueString(this.GetSaleValue(drop, false, metadata), 1, this.Text) })); // generate field yield return(new GenericField(this.Translate(L10n.Crop.Summary), "-" + string.Join($"{Environment.NewLine}-", summary))); } } // crafting if (obj?.heldObject?.Value != null) { if (obj is Cask cask) { // get cask data SObject agingObj = cask.heldObject.Value; ItemQuality curQuality = (ItemQuality)agingObj.Quality; string curQualityName = this.Translate(L10n.For(curQuality)); // calculate aging schedule float effectiveAge = metadata.Constants.CaskAgeSchedule.Values.Max() - cask.daysToMature.Value; var schedule = ( from entry in metadata.Constants.CaskAgeSchedule let quality = entry.Key let baseDays = entry.Value where baseDays > effectiveAge orderby baseDays ascending let daysLeft = (int)Math.Ceiling((baseDays - effectiveAge) / cask.agingRate.Value) select new { Quality = quality, DaysLeft = daysLeft, HarvestDate = SDate.Now().AddDays(daysLeft) } ) .ToArray(); // display fields yield return(new ItemIconField(this.Translate(L10n.Item.Contents), obj.heldObject.Value)); if (cask.MinutesUntilReady <= 0 || !schedule.Any()) { yield return(new GenericField(this.Translate(L10n.Item.CaskSchedule), this.Translate(L10n.Item.CaskScheduleNow, new { quality = curQualityName }))); } else { string scheduleStr = string.Join(Environment.NewLine, ( from entry in schedule let tokens = new { quality = this.Translate(L10n.For(entry.Quality)), count = entry.DaysLeft, date = entry.HarvestDate } let str = this.Text.GetPlural(entry.DaysLeft, L10n.Item.CaskScheduleTomorrow, L10n.Item.CaskScheduleInXDays).Tokens(tokens) select $"-{str}" )); yield return(new GenericField(this.Translate(L10n.Item.CaskSchedule), this.Translate(L10n.Item.CaskSchedulePartial, new { quality = curQualityName }) + Environment.NewLine + scheduleStr)); } } else if (obj is Furniture) { string summary = this.Translate(L10n.Item.ContentsPlaced, new { name = obj.heldObject.Value.DisplayName }); yield return(new ItemIconField(this.Translate(L10n.Item.Contents), obj.heldObject.Value, summary)); } else { string summary = obj.MinutesUntilReady <= 0 ? this.Translate(L10n.Item.ContentsReady, new { name = obj.heldObject.Value.DisplayName }) : this.Translate(L10n.Item.ContentsPartial, new { name = obj.heldObject.Value.DisplayName, time = this.Stringify(TimeSpan.FromMinutes(obj.MinutesUntilReady)) }); yield return(new ItemIconField(this.Translate(L10n.Item.Contents), obj.heldObject.Value, summary)); } } // item if (showInventoryFields) { // needed for { List <string> neededFor = new List <string>(); // bundles if (isObject) { string[] bundles = (from bundle in this.GetUnfinishedBundles(obj) orderby bundle.Area, bundle.DisplayName select $"{this.GetTranslatedBundleArea(bundle)}: {bundle.DisplayName}").ToArray(); if (bundles.Any()) { neededFor.Add(this.Translate(L10n.Item.NeededForCommunityCenter, new { bundles = string.Join(", ", bundles) })); } } // polyculture achievement if (isObject && metadata.Constants.PolycultureCrops.Contains(obj.ParentSheetIndex)) { int needed = metadata.Constants.PolycultureCount - GameHelper.GetShipped(obj.ParentSheetIndex); if (needed > 0) { neededFor.Add(this.Translate(L10n.Item.NeededForPolyculture, new { count = needed })); } } // full shipment achievement if (isObject && GameHelper.GetFullShipmentAchievementItems().Any(p => p.Key == obj.ParentSheetIndex && !p.Value)) { neededFor.Add(this.Translate(L10n.Item.NeededForFullShipment)); } // a full collection achievement LibraryMuseum museum = Game1.locations.OfType <LibraryMuseum>().FirstOrDefault(); if (museum != null && museum.isItemSuitableForDonation(obj)) { neededFor.Add(this.Translate(L10n.Item.NeededForFullCollection)); } // yield if (neededFor.Any()) { yield return(new GenericField(this.Translate(L10n.Item.NeededFor), string.Join(", ", neededFor))); } } // sale data if (canSell && !isCrop) { // sale price string saleValueSummary = GenericField.GetSaleValueString(this.GetSaleValue(item, this.KnownQuality, metadata), item.Stack, this.Text); yield return(new GenericField(this.Translate(L10n.Item.SellsFor), saleValueSummary)); // sell to List <string> buyers = new List <string>(); if (obj?.canBeShipped() == true) { buyers.Add(this.Translate(L10n.Item.SellsToShippingBox)); } buyers.AddRange( from shop in metadata.Shops where shop.BuysCategories.Contains(item.Category) let name = this.Translate(shop.DisplayKey).ToString() orderby name select name ); yield return(new GenericField(this.Translate(L10n.Item.SellsTo), string.Join(", ", buyers))); } // gift tastes var giftTastes = this.GetGiftTastes(item, metadata); yield return(new ItemGiftTastesField(this.Translate(L10n.Item.LovesThis), giftTastes, GiftTaste.Love)); yield return(new ItemGiftTastesField(this.Translate(L10n.Item.LikesThis), giftTastes, GiftTaste.Like)); } // fence if (item is Fence fence) { string healthLabel = this.Translate(L10n.Item.FenceHealth); // health if (Game1.getFarm().isBuildingConstructed(Constant.BuildingNames.GoldClock)) { yield return(new GenericField(healthLabel, this.Translate(L10n.Item.FenceHealthGoldClock))); } else { float maxHealth = fence.isGate.Value ? fence.maxHealth.Value * 2 : fence.maxHealth.Value; float health = fence.health.Value / maxHealth; double daysLeft = Math.Round(fence.health.Value * metadata.Constants.FenceDecayRate / 60 / 24); double percent = Math.Round(health * 100); yield return(new PercentageBarField(healthLabel, (int)fence.health, (int)maxHealth, Color.Green, Color.Red, this.Translate(L10n.Item.FenceHealthSummary, new { percent = percent, count = daysLeft }))); } } // recipes if (item.GetSpriteType() == ItemSpriteType.Object) { RecipeModel[] recipes = GameHelper.GetRecipesForIngredient(this.DisplayItem).ToArray(); if (recipes.Any()) { yield return(new RecipesForIngredientField(this.Translate(L10n.Item.Recipes), item, recipes, this.Text)); } } // owned if (showInventoryFields && !isCrop && !(item is Tool)) { yield return(new GenericField(this.Translate(L10n.Item.Owned), this.Translate(L10n.Item.OwnedSummary, new { count = GameHelper.CountOwnedItems(item) }))); } // see also crop bool seeAlsoCrop = isSeed && item.ParentSheetIndex != this.SeedForCrop.indexOfHarvest.Value && // skip seeds which produce themselves (e.g. coffee beans) !(item.ParentSheetIndex >= 495 && item.ParentSheetIndex <= 497) && // skip random seasonal seeds item.ParentSheetIndex != 770; // skip mixed seeds if (seeAlsoCrop) { Item drop = GameHelper.GetObjectBySpriteIndex(this.SeedForCrop.indexOfHarvest.Value); yield return(new LinkField(this.Translate(L10n.Item.SeeAlso), drop.DisplayName, () => new ItemSubject(this.Text, drop, ObjectContext.Inventory, false, this.SeedForCrop))); } }
/// <summary>Get the custom fields for a crop.</summary> /// <param name="dirt">The dirt the crop is planted in, if applicable.</param> /// <param name="crop">The crop to represent.</param> /// <param name="isSeed">Whether the crop being displayed is for an unplanted seed.</param> private IEnumerable <ICustomField> GetCropFields(HoeDirt?dirt, Crop?crop, bool isSeed) { if (crop == null) { yield break; } var data = new CropDataParser(crop, isPlanted: !isSeed); bool isForage = crop.whichForageCrop.Value > 0 && crop.fullyGrown.Value; // show crop fields for growing mixed seeds // add next-harvest field if (!isSeed) { // get next harvest SDate nextHarvest = data.GetNextHarvest(); // generate field string summary; if (data.CanHarvestNow) { summary = I18n.Generic_Now(); } else if (!Game1.currentLocation.SeedsIgnoreSeasonsHere() && !data.Seasons.Contains(nextHarvest.Season)) { summary = I18n.Crop_Harvest_TooLate(date: this.Stringify(nextHarvest)); } else { summary = $"{this.Stringify(nextHarvest)} ({this.GetRelativeDateStr(nextHarvest)})"; } yield return(new GenericField(I18n.Crop_Harvest(), summary)); } // crop summary if (!isForage) { List <string> summary = new(); // harvest if (!crop.forageCrop.Value) { summary.Add(data.HasMultipleHarvests ? I18n.Crop_Summary_HarvestOnce(daysToFirstHarvest: data.DaysToFirstHarvest) : I18n.Crop_Summary_HarvestMulti(daysToFirstHarvest: data.DaysToFirstHarvest, daysToNextHarvests: data.DaysToSubsequentHarvest) ); } // seasons summary.Add(I18n.Crop_Summary_Seasons(seasons: string.Join(", ", I18n.GetSeasonNames(data.Seasons)))); // drops if (crop.minHarvest != crop.maxHarvest && crop.chanceForExtraCrops.Value > 0) { summary.Add(I18n.Crop_Summary_DropsXToY(min: crop.minHarvest.Value, max: crop.maxHarvest.Value, percent: (int)Math.Round(crop.chanceForExtraCrops.Value * 100, 2))); } else if (crop.minHarvest.Value > 1) { summary.Add(I18n.Crop_Summary_DropsX(count: crop.minHarvest.Value)); } // crop sale price Item drop = data.GetSampleDrop(); summary.Add(I18n.Crop_Summary_SellsFor(price: GenericField.GetSaleValueString(this.GetSaleValue(drop, false), 1) !)); // generate field yield return(new GenericField(I18n.Crop_Summary(), "-" + string.Join($"{Environment.NewLine}-", summary))); } // dirt water/fertilizer state if (dirt != null && !isForage) { // watered yield return(new GenericField(I18n.Crop_Watered(), this.Stringify(dirt.state.Value == HoeDirt.watered))); // fertilizer string[] appliedFertilizers = this.GetAppliedFertilizers(dirt) .Select(GameI18n.GetObjectName) .Distinct() .DefaultIfEmpty(this.Stringify(false)) .OrderBy(p => p) .ToArray(); yield return(new GenericField(I18n.Crop_Fertilized(), string.Join(", ", appliedFertilizers))); } }
/// <summary>Get the data to display for this subject.</summary> public override IEnumerable <ICustomField> GetData() { // get data Item item = this.Target; SObject?obj = item as SObject; bool isCrop = this.FromCrop != null; bool isSeed = this.SeedForCrop != null; bool isDeadCrop = this.FromCrop?.dead.Value == true; bool canSell = obj?.canBeShipped() == true || this.Metadata.Shops.Any(shop => shop.BuysCategories.Contains(item.Category)); bool isMovieTicket = obj?.ParentSheetIndex == 809 && !obj.bigCraftable.Value; // get overrides bool showInventoryFields = !this.IsSpawnedStoneNode(); { ObjectData?objData = this.Metadata.GetObject(item, this.Context); if (objData != null) { this.Name = objData.NameKey != null?I18n.GetByKey(objData.NameKey) : this.Name; this.Description = objData.DescriptionKey != null?I18n.GetByKey(objData.DescriptionKey) : this.Description; this.Type = objData.TypeKey != null?I18n.GetByKey(objData.TypeKey) : this.Type; showInventoryFields = objData.ShowInventoryFields ?? showInventoryFields; } } // don't show data for dead crop if (isDeadCrop) { yield return(new GenericField(I18n.Crop_Summary(), I18n.Crop_Summary_Dead())); yield break; } // crop fields foreach (ICustomField field in this.GetCropFields(this.FromDirt, this.FromCrop ?? this.SeedForCrop, isSeed)) { yield return(field); } // indoor pot crop if (obj is IndoorPot pot) { Crop?potCrop = pot.hoeDirt.Value.crop; Bush?potBush = pot.bush.Value; if (potCrop != null) { Item drop = this.GameHelper.GetObjectBySpriteIndex(potCrop.indexOfHarvest.Value); yield return(new LinkField(I18n.Item_Contents(), drop.DisplayName, () => this.GetCropSubject(potCrop, ObjectContext.World, pot.hoeDirt.Value))); } if (potBush != null) { ISubject?subject = this.Codex.GetByEntity(potBush, this.Location ?? potBush.currentLocation); if (subject != null) { yield return(new LinkField(I18n.Item_Contents(), subject.Name, () => subject)); } } } // machine output foreach (ICustomField field in this.GetMachineOutputFields(obj)) { yield return(field); } // music blocks if (obj?.Name == "Flute Block") { yield return(new GenericField(I18n.Item_MusicBlock_Pitch(), I18n.Generic_Ratio(value: obj.preservedParentSheetIndex.Value, max: 2300))); } else if (obj?.Name == "Drum Block") { yield return(new GenericField(I18n.Item_MusicBlock_DrumType(), I18n.Generic_Ratio(value: obj.preservedParentSheetIndex.Value, max: 6))); } // item if (showInventoryFields) { // needed for foreach (ICustomField field in this.GetNeededForFields(obj)) { yield return(field); } // sale data if (canSell && !isCrop) { // sale price string?saleValueSummary = GenericField.GetSaleValueString(this.GetSaleValue(item, this.KnownQuality), item.Stack); yield return(new GenericField(I18n.Item_SellsFor(), saleValueSummary)); // sell to List <string> buyers = new(); if (obj?.canBeShipped() == true) { buyers.Add(I18n.Item_SellsTo_ShippingBox()); } buyers.AddRange( from shop in this.Metadata.Shops where shop.BuysCategories.Contains(item.Category) let name = I18n.GetByKey(shop.DisplayKey).ToString() orderby name select name ); yield return(new GenericField(I18n.Item_SellsTo(), string.Join(", ", buyers))); } // clothing if (item is Clothing clothing) { yield return(new GenericField(I18n.Item_CanBeDyed(), this.Stringify(clothing.dyeable.Value))); } // gift tastes if (!isMovieTicket) { IDictionary <GiftTaste, GiftTasteModel[]> giftTastes = this.GetGiftTastes(item); yield return(new ItemGiftTastesField(I18n.Item_LovesThis(), giftTastes, GiftTaste.Love, onlyRevealed: this.ProgressionMode, highlightUnrevealed: this.HighlightUnrevealedGiftTastes)); yield return(new ItemGiftTastesField(I18n.Item_LikesThis(), giftTastes, GiftTaste.Like, onlyRevealed: this.ProgressionMode, highlightUnrevealed: this.HighlightUnrevealedGiftTastes)); if (this.ProgressionMode || this.HighlightUnrevealedGiftTastes || this.ShowAllGiftTastes) { yield return(new ItemGiftTastesField(I18n.Item_NeutralAboutThis(), giftTastes, GiftTaste.Neutral, onlyRevealed: this.ProgressionMode, highlightUnrevealed: this.HighlightUnrevealedGiftTastes)); yield return(new ItemGiftTastesField(I18n.Item_DislikesThis(), giftTastes, GiftTaste.Dislike, onlyRevealed: this.ProgressionMode, highlightUnrevealed: this.HighlightUnrevealedGiftTastes)); yield return(new ItemGiftTastesField(I18n.Item_HatesThis(), giftTastes, GiftTaste.Hate, onlyRevealed: this.ProgressionMode, highlightUnrevealed: this.HighlightUnrevealedGiftTastes)); } } } // recipes if (showInventoryFields) { RecipeModel[] recipes = // recipes that take this item as ingredient this.GameHelper.GetRecipesForIngredient(this.DisplayItem) .Concat(this.GameHelper.GetRecipesForIngredient(item)) // recipes which produce this item .Concat(this.GameHelper.GetRecipesForOutput(this.DisplayItem)) .Concat(this.GameHelper.GetRecipesForOutput(item)) // recipes for a machine .Concat(this.GameHelper.GetRecipesForMachine(this.DisplayItem as SObject)) .Concat(this.GameHelper.GetRecipesForMachine(item as SObject)) .ToArray(); if (recipes.Any()) { yield return(new ItemRecipesField(this.GameHelper, I18n.Item_Recipes(), item, recipes.ToArray())); } } // fish spawn rules if (item.Category == SObject.FishCategory) { yield return(new FishSpawnRulesField(this.GameHelper, I18n.Item_FishSpawnRules(), item.ParentSheetIndex)); } // fish pond data // derived from FishPond::doAction and FishPond::isLegalFishForPonds if (!item.HasContextTag("fish_legendary") && (item.Category == SObject.FishCategory || Utility.IsNormalObjectAtParentSheetIndex(item, 393 /*coral*/) || Utility.IsNormalObjectAtParentSheetIndex(item, 397 /*sea urchin*/))) { foreach (FishPondData fishPondData in Game1.content.Load <List <FishPondData> >("Data\\FishPondData")) { if (!fishPondData.RequiredTags.All(item.HasContextTag)) { continue; } int minChanceOfAnyDrop = (int)Math.Round(Utility.Lerp(0.15f, 0.95f, 1 / 10f) * 100); int maxChanceOfAnyDrop = (int)Math.Round(Utility.Lerp(0.15f, 0.95f, FishPond.MAXIMUM_OCCUPANCY / 10f) * 100); string preface = I18n.Building_FishPond_Drops_Preface(chance: I18n.Generic_Range(min: minChanceOfAnyDrop, max: maxChanceOfAnyDrop)); yield return(new FishPondDropsField(this.GameHelper, I18n.Item_FishPondDrops(), -1, fishPondData, preface)); break; } } // fence if (item is Fence fence) { string healthLabel = I18n.Item_FenceHealth(); // health if (Game1.getFarm().isBuildingConstructed(Constant.BuildingNames.GoldClock)) { yield return(new GenericField(healthLabel, I18n.Item_FenceHealth_GoldClock())); } else { float maxHealth = fence.isGate.Value ? fence.maxHealth.Value * 2 : fence.maxHealth.Value; float health = fence.health.Value / maxHealth; double daysLeft = Math.Round(fence.health.Value * this.Constants.FenceDecayRate / 60 / 24); double percent = Math.Round(health * 100); yield return(new PercentageBarField(healthLabel, (int)fence.health.Value, (int)maxHealth, Color.Green, Color.Red, I18n.Item_FenceHealth_Summary(percent: (int)percent, count: (int)daysLeft))); } } // movie ticket if (isMovieTicket) { MovieData movie = MovieTheater.GetMovieForDate(Game1.Date); if (movie == null) { yield return(new GenericField(I18n.Item_MovieTicket_MovieThisWeek(), I18n.Item_MovieTicket_MovieThisWeek_None())); } else { // movie this week yield return(new GenericField(I18n.Item_MovieTicket_MovieThisWeek(), new IFormattedText[] { new FormattedText(movie.Title, bold: true), new FormattedText(Environment.NewLine), new FormattedText(movie.Description) })); // movie tastes const GiftTaste rejectKey = (GiftTaste)(-1); IDictionary <GiftTaste, string[]> tastes = this.GameHelper.GetMovieTastes() .GroupBy(entry => entry.Value ?? rejectKey) .ToDictionary(group => group.Key, group => group.Select(p => p.Key.Name).OrderBy(p => p).ToArray()); yield return(new MovieTastesField(I18n.Item_MovieTicket_LovesMovie(), tastes, GiftTaste.Love)); yield return(new MovieTastesField(I18n.Item_MovieTicket_LikesMovie(), tastes, GiftTaste.Like)); yield return(new MovieTastesField(I18n.Item_MovieTicket_DislikesMovie(), tastes, GiftTaste.Dislike)); yield return(new MovieTastesField(I18n.Item_MovieTicket_RejectsMovie(), tastes, rejectKey)); } } // dyes if (showInventoryFields) { yield return(new ColorField(I18n.Item_ProducesDye(), item)); } // owned and times cooked/crafted if (showInventoryFields && !isCrop) { // owned yield return(new GenericField(I18n.Item_NumberOwned(), I18n.Item_NumberOwned_Summary(count: this.GameHelper.CountOwnedItems(item)))); // times crafted RecipeModel[] recipes = this.GameHelper .GetRecipes() .Where(recipe => recipe.OutputItemIndex == this.Target.ParentSheetIndex && recipe.OutputItemType == this.Target.GetItemType()) .ToArray(); if (recipes.Any()) { string label = recipes.First().Type == RecipeType.Cooking ? I18n.Item_NumberCooked() : I18n.Item_NumberCrafted(); int timesCrafted = recipes.Sum(recipe => recipe.GetTimesCrafted(Game1.player)); if (timesCrafted >= 0) // negative value means not available for this recipe type { yield return(new GenericField(label, I18n.Item_NumberCrafted_Summary(count: timesCrafted))); } } } // see also crop bool seeAlsoCrop = isSeed && item.ParentSheetIndex != this.SeedForCrop !.indexOfHarvest.Value && // skip seeds which produce themselves (e.g. coffee beans) item.ParentSheetIndex is not(495 or 496 or 497) && // skip random seasonal seeds item.ParentSheetIndex != 770; // skip mixed seeds if (seeAlsoCrop) { Item drop = this.GameHelper.GetObjectBySpriteIndex(this.SeedForCrop !.indexOfHarvest.Value); yield return(new LinkField(I18n.Item_SeeAlso(), drop.DisplayName, () => this.GetCropSubject(this.SeedForCrop, ObjectContext.Inventory, null))); } }
// Update Custom Attribute via SOAP API // After create/update incident, the custom attribute may need to update. protected void UpdateIncCustomAttr(int incidentID, string key, string value) { //Create an Incident object Accelerator.Siebel.SharedServices.RightNowServiceReference.Incident updateIncident = new Accelerator.Siebel.SharedServices.RightNowServiceReference.Incident(); //Create and set the Id property ID incID = new ID(); //Set the Id on the Incident Object incID.id = incidentID; incID.idSpecified = true; updateIncident.ID = incID; if (value != null && value != "") { GenericField customField = new GenericField(); // Check update which custom attribute switch (key) { case "siebel_sr_id": customField.name = "siebel_sr_id"; customField.dataType = DataTypeEnum.STRING; customField.dataTypeSpecified = true; customField.DataValue = new DataValue(); customField.DataValue.Items = new object[1]; customField.DataValue.ItemsElementName = new ItemsChoiceType[1]; customField.DataValue.Items[0] = value; customField.DataValue.ItemsElementName[0] = ItemsChoiceType.StringValue; break; case "siebel_sr_num": customField.name = "siebel_sr_num"; customField.dataType = DataTypeEnum.STRING; customField.dataTypeSpecified = true; customField.DataValue = new DataValue(); customField.DataValue.Items = new object[1]; customField.DataValue.ItemsElementName = new ItemsChoiceType[1]; customField.DataValue.Items[0] = value; customField.DataValue.ItemsElementName[0] = ItemsChoiceType.StringValue; break; case "siebel_max_thread_id": customField.name = "siebel_max_thread_id"; customField.dataType = DataTypeEnum.INTEGER; customField.dataTypeSpecified = true; customField.DataValue = new DataValue(); customField.DataValue.Items = new object[1]; customField.DataValue.ItemsElementName = new ItemsChoiceType[1]; customField.DataValue.Items[0] = Convert.ToInt32(value); customField.DataValue.ItemsElementName[0] = ItemsChoiceType.IntegerValue; break; default: return; } GenericObject customFieldsc = new GenericObject(); customFieldsc.GenericFields = new GenericField[1]; customFieldsc.GenericFields[0] = customField; customFieldsc.ObjectType = new RNObjectType(); customFieldsc.ObjectType.TypeName = "IncidentCustomFieldsc"; GenericField cField = new GenericField(); cField.name = "Accelerator"; cField.dataType = DataTypeEnum.OBJECT; cField.dataTypeSpecified = true; cField.DataValue = new DataValue(); cField.DataValue.Items = new object[1]; cField.DataValue.Items[0] = customFieldsc; cField.DataValue.ItemsElementName = new ItemsChoiceType[1]; cField.DataValue.ItemsElementName[0] = ItemsChoiceType.ObjectValue; updateIncident.CustomFields = new GenericObject(); updateIncident.CustomFields.GenericFields = new GenericField[1]; updateIncident.CustomFields.GenericFields[0] = cField; updateIncident.CustomFields.ObjectType = new RNObjectType(); updateIncident.CustomFields.ObjectType.TypeName = "IncidentCustomFields"; } else { return; } //Create the RNObject array RNObject[] objects = new RNObject[] { updateIncident }; try { _rnSrv.updateObject(objects); } catch (Exception ex) { if (_log != null) { string logMessage = "Error in updating incident custom field via Cloud Service SOAP. Try to update incident(ID = " + incidentID + ") custom attribute " + key + " to value" + value + "; Error Message: "+ ex.Message; _log.ErrorLog(incidentId:_logIncidentId, logMessage: logMessage); } MessageBox.Show("There has been an error communicating with Cloud Service SOAP. Please check log for detail.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Create Internal Incident Records /// </summary> /// <param name="contactID"></param> /// <param name="srID"></param> /// <param name="reportingIncID"></param> /// <param name="fsarID"></param> /// <param name="orgID"></param> /// <returns></returns> public int CreateInternalIncident(int contactID, int srID, int reportingIncID, int fsarID, int orgID) { try { //Check if it exist in order to avoid duplicate record Incident internalIncident = new Incident(); string response = checkIfInternalIncidentExistForSR(reportingIncID, srID); if (response != null) { internalIncident.ID = new ID { id = Convert.ToInt32(response), idSpecified = true }; } /*Set OOTB fields*/ IncidentContact primarycontact = new IncidentContact { Contact = new NamedID { ID = new ID { id = contactID, idSpecified = true } } }; internalIncident.PrimaryContact = primarycontact; internalIncident.Organization = new NamedID { ID = new ID { id = orgID, idSpecified = true } }; /*Set Custom fields*/ List <GenericField> customAttributes = new List <GenericField>(); customAttributes.Add(createGenericField("FSAR", createNamedIDDataValue(fsarID), DataTypeEnum.NAMED_ID)); customAttributes.Add(createGenericField("SalesRelease", createNamedIDDataValue(srID), DataTypeEnum.NAMED_ID)); customAttributes.Add(createGenericField("reporting_incident", createNamedIDDataValue(reportingIncID), DataTypeEnum.NAMED_ID)); GenericObject customAttributeobj = genericObject(customAttributes.ToArray(), "IncidentCustomFieldsc"); GenericField caPackage = createGenericField("CO", createObjDataValue(customAttributeobj), DataTypeEnum.OBJECT); /*Set Custom fields*/ List <GenericField> customFields = new List <GenericField>(); customFields.Add(createGenericField("incident_type", createNamedIDDataValueForName("Internal Incident"), DataTypeEnum.NAMED_ID));//55 is id of "Internal incident" GenericObject customfieldobj = genericObject(customFields.ToArray(), "IncidentCustomFieldsc"); GenericField cfpackage = createGenericField("c", createObjDataValue(customfieldobj), DataTypeEnum.OBJECT); internalIncident.CustomFields = genericObject(new[] { caPackage, cfpackage }, "IncidentCustomFields"); ClientInfoHeader hdr = new ClientInfoHeader() { AppID = "Create Internal Incident" }; //Update if internal incident exist if (response != null) { _rightNowClient.Update(hdr, new RNObject[] { internalIncident }, new UpdateProcessingOptions { SuppressExternalEvents = false, SuppressRules = false }); return(Convert.ToInt32(response)); } else//create a new internal incident { RNObject[] resultobj = _rightNowClient.Create(hdr, new RNObject[] { internalIncident }, new CreateProcessingOptions { SuppressExternalEvents = false, SuppressRules = false }); if (resultobj != null) { return(Convert.ToInt32(resultobj[0].ID.id)); } } } catch (Exception ex) { WorkspaceAddIn.InfoLog("Excpetion in creating internal incident: " + ex.Message); } return(0); }
/// <summary>Get the custom fields for a crop.</summary> /// <param name="crop">The crop to represent.</param> /// <param name="isSeed">Whether the crop being displayed is for an unplanted seed.</param> private IEnumerable <ICustomField> GetCropFields(Crop crop, bool isSeed) { if (crop == null) { yield break; } var data = new CropDataParser(crop, isPlanted: !isSeed); // add next-harvest field if (!isSeed) { // get next harvest SDate nextHarvest = data.GetNextHarvest(); // generate field string summary; if (data.CanHarvestNow) { summary = I18n.Generic_Now(); } else if (!Game1.currentLocation.IsGreenhouse && !data.Seasons.Contains(nextHarvest.Season)) { summary = I18n.Crop_Harvest_TooLate(date: this.Stringify(nextHarvest)); } else { summary = $"{this.Stringify(nextHarvest)} ({this.GetRelativeDateStr(nextHarvest)})"; } yield return(new GenericField(I18n.Crop_Harvest(), summary)); } // crop summary if (crop.whichForageCrop.Value <= 0) { List <string> summary = new List <string>(); // harvest if (!crop.forageCrop.Value) { summary.Add(data.HasMultipleHarvests ? I18n.Crop_Summary_HarvestOnce(daysToFirstHarvest: data.DaysToFirstHarvest) : I18n.Crop_Summary_HarvestMulti(daysToFirstHarvest: data.DaysToFirstHarvest, daysToNextHarvests: data.DaysToSubsequentHarvest) ); } // seasons summary.Add(I18n.Crop_Summary_Seasons(seasons: string.Join(", ", I18n.GetSeasonNames(data.Seasons)))); // drops if (crop.minHarvest != crop.maxHarvest && crop.chanceForExtraCrops.Value > 0) { summary.Add(I18n.Crop_Summary_DropsXToY(min: crop.minHarvest.Value, max: crop.maxHarvest.Value, percent: (int)Math.Round(crop.chanceForExtraCrops.Value * 100, 2))); } else if (crop.minHarvest.Value > 1) { summary.Add(I18n.Crop_Summary_DropsX(count: crop.minHarvest.Value)); } // crop sale price Item drop = data.GetSampleDrop(); summary.Add(I18n.Crop_Summary_SellsFor(price: GenericField.GetSaleValueString(this.GetSaleValue(drop, false), 1))); // generate field yield return(new GenericField(I18n.Crop_Summary(), "-" + string.Join($"{Environment.NewLine}-", summary))); } }
/// <summary> /// Create Reporting Incident /// </summary> /// <param name="contactID"></param> /// <param name="fsarID"></param> /// <param name="orgID"></param> /// <returns></returns> public int CreateReportingIncident(int contactID, int fsarID, int orgID) { try { string response = checkIfReportingIncidentExistforFSAR(fsarID, contactID); if (response != null) { return(Convert.ToInt32(response)); } /*Set OOTB fields*/ Incident reportedIncident = new Incident(); IncidentContact primarycontact = new IncidentContact { Contact = new NamedID { ID = new ID { id = contactID, idSpecified = true } } }; reportedIncident.PrimaryContact = primarycontact; reportedIncident.Organization = new NamedID { ID = new ID { id = orgID, idSpecified = true } }; reportedIncident.StatusWithType = new StatusWithType { Status = new NamedID { Name = "Solution Development" } }; /*Set Custom Attributes*/ List <GenericField> customAttributes = new List <GenericField>(); customAttributes.Add(createGenericField("FSAR", createNamedIDDataValue(fsarID), DataTypeEnum.NAMED_ID)); customAttributes.Add(createGenericField("FSAR_required", createBooleanDataValue(true), DataTypeEnum.BOOLEAN)); GenericObject customAttributeobj = genericObject(customAttributes.ToArray(), "IncidentCustomFieldsc"); GenericField caPackage = createGenericField("CO", createObjDataValue(customAttributeobj), DataTypeEnum.OBJECT); /*Set Custom fields*/ List <GenericField> customFields = new List <GenericField>(); customFields.Add(createGenericField("incident_type", createNamedIDDataValueForName("Reported Incident"), DataTypeEnum.NAMED_ID));//55 is id of "Internal incident" GenericObject customfieldobj = genericObject(customFields.ToArray(), "IncidentCustomFieldsc"); GenericField cfpackage = createGenericField("c", createObjDataValue(customfieldobj), DataTypeEnum.OBJECT); reportedIncident.CustomFields = genericObject(new[] { caPackage, cfpackage }, "IncidentCustomFields"); ClientInfoHeader hdr = new ClientInfoHeader() { AppID = "Create Reported Incident" }; RNObject[] resultobj = _rightNowClient.Create(hdr, new RNObject[] { reportedIncident }, new CreateProcessingOptions { SuppressExternalEvents = false, SuppressRules = false }); if (resultobj != null) { return(Convert.ToInt32(resultobj[0].ID.id)); } } catch (Exception ex) { WorkspaceAddIn.InfoLog("Excpetion in creating reported incident: " + ex.Message); } return(0); }
/// <summary>Get the data to display for this subject.</summary> /// <param name="metadata">Provides metadata that's not available from the game data directly.</param> public override IEnumerable <ICustomField> GetData(Metadata metadata) { // get data Item item = this.Target; SObject obj = item as SObject; bool isCrop = this.FromCrop != null; bool isSeed = this.SeedForCrop != null; bool isDeadCrop = this.FromCrop?.dead.Value == true; bool canSell = obj?.canBeShipped() == true || metadata.Shops.Any(shop => shop.BuysCategories.Contains(item.Category)); // get overrides bool showInventoryFields = true; { ObjectData objData = metadata.GetObject(item, this.Context); if (objData != null) { this.Name = objData.NameKey != null?this.Translate(objData.NameKey) : this.Name; this.Description = objData.DescriptionKey != null?this.Translate(objData.DescriptionKey) : this.Description; this.Type = objData.TypeKey != null?this.Translate(objData.TypeKey) : this.Type; showInventoryFields = objData.ShowInventoryFields ?? true; } } // don't show data for dead crop if (isDeadCrop) { yield return(new GenericField(this.GameHelper, this.Translate(L10n.Crop.Summary), this.Translate(L10n.Crop.SummaryDead))); yield break; } // crop fields foreach (ICustomField field in this.GetCropFields(this.FromCrop ?? this.SeedForCrop, isSeed, metadata)) { yield return(field); } // indoor pot crop if (obj is IndoorPot pot) { Crop potCrop = pot.hoeDirt.Value.crop; if (potCrop != null) { Item drop = this.GameHelper.GetObjectBySpriteIndex(potCrop.indexOfHarvest.Value); yield return(new LinkField(this.GameHelper, this.Translate(L10n.Item.Contents), drop.DisplayName, () => new ItemSubject(this.GameHelper, this.Text, this.GameHelper.GetObjectBySpriteIndex(potCrop.indexOfHarvest.Value), ObjectContext.World, knownQuality: false, fromCrop: potCrop))); } } // machine output foreach (ICustomField field in this.GetMachineOutputFields(obj, metadata)) { yield return(field); } // item if (showInventoryFields) { // needed for foreach (ICustomField field in this.GetNeededForFields(obj, metadata)) { yield return(field); } // sale data if (canSell && !isCrop) { // sale price string saleValueSummary = GenericField.GetSaleValueString(this.GetSaleValue(item, this.KnownQuality, metadata), item.Stack, this.Text); yield return(new GenericField(this.GameHelper, this.Translate(L10n.Item.SellsFor), saleValueSummary)); // sell to List <string> buyers = new List <string>(); if (obj?.canBeShipped() == true) { buyers.Add(this.Translate(L10n.Item.SellsToShippingBox)); } buyers.AddRange( from shop in metadata.Shops where shop.BuysCategories.Contains(item.Category) let name = this.Translate(shop.DisplayKey).ToString() orderby name select name ); yield return(new GenericField(this.GameHelper, this.Translate(L10n.Item.SellsTo), string.Join(", ", buyers))); } // gift tastes var giftTastes = this.GetGiftTastes(item, metadata); yield return(new ItemGiftTastesField(this.GameHelper, this.Translate(L10n.Item.LovesThis), giftTastes, GiftTaste.Love)); yield return(new ItemGiftTastesField(this.GameHelper, this.Translate(L10n.Item.LikesThis), giftTastes, GiftTaste.Like)); } // fence if (item is Fence fence) { string healthLabel = this.Translate(L10n.Item.FenceHealth); // health if (Game1.getFarm().isBuildingConstructed(Constant.BuildingNames.GoldClock)) { yield return(new GenericField(this.GameHelper, healthLabel, this.Translate(L10n.Item.FenceHealthGoldClock))); } else { float maxHealth = fence.isGate.Value ? fence.maxHealth.Value * 2 : fence.maxHealth.Value; float health = fence.health.Value / maxHealth; double daysLeft = Math.Round(fence.health.Value * metadata.Constants.FenceDecayRate / 60 / 24); double percent = Math.Round(health * 100); yield return(new PercentageBarField(this.GameHelper, healthLabel, (int)fence.health.Value, (int)maxHealth, Color.Green, Color.Red, this.Translate(L10n.Item.FenceHealthSummary, new { percent = percent, count = daysLeft }))); } } // recipes if (item.GetSpriteType() == ItemSpriteType.Object) { RecipeModel[] recipes = this.GameHelper.GetRecipesForIngredient(this.DisplayItem).ToArray(); if (recipes.Any()) { yield return(new RecipesForIngredientField(this.GameHelper, this.Translate(L10n.Item.Recipes), item, recipes, this.Text)); } } // owned if (showInventoryFields && !isCrop && !(item is Tool)) { yield return(new GenericField(this.GameHelper, this.Translate(L10n.Item.Owned), this.Translate(L10n.Item.OwnedSummary, new { count = this.GameHelper.CountOwnedItems(item) }))); } // see also crop bool seeAlsoCrop = isSeed && item.ParentSheetIndex != this.SeedForCrop.indexOfHarvest.Value && // skip seeds which produce themselves (e.g. coffee beans) !(item.ParentSheetIndex >= 495 && item.ParentSheetIndex <= 497) && // skip random seasonal seeds item.ParentSheetIndex != 770; // skip mixed seeds if (seeAlsoCrop) { Item drop = this.GameHelper.GetObjectBySpriteIndex(this.SeedForCrop.indexOfHarvest.Value); yield return(new LinkField(this.GameHelper, this.Translate(L10n.Item.SeeAlso), drop.DisplayName, () => new ItemSubject(this.GameHelper, this.Text, drop, ObjectContext.Inventory, false, this.SeedForCrop))); } }
/// <summary>Get the custom fields for a crop.</summary> /// <param name="crop">The crop to represent.</param> /// <param name="isSeed">Whether the crop being displayed is for an unplanted seed.</param> /// <param name="metadata">Provides metadata that's not available from the game data directly.</param> private IEnumerable <ICustomField> GetCropFields(Crop crop, bool isSeed, Metadata metadata) { if (crop == null) { yield break; } var data = new CropDataParser(crop); // add next-harvest field if (!isSeed) { // get next harvest SDate nextHarvest = data.GetNextHarvest(); int daysToNextHarvest = nextHarvest.DaysSinceStart - SDate.Now().DaysSinceStart; // generate field string summary; if (data.CanHarvestNow) { summary = this.Translate(L10n.Crop.HarvestNow); } else if (!Game1.currentLocation.IsGreenhouse && !data.Seasons.Contains(nextHarvest.Season)) { summary = this.Translate(L10n.Crop.HarvestTooLate, new { date = this.Stringify(nextHarvest) }); } else { summary = $"{this.Stringify(nextHarvest)} ({this.Text.GetPlural(daysToNextHarvest, L10n.Generic.Tomorrow, L10n.Generic.InXDays).Tokens(new { count = daysToNextHarvest })})"; } yield return(new GenericField(this.GameHelper, this.Translate(L10n.Crop.Harvest), summary)); } // crop summary { List <string> summary = new List <string>(); // harvest summary.Add(data.HasMultipleHarvests ? this.Translate(L10n.Crop.SummaryHarvestOnce, new { daysToFirstHarvest = data.DaysToFirstHarvest }) : this.Translate(L10n.Crop.SummaryHarvestMulti, new { daysToFirstHarvest = data.DaysToFirstHarvest, daysToNextHarvests = data.DaysToSubsequentHarvest }) ); // seasons summary.Add(this.Translate(L10n.Crop.SummarySeasons, new { seasons = string.Join(", ", this.Text.GetSeasonNames(data.Seasons)) })); // drops if (crop.minHarvest != crop.maxHarvest && crop.chanceForExtraCrops.Value > 0) { summary.Add(this.Translate(L10n.Crop.SummaryDropsXToY, new { min = crop.minHarvest, max = crop.maxHarvest, percent = Math.Round(crop.chanceForExtraCrops.Value * 100, 2) })); } else if (crop.minHarvest.Value > 1) { summary.Add(this.Translate(L10n.Crop.SummaryDropsX, new { count = crop.minHarvest })); } // crop sale price Item drop = data.GetSampleDrop(); summary.Add(this.Translate(L10n.Crop.SummarySellsFor, new { price = GenericField.GetSaleValueString(this.GetSaleValue(drop, false, metadata), 1, this.Text) })); // generate field yield return(new GenericField(this.GameHelper, this.Translate(L10n.Crop.Summary), "-" + string.Join($"{Environment.NewLine}-", summary))); } }
// Create new contact via SOAP API - Created when an EBS Contact without association is selected public long CreateContact(String firstName, String lastName, String phone, String emailAdd, String contactPartyId, string orgId) { string logMessage; string logNote; //Create a Contact Accelerator.EBS.SharedServices.RightNowServiceReference.Contact newContact = new Accelerator.EBS.SharedServices.RightNowServiceReference.Contact(); //Build a PersonName object for the Contact and add the PersonName to the new Contact object PersonName personName = new PersonName(); if (firstName != null && firstName != "") personName.First = firstName; if (lastName != null && lastName != "") personName.Last = lastName; newContact.Name = personName; //Build an Email object and add the Email to the new Contact object if (emailAdd != null && emailAdd != "") { newContact.Emails = new Email[1]; newContact.Emails[0] = new Email(); newContact.Emails[0].Address = emailAdd; newContact.Emails[0].action = ActionEnum.add; newContact.Emails[0].actionSpecified = true; newContact.Emails[0].AddressType = new NamedID(); newContact.Emails[0].AddressType.ID = new ID(); newContact.Emails[0].AddressType.ID.id = 0; newContact.Emails[0].AddressType.ID.idSpecified = true; } //Build a Phone object and add the Phone to the new Contact object if (phone != null && phone != "") { newContact.Phones = new Phone[1]; newContact.Phones[0] = new Phone(); newContact.Phones[0].Number = phone; newContact.Phones[0].action = ActionEnum.add; newContact.Phones[0].actionSpecified = true; newContact.Phones[0].PhoneType = new NamedID(); newContact.Phones[0].PhoneType.ID = new ID(); newContact.Phones[0].PhoneType.ID.id = 0; newContact.Phones[0].PhoneType.ID.idSpecified = true; } //Set EBS Contact Party ID (custom field) to the new Contact if (contactPartyId != null && contactPartyId != "") { GenericField cfContactPartyIdField = new GenericField(); cfContactPartyIdField.name = "ebs_contact_party_id"; cfContactPartyIdField.dataType = DataTypeEnum.INTEGER; cfContactPartyIdField.dataTypeSpecified = true; cfContactPartyIdField.DataValue = new DataValue(); cfContactPartyIdField.DataValue.Items = new object[1]; cfContactPartyIdField.DataValue.ItemsElementName = new ItemsChoiceType[1]; cfContactPartyIdField.DataValue.Items[0] = Convert.ToInt32(contactPartyId); cfContactPartyIdField.DataValue.ItemsElementName[0] = ItemsChoiceType.IntegerValue; GenericField cfContactOrgIdField = new GenericField(); cfContactOrgIdField.name = "ebs_contact_org_id"; cfContactOrgIdField.dataType = DataTypeEnum.INTEGER; cfContactOrgIdField.dataTypeSpecified = true; cfContactOrgIdField.DataValue = new DataValue(); cfContactOrgIdField.DataValue.Items = new object[1]; cfContactOrgIdField.DataValue.ItemsElementName = new ItemsChoiceType[1]; cfContactOrgIdField.DataValue.Items[0] = Convert.ToInt32(orgId); cfContactOrgIdField.DataValue.ItemsElementName[0] = ItemsChoiceType.IntegerValue; GenericObject customFieldsc = new GenericObject(); customFieldsc.GenericFields = new GenericField[2]; customFieldsc.GenericFields[0] = cfContactPartyIdField; customFieldsc.GenericFields[1] = cfContactOrgIdField; customFieldsc.ObjectType = new RNObjectType(); customFieldsc.ObjectType.TypeName = "ContactCustomFieldsc"; GenericField cField = new GenericField(); cField.name = "Accelerator"; cField.dataType = DataTypeEnum.OBJECT; cField.dataTypeSpecified = true; cField.DataValue = new DataValue(); cField.DataValue.Items = new object[1]; cField.DataValue.Items[0] = customFieldsc; cField.DataValue.ItemsElementName = new ItemsChoiceType[1]; cField.DataValue.ItemsElementName[0] = ItemsChoiceType.ObjectValue; newContact.CustomFields = new GenericObject(); newContact.CustomFields.GenericFields = new GenericField[1]; newContact.CustomFields.GenericFields[0] = cField; newContact.CustomFields.ObjectType = new RNObjectType(); newContact.CustomFields.ObjectType.TypeName = "ContactCustomFields"; } //Build the RNObject[] RNObject[] newObjects = new RNObject[] { newContact }; RNObject[] results = null; try { results = _rnSrv.createObject(newObjects); } catch (Exception ex) { if (_log != null) { logMessage = "Error in creating contact via CWSS. Contact " + firstName + " " + lastName + ": " + ex.Message; logNote = ""; _log.ErrorLog(_logIncidentId, _logContactId, logMessage, logNote); } MessageBox.Show("Cannot create contact: " + firstName + " " + lastName + ". Please check log for detail. ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return 0; } logMessage = "New Contact is created successfully. Contact ID = " + results[0].ID.id; logNote = ""; _log.DebugLog(_logIncidentId, _logContactId, logMessage, logNote); return results[0].ID.id; }
/// <summary>Get the custom fields for a crop.</summary> /// <param name="dirt">The dirt the crop is planted in, if applicable.</param> /// <param name="crop">The crop to represent.</param> /// <param name="isSeed">Whether the crop being displayed is for an unplanted seed.</param> private IEnumerable <ICustomField> GetCropFields(HoeDirt dirt, Crop crop, bool isSeed) { if (crop == null) { yield break; } var data = new CropDataParser(crop, isPlanted: !isSeed); bool isForage = crop.whichForageCrop.Value > 0 && crop.fullyGrown.Value; // show crop fields for growing mixed seeds // add next-harvest field if (!isSeed) { // get next harvest SDate nextHarvest = data.GetNextHarvest(); // generate field string summary; if (data.CanHarvestNow) { summary = I18n.Generic_Now(); } else if (!Game1.currentLocation.SeedsIgnoreSeasonsHere() && !data.Seasons.Contains(nextHarvest.Season)) { summary = I18n.Crop_Harvest_TooLate(date: this.Stringify(nextHarvest)); } else { summary = $"{this.Stringify(nextHarvest)} ({this.GetRelativeDateStr(nextHarvest)})"; } yield return(new GenericField(I18n.Crop_Harvest(), summary)); } // crop summary if (!isForage) { List <string> summary = new List <string>(); // harvest if (!crop.forageCrop.Value) { summary.Add(data.HasMultipleHarvests ? I18n.Crop_Summary_HarvestOnce(daysToFirstHarvest: data.DaysToFirstHarvest) : I18n.Crop_Summary_HarvestMulti(daysToFirstHarvest: data.DaysToFirstHarvest, daysToNextHarvests: data.DaysToSubsequentHarvest) ); } // seasons summary.Add(I18n.Crop_Summary_Seasons(seasons: string.Join(", ", I18n.GetSeasonNames(data.Seasons)))); // drops if (crop.minHarvest != crop.maxHarvest && crop.chanceForExtraCrops.Value > 0) { summary.Add(I18n.Crop_Summary_DropsXToY(min: crop.minHarvest.Value, max: crop.maxHarvest.Value, percent: (int)Math.Round(crop.chanceForExtraCrops.Value * 100, 2))); } else if (crop.minHarvest.Value > 1) { summary.Add(I18n.Crop_Summary_DropsX(count: crop.minHarvest.Value)); } // crop sale price Item drop = data.GetSampleDrop(); summary.Add(I18n.Crop_Summary_SellsFor(price: GenericField.GetSaleValueString(this.GetSaleValue(drop, false), 1))); // generate field yield return(new GenericField(I18n.Crop_Summary(), "-" + string.Join($"{Environment.NewLine}-", summary))); } // dirt water/fertilizer state if (dirt != null && !isForage) { // watered yield return(new GenericField(I18n.Crop_Watered(), this.Stringify(dirt.state.Value == HoeDirt.watered))); // fertilizer yield return(new GenericField(I18n.Crop_Fertilized(), dirt.fertilizer.Value switch { HoeDirt.noFertilizer => this.Stringify(false), HoeDirt.speedGro => GameI18n.GetObjectName(465), // Speed-Gro HoeDirt.superSpeedGro => GameI18n.GetObjectName(466), // Deluxe Speed-Gro HoeDirt.hyperSpeedGro => GameI18n.GetObjectName(918), // Hyper Speed-Gro HoeDirt.fertilizerLowQuality => GameI18n.GetObjectName(368), // Basic Fertilizer HoeDirt.fertilizerHighQuality => GameI18n.GetObjectName(369), // Quality Fertilizer HoeDirt.fertilizerDeluxeQuality => GameI18n.GetObjectName(919), // Deluxe Fertilizer HoeDirt.waterRetentionSoil => GameI18n.GetObjectName(370), // Basic Retaining Soil HoeDirt.waterRetentionSoilQuality => GameI18n.GetObjectName(371), // Quality Retaining Soil HoeDirt.waterRetentionSoilDeluxe => GameI18n.GetObjectName(920), // Deluxe Retaining Soil _ => I18n.Generic_Unknown() }));