logo
down
shadow

Using a parameter's property in an ArgumentException


Using a parameter's property in an ArgumentException

By : user2173062
Date : October 21 2020, 08:10 PM
this will help I think SonarQube is spot on here: there's no parameter named UserCode, so you shouldn't be specifying it as an argument to the ArgumentNullException constructor. I would avoid using ArgumentNullException at all here, as the argument isn't null - otherwise it would be throwing a NullReferenceException at command.UserCode.
Instead, just use ArgumentException with a descriptive message, e.g.
code :
throw new ArgumentException(
    $"{nameof(command.UserCode)} property cannot be null or empty",
    nameof(command));


Share : facebook icon twitter icon
ArgumentException or ArgumentNullException for string parameters?

ArgumentException or ArgumentNullException for string parameters?


By : Gabriel Huertd Msrt
Date : March 29 2020, 07:55 AM
wish of those help I'd say the second way is indeed more precise - yes, it's more cumbersome but you can always wrap it in a method to avoid having to do it all the time. It could even be an extension method:
code :
str.ThrowIfNullOrEmpty("str");


public static void ThrowIfNullOrEmpty(this string value, string name)
{
    if (value == null)
    {
        throw new ArgumentNullException(name);
    }
    if (value == "")
    {
        throw new ArgumentException("Argument must not be the empty string.",
                                    name);
    }
}
public Person(string name)
{
    this.name = name.CheckNotEmpty();
}
Catch ArgumentException on WebService when receive Null Parameters

Catch ArgumentException on WebService when receive Null Parameters


By : Валера Скиба
Date : March 29 2020, 07:55 AM
this will help If you want to allow the user to pass null you would have to make the int parameters nullable. Change the signature to use int? instead of int.
code :
public string[] M102(int? p_enclosure, string p_transaction, int? p_operation, int? p_commodity,
                      string p_bl, string p_inDate, string p_blhouse, string p_anexo29, int p_tranType,
                      string p_vessel, string p_trip, int? p_entry, string p_padlock, string p_brands, 
                      string p_appoint, string p_plates, string p_qmark)
