Make a global variable from var [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
In a C# method I Had:
var followers = user.GetFollowers(250);
var friends = user.GetFriends(250);
var favorites = user.GetFavorites(40);
How can I make these variables accessible to other methods, within my Windows Form App?
I have tried:
private string followers = user.GetFollowers(250);
private string friends = user.GetFriends(250);
private string favorites = user.GetFavorites(40);
And:
private followers = user.GetFollowers(250);
private friends = user.GetFriends(250);
private favorites = user.GetFavorites(40);
I have tried putting the above examples, right at the top of my code, but this does not work. What could I be doing wrong. I'm new to programming.

It all depends on what the return type of the user.GetFollowers(int i) is.
And in what context is user defined?
You seem to be a bit confused about the basics of C#.
private is simply specifying that you cannot access your member outside the context of your class. It is not a data-type.
See this question for more info about access-modifiers as they are called
What is the difference between Public, Private, Protected, and Nothing?
The keyword var is just compliler-magic, and cannot be used for properties or other members of a class.
To implement a member of class (be it a field, property or method) you must know the return-type.
In your case; the easiest way to get it is just to see what user.GetFollowers(int i) returns, the fastest way to do this is to simply browse to it by putting your cursor on it and go to it by pressing the F12 key in visual studio.
You have tagged your question with tweetinvi so I'm going to assume this has something to do with twitter.
For this example, i will just call the unknown types FriendCollection, FollowerCollection and FavoriteCollection. Since "GetFriends" seems to suggest that it will return some sort of collection.
public class TwitterUserInfo
{
public FriendCollection Friends { get; get; }
public FollowerCollection Followers { get; set; }
public FavoriteCollection Favorites { get; set; }
public TwitterUserInfo(TwitterUser user)
{
Friends = user.GetFriends(20);
Followers = user.GetFollowers(20);
Favorites = user.GetFavorites(20);
}
}
You can then use it as such:
TwitterUserInfo userInfo = new TwitterUserInfo(someTwitterUser);
And the "userInfo" will then contain the properties you want. for example userInfo.Friends will contain the friends.
Since you have not provided much information about what is going on, i cannot give a more elaborate answer.
EDIT: Cleared up a few things

Related

.NET MVC var in controller is returning incorrect results [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
What the heck am I missing here. I'm having an issue adding variables to a MVC Model:
var clientnumber returns the correct value (ex. 123)
var companyname returns the correct value (ex. foo)
var blah returns "System.Web.Mvc.ContentResult" for both the clientnumber
and companyname
CONTROLLER:
var clientnumber = GetClientNumber().ToString();
var companyname = GetCompanyName().ToString();
var blah = new UserExperience { client_number = clientnumber, us_name =
companyname };
MYSQL.UserExperiences.Add(blah);
MYSQL.SaveChanges();
MODEL:
`public partial class UserExperience
{
public int ID { get; set; }
public string client_number { get; set; }
public string us_name { get; set; }
}`
Your methods GetClientNumber and GetCompanyName aren't returning what you think they're returning. Your biggest clue to this is the use of .ToString(). After all, if (as you assume) they are returning string values then why would you need to call .ToString() on them?
They're returning System.Web.Mvc.ContentResult objects. And the default string representation of an object is its class name.
We can't see those methods or anything about them, but it seems like they're not the methods you want to use here. They're likely controller actions. You don't want a ContentResult, you want a string value. Instead of calling other MVC controller actions, invoke whatever logic you need to get the value that those actions are also getting.

Handling extra data to store for each model attribute [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am working on an application where I want the user to be able to enter notes associated to any input field. For example, a user may type in a value for a field named Price, and add a note next to it to specify that it is negotiable under certain conditions.
The solutions I have considered are:
Creating two attributes for each field (e.g. Price and PriceNote)
Creating a new class (e.g. Field) containing a Value and a Note, then changing all model properties to that Field type.
There are downsides to both of these solutions, though. Creating additional attributes would bloat the code and make modifications awkward, while creating an extra class would require typecasting field values constantly and handling editors/displays manually in the views.
Is there a better, more elegant solution?
Not sure what the backend looks like, but you could create a object that looks like this:
{ProductId: 123,
ProductName:'Widget',
Price:200.00,
minQuantity: 10,
Comments:[
Price: "can be reduced blah blah",
minQuantity: "N/A on orders > 1000"
]
}
This way - you can access price/minQuantity the same way you always would, and Comments are stored in a simple string/string dictionary.
You could also cache those comments in a totally different call ... So you pull them separately from the actual object definition.
Data Storage
Again, depending on your db, you could store comments as json in a text field, or you could store them normalized in a table that has ObjectType,EntityId,FieldName,Comment in it. Up to you, but I'm guessing you don't need them in "every" table -- just occasionally want to add label/comments to fields.
Let me know the middle tier (eg - c#) and maybe we can turn that json into an actual class in your middle tier.
public interface IProduct {
string ProductId {get; set; }
string ProductName {get; set; }
Double Price {get; set; }
int minQuantity {get; set; }
Dictionary<string,string> Comments {get; set; }
}
As a simple example.
Finally, in Angular/Controller
For the front end, you could create a simple property that returns the correct comment:
HTML:
<input ng-model="Price" /><p>{{getComments("Price")}}</p>
Controller:
$scope.getComments = function(fieldNm) {
if($scope.product==undefined
|| $scope.product.Comments.length==0) {
|| $scope.product.Comments.hasOwnProperty(fieldNm)==false) {
return '';
}
return $scope.product.Comments[fieldNm];
}
Or, you could create a directive to accomplish the same thing universally (so you don't have to repeat code in several controllers.
You could try a class structure like this
public class Field
{
private string Value;
private string Comment;
}
public class ViewModel
{
private Field Price { get; set; }
private Field SomeOtherFiled { get; set; }
}
One downside will be to access the value you'll have to do Price.Value or for comment Price.Comment (but it makes sense logically anyway)
The best solution I found is to create a Dictionary<string, string> in the model to store notes, with keys set using nameof(MyAttribute). Notes will have to be retrieved with TryGetValue(), but it is less awkward than constantly typecasting or duplicating fields, and it is easily accessible from views.
Model:
public virtual IDictionary<string, string> Notes { get; set; }
View:
#Html.EditorFor(model => model.Notes[nameof(model.MyAttribute)], new { htmlAttributes = new { #class = "form-control" } })
If I need to manipulate the note:
string myNote;
if (MyModel.Notes.TryGetValue(nameof(MyModel.MyAttribute), out myNote))
{
// Do something with the note
}
else
{
// There is no note for the given attribute
}

Best way to store user's input in a multi-step application [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
My program consists of a number of steps. Say each step is in a tabpage on which upon completion, the user selects "Next".
What is the best/fastest way of storing these information?
I would generally say that this would be one Model to keep all the data - which then gets forwarded to the processing method once the user says "ok" at the last page. BUt then this depends a lot on actual usage scenarios, so that may not be the best way all the time.
I created a separate class that had properties for the 'answers' on the individual pages. Not sure if this is the best way to do it, but it worked perfectly for me. The user could go back and forth between the pages and the answers were stored. To Prescott's point, if they need to come back later perhaps you could save their partial form out as XML.
Create a viewmodel that represents the wizard, and in that viewmodel all the data related to your steps. You can also keep track of current step, and implement some methods to enable/disable next and previous buttons etc.
Your actual wizard window and tabs (the views) then all work with the wizard viewmodel (the data).
I would go with In-Memory Repository if you just want to retain this information for program execution, For example
namespace Repository {
public class InMemoryRepository : IRepository{
static readonly List<Item> items = new List<Item> {
new Item("CurrentTaxRate", 20m),
new Item("CurrentAmount", 100m)
};
public Item Get(string name) {
return items.Single(x => x.Name == name);
}
}
}
public class Item {
public Item(string name, decimal value) {
Name = name;
Value = value;
}
public string Name { get; private set; }
public decimal Value { get; private set; }
}
You can bolt on Add, Delete or Edit functionality easily to this and replace the "Item" here with your own "UserData" type.
Use dependency injection for getting this information back
public class TaxRate : ITaxRate {
private readonly IRepository repository;
public TaxRate(IRepository repository) {
this.repository = repository;
}
public decimal Get() {
var item = repository.Get("CurrentTaxRate");
return item.Value;
}
}

get model from List of a model [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Is there a way to get the specific items from the list of a model without using a foreach of the list? like if you return a List<model> holding a model with a few differnt items to specifically call those item.
If you want a list of a specific item that's within your list then you can use LINQ to return those items, for example:
var customerNames = customersList.Select(customer => customer.Name);
This would give you a string collection with all of your customer names equal to the amount that was in your original list.
Or if you would like to retrieve a number of different items from your model list then you may want to look into creating a class specifically for stripping out those items, for example:
public class CustomerContactDetails
{
public string Address { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
}
...
var contactDetails = customersList.Select(customer => new CustomerContactDetails { Address = customer.Address, Email = customer.Email, Telephone = customer.Telephone });
You can use C# LambdaExpression, like this:
var yourModel = modelList.Where(x => x.Id = 12).Select(x).First();

Am I taking value objects too far (DDD) [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
EDIT:
For clarity, this question is related to DDD, which has a concept called Value Objects, these are not Value Types, they are a way of building objects in such a way that the contents make up the identity, I was trying to understand how far these concepts should apply (From Comments it seems they should not seep outside domain). This question may look odd for people not familiar with DDD but to be clear it is about a very specific mechanism for creating objects NOT creating value types.
Consider the following sample code, which has two Value Objects:
public class SqlServerConnectionSettings
{
public string DatabaseName { get; set; }
public string ServerName { get; set; }
public SqlServerCredentials Credentials { get; private set; }
public SqlServerConnectionSettings(SqlServerCredentials credentials)
{
Credentials = credentials;
}
public string AsConnectionString()
{
//Snip
}
}
public class SqlServerCredentials
{
public string Username { get; private set; }
public string Password { get; private set; }
public bool UseIntegratedSecurity { get; private set; }
public SqlServerCredentials(string username = "", string password = "", bool useIntegratedSecurity = true)
{
Username = username;
Password = password;
UseIntegratedSecurity = useIntegratedSecurity;
}
public string AsConnectionStringCredentials()
{
//Snip
}
}
Rather than have distinct params for Username, Password, UseIntegratedSecurity I have created a value object to hold them. My question is, Is this taking the concept too far, have I misunderstood the point value objects have been designed for?
Looks good to me. You group items which belong together into cohesive units, what could be wrong about that?
It depends on your context.
If you define SqlServerCredentials as an Entity, yes, you're going too far :
"An entity is an object that is not defined by its attributes, but rather by a thread of continuity and its identity."
If you define SqlServerCredentials as a Value Object, you're right (don't forget that it should be immutable !):
"A value object is an object that contains attributes but has no conceptual identity. They should be treated as immutable."
If you define SqlServerCredentials as an Aggregate, you're right, too :
A n aggregate is a collection of objects that are bound together by a root entity, otherwise known as an aggregate root. The aggregate root guarantees the consistency of changes being made within the aggregate by forbidding external objects from holding references to its members.
In conclusion, in a DDD way, if you're not considering SqlServerCredentials as an entity, it's ok. But it's all about context.

Categories

Resources