C# != operator won't work properly - c#

When this runs:
if (Title != "") {
Server.s.Log("title found: " + Title);
if (TitleColor != "") {
NameTitle = "[" + TitleColor + Title + NameColor + "]";
} else {
NameTitle = "[" + Title + "]";
}
} else {
NameTitle = "";
}
It thinks that the title has a value, when in fact, the title is most definitely just "", help me please?

You may be confusing an empty string with a null value. Try this:
if (!string.IsNullOrEmpty(Title))
or this:
if (!string.IsNullOrWhitespace(Title))
depending on your needs.

Are you sure it is an empty string and not null? Those are different. If it could be either, you can use String.IsNullOrEmpty().

I believe Title is string.
Try..
if(!string.IsNullOrEmpty(Title))

Use: String.IsNullOrEmpty(yourString))

Related

Query is not returning results in MS Access with C#?

So I have a relatively simple query, but it is not matching the full_name text field even though I can see the data is there and is an exact match?
I made sure to checkk the fullName parameter being passed in is the correct value. I couldn't find any documentation verifying if I needed the single quotes or not, but without it an error was thrown.
Anyone have any suggestions?
Code in question with the SQL statement?
public static ObservableCollection<ShiftView> GetShifts(DateTime? start, DateTime? stop, string fullName, bool? closed)
{
ObservableCollection<ShiftView> shifts = new ObservableCollection<ShiftView>();
// INFO: Not intended to retrieve a lot of records as there is no caching....
OleDbCommand cmd = new OleDbCommand("SELECT profiles.profile_id, profiles.full_name, shifts.start, shifts.stop, shifts.start_log, shifts.stop_log, shifts.start_notes, shifts.stop_notes FROM shifts, profiles WHERE " +
(start.HasValue ? "(shifts.start>=#start) AND " : "") +
(stop.HasValue ? "(shifts.stop<=#stop) AND " : "") +
(fullName != null ? "profile.full_name='#full_name' AND " : "") +
(closed.HasValue ? "shifts.closed=#closed AND " : "") +
"(shifts.profile_id=profiles.profile_id)"
);
if (start.HasValue)
cmd.Parameters.AddWithValue("#start", start.Value.ToString());
if (stop.HasValue)
cmd.Parameters.AddWithValue("#stop", stop.Value.ToString());
if (fullName != null)
cmd.Parameters.AddWithValue("#full_name", fullName);
if (closed.HasValue)
cmd.Parameters.AddWithValue("#closed", closed);
OleDbDataReader reader = Database.Read(cmd);
DateTime? _stop, _stopLog;
while(reader.Read())
{
Console.WriteLine("!");
// shorthand form if's with ? does not work here.
if (reader.IsDBNull(reader.GetOrdinal("stop")))
_stop = null;
else
_stop = reader.GetDateTime(reader.GetOrdinal("stop"));
if (reader.IsDBNull(reader.GetOrdinal("stop_log")))
_stopLog = null;
else
_stopLog = reader.GetDateTime(reader.GetOrdinal("stop_log"));
shifts.Add(new ShiftView(
reader.GetString(reader.GetOrdinal("profile_id")),
reader.GetString(reader.GetOrdinal("full_name")),
reader.GetDateTime(reader.GetOrdinal("start")),
_stop,
reader.GetDateTime(reader.GetOrdinal("start_log")),
_stopLog,
reader.GetString(reader.GetOrdinal("start_notes")),
reader.GetString(reader.GetOrdinal("stop_notes"))
));
}
return shifts;
}
The above code gets called from this button press:
private void ShowStatsButton_Click(object sender, RoutedEventArgs e)
{
DateTime? start = StartDatePicker.SelectedDate;
DateTime? stop = StopDatePicker.SelectedDate;
string name = NameComboBox.Text;
if (name.Equals("Everyone"))
name = null;
if (stop.HasValue)
stop = stop.Value.AddDays(1);
StatsGridView.ItemsSource = Shift.GetShifts(start, stop, name, true);
}
This filters the date range and if there is a full name. I ensure there is a valid value for name.
I think that the problem is in here, you need to remove '' from full_name line:
OleDbCommand cmd = new OleDbCommand("SELECT profiles.profile_id, profiles.full_name, shifts.start, shifts.stop, shifts.start_log, shifts.stop_log, shifts.start_notes, shifts.stop_notes FROM shifts, profiles WHERE " +
(start.HasValue ? "(shifts.start>=#start) AND " : "") +
(stop.HasValue ? "(shifts.stop<=#stop) AND " : "") +
(fullName != null ? "profile.full_name='#full_name' AND " : "") + <-- remove '' from '#full_name'
(closed.HasValue ? "shifts.closed=#closed AND " : "") +
"(shifts.profile_id=profiles.profile_id)"
);
and do this:
OleDbCommand cmd = new OleDbCommand("SELECT profiles.profile_id, profiles.full_name, shifts.start, shifts.stop, shifts.start_log, shifts.stop_log, shifts.start_notes, shifts.stop_notes FROM shifts, profiles WHERE " +
(start.HasValue ? "(shifts.start>=#start) AND " : "") +
(stop.HasValue ? "(shifts.stop<=#stop) AND " : "") +
(fullName != null ? "profile.full_name=#full_name AND " : "") +
(closed.HasValue ? "shifts.closed=#closed AND " : "") +
"(shifts.profile_id=profiles.profile_id)"
);
I hope this help
It turns out that adding in the table name was the cause of the problem. Why this is the case, is uncertain and I will follow up with another question specific to that.
So the solution I eventually went with to change the following:
OleDbCommand cmd = new OleDbCommand("SELECT profiles.profile_id, profiles.full_name, shifts.start, shifts.stop, shifts.start_log, shifts.stop_log, shifts.start_notes, shifts.stop_notes FROM shifts, profiles WHERE " +
(start.HasValue ? "(shifts.start>=#start) AND " : "") +
(stop.HasValue ? "(shifts.stop<=#stop) AND " : "") +
(fullName != null ? "profile.full_name='#full_name' AND " : "") + // this is where the problem is
(closed.HasValue ? "shifts.closed=#closed AND " : "") +
"(shifts.profile_id=profiles.profile_id)"
);
and change it to:
(fullName != null ? "full_name=#full_name AND " : "") + // Notice I removed the table name and just straight referenced the field.
EDIT:
I updated the above correct line to remove single quotes, that I accidentally left in copy and pasting (numero uno coding mistake!).
I also discovered why I kept getting an error staring at it for hours. Turns out, the table is called "profiles", not "profile" and therefore when I removed the table name it worked!
So an alternative solution is:
(fullName != null ? "profiles.full_name=#full_name AND " : "")
Silly, I know. Feel stupid now.

