public string FirstPersonName
{Get; set; }
public string LocationName
{Get; set; }
public PropertyEvidenceBL()
{
if (FirstPersonName==string.empty)
{
//grab the LocationName in its place. How do I write this.
return LocationName; //does not work
}
query GetPropertyReport contains all person location info.
business class is PropertyEvidenceBL that has all objects/properties
It looks like you have a return statement in the constructor from your posted code. Why?
Try something like this.
Also note you most likely want string.IsNullOrEmpty or string.IsNullOrWhiteSpace as your test. FirstPersonName in your case is likely null and not empty. Two very different things.
public string FirstPersonName { get; set; }
public string LocationName { get; set; }
public string PersonOrLocationName {
get {
return !string.IsNullOrEmpty(FirstPersonName) ? FirstPersonName : LocationName;
}
}
// From your post this looks like the class constructor...
public PropertyEvidenceBL
{
// Do something with the name...
string name = PersonOrLocationName;
}
If you're curious about the ? : syntax, it's shorthand for this:
if(!string.IsNullOrEmpty(FirstPersonName) {
return FirstPersonName
}
else {
return LocationName;
}
What you could do is separate out your logic checking if the FirstPersonName is empty. Obviously with more code in there handle the return from the CheckFirstName method (not sure what you are doing with it).
public PropertyEvidenceBL()
{
CheckFirstName();
}
private string CheckFirstName()
{
if (FirstPersonName == string.empty)
{
return LocationName;
}
else
{
return FirstPersonName
}
}
Related
I have an XML like this:
"<ArrayOfClsLog xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
<ClsLog>
<Subject>sth</Subject>
<Value>123456</Value>
<Comment>val</Comment>
</ClsLog>
</ArrayOfClsLog>"
and with this code I desterilize it:
var tmpSerializer = new XmlSerializer(typeof(ObservableCollection<ClsLog>));
tmpResult = tmpSerializer.Deserialize(tmpReader) as ObservableCollection<ClsLog>;
here is my ClsLog:
public class ClsLog
{
public string Subject { get; set; }
public string Value {get; set;}
public string Comment { get; set; }
}
Everything is fine except:
Big Problem
I want the content of value which can be a number like 123456 converts into 123,456
So I've changed Clslog to :
public class ClsLog
{
public string Subject { get; set; }
public string Value {
get
{
return decimal.Parse(Value.ToString()).ToString("N2", System.Globalization.CultureInfo.InvariantCulture);
}
set
{ }
}
public string Comment { get; set; }
}
But nothing changed, also I've tried to change tmpResult with LINQ:
tmpResult=tmpResult.ToList().ForEach(i => i.Value =
decimal.Parse( i.Value.ToString()).ToString("N2", System.Globalization.CultureInfo.InvariantCulture));
So bad exception happened and turned out I can't change it manually.
Question
How I can fix it? (make value from 123456 to 123.456)
You are declaring this property wrong.
public string Value //why a string why not a decimal?
{
get
{
// you have an infinite recursion here
return decimal.Parse(Value.ToString()).ToString("N2", System.Globalization.CultureInfo.InvariantCulture);
}
set { } // the setter is empty anyway so youcan't set it.
}
Instead try this
private decimal _value; // internal field
public decimal Value
{
get
{
return _value; // return internal field
}
set
{
_value = value / 1000; // set the internal field to the value / 1000
}
}
I need your help. I've got the following situation that I have a method with has to determine some conditions and depending on these conditions, returning an object of a specific type.
Now, I do not want to say public object methodXY() with object as return type but I have the approach which does not seem to work yet.
public T methodXY<T>()
{
if (condition A)
return (T)Convert.ChangeType(myValue, typeof(myType));
else if (condition B)
return (T)Convert.ChangeType(myValue, typeof(myOtherType));
else
throw new exception("xyz")
}
But with this, it seems that I have to set the return type already when calling the method. That's what I don't want and don't can.
//myType looks like this
public class myType
{
public string name;
public string firstname;
public string address;
}
and
//myOtherType looks like
public class myOtherType
{
public string name;
public string firstname;
}
Do you need more or more detailed information? Let me know.
Thanks in advance :-)
EDIT:
Here is the complete code sample of the method with object
public object myMethod(MyDto myDto)
{
userHasRoles = GetUserRoles();
if (userHasRoles .Contains("Admin"))
return (mapper.Map<myType>(myDto));
else if (userHasRoles.Contains("User"))
return (mapper.Map<myOtherType>(myDto));
throw new Exception("No elements!");
}
As far as I understand the problem, you need to return a more complete data when the retriever is the admin, and a not-so-complete one when not.
If that is the objective, then you can retrieve the appropriate data from the database and fill in an object of one of the following classes:
public class PersonData {
public string Name { get; private set; }
public string Surname { get; private set; }
}
public class ExtendedPersonData: PersonData {
public string Name { get; private set; }
public string Surname { get; private set; }
public string Address { get; private set; }
}
Since the latter class inherits from the former, you can just create a List<PersonData> and that will cover both cases.
Another, different approach: the data class takes into account the user in order to return or not certain data:
class Person {
public Person(User usr, string address)
{
this.User = usr;
this.address = address;
}
public string User { get; private set; }
public string Name { get; private set; }
public string Surname { get; private set; }
public string Address {
get {
string toret = "N/A";
if ( this.User.IsAdmin() ) {
toret = this.address;
}
return toret;
}
}
private string address;
}
Neither of both solutions is perfect, and both have their own issues, but the problem, at least how you stated it, cannot be solved.
Hope this helps.
I am total MVC newbie coming from 10 years of webforms. Here is the code I have inherited:
namespace sample.Models
{
public class Pages
{
public int PageID { get; set; }
public string FolderName { get; set; }
}
}
How can I apply a trim function to the "set" portion of this code? Right now it is allowing spaces at the end of foldername and I need to prevent that.
Okay I have incorporated the suggestions however the spaces are still getting saved.
Here are the UI/ vs Database. The UI is trimming properly but the full value with spaces is stored in the table:
You need a backing field:
public class Pages
{
public int PageID { get; set; }
private string _folderName;
public string FolderName
{
get { return _folderName; }
set { _folderName = value.Trim(); }
}
}
In the setter method we use the Trim string's method, which
Removes all leading and trailing white-space characters from the current String object.
For further info regarding this method, please have a look here.
What about this solution:
public class Pages
{
private string _folderName;
public int PageID { get; set; }
public string FolderName
{
get { return _folderName; }
set { _folderName = value?.Trim() ?? string.Empty; }
}
}
You may consider writing a custom extension method to call Trim only if the value of your string is not null:
public static class CustomExtensions
{
public static string TrimIfNotNull(this string value)
{
if (value != null)
{
value = value.Trim();
}
return value;
}
}
And then in your Pages class, something like
private string _folderName;
public string FolderName
{
get { return _folderName.TrimIfNotNull(); }
set { _folderName = value.TrimIfNotNull(); }
}
If you're using C#6, as mentioned by Jacob Krall, you can use the null conditional operator directly and not worry about the extension method:
public string FolderName
{
get { return _folderName; }
set { _folderName = value?.Trim(); }
}
The shorthand syntax for properties is only for when you want to provide a thin layer of abstraction on top of a field. If you want to manipulate the field within the getter or setter, you need to specify the backing field on your own.
namespace sample.Models
{
public class Pages
{
public int PageID { get; set; }
private string folderName;
public string FolderName
{
get { return folderName; }
set { folderName = value.Trim(); }
}
}
}
public class Pages
{
public int PageId { get; set; }
// you need a backing field then you can customize the set and get code
private string folderName;
public string FolderName
{
get { return this.folderName; }
// if the fileName can be set to null you'll want to use ?. or you'll get
// a null reference exception
set { this.folderName = value?.Trim(); }
}
}
See the code below.
//You can filter the entry before saving it into the database.
//About the null issue. You can use this.
if(String.IsNullOrEmpty(txtusername.Text))
{
throw new Exception("Cannot be blank!");
}
//You can filter the entry before saving it into the database
txtpageid.Text = book.PageID.Trim();
txtfoldername.Text = book.FolderName.Trim();
I am having some class like
public class Employee
{
public List<Employee> ChildOrg{get; set;}
public string name {get; set;};
public string id{get; set;};
public string parentid{get; set;};
}
Now in project I am having the object of Employee that contains the actual hierarchy to display in TreeView.
Now to give this object TreeView i need to give IHierarchicalEnumarable type reference.
So how can i convert my Modal to IHierarchicalEnumrable and give it to TreeView?
I already used following link.
http://www.codeproject.com/Articles/19639/Implementing-IHierarchy-Support-Into-Your-Custom-C
In above link i am specially confused about "GetChildern" and "GetParent" method i am unable to understand how it can fit in my requirement where i am already having hierarchy.
I am unable to understand please help me to understand how it works.
Finally found out how I can use IHierarchicalEnumerable.
Please check out following. Modified my model class like this:
public class Employee : IHierarchyData
{
public EmployeeCollection ChildOrg { get; set; }
public string name { get; set; }
public string id { get; set; }
public IHierarchicalEnumerable GetChildren()
{
return ChildOrg as IHierarchicalEnumerable;
}
public System.Web.UI.IHierarchyData GetParent()
{
return null;
}
public bool HasChildren
{
get { return ((this.ChildOrg != null) && (this.ChildOrg.Count > 0)); }
}
public object Item
{
get { return this; }
}
public string Path
{
get { return this.id; }
}
public string Type
{
get { return this.GetType().ToString(); }
}
}
Added new class as follows:
public class EmployeeCollection : List<Employee>, IHierarchicalEnumerable
{
public IHierarchyData GetHierarchyData(object enumeratedItem)
{
return enumeratedItem as IHierarchyData;
}
}
And used recursive function to create hierarchy.
This 'foreach' code will quit working and it appears that it's due to some error. However, no exception is thrown. Is there any good reason? The code INSIDE the loop ( ie where the comment is ) never get reached. The failure is while it's enumerating.
foreach (DeviceOption<int> d in _deviceOptions.Where(d => d.HasChanges))
{
//Call some DAL method
}
In case this is part of the equation, this is the 'DeviceOption' class code:
public class DeviceOption
{
private object _state;
public object State
{
get { return _state; }
set
{
if (_state == value)
{
return;
}
HasChanges = true;
_state = value;
}
}
public bool UserEditable { get; set; }
public DateTime Timestamp { get; set; }
public int UserId { get; set; }
public bool HasChanges { get; set; }
public bool IsNew { get; set; }
public Guid ID { get; set; }
public string DisplayCategory { get; set; }
public string Name { get; set; }
}
public class DeviceOption<T> : DeviceOption where T : IComparable
{
private T _value;
public T Value
{
get { return _value; }
set
{
if (value.CompareTo(_value) == 0) { return; }
HasChanges = true;
OriginalValue = _value;
_value = value;
}
}
public T OriginalValue { get; set; }
}`
UPDATE: I figured this out.
I figured this out. Turns out that an invalid cast was happening and the code was faulting. What's odd is that the exception wasn't being thrown. I know this now because I wrapped the code in a try/catch. The behaviour is acting as if this code is running on seperate thread. Is that how LINQ works?
The reason for the cast is because _deviceOptions is a List and contains derived types such as DeviceOption or or etc. By adding this to the LINQ, things are fine now: '&& d is DeviceOption'
Here is the updated code and how I fixed the invalid cast:
try
{
foreach( DeviceOption<int> d in _deviceOptions.Where( d => d.HasChanges && d is DeviceOption<int>) )
{
//blah blah blah
}
}
catch(Exception ex)
{
//this is how I detected the exception. Don't ask why I didn't think of this before :(
Console.Write( ex.Message );
}
It appears that there are no device options where HasChanges is True. In that case the Where extension method yields an empty enumerable.
Well, given the information you have provided, I have to assume that this query returns an empty enumerable:
_deviceOptions.Where(d => d.HasChanges)
Have you used the debugger at all to see what exactly is happening? Pull the query out of the loop expression and see what it contains.