BackgroundService memory leak SqlDependency - cmd

this is my service code
public class Worker : BackgroundService
{
public bool isRegister { get; set; }
public bool checkIp { get; set; }
public long timePass { get; set; }
public Worker()
{
}
public override Task StartAsync(CancellationToken cancellationToken)
{
return base.StartAsync(cancellationToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
if (isRegister == false)
registerSelect();
if (checkIp == true)
{
checkIp = false;
await SecurityConfig.cacheServices?.BuildServiceProvider()?.GetService<IBlockFirewallIpService>().RegisterInFirewall();
}
timePass += 1000;
if (timePass % 60000 == 0)
await SecurityConfig.cacheServices?.BuildServiceProvider()?.GetService<IBlockFirewallIpService>().RegisterInFirewall();
await Task.Delay(1000, stoppingToken);
}
}
public void registerSelect()
{
isRegister = true;
using (SqlConnection conn = new SqlConnection(GetDbConnection()))
{
conn.Open();
SqlDependency.Start(GetDbConnection());
string commandText = "SELECT [Ip1],[Ip2] ,[Ip3] ,[Ip4] FROM dbo.BlockFirewallIps where IsRead is null";
using (SqlCommand cmd = new SqlCommand(commandText, conn))
{
SqlDependency dependency = new SqlDependency(cmd);
dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
void OnDependencyChange(object sender, SqlNotificationEventArgs e)
{
if (e.Info == SqlNotificationInfo.Insert)
checkIp = true;
SqlDependency temp = sender as SqlDependency;
if (temp != null)
temp.OnChange -= new OnChangeEventHandler(OnDependencyChange);
registerSelect();
}
private string GetDbConnection()
{
return GlobalConfig.Configuration["ConnectionStrings:DefaultConnection"];
}
}
and this is my IBlockFirewallIpService.RegisterInFirewall() code
public async Task RegisterInFirewall()
{
var allBlockIps = await db.BlockFirewallIps.Where(t => t.IsRead == null).ToListAsync();
foreach (var ip in allBlockIps)
{
BanIP("OjeFirTCP" + ip.Ip1 + "_" + ip.Ip2 + "_" + ip.Ip3 + "_" + ip.Ip4, ip.Ip1 + "." + ip.Ip2 + "." + ip.Ip3 + "." + ip.Ip4, "Any", "TCP");
BanIP("OjeFirUDP" + ip.Ip1 + "_" + ip.Ip2 + "_" + ip.Ip3 + "_" + ip.Ip4, ip.Ip1 + "." + ip.Ip2 + "." + ip.Ip3 + "." + ip.Ip4, "Any", "UDP");
ip.IsRead = true;
db.SaveChanges();
}
}
void BanIP(string RuleName, string IPAddress, string Port, string Protocol)
{
if (OperatingSystem.IsWindows())
{
if (!string.IsNullOrEmpty(RuleName) && !string.IsNullOrEmpty(IPAddress) && !string.IsNullOrEmpty(Port) && !string.IsNullOrEmpty(Protocol) && new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
{
using (Process RunCmd = new Process())
{
RunCmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
RunCmd.StartInfo.FileName = "cmd.exe";
RunCmd.StartInfo.Arguments = "/C netsh advfirewall firewall add rule name=\"" + RuleName + "\" dir=in action=block remoteip=" + IPAddress + " remoteport=" + Port + " protocol=" + Protocol;
RunCmd.Start();
}
}
}
}
this is progeram.cs
IHost host = Host.CreateDefaultBuilder(args)
.UseWindowsService(options =>
{
options.ServiceName = "OjeFirewall";
})
.ConfigureServices((hostContext, services) =>
{
GlobalConfig.Configuration = hostContext.Configuration;
services.AddScoped<IHttpContextAccessor, FakeIHttpContextAccessor>();
SecurityConfig.Config(services);
services.AddHostedService<Worker>();
})
.Build();
await host.RunAsync();
this is SecurityConfig.Config codes
services.AddDbContext<SecurityDBContext>(options =>
options.UseSqlServer(GlobalConfig.Configuration["ConnectionStrings:DefaultConnection"],
b => b.UseQuerySplittingBehavior(QuerySplittingBehavior.SingleQuery))
, ServiceLifetime.Singleton
);
services.AddSingleton<IIpLimitationWhiteListService, IpLimitationWhiteListService>();
services.AddSingleton<IIpLimitationBlackListService, IpLimitationBlackListService>();
services.AddSingleton<IFileAccessRoleService, FileAccessRoleService>();
services.AddSingleton<IRoleService, RoleService>();
services.AddSingleton<IBlockClientConfigService, BlockClientConfigService>();
services.AddSingleton<IBlockAutoIpService, BlockAutoIpService>();
services.AddSingleton<IBlockFirewallIpService, BlockFirewallIpService>();
the problem :
this code using too much memory after 3 day
starting ram usage is 20mb after first call (OnDependencyChange) it use 47mb
after 3 day it use 178mb
where i am doing wrong ?!

i found problem
await SecurityConfig.cacheServices?.BuildServiceProvider()?.GetService<IBlockFirewallIpService>().RegisterInFirewall();
this line code was the problem after change it to normal injection ram usage is stable now, but i can not understand whay !?

Related

how to implement Android In App BillingClient in Xamarin.Android Asynchronously

I am trying to implement below java code in c# referring to Android documentation
List<String> skuList = new ArrayList<> ();
skuList.add("premium_upgrade");
skuList.add("gas");
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
params.setSkusList(skuList).setType(SkuType.INAPP);
billingClient.querySkuDetailsAsync(params.build(),
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(BillingResult billingResult,
List<SkuDetails> skuDetailsList) {
// Process the result.
}
});
I have here 2 questions. I thought that i would run this code on a separate thread than UI thread like below to keep my ui responsive while network connection is done. is that the correct approach? QuerySkuDetailsAsync is called async but doesnt implement as async. how should this be working and how to handle in c# because it will fire and forget but Listener to handle the response.
public async Task<List<InAppBillingProduct>> GetProductsAsync(List<string> ProductIds)
{
var getSkuDetailsTask = Task.Factory.StartNew(() =>
{
var prms = SkuDetailsParams.NewBuilder();
var type = BillingClient.SkuType.Inapp;
prms.SetSkusList(ProductIds).SetType(type);
BillingClient.QuerySkuDetailsAsync(prms.Build(), new SkuDetailsResponseListener());
return InAppBillingProducts;
});
return await getSkuDetailsTask;
}
2nd question regarding how to handle with the listener as below. How do I return value from the listener. I need return list of InAppBillingProduct object.
public class SkuDetailsResponseListener : Java.Lang.Object, ISkuDetailsResponseListener
{
public void OnSkuDetailsResponse(BillingResult billingResult, IList<SkuDetails> skus)
{
if (billingResult.ResponseCode == BillingResponseCode.Ok)
{
// get list of Products here and return
}
}
}
FYI. This is how I did it. This is not a complete code but this will give you and idea.
Listener - PCL
============
private async Task EventClicked()
{
var skuList = new List<string>();
skuList.Add("[nameofsubscriptionfoundinyourgoogleplay]");
if (await _billingClientLifecycle.Initialize(skuList, DisconnectedConnection))
{
var firstProduct = _billingClientLifecycle?.ProductsInStore?.FirstOrDefault();
if (firstProduct != null)
{
//purchase here
}
}
}
private void DisconnectedConnection()
{
//Todo.alfon. handle disconnection here...
}
Interface - PCL
===========
public interface IInAppBillingMigratedNew
{
List<InAppBillingPurchase> PurchasedProducts { get; set; }
List<InAppBillingProduct> ProductsInStore { get; set; }
Task<bool> Initialize(List<String> skuList, Action onDisconnected = null);
}
Dependency - Platform Droid
===============
[assembly: XF.Dependency(typeof(InAppBillingMigratedNew))]
public class InAppBillingMigratedNew : Java.Lang.Object, IBillingClientStateListener
, ISkuDetailsResponseListener, IInAppBillingMigratedNew
{
private Activity Context => CrossCurrentActivity.Current.Activity
?? throw new NullReferenceException("Current Context/Activity is null");
private BillingClient _billingClient;
private List<string> _skuList = new List<string>();
private TaskCompletionSource<bool> _tcsInitialized;
private Action _disconnectedAction;
private Dictionary<string, SkuDetails> _skusWithSkuDetails = new Dictionary<string, SkuDetails>();
public List<InAppBillingPurchase> PurchasedProducts { get; set; }
public List<InAppBillingProduct> ProductsInStore { get; set; }
public IntPtr Handle => throw new NotImplementedException();
public Task<bool> Initialize(List<string> skuList, Action disconnectedAction = null)
{
_disconnectedAction = disconnectedAction;
_tcsInitialized = new TaskCompletionSource<bool>();
var taskInit = _tcsInitialized.Task;
_skuList = skuList;
_billingClient = BillingClient.NewBuilder(Context)
.SetListener(this)
.EnablePendingPurchases()
.Build();
if (!_billingClient.IsReady)
{
_billingClient.StartConnection(this);
}
return taskInit;
}
#region IBillingClientStateListener
public void OnBillingServiceDisconnected()
{
Console.WriteLine($"Connection disconnected.");
_tcsInitialized?.TrySetResult(false);
_disconnectedAction?.Invoke();
}
public void OnBillingSetupFinished(BillingResult billingResult)
{
var responseCode = billingResult.ResponseCode;
var debugMessage = billingResult.DebugMessage;
if (responseCode == BillingResponseCode.Ok)
{
QuerySkuDetails();
QueryPurchases();
_tcsInitialized?.TrySetResult(true);
}
else
{
Console.WriteLine($"Failed connection {debugMessage}");
_tcsInitialized?.TrySetResult(false);
}
}
#endregion
#region ISkuDetailsResponseListener
public void OnSkuDetailsResponse(BillingResult billingResult, IList<SkuDetails> skuDetailsList)
{
if (billingResult == null)
{
Console.WriteLine("onSkuDetailsResponse: null BillingResult");
return;
}
var responseCode = billingResult.ResponseCode;
var debugMessage = billingResult.DebugMessage;
switch (responseCode)
{
case BillingResponseCode.Ok:
if (skuDetailsList == null)
{
_skusWithSkuDetails.Clear();
}
else
{
if (skuDetailsList.Count > 0)
{
ProductsInStore = new List<InAppBillingProduct>();
}
foreach (var skuDetails in skuDetailsList)
{
_skusWithSkuDetails.Add(skuDetails.Sku, skuDetails);
//ToDo.alfon. make use mapper here
ProductsInStore.Add(new InAppBillingProduct
{
Name = skuDetails.Title,
Description = skuDetails.Description,
ProductId = skuDetails.Sku,
CurrencyCode = skuDetails.PriceCurrencyCode,
LocalizedIntroductoryPrice = skuDetails.IntroductoryPrice,
LocalizedPrice = skuDetails.Price,
MicrosIntroductoryPrice = skuDetails.IntroductoryPriceAmountMicros,
MicrosPrice = skuDetails.PriceAmountMicros
});
}
}
break;
case BillingResponseCode.ServiceDisconnected:
case BillingResponseCode.ServiceUnavailable:
case BillingResponseCode.BillingUnavailable:
case BillingResponseCode.ItemUnavailable:
case BillingResponseCode.DeveloperError:
case BillingResponseCode.Error:
Console.WriteLine("onSkuDetailsResponse: " + responseCode + " " + debugMessage);
break;
case BillingResponseCode.UserCancelled:
Console.WriteLine("onSkuDetailsResponse: " + responseCode + " " + debugMessage);
break;
// These response codes are not expected.
case BillingResponseCode.FeatureNotSupported:
case BillingResponseCode.ItemAlreadyOwned:
case BillingResponseCode.ItemNotOwned:
default:
Console.WriteLine("onSkuDetailsResponse: " + responseCode + " " + debugMessage);
break;
}
}
#endregion
#region Helper Methods Private
private void ProcessPurchases(List<Purchase> purchasesList)
{
if (purchasesList == null)
{
Console.WriteLine("No purchases done.");
return;
}
if (IsUnchangedPurchaseList(purchasesList))
{
Console.WriteLine("Purchases has not changed.");
return;
}
_purchases.AddRange(purchasesList);
PurchasedProducts = _purchases.Select(sku => new InAppBillingPurchase
{
PurchaseToken = sku.PurchaseToken
})?.ToList();
if (purchasesList != null)
{
LogAcknowledgementStatus(purchasesList);
}
}
private bool IsUnchangedPurchaseList(List<Purchase> purchasesList)
{
// TODO: Optimize to avoid updates with identical data.
return false;
}
private void LogAcknowledgementStatus(List<Purchase> purchasesList)
{
int ack_yes = 0;
int ack_no = 0;
foreach (var purchase in purchasesList)
{
if (purchase.IsAcknowledged)
{
ack_yes++;
}
else
{
ack_no++;
}
}
//Log.d(TAG, "logAcknowledgementStatus: acknowledged=" + ack_yes +
// " unacknowledged=" + ack_no);
}
private void QuerySkuDetails()
{
var parameters = SkuDetailsParams
.NewBuilder()
.SetType(BillingClient.SkuType.Subs)
.SetSkusList(_skuList)
.Build();
_billingClient.QuerySkuDetailsAsync(parameters, this);
}
private void QueryPurchases()
{
if (!_billingClient.IsReady)
{
Console.WriteLine("queryPurchases: BillingClient is not ready");
}
var result = _billingClient.QueryPurchases(BillingClient.SkuType.Subs);
ProcessPurchases(result?.PurchasesList?.ToList());
}
#endregion
}

JeroMQ: connection does not recover reliably

I have two applications, sending messages asynchronously in both directions. I am using sockets of type ZMQ.DEALER on both sides. The connection status is additionally controlled by heartbeating.
I have now problems to get the connection reliably recovering after connection problems (line failure or application restart on one side). When I restart the applicaton on the server side (the side doing the bind()), the client side will not always reconnect successfully and then needs to be restarted, especially when the local buffer has reached the HWM limit.
I did not find any other way to make the connection recovery reliable, other than resetting the complete ZMQ.Context in case of heartbeat failures or if send() returned false. I will then call Context.term() and will create Context and Socket again. This seemed to work fine in my tests. But now I observed occasional and hangups inside Context.term(), which are rare and hard to reproduce. I know, that creating the Context should be done just once at application startup, but as said I found no other way to re-establish a broken connection.
I am using JeroMQ 0.3.4. The source of a test application is below, ~200 lines of code.
Any hints to solve this are very much appreciated.
import java.util.Calendar;
import org.zeromq.ZMQ;
public class JeroMQTest {
public interface IMsgListener {
public void newMsg(byte[] message);
}
final static int delay = 100;
final static boolean doResetContext = true;
static JeroMQTest jeroMQTest;
static boolean isServer;
private ZMQ.Context zContext;
private ZMQ.Socket zSocket;
private String address = "tcp://localhost:9889";
private long lastHeartbeatReceived = 0;
private long lastHeartbeatReplyReceived;
private boolean sendStat = true, serverIsActive = false, receiverInterrupted = false;
private Thread receiverThread;
private IMsgListener msgListener;
public static void main(String[] args) {
isServer = args.length > 0 && args[0].equals("true");
if (isServer) {
new JeroMQTest().runServer();
}
else {
new JeroMQTest().runClient();
}
}
public void runServer() {
msgListener = new IMsgListener() {
public void newMsg(byte[] message) {
String msgReceived = new String(message);
if (msgReceived.startsWith("HEARTBEAT")) {
String msgSent = "HEARTBEAT_REP " + msgReceived.substring(10);
sendStat = zSocket.send(msgSent.getBytes());
System.out.println("heartbeat rcvd, reply sent, status:" + sendStat);
lastHeartbeatReceived = getNow();
} else {
System.out.println("msg received:" + msgReceived);
}
}
};
createJmq();
sleep(1000);
int ct = 1;
while (true) {
boolean heartbeatsOk = lastHeartbeatReceived > getNow() - delay * 4;
if (heartbeatsOk) {
serverIsActive = true;
String msg = "SERVER " + ct;
sendStat = zSocket.send(msg.getBytes());
System.out.println("msg sent:" + msg + ", status:" + sendStat);
ct++;
}
if (serverIsActive && (!heartbeatsOk || !sendStat)) {
serverIsActive = false;
if (doResetContext) {
resetContext();
}
}
sleep(delay);
}
}
public void runClient() {
msgListener = new IMsgListener() {
public void newMsg(byte[] message) {
String msgReceived = new String(message);
if (msgReceived.startsWith("HEARTBEAT_REP")) {
System.out.println("HEARTBEAT_REP received:" + msgReceived);
lastHeartbeatReplyReceived = getNow();
}
else {
System.out.println("msg received:" + msgReceived);
}
}
};
createJmq();
sleep(1000);
int ct = 1;
boolean reconnectDone = false;
while (true) {
boolean heartbeatsOK = lastHeartbeatReplyReceived > getNow() - delay * 4;
String msg = "HEARTBEAT " + (ct++);
sendStat = zSocket.send(msg.getBytes());
System.out.println("heartbeat sent:" + msg + ", status:" + sendStat);
sleep(delay / 2);
if (sendStat) {
msg = "MSG " + ct;
sendStat = zSocket.send(msg.getBytes());
System.out.println("msg sent:" + msg + ", status:" + sendStat);
reconnectDone = false;
}
if ((!heartbeatsOK && lastHeartbeatReplyReceived > 0) || (!sendStat && !reconnectDone)) {
if (doResetContext) {
resetContext();
}
lastHeartbeatReplyReceived = 0;
reconnectDone = true;
}
sleep(delay / 2);
}
}
public void resetContext() {
closeJmq();
sleep(1000);
createJmq();
System.out.println("resetContext done");
}
private void createJmq() {
zContext = ZMQ.context(1);
zSocket = zContext.socket(ZMQ.DEALER);
zSocket.setSendTimeOut(100);
zSocket.setReceiveTimeOut(100);
zSocket.setSndHWM(10);
zSocket.setRcvHWM(10);
zSocket.setLinger(100);
if (isServer) {
zSocket.bind(address);
} else {
zSocket.connect(address);
}
receiverThread = new Thread() {
public void run() {
receiverInterrupted = false;
try {
ZMQ.Poller poller = new ZMQ.Poller(1);
poller.register(zSocket, ZMQ.Poller.POLLIN);
while (!receiverInterrupted) {
if (poller.poll(100) > 0) {
byte byteArr[] = zSocket.recv(0);
msgListener.newMsg(byteArr);
}
}
poller.unregister(zSocket);
} catch (Throwable e) {
System.out.println("Exception in ReceiverThread.run:" + e.getMessage());
}
}
};
receiverThread.start();
}
public void closeJmq() {
receiverInterrupted = true;
sleep(100);
zSocket.close();
zContext.term();
}
long getNow() {
Calendar now = Calendar.getInstance();
return (long) (now.getTime().getTime());
}
private static void sleep(int mSleep) {
try {
Thread.sleep(mSleep);
} catch (InterruptedException e) {
}
}
}

Google Login and retrieving profile info in Windows Phone 8.1 WinRT app

I am trying to add Google login in my universal app,For Windows 8.1 app,it's easy to do but in case of Windows Phone 8.1 WinRT app,
Here is the code I did:
private String simpleKey = "YOUR_SIMPLE_API_KEY"; // Should keep this secret
private String clientID = "ffffff- n12s9sab94p3j3vp95sdl7hrm2lbfk3e.apps.googleusercontent.com";
private string CALLBACKuri = "writeprovidedcallbackuri";
private String clientSecret = "LYffff2Q6MbgH623i"; // Keep it secret!
private String callbackUrl = "urn:ietf:wg:oauth:2.0:oob";
private String scope = "https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email";
public GooglePlusLoginPage()
{
this.InitializeComponent();
refreshToken = null;
code = null;
access_token = null;
renderArea = this;
Auth();
}
public void Auth()
{
Windows.Storage.ApplicationData.Current.LocalSettings.Values["code"] = "";
if (access_token == null)
{
if (refreshToken == null && code == null)
{
try
{
String GoogleURL = "https://accounts.google.com/o/oauth2/auth?client_id=" + Uri.EscapeDataString(clientID) + "&redirect_uri=" + Uri.EscapeDataString(callbackUrl) + "&response_type=code&scope=" + Uri.EscapeDataString(scope);
System.Uri StartUri = new Uri(GoogleURL);
// When using the desktop flow, the success code is displayed in the html title of this end uri
System.Uri EndUri = new Uri("https://accounts.google.com/o/oauth2/approval?");
WebAuthenticationBroker.AuthenticateAndContinue(StartUri, EndUri, null, WebAuthenticationOptions.None);
// await Task.Delay(2);
}
catch (Exception Error)
{
((GooglePlusLoginPage)renderArea).SendToLangingPage();
}
}
}
//codeToAcccesTok();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
string name = e.Parameter as string;
IsGplusLogin = true;
// When the navigation stack isn't restored navigate to the ScenarioList
}
private void OutputToken(String TokenUri)
{
string access_token = TokenUri;
}
public void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args)
{
WebAuthenticationResult result = args.WebAuthenticationResult;
if (result.ResponseStatus == WebAuthenticationStatus.Success)
{
string response = result.ResponseData.ToString();
code = response.Substring(response.IndexOf("=") + 1);
Windows.Storage.ApplicationData.Current.LocalSettings.Values["code"] = code;
// TODO: switch off button, enable writes, etc.
}
else if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
{
//TODO: handle WebAuthenticationResult.ResponseErrorDetail.ToString()
}
else
{
((GooglePlusLoginPage)renderArea).SendToLangingPage();
// This could be a response status of 400 / 401
// Could be really useful to print debugging information such as "Your applicationID is probably wrong"
//TODO: handle WebAuthenticationResult.ResponseStatus.ToString()
}
codeToAcccesTok();
}
interface IWebAuthenticationContinuable
{
/// <summary>
/// This method is invoked when the web authentication broker returns
/// with the authentication result
/// </summary>
/// <param name="args">Activated event args object that contains returned authentication token</param>
void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args);
}
private async void codeToAcccesTok()
{
string oauthUrl = "https://accounts.google.com/o/oauth2/token";
HttpClient theAuthClient = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, oauthUrl);
// default case, we have an authentication code, want a refresh/access token
string content = "code=" + code + "&" +
"client_id=" + clientID + "&" +
"client_secret=" + clientSecret + "&" +
"redirect_uri=" + callbackUrl + "&" +
"grant_type=authorization_code";
if (refreshToken != null)
{
content = "refresh_token=" + refreshToken + "&" +
"client_id=" + clientID + "&" +
"client_secret=" + clientSecret + "&" +
"grant_type=refresh_token";
}
request.Method = HttpMethod.Post;
request.Content = new StreamContent(new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(content)));
request.Content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
try
{
HttpResponseMessage response = await theAuthClient.SendAsync(request);
parseAccessToken(response);
}
catch (HttpRequestException)
{
}
}
public async void parseAccessToken(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
//content="{\n \"error\" : \"invalid_request\",\n \"error_description\" : \"Missing required parameter: code\"\n}";
if (content != null)
{
string[] lines = content.Replace("\"", "").Replace(" ", "").Replace(",", "").Split('\n');
for (int i = 0; i < lines.Length; i++)
{
string[] paramSplit = lines[i].Split(':');
if (paramSplit[0].Equals("access_token"))
{
access_token = paramSplit[1];
}
if (paramSplit[0].Equals("refresh_token"))
{
refreshToken = paramSplit[1];
Windows.Storage.ApplicationData.Current.LocalSettings.Values["refreshToken"] = refreshToken;
}
}
//access_token="ya29.aAAvUHg-CW7c1RwAAACtigeHQm2CPFbwTG2zcJK-frpMUNqZkVRQL5q90mF_bA";
if (access_token != null)
{
getProfile();
}
else
{
((GooglePlusLoginPage)renderArea).SendToLangingPage();
// something is wrong, fix this
}
}
}
private async void ParseProfile(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
if (content != null)
{
var serializer = new DataContractJsonSerializer(typeof(UserEmail));
UserInfo = serializer.ReadObject(new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(content))) as UserEmail;
((GooglePlusLoginPage)renderArea).RenderUser();
WebView wb = new WebView();
var url = "http://accounts.google.com/Logout";
wb.Navigate(new Uri(url, UriKind.RelativeOrAbsolute));
}
}
public async void getProfile()
{
httpClient = new HttpClient();
var searchUrl = "https://www.googleapis.com/oauth2/v2/userinfo";
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + access_token);
try
{
HttpResponseMessage response = await httpClient.GetAsync(searchUrl);
ParseProfile(response);
}
catch (HttpRequestException hre)
{
// DebugPrint(hre.Message);
}
}
public async void RenderUser()
{
GridProgressRing.Visibility = Visibility.Visible;
Imageuri = UserInfo.picture.ToString().Replace("sz=50", "sz=150");
displayname = UserInfo.name;
Google_Id = UserInfo.id;
emailid = UserInfo.Email;
first_name = displayname;
uniqueName = Imageuri.ToString();
string Imagefile = "";
if (ShareMenuClass.CheckInternetConnection())
{
Imagefile = await ShareMenuClass.ToBase64String(Imageuri);
}
if (first_name.Contains(' '))
{
string[] dfdf = new string[2];
dfdf = first_name.Split(' ');
first_name = dfdf[0];
last_name = dfdf[1];
}
password = "google user";
string DataString = "<UserRegistration>" + "<FirstName>" + first_name + "</FirstName><LastName>" + last_name + "</LastName><Platform>Windows 8</Platform>" +
"<UUID>" + getDeviceId() + "</UUID><EmailId>" + emailid + "</EmailId><Password>" + password + "</Password><Photo>" + Imagefile +
"</Photo><OrganiztionName>" + organization_name + "</OrganiztionName><Location>indore</Location><AppId>2</AppId><querytype>register</querytype></UserRegistration>";
if (ShareMenuClass.CheckInternetConnection())
{
string Front = "<UserRegistration xmlns=\"www.XMLWebServiceSoapHeaderAuth.net\"> <UserRegistrationXml>";
string Back = "</UserRegistrationXml></UserRegistration>";
DataString = DataString.Replace("<", "<");
DataString = DataString.Replace(">", ">");
DataString = Front + DataString + Back;
string RecivedString = await ShareMenuClass.CallWebService("UserRegistration", DataString);
bool flagtoFillDefaultProgress = true;
if (RecivedString.Contains("Email Id is already registered"))
{
flagtoFillDefaultProgress = false;
string SoapXml = "<getuserProgressInfo><EmailId>" + emailid + "</EmailId><AppId>2</AppId></getuserProgressInfo>";
Front = "<getuserProgress xmlns=\"www.XMLWebServiceSoapHeaderAuth.net\"><getuserProgressInfoXml>";
Back = "</getuserProgressInfoXml></getuserProgress>";
SoapXml = SoapXml.Replace("<", "<");
SoapXml = SoapXml.Replace(">", ">");
SoapXml = Front + SoapXml + Back;
RecivedString = await ShareMenuClass.CallWebService("getuserProgress", SoapXml);
}
if (RecivedString.Contains("success"))
{
txtplswait.Text = "Configuring your account...";
RecivedXml.RecivedStringToObserCollection(RecivedString);
//if (flagtoFillDefaultProgress)
//{
await System.Threading.Tasks.Task.Delay(25);
await RecivedXml.FillMyHalfList();
//}
RecivedXml.SerializeRecivedRecivedollection();
ShareMenuClass.Google_Loging = true;
if (RecivedXml.WholeRecivedData[0].response == "success")
{
StorageFile storagefile = await ApplicationData.Current.LocalFolder.CreateFileAsync("IsGoogleUser.txt", CreationCollisionOption.ReplaceExisting);
RecivedXml.SerializeSignedUserInfo(RecivedXml.WholeRecivedData[0].Id);
Quizstatemodleobj.GetOverallQuizProgressForAllUserAndFillThisUserList(RecivedXml.WholeRecivedData[0].Id);
await System.Threading.Tasks.Task.Delay(25);
GridProgressRing.Visibility = Visibility.Collapsed;
Frame.Navigate(typeof(TrainingModulesPage));
}
}
else
{
MessageDialog msg1 = new MessageDialog("Somthing went wrong.Try again later!");
await msg1.ShowAsync();
Frame.Navigate(typeof(RegistrationPage));
}
}
else
{
MessageDialog msg1 = new MessageDialog("You are not connected to internet!");
await msg1.ShowAsync();
Frame.Navigate(typeof(RegistrationPage));
}
}
public Page renderArea { get; set; }
public string refreshToken { get; set; }
public string code { get; set; }
Here in ContinueWebAuthentication which is triggered after user accepts to let the app get the profile info the value of "code" is not the desired one,In W8.1 app the value of "code" is correct but here it is not.
Due to this I am unable to get the user profile info
I finally figured this out.
Change the "redirect_uri" query parameter in the "StartUri" parameter of the AuthenticateAndContinue method to http://localhost
Change the CallbackURL (or "EndUri") parameter of the "AuthenticateAndContinue" method to also equal http://localhost
After many hours this is what worked for me. I found the answer by browsing the code at: http://code.msdn.microsoft.com/windowsapps/Authentication-using-bb28840e and specifically looking at the class "GoogleService.cs" in the Authentication.Shared project of the solution.
Hope this helps.

