How to make oledb query asychronous - c#-5.0

I'm having problems with this query, it takes a long time to run and is timing out. I wanted to try to make it async but I can't find a good example that's close to what I'm trying to do.
Below is what I've tried, it starts but does nothing. This is inside a WinForm project.
namespace access_db_csharp
{
public partial class Form1 : Form
{
string SQL = "";
public Form1()
{
InitializeComponent();
textBox1.Text = "Select Project, Request, Release, TestName, AssignmentNumber, Formulation, Container, Closure FROM tblWtLossBottDropResults";
textBox2.Text = "Where Container LIKE '%2700-305%'";
dataGridView1.Focus();
}
OleDbConnection con=new OleDbConnection ();
OleDbCommand cmd=new OleDbCommand ();
string connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=K:\R&D Dept\Development Lab\DLab Databases and Add Ins\DLab Results Database\DLab Results Individual Tables.accdb;Jet OLEDB:Database Password='roscoe'";
private async void button1_Click(object sender, EventArgs e)
{
Task<DataTable> task = new Task<DataTable>(RunQuery);
task.Start();
}
private DataTable RunQuery()
{
if (checkBox1.Checked == true)
{
SQL = textBox1.Text + " " + textBox2.Text;
}
else
{
SQL = textBox1.Text;
}
OleDbConnection con = new OleDbConnection(connectionstring);
OleDbCommand cmd = new OleDbCommand(SQL, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable tblWtLossBottDropResults = new DataTable();
da.Fill(tblWtLossBottDropResults);
dataGridView1.DataSource = tblWtLossBottDropResults;
//dataGridView1.ColumnCount = 17;
dataGridView1.Columns[0].Name = "Project";
dataGridView1.Columns[1].Name = "Request";
dataGridView1.Columns[2].Name = "Release";
dataGridView1.Columns[3].Name = "TestName";
dataGridView1.Columns[4].Name = "AssignmentNumber";
dataGridView1.Columns[5].Name = "Formulation";
dataGridView1.Columns[6].Name = "Container";
dataGridView1.Columns[7].Name = "Closure";
MessageBox.Show("Done");
int numRows = dataGridView1.RowCount;
label4.Text = "Rows Returned: " + numRows.ToString();
return tblWtLossBottDropResults;
}
private void Form1_Load(object sender, EventArgs e)
{
con.ConnectionString = connectionstring;
con.Open();
}
}
}
Ideally I want to get the data from the query and load it into a datagridview table.

There are a few things you should change:
1. You should not mix UI and non-UI code.
2. You should keep your connection open for the shortest amount of time.
Because the OleDb provider doesn't have asynchronous APIs, your database code will be synchronous:
private DataTable RunQuery(string commandText)
{
using (var connection = new OleDbConnection(connectionstring))
{
using (var command = connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = commandText;
using (var dataAdapter = new OleDbDataAdapter(command))
{
connection.Open();
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
return dataTable;
}
}
}
}
Because it's a Windows Forms application you can use Task.Run to offload that work to the thread pool and free the UI thread:
private async void button1_Click(object sender, EventArgs e)
{
var commandText = checkBox1.Checked
? textBox1.Text + " " + textBox2.Text
: textBox1.Text;
var dataTable = await Task.Run(() => RunQuery(commandText));
/* This should be set on the designer or on the constructor
//dataGridView1.ColumnCount = 17;
dataGridView1.Columns[0].Name = "Project";
dataGridView1.Columns[1].Name = "Request";
dataGridView1.Columns[2].Name = "Release";
dataGridView1.Columns[3].Name = "TestName";
dataGridView1.Columns[4].Name = "AssignmentNumber";
dataGridView1.Columns[5].Name = "Formulation";
dataGridView1.Columns[6].Name = "Container";
dataGridView1.Columns[7].Name = "Closure";
*/
dataGridView1.DataSource = dataTable;
MessageBox.Show("Done");
int numRows = dataGridView1.RowCount;
label4.Text = "Rows Returned: " + numRows.ToString();
}

Related

insert whole list of data into sql database table in xamarin.android

i'm trying to create an application where data in a list must be inserted into a database table at once. I made some research and found out that this is possible using user-defined table types where in c# a datatable is used and passed to a stored procedure that is executed. now my problem is that there are no data tables in Xamarin.Android. so I thought to use a list instead. my idea was to create a list in the application and pass it to the webservice method, and in my webservice method I receive the list and convert it to a datatable then pass it as a parameter to the stored procedure. I wrote the following codes:
in my webservice:
[WebMethod]
public bool insrt_dt(List<Class1> lst)
{
SqlParameter param;
SqlConnection conn = new SqlConnection(new DBConnection().ConnectionString);
DataTable dt = list_to_dt(lst);
SqlCommand cmd = new SqlCommand("Insert_Customers", conn);
cmd.CommandType = CommandType.StoredProcedure;
if (conn.State == System.Data.ConnectionState.Closed)
{
conn.Open();
}
param = new SqlParameter("#tblcustomers", dt);
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
cmd.Parameters.Add(param);
cmd.CommandTimeout = 300;
int a=cmd.ExecuteNonQuery();
if (a > 0)
{
return true;
}
else return false;
}
}
Class1:
public class Class1
{
public int id { get; set; }
public string name { get; set; }
public string country { get; set; }
}
in my Xamarin.Android app
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
Button btn = FindViewById<Button>(Resource.Id.button1);
btn.Click += delegate
{
wr.WebService1 ws = new wr.WebService1();
wr.Class1 class1 = new wr.Class1();
List<wr.Class1> lst = new List<wr.Class1>(){
new wr.Class1() { id = 1, name = "hgf", country = "khg" },
new wr.Class1() { id = 2, name = "hgf", country = "khg"} };
ws.insrt_dt(lst);
ws.insrt_dtCompleted += Ws_insrt_dtCompleted;
};
}
private void Ws_insrt_dtCompleted(object sender, wr.insrt_dtCompletedEventArgs e)
{
bool l = e.Result;
if (l == true)
Toast.MakeText(this, "khh", ToastLength.Long).Show();
else
Toast.MakeText(this, "ijo'pioo", ToastLength.Long).Show();
}
}
but I keep getting this error:
Argument 1: cannot convert from 'System.Collections.Generic.List<app_dt.wr.Class1>' to 'app_dt.wr.Class1[]
so I used these lines instead
new wr.Class1() { id = 1, name = "hgf", country = "khg" },
new wr.Class1() { id = 2, name = "hgf", country = "khg"} };
wr.Class1[] class1s = lst.ToArray();
ws.insrt_dt(class1s);
now I don't get an error, but it doesn't work, I mean why does it say that the webservice method input must be an array and I've created it as a list. any suggestions for this?
As i know, Xamarin do not support System.Data.SqlClient. If you want to use the database for the Xamarin android project, you could use the SQLite.NET.
Install the package from the NuGet.
NuGet: sqlite-net-pcl https://www.nuget.org/packages/sqlite-net-pcl/
For the code sample about how to use the database in Xamarin, you could check the link below. https://learn.microsoft.com/en-us/xamarin/get-started/quickstarts/database?pivots=windows
For Xamarin.Android, you could check the sample code in the link below. https://learn.microsoft.com/en-us/xamarin/android/data-cloud/data-access/using-sqlite-orm