if-statement inside function

I have this piece of code:
public static void Debug(string workName, string message, string logcontext, string exMessage = "")
{
LogEventInfo logEvent = new LogEventInfo(LogLevel.Debug, logcontext, message + ": " + exMessage);
...
}
As you can see, the last parameter of the Debug method is optional (string exMessage = ""). That means that if I run this code as-is it will look fine if a exMessage arrived: "...message: exMessage"
However, If a exMessage wasn't provided, it will look like this: "...message: " (Note the trailing :).
Of course, this can easily be solved by using something like this:
if(!String.IsNullOrEmpty(exMessage)
{
...(...,message + ": " + exMessage);
}
else
{
...(...,message);
}
I want a more beautiful approach. Like if there is something in the lines of:
...(...(!exMessage -> ,message | else -> ,message + ": " + exMessage));
Is there some way of doing this in-line if-statement in C#? Can I use lambdas some how? (I'm super-new to the whole concept of lambdas)
LogEventInfo logEvent = new LogEventInfo(LogLevel.Debug, logcontext, message + (!string.IsNullOrEmpty(exMessage) ? ": " : string.Empty) + exMessage);
You can use the conditional operator
exMessage == "" ? message : message + ": " + exMessage
There is its called the ?: operator. You use it like this:
var logText = string.IsNullOrEmpty(exMessage) ? message : message + ": " + exMessage;

c# null string?

I had the following:
string Name = name.First + " " + name.Last;
This returns Tom Jones just fine.
In case name.First may be null or name.Last may be null, I have the following:
string SpeakerName = name.First ?? string.Empty + " " + name.Last ?? string.Empty;
What is strange is that it only returns Tom. Why is this and how can I fix it such that if null it defaults to empty string for either first or last name?
Because of the relative precedence of the ?? and + operators. Try this:
string SpeakerName = (name.First ?? "") + " " + (name.Last ?? "");
Your original example is evaluating as if it was:
string SpeakerName = name.First ?? ("" + " " + (name.Last ?? ""));
Also, read Jon's answer here: What is the operator precedence of C# null-coalescing (??) operator?
As he suggests there, this should work as well:
string SpeakerName = name.First + " " + name.Last;
Because that compiles to #L.B.'s answer below, minus the trim:
string SpeakerName = String.Format("{0} {1}", name.First, name.Last)
EDIT:
You also asked that first and last both == null makes the result an empty string. Generally, this is solved by calling .Trim() on the result, but that isn't exactly equivalent. For instance, you may for some reason want leading or trailing spaces if the names are not null, e.g. " Fred" + "Astair " => " Fred Astair ". We all assumed that you would want to trim these out. If you don't, then I'd suggest using a conditional:
string SpeakerName = name.First + " " + name.Last;
SpeakerName = SpeakerName == " " ? String.Empty : SpeakerName;
If you never want the leading or trailing spaces, just add a .Trim() as #L.B. did
string SpeakerName = String.Format("{0} {1}", name.First, name.Last).Trim();
string SpeakerName = name.First != null && name.Last != null
? string.Format("{0} {1}", name.First, name.Last)
: string.Empty;
string fullName = (name.First + " " + name.Last).Trim();
This works for either or both being null and will not return a string with leading, trailing, or only spaces.

c# why wont this display to label

I want to be able to display balance to label and my code is not working. This is code I got so far:
SqlDataReader readdata;
{
sqlCommandbalance.Connection.Open();
sqlCommandbalance.Parameters["#accountID"].Value = show.accoundID;
readdata = sqlCommandbalance.ExecuteReader();
string balanceDB = null;
while (readdata.Read())
{
balanceDB = readdata["balance"].ToString();
}
sqlCommandbalance.Connection.Close();
balanceShow.Text += " " + balanceDB.ToString();
}
On this line - balanceShow.Text += " " + balanceDB.ToString(); got a error saying Object reference not set to an instance of an object.
You're calling balanceDB.ToString(), when balanceDB will be null if the data reader contains no rows.
Note that balanceDB.ToString() is redundant, since balanceDB is already a string. Just take out the ToString call.
You could also initialize balanceDB as
string balanceDB = "";
Originally you set balanceDB = null;.
If no data was found, then no assignment will be made to balanceDB in the while loop, so it stays undefined.
It's because of string balanceDB = null;
Set that to string balanceDB = string.Empty; and you should be OK
Readdata.read probably returned false, making the while to never run. Thus balanceDB is still null.
Looks like your query is returning an empty set. You should check for that before you set the balanceShow.Text:
if (balanceDB != null) {
balanceShow.Text += " " + balanceDB.ToString();
} else {
// tell the user that id: show.accoundID has no balance
}
Probably your code is returing null in dataRader and consequentily you're tanking an null value on balanceDB. I recomend you do something like this:
public static string GetBalance() {
string result = string.Emtpy;
using (var connection = /* Build your SqlConnection */) {
using (var cmd = new SqlCommand("your select command here", connection) {
try
{
connection.Open();
// you don't need a reader to take just a single value
object value = cmd.ExecuteScalar();
if (value != null)
result = value.ToString();
}
catch(Exception ex)
{
/* you've got an error */
}
finally
{
connection.Close();
}
}
}
return result;
}
and in your page:
string balance = GetBalance();
if (!string.IsNullOrEmpty(balance))
balanceShow.Text += string.Contat(" ", balance);
if you wish to concat the balanceShow label, use '+=' operator, instead of this you just '='.
PS: Sorry for my english!

error: The query results cannot be enumerated more than once

Edit:
DataClassesDataContext dc = new DataClassesDataContext();
string _idCompany = Request["idCompany"];
var newes = dc.GetNewsCompany(Int64.Parse(_idCompany));
string date = "";
string newsHtml = "<center>";
if(newes.GetEnumerator().MoveNext()){
foreach (var item in newes)//say Error .......................
{
// date = calendar.GetDayOfMonth(item.DateSend) + "/" + calendar.GetMonth(item.DateSend) + "/" + calendar.GetYear(item.DateSend).ToString();
// newsHtml += "<li class='news-item'><a style='text-decoration:none' class=\"link\" onclick=\"$(\'#BodyNews\').text(\'" + HttpUtility.HtmlEncode(item.Body).Trim() + "\');$(\'#BodyNews\').dialog({resizable:false});\" href=\"#\" > " + item.Title.ToString() + "</a> " + date + " </li>";
}
newsHtml += "</center>";
}
else
{
// var propertyCompany = dc.GetPropertyCompanyById(Int64.Parse(_idCompany));
// newsHtml += "<li class='news-item'><a style='text-decoration:none' class=\"link\" );$(\'#BodyNews\').dialog({resizable:false});\" href=\"#\" > " + "!به صفحه شخصی شرکت " + propertyCompany.FirstOrDefault().NameCompany + " خوش آمدید " + "</a> " + date + " </li>";
}
return newsHtml;
say error:The query results cannot be enumerated more than once
how check var is empty or null with out enumerated;
Why bother with the if at all?
var newes = dc.GetNewsCompany(Int64.Parse(_idCompany));
//if (newes.GetEnumerator().MoveNext())//check is null or empty
var newesList = newes.ToList();
if (neweList.Count > 0)
{
...
}
You can always check the newesList.Count property afterward.
Not sure what's available as a member in newes, but if it's an object and depending on what dc.GetNewsCompany returns you could check for null
if (news == null) return;
or if it returns an empty collection/array, just check the count/length:
if (news.Count == 0) return;
if (news.Length == 0) return;
the error comes, because you are using .GetEnumerator() on newes and then using the newes again in a foreach Loop .. this causes the "double enumeration".
Generally avoid walking "such var"'s with a foreach, since the DataReader is locked the whole loop !. Means that you cannot use the same entitie in this loop.
Better .ToList() , you can the list.AsQuearable agian if you want to Linq on it
f.e. something like
var newes = dc.CompanyTable.Where(ln => ln.id.Equals(_idCompany));;
List<CompanyTable> newesList = newes.ToList();

Categories