I am using Yahoo Finanace CSV API for fetching currency exchange
https://code.google.com/p/yahoo-finance-managed/wiki/CSVAPI
Currencies = new List<CurrencyModel>();
string[] rates = null;
StringBuilder codes = new StringBuilder();
codes.Append("s=USDUSD=X");
codes.Append(",USDAUD=X");
codes.Append(",USDEUR=X");
codes.Append(",USDCAD=X");
codes.Append(",USDGBP=X");
codes.Append(",USDJPY=X");
codes.Append(",USDCHF=X");
codes.Append(",USDILS=X");
WebClient wc = new WebClient();
var response = wc.DownloadString(string.Format("http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&{0}", codes));
rates = response.Replace(#"""", "").Replace("=X", "").Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string rate in rates)
{
var split = rate.Split(',');
Currencies.Add(new CurrencyModel
{
FromCurrency = split[0].Substring(0, 3),
ToCurrency = split[0].Substring(3, 3),
Rate = split[1],
Date = split[2],
Time = split[3]
});
}
return Currencies;
}
My Question is how can I get the perchance between today's currency to yesterday?
Do I need to fetch yesterday and to calculate it my self? how can this be done
Thanks
Related
I'm trying to create a report showing daily conversions from the last 30 days with google analytics data api. This is using the dotnet client library Google.Analytics.Data.V1Beta.
However I'm only getting back about 5 conversion values, the last value seems to be reflecting total conversions of all time, ideally I'd like a running update of how many conversions per day so I can plot it to a line chart.
I'm planning to change this to weekly over the course of the past X months once I have the previous issue sorted out.
I'm essentially trying to recreate the chart on the google analytics dashboard:
What am I missing?
public async Task<RunReportResponse> RunReport(string propertyId = "xxxx")
{
BetaAnalyticsDataClient client = BetaAnalyticsDataClient.Create();
FilterExpression hostnameFilter = new();
hostnameFilter.Filter = new();
hostnameFilter.Filter.InListFilter = new();
hostnameFilter.Filter.InListFilter.Values.Add("xxxx");
hostnameFilter.Filter.FieldName = "hostName";
CohortSpec cohort = new();
cohort.Cohorts.Add(new Cohort
{
Dimension = "firstSessionDate",
DateRange = new DateRange()
{
StartDate = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd"),
EndDate = DateTime.Now.ToString("yyyy-MM-dd")
},
});
cohort.CohortsRange = new CohortsRange
{
EndOffset = 5,
Granularity = CohortsRange.Types.Granularity.Daily
};
// Initialize request argument(s)
RunReportRequest request = new()
{
Property = "properties/" + propertyId,
Dimensions = {new Dimension { Name = "cohort" }, new Dimension { Name = "cohortNthDay" } },
Metrics = { new Metric { Name = "conversions" }, },
DimensionFilter = hostnameFilter,
CohortSpec = cohort,
};
// Make the request
var response = await client.RunReportAsync(request);
return response;
}
}
I'm trying to fetch detail of the email address from Attendees because of more addresses in the group, this is my code.
public List<Meeting> getAll(string email, string sDate, string eDate)
{
List<Meeting> res = new List<Meeting>();
ExchangeService es = new ExchangeService();
string username = Properties.Settings.Default.username;
string password = Properties.Settings.Default.password;
SecureString ssPassword = new SecureString();
foreach (char x in password)
ssPassword.AppendChar(x);
es.Credentials = new NetworkCredential(username, ssPassword);
es.Url = new Uri("https://outlook.office365.com/ews/exchange.asmx");
FolderId folderID = new FolderId(WellKnownFolderName.Calendar, "xxxxxx#xxxx.com");
DateTime startDate = DateTime.ParseExact(sDate + " 00:00:00", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
DateTime endDate = DateTime.ParseExact(eDate + " 23:59:59", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
CalendarView cView = new CalendarView(startDate, endDate);
//cView.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties);
FindItemsResults<Item> resultItem = es.FindItems(folderID, cView);
foreach (Item item in resultItem.Items)
{
ServiceResponseCollection<GetItemResponse> itemResponseCollection = es.BindToItems(new[] { new ItemId(item.Id.UniqueId) }, new PropertySet(BasePropertySet.FirstClassProperties));
foreach (GetItemResponse itemResponse in itemResponseCollection)
{
Appointment app = (Appointment)itemResponse.Item;
res.Add(GetClassFromAppointment(app));
}
}
return res;
}
obj.Attendees = {aaa#xxxx.com, bbb#xxxx.com, Group#xxxx.com}
"Group#xxxx.com" include more emaill address: ccc#xxxx.com, ddd#xxxx.com
How to fetch detail's addresses from the group?
You should be about just to use the EWS ExpandGroup operation https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-expand-distribution-groups-by-using-ews-in-exchange-2013. eg with your code something like
// Return the expanded group.
ExpandGroupResults myGroupMembers = es.ExpandGroup("Group#xxxx.com");
// Display the group members.
foreach (EmailAddress address in myGroupMembers.Members)
{
Console.WriteLine("Email Address: {0}", address);
}
Another approach is because you using Office365 is that you can get the Group members using the Microsoft Graph API https://learn.microsoft.com/en-us/graph/api/group-list-members?view=graph-rest-1.0&tabs=http
Introduction
I built a web crawler for a project. One of the variables parse from the website is the date. I thought that building a dictionary containing the month in French and the int associated with it.
The way that I saw the code going is.
Scrape the data from the website
var moisLettres
Find the variable in the dictionary
Return the number associated with it
So far, I built this code, I searched for a few hours but the concept of comparing a dictionary is a little bit confusing. I'm open to other solutions since I'm here to help. Feel free to correct me.
Dictionary:
IDictionary<string, int> dictMonth = new Dictionary<string, int>();
dictMonth.Add("Janvier",1);
dictMonth.Add("Février",2);
dictMonth.Add("Mars",3);
//Up to 12 months
Examples so far:
foreach (KeyValuePair<string, int> b in dictMonth) //
{
if (b.Value.Equals(e.MonthInLetters, StringComparison.CurrentCultureIgnoreCase))
return /* The TValue associated */
}
Ways I explored:
Using the date.time method to translate automatically the month in string to month in Int. Since the data scraped is in French, the code doesn't work.
FULL CODE 1/2 (Some variables are in French since it is my main language)
`
{
//Variables de bases
const string accountSid = "Private";
const string authToken = "Private";
List<Date> lstDate = new List<Date>();
string sMessage = "";
//Création du dictionnaire
IDictionary<string, int> dictMois = new Dictionary<string, int>();
dictMois.Add("Janvier",1);
dictMois.Add("Février",2);
dictMois.Add("Mars",3);
dictMois.Add("Avril",4);
dictMois.Add("Mai",5);
dictMois.Add("Juin",6);
dictMois.Add("Juillet",7);
dictMois.Add("Aout",8);
dictMois.Add("Septembre",9);
dictMois.Add("Octobre",10);
dictMois.Add("Novembre",11);
dictMois.Add("Décembre",12);
// Initialisation
Date un = new Date("19 Septembre", "Inconnu", "----------- ");
Date deux = new Date("26 Septembre", "Inconnu", "----------");
Date trois = new Date("3 Octobre", "Inconnu", "-----------");
Date quatre = new Date("10 Octobre", "Inconnu", "-----------");
Date cinq = new Date("17 Octobre", "Inconu", "-----------");
Date six = new Date("24 Octobre", "Inconnu", "-----------");
lstDate.Add(un);
lstDate.Add(deux);
lstDate.Add(trois);
lstDate.Add(quatre);
lstDate.Add(cinq);
lstDate.Add(six);
//Captation des dates
foreach (Date d in lstDate)
{
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load(d.url);
var xpathDate = "-----------";
var locationDate = doc.DocumentNode.SelectSingleNode(xpathDate);
var dateEvenement = locationDate.InnerText;
d.date = dateEvenement;
}
//Vérification si les données sont exactes.
foreach (Date e in lstDate)
{
The way it works
// The data parse is "jeu., 19 septembre 2019"
//un.date = "jeu., 19 septembre 2019"
// un.annee = "jeu., 19 septembre 2019"
// un.annee = (un.date).Substring(un.date.Length -4)
// un.jourMois = "jeu., 19 septembre 2019"
// un.jourMois = (un.date).Subtring(un.date.Length xxx)
//un.moisMots = "jeu., 19 septembre 2019"
//un.moisMots = (un.date).Subtring(un.date.Length xxx)
//un.moisChiffre = (** Here goes the comparaison to the dictionary **)
// At Last
//e.dateReel = (The combinaison of the int of the year, month et day of the month)
//e.dateReel = (e.annee + e.jourMois + e.moisChiffre);
}
//Checking the status of the event if there place it send me a sms message
foreach (Date d in lstDate)
{
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load(d.url);
var xpathStatut = "//*[#id='event-page']/main/div[1]/div[2]/div/div[2]/div[2]/div/div[2]/div/div/div";
var locationStatut = doc.DocumentNode.SelectSingleNode(xpathStatut);
var statut = locationStatut.InnerText;
if (statut.IndexOf("Complet") <= 0)
{
if (sMessage == "")
sMessage = "Il reste de la place pour";
sMessage += d.date + " ";
}
}
if (sMessage.Length > 0)
{
TwilioClient.Init(accountSid, authToken);
var message = MessageResource.Create(
body: sMessage,
from: new Twilio.Types.PhoneNumber("-------"),
to: new Twilio.Types.PhoneNumber("------------")
);
Console.WriteLine("Message envoyé" + message.Sid);
}
Console.ReadKey();
FULL CODE 2/2 - Classe Date:
class Date
{
public string date;
public string statut;
public string url;
public string moisMots;
public int moisChiffre;
public string jourMois;
public string annee;
public string dateReel;
public Date(string Date, string Statut, string Url)
{
date = Date;
statut = Statut;
url = Url;
}
}
To get the month from a string, DateTime.Parse can be used :
var culture = new System.Globalization.CultureInfo("fr");
var date = DateTime.Parse("jeu., 19 septembre 2019", culture);
int year = date.Year, month = date.Month, day = date.Day; // 2019, 9, 19
For more reliable code, DateTime.TryParse and DateTime.TryParseExact can be used.
It looks like you're looking for a way to lookup a value in a dictionary from a key. You can use the dictionary[key] syntax:
IDictionary<string, int> dictMonth = new Dictionary<string, int>();
dictMonth.Add("Janvier", 1);
dictMonth.Add("Février", 2);
dictMonth.Add("Mars", 3);
string myMonth = "Février"; //comes from your parsed data, for example.
int monthNumber = dictMonth[myMonth]; //lookup value in dictionary
//monthNumber is now equal to 2
You should check that that the key you're looking for exists in the dictionary by using the ContainsKey method, otherwise dictMonth[myMonth] will throw an exception if myMonth is not in dictMonth.
I am looking to display the current trending tweets using Twitterizer. I am using the following code to try to generate the current trends .
public TwitterResponse<TwitterTrendCollection>
GetTrendingTweets(string
accesstoken, string accesstokensecreat, double lati, double longi)
{
OAuthTokens tokens = SetTokens(accesstoken, accesstokensecreat);
LocalTrendsOptions options = new LocalTrendsOptions();
options.UseSSL = true;
options.APIBaseAddress = "http://api.twitter.com/1.1/";
PlaceInfo p = GetWoeid(lati, longi);
AvailableTrendsOptions option = new AvailableTrendsOptions() { Lat =
lati, Long = longi };
TwitterResponse<TwitterTrendCollection> trends =
TwitterTrend.Trends(tokens, (int)p.Woeid, options);
return trends;
}
How do i get the CPU usage of an instance in c#?
I've read Amazon EC2 - how to get available ram and cpu usage via AWS API? already, but i can't get it working.
NameValueCollection appConfig = ConfigurationManager.AppSettings;
var client = AWSClientFactory.CreateAmazonCloudWatchClient(
appConfig["AWSAccessKey"],
appConfig["AWSSecretKey"]
);
var dimension = new Dimension
{
Name = "InstanceId",
Value = "<i-ad20b4db>",
};
var request = new GetMetricStatisticsRequest();
request.MetricName = "CPUUtilization";
request.Period = 60;
request.Statistics.Add("Maximum");
request.Dimensions.Add(dimension);
request.Namespace = "AWS/EC2";
request.Unit = "Percent";
var currentTime = DateTime.UtcNow;
var startTime = currentTime.AddSeconds(-5);
string currentTimeString= currentTime.ToString("yyyy-MM-ddTHH:mm:ssZ");
string startTimeString= startTime.ToString("yyyy-MM-ddTHH:mm:ssZ");
request.StartTime = Convert.ToDateTime( startTimeString);
request.EndTime = Convert.ToDateTime(currentTimeString);
var response = client.GetMetricStatistics(request);
if ( response.GetMetricStatisticsResult.Datapoints.Count > 0)
{
var dataPoint = response.GetMetricStatisticsResult.Datapoints[0];
Console.WriteLine( "Instance: {0} CPU Max load: {1}", dimension.Value, dataPoint.Maximum);
}
Here's a simple proof of concept for showing the CPU Utilization during the last two days. I think there will be a datapoint like every half an hour, but you can easily change by changing the value of the Period property in the GetMetricStatisticsRequest object.
AmazonCloudWatch cw = AWSClientFactory.CreateAmazonCloudWatchClient(accessKey, secretKey, new AmazonCloudWatchConfig().WithServiceURL("https://eu-west-1.monitoring.amazonaws.com"));
DataTable data = new DataTable();
try
{
Dimension dim = new Dimension() { Name = "InstanceId", Value = GetInstanceName(amazonInstance) };
System.Collections.Generic.List<Dimension> dimensions = new List<Dimension>() { dim };
string startTime = startTime = DateTimeOffset.Parse(DateTime.Now.AddDays(-2).ToString()).ToUniversalTime().ToString("s"); // "2010-09-29T11:00:00+01:00";
GetMetricStatisticsRequest reg = new GetMetricStatisticsRequest()
{
MeasureName = "CPUUtilization",
Period = 1800
Statistics = new System.Collections.Generic.List<string>() { "Average" },
Dimensions = dimensions,
Namespace = "AWS/EC2",
EndTime = DateTime.Now.ToUniversalTime().ToString("s"), //has to be in this format: 2010-09-29T14:00:00+01:00;
StartTime = startTime
};
var points = cw.GetMetricStatistics(reg).GetMetricStatisticsResult.Datapoints.OrderBy(p => p.Timestamp);
data.Columns.Add("Average");
data.Columns.Add("TimeStamp");
foreach (var p in points)
{
DataRow row = data.NewRow();
row["Average"] = Math.Round(p.Average, 0);
row["TimeStamp"] = DateTimeOffset.Parse(p.Timestamp).LocalDateTime.ToString("yyyy-MM-dd HH:mm");
data.Rows.Add(row);
}
}
catch (AmazonCloudWatchException ex)
{
if (ex.ErrorCode.Equals("OptInRequired"))
throw new Exception("You are not signed in for Amazon EC2.");
else
throw;
}
This is my final code which works for me.
I have added new user in the IAM aws management console then i have Attached CloudWatchfullacess Policy to new user then i have used this user Accesskey & secret key in this Code.
var cw =AWSClientFactory.CreateAmazonCloudWatchClient("AccessKey","secretkey",Amazon.RegionEndpoint.USWest2);
DataTable data = new DataTable();
try
{
Dimension dim = new Dimension() { Name = "InstanceId", Value = "InstanceId of you EC2 Server" };
System.Collections.Generic.List<Dimension> dimensions = new List<Dimension>() { dim };
string startTime1 = DateTimeOffset.Parse(DateTime.Now.AddMinutes(-60).ToString()).ToUniversalTime().ToString("s");
GetMetricStatisticsRequest reg = new GetMetricStatisticsRequest()
{
MetricName = "CPUUtilization",
Period = 60,
Statistics = new System.Collections.Generic.List<string>() { "Average","Minimum","Maximum" },
Dimensions = dimensions,
Namespace = "AWS/EC2",
EndTime = DateTime.Now, //Convert.ToDateTime(DateTime.Now.ToUniversalTime().ToString("s")), //has to be in this format: 2010-09-29T14:00:00+01:00;
StartTime = DateTime.Now.AddHours(Convert.ToInt32(-15)),// Convert.ToDateTime(startTime1),
};
var points = cw.GetMetricStatistics(reg).GetMetricStatisticsResult.Datapoints.OrderBy(p => p.Timestamp);
data.Columns.Add("Average");
data.Columns.Add("TimeStamp");
foreach (var p in points)
{
DataRow row = data.NewRow();
row["Average"] = Math.Round(p.Average, 0);
row["TimeStamp"] = p.Timestamp; //DateTimeOffset.Parse(Convert.ToDateTime(p.Timestamp)).LocalDateTime.ToString("yyyy-MM-dd HH:mm");
data.Rows.Add(row);
}
dataGridView1.DataSource = data;
}
catch (AmazonCloudWatchException ex)
{
if (ex.ErrorCode.Equals("OptInRequired"))
throw new Exception("You are not signed in for Amazon EC2.");
else
throw;
}
Pleas also note that when you want to get CPU usage or any other type of metric, you should be wary of the time-stamp you include in the request. This is because it can take more than 48 hours for data to become available in CloudWatch (according to Amazon).
That is why I personally try to retrieve data from about 3-4 days ago as sometimes CloudWatch will not return any data even if the request and the code are all correct as it does not have any data to publish from the previous day or two.
For more information check this URL and scroll down to StartTime: http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricStatistics.html