Web Agora.io DYNAMIC_KEY_EXPIRED - c#

I am using c# with mvc.
I used this code to generate token and generated successfully. but after generate token when join channel using .join() it return DYNAMIC_KEY_EXPIRED.
I Used "AgoraRTCSDK-3.1.0.js"
I used https://github.com/AgoraIO/Tools/blob/master/DynamicKey/AgoraDynamicKey/csharp to generate dynamic token
If any one has experience on Agora.io, please help me.
Sample code is..
AccessToken token = new AccessToken(apiKey, appCertificate, channelName, "0");
token.addPrivilege(Privileges.kJoinChannel, _expiredTs);
token.addPrivilege(Privileges.kPublishAudioStream, _expiredTs);
token.addPrivilege(Privileges.kPublishVideoStream, _expiredTs);
string strToken = token.build();
public string build()
{
this._messageRawContent = Utils.pack(this.message);
this._signature = generateSignature(_appCertificate
, _appId
, _channelName
, _uid
, _messageRawContent);
this._crcChannelName = Crc32CAlgorithm.Compute(this._channelName.GetByteArray());
this._crcUid = Crc32CAlgorithm.Compute(this._uid.GetByteArray());
PackContent packContent = new PackContent(_signature, _crcChannelName, _crcUid, this._messageRawContent);
byte[] content = Utils.pack(packContent);
return getVersion() + this._appId + Utils.base64Encode(content);
}

Whenever you generate a token for Agora applications, you need to keep in mind that the expiration time is calculated as a timestamp (time since 1970) so you need to ensure the the expiration time is set to the currentTime + expirationTimeInSeconds.
In the above example you are passing the expiration time as 0 which generates a token that is already considered expired.
consider using:
// set a expiration time of 1 hour in seconds
let expireTime = 3600;
// calculate current time in seconds
const currentTime = Math.floor(Date.now() / 1000);
// calculate privilege expire time
const privilegeExpireTime = currentTime + expireTime;

Related

EWS Performance in C# WinForms application

I'm using EWS in my winforms application to create a new appointment in my Outlook (+ to get items from my Outlook Calendar).
The issue i'm having is the following:
Everything works perfect but currently it takes 20-25 seconds to retrieve my appointments (= calendar items in Outlook) and 13-20 seconds to create an appointment
The code that does this comes straight from 'Google':
private void btn_Test_Click(object sender, EventArgs e)
{
DateTime d1 = DateTime.Now;
ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
try
{
service = new ExchangeService(ExchangeVersion.Exchange2013);
service.Credentials = new WebCredentials("mail", "pass");
/*service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;*/
service.AutodiscoverUrl("mail", RedirectionUrlValidationCallback);
service.Url = new Uri("https://mail.domain.com/EWS/Exchange.asmx");
}
catch (Exception ml2)
{
MessageBox.Show(ml2.ToString());
}
// We get 10 items in the calendar for the next week
DateTime startDate = DateTime.Now;
DateTime endDate = startDate.AddDays(7);
const int NUM_APPTS = 10;
// Initialize the calendar folder object with only the folder ID.
CalendarFolder calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());
// Set the start and end time and number of appointments to retrieve.
CalendarView cView = new CalendarView(startDate, endDate, NUM_APPTS);
// Limit the properties returned to the appointment's subject, start time, and end time.
cView.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End);
// Retrieve a collection of appointments by using the calendar view.
FindItemsResults<Appointment> appointments = calendar.FindAppointments(cView);
Console.WriteLine("\nThe first " + NUM_APPTS + " appointments on your calendar from " + startDate.Date.ToShortDateString() +
" to " + endDate.Date.ToShortDateString() + " are: \n");
foreach (Appointment a in appointments)
{
Console.Write("Subject: " + a.Subject.ToString() + " ");
Console.Write("Start: " + a.Start.ToString() + " ");
Console.Write("End: " + a.End.ToString());
Console.WriteLine();
}
DateTime d2 = DateTime.Now;
MessageBox.Show( "Seconds: " + (d2 - d1).TotalSeconds.ToString());
}
Since I have absolutely 0 experience with EWS (or developing while using API's) I was wondering if there was room for performance or I wanted to know if this is just normal? I haven't found anything EWS = SLOW related so I was worrying a bit.
Could it be that my code is wrong or that i need to configure one thing or another server sided to improve results?
Thanks
The most likely thing to slow down you code is
service.AutodiscoverUrl("mail", RedirectionUrlValidationCallback);
service.Url = new Uri("https://mail.domain.com/EWS/Exchange.asmx");
You do an AutoDiscover and then set the link manually which is make the first AutoDiscover Call redundant. Auto-discover will do multiple searches of Local AD domain, DNS records to try and discover the correct URL to use so I would suggest if you are going to hardcode the URL you remark out the first line.
Also your testing logic only looks at the total time to execute you function which isn't going to be helpfully you should look at the time to complete each operation eg
FindItemsResults<Appointment> appointments = calendar.FindAppointments(cView);
or
CalendarFolder calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());
or any Save, Send type method call when the actually call to the server is made if you time this that will give you a true indication of the speed of each call.