How to unit test a repository and mock db with moq

I am onboarding alone on an existing project that do not have any unit test. My first goal before any refactoring is to cover 100% of the code. I would like to avoid any regression.
I have read how do I mock sqlconnection or should I refactor the code? but my case as you can see below is quite different cause I need to do more than stub simply the sqlConnection. Basically, I need to mock the db. I would like to know the best approach to achieve it.
(By the way, I do not want to use any ORM such as Entity).
Below the code of the repository :
public class HotelRepository : IHotelRepository
{
private readonly IDbConnection _dbConnection;
private readonly ILogService _loggerService;
public HotelRepository(IDbConnection dbConnection, ILogService loggerService)
{
_dbConnection = dbConnection;
_loggerService = loggerService;
}
public HotelDo GetByRid(string rid)
{
return Find(rid).FirstOrDefault();
}
public List<HotelDo> Find(string text)
{
try
{
_dbConnection.Open();
var items = new List<HotelDo>();
using (var command = _dbConnection.CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "dbo.HotelSearchByRidOrName";
command.Parameters.Add(new SqlParameter("#Text", text));
using (var reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
while (reader.Read())
{
items.Add(new HotelDo()
{
Name = SqlExtension.ReaderToStringConverter(reader["Name"]),
Id = SqlExtension.ReaderToIntConverter(reader["Id"]),
Rid = SqlExtension.ReaderToStringConverter(reader["RIDHotel"]),
IdPms = SqlExtension.ReaderToNullableIntConverter(reader["IdPms"]),
LinkResaWeb = SqlExtension.ReaderToStringConverter(reader["LinkResaWeb"]),
LinkPms = SqlExtension.ReaderToStringConverter(reader["LinkPms"]),
IdBrand = SqlExtension.ReaderToNullableIntConverter(reader["IdBrand"]) ?? 0,
IsOnline = SqlExtension.ReaderToBoolConverter(reader["IsOnline"]) ?? false,
CodeCountry = SqlExtension.ReaderToStringConverter(reader["CodeCountry"])
});
}
}
}
return items;
}
catch (Exception e)
{
var errorMessage = $"HotelRepository Find, text {text} ";
_loggerService.Trace(LogSeverity.Error, errorMessage, e);
throw new DalException() { Source = errorMessage, };
}
finally
{
_dbConnection.Close();
}
}
public List<HotelDo> GetAll()
{
try
{
_dbConnection.Open();
var items = new List<HotelDo>();
using (var command = _dbConnection.CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "dbo.HotelGetAll";
using (var reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
while (reader.Read())
{
bool.TryParse(reader["IsOnline"].ToString(), out var isOnline);
items.Add(new HotelDo()
{
Id = SqlExtension.ReaderToIntConverter(reader["Id"]),
Rid = SqlExtension.ReaderToStringConverter(reader["RIDHotel"]),
Name = SqlExtension.ReaderToStringConverter(reader["Name"]),
CodeCountry = SqlExtension.ReaderToStringConverter(reader["CodeCountry"]),
LinkPms = SqlExtension.ReaderToStringConverter(reader["LinkPms"]),
IdPms = SqlExtension.ReaderToNullableIntConverter(reader["IdPms"]),
IdBrand = SqlExtension.ReaderToNullableIntConverter(reader["IdBrand"]) ?? 0,
LinkResaWeb = SqlExtension.ReaderToStringConverter(reader["LinkResaWeb"]),
IsOnline = isOnline
});
}
}
}
return items;
}
catch (Exception e)
{
var errorMessage = $"HotelRepository GetAllHotels";
_loggerService.Trace(LogSeverity.Error, errorMessage, e);
throw new DalException() { Source = errorMessage, };
}
finally
{
_dbConnection.Close();
}
}
}
Thank you for your help
So based on what you've got I've set up a test frame for you to follow. I've removed less important components for breviety.
Before you you jump in I just want to give my 2 cents, if you don't know how to do this sort of thing you seem to be more or less in a junior position or less experiance with C# and also found your self in a more or less mature company that doesn't care about the development deparment, since an uncovered project just get's thrown your way says you don't have alot of resources to go about to imrpove the code base.
Test only the things that have business value (can you put a price on the piece of logic if it brakes)
Delivering stuff faster will make you look better as a programmer (noone in the business gives a damn about test covarage)
Study hard, get your experiance, good reputation and don't be afraid to get the hell out of there as soon as you start getting bored.
Main
void Main()
{
var idIndex = 0;
var ids = new string[] { "1", "2" };
var mockDataReader = new Mock<IDataReader>();
mockDataReader.SetupSequence(x => x.Read()).Returns(true).Returns(true).Returns(false);
mockDataReader.SetupGet(x => x["Id"]).Returns(() => ids[idIndex]).Callback(() => idIndex++);
var mockParameters = new Mock<IDataParameterCollection>();
var mockCommand = new Mock<IDbCommand>();
mockCommand.SetupGet(x => x.Parameters).Returns(mockParameters.Object);
mockCommand.Setup(x => x.ExecuteReader(CommandBehavior.CloseConnection)).Returns(mockDataReader.Object);
var mockConnection = new Mock<IDbConnection>();
mockConnection.Setup(x => x.CreateCommand()).Returns(mockCommand.Object);
var repo = new HotelRepository(mockConnection.Object);
var result = repo.Find("search");
Assert.Equal("1", result[0].Id);
Assert.Equal("2", result[1].Id);
}
Repository
public class HotelRepository
{
private readonly IDbConnection _dbConnection;
public HotelRepository(IDbConnection dbConnection)
{
_dbConnection = dbConnection;
}
public List<Pony> Find(string text)
{
_dbConnection.Open();
var items = new List<Pony>();
using (var command = _dbConnection.CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "dbo.HotelSearchByRidOrName";
command.Parameters.Add(new SqlParameter("#Text", text));
using (var reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
while (reader.Read())
{
items.Add(new Pony
{
Id = reader["Id"].ToString()
});
}
}
}
return items;
}
}
Just a dumb o'l pony
public class Pony {
public string Id { get; set; }
}

