Asynchronous , Async Await - asynchronous

I have list of sensor details and i need to get configuration setting for each sensor and apply some business logic. I want to do Aynchrosnously, like each sensor will call the same method and execute its logic at the same time.I tried with Async and await and below is sample. Please let me know, if the below will help to execute each sensor execute asynchronously.
public static async Task GetSensor()
{
List<SensorMaster> sensorAddress = GetSensorService();
foreach (SensorMaster sensorInfo in sensorAddress)
{
await ParseSensor(sensorInfo);
}
}
private static async Task ParseSensor(SensorMaster senInfo)
{
List<Sensor> sTestdownTime = await GetTestDownTime(senInfo);
if (DateTime.Parse(sTestdownTime[0].LastHeartBeatAt.ToString()).Year > 1900)
{
CreateEvent(senInfo, sTestdownTime);
}
}
public static async Task<List<Sensor>> GetTestDownTime(SensorMaster senInfo)
{
List<Sensor> lstSensor = new List<Sensor>();
var connectionString = "Data Source=xxxx;Initial Catalog=xx;persist security info=True;User ID=xx;Password=xxx;";
var asyncConnectionString = new SqlConnectionStringBuilder(connectionString) { AsynchronousProcessing = true }.ToString();
using (var cn = new SqlConnection(asyncConnectionString))
{
cn.Open();
SqlCommand cmd = new SqlCommand("SetingSp", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#StationType", senInfo.SensorName));
cmd.Parameters.Add(new SqlParameter("#ThresholdValue", senInfo.SensorThreshold));
using (SqlDataReader dr = await cmd.ExecuteReaderAsync())
{
if (dr.HasRows)
{
while (dr.Read())
{
Sensor cpData = new Sensor();
cpData.SensorName = dr["SensorName"].ToString();
cpData.LastHeartBeatAt = Convert.ToDateTime(dr["LastTimeStamp"]);
lstSensor.Add(cpData);
}
}
}
return lstSensor;
}
}

Yes, they will execute asynchronously. But not in parallel. And I don't think you should even try to make it parallel unless you have a very clear performance problem.
Going parallel (with for example Parallel.ForEach()) would open many SqlConnections at once. Unclear on what kind of system you are running, and what would be expected.

Related

Application is not working when using SQlite databse in windows phone 8

I developed my first application in windows phone 8.1.It is working fine in my local emulator and device but whenever i upload the app in store it is not working.whenever I open the app it is suddenly come back.I used the SQlite database in my application.When I am not using the Sqlite database it is working fine(I uploaded in beta).Please any one help me solve from this issue.
Thank you in advance
sqlite code:
public async void createdatabase()
{
SQLiteConnectionString c = new SQLiteConnectionString(System.IO.Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "newDB.db"), true);
var conn = new SQLiteAsyncConnection(c.DatabasePath);
await conn.CreateTableAsync<Operators>();
}
public async void Drop()
{
SQLiteConnectionString c = new SQLiteConnectionString(System.IO.Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "newDB.db"), true);
using (var dbConn = new SQLiteConnection(c.DatabasePath))
{
SQLiteCommand cmd = new SQLiteCommand(dbConn);
cmd.CommandText = "DROP TABLE IF EXISTS Operators";
int response = cmd.ExecuteNonQuery();
}
public async void insert()
{
rechargeOperator1.Items.Clear();
rechargeCircles1.Items.Clear();
SQLiteConnectionString c = new SQLiteConnectionString(System.IO.Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "newDB.db"), true);
var conn = new SQLiteAsyncConnection(c.DatabasePath);
var client = new pavandatabase.JsonWebClient();
var resp1 = await client.DoRequestAsync(Url.weburl + "getRechargeCircleList");
string result1 = resp1.ReadToEnd();
JArray jsonArray = JArray.Parse(result1);
for (int j = 0; j < jsonArray.Count; j++)
{
JObject jobj = (JObject)jsonArray[j];
string id = (string)jobj["CircleID"];
string statename = (string)jobj["CircleName"];
//circles combobox......
rechargeCircles1.Items.Add(statename);
Operators op = new Operators();
op.Operatorid = int.Parse(OperatorID);
op.Operatorname = Operator;
op.servicetypeid = int.Parse(ServiceTypeID);
await conn.InsertAsync(op);
}
Try to put the break points on the first line of your application and keep on pressing f10 and see at which line it com out and post that line.
Hope it will help you to get the solution.
Thanks,

ASP.NET & SQL Server : Incorrect syntax near '?'

