Cannot convert method group... NOT missing parentheses - c#

bool connected = false;
if (isConnected()) //if(isConnected() == true) also doesn't work
{
//code
}
else {
connect();
}
public bool isConnected() {
if (nextEvent != "null" && !nextEvent.Contains(getEvent("disconnected"))) {
connected = true;
}
return connected;
}
Getting the error:
Cannot convert method group 'isConnected' tot non-delegate type 'bool'.
Why? I've looked this up and in most cases, people forget to put parentheses after the function name, like this:
if(isConnected) { // .... }
Which is not the case for me. What's wrong?

You are probably trying to define function inside other function, if so put the function in out side function, suppose the code for calling is inside YourFun() then take isConnected() definition out side YourFun()
void YourFun()
{
bool connected = false;
if (isConnected()) //if(isConnected() == true) also doesn't work
{
//code
}
else {
connect();
}
}
public bool isConnected() {
if (nextEvent != "null" && !nextEvent.Contains(getEvent("disconnected"))) {
connected = true;
}
return connected;
}

Related

How to test connection string?

I have a simple issue, I am trying to check if the connection string in App.config is valid and the server & database inside of it are accessible. I have tried the following code but still it doesn't work:-
public static bool checkConnectionString(string con)
{
if (ConfigurationManager.ConnectionStrings[con].ConnectionString == "" && !checkConnectionStringValidity(con))
{
return false;
}
else
{
return true;
}
}
public static bool checkConnectionStringValidity(string con)
{
try {
using(var connection = new SqlConnection(con)) {
connection.Open();
return true;
}
} catch {
return false;
}
}
And then I use the above methods in the main screen:-
if (Data.checkConnectionString("Utilities"))
{
Application.Run(new Log_In());
}
else
{
Application.Run(new ApplicationMainSettings());
}
I want that when I write wrong information in the app.config the program directs me to ApplicationMainSettings() screen.
Your method looks fine and working, the issue is && operator in the if, Due to its presents the method checkConnectionStringValidity will called only if the connection string is "" I thing it is not needed to check for "" here you can directly use like the following:
if(checkConnectionStringValidity(ConfigurationManager.Connecti‌​onStrings[con].Conne‌​ctionString))
{
// Proceed the connection is valid
}
else
{
// Stop here the connection is invalid
}
Or else you can try with != "" && checkConnectionStringValidity(con) so the method will called only if the connection string is non-empty(because, the method will definitely return false if the value is empty). So you can try like this:
if (ConfigurationManager.ConnectionStrings[con].ConnectionString != "" && checkConnectionStringValidity(con))
{
// Proceed the connection is valid
}
else
{
// Stop here the connection is invalid
}
Refactor the code to apply the intended logic...
public static bool checkConnectionString(string key) {
var connectionSetting = ConfigurationManager.ConnectionStrings[key];
return connectionSetting != null && checkConnectionStringValidity(connectionSetting.ConnectionString);
}
We first check that the connect settings actually exist.
If it does then you can check the connection string.
If it does not then you run the chance of getting a null exception.
You can try this solution.
public static bool checkConnectionStringValidity(string con)
{
var _testConnection=false;
try {
using(var connection = new SqlConnection(con)) {
if (con.State == ConnectionState.Closed)
{
con.Open();
_testConnection = true;
con.Close();
}
}
} catch {
_testConnection = false;
}
return _testConnection ;
}
also you need to change checkConnectionString function as per below.
public static bool checkConnectionString(string con)
{
if(ConfigurationManager.ConnectionStrings[con] !=null)
{
if (Convert.Tostring( ConfigurationManager.ConnectionStrings[con].ConnectionString) == "" && !checkConnectionStringValidity(con)
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
Let me know if you have any query.

not all code path returns a value on Active Directory check

I am in the process of converting code from VB to C# from an old system that used a base classes for web forms to inherit classes from. My hope is to build a new login for our new extranet that functions like the old system, I may have missed a step but here is the block I tried to convert.
public bool CheckAD()
{
string fncADStatus = "Failure";
string fncSuccess = "Success";
string fncFailure = "Failure";
fncADStatus = Convert.ToString(Session["SessionADStatus"]);
try
{
if (fncADStatus == fncSuccess)
{
return true;
}
}
catch
{
if (fncADStatus == fncFailure)
{
return false;
}
if (Session["SessionADStatus"] == null)
{
return false;
}
}
}
And I get the following error "not all code path return a value" but I don't quite understand why.
it give you the error because you have not mentioned the else statment; nothing will be returned if condition fall in else. do the following will not give you the errro.
public bool CheckAD() {
string fncADStatus = "Failure";
string fncSuccess = "Success";
string fncFailure = "Failure";
fncADStatus = Convert.ToString(Session["SessionADStatus"]);
try
{
Boolean output = false;
if (fncADStatus == fncSuccess)
{
output = true;
}
return output;
}
catch
{
Boolean output = true;
if (fncADStatus == fncFailure)
{
output = false;
}
if (Session["SessionADStatus"] == null)
{
output = false;
}
return output;
}
}
Not all the code paths in the catch block return a result. Usually, you would write something like this
public bool CheckAD()
{
try {...}
catch
{
if (fncADStatus == fncFailure)
{
logger.Debug("One");
}
if (Session["SessionADStatus"] == null)
{
logger.Debug("Two");
}
return false; // <<<<< This bit is missing in your case
}
}

how to return Action<bool> inside method?

I have the following code in my class:
private static void SetUserMeta(string pUserToken, string pMetaKey, string pMetaValue, Action<bool> callback)
{
BuddyClient client = CreateBuddy();
bool rValue = false;
client.LoginAsync((user, state) =>
{
if (state.Exception != null)
{
rValue = false;
}
else
{
client.Metadata.SetAsync((result, resultState) =>
{
if (resultState.Exception != null)
{
rValue = false;
}
else
{
rValue = true;
}
}, key: pMetaKey, value: pMetaValue);
}
callback(rValue);
}, token: pUserToken);
}
and I want to get rValue and return it from my other method which is the following
public static void SetBuddyData(string pUserToken, BuddyData pMetaValue, Action<bool> callback)
{
//my problem is here and I don't know how to get and return data from SetUserMeta
return SetUserMeta(pUserToken, "SavedGameData", pMetaValue.Serialize());
}
And also I want to call this return value from my application. These codes are in my library. How can I do it?
Just pass callback to SetUserMeta like
public static void SetBuddyData(string pUserToken, BuddyData pMetaValue, Action<bool> callback)
{
SetUserMeta(pUserToken, "SavedGameData", callback);
}
And call SetBuddyData like this
SetBuddyData("my user token", myBundle, isLoggedIn => HandleUserLogin(isLoggedIn));
Where at HandleUserLogin you will process bool callback data, returned at callback(rValue); in SetUserMeta method. It's body example is shown
next
public static void HandleUserLogin(bool isLogged)
{
Console.WriteLine("user is {0} logged in", isLogged ? "" : "not");
}
You also can take advantage of method group syntax and call SetBuddyData method like:
SetBuddyData("my user token", myBundle, HandleUserLogin);

expected class, delegate, enum, interface or struct error C#

have a php code like this,going to convert it in to C#.
function isValid($n){
if (preg_match("/\d+/",$n) > 0 && $n<1000) {
return true;
}
return false;
}
Here is my try,BUT error shown Error is "expected class, delegate, enum, interface or struct error C#"
public string IsValidate(string Item)
{
string Result = Item;
try
{
Result = System.Text.RegularExpressions.Regex.Replace(InputTxt, #"(\\)([\000\010\011\012\015\032\042\047\134\140])", "$2");
}
catch(Exception ex)
{
console.WriteLine(ex.Message)
}
return Result;
}
What is the error,Is there any other way to implement this better than my try ?
i got this snippet from here code
You haven't define this method inside a class/struct that is why you are getting this error. You may define this method inside a class.
public class MyValidator
{
public string IsValidate(string Item)
{
//Your code here
}
}
Later you can use it like:
MyValidator validator = new MyValidator();
validator.IsValid("Your string");
Also you are missing semicolon at the end of the Console.Write statement, plus 'c' for Console should be in uppercase
Edit:
Since in your php code, it looks like you are trying to see if the string passed is an integer and it is less than 1000, you may use the int.TryParse like the following:
public class MyValidator
{
public bool IsValidate(string Item)
{
string Result = Item;
int val;
if (int.TryParse(Item, out val) && val > 0 && val < 1000)
{
return true;
}
else
{
return false;
}
}
}
In you main method you can do:
static void Main()
{
MyValidator validator = new MyValidator();
Console.WriteLine(validator.IsValidate("asdf123")); // This will print false
Console.WriteLine(validator.IsValidate("999")); //This will print true
Console.WriteLine(validator.IsValidate("1001")); //This will print false
}
In C# a method must be placed inside a class or struct:
public class Validator {
public string IsValidate(string item) {
...
}
}
In this case I would probably translate it like this:
public static class Validator {
public static bool IsValid(string item) {
int value;
return int.TryParse(item, out value)
&& value > 0 && value < 1000;
}
}
You could define your function inside a static class such that you dont have to create an instance of it before invoking the function. Like,
public static class Validator
{
public static string IsValidate(string item)
{
// ...
}
}
Then, you can call it using:
Validator.IsValidate("String to validate")
EDIT: You could then check that your function is returning what you expect by doing:
if(Validator.IsValidate("String to validate") == "Expected result")
{
/* Logic to be executed here */
}

C# Refactoring of If Statement

I am experimenting with different areas of C# and refactoring best practices/patterns.
As can be seen the Validate method below has 3 child validation methods.
Is there a way to redesign this method/refactor it so that the if statement are remove? (possibly using Delegate?).
Also what general code standard improvements would you suggest?
public bool Validate()
{
bool validDump;
validDump = ValidateRecordIdentifiers();
if (!validDump)
{
LogLogic.AddEntry(LogLogic.GetEnumDescription(
LogMessages.StatusMessages.JobValidationFailed));
return false;
}
validDump = ValidateTotals();
if (!validDump)
{
LogLogic.AddEntry(LogLogic.GetEnumDescription(
LogMessages.StatusMessages.JobValidationFailed));
return false;
}
validDump = ValidateRecordCount();
if (!validDump)
{
LogLogic.AddEntry(LogLogic.GetEnumDescription(
LogMessages.StatusMessages.JobValidationFailed));
return false;
}
LogLogic.AddEntry(LogLogic.GetEnumDescription(
LogMessages.StatusMessages.JobValidationPassed));
return true;
}
bool valid = false;
if(ValidateRecordIdentifiers() && ValidateTotals() && ValidateRecordCount())
{
valid = true;
}
/******AN Alternate Suggestion for the above code********/
bool valid = ValidateRecordIdentifiers() &&
ValidateTotals() &&
ValidateRecordCount();
/*******End Alternate Suggestion*************/
var statusMessage = (valid) ?
LogMessages.StatusMessages.JobValidationPassed :
LogMessages.StatusMessages.JobValidationFailed
LogLogic.AddEntry(LogLogic.GetEnumDescription(statusMessage));
return valid;
See short circuiting:
http://msdn.microsoft.com/en-us/library/2a723cdk%28VS.71%29.aspx
Framework:
class Validator
{
Func<bool> validatorDelegate;
Action failDelegate;
public Validator(Func<bool> v, Action fail)
{
validatorDelegate = v;
failDelegate = fail;
}
public bool Validate()
{
bool rc = validatorDelegate();
if (!rc) failDelegate();
return rc;
}
}
class ValidatorCollection : List<Validator>
{
Action successDelegate;
Action failDelegate;
public ValidatorCollection(Action failDelegate, Action successDelegate)
{
this.successDelegate = successDelegate;
this.failDelegate = failDelegate;
}
public bool Validate()
{
var rc = this.All(x => x.Validate());
if (rc) successDelegate();
return rc;
}
public void Add(Func<bool> v)
{
this.Add(new Validator(v, failDelegate));
}
}
Usage:
class test
{
public bool Validate()
{
return new ValidatorCollection(
FailAction,
SuccessAction)
{
valTrue,
valTrue,
valFalse
}.Validate();
}
public void FailAction()
{
LogLogic.AddEntry(LogLogic.GetEnumDescription(LogMessages.StatusMessages.JobValidationFailed));
}
public void SuccessAction()
{
LogLogic.AddEntry(LogLogic.GetEnumDescription(LogMessages.StatusMessages.JobValidationPassed));
}
public bool valTrue()
{
return true;
}
public bool valFalse()
{
return false;
}
}
public bool Validate()
{
return Validate(ValidateRecordIdentifiers, ValidateTotals, ValidateRecordCount);
}
public bool Validate(params Func<bool>[] validators)
{
var invalid = validators.FirstOrDefault(v => !v());
if (invalid != null)
{
LogLogic.AddEntry(LogLogic.GetEnumDescription(LogMessages.StatusMessages.JobValidationFailed));
return false;
}
LogLogic.AddEntry(LogLogic.GetEnumDescription(LogMessages.StatusMessages.JobValidationPassed));
return true;
}
You could modify your validate methods so that they take in the LogLogic parameter and add an entry themselves for failing.
They could still return a boolean value, and this could be used to keep your return as soon as possible.
return ValidateRecordIdentifiers(LogLogic)
&& ValidateTotals(LogLogic)
&& ValidateRecordCount(LogLogic);
The first thing that jumps out is duplication:
LogLogic.AddEntry(LogLogic.GetEnumDescription(LogMessages.StatusMessages.JobValidationFailed));
So I'd look to collapse it into something like:
public StatusMessages Validate() {
LogMessages.StatusMessages status = LogMessages.StatusMessages.JobValidationFailed;
if( ValidateRecordIdentifiers() && ValidateTotals() && ValidateRecordCount())
status = LogMessages.StatusMessages.JobValidationPassed;
LogLogic.AddEntry(status.ToString());
return status;
}
There's a number of different ways to write this but your method is short and readable. The suggestions posted so far are, imo, much less readable and harder to debug (where would you set a breakpoint?). I would leave this method as is and look for other refactoring opportunities.
You are writing the same error message regardless of which validation function fails. It might be more helpful to log a specific error message in each case.
Otherwise you can rewrite what you already have much simpler:
if (ValidateRecordIdentifiers() && ValidateTotals() && ValidateRecordCount())
{
LogLogic.AddEntry(LogLogic.GetEnumDescription(LogMessages.StatusMessages.JobValidationPassed));
return true;
}
LogLogic.AddEntry(LogLogic.GetEnumDescription(LogMessages.StatusMessages.JobValidationFailed));
return false;
You can take a look at Validation Application Block and Code Contracts
You could do something simple like this:
bool validDump;
string message;
if ((!ValidateRecordIdentifiers()) ||
(!ValidateTotals()) ||
(!ValidateRecordCount()))
{
message = LogLogic.GetEnumDescription(LogMessages.StatusMessages.JobValidationFailed);
}
else
{
message = LogLogic.GetEnumDescription(LogMessages.StatusMessages.JobValidationPassed);
validDump = true;
}
LogLogic.AddEntry(message);
return validDump;
Maybe:
public bool Validate()
{
if (ValidateRecordIdentifiers() && ValidateTotals() && ValidateRecordCount())
{
LogLogic.AddEntry(LogLogic.GetEnumDescription(LogMessages.StatusMessages.JobValidationPassed));
return true;
}
LogLogic.AddEntry(LogLogic.GetEnumDescription(LogMessages.StatusMessages.JobValidationFailed));
return false;
}
This looks to me like a case for structured exception handling. It looks like an exception condition that you are handling in the sense that something invalid has been input, and it results in abandoning the process. Have you considered using try/catch in the parent function and throw within the child functions to handle this?
Example:
public bool Validate()
{
try
{
ValidateRecordIdentifiers();
ValidateTotals();
ValidateRecordCount();
LogLogic.AddEntry(LogLogic.GetEnumDescription(LogMessages.StatusMessages.JobValidationPassed));
return true;
}
catch (ValidationException ex)
{
LogLogic.AddEntry(ex.status);
return false;
}
}
class ValidationException : ApplicationException
{
public readonly LogMessages.StatusMessages status;
ValidationException(LogMessages.StatusMessages status)
{
this.status = status;
}
}
void ValidateRecordIdentifiers()
{
if (bad)
throw new ValidationException(LogMessages.StatusMessages.JobValidationFailed);
}
void ValidateTotals()
{
if (bad)
throw new ValidationException(LogMessages.StatusMessages.JobValidationFailed);
}
void ValidateRecordCount()
{
if (bad)
throw new ValidationException(LogMessages.StatusMessages.JobValidationFailed);
}
Edit: I generally don't like to use exception handling for errors that are not immediately reported out to the UI because exception handling can be costly, and excessive exception throwing can make the application harder to debug if you're trying to find real exception cases among a bunch of exceptions that aren't really "exceptional". But depending on your specific case, it may be appropriate. Just use with caution.
Your function does two things: validation and logging. You could separate them like this. This also lets you log these errors differently if you ever decide to do this.
public bool ValidateAndLog()
{
LogMessages.StatusMessages result=Validate();
LogLogic.AddEntry(LogLogic.GetEnumDescription(result));
return result==LogMessages.StatusMessages.JobValidationPassed;
}
private LogMessages.StatusMessages Validate()
{
//of course you can combine the next three ifs into one
if (!ValidRecordIdentifiers())
return LogMessages.StatusMessages.JobValidationFailed;
if (!ValidateTotals())
return LogMessages.StatusMessages.JobValidationFailed;
if (!ValidateRecordCount())
return LogMessages.StatusMessages.JobValidationFailed;
return LogMessages.StatusMessages.JobValidationPassed;
}
public bool Validate()
{
return LogSuccess(
new[] {ValidateRecordIdentifiers, ValidateTotals, ValidateRecordCount }
.All(v=>v()));
}
private bool LogSuccess(bool success)
{
LogLogic.AddEntry(LogLogic.GetEnumDescription(success
? LogMessages.StatusMessages.JobValidationPassed
: LogMessages.StatusMessages.JobValidationFailed
);
return success;
}
Value readability above all else (well, as long as it is in the same ballpark efficiency).
About the only changes I would make is to eliminate the unneeded variable, and use the function call in the conditional, and replace the ! operator with == false. This is easier to see for aging programmers like myself with bad eyesight :)
As implied by the comment of another poster, it is better to make the function read InvalidXX instead, to avoid using negation or == false and for better readability.
Also, as far as combining all the conditionals into a single "AND" statement, I would do that in lisp, but not in c#, because it will making debugging and tracing harder.
In particular, you probably don't want to put the same error message for each case - you should have a different one for each case so you know exactly what happened. Combining all cases into a single expression won't allow you to do this.
public bool Validate() {
if (ValidRecordIdentifiers() == false) {
LogLogic.AddEntry(LogLogic.GetEnumDescription(LogMessages.StatusMessages.JobValidationFailed));
return false;
}
if (ValidTotals() == false) {
LogLogic.AddEntry(LogLogic.GetEnumDescription(LogMessages.StatusMessages.JobValidationFailed));
return false;
}
if (ValidateRecordCount() == false) {
LogLogic.AddEntry(LogLogic.GetEnumDescription(LogMessages.StatusMessages.JobValidationFailed));
return false;
}
LogLogic.AddEntry(LogLogic.GetEnumDescription(LogMessages.StatusMessages.JobValidationPassed));
return true;
}
As the statement of those if conditions are the same for all, so you can do the check in one condition and do the reset job at the below.
public bool Validate()
{
bool validDump;
if(ValidateRecordIdentifiers() && ValidateTotals() && ValidateRecordCount()) {
LogLogic.AddEntry(LogLogic.GetEnumDescription(
LogMessages.StatusMessages.JobValidationPassed));
return true;
}
LogLogic.AddEntry(LogLogic.GetEnumDescription(
LogMessages.StatusMessages.JobValidationFailed));
return false;
}

Categories

Resources