// you'd want to add this check early in the method body
if(!p_enclosure.HasValue || p_transaction == null || !p_operation.HasValue ...
{
    try{
       // log the error
    }catch{
       // ignore errors from the logging system
    }

    //   and stop processing
    return null; // or whatever makes sense in case of invalid arguments
}
Why are the parameters in the constructors for ArgumentNullException and ArgumentException reversed?

Why are the parameters in the constructors for ArgumentNullException and ArgumentException reversed?


By : Mauricio Jiménez
Date : November 14 2020, 05:16 PM
Does that help Because the constructor which takes only one argument, takes a different argument:
ArgumentNullException(String) takes paramName as argument, ArgumentException(String) takes a message.
ArgumentException ParamName convention for multiple parameters and nested parameters

ArgumentException ParamName convention for multiple parameters and nested parameters


By : user3131290
Date : March 29 2020, 07:55 AM
To fix this issue I can't speak for third-party tools that might use that data, but I don't think there are any conventions. MSDN suggests it is for informational purposes: (for end-users, or for developers who might catch it in another assembly further upstream, so they can handle it accordingly)
code :
public bool IsDiscountValid(ProductPrice pp)
{
    return pp.SalePrice <= pp.RegularPrice;
}

public decimal CalculateDiscount(ProductPrice pp)
{
   return (pp.RegularPrice - pp.SalePrice) / pp.RegularPrice;
}
if (IsDiscountValid(thePriceInfo))
    return CalculateDiscount(thePriceInfo);

MessageBox.Show("Sale price cannot be greater than regular price.", "Invalid Price");

// or display text in a Label or whatever, depending on which platform you're using
ArgumentException on Adding multiple Parameters in Stored Procedure

ArgumentException on Adding multiple Parameters in Stored Procedure


By : jgabriel zavar
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further You are getting the error because param is already added to the parameter collection. In your code, you're simply changing the values of the existing object then trying to re-add it.
You need to create a new parameter object instance for each parameter in the collection:
code :
IDataParameter param = cmd.CreateParameter();
param.ParameterName = "@rvcName";
param.Value = productName;
cmd.Parameters.Add(param);

param = cmd.CreateParameter(); //create a new instance for the next parameter
param.ParameterName = "@rvcCode";
param.Value = productCode;
cmd.Parameters.Add(param);

param = cmd.CreateParameter(); //create a new instance for the next parameter
param.ParameterName = "@riProductTypeID";
param.Value = productTypeID;
cmd.Parameters.Add(param);
cmd.Parameters.AddWithValue("@rvcName", (object)productName ?? DBNull.Value);
cmd.Parameters.AddWithValue("@rvcCode", (object)productCode ?? DBNull.Value);
cmd.Parameters.AddWithValue("@riProductTypeID", (object)productTypeID ?? DBNull.Value);
static void AddParameterWithValue(this IDbCommand cmd, string paramName, object value)
{
    if(paramName == null)
        throw new ArgumentNullException(nameof(paramName));

    if(string.IsNullOrWhiteSpace(paramName))
    {
        throw new ArgumentOutOfRangeException(
            nameof(paramName), 
            paramName, 
            "Parameter name cannot be empty");
    }

    cmd.Parameters.AddWithValue(paramName, value ?? DBNull.Value);
}
Related Posts Related Posts :
  • How do request a correct access token in ASP.NET Core for Azure AD to access Microsoft Graph
  • How to run a .NET Core console application on Linux
  • UI not updating for bound element
  • C# Odata v4 open type raw values
  • DocumentFormat.OpenXml Modify Creator Propery of Document
  • How to SetBasePath in ConfigurationBuilder in Core 2.0
  • ASP MVC5 public readonly variable changes value when it should not
  • How to conditionally select item from hashset with queryable linq?
  • Progress Bar C# not showing the real progress
  • Correct logic to reconnect in SignalR with HubConnection
  • ComboBox with two or more sections
  • .NET listbox to SQLite DB
  • C# Ninject binding from Dictionary<Type, Type>
  • asp.net mvc -view displaying real-time progress status
  • Getting reference to dependent in service with generic type
  • Implementing EqualityCompare vs overriding GetHashCode and Equals
  • C# Linq Find all indexes of item in List<int> within another List<int>
  • XML image how to display at data grid columns in c#.net
  • How to override Equals and GetHash of HashSet
  • Creating Windows authentication and SQL Server authentication in login form
  • How to interop with Azure Service Bus topics created by MassTransit using Rebus?
  • MVC 5 Google Calendar Integration
  • C# - Use parallel arrays to calculate cost of a phone call in GUI
  • Use a int in entire code
  • How to display newly added element at the top of StackPanel in WPF?
  • T4MVC is generating T4MVC.cs and T4MVC1.cs
  • Remove blur effect on certain controls inside UserControl
  • Sql Transcation Query to Linq Query in Wcf Rest Service
  • Setting AWS S3 credentials in C# app
  • does not contain in an ObservableCollection
  • App doesn't run it crashed directly after I started it
  • Is it possible in Entity Framework MVC application to run .sql scripts on a different database
  • Type Inference with Deconstruct tuple assignment extension methods
  • Setting up mock objects for EF dbcontext to test repository methods
  • Using C# in XSLT with MSXSL 6.0
  • Absolute positioning of UIElement in FlowDocument in WPF
  • Display debuggers not showing up in Visual Studio 2017
  • Discord.NET Users playing the same game
  • Azure function output API call to 3rd party service
  • Unable to determine the relationship represented by navigation property ASP.NET core 2.0 Entity Framework
  • Regex to find group of Regex inside a word
  • When calling a method, when to reference the class, and when to reference the object?
  • AmazonCloudWatchLogsClient async methods failing with no error
  • Create FileStream in memory instead of saving a physical file on disk
  • ViewBag data coming from ActionFilter is persisting in session even after database
  • ERROR: the name 'lvSubCategories' does not exist in the current context
  • Why datetime can't recognise the string?
  • Getting 500 error while requesting to webservice using Ajax AutoCompleteExtender
  • The property 'x' is not a navigation property of entity type 'y'
  • ASP.NET MVC - How to generate empty input boxes in loop when model is empty?
  • Need help writing regular expression
  • Add/remove buttons to a panel with an arraylist c#
  • Linq .Where(type = typeof(xxx)) comparison is always false
  • Using EF6 Code First without migrations to an existing db how do I specify column names of the many to many join table?
  • C# - Using Thread.Sleep precisely in a console application
  • Add item to a List<Tuple> inside another list
  • Double[,], inversion C#
  • Counting a string to ensure the input is within a min/max boundary
  • Assign invalidValue to Enum variable (why is this not throwing an Exception?)
  • Namespace or type specified in the project-level Imports 'System.Threading.Tasks' doesn't contain any public member or c
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org