I was hoping to get some insight on the error that are produced by the system. I am using a already built message system that I got some time ago and it works but sometimes on the forms I will get errors that I do not understand. For instance on a Create I have a try / catch block that produces a message if it has successfully Executed. I have tried to search for these errors in my project and it does not come up with anything. Even if it was in meta data a search should find it.
I use System.Text.StringBuilder sb = new System.Text.StringBuilder(); for the message and the code looks like this:
public ActionResult Create(Vendors model)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
try
{
if (ModelState.IsValid)
{
var userId = User.Identity.GetUserId();
//var getdata = ExtendedViewModels.VendorToEntity(model);
model.VendorId = Guid.NewGuid();
model.CreatedDate = System.DateTime.Now;
model.CreatedBy = User.Identity.Name;
model.Status = true;
db.Vendors.Add(model);
db.SaveChanges();
sb.Append("Submitted");
return Content(sb.ToString());
}
else
{
foreach (var key in this.ViewData.ModelState.Keys)
{
foreach (var err in this.ViewData.ModelState[key].Errors)
{
sb.Append(err.ErrorMessage + "<br/>");
}
}
}
}
catch (Exception ex)
{
sb.Append("Error :" + ex.Message);
}
return Content(sb.ToString());
}
When this returns or closes the Modal it produces a message or if there is an error it will produce that so you can fix it like a Required field. If everything is okay it will produce from this:
#Html.StarkAjaxFormSubmiter("frmVendors", "tbVendors", true, "Action Successfully Executed")
This is a green box that shows up as "Action Successfully Executed". If something is wrong a red box shows up and you get a message. In my case I am getting a red box that says Submitted Read Warnings Alerts This is how it is spelled. I doubt this is a error that comes from ASP.Net it looks more like a custom message, I dont know what it means and I cannot find it anywhere. Regardless, it does create the record in the db. The other error I have gotten shows Something is went wrong [object, object] Not only do I want to find out what these mean, I also want to clean them up and give a proper message that makes sense. Does anyone have any ideas as to how to correct this? Could they be encypted in the custom package that was written for this? That is why I cannot find them. I have also viewed the package and did not find anything for this.
This is from Meta data:
//
// Parameters:
// stark:
//
// FormId:
// Enter Here Form ID LIKE So you have to pass = frmCreate
//
// DataTableId:
// Which DataTable You have update after submit provide that ID
//
// IsCloseAfterSubmit:
// Do you want to opened popup close after submit , So pass=true or false any
//
// SuccessMessage:
// Give any Success message
public static MvcHtmlString StarkAjaxFormSubmiter(this HtmlHelper stark, string FormId, string DataTableId, bool IsCloseAfterSubmit, string SuccessMessage);
//
// Parameters:
// stark:
//
// FormId:
// Enter Here Form ID LIKE So you have to pass = frmCreate
//
// DataTableId:
// Which DataTable You have update after submit provide that ID
//
// IsCloseAfterSubmit:
// Do you want to opened popup close after submit , So pass=true or false any
//
// SuccessMessage:
// Give any Success message
//
// AfterSuccessCode:
// Add other JQuery code if you want
public static MvcHtmlString StarkAjaxFormSubmiter(this HtmlHelper stark, string FormId, string DataTableId, bool IsCloseAfterSubmit, string SuccessMessage, string AfterSuccessCode);
Thanks for our help
UPDATE:
I did some searching on the web and found a program called JetBrains dotPeek. I decompiled the dll and sure enough the messages are in there. So I should be able to change them and recompile it and add if I want, to it.
I was not able to edit the decompiled dll. So I decided to just create a class in the main project and copy the the code to that class. Changing what I needed. Where my trouble was, was with misspellings. The dll used Sumitted as the sb.Append("Sumitted") I changed that in the controller to be Submitted. So the dll did not find "Sumitted" in the action, and in the dll class there is an If statement that faults to error if not found - which was listed as Read Warnings Error. I changed that and fixed all the misspellings. I also got rid of the Something is went wrong and changed it to something more meaningful. I will continue to add to this to give more meaningful messages. It helps to know what the error is, instead of [object], [object]. I dont know if this will help others, maybe if they have downloaded the same code I have and have issues.
I have a C# class with a field and a property that looks like this.
public static class Config {
// ...
private static string admin_email;
public static string AdminEmail {
get {
if (admin_email == null) {
admin_email = config_xml.Element("admin_email").Value;
// ^ The exception is thrown here.
}
return admin_email;
}
}
}
In the above code, config_xml is an XElement which contains a child element that looks like
<admin_email>myemail#example.com</admin_email>
However, when I try to access this property, I get a NullReferenceException even though the debugger shows that nothing is null.
I checked the debugger, and watching config_xml.Element("admin_email").Value shows the email, as expected.
The weird part is that when I put a breakpoint on that line and step in one step at a time there is no exception thrown.
I have tried with and without enabling the option Just My Code.
In case this helps, I try to access the property on a line like this (from a different project)
message.From = new MailAddress(Config.AdminEmail);
Edit
After changing the code to this, I realised that c was still null.
get {
if (admin_email == null) {
XElement c = config_xml;
XElement e = c.Element("admin_email");
// ^ Exception is now thrown here
string v = e.Value;
admin_email = v;
}
return admin_email;
}
Thank you David, asawyer, and Lasse V. Karlsen for helping me realise my mistake. I changed my code to this, and now it works.
admin_email = new Email(ConfigXml.Element("admin_email").Value;
I was using a similar technique for config_xml and ConfigXml, so I would only load the XML into the field config_xml if it was ever needed, and I forgot to access it with the property ConfigXml (which did the loading) instead of the field config_xml (which was null until I used the property).
I don't know why it was working with a breakpoint, maybe when I watched the property it assigned it? I don't know.
I tried to recreate a code (that I've seen in a video) in Visual Studio 2013 (c#) that was written in VS2008 (c#):
I've tried both EF 6 and EF 5 version options same result..searched web and MSDN with no luck.
Here is my code with comments showing the errors I got:
private CoffeeShopDBEntities cse = new CoffeeShopDBEntities();
private void AddProductsToTabbedPanel()
{
// using (CoffeeShopDBEntities context = new CoffeeShopDBEntities())
//--found this on msdn..got rid of old but end up w/2 new errors see below
{
//the foreach code below goes here
}
foreach(TabPage tp in tabControl1.TabPages)
{
ObjectQuery<tblProduct> filteredProduct = new ObjectQuery<tblProduct>
("SELECT VALUE P FROM tblProducts AS P", cse);
//when 'context' used 1)possible mistaken empty statment
//2)the name 'context' doesnt exist in the current context
//when 'cse'used :
//Error 1 The best overloaded method match for 'System.Data.Objects.ObjectQuery<P.tblProduct>.ObjectQuery(string, System.Data.Objects.ObjectContext)' has some invalid arguments
//Error 2 Argument 2: cannot convert from 'P.CoffeeShopDBEntities' to 'System.Data.Objects.ObjectContext'
foreach (tblProduct tprod in filteredProduct)
{
Button b = new Button();
b.Text = tprod.Description;
tp.Controls.Add(b);
}
}
}
I found a similar issue on Stack Overflow and the reply states it's a syntax error but doesn't point out where.
You are getting errors because ObjectQuery is looking for an ObjectContext which comes with EF 4.0 and below. The CoffeeShopDBEntities is of the DBContext type which comes with anything EF 4.1 and above.
I would suggest changing your query to:
List<tblProduct> filteredProducts = cse.tblProducts.ToList();
If you want to read more on the ObjectContext vs. DBContext, you can check out this link:
http://www.c-sharpcorner.com/UploadFile/ff2f08/objectcontext-vs-dbcontext/
I am writing an app (something like Notepad) in C#. I'm using Properties.Settings class to save user preferences. It was working fine until suddenly when it started showing this exception message anytime I try to run it.
Configuration system failed to initialize
I noticed that the error originated from this part of the code:
private void TextPad_Load(object sender, EventArgs e)
{
rtbText.WordWrap = Properties.Settings.Default.WordWrap;
rtbText.Font = Properties.Settings.Default.DefFont;
rtbText.ForeColor = Properties.Settings.Default.ForeColor;
rtbText.BackColor = Properties.Settings.Default.BackColor;
if (Properties.Settings.Default.ShowLast)
{
OpenLocalFile(Properties.Settings.Default.LastFile);
}
// There are other lines which are not relevant to this question
}
I moved the supposedly lines to the form constructor immediately after InitializeComponent(); but I still got the same error.
Actually the compiler is telling the error originates from this in Settings.Designer.cs:
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool WordWrap {
get {
return ((bool)(this["WordWrap"]));
}
set {
this["WordWrap"] = value;
}
If I remove rtbText.WordWrap = Properties.Settings.Default.WordWrap; from TextPad_Load, it shows
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("Consolas, 9.75pt")]
public global::System.Drawing.Font DefFont {
get {
return ((global::System.Drawing.Font)(this["DefFont"]));
}
set {
this["DefFont"] = value;
}
The only solution now is either to remove those lines from TextPad_Load (which makes the idea loading user preferences useless) or starting a new project (which I have done, anyway). Can someone please explain what the exception message means and maybe I can get a solution (in case I run into it again)? Microsoft VS Help is not giving me anything tangible.
Thanks
It might help to throw away your existing .config files.
After changes in the Properties.Settings the old file might not be valid any more (changed names, or removed items no longer recognized).
Note that user scoped settings are stored in (drive):\Users(usr)\AppData\Local\Microsoft...something
I just had this idea for something that I'd love to be able to use:
Let's say I have to fix a bug and I decide to write an ugly code line that fixes the immediate problem - but only because I promise myself that I will soon find the time to perform a proper refactoring.
I want to be able to somehow mark that code line as "Expired in" and add a date - so that if the code is compiled some time after that date there will be a compilation error/warning with a proper message.
Any suggestions? It must be possible to perform - maybe using some complicated #IF or some options in visual studio?
I'm using VS 2005 - mainly for C#.
Mark the code with the System.ObsoleteAttribute attribute, you'll get a compiler warning, which will nag you to fix the code
[Obsolete("You've an ugly hack here")]
public void MyUglyHack()
{
...
}
Alternatively . . .
Write your own attribute, passing it an expiration date on the constructor, in the constructor throw an exception if DateTime.Now >= expirationDate.
The compile will fail until you fix the code (or more likely increase the expiration date, or far more likely you just remove the Attribute.
oooohhh - this is 'orrible. try this for a giggle:
[AttributeUsage(AttributeTargets.All)]
public class BugExpiryAttribute : System.Attribute
{
// don't tell 'anyone' about this hack attribute!!
public BugExpiryAttribute(string bugAuthor, string expiryDate)
{
DateTime convertedDate = DateTime.Parse(expiryDate);
Debug.Assert(DateTime.Now <= convertedDate,
string.Format("{0} promised to remove this by {1}",
bugAuthor, convertedDate.ToString("dd-MMM-yyyy")));
}
}
then, decorate your method/class etc:
[BugExpiryAttribute("Jack Skit", "2011-01-01")]
public static void Main(string[] args)
{
...
}
... nasty :-)
[DISCLAIMER] - created in the name of academic interest, not production code finese!!
[edit] - just to clarify, code compiled and in production will continue to run on/after the 'bugExpriryDate'. only once the code is run in the compiler (on/after the date), will the warning message be raised (debug.assert). just thought it worth making that distinction - cheers MartinStettner.
[caveat] - if used in classes/methods etc would need to be read via reflection. however (and this is interesting) will work straight off in the compiler if used on sub Main(). how strange!! (thanks for the nod Hans...)
I think this is the reason Visual Studio has a Task List. Add the comment:
\\ TODO: Fix this spaghetti by 01APR11
and it will show up like this
.
the keywords are configurable from the options
You could write comment lines in the form
// Expires on 2011/07/01
and add a prebuild step which does a solution-wide replace of these lines by something like
#error Code expired on 2011/07/01
for all lines that contain a date before the current day. For this prebuild step you would need to write a short program (probably using regular expressions and some date comparision logic)
This step could also be performed by a VS macro, which allows for easier access to all files fo the solution but has the disadvantage that it must be installed and run on all VS installations where your project is compiled.
One more option if you have unit tests for your code you can time bomb the tests that verifies your fix. This way you don't introduce strange checks in your production code.
Also I think the best option if you have to put in hack (you've probably already spent enough time looking at it to fix properly... but still want a hack there) than open bug/create task/work item (whatever you use to track future work) and decide if you want to fix it later.
Well it doesn't do exactly what you're asking for but you could use a Debug.Assert() method call which would alert you (in Debug only) that the code has expired. One benefit would be that it wouldn't inadvertently affect your production code (compilation or execution) but would be sufficiently annoying in Debug for you to want to correct it.
// Alert the developer after 01/07/2011
Debug.Assert(Date.Now < new DateTime(2011, 7, 1))
With .NET 6+ this is quite simple when a source generator is used:
Source generator
[Generator]
public class ObsoleteFromDateSourceGenerator : ISourceGenerator
{
public void Execute(GeneratorExecutionContext context)
{
var currentDate = DateTime.Now.Date;
ImmutableArray<AttributeSyntax> attributes = context.Compilation
.SyntaxTrees.SelectMany(s => s.GetRoot().DescendantNodes())
.Where((d) => d.IsKind(SyntaxKind.Attribute))
.OfType<AttributeSyntax>()
.Where(d => d.Name.ToString() == SourceGeneratorConstants.ObsoleteFromDateAttributeName)
.ToImmutableArray();
foreach (var attribute in attributes)
{
try
{
var semanticModel = context.Compilation.GetSemanticModel(attribute.SyntaxTree);
var argumentDate = attribute.ArgumentList?.Arguments.FirstOrDefault()?.Expression;
var argumentMessage = attribute.ArgumentList?.Arguments.Skip(1).FirstOrDefault()?.Expression;
if (argumentDate != null)
{
var date = DateTime.ParseExact(semanticModel.GetConstantValue(argumentDate).ToString(), SourceGeneratorConstants.ObsoleteFromDateAttributeDateFormat, CultureInfo.InvariantCulture);
string? message = null;
if (argumentMessage is not null
&& semanticModel.GetConstantValue(argumentMessage) is Optional<object> tmp
&& tmp.HasValue)
{
message = tmp.Value?.ToString();
}
var diagnostic = Diagnostic.Create(DiagnosticDescriptors.ObsoleteFromDate(message, /*isWarning:*/ currentDate < date), attribute.GetLocation());
context.ReportDiagnostic(diagnostic);
}
else
{
throw new ArgumentNullException(paramName: "date");
}
}
catch (Exception ex)
{
var diagnostic = Diagnostic.Create(DiagnosticDescriptors.ObsoleteFromDateError(ex.Message), attribute.GetLocation());
context.ReportDiagnostic(diagnostic);
}
}
}
public void Initialize(GeneratorInitializationContext context)
{
}
}
Some constants
public static class SourceGeneratorConstants
{
public const string ObsoleteFromDateAttributeName = "ObsoleteFromDate";
public const string ObsoleteFromDateAttributeDateFormat = "yyyy-MM-dd";
}
Build diagnostics
public static class DiagnosticDescriptors
{
public const string Category = "BNX";
public const string ErrorTitle = "Source code error";
public static readonly Func<string?, bool, DiagnosticDescriptor> ObsoleteFromDate = (message, isWarning) => new DiagnosticDescriptor(
id: $"{Category}{SourceGeneratorConstants.ObsoleteFromDateAttributeName}",
title: "Obsolete code",
messageFormat: message ?? "Obsolete code, please review",
category: Category,
defaultSeverity: isWarning ? DiagnosticSeverity.Warning : DiagnosticSeverity.Error,
isEnabledByDefault: true);
public static readonly Func<string?, DiagnosticDescriptor> ObsoleteFromDateError = (message) => new DiagnosticDescriptor(
id: $"{Category}{SourceGeneratorConstants.ObsoleteFromDateAttributeName}",
title: ErrorTitle,
messageFormat: $"Unable to parse {SourceGeneratorConstants.ObsoleteFromDateAttributeName} attribute because of error: {message} Expecting the following syntax: [{SourceGeneratorConstants.ObsoleteFromDateAttributeName}(\"{SourceGeneratorConstants.ObsoleteFromDateAttributeDateFormat}\", \"message\")]",
category: Category,
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
}
A custom attribute
/// <summary>
/// Triggers a build error at and after a specific system date. Source generators must be included in the project.
/// </summary>
public class ObsoleteFromDateAttribute : Attribute
{
public const string DateFormat = "yyyy-MM-dd";
/// <summary>
/// Build error message.
/// </summary>
public string Message { get; }
/// <summary>
/// System date at and after which the build error should occur.
/// </summary>
public string Date { get; }
/// <summary>
/// Initializes a new instance of the <see cref="ObsoleteFromDateAttribute"/> class.
/// </summary>
/// <param name="date">Required. System date at and after which the build error should occur. Expected format: <see cref="DateFormat"/></param>
/// <param name="message">Optional. Build error message.</param>
public ObsoleteFromDateAttribute(string date, string message): base()
{
Date = date;
Message = message;
}
}
And finally a test:
// The following should result in a build error
[ObsoleteFromDate("2000-01-01", "We are waiting for some Jira thing 1 to complete")]
public class ObsoleteClass1
{
}
// The following should result in a build warning
[ObsoleteFromDate("3000-01-01", "We are waiting for some Jira thing 2 to complete")]
public class ObsoleteClass2
{
}
Without controlling the compiler (possible in the 5.0 timeframe with compiler as a service?), you are not going to have your code expire. You can mark the code as deprecated, or use the Obsolete attribute, or similar, to fire off a warning, but people can ignore warnings (many devs I have met have not learned the rule that warnings are errors).
I think it is a lot of work to try to protect people from themselves. It is even harder when you are protecting them from themselves in the future. Mark the code as a kludge and leave it at that.
Instead of embedding a time bomb, perhaps consider applying a BUGBUG: comment?
Rather than forcing you or someone else to fix code that may be kind of unsightly but works as expected down the road, you can just do a solution-wide search and find the ugly bits when you decide it's time to get down and refactor the really ugly stuff.
Track it in a bug instead. Then it can be properly scheduled and prioritized with other refactoring work.
TODO comments in code can have a tendency to be lost and forgotten. Throwing a compiler error after a particular date will likely lead to that date being pushed forward, or the comment/attribute removed.
I hope i can help with this. take 2 datetimepicker on tool box. And just convert 1 datetimepicker.
private void expired()
{
DateTime expired = DateTime.Parse(Convert.ToDateTime(datetimepicker1.Text).ToString());
DateTime compare = DateTime.Parse(Convert.ToDateTime(datetimepicker2.Text).ToString());
if(expired < compare)
{
MessageBox.Show("This product is expired!");
}
else
}
MessageBox.Show("This product is not expired");
{
}
Both TIME and DATE emit strings and, to my knowledge, there is no way to parse them out at the preprocessing stage.
There are a few methods you can easily do in code to ensure that the code at least warns you at run time. Including an assert is one way, putting in a code comment also works, but the way I handle it is through including a doxygen comment with a note explaining that the function contains a hack, bug, or performance issue that needs to be resolved. This ends up getting filtered by many programmers and is easily viewable on the website for myself or other people to fix.