I am receiving an error
Incorrect syntax near ?
when trying to use a update query function. The code is from SagePay http://www.sagepay.co.uk/file/12136/download-document/DotNetkit%201.2.6.7%20-%202014-08-14.zip?token=BJFwtM7qNnnm5ZCc_l_dOhq4INB0cQTPCxCd5JOpeh4 and relates to their server InFrame implementation.
As far as I can see the order is being passed correctly, and the list of fields, match the database, just not understanding why I am seeing this error. The code was originally created for MySQL but have had to adapt to SQL Server.
I've tried debugging, but cannot actually see what is being committed to the SQL Server from cmd.ExecuteNonQuery(); any help would be much appreciated, here is the code:
private static readonly List<String> FieldNames = new List<String>
{
VendorTxCodeField, AddressResultField, AddressStatusField, AmountField, AvsCv2Field, BankAuthCodeField, BasketField,
BillingFirstnamesField, BillingSurnameField, BillingPhoneField, BillingAddress1Field, BillingAddress2Field, BillingCityField,
BillingPostCodeField, BillingStateField, BillingCountryField, DeclineCodeField, DeliveryFirstnamesField, DeliverySurnameField, DeliveryPhoneField,
DeliveryAddress1Field, DeliveryAddress2Field, DeliveryCityField, DeliveryPostCodeField, DeliveryStateField, DeliveryCountryField,
CapturedAmountField, CardTypeField, CavvField, CurrencyField, CustomerEmailField, Cv2ResultField, ExpiryDateField, FraudResponseField,
GiftAidField, Last4DigitsField, LastUpdatedField, PayerIdField, PayerStatusField, PostCodeResultField,
RelatedVendorTxCodeField, SecurityKeyField, StatusField, StatusMessageField, SurchargeField, ThreeDSecureStatusField,
TransactionTypeField, TxAuthNoField, TokenIdField, VpsTxIdField
};
public static bool UpdateOrder(Order order, string vendorTxCode)
{
var result = false;
SqlConnection conn = null;
try
{
conn = new SqlConnection(ConnectionString);
conn.Open();
var cmd = new SqlCommand
{
Connection = conn, CommandText = "UPDATE Orders SET " + string.Join(",", FieldNames.Select(field => field + "=?" + field).ToList()) + " WHERE " + VendorTxCodeField + " =?" + VendorTxCodeField
};
cmd.Prepare();
AddOrderParameters(cmd, order);
cmd.ExecuteNonQuery();
result = true;
}
catch (SqlException ex)
{
Console.WriteLine("Error: {0}", ex);
}
finally
{
if (conn != null)
{
conn.Close();
}
}
return result;
}
private static void AddOrderParameters(SqlCommand command, Order order)
{
command.Parameters.AddWithValue(VendorTxCodeField, order.VendorTxCode);
command.Parameters.AddWithValue(AddressResultField, order.AddressResult);
command.Parameters.AddWithValue(AddressStatusField, order.AddressStatus);
command.Parameters.AddWithValue(AmountField, order.Amount);
command.Parameters.AddWithValue(AvsCv2Field, order.AvsCv2);
command.Parameters.AddWithValue(BankAuthCodeField, order.BankAuthCode);
command.Parameters.AddWithValue(BasketField, order.Basket);
command.Parameters.AddWithValue(BillingAddress1Field, order.BillingAddress1);
command.Parameters.AddWithValue(BillingAddress2Field, order.BillingAddress2);
command.Parameters.AddWithValue(BillingCityField, order.BillingCity);
command.Parameters.AddWithValue(BillingCountryField, order.BillingCountry);
command.Parameters.AddWithValue(BillingFirstnamesField, order.BillingFirstnames);
command.Parameters.AddWithValue(BillingPhoneField, order.BillingPhone);
command.Parameters.AddWithValue(BillingPostCodeField, order.BillingPostCode);
command.Parameters.AddWithValue(BillingStateField, order.BillingState);
command.Parameters.AddWithValue(BillingSurnameField, order.BillingSurname);
command.Parameters.AddWithValue(CapturedAmountField, order.CapturedAmount);
command.Parameters.AddWithValue(CardTypeField, order.CardType);
command.Parameters.AddWithValue(CavvField, order.Cavv);
command.Parameters.AddWithValue(CurrencyField, order.Currency);
command.Parameters.AddWithValue(CustomerEmailField, order.CustomerEmail);
command.Parameters.AddWithValue(Cv2ResultField, order.Cv2Result);
command.Parameters.AddWithValue(DeclineCodeField, order.DeclineCode);
command.Parameters.AddWithValue(DeliveryAddress1Field, order.DeliveryAddress1);
command.Parameters.AddWithValue(DeliveryAddress2Field, order.DeliveryAddress2);
command.Parameters.AddWithValue(DeliveryCityField, order.DeliveryCity);
command.Parameters.AddWithValue(DeliveryCountryField, order.DeliveryCountry);
command.Parameters.AddWithValue(DeliveryFirstnamesField, order.DeliveryFirstnames);
command.Parameters.AddWithValue(DeliveryPhoneField, order.DeliveryPhone);
command.Parameters.AddWithValue(DeliveryPostCodeField, order.DeliveryPostCode);
command.Parameters.AddWithValue(DeliveryStateField, order.DeliveryState);
command.Parameters.AddWithValue(DeliverySurnameField, order.DeliverySurname);
command.Parameters.AddWithValue(ExpiryDateField, order.ExpiryDate);
command.Parameters.AddWithValue(FraudResponseField, order.FraudResponse);
command.Parameters.AddWithValue(GiftAidField, order.GiftAid);
command.Parameters.AddWithValue(Last4DigitsField, order.Last4Digits);
command.Parameters.AddWithValue(LastUpdatedField, order.LastUpdated);
command.Parameters.AddWithValue(PayerIdField, order.PayerId);
command.Parameters.AddWithValue(PayerStatusField, order.PayerStatus);
command.Parameters.AddWithValue(PostCodeResultField, order.PostCodeResult);
command.Parameters.AddWithValue(RelatedVendorTxCodeField, order.RelatedVendorTxCode);
command.Parameters.AddWithValue(SecurityKeyField, order.SecurityKey);
command.Parameters.AddWithValue(StatusField, order.Status);
command.Parameters.AddWithValue(StatusMessageField, order.StatusMessage);
command.Parameters.AddWithValue(SurchargeField, order.Surcharge);
command.Parameters.AddWithValue(ThreeDSecureStatusField, order.ThreeDSecureStatus);
command.Parameters.AddWithValue(TokenIdField, order.TokenId);
command.Parameters.AddWithValue(TransactionTypeField, order.TransactionType);
command.Parameters.AddWithValue(TxAuthNoField, order.TxAuthNo);
command.Parameters.AddWithValue(VpsTxIdField, order.VpsTxId);
}
You have to use # for sql-parameters. Maybe this fixes your issue although i must admit that i don't understand the query because the column-names are the same as the values. However ...
string sql = #"UPDATE Orders SET {0}
Where {1}=#{1};";
sql = string.Format(sql
, string.Join(",", FieldNames.Select(field => string.Format("{0}=#{0}", field)))
, VendorTxCodeField);
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
for (int i = 0; i < FieldNames.Count; i++)
{
cmd.Parameters.AddWithValue(FieldNames[i], FieldNames[i]);
}
// open connection and execute the command...
}

