Concatenating multiple strings with nullables - c#

I Have a messagebox to display some text and data (if existing) within database. The current Issue is trying to show nulls and trying to convert to ShortDate. I've taken two approach but none quite work in the way I need.
The first approach uses Ternary concatenation within the string but it behaves really weird.
DialogResult DuplicateMessage = MessageBox.Show("A contact name " + DuplicateName.Forename + " " + DuplicateName.Surname + " already exists within the System."
+ "\n Existing Client: " + DuplicateName.Forename + " " + DuplicateName.Surname
+ "\n Date of Birth: " + DuplicateName.DOB != null ? Convert.ToDateTime(DuplicateName.DOB).ToString("yyyy-mm-dd") : " ",
,"Possible Duplicate Client", MessageBoxButtons.YesNo);
Currently The message box only shows the line breaks and the Date Of birth. Not even the text "Date of Birth"
If I remove Tertiary and conversion and simply have
DialogResult DuplicateMessage = MessageBox.Show("A contact name " + DuplicateName.Forename + " " + DuplicateName.Surname + " already exists within the System."
+ "\n Existing Client: " + DuplicateName.Forename + " " + DuplicateName.Surname
+ "\n Date of Birth: " + DuplicateName.DOB
,"Possible Duplicate Client", MessageBoxButtons.YesNo);
This works, shows everything. Only issue is that the Date of birth is in the wrong format. Was wondering how do I make it so the date is in short date format and will show everything.
all Properties Of 'DuplicateName' are nullable,

I suspect this is a problem with operator precedence using the conditional operator. It's likely including string concatenations as part of the condition being tested, rather than as part of the result. You can explicitly enclose the elements of that operator with parentheses to identify which strings belong therein and which do not:
"\n Date of Birth: " + (DuplicateName.DOB != null ? Convert.ToDateTime(DuplicateName.DOB).ToString("yyyy-mm-dd") : " ")
Additionally, if DOB is a DateTime? then you can simplify your code a little:
"\n Date of Birth: " + (DuplicateName.DOB.HasValue ? DuplicateName.DOB.Value.ToString("yyyy-mm-dd") : " ")
There's no need to use Convert on Nullable<T> types, you can more easily (and safely) make use of the HasValue and Value properties.

You can fix it by using another pair of parentheses:
(DuplicateName.DOB != null ? Convert.ToDateTime(DuplicateName.DOB))
In your first case, you're concatenating a huge string together (because you don't use any parentheses) and then testing that for null. It's equivalent to this:
var stringToTest = "A contact name " + DuplicateName.Forename + " " + DuplicateName.Surname + " already exists within the System."
+ "\n Existing Client: " + DuplicateName.Forename + " " + DuplicateName.Surname
+ "\n Date of Birth: " + DuplicateName.DOB;
DialogResult DuplicateMessage =
MessageBox.Show(stringToTest != null ? Convert.ToDateTime(DuplicateName.DOB).ToString("yyyy-mm-dd") : " ",
,"Possible Duplicate Client", MessageBoxButtons.YesNo);

Related

ASP.NET MVC Null Calculated Field [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 3 years ago.
I have the following calculated field in Vendor.cs:
public string FullAddress
{
get
{
return VendorAddNum + " " + TLRoadDirection.Direction + " " + VendorAddName + " " + TLRoadType.RdType + " " + TLUnitTypeOne.UnitType + " " + VendorAddUnitOne + " " + TLUnitTypeTwo.UnitType + " " + VendorAddUnitTwo;
}
}
Here's the markup from the view for the field:
#Html.DisplayNameFor(model => model.FullAddress)
When one of my vendors doesn't have any address information, FullAddress is null, which causes me to get a null reference exception. How can I allow FullAddress to be null?
Instead of concatenating all of the values, use string interpolation to better handle null values:
return $"{VendorAddNum} {TLRoadDirection.Direction} {VendorAddName} {TLRoadType.RdType} {TLUnitTypeOne.UnitType} {VendorAddUnitOne} {TLUnitTypeTwo.UnitType} {VendorAddUnitTwo}";
As an added bonus, the performance is a little better and the code is a little cleaner.
If you're using an older version of C#, you can use string.Format similarly:
return string.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}", VendorAddNum, TLRoadDirection.Direction, VendorAddName, TLRoadType.RdType, TLUnitTypeOne.UnitType, VendorAddUnitOne, TLUnitTypeTwo.UnitType, VendorAddUnitTwo);

And/Or XPath query to select some Event Log records

