I don't think I understand dictionaries at all. I understand how to set them up and access them from the same script/object but when it comes to accessing it from a different object/script that's not parent/child I have no idea what I'm doing. This is my script for the gameobject holding the dictionaries:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class HeroStats : MonoBehaviour {
//Dictionary Structure <Key, value>
Dictionary<string,int> HeroStat = new Dictionary<string,int>();
Dictionary<string,string>HeroName = new Dictionary<string,string>();
Dictionary<string,string>StatDef = new Dictionary<string,string>();
//Initialization:
void Start(){
//===NAME==========================
HeroName.Add("Name","Insert Name");
//===STATS=========================
HeroStat.Add("Constitution", 3);
HeroStat.Add("Dexterity", 3);
HeroStat.Add("Intelligence", 3);
HeroStat.Add("Strength", 3);
HeroStat.Add("Wisdom", 3);
//===STAT DEFINITION==============
StatDef.Add("Constitution", "Your Overall Healthiness");
print (HeroName["Name"]);
print (HeroStat["Strength"]);
}
}
and this is the script I'm trying to use to access the dictionary:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
public class heroName : MonoBehaviour {
public HeroStats heroStats;
public Text text;
public string lookUp;
public string what;
// Use this for initialization
void Start(){
heroStats = FindObjectOfType<HeroStats>();
what = heroStats.GetType().GetField("Name").GetValue(this).ToString();
text = gameObject.GetComponent<Text>();
lookUp = this.gameObject.name;
}
void Update(){
}
}
I just have no idea what I'm doing at this point or know what to google. Every video/tutorial I've seen always shows them accessing the dictionary from the same script/object.
A Dictionary is just a way of storing data. Just like an int, or string. You need to have access to your Dictionary in your external script.
You would need to make your Dictionary public in HeroStats, and then in heroName you would simply have
heroStats.HeroStat["Constitution"]
Related
I wanted to create a small extension to add a list of External Tools to VS2019. A quick search brought up what appeared to be perfect example code at https://learn.microsoft.com/en-us/visualstudio/extensibility/writing-to-the-user-settings-store?view=vs-2019. This adds a command to invoke Notepad, so I thought with a few edits, my work was done.
However, this example is written as a synchronous extension, which is deprecated, so I tried putting the code intended for MenuItemCallBack into the Execute method of the extension, but the line
SettingsManager settingsManager = new ShellSettingsManager(ServiceProvider);
fails to compile, because ServiceProvider is now type IAsyncServiceProvider and the ShellSettingsManager constructor wants an argument of type IServiceProvider.
As far as I can tell, ShellSettingsManager is still the way to access the Settings Store, but all the examples I could find all refer to putting code in MenuItemCallback (as well as being several years old) so are for synchronous extensions.
So, can someone point me to the recommended way to get access to the settings store in an asynchronous extension?
The ShellSettingsManager constructor takes either an IServiceProvider interface or an IVsSettings interface. Given your AsyncPackage derived object implements IServiceProvider, you should be able to just pass it in as the argument to your constructor. The following quick demo package worked for me:
using System;
using System.ComponentModel.Design;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft;
using Microsoft.VisualStudio.Settings;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell.Settings;
using Task = System.Threading.Tasks.Task;
namespace UserSettingsDemo
{
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[Guid(UserSettingsDemoPackage.PackageGuidString)]
[ProvideMenuResource("Menus.ctmenu", 1)]
public sealed class UserSettingsDemoPackage : AsyncPackage
{
public const string PackageGuidString = "cff6cdea-21d1-4736-b5ea-6736624e718f";
public static readonly Guid CommandSet = new Guid("dde1417d-ae0d-46c4-8c84-31883dc1a835");
public const int ListExternalToolsCommand = 0x0100;
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
OleMenuCommandService commandService = await GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService;
Assumes.Present(commandService);
var menuItem = new MenuCommand(OnListExternalTools, new CommandID(CommandSet, ListExternalToolsCommand));
commandService.AddCommand(menuItem);
}
private void OnListExternalTools(object sender, EventArgs e)
{
ShellSettingsManager settingsManager = new ShellSettingsManager(this);
WritableSettingsStore userSettingsStore = settingsManager.GetWritableSettingsStore(SettingsScope.UserSettings);
int toolCount = userSettingsStore.GetInt32("External Tools", "ToolNumKeys");
for (int i = 0; i < toolCount; i++)
{
string tool = userSettingsStore.GetString("External Tools", "ToolCmd" + i);
VsShellUtilities.ShowMessageBox(this, tool, "External Tools", OLEMSGICON.OLEMSGICON_INFO,
OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
}
}
}
}
Sincerely
AWS CodePipeline allows you to invoke a custom Lambda from an action as described here, https://docs.aws.amazon.com/codepipeline/latest/userguide/actions-invoke-lambda-function.htmltion
I am having trouble determining how my C# Lambda function should be defined in order to access the input data from the pipeline.
I tried numerous attempts, was thinking it would be something similar to below. I have also tried to create my own C# classes that the input JSON data would be deserialized to.
public void FunctionHandler( Amazon.CodePipeline.Model.Job
CodePipeline, ILambdaContext context)
I was able to find out a solution. Initially the first step that helped was to change the input parameter for my lambda function to a Stream. I was then able to convert the stream to a string and determine exactly what was being sent to me, e.g
public void FunctionHandler(Stream input, ILambdaContext context)
{
....
}
Then, based on the input data I was able to map it to a C# class that wrapped the AWS SDK Amazon.CodePipeline.Model.Job class. It had to be mapped to the json property "CodePipeline.job". The below code worked, I was able to retrieve all input values.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Amazon.CodePipeline;
using Newtonsoft.Json;
using System.IO;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace lambdaEmptyFunction
{
public class Function
{
public class CodePipelineInput
{
[JsonProperty("CodePipeline.job")]
public Amazon.CodePipeline.Model.Job job { get; set; }
}
public void FunctionHandler(CodePipelineInput input, ILambdaContext context)
{
context.Logger.LogLine(string.Format("data {0} {1} {2}", input.job.AccountId, input.job.Data.InputArtifacts[0].Location.S3Location.BucketName, input.job.Id));
}
}
}
I have written a custom activity which contains a simple ExpressionTextBox:
<sapv:ExpressionTextBox HintText="List of Strings"
Grid.Row ="0" Grid.Column="1" MaxWidth="150" MinWidth="150" Margin="5"
OwnerActivity="{Binding Path=ModelItem}"
Expression="{Binding Path=ModelItem.Test, Mode=TwoWay,
Converter={StaticResource ArgumentToExpressionConverter},
ConverterParameter=In }" />
In the library, i've added Test property as follows:
public InArgument<string> Test { get; set; }
So, this is the whole thing:
A while and a variable i of type i defined in its scope. I would expect to get back "Test1", "Test2" ... and so on, but instead i get :
So, that variable i is seen as a string and not interpreted as the integer defined in the variables section.
I've tried this with a simple property of type string also. Then i thought that InArgument might handle the thing.. i don't know what to do more. Any clues about this?
I might need more of your code posting to bb able to help more, and understand fully what you want to achieve. But from the screen shot I can see that your not accessing the Runtime Arguments in the cache meta data method. Subsequently the console writeline method you are calling is interpreting the raw text value rather than correctly evaluating the expression.
Try the following in your code activity
using System;
using System.ComponentModel;
using System.IO;
using System.Runtime;
using System.Activities.Validation;
using System.Collections.Generic;
using System.Windows.Markup;
using System.Collections.ObjectModel;
using System.Activities;
namespace WorkflowConsoleApplication2
{
public sealed class CodeActivity1 : CodeActivity
{
// Define an activity input argument of type string
[DefaultValue(null)]
public InArgument<string> Test
{
get;
set;
}
protected override void CacheMetadata(CodeActivityMetadata metadata)
{
RuntimeArgument textArgument = new RuntimeArgument("Test", typeof(string), ArgumentDirection.In);
metadata.Bind(this.Test, textArgument);
metadata.SetArgumentsCollection(
new Collection<RuntimeArgument>
{
textArgument,
});
}
// If your activity returns a value, derive from CodeActivity<TResult>
// and return the value from the Execute method.
protected override void Execute(CodeActivityContext context)
{
Console.WriteLine(this.Test.Get(context));
}
}
}
So here's my predicament. I'm writing a custom, one-off content management system, and I can not for the life of me getting this method to work correctly. What I want to do is create a laundry list worth of methods in separate folders and call them as I need them on whichever web forms I want to call them on.
I created a WebApp and created a folder inside of the app called App_Code. Inside of App_Code, there is a public class called "TestimonialService". Here it is:
/******************** TESTIMONIAL SERVICE ****************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BlueTreeSecurity.App_Code.Data;
namespace BlueTreeSecurity.App_Code.Testimonials
{
public class TestimonialService
{
private readonly CMSObjectContext _context;
public TestimonialService(CMSObjectContext context)
{
this._context = context;
}
#region methods
/// <summary>
/// Gets all testimonials
/// </summary>
/// <returns>testimonial collection</returns>
public List<Testimonial> GetAllTestimonials()
{
var query = from t in _context.Testimonials
orderby t.DisplayOrder ascending
select t;
if (query.Count() > 0)
{
var testimonial = query.ToList();
return testimonial;
}
else
{
return null;
}
}
#endregion
}
}
Then on the actual aspx.cs page I call said function like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BlueTreeSecurity.App_Code;
using BlueTreeSecurity.App_Code.Data;
using BlueTreeSecurity.App_Code.Testimonials;
namespace BlueTreeSecurity
{
public partial class Testimonials : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.Page.Title = "Testimonials | ...";
Bind_Data();
}
protected void Bind_Data()
{
/** when i try to use intellisense here it's not recognized. **/
var testimonials = TestimonialService.GetAllTestimonials();
rptTestimonials.DataSource = testimonials;
rptTestimonials.DataBind();
}
}
}
The exact error spat back is this:
Error 1
An object reference is required for the non-static field, method, or property
'BlueTreeSecurity.App_Code.Testimonials.TestimonialService.GetAllTestimonials()'
Anything would be appreciated, guys. I'm ripping my hair out here.
Here's the Project structure
- Blue Tree Security (main project)
- App_Code
+ Data
+ Testimonials
+ TestimonialService.cs
Rest of the .aspx, .aspx.cs, and .ascx files.
If i'm not totally misinterpreting here, the error message you are getting is telling you what the problem is. Make GetAllTestimonials() static or instantiate a TestimonialService instance.
protected void Bind_Data()
{
var testimonialService = new TestimonialService(yourContextObect);
var testimonials = testimonialService.GetAllTestimonials();
rptTestimonials.DataSource = testimonials;
rptTestimonials.DataBind();
}
I've been reading a lot on TDD over the past few months and decided to jump in and try it out with an easy example, I'm just not sure I'm testing for the right things in practice. Here the tests for a custom Data Annotation for validating emails:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MembershipTest.Tests
{
[TestClass]
public class CustomDataAnnotationsTest
{
[TestMethod]
public void CustomDataAnnotations_Email_ReturnTrueIfNull()
{
// Arrange
EmailAttribute attribute = new EmailAttribute();
// Act
bool result = attribute.IsValid(null);
// Assert
Assert.AreEqual(true, result);
}
[TestMethod]
public void CustomDataAnnotations_Email_ReturnFalseIfInvalid()
{
// Arrange
EmailAttribute attribute = new EmailAttribute();
// Act
bool result = attribute.IsValid("()[]\\;:,<>#example.com");
// Assert
Assert.AreEqual(false, result);
}
[TestMethod]
public void CustomDataAnnotations_Email_ReturnTrueIfValid()
{
// Arrange
EmailAttribute attribute = new EmailAttribute();
// Act
bool result = attribute.IsValid("john.smith#example.com");
// Assert
Assert.AreEqual(true, result);
}
}
}
And here is the subsequent code written for the test:
using System;
using System.ComponentModel.DataAnnotations;
using System.Net.Mail;
public class EmailAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
//Let RequiredAttribute validate whether the value is required or not.
if (value == null)
{
return true;
}
//Check to see if System.Net.Mail can send to the address.
try
{
var i = new MailAddress(value.ToString());
}
catch (Exception)
{
return false;
}
return true;
}
}
All tests failed initially and then succeeded after writing the code, but are the tests appropriately written? Too much, or too little? I know this is a very simple example, but I want to make sure I'm on the right track before moving on to more complicated things.
I think you are on the right track. At this point I would suggest some refactoring in your tests. Since you are using
EmailAttribute attribute = new EmailAttribute();
in every test. I would suggest creating TestInitialize() and TestCleanup() methods. The TestInitialize would new EmailAttribute and the TestCleanup would null the object out. This is just a matter of preference. Like this
private EmailAttribute _attribute;
[TestInitialize]
public void TestInitialize()
{
_attribute = new EmailAttribute
}
[TestCleanup]
public void TestCleanup()
{
_attribute = null;
}