How do I update a Cloudwatch custom metric in C#?

How do I create a custom metric for my Elastic Beanstalk environment in C#?
I have a numerical metric seconds.
I use the following code:
double seconds = ts.Seconds + (Convert.ToDouble(ts.Milliseconds / 10) / 100);
using (AmazonCloudWatchClient cloudwatch = new AmazonCloudWatchClient(accessKey, secretKey))
{
PutMetricDataRequest mdr = new PutMetricDataRequest();
mdr.Namespace = "Performance";
MetricDatum dataPoint = new MetricDatum();
dataPoint.MetricName = "UploadSpeedInSeconds";
dataPoint.Unit = "Seconds";
dataPoint.Value = seconds;
}
I have no idea were to continue on. I want the custom metric to mesuare the uploads in seconds of files. I already have the metric value, and I want to update a custom metric so I can keep track of it (BTW: can I view the custom metric in the console?).
Don't forget to actually send it off to AWS:
mdr.MetricData = new List<MetricDatum>();
mdr.MetricData.Add(dataPoint);
PutMetricDataResponse resp = cloudwatch.PutMetricData(mdr);
Debug.Assert(resp.HttpStatusCode == System.Net.HttpStatusCode.OK);

Manage booking policy of resources in Exchange 2013 via Managed Api

I want to manage the booking policy of a room, maximum duration of a meeting for example. Do someone has idea how do you do that via Managed API?
The managed API cannot police max duration but what you need todo is validate the entry before you submit a reservation...
public override bool IsNoOverTimeLimit(Reservation reservation)
{
return reservation.End.Subtract(reservation.Start).TotalMinutes <= 120;
}
if(!IsNoOverTimeLimit)
{
var errorMsg = new Label();
var fontSize = FontUnit.Point(10);
errorMsg.Font.Size = fontSize;
errorMsg.Text = "Reservation time is limited to " + ((float)30 / 60).ToString(CultureInfo.InvariantCulture) + " hours at a time.<br /> ";
placeHolder.Controls.Add(errorMsg);
}
My version is way more complicated than this but you get the point. Just simply check the reservation before you submit and if over time limit, return to page with some pretty warning..

Google Analytics API in C# -Execution of request failed: https://www.google.com/analytics/feeds/accounts/default

i want to access Google analytic data and i got samples from Google data API SDK. but these coding does not working and throws exception
Execution of request failed: https://www.google.com/analytics/feeds/accounts/default
so i found the reason for this is Google updated it's to v3.0. i searched updated coding for the C#, but i couldn't find solution for this.
i have same problem as this, but with C#.
Exception thrown when using GData .NET Analytics API
i tried coding with doing changes as follows as it says in Google developer - https://developers.google.com/analytics/resources/articles/gdata-migration-guide#appendix_a
string userName = this.Username.Text;
string passWord = this.Password.Text;
AnalyticsService service = new AnalyticsService("AnalyticsSampleApp");
service.setUserCredentials(userName, passWord);
string googleAccountWebId = "AIXXXXXXXXXXXXXXXXXXXXXXXXXXX";
string profileFeedUrl = "https://www.googleapis.com/analytics/v2.4/data?key=" + googleAccountWebId;
DataQuery query2 = new DataQuery(profileFeedUrl);
query2.Ids = "12345678";
query2.Metrics = "ga:visits";
query2.Sort = "ga:visits";
query2.GAStartDate = DateTime.Now.AddMonths(-1).AddDays(-2).ToString("2011-08-01");
query2.GAEndDate = DateTime.Now.ToString("2013-09-01");
query2.StartIndex = 1;
DataFeed data = service.Query(query2);
foreach (DataEntry entry in data.Entries)
{
string st=entry.Metrics[0].Value;
}
but even i change this it throws exception in
DataFeed data = service.Query(query2);
this line. exception is as follows:
Execution of request failed: https://www.googleapis.com/analytics/v2.4/data?key=AIXXXXXXXXXXXXXXXXXXXXXX-8&start-index=1&end-date=2013-09-01&ids=12345678&metrics=ga:visits&sort=ga:visits&start-date=2011-08-01
i'm using following DLL
Google.GData.Analytics.dll
Google.GData.Client.dll
Google.GData.Extensions.dll
My Questions :
how can i correct this error?
how can i access Google analytic data? is this correct? or else what is the way to doing it??
for a example i want to get available ProfileId and their values. (Title and Page views)
Analytics Account:
I am assuming you have an analytics account already if you don't then create one, and sign up your domain here:
http://www.google.com/intl/en/analytics/
To get your API Key do this:
Follow the instructions on https://developers.google.com/analytics/resources/articles/gdata-migration-guide (Create a Project in the Google APIs Console) to generate your key Once you have it set it as part of the querystring to request to Google Analytics service, in this case:
YourAPIkEStringabcdefghijklmno
To get the profileId (Ids on the code) you should do this:
Log into your analytics account, select the desired domain on your list (blue link) click on the administrator button and on the profiles tab find the profile
configuration subtab, right there you will find the profile id in this case the eight characters long id:
12345678
Here you have some C# code to help you getting the number of visits for that Id:
public string VisitsNumber()
{
string visits = string.Empty;
string username = "youremailuser#domain.com";
string pass = "yourpassword";
string gkey = "?key=YourAPIkEYYourAPIkEYYourAPIkEYYourAPIkE";
string dataFeedUrl = "https://www.google.com/analytics/feeds/data" + gkey;
string accountFeedUrl = "https://www.googleapis.com/analytics/v2.4/management/accounts" + gkey;
AnalyticsService service = new AnalyticsService("WebApp");
service.setUserCredentials(username, pass);
DataQuery query1 = new DataQuery(dataFeedUrl);
query1.Ids = "ga:12345678";
query1.Metrics = "ga:visits";
query1.Sort = "ga:visits";
//You were setting 2013-09-01 and thats an invalid date because it hasn't been reached yet, be sure you set valid dates
//For start date is better to place an aprox date when you registered the domain on Google Analytics for example January 2nd 2012, for an end date the actual date is enough, no need to go further
query1.GAStartDate = new DateTime(2012, 1, 2).ToString("yyyy-MM-dd");
query1.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");
query1.StartIndex = 1;
DataFeed dataFeedVisits = service.Query(query1);
foreach (DataEntry entry in dataFeedVisits.Entries)
{
string st = entry.Title.Text;
string ss = entry.Metrics[0].Value;
visits = ss;
}
return visits;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Write("Visits:" + this.VisitsNumber());
}
}
Since the 2.4 API is not so flexible anymore, I have another post here hacking it to get the profile Id:
Getting an specific ProfileId from registered Accounts using GData .NET Analytics API 2.4 if you need to convert the code to C# you can use the Telerik converter: http://converter.telerik.com/
I think this suffice to use the 2.4 API. If you need extra help let me know.