Pass field from Droid project to PCL, Xamarin.Forms

I have an app that allows users to log in via facebook, once user enters their credentials - My api request saves the user onto the database and auto-generates a user token(This is unique to each user). In order to display user specific details once user logs in - the token needs to be referenced. I am trying to get this token to the PCL project but it returns null just for the token. When I tried passing another string like name, it passes the correct value. Any help will be much appreciated.Thanks
FacebookRender in droid:
public class FacebookRender : PageRenderer
{
public FacebookRender()
{
CustomerService customerService = new CustomerService();
String error;
var activity = this.Context as Activity;
var auth = new OAuth2Authenticator(
clientId: "",
scope: "",
authorizeUrl: new Uri("https://www.facebook.com/dialog/oauth/"),
redirectUrl: new Uri("https://www.facebook.com/connect/login_success.html")
);
auth.Completed += async (sender, eventArgs) =>
{
try
{
if (eventArgs.IsAuthenticated)
{
await AccountStore.Create().SaveAsync(eventArgs.Account, "FacebookProviderKey");
var accessToken = eventArgs.Account.Properties["access_token"].ToString();
var expiresIn = Convert.ToDouble(eventArgs.Account.Properties["expires_in"]);
var expiryDate = DateTime.Now + TimeSpan.FromSeconds(expiresIn);
var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me?fields=email,first_name,last_name,gender,picture"), null, eventArgs.Account);
var response = await request.GetResponseAsync();
var obj = JObject.Parse(response.GetResponseText());
var id = obj["id"].ToString().Replace("\"", "");
var name = obj["first_name"].ToString().Replace("\"", "");
var surname = obj["last_name"].ToString().Replace("\"", "");
var gender = obj["gender"].ToString().Replace("\"", "");
//var email = obj["email"].ToString().Replace("\"", "");
Customer.Customers cust = new Customer.Customers();
cust.Credentials = new Customer.Credentials();
cust.Name = name;
cust.Surname = surname;
cust.Email = "";
cust.MobilePhone = "";
cust.DOB = DateTime.Now;
cust.Number = "";
cust.City = "";
cust.Region = "";
cust.Country = "";
cust.DeviceToken = "sample";
cust.Credentials.SecretKey = "";
await customerService.AddCustomer(cust);
App.SaveToken(cust.Credentials.Token); - **//This is where I am passing the token**
App.NavigateToProfile(string.Format(name + surname));
}
else
{
App.NavigateToProfile("Invalid Login");
}
}
catch(Exception ex)
{
error = ex.Message;
}
};
activity.StartActivity(auth.GetUI(activity));
}
App.cs
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
}
public static void NavigateToProfile(string message)
{
App.Current.MainPage = (new Profile(message));
}
static string _Token;
public static string Token
{
get { return _Token; }
}
public static void SaveToken(string token)
{
_Token = token;
}
AboutPage.cs - I am passing the token in a label just to see if it's passing
public partial class About : ContentPage
{
private Label _lbltoken;
public About()
{
//InitializeComponent();
Appearing += (object s, EventArgs a) => {
_lbltoken.Text = App.Token;
};
string tk = App.Token;
_lbltoken = new Label()
{
FontSize = 20,
HorizontalOptions = LayoutOptions.CenterAndExpand,
Text = tk,
};
var stack = new StackLayout
{
VerticalOptions = LayoutOptions.StartAndExpand,
Children = { _lbltoken },
};
Content = stack;
}
}
You can use the MessagingCenter.
Messages may be sent as a result like a button click, a system event or some other incident. Subscribers might be listening in order to change the appearance of the user interface, save data or trigger some other operation.
More Info
I don't really now if its good idea use static fields in App class. Xamarin access all fields with service locator, App.Current.[property] I will suggest you try to change these fields to public
string _Token;
public string Token
{
get { return _Token; }
}
public void SaveToken(string token)
{
_Token = token;
}
and use it with App.Current.SaveToken(token) or App.Current.Token

