Xamarin Forms Azure SQL connection is not responding - sql-server

I have a xamarin project working with azure sql database. It was working fine till today but I had to change my db and all server. From now whenever i want to open my connection app freeze and says is not responding. I tried to change my connection string but as I said it used to works fine. Here is my codes;
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App1.MainPage">
<StackLayout>
<Button Text="Check Conn" Clicked="Button_Clicked"></Button>
</StackLayout>
</ContentPage>
MainPage.xaml.cs [sqlconn is proper its for an example]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using Xamarin.Forms;
namespace App1
{
public partial class MainPage : ContentPage
{
SqlConnection sqlConnection;
public MainPage()
{
InitializeComponent();
string dbname = "dbname";
string srvrname = "servrnm";
string username = "username";
string password = "password";
string sqlconn = $"Data Source={srvrname}.database.windows.net;Initial Catalog={dbname};User ID={username};Password={password}" ;
sqlConnection = new SqlConnection(sqlconn);
}
private async void Button_Clicked(object sender, EventArgs e)
{
try
{
sqlConnection.Open();
await App.Current.MainPage.DisplayAlert("ALERT", "CONNECTION OPENED", "Ok");
sqlConnection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
}
screenshots

Related

xamarin.forms: retrieving existing data from .db file

In Xamarin Forms 4.3, I'm following this "Local Databases" doc: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/data/databases
This doc explains how to create and use a new sqlite db, but how do I go about in loading and displaying data in an existing .db file with the end purpose of transferring it into a new local sqlite database?
using SQLite;
namespace TruckExample.Models
{
public class Truck
{
[PrimaryKey, AutoIncrement]
public int TruckNo { get; set; }
public string TruckName { get; set; }
}
}
//////////////////////////////////////////////
using System.Collections.Generic;
using System.Threading.Tasks;
using SQLite;
using TruckExample.Models;
namespace TruckExample.Data
{
public class TruckDatabase
{
readonly SQLiteAsyncConnection _database;
public TruckDatabase(string dbPath)
{
_database = new SQLiteAsyncConnection(dbPath);
_database.CreateTableAsync<Truck>().Wait();
}
public Task<List<Truck>> GetTrucksAsync()
{
return _database.Table<Truck>().ToListAsync();
}
}
}
////////////////////////////////////////////////
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using TruckExample.Data;
using System.IO;
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace TruckExample
{
public partial class App : Application
{
static TruckDatabase database;
public static TruckDatabase Database
{
get
{
if(database == null)
{
database = new TruckDatabase(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Truck.db"));
}
return database;
}
}
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
}
}
}
/////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace TruckExample
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainPage : ContentPage
{
public MainPage ()
{
InitializeComponent ();
}
protected override async void OnAppearing()
{
base.OnAppearing();
listView.ItemsSource = await App.Database.GetTrucksAsync();
Debug.Write(App.Database.GetTrucksAsync());
}
}
}
For others, helpful resources:
Implementation by Hameed Kunkanoor: "Creating a sqlite databse and storing your data in your android and ios application in Xamarin Forms" https://medium.com/#hameedkunkanoor/creating-a-sqlite-databse-and-storing-your-data-in-your-android-and-ios-application-in-xamarin-2ebaa79cdff0
(Refer to his git if needed)
Explanation/response by Matthewrdev: Use a local database in Xamarin
To improve the implementation -- Brandon Minnick: "Xamarin: Efficiently Using a SQLite Database" https://codetraveler.io/2019/11/26/efficiently-initializing-sqlite-database/

INSERT a record in a Local SQL Server database and app.config

I am trying to insert a record into the Users table with the C# code below. This is a Windows Forms project with app.config and the the records don't seem to be added to the database as intended. Any idea why?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace DemoDBConnection
{
public partial class RegisterUser : Form
{
SqlConnection connection =
new SqlConnection(ConfigurationManager.ConnectionStrings
["DemoDBConnection"].ConnectionString);
public RegisterUser()
{
InitializeComponent();
}
public void AuthenticateUser()
{
try
{
string insertQuery =
"INSERT INTO Users (Username,Password) VALUES ('" +
this.txtUsername.Text + "','" +
this.txtPassword.Text + "')";
SqlCommand sqc = new SqlCommand(insertQuery, connection);
connection.Open();
sqc.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Record Added Successfully");
}
catch (Exception ex)
{
MessageBox.Show("Record Can Not Successfully" + ex.Message);
}
}
private void btnRegister_Click(object sender, EventArgs e)
{
AuthenticateUser();
}
}
My app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="DemoDBConnection"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\App_Data\DemoDB.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>

Need to click on a button in iFrame page

I am trying to click on "btnPunch". This button is located in an iFrame. I am unable to make this work. I have used the Selenium IDE to record this button being clicked and created a DLL that also runs this process in NUnit without a problem. Any help would be appreciated after three months of working on this.
Thank you
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using NUnit.Framework;
using Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium;
namespace TimeClockEntry
{
public partial class PNow : Form
{
IWebDriver driver = new InternetExplorerDriver();
//driver = new InternetExplorerDriver();
//private ISelenium selenium;
//private StringBuilder verificationErrors;
//public void SetupTest()
//{
// selenium = new DefaultSelenium("localhost", 4444, "*chrome", "https://ew23.ultipro.com/");
// selenium.Start();
// verificationErrors = new StringBuilder();
//}
int linkcount = 0;
string userName;
string passWord;
public PNow()
{
InitializeComponent();
webBrowser1.Navigate("https://ew23.ultipro.com/login.aspx");
}
private void PNow_Load(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Normal;
userName = Properties.Settings.Default.userName;
passWord = Properties.Settings.Default.passWord;
}
private void PNow_FormClosed(object sender, FormClosedEventArgs e)
{
this.Hide();
welcome f1 = new welcome();
f1.ShowDialog();
this.Close();
}
protected override void OnLostFocus(EventArgs e)
{
base.OnLostFocus(e);
this.Focus();
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
linkcount++;
if (linkcount == 1)
{
webBrowser1.Document.GetElementById("ctl00_Content_Login1_UserName").SetAttribute("value", userName);
webBrowser1.Document.GetElementById("ctl00_Content_Login1_Password").SetAttribute("value", passWord);
webBrowser1.Document.GetElementById("ctl00_Content_Login1_LoginButton").InvokeMember("click");
}
if (linkcount == 2)
{
HtmlElement link = (from HtmlElement elem in webBrowser1.Document.GetElementsByTagName("a")
where elem.InnerHtml == "Time Clock Entry"
select elem).ElementAt(0);
link.InvokeMember("Click");
}
if (linkcount == 3)
{
// driver.FindElement(By.Id("btnPunch")).Click();
webBrowser1.Document.GetElementById("ctl00_Content_lnkLogout").InvokeMember("click");
this.Close();
}
}
}
}
You can try this also:-
if (linkcount == 3)
{
WebElement frameSwitch = driver.findElement(By.xpath("Xpath of iframe")); //Frame Xpath
driver.switchTo().frame(frameSwitch);
driver.FindElement(By.Id("btnPunch")).Click();
webBrowser1.Document.GetElementById("ctl00_Content_lnkLogout").InvokeMember("click");
driver.switchTo().defaultContent();
this.Close();
}
Try this.
if (linkcount == 3)
{
//get back to basic html source.
driver.SwitchTo().DefaultContent();
//switch to new frame
driver.SwitchTo().Frame("<FRAME NAME OR ID>");
driver.FindElement(By.Id("btnPunch")).Click();
}

Connection string. Cannot implicitly convert 'String' to 'System.Data.SqlClient.SqlConnection'

I'm getting that error in title.
For my
cmd.Connection = Conn;
I have this
public string Conn = connection.getConnection();
I'm using a windows application, how do I fix this?
Here is my complete code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication3
{
public partial class Room : Form
{
public SqlDataReader re;
public string Conn = connection.getConnection();
public Room()
{
InitializeComponent();
}
private void Room_Load(object sender, EventArgs e)
{
..
..
..
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (textBox1.Text.Length != 0 && textBox2.Text.Length != 0)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "insertToRoom";
cmd.Parameters.AddWithValue("#room_name", textBox1);
cmd.Parameters.AddWithValue("#room_rate", textBox2);
cmd.ExecuteNonQuery();
}
else
{
MessageBox.Show("Please fill in all the textbox.", "Wrong Input", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Try this way. First get the connection string from web.conf or app.conf and then create a sqlconnection to assign to sqlcommand.
var connectionString =
ConfigurationManager.ConnectionStrings["NameofConstringFromWebconfig"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.Connection =new SqlConnection(connectionString);

How set EnqueueCallBack to my generic callback

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsistec.Domain;
using Microsistec.Client;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using Microsistec.Tools;
using System.Json;
using Microsistec.SystemConfig;
using System.Threading;
using Microsoft.Silverlight.Testing;
namespace Test
{
[TestClass]
public class SampleTest : SilverlightTest
{
[TestMethod, Asynchronous]
public void login()
{
List<PostData> data = new List<PostData>();
data.Add(new PostData("email", "xxx"));
data.Add(new PostData("password", MD5.GetHashString("xxx")));
WebClient.sendData(Config.DataServerURL + "/user/login", data, LoginCallBack);
EnqueueCallback(?????????);
EnqueueTestComplete();
}
[Asynchronous]
public void LoginCallBack(object sender, System.Net.UploadStringCompletedEventArgs e)
{
string json = Microsistec.Client.WebClient.ProcessResult(e);
var result = JsonArray.Parse(json);
Assert.Equals("1", result["value"].ToString());
TestComplete();
}
}
Im tring to set ???????? value but my callback is generic, it is setup on my WebClient .SendData, how i implement my EnqueueCallback to a my already functio LoginCallBack???
You have to take a different approach to make this work. Why do you want to enqueue LoginCallBack? It would get called asynchronously when sendData has ended, would it not?
Also, I see no point in having a TestComplete() in LoginCallBack and EnqueueTestComplete() in login. Would this not work:
[TestClass]
public class SampleTest : SilverlightTest
{
[TestMethod, Asynchronous]
public void login()
{
List<PostData> data = new List<PostData>();
data.Add(new PostData("email", "xxx"));
data.Add(new PostData("password", MD5.GetHashString("xxx")));
WebClient.sendData(Config.DataServerURL + "/user/login", data, LoginCallBack);
}
[Asynchronous]
public void LoginCallBack(object sender, System.Net.UploadStringCompletedEventArgs e)
{
string json = Microsistec.Client.WebClient.ProcessResult(e);
var result = JsonArray.Parse(json);
Assert.Equals("1", result["value"].ToString());
TestComplete();
}
}
I'm unsure of how LoginCallback gets called but if you make sure that that happens it should make the test pass!

Resources