I have googled lots of possible answers with no luck. I am trying to extract the following from the Event Log (pseudo-code):
select events
where
event date/time between FromDateTime and ToDateTime
and
((Level<=2) // error, critical only
or
((Level<=x) and Provider[Name] in a specific list) // any messages for these apps
)
(The second "Level" expression is to allow the user to specify whether to include Informational messages or limit to Warnings and above, so I can't just discard it.)
The following is the (latest) expression I am trying to use - unsucessfully.
string queryString =
"*[System[TimeCreated[#SystemTime>='" + dFrom + "' and #SystemTime<='" + dTo + "']]] " +
" and " +
"(*[System[Level<=2]]" +
" or " +
" ( " +
" *[System[Provider[#Name='<1st name>' or #Name='<2nd name>' or #Name='<3rd name>]] " +
" and " +
"System[Level<=" + maxLevel.ToString() + "]]" +
")" +
");"
Am I trying to make an expression that is too hard for the Event Log query evaluator, or do I just have a simple error in the expression?
I have been trying various forms of the expression. It appears that the "Level" filters are just being ignored, but why?
*** ARRGGHH!! - I think I found it. The Event Log Level enumeration is:
1 - Critical alert
2 - Error
3 - Warning
4 - Informational
5 - Logs at all levels
... and ...
0 - Undefined - indicates logs at all levels
It turns out that some of the "Information" log entries from Microsoft components use Level 0 instead of 4, so these are being picked up by the filter.
My assumption that log entries (especially Microsoft's) would use the appropriate Level was false.
I will need to explicitly look for (Level=1 or Level=2) - Level <= 2 will pick up various Microsoft "Information" log entries.
For anyone interested - the final working query is:
*[System[TimeCreated[#SystemTime>='2018-07-30T17:22:30.000Z'
and #SystemTime<='2018-07-30T20:22:30.000Z']
and (Level=1 or Level=2 or
(Provider[#Name='Application Error' or #Name='Application Hang']
and (Level=1 or Level=2 or Level=3 or Level=4)))]]
There are two issues that I can see in the code that you had posted.
the single quote is not closed on the 3rd name: #Name='<3rd name>]] should be #Name='<3rd name>']]
the second filter for */System/Level should be *[System[Level<=" + maxLevel.ToString() + "]]] "
From your pseudo code and what you have shared, it looks like you could consolidate and move some of your logic inside of the predicate filter for */System and use an XPath such as:
string queryString =
"*[System[TimeCreated[#SystemTime>='" + dFrom + "' and #SystemTime<='" + dTo + "']" +
" and (Level<=2 or " +
" (Provider[#Name='<1st name>' or #Name='<2nd name>' or #Name='<3rd name>'] " +
" and Level<=" + maxLevel.ToString() + "))" +
"]];"

How to pass a variable to another ASP.net page

Okay so I have some c# that generated href anchor tags styled as list items and throws it onto an aspx page like so;
html += "<a href='../InspectionView.aspx' class='list-group-item' id=''>Inspection ID: " + inspectionID + " - Due Date: " + inspDueDate + " - Inspector(s): Bob Williams <span style='min-width:75px' class='label label-primary pull-right'>" + status + "</span></a>";
Now this is in a loop, the variables are pulled from a SQL database and used to populate that html string.
Now, what I'm trying to do is have it so when the user clicks on one of the generated hrefs, and is redirected to the next page, the variable inspectionID is passed forward. I thought there might be someway of storing it in the ID of the href tag but I dont know where to go from there.
Thanks a lot.
Add a query string parameter.
html += "<a href='../InspectionView.aspx?inspectionID='" + inspectionID + " class='list-group-item' id=''>Inspection ID: " + inspectionID + " - Due Date: " + inspDueDate + " - Inspector(s): Bob Williams <span style='min-width:75px' class='label label-primary pull-right'>" + status + "</span></a>";
For reading on the receiving page:
string inspectionID = Request.QueryString["inspectionID"];
See
https://msdn.microsoft.com/en-us/library/system.web.httprequest.querystring(v=vs.110).aspx
a very simple way is to stick into a query string. Since this isn't a server control it might be the only way to it.
something like...
html += "<a href='../InspectionView.aspx?InspectionID="+HttpUtility.UrlEncode(Inspection_ID.ToString())+"&anyotherQSField="+HttpUtility.UrlEncode(anyotherQSFieldVariable) + "' class='list-group-item'> - Due Date: " + inspDueDate + " - Inspector(s): Bob Williams <span style='min-width:75px' class='label label-primary pull-right'>" + status + "</span></a>";
Then in InspectionView.aspx,get values with something like:
String strInspection_ID = Request.QueryString["InspectionID"];
You likely need to convert to string for this to work for the ID.
You dont have to use HttpUtility.UrlEncode for Inspection_ID but if you have other strings you want to use in QS that might contain spaces or other odd characters - it would be wise.

Better way to give space other than

I am using the following code to give blank space so that the three elements "label, then dropdown and then a button for action on dropdown" are right aligned in a panel in a web page.
Now, I know I can do with padding/margin, however, it all works only with respect to the element at right side and not from the right hand side of the browser.
However, I was talented enough to achieve what I want using but I find it weird to write the code this way:
LiteralSpecial.Text = " " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
"Select page ";
Is there are way to refine this please, folks?
Have you tried using CSS?
<div style="text-align:right">Select page</div>
See it in action: http://jsfiddle.net/vhxchyrj/2/
<div style="width:600px;padding-left:550px;">Select page</div>

Textbox not showing output in MVC [duplicate]

This question already has answers here:
How to display the text in MVC?
(4 answers)
Closed 8 years ago.
I want to show a output in textbox in MVC. But its not displaying anything. I used the following code and i attached screenshot below:
#Html.TextAreaFor(up => up.CompileOutput)
foreach (CompilerError CompErr in results.Errors)
{
userProgram.CompileOutput = "Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
return View(userProgram);
The first image shows that the output is binded with that particular textbox. But in browser (image 2) shows nothing in the textbox (red colour)
I am even wondering why you did not got an exception. return view(string) will look for a view with the string parameter as name, it will not show the text.
I would suggest you use ViewBag instead. So you set your error text in a property you name as follow:
foreach (CompilerError CompErr in results.Errors)
{
userProgram.CompileOutput = "Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
ViewBag.ErrorText = userProgram.CompileOutput;
You can later on retrieve the value by simply calling ViewBag.ErrorText from you Razor view
Why not try doing it another way?
#Html.TextArea("CompileOutput", userProgram.CompileOutput)

Categories

Resources