How to test connection string? - c#

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.

Related

Connection string property of SqlConnection is not initialized

I have already searched for the error
the connection string property has not been initialized.
on Google as well as on Stack Overflow but couldn't find the solution. I have created a database class for interaction with database all related code is written in this file. The problem is same code runs fine on other pages and it just don't work on a page called "addevent.aspx" I don't understand the reason why it is not running properly.
Here are the methods that I created in database.cs file
public void CreateConnection()
{
var ConfiguredString = ConfigurationManager.ConnectionStrings[ConnectionString].ConnectionString;
obj_sqlconnection = new SqlConnection(ConfiguredString);
}
//This property will set the connection string for database
public string ConnectionString
{
get
{ //if _connectionString is already created or set, only then it will return the value of _connectionString
if (_connectionString != string.Empty && _connectionString != "" && _connectionString != null)
return _connectionString;
else
return string.Empty;
}
// When you want to set the connection string set block is called.
set
{ // this line sets the connection string to the _connectionString data member for the first time.
if (_connectionString == string.Empty || _connectionString == "" || _connectionString == null)
_connectionString = value;
}
}
// Open database connection.
public void OpenConnection()
{
obj_sqlconnection.Open();
}
// Close database connection.
public void CloseConnection()
{
obj_sqlconnection.Close();
obj_sqlconnection.Dispose();
}
public SqlConnection GetCurrentConnection
{
get { return obj_sqlconnection; }
set { obj_sqlconnection = value; }
}
I simply don't understand the logic of this error and its occurrence. I get this error when I open the connection
How do I call these methods, I have already created a object of database.cs class outside the method AddEvent with object name mydb
public int AddEvent(string _title, string _description, string _place, int _eventTypeID, string _startingTime, string _endingTime, string _startingDate, string _endingDate, string _creatorID, string _picture)
{
string[] blacklist = { _title, _description, _place, _picture };
if (Jvalidate.FilterBlackLIstKeywords(blacklist))
{
int eventid = Convert.ToInt32(mydb.GetLastValueByColumnName("event_id", "tbl_events"));
int rowsaffected = 0;
mydb.CreateConnection();
mydb.InitializeSQLCommandObject(mydb.GetCurrentConnection, "spAddEvent", true);
mydb.obj_sqlcommand.Parameters.AddWithValue("#eventID", eventid + 1);
mydb.obj_sqlcommand.Parameters.AddWithValue("#title", _title);
mydb.obj_sqlcommand.Parameters.AddWithValue("#description", _description);
mydb.obj_sqlcommand.Parameters.AddWithValue("#place", _place);
mydb.obj_sqlcommand.Parameters.AddWithValue("#eventType", _eventTypeID);
mydb.obj_sqlcommand.Parameters.AddWithValue("#startingTime", _startingTime);
mydb.obj_sqlcommand.Parameters.AddWithValue("#endingTime", _endingTime);
mydb.obj_sqlcommand.Parameters.AddWithValue("#startDate", _startingDate);
mydb.obj_sqlcommand.Parameters.AddWithValue("#endDate", _endingDate);
mydb.obj_sqlcommand.Parameters.AddWithValue("#schoolID", SchoolID);
mydb.obj_sqlcommand.Parameters.AddWithValue("#eventCreatorID", _creatorID);
mydb.obj_sqlcommand.Parameters.AddWithValue("#eventPicture", _picture);
try
{
//mydb.obj_sqlconnection.ConnectionString = ConfigurationManager.ConnectionStrings["cesConnectionString"].ToString();
mydb.OpenConnection();
rowsaffected = mydb.obj_sqlcommand.ExecuteNonQuery();
}
finally
{
mydb.CloseConnection();
mydb.obj_sqlcommand.Dispose();
}
return rowsaffected;
}
return 0;
}
it's too complicated solution... this will solve your problem of understanding and unnecessary code lines:
solution:
namespace Stackoverflow
{
public static class Solution
{
static readonly string _connectionStringName =
#"mainConnectionStringName";
static readonly string _connectionString =
_connectionStringName.getConnectionString();
// string extended method like .ToLower() or .Trim()
public static string getConnectionString(
this string connectionStringName)
{
return
System.
Configuration.
ConfigurationManager.
ConnectionStrings[connectionStringName].
ConnectionString;
}
public static object SqlExecute(
string connectionStringName,
string storedProcedureName,
System
.Collections
.Generic
.Dictionary<string, object> parameters,
bool isScalar)
{
object result = null;
using (System
.Data
.SqlClient
.SqlConnection connection =
new System.Data.SqlClient.SqlConnection(
string.IsNullOrWhiteSpace(connectionStringName)
? _connectionString
: connectionStringName.getConnectionString()))
if (connection != null)
using (System.Data.SqlClient.SqlCommand command =
new System.Data.SqlClient.SqlCommand()
{
CommandText = storedProcedureName,
CommandType = System
.Data
.CommandType
.StoredProcedure,
Connection = connection
})
if (command != null)
{
if (parameters != null)
foreach (System
.Collections
.Generic
.KeyValuePair<string, object>
pair in parameters)
command.Parameters.AddWithValue(
pair.Key, pair.Value);
command.Connection.Open();
result = isScalar
? command.ExecuteScalar()
: command.ExecuteNonQuery();
if (command.Connection.State ==
System.Data.ConnectionState.Open)
command.Connection.Close();
}
return result;
}
}
}
usage:
namespace SomeNamespace
{
public sealed class SomeClass
{
public int Example()
{
return (int)Stackoverflow
.Solution
.SqlExecute(
#"anyConnectionStringName", // or null for main connection string
#"anyStoredProcedureName",
new System
.Collections
.Generic
.Dictionary<string, object>()
{
{ #"field0", "value" },
{ #"field1", -1.5 },
{ #"field2", System.DateTime.Now },
{ #"field3", 3.5 },
{ #"field4", 7 },
},
false // for ExecuteNonQuery or true for ExecuteScalar
);
}
}
}

How to catch error from bool type method?

I am writing to seek help with regards to implementing a return statement for my test method. I am currently getting a null response from my test() method, but I would like to know, how can I catch the error from my "IsValidEmailDomain" method in my "test" method:
public static bool IsValidEmailDomain(MailAddress address)
{
if (address == null) return false;
var response = DnsClient.Default.Resolve(address.Host, RecordType.Mx);
try
{
if (response == null || response.AnswerRecords == null) return false;
}
catch (FormatException ex)
{
ex.ToString();
throw ex;
//return false;
}
return response.AnswerRecords.OfType<MxRecord>().Any();
}
public static bool IsValidEmailDomain(string address)
{
if (string.IsNullOrWhiteSpace(address)) return false;
MailAddress theAddress;
try
{
theAddress = new MailAddress(address);
}
catch (FormatException)
{
return false;
}
return IsValidEmailDomain(theAddress);
}
public static string test()
{
string mail = "########";
if (IsValidEmailDomain(mail))
{
return mail;
}
else
{
///How to return error from IsValidEmailDomain() method.
}
}
Any hint or suggestion would be most appreciated.
public static string test()
{
string mail = "########";
bool? answer;
Exception ex;
try
{
answer = IsValidEmailDomain(mail);
}
catch(Exception e)
{
ex = e;
}
if (answer)
{
return mail;
}
else
{
// here you can check to see if the answer is null or if you actually got an exception
}
}
There are a couple of ways to do this.
Use an out parameter.
Throw an exception if there was an issue. (Defeats the purpose of bool)
I usually go with a combination when I come across something like this.
public bool IsValidEmailDomain(string email)
{
return IsValidEmailDomain(email, false);
}
public bool IsValidEmailDomain(string email, bool throwErrorIfInvalid)
{
string invalidMessage;
var valid = ValidateEmailDomain(email, out invalidMessage);
if(valid)
return true;
if (throwErrorIfInvalid)
throw new Exception(invalidMessage);
return false;
}
public bool ValidateEmailDomain(string email, out string invalidMessage)
{
invalidMessage= null;
if (....) // Whatever your logic is.
return true;
invalidMessage= "Invalid due to ....";
return false;
}

no return data from Web Method Web Service

I have a method that is a search for Branches. the parameter is Branch Code and it should return the details of the branch
public bool SearchBranch()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBReader"].ConnectionString))
{
using (SqlCommand com = new SqlCommand("Reader.usp_SearchBranch", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("#BranchCode", SqlDbType.Int).Value = this.BranchCode;
con.Open();
SqlDataReader dr = com.ExecuteReader();
if (dr.Read())
{
this.BranchName = dr.GetValue(0).ToString();
this.AreaCode = dr.GetValue(1).ToString();
this.RegionCode = dr.GetValue(2).ToString();
this.CompanyCode = dr.GetValue(3).ToString();
this.CompanyName = dr.GetValue(4).ToString();
return true;
}
else
{
return false;
}
}
}
}
Here is my code in my Web Method in my Web Service (I dont know if this is correct)
[WebMethod(Description = "Search Affected User from Database in Access Request")]
public bool SearchBranchAccessRequest(AccessRequest accessrequest)
{
return accessrequest.SearchBranch();
}
And this is how I access/call the web method in my web page
protected void SearchBranchButton_Click(object sender, EventArgs e)
{
try
{
accessrequest.BranchCode = Convert.ToInt32(BranchCodeTextBox.Text);
iTicketWebService.SearchBranchAccessRequest(accessrequest);
if (iTicketWebService.SearchBranchAccessRequest(accessrequest) == true)
{
BranchNameLabel.Text = accessrequest.BranchName;
AreaLabel.Text = accessrequest.AreaCode;
RegionLabel.Text = accessrequest.RegionCode;
CompanyCodeLabel.Text = accessrequest.CompanyCode;
CompanyLabel.Text = accessrequest.CompanyName;
BranchEmailLabel.Text = accessrequest.BranchCode + "#pjlhuillier.com";
}
else
{
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "clientScript", "<script type=\"text/javascript\">alert('Record not found. Please try again');</script>");
}
}
catch (Exception)
{
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "clientScript", "<script type=\"text/javascript\">alert('Wrong Input. Please try again');</script>");
}
}
Help! it doesnt return Branch Name,Area Code,Region Code,Company Code and Company name?
change your web method as below
public AccessRequest SearchBranchAccessRequest(AccessRequest accessrequest)
{
return accessrequest.SearchBranch(accessrequest);
}
and you need to change SearchBranch() method as well
public accessrequest SearchBranch(AccessRequest accessrequest)
{
if(you found record in database)
{
// update accessrequest here
}else
{
accessrequest =null;
}
// finally return the object
return accessrequest;
}
when you call this web service
AccessRequest request = iTicketWebService.SearchBranchAccessRequest(accessrequest);
if(request!=null)
{
BranchNameLabel.Text = request.BranchName;
}
since your method signature change with above implementation, in case of null object return you can consider it as false case as your current implementation and if object return from the service you can consider it as true case.
If you need return true false from the service method and also need to have the updated object then you can have custom class to return both, like below
public class SearchBrancResponse
{
public bool SearchStatus { get; set; }
public AccessRequest AccessReq { get; set; }
}
you can then return above from the service method. from client side you have both Boolean value and the AccessRequest

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
}
}

Cannot convert method group... NOT missing parentheses

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;
}

Categories

Resources