Web Scraping-crawling

private void button2_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
StringBuilder sb = new StringBuilder();
byte[] ResultsBuffer = new byte[8192];
string SearchResults = "http://google.com/search?q=" + textBox2.Text.Trim();//txtKeyWords? Anladigim texte girilen deger
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SearchResults);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
do
{
count = resStream.Read(ResultsBuffer, 0, ResultsBuffer.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(ResultsBuffer, 0, count);
sb.Append(tempString);
}
}
while (count > 0);
string sbb = sb.ToString();
HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();
html.OptionOutputAsXml = true;
html.LoadHtml(sbb);
HtmlNode doc = html.DocumentNode;
StreamWriter sw = File.AppendText("website.txt");
foreach (HtmlNode link in doc.SelectNodes("//a[#href]"))
{
HtmlAttribute att = link.Attributes["href"];
string hrefValue = link.GetAttributeValue("href", string.Empty);
if (!hrefValue.ToString().ToUpper().Contains("GOOGLE") && hrefValue.ToString().Contains("/url?q=") && hrefValue.ToString().ToUpper().Contains("HTTP://"))
{
int index = hrefValue.IndexOf("&");
if (index > 0)
{
hrefValue = hrefValue.Substring(0, index);
listBox1.Items.Add(hrefValue.Replace("/url?q=", ""));
}
}
List<string> values = new List<string>();
string SourceCode = worker.GetSourceCode(SearchResults);
MatchCollection data = Regex.Matches(SourceCode, #"<p>\s*(.+?)\s*</p>", RegexOptions.Singleline);
foreach (Match m in data)
{
string value = m.Groups[1].Value;
value = value.Replace("’", "'").Replace("<strong>", "").Replace("</strong>", "").Replace("Ouml;z", "Ö").Replace("ö", "ö").Replace("ü", "ü").Replace("ç", "ç");
values.Add(value);
sw.Write(value);
}
}
sw.Close(); ;
}
public static string GetSourceCode(string url)
{
HttpWebRequest reg = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)reg.GetResponse();
StreamReader sr = new
StreamReader(resp.GetResponseStream(),System.Text.UTF8Encoding.UTF8);
string SourceCode = sr.ReadToEnd();
sr.Close();
resp.Close();
return SourceCode
Hi for all. I am trying to prepare a Windows Form Application for scraping. I ll enter some expression from my windows Form and search automatically that expressions inside google . Program will show me found links inside a listbox and show that links contains(Letters inside that links) inside a text file. Showing links work fine but program don't record link content inside text file.
I tried debug mode.As a result program didn't enter inside that code block.
foreach(Match m in data)
{
string value = m.Groups[1].Value;
value = value.Replace("’", "'").Replace("<strong>", "").Replace("</strong>", "").Replace("Ouml;z", "Ö").Replace("ö", "ö").Replace("ü", "ü").Replace("ç", "ç");
values.Add(value);
sw.Write(value);
}
I tried showing links code block and recording links content code block seperately.Both of them works fine. when I tried to combine them ı couldn't get a working code.no error but didn't work.Please help.
private void Clicked(object sender, EventArgs e)
{
List<string> values = new List<string>();
string url = textBox1.Text;
string SourceCode = worker.GetSourceCode(url);
MatchCollection data = Regex.Matches(SourceCode, #"<p>\s*(.+?)\s*</p>", RegexOptions.Singleline);
foreach (Match m in data)
{
string value = m.Groups[1].Value;
value = value.Replace("’", "'").Replace("<strong>", "").Replace("</strong>", "").Replace("Ouml;z", "Ö").Replace("ö", "ö").Replace("ü", "ü").Replace("ç", "ç");
values.Add(value);
StreamWriter sw = File.AppendText("website.txt");
sw.Write(value);
sw.Close(); ;
}
}
private void button2_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
StringBuilder sb = new StringBuilder();
byte[] ResultsBuffer = new byte[8192];
string SearchResults = "http://google.com/search?q=" + textBox2.Text.Trim();//txtKeyWords? Anladigim texte girilen deger
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SearchResults);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
do
{
count = resStream.Read(ResultsBuffer, 0, ResultsBuffer.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(ResultsBuffer, 0, count);
sb.Append(tempString);
}
}
while (count > 0);
string sbb = sb.ToString();
HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();
html.OptionOutputAsXml = true;
html.LoadHtml(sbb);
HtmlNode doc = html.DocumentNode;
//StreamWriter sw = File.AppendText("website.txt");
foreach (HtmlNode link in doc.SelectNodes("//a[#href]"))
{
HtmlAttribute att = link.Attributes["href"];
string hrefValue = link.GetAttributeValue("href", string.Empty);
if (!hrefValue.ToString().ToUpper().Contains("GOOGLE") && hrefValue.ToString().Contains("/url?q=") && hrefValue.ToString().ToUpper().Contains("HTTP://"))
{
int index = hrefValue.IndexOf("&");
if (index > 0)
{
hrefValue = hrefValue.Substring(0, index);
hrefValue = hrefValue.Replace("/url?q=", "");
listBox1.Items.Add(hrefValue);
GetData(hrefValue);
}
}
}
}
private void GetData(string url)
{
StreamWriter sw = File.AppendText("website.txt");
List<string> values = new List<string>();
string SourceCode = worker.GetSourceCode(url);
MatchCollection data = Regex.Matches(SourceCode, #"<p>\s*(.+?)\s*</p>", RegexOptions.Singleline);
foreach (Match m in data)
{
string value = m.Groups[1].Value;
value = value.Replace("’", "'").Replace("<strong>", "").Replace("</strong>", "").Replace("Ouml;z", "Ö").Replace("ö", "ö").Replace("ü", "ü").Replace("ç", "ç");
values.Add(value);
sw.Write(value);
}
sw.Close();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
}
}
I finally manage to launch successfully. Here is the answer. Just left a few problems in my answer. They are all about regular expressions. Because websites html codes don't have a standart concept. So it needed to be corrected with regex. When ı complete my project ı ll share my full codes.