Xamarin.Forms using SQLite.Net.Async

I have followed the instructions here http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/databases/ - to connect to the SQLite database synchronously.
public SQLiteConnection GetConnection()
{
var dbFilname = "localDB.db3";
string docsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(docsPath, dbFilname);
var plat = new SQLitePlatformAndroid();
var conn = new SQLiteConnection(plat, path);
return conn;
}
I want to change it to an asynchronous connection (SQLiteAsyncConnection) but can't get it to work.
According to the instructions here - https://components.xamarin.com/gettingstarted/sqlite-net -it just needs the path as a parameter
var conn = new SQLiteAsyncConnection(path);
that doesn't work, the error says that the parameters expected are:
a connection function, a TaskScheduler and TaskCreationOptions
I have no idea what to do and have not been able to find any examples that work.
Thanks in advance
You could simply reuse the GetConnection method you already have and create async connection like this:
var asyncDb = new SQLiteAsyncConnection(() => GetConnection());
Xamarin Platforms Android Config, iOS and WP basicaly equal
public SQLiteAsyncConnection GetConnectionAsync()
{
const string fileName = "MyDB.db3";
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var path = Path.Combine(documentsPath, fileName);
var platform = new SQLitePlatformAndroid();
var param = new SQLiteConnectionString(path, false);
var connection = new SQLiteAsyncConnection(() => new SQLiteConnectionWithLock(platform, param));
return connection;
}

Change this from sync to async webrequests