"The request has already been submitted.” while working with Skydrive API in WP8

I am trying to use the SkyDrive API to upload a file. I tried using the below code.GEtAccountInformaiton and GetQuotaInformaiton methods are successfully executed But it always sets this error "The request has already been submitted.” at the end (in UploadISOFileToSkyDriveAsync() method for the field lblMessageBar.Text ).
private async void GetAccountInformations()
{
try
{
LiveOperationResult operationResult = await App.liveConnectClient.GetAsync("me");
var jsonResult = operationResult.Result as dynamic;
string firstName = jsonResult.first_name ?? string.Empty;
string lastName = jsonResult.last_name ?? string.Empty;
lblMessageBar.Text = "Welcome " + firstName + " " + lastName;
GetQuotaInformations();
}
catch (Exception e)
{
lblMessageBar.Text = e.ToString();
}
}
private async void GetQuotaInformations()
{
try
{
LiveOperationResult operationResult = await App.liveConnectClient.GetAsync("me/skydrive/quota");
var jsonResult = operationResult.Result as dynamic;
quota = jsonResult.quota ?? string.Empty;
available = jsonResult.available ?? string.Empty;
lblMessageBar.Text = "Available space in bytes: " + ConvertBytesToGigabytes(available).ToString("#.####") + "GB " + "out of bytes " + ConvertBytesToGigabytes(quota).ToString("#.####") + "GB";
UploadISOFileToSkyDriveAsync();
}
catch (Exception e)
{
lblMessageBar.Text = e.ToString();
}
}
public async void UploadISOFileToSkyDriveAsync()
{
try
{
//http://developer.nokia.com/Community/Wiki/SkyDrive_-_How_to_upload_content_on_Windows_Phone
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
StreamWriter Writer = new StreamWriter(new IsolatedStorageFileStream("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, FileMode.Append, fileStorage));
//get the data from local database and write to the isolated file and then use the path of this file to saved it to skydrive..
ObservableCollection<SavedLocationsTableEntity> SavedLocations = SavedLocationsTableEntity.GetSavedLocations();
foreach (SavedLocationsTableEntity item in SavedLocations)
{
Writer.WriteLine(UtilityLib.GetGoogleURL(new System.Device.Location.GeoCoordinate(item.SavedLocationLatitude, item.SavedLocationLongitude, item.SavedLocationAltitude)));
}
Writer.Close();
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
fileStream = store.OpenFile("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, FileMode.OpenOrCreate, FileAccess.Read);
//strEncryptedFileStream = Encoding.Unicode.GetBytes(fileStream.ToString()).ToString();
if (fileStream.Length == 0)
{
lblMessageBar.Text = "No data to upload to SkyDrive..";
return;
}
fileStream.Close();
}
//remove previous calls
var reqList = BackgroundTransferService.Requests.ToList();
foreach (var req in reqList)
{
if (req.UploadLocation.Equals(new Uri(MyFilePathInIsoStore, UriKind.Relative)))
BackgroundTransferService.Remove(BackgroundTransferService.Find(req.RequestId));
}
//Make a new call to upload
LiveOperationResult res = await App.liveConnectClient.BackgroundUploadAsync("me/skydrive", new Uri("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, UriKind.Relative), OverwriteOption.Overwrite);
lblMessageBar.Text = "File " + Constants.SkyDriveSavedLocationsFileName + " uploaded.";
return;
}
catch (Exception ex)
{
lblMessageBar.Text = "Cannot upload to SkyDrive.. " + ex.Message;
return;
}
}
It looks like MyFilePathInIsoStore here:
if (req.UploadLocation.Equals(new Uri(MyFilePathInIsoStore
is not equals "/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName here:
new Uri("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, UriKind.Relative)

Entity Framework Code First Concurrency Control

There
I’m using the EF code first to persist the data by following the sequence: filter => remove => add, run the attached sample(two threads run conrrrently), sometime I noticed there was no existing record return after the filtering, sometime there are two records after the filtering, what I thought/expected is - every time the filter should have one existing record return. Also, there are some exceptions raised up during saving the change.
As I known, EF by default uses the Read Committed isolation level to execute the transaction, I think that means during the filtering, the shared lock is put on the resource, but why I can observe that there is not existing record or two existing records after the filtering, the remove and add operation together should be an atomic operation, right? If I’m right, there should be only and just one record after filtering.
Is there anything I missed? How to handle this case correctly?
Please help.
Another question:
Use the LastUpdated column as the concurrency token, how to the following case correctly:
1. If the entity in the database is newer than the entity in the context, start another thread to archive the entity to the history database.
2. If the entity in the database is old than the entity in the context, retry the saving to overwrite the entity in the database.
Am i right to use the code below to handle the case:
internal void SaveChangesEx()
{
bool saveFailed;
do
{
saveFailed = false;
try
{
base.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
saveFailed = false;
ex.Entries.ToList().ForEach(entry =>
{
if (entry.State == System.Data.EntityState.Deleted)
{
var current = base.Set<Customer>().FirstOrDefault();
Customer rfqInDb = (Customer)entry.GetDatabaseValues();
// If the newer one aready exists, start the archive, otherwise, retry by reloading the entity from DB and marking the state as deleted
if (current.LastUpdated < customerInDb.LastUpdated)
{
using (var archiver = new CustomerArchiveDBContext())
{
archiver.RFQS.Add(current);
archiver.SaveChangesEx();
}
saveFailed = false;
}
else
{
//Refresh the context and retry
entry.Reload();
entry.State = System.Data.EntityState.Deleted;
}
}
});
}
} while (saveFailed);
}
Script: ========
CREATE TABLE [dbo].[Customers](
[FirstName] [nvarchar](20) NOT NULL,
[LastName] [nvarchar](60) NULL,
[Company] [nvarchar](250) NULL,
[Telephone] [nvarchar](20) NULL,
[LastUpdated] [datetime] NULL
) ON [PRIMARY]
Code ========
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;
using System.Data.Entity.Validation;
using System.Threading.Tasks;
using System.Threading;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace EFOptimisticConcurrency
{
public abstract class Entity
{
public int Id { get; set; }
}
public class Customer
: Entity
{
public string FirstName { get; set; }
/// <summary>
/// Get or set the surname of this customer
/// </summary>
public string LastName { get; set; }
/// <summary>
/// Get or set the telephone
/// </summary>
public string Telephone { get; set; }
/// <summary>
/// Get or set the company name
/// </summary>
public string Company { get; set; }
public DateTime LastUpdated { get; set; }
}
class CustomerEntityConfiguration
: EntityTypeConfiguration<Customer>
{
/// <summary>
/// Create a new instance of customer entity configuration
/// </summary>
public CustomerEntityConfiguration()
{
//configure keys and properties
this.HasKey(c => c.FirstName);
this.Ignore(c => c.Id);
this.Property(c => c.FirstName)
.HasMaxLength(20)
.IsRequired();
this.Property(c => c.LastName)
.HasMaxLength(60)
.IsRequired();
this.Property(c => c.Company)
.HasMaxLength(250);
//this.Property(c => c.LastUpdated).IsConcurrencyToken();
this.Property(c => c.Telephone)
.HasMaxLength(20);
this.ToTable("Customers");
}
}
public class CustomerContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Configurations.Add(new CustomerEntityConfiguration()); ;
}
}
public class Program
{
public static volatile int showStopper = 0;
static void Main(string[] args)
{
var color = Console.ForegroundColor;
EntityFrameworkProfiler.Initialize();
Task.Factory.StartNew(() =>
{
while (true)
{
Customer customer = new Customer();
customer.FirstName = "FirstName";
customer.LastName = "Last " + new Random().Next(0, 10000).ToString();
customer.Telephone = "686868";
customer.Company = "MyCity";
customer.LastUpdated = DateTime.Now;
if (showStopper == 2)
{
Console.ReadLine();
showStopper = 0;
}
try
{
Console.WriteLine("Start the Store => " + customer.LastName + " , " + customer.LastUpdated.ToString());
{
int i = 0;
using (var customerConext = new CustomerContext())
{
Console.WriteLine("Start the filter 1 => " + customer.Telephone + " , " + customer.LastUpdated.ToString());
var matched = customerConext.Customers.Where(c => c.Telephone == "686868" && c.LastUpdated < customer.LastUpdated);
foreach (var hit in matched)
{
i++;
customerConext.Customers.Remove(hit);
}
if (i == 2)
{
Console.WriteLine("1 - 2 exist, has the problem now");
showStopper = 2;
}
else if (i == 0)
{
Console.WriteLine("1 - 0 exist, has the problem now");
showStopper = 2;
}
Console.WriteLine("Start Adding 1 => " + customer.LastName + " , " + customer.LastUpdated.ToString());
try
{
customerConext.Customers.Add(customer);
customerConext.SaveChanges();
Console.WriteLine("SaveChanges 1 => " + customer.LastName + " , " + customer.LastUpdated.ToString());
}
catch (Exception ex)
{
Console.WriteLine("Exception 1 : " + ex.Message + " => " + customer.LastName + " , " + customer.LastUpdated);
if (ex.InnerException != null)
{
Console.WriteLine("Inner Exception 2 : " + ex.InnerException.Message + " => " + customer.LastName + " , " + customer.LastUpdated);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception 1 " + ex.Message);
if (ex.InnerException != null)
{
Console.WriteLine(ex.InnerException.Message);
}
showStopper = 2;
}
}
});
Thread.Sleep(10000);
Task.Factory.StartNew(() =>
{
while (true)
{
Console.ForegroundColor = color;
try
{
Customer customer = new Customer();
customer.FirstName = "FirstName";
customer.LastName = "Last " + new Random().Next(0, 10000).ToString();
customer.Telephone = "686868";
customer.Company = "MyCity2";
customer.LastUpdated = DateTime.Now;
if (showStopper == 3)
{
Console.ReadLine();
showStopper = 0;
}
Console.WriteLine("Start the store 2 => " + customer.LastName + " , " + customer.LastUpdated.ToString());
{
int i = 0;
using (var customerConext = new CustomerContext())
{
Console.WriteLine("Start the filter 2 => " + customer.Telephone + " , " + customer.LastUpdated.ToString());
var matched = customerConext.Customers.Where(c => c.Telephone == "686868" && c.LastUpdated < customer.LastUpdated);
foreach (var hit in matched)
{
i++;
customerConext.Customers.Remove(hit);
}
Console.WriteLine("Start Adding 2 => " + customer.LastName + " , " + customer.LastUpdated.ToString());
try
{
customerConext.Customers.Add(customer);
customerConext.SaveChanges();
Console.WriteLine("SaveChanges 2 => " + customer.LastName + " , " + customer.LastUpdated.ToString());
}
catch (Exception ex)
{
Console.WriteLine("Exception 2 : " + ex.Message + " => " + customer.LastName + " , " + customer.LastUpdated);
if (ex.InnerException != null)
{
Console.WriteLine("Inner Exception 2 : " + ex.InnerException.Message + " => " + customer.LastName + " , " + customer.LastUpdated);
}
showStopper = 2;
}
}
if (i == 2)
{
Console.WriteLine("1 - 2 exist, has the problem now");
showStopper = 2;
}
else if (i == 0)
{
Console.WriteLine("1 - 0 exist, has the problem now");
showStopper = 2;
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception 2 " + ex.Message);
if (ex.InnerException != null)
{
Console.WriteLine(ex.InnerException.Message);
}
}
}
});
Console.WriteLine("PRESS ANY KEY TO END");
Console.ReadLine();
}
}
}

Resources