Opening a Postgres Connection in Xamarin returns Error While Connecting - postgresql

I am trying to connect my Android Application to Postgres but seems not to work.
The Exception Message is: Exception while Connecting
This is my Code Behind,
private void Login_Clicked(object sender, EventArgs e)
{
DBInterface<DBLogicInput, DBLogicResult> dbLoginLogic = new DBLoginLogic();
DBLogicInput userInput = new DBLogicInput();
DBLogicResult DBResult = new DBLogicResult();
LoginModel useCredentials = new LoginModel()
{
userName = txtUsername.Text,
passWord = txtPassword.Text
};
userInput[typeof(LoginModel).FullName] = useCredentials;
try
{
DBResult = dbLoginLogic.DoProcess(userInput);
bool userExisting = DBResult.ResultCode != DBLogicResult.RESULT_CODE_ERR_DATA_NOT_EXIST;
if (userExisting)
{
Application.Current.MainPage = new NavigationPage(new IndexPage());
}
else
{
_ = DisplayAlert("Login Error", "User does not exist", "Ok");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
This is the Class I created to connect the DB.
public abstract class DBLogic : DBInterface<DBLogicInput, DBLogicResult>
{
public string connectionString = "Server=localhost;Port=5432;User Id=postgres;Password=postgres;Database=proyektoNijuan";
public DBLogicResult DoProcess(DBLogicInput inOut)
{
//throw new NotImplementedException();
DBLogicResult result = default(DBLogicResult);
NpgsqlConnection connection = null;
NpgsqlTransaction transaction = null;
try {
connection = new NpgsqlConnection(connectionString);
if (connection.State != System.Data.ConnectionState.Open)
{
connection.Open();
}
transaction = connection.BeginTransaction();
result = Process(connection, inOut);
transaction.Commit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
transaction.Rollback();
} finally {
if (connection != null)
{
connection.Close();
}
}
return result;
}
protected abstract DBLogicResult Process(NpgsqlConnection conn, DBLogicInput InOuT);
}
The error exists after the debugger hits the code connection.Open();.
Should I add a web services to connect the postgres to my android app built in xamarin forms?
I am only a beginner in Xamarin Forms. I am just trying to create a self application. And need a little help for me to learn a new platform in programming.
Thank you and Regards,
How to fix it?

Well, I think I am doing it wrong.
Maybe the Right way to Connect the PostgreSQL is to have a WEB API.
Calling that web API to the Xamarin forms.
I really don't know if it is correct, but I will give it a try.
I will update the correct answer after I finish the development of that WEB API so that other beginners will found this answer helpful.

Related

NPoco and PostgreSQL: PostgresException: 53300: sorry, too many clients already

NPoco and PostgreSQL: PostgresException: 53300: sorry, too many clients already
I'm getting this error when I browse my own website allverse.co for a while. Here's the project: https://github.com/claysmith/allverse
and typical NPoco connection code in each Controller...
private IDatabase _db = new Database(new NpgsqlConnection(Startup.Configuration["PostgresConn"]), DatabaseType.PostgreSQL, NpgsqlFactory.Instance);
private IDatabase GetDB()
{
return _db;
}
public SomeFunc()
{
using(IDatabase db = GetDB())
{
try
{
article.id = (long)db.Insert(article);
}
catch(Exception ex)
{
string m = ex.Message;
string im = ex.InnerException.ToString();
}
}
}
Do I need to increase my postgresql connections or am I not closing connections somewhere? Thanks.

Azure Mobile Apps Offline Client Throws NotSupportedException on Query

I have a Azure Mobile Apps Xamarin.Forms PCL client and have Offline Sync enabled. I tried to Pull data from my backend and afterwards query data from the offline storage with a Where clause. That throws the following exception and I don't know why.
Sync error: 'fahrerinfo.Imei.Equals("02032032030232")' is not supported in a 'Where' Mobile Services query expression.
public async Task SyncAsync()
{
ReadOnlyCollection<MobileServiceTableOperationError> syncErrors = null;
try
{
await OfflineSyncStoreManager.Instance.TruckFahrerTable.PullAsync("allTruckFahrerItems",
OfflineSyncStoreManager.Instance.TruckFahrerTable.CreateQuery());
Debug.WriteLine("SyncAsync: PUSH/PULL completed.");
}
catch (MobileServicePushFailedException e)
{
Debug.WriteLine("SyncAsync: PUSH failed.");
Debug.WriteLine(e.Message);
}
catch (Exception e)
{
Debug.WriteLine("SyncAsync: PUSH/PULL failed.");
Debug.WriteLine(e.Message);
//Debugger.Break();
}
}
public async Task<ObservableCollection<TruckFahrer>> GetTruckFaherAsync(bool syncItems)
{
try
{
if (syncItems)
{
await OfflineSyncStoreManager.Instance.SyncAsync().ConfigureAwait(false);
}
var deviceInfo = DependencyService.Get<IDeviceInfo>().GetPhoneInfo();
var imeiString = deviceInfo[trucker_rolsped.PhoneInfo.PhoneInfo.ImeiKey];
var imei = imeiString.Equals("000000000000000") ? deviceInfo[trucker_rolsped.PhoneInfo.PhoneInfo.IdKey] : imeiString;
IEnumerable<TruckFahrer> items =
await OfflineSyncStoreManager.Instance.TruckFahrerTable
//.Where(fahrerinfo => fahrerinfo.Imei.Equals(imei)) TODO: Why does that throw an exception???
.ToEnumerableAsync();
// TODO: Because above does not work
items = items.Where(fahrer => fahrer.Imei.Equals(imei));
return new ObservableCollection<TruckFahrer>(items);
}
catch (MobileServiceInvalidOperationException msioe)
{
Debug.WriteLine(#"Invalid sync operation: {0}", msioe.Message);
Debugger.Break();
}
catch (Exception e)
{
Debug.WriteLine(#"Sync error: {0}", e.Message);
Debugger.Break();
}
return null;
}
Thanks for any hint,
Eric
Are you a Java developer too? I'm and had this issue because in Java we need to compare strings with String#equals method, haha.
For some reason MobileServices doesn't allow us to use Equals in this situation.
To fix your problem, use == instead. As you can see here C# difference between == and Equals() both have the same effect in this case.
Where(fahrerinfo => fahrerinfo.Imei == imei)

Write to Event Log - The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security."

I'am trying to write some messages to Windows Event log.
The (security) exception will be thrown when calling function "SourceExists()".
private bool CheckIfEventLogSourceExits()
{
try
{
if (!EventLog.SourceExists(this.BaseEventLog))
{
return false;
}
return true;
}
catch (System.Security.SecurityException)
{
return false;
}
}
All answers to this question are explaining how you can MANUALLY resolve issue.
Like here: Stackoverflow Thread. Solution would be changing some registry keys
But you can't expect that everyone who consumes your application is aware of these changes.
So my question is, how can we solve this issue programmatically?
Below my code:
try
{
string sLog = "Application";
if (CheckIfEventLogSourceExits())
{
EventLog.CreateEventSource(this.BaseEventLog, sLog);
}
EventLog.WriteEntry(this.BaseEventLog, message, eventLogEntryType);
}
catch (Exception ex)
{
ex.Source = "WriteToEventLog";
throw ex;
}
I know it's too late for this posting, but the answer, I found from similar experience, is that the service you're running under doesn't have administrative rights to the machine and, thus, can't write to the logs.
It's easy enough to figure out if an app is being run under admin rights. You can add something like this to your code with a message box advising the user to run "admin".
private void GetServicePermissionLevel()
{
bool bAdmin = false;
try {
SecurityIdentifier sidAdmin = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
AppDomain myDomain = Thread.GetDomain();
myDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal myPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal;
if (myPrincipal.IsInRole(sidAdmin)) {
bAdmin = true;
} else {
bAdmin = false;
}
} catch (Exception ex) {
throw new Exception("Error in GetServicePermissionlevel(): " + ex.Message + " - " + ex.StackTrace);
} finally {
_ServiceRunAsAdmin = bAdmin;
}
}

A network related error or instance-specific error occured while establishing a connection to sql server

This is the error which arises when I tried to debug an application under Visual C# 2010
I write that code to retrieve some rows from a database table, I already attached the two well known databases Pubs and Northwind to the db explorer, but the error remains
class Author
{
SqlConnection _pubConnection;
string _connString;
public Author()
{
_connString = "Data Source=./INSTANCE2;Initial Catalog=pubs;Integrated Security=True";
_pubConnection = new SqlConnection();
_pubConnection.ConnectionString = _connString;
}
public int CountAuthors()
{
try
{
SqlCommand pubCommand = new SqlCommand();
pubCommand.Connection = _pubConnection;
pubCommand.CommandText = "Select Count(au_id) from authors";
_pubConnection.Open();
return (int)pubCommand.ExecuteScalar();
}
catch (SqlException ex)
{
throw ex;
}
finally
{
if (_pubConnection != null)
{
_pubConnection.Close();
}
}
}
}
static void Main(string[] args)
{
try
{
Author author = new Author();
Console.WriteLine(author.CountAuthors());
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
the Connection string isn't ok , i correct it and it works fine

Error in ExecuteReader

I am getting the following error message:
System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is Closed.
And here is my code:
public IDataReader ExecuteReader()
{
IDataReader reader = null;
try
{
this.Open();
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
if (handleErrors)
strLastError = ex.Message;
else
throw;
}
catch
{
throw;
}
return reader;
}
Does anyone know how I can resolve this?
The Connection object that your SQLCommand is attached to has not been opened. You must open the connection before you can query.
Something like this:
private static void OpenSqlConnection(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
var cmd = connection.CreateCommand();
// Do your command access here.
}
}