I want to fetch location details for all the ads from google adwords but I am getting null entries.I am not able to get any data from adwords api .Help me in That as according to my knowledge there is not problem with my code and I am not able to find any solution for that.My code that I have tried is written below.
public void GetLocationAds()
{
AdWordsUser user = new AdWordsUser();
{
try
{
int offset = 0;
// Create selector.
using (CampaignCriterionService campaignCriterionService =
(CampaignCriterionService)user.GetService(AdWordsService.v201809.CampaignCriterionService))
{
Selector selector = new Selector()
{
fields = new string[]
{
CampaignCriterion.Fields.CampaignId,
CampaignCriterion.Fields.CampaignCriterionStatus,
//Location.Fields.LocationName,
//Location.Fields.CriteriaType,
//Location.Fields.ParentLocations,
//LocationCriterion.Fields.CanonicalName,
//LocationCriterion.Fields.CountryCode,
CampaignCriterion.Fields.IsNegative,
},
// predicates = new Predicate[]
//{
// Predicate.Equals( "CriteriaType","LOCATION"),
//},
paging = Paging.Default,
ordering = new OrderBy[]
{
OrderBy.Asc( CampaignCriterion.Fields.CampaignId)
}
};
CampaignCriterionPage page = new CampaignCriterionPage();
do
{
// Get the ad groups.
page = campaignCriterionService.get(selector);
// Display the results.
if (page != null && page.entries != null)
{
int j = selector.paging.startIndex;
foreach (CampaignCriterion campaignCriterion in page.entries)
{
var campaignId = campaignCriterion.campaignId;
bool IsLocation = campaignCriterion.isNegative;
var CampaignCriterionType = campaignCriterion.CampaignCriterionType;
}
}
else
{
Console.Write("No campaignCriterion were found.");
}
selector.paging.IncreaseOffset();
}
while (selector.paging.startIndex < page.totalNumEntries);
}
}
catch (Exception ex)
{
}
}
}
Kindly help me in that.
Related
I have an app that is using an http server to serve files to a Web View. The web viewers are caching image links which is causing broken images when their paths changes.
I can delete the web store on Android and UWP but I cannot figure out how to properly with iOS.
Android:
Android.Webkit.WebStorage.Instance.DeleteAllData();
UWP:
Windows.UI.Xaml.Controls.WebView.ClearTemporaryWebDataAsync();
I have tried the following with no luck:
NSHttpCookieStorage.SharedStorage.RemoveCookiesSinceDate(NSDate.DistantPast);
WKWebsiteDataStore.DefaultDataStore.FetchDataRecordsOfTypes(WKWebsiteDataStore.AllWebsiteDataTypes, (NSArray records) =>
{
for (nuint i = 0; i < records.Count; i++)
{
var record = records.GetItem<WKWebsiteDataRecord>(i);
WKWebsiteDataStore.DefaultDataStore.RemoveDataOfTypes(
websiteDataTypes: record.DataTypes,
date: new[] { record },
completionHandler: ()=> { });
}
for (nuint i = 0; i < records.Count; i++)
{
var record = records.GetItem<WKWebsiteDataRecord>(i);
WKWebsiteDataStore.DefaultDataStore.RemoveDataOfTypes(record.DataTypes,
new[] { record }, () => { Console.Write($"deleted: {record.DisplayName}"); });
}
});
NSUrlCache.SharedCache.RemoveAllCachedResponses();
NSUrlCache.SharedCache.DiskCapacity = 0;
NSUrlCache.SharedCache.MemoryCapacity = 0;
Found the answer at: https://gochannel.org/links/link/snapshot/640
Rewrote to Xamarin IOS
private void DeleteCachedFiles()
{
if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
{
NSHttpCookieStorage.SharedStorage.RemoveCookiesSinceDate(NSDate.DistantPast);
WKWebsiteDataStore.DefaultDataStore.FetchDataRecordsOfTypes(WKWebsiteDataStore.AllWebsiteDataTypes, (NSArray records) =>
{
for (nuint i = 0; i < records.Count; i++)
{
var record = records.GetItem<WKWebsiteDataRecord>(i);
WKWebsiteDataStore.DefaultDataStore.RemoveDataOfTypes(record.DataTypes,
new[] { record }, () => { Console.Write($"deleted: {record.DisplayName}"); });
}
});
NSUrlCache.SharedCache.RemoveAllCachedResponses();
}
else
{
// Remove the basic cache.
NSUrlCache.SharedCache.RemoveAllCachedResponses();
var cookies = NSHttpCookieStorage.SharedStorage.Cookies;
foreach (var c in cookies)
{
NSHttpCookieStorage.SharedStorage.DeleteCookie(c);
}
}
try
{
// Clear web cache
DeleteLibraryFolderContents("Caches");
// Remove all cookies stored by the site. This includes localStorage, sessionStorage, and WebSQL/IndexedDB.
DeleteLibraryFolderContents("Cookies");
// Removes all app cache storage.
DeleteLibraryFolder("WebKit");
}
catch (Exception ex)
{
App.UnhandledException(ex, $"Error deleting cache {ex.Message}");
}
}
private void DeleteLibraryFolder(string folderName)
{
var manager = NSFileManager.DefaultManager;
var library = manager.GetUrls(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User).First();
var dir = Path.Combine(library.Path, folderName);
manager.Remove(dir, out NSError error);
if (error != null)
{
App.UnhandledException(new Exception(error.Description), error.Description);
}
}
private void DeleteLibraryFolderContents(string folderName)
{
var manager = NSFileManager.DefaultManager;
var library = manager.GetUrls(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User).First();
var dir = Path.Combine(library.Path, folderName);
var contents = manager.GetDirectoryContent(dir, out NSError error);
if (error != null)
{
App.UnhandledException(new Exception(error.Description), error.Description);
}
foreach (var c in contents)
{
try
{
manager.Remove(Path.Combine(dir, c), out NSError errorRemove);
if (errorRemove != null)
{
App.UnhandledException(new Exception(error.Description), error.Description);
}
}
catch (Exception ex)
{
App.UnhandledException(ex, $"Error deleting folder contents: {folderName}{Environment.NewLine}{ex.Message}");
}
}
}
I am implementing CoinPayments IPN in my application and I have trouble with passing data to the method that take their Callback. I have tried like everything I could find: TempData, SessionVariables, tried to implement it somewhere in forms and maybe Request it but that didn`t work for me. So I also tried to implement it with Global static variables. And it worked! But then came another issue: if more than one user were to buy something from website at the same time or even in between any callbacks their data will get mixed. So here I am, trying again to make Session Variables work and have no clue why they are not working as I used them before. Probably what I can think of is that because its a callback from CoinPayments and I handle something wrongly.
Here is the code I have right now: Tho I tried different variations like implementing Session in Get Payment method. Now I ended up with it and it still comes out as null in POST METHOD.
Class for handling Session Variables:
public static class MyGlobalVariables
{
public static int TokenChoice
{
get
{
if (System.Web.HttpContext.Current.Session["TokenChoice"] == null)
{
return -1;
}
else
{
return (int)System.Web.HttpContext.Current.Session["TokenChoice"];
}
}
set
{
System.Web.HttpContext.Current.Session["TokenChoice"] = value;
}
}
public static int PaymentChoice
{
get
{
if (System.Web.HttpContext.Current.Session["PaymentChoice"] == null)
{
return -1;
}
else
{
return (int)System.Web.HttpContext.Current.Session["PaymentChoice"];
}
}
set
{
System.Web.HttpContext.Current.Session["PaymentChoice"] = value;
}
}
public static string CurrentUser
{
get
{
System.Web.HttpContext.Current.Session["CurrentUser"] = System.Web.HttpContext.Current.User.Identity.Name;
return (string)System.Web.HttpContext.Current.Session["CurrentUser"];
}
}
}
Class that returns view where you click on CoinPayments button:
public ActionResult Payment(int tokenChoice, int paymentChoice)
{
ViewBag.Payment = paymentChoice;
MyGlobalVariables.PaymentChoice = paymentChoice;
MyGlobalVariables.TokenChoice = tokenChoice;
return View();
}
Callback class that handles Callback from CoinPayments:
[HttpPost]
public ActionResult Payment()
{
NameValueCollection nvc = Request.Form;
var merchant_id = id;
var ipn_secret = secret;
var order_total = MyGlobalVariables.PaymentChoice;
if (String.IsNullOrEmpty(nvc["ipn_mode"]) || nvc["ipn_mode"] != "hmac")
{
Trace.WriteLine("IPN Mode is not HMAC");
return View();
}
if (String.IsNullOrEmpty(HTTP_HMAC))
{
Trace.WriteLine("No HMAC signature sent");
return View();
}
if (String.IsNullOrEmpty(nvc["merchant"]) || nvc["merchant"] != merchant_id.Trim())
{
Trace.WriteLine("No or incorrect Merchant ID passed");
return View();
}
//var hmac = hash_hmac("sha512", request, ipn_secret.Trim());
var txn_id = nvc["txn_id"];
var item_name = nvc["item_name"];
var item_number = nvc["item_number"];
var amount1 = nvc["amount1"];
var amount2 = float.Parse(nvc["amount2"], CultureInfo.InvariantCulture.NumberFormat);
var currency1 = nvc["currency1"];
var currency2 = nvc["currency2"];
var status = Convert.ToInt32(nvc["status"]);
var status_text = nvc["status_text"];
Trace.WriteLine(status);
if (currency1 != "USD") {
Trace.WriteLine("Original currency mismatch!");
return View();
}
if (Convert.ToInt32(amount1) < Convert.ToInt32(order_total))
{
Trace.WriteLine("Amount is less than order total!");
return View();
}
if (status >= 100 || status == 2) {
using (MyDatabaseEntities1 dc = new MyDatabaseEntities1())
{
var account = dc.Users.Where(a => a.Username == MyGlobalVariables.CurrentUser).FirstOrDefault();
if (account != null && account.Paid == 0)
{
Trace.WriteLine("Payment Completed");
Trace.WriteLine("Tokens to add: " + MyGlobalVariables.TokenChoice);
account.Tokens += MyGlobalVariables.TokenChoice;
account.Paid = 1;
dc.Configuration.ValidateOnSaveEnabled = false;
dc.SaveChanges();
}
}
} else if (status < 0)
{
Trace.WriteLine(
"payment error, this is usually final but payments will sometimes be reopened if there was no exchange rate conversion or with seller consent");
} else {
using (MyDatabaseEntities1 dc = new MyDatabaseEntities1())
{
var account = dc.Users.Where(a => a.Username == MyGlobalVariables.CurrentUser).FirstOrDefault();
if (account != null)
{
account.Paid = 0;
dc.Configuration.ValidateOnSaveEnabled = false;
dc.SaveChanges();
}
}
Trace.WriteLine("Payment is pending");
}
return View();
}
As you can see there are only 3 variables I need to handle.
Also someone might ask why I use Session Variable for Current.User?
Well for some reason Callback method can not read Current.User as it return null. And well... nothing really changed as for now.
If you have ever experienced something like that or can find an issue I would be so thankful since I wasted already over 2 days on that issue.
EDIT:
After some testing I found out variables works fine if I run Post method on my own. So the problem is with handling callback from CoinPayments. Is there a specific way to deal with this?
We have a requirement that is we need to access onedirve through asp.net/C# and need to get the latest uploaded file..?
Please help me how to solve this type of requirement..?
i tried the following code..
i used following namespaces. but didn't work
using Microsoft.Live.Web.Samples.ConnectAppUserWithMSAccount.Filters;
using Microsoft.Live.Web.Samples.ConnectAppUserWithMSAccount.Models;
private LiveAuthClient MSAuthClient
{
get
{
if (this.liveAuthClient == null)
{
IDictionary<int, string> secretMap = new Dictionary<int, string>();
secretMap.Add(ClientSecretKey, ClientSecret);
this.liveAuthClient = new LiveAuthClient(ClientId, secretMap, null, this);
}
return this.liveAuthClient;
}
}
private MSAccountStatus MSAccountStatus
{
get
{
if (this.msAccountStatus == Controllers.MSAccountStatus.None)
{
using (UsersContext db = new UsersContext())
{
MSAccount msAccount = db.MSAccounts.FirstOrDefault(u => u.UserName == this.User.Identity.Name);
this.msAccountStatus = msAccount != null ? MSAccountStatus.Connected : MSAccountStatus.NotConnected;
}
}
if (this.msAccountStatus == MSAccountStatus.Connected)
{
LiveConnectSession session = this.MSAuthClient.Session;
if (session == null || session.Expires < DateTimeOffset.UtcNow)
{
this.msAccountStatus = MSAccountStatus.ConnectedWithError;
}
}
return this.msAccountStatus;
}
}
I am using a standard list method for my lookups I use this for winforms and works fine just trying to re use on web and its not displaying my items.
public List<SISLookupLists> GetGender()
{
List<SISLookupLists> lookups = new List<SISLookupLists>();
try
{
var q = from lookup in schoolEntities.Genders
orderby lookup.description
select new
{
Code = lookup.code,
Description = lookup.description.Trim()
};
if (q != null)
{
Array.ForEach(q.ToArray(), l =>
{
lookups.Add(new SISLookupLists(l.Code, l.Description));
});
}
}
catch (Exception ex)
{
throw new EntityContextException("GetGender failed.", ex);
}
return lookups;
}
public SISDBContext _db = new SISDBContext();
rdGender.DataSource = _db.GetGender();
rdGender.DataTextField = "Description";
rdGender.DataValueField= "Code";
rdGender.DataBind();
Any idea what I am doing wrong here guys.
What I am doing currently is adding an item to the Cache and disposing of my object when that object is removed from the Cache. The logic being that it gets removed when memory consumption gets too high. I'm open to outher suggestions but I would like to avoid creating a thread than continually measures memory statistics if possible. Here is my code:
public class WebServiceCache : ConcurrentDictionary<string, WebServiceCacheObject>, IDisposable
{
private WebServiceCache()
{
if (HttpContext.Current != null && HttpContext.Current.Cache != null)
{
HttpContext.Current.Cache.Add("CacheTest", true, null, DateTime.Now.AddYears(1), System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Low,
(key, obj, reason) => {
if (reason != System.Web.Caching.CacheItemRemovedReason.Removed)
{
WebServiceCache.Current.ClearCache(50);
}
});
}
}
private static WebServiceCache _current;
public static WebServiceCache Current
{
get
{
if (_current != null && _current.IsDisposed)
{
// Might as well clear it fully
_current = null;
}
if (_current == null)
{
_current = new WebServiceCache();
}
return _current;
}
}
public void ClearCache(short percentage)
{
try
{
if (percentage == 100)
{
this.Dispose();
return;
}
var oldest = _current.Min(c => c.Value.LastAccessed);
var newest = _current.Max(c => c.Value.LastAccessed);
var difference = (newest - oldest).TotalSeconds;
var deleteBefore = oldest.AddSeconds((difference / 100) * percentage);
// LINQ doesn't seem to work very well on concurrent dictionaries
//var toDelete = _current.Where(c => DateTime.Compare(c.Value.LastAccessed,deleteBefore) < 0);
var keys = _current.Keys.ToArray();
foreach (var key in keys)
{
if (DateTime.Compare(_current[key].LastAccessed, deleteBefore) < 0)
{
WebServiceCacheObject tmp;
_current.TryRemove(key, out tmp);
tmp = null;
}
}
keys = null;
}
catch
{
// If we throw an exception here then we are probably really low on memory
_current = null;
GC.Collect();
}
}
public bool IsDisposed { get; set; }
public void Dispose()
{
this.Clear();
HttpContext.Current.Cache.Remove("CacheTest");
this.IsDisposed = true;
}
}
In Global.asax
void context_Error(object sender, EventArgs e)
{
Exception ex = _context.Server.GetLastError();
if (ex.InnerException is OutOfMemoryException)
{
if (_NgageWebControls.classes.Caching.WebServiceCache.Current != null)
{
_NgageWebControls.classes.Caching.WebServiceCache.Current.ClearCache(100);
}
}
}
Thanks,
Joe
You can access the ASP.NET Cache from anywhere in your application as the static property:
HttpRuntime.Cache
You don't need to be in the context of a Request (i.e. don't need HttpContext.Current) to do this.
So you should be using it instead of rolling your own caching solution.