I am using Google.Apis.AdSense to get AdSense Data from C# windows form..
i can get adsense info and Metric Report, using Metric i can optians some values such as
["PAGE_VIEWS",
"INDIVIDUAL_AD_IMPRESSIONS",
"CLICKS","AD_REQUESTS_CTR",
"INDIVIDUAL_AD_IMPRESSIONS_CTR",
"COST_PER_CLICK","AD_REQUESTS_RPM",
"INDIVIDUAL_AD_IMPRESSIONS_RPM",
"AD_REQUESTS_COVERAGE","EARNINGS"]
here a code for this process:
public AdsenseReportsGenerateResponse GenerateReport(Account adSenseAccount, DateTime startDate, DateTime endDate)
{
var reportRequest = service.Accounts.Reports.Generate(
adSenseAccount.Id, startDate.ToString(DateFormat), endDate.ToString(DateFormat));
reportRequest.Metric = new List<string>
{
"PAGE_VIEWS","INDIVIDUAL_AD_IMPRESSIONS", "CLICKS","AD_REQUESTS_CTR","INDIVIDUAL_AD_IMPRESSIONS_CTR",
"COST_PER_CLICK","AD_REQUESTS_RPM","INDIVIDUAL_AD_IMPRESSIONS_RPM", "AD_REQUESTS_COVERAGE","EARNINGS"
};
reportRequest.Dimension = new List<string> { "DATE" };
reportRequest.Sort = new List<string> { "+DATE" };
// Run report.
var reportResponse = reportRequest.Execute();
ReportUtils.FillGapsDates(reportResponse, startDate, endDate);
if (!reportResponse.Rows.IsNullOrEmpty())
{
ReportUtils.DisplayHeaders(reportResponse.Headers);
Console.WriteLine("Showing data from {0} to {1}", reportResponse.StartDate, reportResponse.EndDate);
return reportResponse;
}
else
{
return null;
}
}
First issue:
Although the data are not identical, they are similar. Why?
Second issue (important):
How or where can i get CTR Value?
Currently, we calculated the following equation:
INDIVIDUAL_AD_IMPRESSIONS_CTR * 2 * 100
Is this correct?
Related
When this function is called, it creates a text file with these attributes. There is one attribute known as start_date. When I convert to DateTime, the date format will be MM:DD:YYYY and an error will be shown. I am not sure how to change the format to DD:MM:YYYY, I have also read on the DateTime formatting but I still do not understand. Thanks.
Code is as follows:
static void generateInfoForITDepartment()
{
string filepath = #"C:\Users\notgivingmydirectory\HRMasterlist.txt";
List<Employee> people = new List<Employee>();
List<string> lines = File.ReadAllLines(filepath).ToList();
foreach (var line in lines)
{
string[] entries = line.Split('|');
Employee newIT = new Employee();
newIT.Nric = entries[0];
newIT.FullName = entries[1];
newIT.Start_Date = Convert.ToDateTime(entries[3]);
newIT.Department = entries[5];
newIT.MobileNo = entries[6];
people.Add(newIT);
}
List<string> output = new List<string>();
foreach (var it in people)
{
output.Add($"{ it.Nric }, { it.FullName }, { it.Start_Date }, { it.Department }, { it.MobileNo }");
}
File.WriteAllLines("ITDepartment.txt", output);
Console.WriteLine("ITDepartment.txt has been created");
}
Edit:
My textfile currently looks like this:
S1234567A|Jan Lee|Ms|05/10/1990|Software Architect|IT Department|98785432|PartTime|3500
S1234567B|Feb Tan|Mr|10/12/1991|Corporate Recruiter|HR CorporateAdmin|98766432|PartTime|1500
S1234567C|Mark Lim|Mr|15/07/1992|Benefit Specialist|HR Corporate Admin|98265432|PartTime|2900
Since the data is not a valid date format, you need ParseExact or TryParseExact. If you are sure about incoming format is always in dd/MM/yyyy, then use ParseExact
Here is the example with ParseExact
newIT.Start_Date = DateTime.ParseExact(entries[3], "dd/MM/yyyy", CultureInfo.InvariantCulture);
Another example with TryParseExact
DateTime start_date = DateTime.MinValue;
var isValidDate = DateTime.TryParseExact(entries[3], "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out start_date);
newIT.Start_Date = isValidDate ? start_date : DateTime.MinValue;
We need to use an option to parse the date from a specific format. While where here, let's improve the structure a bit, and the performance and memory use a LOT (what you had was grossly memory inefficient):
static IEnumerable<Employee> readEmployees(string filePath)
{
var lines = File.ReadLines(filepath);
return lines.Select(line => {
var data = line.Split('|');
var result = new Employee();
result.Nric = data[0];
result.FullName = data[1];
result.Start_Date = DateTime.ParseExact(data[3], "dd/MM/yyyy", CultureInfo.InvariantCulture);
result.Department = data[5];
result.MobileNo = data[6];
return result;
});
}
static void generateInfoForITDepartment()
{
string filepath = #"C:\Users\notgivingmydirectory\HRMasterlist.txt";
var people = readEmployees(filePath);
// note the extra format specifier for the date value
var output = people.Select(emp => $"{ emp.Nric }, { emp.FullName }, { emp.Start_Date:d }, { emp.Department }, { emp.MobileNo }");
File.WriteAllLines("ITDepartment.txt", output);
Console.WriteLine("ITDepartment.txt has been created");
}
FWIW, I would also tend to update the Employee class to move some of this code to a ToString() override and a static Parse() method, which could let you simplify the code like this:
static IEnumerable<Employee> readEmployees(string filePath)
{
var lines = File.ReadLines(filepath);
return lines.Select(line => Employee.Parse(line));
}
static void generateInfoForITDepartment()
{
string filepath = #"C:\Users\notgivingmydirectory\HRMasterlist.txt";
var people = readEmployees(filePath);
File.WriteAllLines("ITDepartment.txt", people); //calls the default ToString()
Console.WriteLine("ITDepartment.txt has been created");
}
I have a search method that queries Solr for event items. I need to modify it to only get events where the date has not already passed (i.e. Where(x => x.EventDate.Date >= DateTime.Now.Date), but I'm not sure how to add this because I'm not very familiar with Solr. Here's my search function:
public SearchQueryResults Search(string keywords, int page,int perPage, List<Guid> contentTypeFilters, List<Guid> otherFilters, ISortBuilder<SearchResultItem> sortBuilder)
{
var searchFilters = new List<IPredicateBuilder<SearchResultItem>>()
{
new IsSearchablePredicateBuilder()
};
if (contentTypeFilters.Any())
{
var contentTypePredicateBuilder = new ContentTypePredicateBuilder();
contentTypePredicateBuilder.ContentTypes = contentTypeFilters;
searchFilters.Add(contentTypePredicateBuilder);
}
if (otherFilters.Any())
{
var tagFilterBuilder = new TagsAndPredicateBuilder(otherFilters,_sitecoreContext);
searchFilters.Add(tagFilterBuilder);
}
if (string.IsNullOrWhiteSpace(keywords))
{
keywords = "";
}
SearchRequest searchRequest = new SearchRequest();
var queryParams = new Dictionary<string, string>() { };
queryParams.Add("q", keywords);
searchRequest.QueryParameters = queryParams;
searchRequest.SortBy = "";
searchRequest.SortOrder = "";
SearchQuery<SearchResultItem> queryArguments = new SearchQuery<SearchResultItem>();
queryArguments.FilterBuilders = searchFilters;
queryArguments.Page = page;
queryArguments.PerPage = perPage;
queryArguments.FacetsBuilder = new SearchFacetBuilder<SearchResultItem>();
queryArguments.SearchRequest = searchRequest;
queryArguments.IndexName = _indexName;
if (string.IsNullOrWhiteSpace(keywords))
{
queryArguments.QueryBuilders =new List<IPredicateBuilder<SearchResultItem>>();
}
else
{
queryArguments.QueryBuilders = new[] { new KeywordPredicateBuilder<SearchResultItem>(new[] { keywords }) };
}
queryArguments.SortBuilder = sortBuilder;
try
{
var results = _searchManager.GetResults<SearchResultItem>(queryArguments);
SearchQueryResults queryResults = new SearchQueryResults();
queryResults.ResultItems = results.Results;
queryResults.CurrentPage = page;
queryResults.TotalResults = Int32.Parse(results.TotalResults.ToString());
queryResults.TotalPages = (queryResults.TotalResults + perPage - 1) / perPage; ;
return queryResults;
}
catch (Exception exc)
{
Sitecore.Diagnostics.Log.Error("Error with FilteredSearch, could be a loss of connection to the SOLR server: " + exc.Message, this);
return null;
}
}
and here is how it's being called:
Results = _searchService.Search(searchTerm, CurrentPage - 1, 10, contentTypes, searchFilters,
new GenericSortBuilder<SearchResultItem>(q => q.OrderByDescending(r => r.SearchDate)));
How do I add in date filtering so that it only returns items where the date is in the future?
I would add filter query to the list of existing ones filtering the date field. On the documentation page, I was able to find information about fluent API, which could help here
Query.Field("date").From(DateTime.Now)
I'm not C# developer, that this code could have some mistakes, but I think the main idea is clear what needs to be done.
I am trying to read the stepcount from 365 days back in time from the user and then upload this to a server. But I'm currently stuck at extracting the data, I get the permission from the iOS healthkit correctly, but the return type of my data is just get "[0:] HealthKit.HKSample[]"
public void GetSteps()
{
var healthKitStore = new HKHealthStore();
var stepRateType = HKQuantityType.Create(HKQuantityTypeIdentifier.StepCount);
var sort = new NSSortDescriptor(HKSample.SortIdentifierStartDate, true);
var q = new HKSampleQuery(stepRateType, HKQuery.GetPredicateForSamples(NSDate.Now.AddSeconds(TimeSpan.FromDays(-365).TotalSeconds), NSDate.Now.AddSeconds(TimeSpan.FromDays(1).TotalSeconds), HKQueryOptions.None), 0, new NSSortDescriptor[] { },
new HKSampleQueryResultsHandler((HKSampleQuery query2,HKSample[] results, NSError error2) =>
{
var query = results; //property created within the model to expose later.
Debug.WriteLine(query);
Debug.WriteLine(results);
}));
healthKitStore.ExecuteQuery(q);
}
I think I know why you are getting "[0:] HealthKit.HKSample[]", you are trying to Debug.WriteLine an array of objects. The results variable is an array. Loop through the array instead and extract out the "Quantity", "StartDate", and "EndDate" among other fields that are available:
foreach (var item in results)
{
var sample = (HKQuantitySample) item;
var hkUnit = HKUnit.Count;
var quantity = sample.Quantity.GetDoubleValue(hkUnit);
var startDateTime = sample.StartDate.ToDateTime().ToLocalTime();
var endDateTime = sample.EndDate.ToDateTime().ToLocalTime();
Debug.WriteLine(quantity);
Debug.WriteLine(startDateTime);
Debug.WriteLine(endDateTime);
}
I am trying to do a tracker application in wp8. I want to save the values in database using Sqlite. All the values r working (time, distance and pace). After pressing Stop button, I want the values to be posted in a table view using Sqlite as u can see in the second screen. Any good suggestions or links are appreciated. Thank u.
Try this nokia developer site here.
Gives you a small tutorial how to use sqlite on windows phones.
This piece of code gives you the answer?
private void Insert_Click_1(object sender, RoutedEventArgs e)
{
// Create a new task.
Task task = new Task()
{
Title = TitleField.Text,
Text = TextField.Text,
CreationDate = DateTime.Now
};
/// Insert the new task in the Task table.
dbConn.Insert(task);
/// Retrieve the task list from the database.
List<Task> retrievedTasks = dbConn.Table<Task>().ToList<Task>();
/// Clear the list box that will show all the tasks.
TaskListBox.Items.Clear();
foreach (var t in retrievedTasks)
{
TaskListBox.Items.Add(t);
}
}
hm, i see this is a retrieval piece of code. Maybee this site helps you further.
The following example is an insert:
public void Initialize()
{
using ( var db = new SQLite.SQLiteConnection( _dbPath ) )
{
db.CreateTable<Customer>();
//Note: This is a simplistic initialization scenario
if ( db.ExecuteScalar<int>(
"select count(1) from Customer" ) == 0 )
{
db.RunInTransaction( () =>
{
db.Insert( new Customer() {
FirstName = "Jon", LastName = "Galloway" } );
db.Insert( new Customer() {
FirstName = "Jesse", LastName = "Liberty" } );
} );
}
else
{
Load();
}
}
}
I'm assuming your table is.
public class HistoryTable
{
public string date { get; set; }
public string time { get; set; }
public double pace { get; set; }
public double distance { get; set; }
}
Insert values using this statement.
string date = DateTime.Now.ToShortDateString();
string time = DateTime.Now.ToShortTimeString();
double pace = 16;
double distance = 4;
SQLiteConnection conn = new SQLiteConnection(System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Database.sqlite"));
conn.Execute("Insert into HistoryTable values(?,?,?,?)", date, time, pace, distance);
Fetch your data as below statement, I'm assuming that you know how to bind the data in listbox if there is need. I'm taking the values in textbox.
SQLiteConnection conn = new SQLiteConnection(System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Database.sqlite"));
var result = conn.Table<HistoryTable>();
foreach (var val in result)
{
TimeSpan pace = TimeSpan.FromMinutes(val.pace);
TextBoxDate.Text = val.date;
TextBoxTime.Text = val.time;
TextBoxPace.Text = pace.Minutes + ":" + pace.Seconds;
TextBoxDistance.Text = val.distance + " Km";
}
The reason why I used Pace as double because I can use this double value as total minutes and can be changed as timespan(in minutes and seconds). For any other queries you can ask any time.
To get exactly the same format as you ask in your question you should use like this also.
string date = string.Format("{0:00}.{1:00}.{2:00}", DateTime.Now.Day, DateTime.Now.Month, DateTime.Now.Year);
string time = DateTime.Now.ToString("HH:mm:ss");
double pace = 16.5;
double distance = 4;
SQLiteConnection conn = new SQLiteConnection(System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Database.sqlite"));
conn.Execute("Insert into HistoryTable values(?,?,?,?)", date, time, pace, distance);
At the time of fetching info, please change the above steps by this.
TextBoxDistance.Text = string.Format("{0:0.00}Km", val.distance);
I am trying to change date to all workouts in the list, the other properties are working fine, its only when I change Date i get problem. I have tried different trouble shooting, but none have worked. I have tried with using updatedWorkout.Date as workoutStart = out of range. If I use old.Date, then, how can I add the new date with 7days a part ?
Maybe there is a better way to do this?
Here's my method:
private int UpdateForAllWorkouts(IWorkoutCommand updatedWorkout)
{
try
{ // get schedule
var schedule = _scheduleRepository.GetIncludeWorkouts(updatedWorkout.ScheduleId);
// get workouts within the schedule by schedule id
var workout = schedule.Workouts.FirstOrDefault(w => w.Id == updatedWorkout.Id);
for (var workoutStart = workout.Date; workoutStart <= schedule.ToDate; workoutStart = workoutStart.AddDays(7))
{
// get specdfic workout by workout id and start time
var old = schedule.Workouts.Single(w => w.Date == workoutStart && w.StartTime == workout.StartTime);
var tmp = new Model.Workout
{
Id = old.Id,
CourseId = updatedWorkout.CourseId,
InstructorId = updatedWorkout.InstructorId,
Date = //<---problem
StartTime = updatedWorkout.StartTime,
EndTime = updatedWorkout.EndTime,
ScheduleId = updatedWorkout.ScheduleId,
WeekOffSet = updatedWorkout.WeekOffSet.Days
};
}
return updatedWorkout.Id;
}
catch (Exception ex)
{
throw new Exception("");
}
}
thx for helping!
I think you can use a loop for 7.
like this :
var workoutStart = workout.Date;
while(true){
if(workoutStart <= schedule.ToDate){
// Do something
}else{
break;
}
workoutStart = workoutStart.AddDays(7);
}
Please consider to check the value of our DateTime properties.Their values could be less than your SQL server allow for datetime field.
What is the Date value of updatedWorkOut object before you assign "tmp" object ?
Is your "old" object null or what is the value of date ?
your code seems to be ok. the problem underlies the value of DateTime properties and fields.