I ahve been diggin the net for some time now, not finding code examples that help me through my problem.. I have looked at example code but I'm still not "getting" it...
I have read up on,
http://msdn.microsoft.com/en-us/library/aa480507.aspx and
http://msdn.microsoft.com/en-us/library/dd781401.aspx
But I cant seem to get it to work..
Im using HTMLAGILITYPACK
Today I make up to 20 webrequests,
After a request has finished, result is added to dictionary, after that a method searches it for the information, if found the code exits if not it makes another webrequest , until it caps at 20. I need to be able to exit all threads async calls when everything is found.
It goes like this
public void FetchAndParseAllPages()
{
PageFetcher fetcher = new PageFetcher();
for (int i = 0; i < _maxSearchDepth; i += _searchIncrement)
{
string keywordNsearch = _keyword + i;
ParseHtmldocuments(fetcher.GetWebpage(keywordNsearch));
//this checks if the information was found or not, if
//found stop exit and add to database
if (GetPostion() != 201)
{ //ADD DATA TO DATABASE
InsertRankingData(DocParser.GetSearchResults(), _theSearchedKeyword);
return;
}
}
}
This is inside the class that fetches the page
public HtmlDocument GetWebpage(string urlToParse)
{
System.Net.ServicePointManager.Expect100Continue = false;
HtmlWeb htmlweb = new HtmlWeb();
htmlweb.PreRequest = new HtmlAgilityPack.HtmlWeb.PreRequestHandler(OnPreRequest);
HtmlDocument htmldoc = htmlweb.Load(#"urlToParse", "38.69.197.71", 45623, "PORXYUSER", "PROXYPASSWORD");
return htmldoc;
}
public bool OnPreRequest(HttpWebRequest request)
{
// request.UserAgent = RandomUseragent();
request.KeepAlive = false;
request.Timeout = 100000;
request.ReadWriteTimeout = 1000000;
request.ProtocolVersion = HttpVersion.Version10;
return true; // ok, go on
}
How can I make this async and make it really quick with threads? Or should i even use threads when doing it async?
Okay I solved it! At least I think so! Execution time went down to around seven seconds. It took me about 30 secs to do that without async.
Here my code for future reference. EDIT I used a console project to test the code. Also I'm using html agilitypack. This is my way of doing it, any tips on how to further optimize this would be cool to see.
public delegate HtmlDocument FetchPageDelegate(string url);
static void Main(string[] args)
{
System.Net.ServicePointManager.DefaultConnectionLimit = 10;
FetchPageDelegate del = new FetchPageDelegate(FetchPage);
List<HtmlDocument> htmllist = new List<HtmlDocument>();
List<IAsyncResult> results = new List<IAsyncResult>();
List<WaitHandle> waitHandles = new List<WaitHandle>();
DateTime start = DateTime.Now;
for(int i = 0; i < 200; i += 10)
{
string url = #"URLSTOPARSE YOU CHANGE IT HERE READ FROM LIST OR ANYTHING";
IAsyncResult result = del.BeginInvoke(url, null, null);
results.Add(result);
waitHandles.Add(result.AsyncWaitHandle);
}
WaitHandle.WaitAll(waitHandles.ToArray());
foreach (IAsyncResult async in results)
{
FetchPageDelegate delle = (async as AsyncResult).AsyncDelegate as FetchPageDelegate;
htmllist.Add(delle.EndInvoke(async));
}
Console.ReadLine();
}
static HtmlDocument FetchPage(string url)
{
HtmlWeb htmlweb = new HtmlWeb();
HtmlDocument htmldoc = htmlweb.Load(url);
return htmldoc;
}

How do I check whether a Local Publication exists given the publication name and how do I delete it along with everything associated with it?

I'm working in ASP .NET and I need to do a couple of things:
Check whether the Publication I'm about to create already exists.
If it does, delete it along with EVERYTHING related to it (jobs, etc. including anything at the subscriber side).
I started with this:
public static bool PublicationExists(string server)
{
string finalConnString = Properties.Settings.Default.rawConnectionString.Replace("<<DATA_SOURCE>>", server).Replace("<<INITIAL_CATALOG>>", "tempdb");
using (var conn = new SqlConnection(finalConnString))
{
using (var cmd = new SqlCommand("what is the query to check whether a publication exists?", conn))
{
conn.Open();
cmd.ExecuteNonQuery();
using (var da = new SqlDataAdapter(cmd))
{
using (var ds = new DataSet())
{
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
return true;
}
return false;
}
}
}
}
}
Now...
If (PublicationExists(server) == true)
{
//I want to delete the publication along with everything associated with it.
}
How would I go about doing this?

Resources