.NET Active Directory Password Expiration on Windows 2008

Searched SO and Everywhere else, including the .net developers guide to directory services programming book - no luck.
I am trying to create a simple password reset web page that allows the user to change their password. The change password portion of the code is working fine. For the users I would also like to display when their current password will expire next.
Using the sample code from the book mentioned above I was able to get all of the code setup however, the attribute that is returned is always equal to Long.MinValue and hence cannot be inverted to a positive number, plus this means it did not find the proper domain setting.
Does anyone have sample code or references for getting the password expiration in a Windows 2008 or R2 domain environment where password policies can be different for each user?
Updated to include code
Constructor that gets the policy object:
public PasswordExpires()
{
//Get Password Expiration
Domain domain = Domain.GetCurrentDomain();
DirectoryEntry root = domain.GetDirectoryEntry();
using (domain)
using (root)
{
this.policy = new DomainPolicy(root);
}
}
Domain Policy Constructor:
public DomainPolicy(DirectoryEntry domainRoot)
{
string[] policyAttributes = new string[] {
"maxPwdAge", "minPwdAge", "minPwdLength",
"lockoutDuration", "lockOutObservationWindow",
"lockoutThreshold", "pwdProperties",
"pwdHistoryLength", "objectClass",
"distinguishedName"
};
//we take advantage of the marshaling with
//DirectorySearcher for LargeInteger values...
DirectorySearcher ds = new DirectorySearcher(
domainRoot,
"(objectClass=domainDNS)",
policyAttributes,
SearchScope.Base
);
SearchResult result = ds.FindOne();
//do some quick validation...
if (result == null)
{
throw new ArgumentException(
"domainRoot is not a domainDNS object."
);
}
this.attribs = result.Properties;
}
Call this method to get the password expiration:
public TimeSpan MaxPasswordAge
{
get
{
string val = "maxPwdAge";
if (this.attribs.Contains(val))
{
long ticks = GetAbsValue(
this.attribs[val][0]
);
if (ticks > 0)
return TimeSpan.FromTicks(ticks);
}
return TimeSpan.MaxValue;
}
}
Code fails here because it cannot convert Long.MinValue, which it should not be in the first place
private long GetAbsValue(object longInt)
{
return Math.Abs((long)longInt);
}
Here is the debugger output and values. According to the MSDN Site the overflow exception is caused from the minvalue. My numbers match the examples for minvalue.
Screenshot http://www.brentpabst.com/capture.png
Password expiration times are stored such that if lastPwdSet - maxPwdAge < DateTime.UtcNow is true, then your password is expired. So if you set your password a week ago, but the password will expire in 10 days, the left side will be (DateTime.UtcNow - 7) - (-10), or DateTime.UtcNow - 7 + 10, or DateTime.UtcNow + 3, which is not less than DateTime.UtcNow, so your password won't be expired.
This means that setting maxPwdAge to long.MinValue will effectively give you thousands of years before your password expires. So if you are getting long.MinValue, your policy says that passwords won't expire. You should just look for that value and treat it properly, possibly like this:
private long GetAbsValue(object longInt) // poorly named
{
long val = (long)longInt;
if (val == long.MinValue)
return long.MaxValue;
return Math.Abs((long)longInt);
}
Also, I should point out that the values are stored in 100-nanosecond increments, so you should expect values in the billions.

Categories