Where do you set the OrmLiteConfig.DialectProvider.NamingStrategy in a unit test?

I'm using both ORMLite and Dapper in a project and would like standardized on the naming conventions used by both ORMs. In order to do this I'd like to set the NamingStrategy as such:
OrmLiteConfig.DialectProvider.NamingStrategy = new OrmLiteNamingStrategyBase();
and a unit test to verify
public class BorrowerUnitTests : IDisposable
{
private readonly ServiceStackHost appHost;
public BorrowerUnitTests()
{
//Set ORMLite to work with columns like ColumnLikeThis
// OrmLiteConfig.DialectProvider.NamingStrategy = new OrmLiteNamingStrategyBase();
appHost = new BasicAppHost(typeof(BorrowerServices).Assembly)
{
ConfigureContainer = container =>
{
container.Register<IDbConnectionFactory>(c =>
new OrmLiteConnectionFactory(ConfigUtils.GetConnectionString("LoanOrigination:Default"), PostgreSqlDialect.Provider));
container.RegisterAutoWiredAs<Repository, IRepository>();
container.RegisterAutoWired<BorrowerDomainService>();
}
}
.Init();
}
public void Dispose()
{
appHost.Dispose();
}
[Fact]
public void TestPostMethod()
{
var service = appHost.Container.Resolve<BorrowerServices>();
BorrowerCreate request = new BorrowerCreate();
request.FirstName = "Orm";
request.LastName = "Lite";
request.Email = "ormlite#servicestack.net";
var response = service.Post(request);
Assert.True(response.Id > 0, "Id retured from POST cannot be zero");
}
[Fact]
public void TestGetMethod()
{
var service = appHost.Container.Resolve<BorrowerServices>();
BorrowerGet request = new BorrowerGet();
request.Id = 1;
var response = service.Get(request);
Assert.Equal("ormlite#servicestack.net", response.Email);
}
[Fact]
public void TestPutMethod()
{
var service = appHost.Container.Resolve<BorrowerServices>();
BorrowerUpdate request = new BorrowerUpdate();
request.Id = 5;
request.FirstName = "MyFirstName2";
request.LastName = "MyLastName2";
request.Email = "MyEmail#Example.com";
var response = service.Put(request);
Assert.True(response.FirstName == "MyFirstName2", "FirstName is noth equal");
}
}
No matter where I put the NamingStrategy statement, I get a exception from the DialectProvider property of the OrmLiteConfig class, "You must set the singleton 'OrmLiteConfig.DialectProvider' to use the OrmLiteWriteExtensions"
Where's the proper place to set this property?
Thank you,
Stephen
You can just assign it to the DialectProvider you're using, e.g:
PostgreSqlDialect.Provider.NamingStrategy = new OrmLiteNamingStrategyBase();
The OrmLiteConfig.DialectProvider is a singleton that can either be set manually:
OrmLiteConfig.DialectProvider = PostgreSqlDialect.Provider;
OrmLiteConfig.DialectProvider.NamingStrategy = new OrmLiteNamingStrategyBase();
Or implicitly with the new OrmLiteConnectionFactory() constructor, which to run, needs to resolved from the IOC:
container.Register<IDbConnectionFactory>(c => new OrmLiteConnectionFactory(...));
using (var db = container.Resolve<IDbConnectionFactory>().Open())
{
OrmLiteConfig.DialectProvider.NamingStrategy = new OrmLiteNamingStrategyBase();
}