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..
Related
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;
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.
I want to build Up/down voting system for several articles retrieved from database, but i want to add cookie for each article to limit number of votes so cookie will expires in one day, but i don't know where to add the appropriate code.
more details:
<script>
function vote(id, value) { // function vote with 2 arguments: article ID and value (+1 or -1) depending if you clicked on the arrow up or down
var dataFields = { 'id': id, 'value': value }; // We pass the 2 arguments
$.ajax({ // Ajax
type: "POST",
dataType: "text",//This for indicate that you'r expecting a text response from server
url: "WebService.asmx/updateVotes",
data: dataFields,
timeout: 3000,
success: function (dataBack) {
if(
$('#number' + id).html(dataBack);// div "number" with the new number
$('#arrow_up' + id).html('<div class="arrow_up_voted"></div>'); // We replace the clickable "arrow up" by the not clickable one
$('#arrow_down' + id).html('<div class="arrow_down_voted"></div>'); // We replace the clickable "arrow down" by the not clickable one
$('#message' + id).html('<div id="alertFadeOut' + id + '" style="color: green">Thank you for voting</div>'); // Diplay message with a fadeout
$('#alertFadeOut' + id).fadeOut(1100, function () {
$('#alertFadeOut' + id).text('');
});
},
error: function () {
$('#number' + id).text('Problem!');
}
});
}
</script>
the above code is a script calling ajax method to increase number of votes per one every time user click on the up arrow and decrease conversely.
public string updateVotes(string id,int value)
{
System.Threading.Thread.Sleep(500); // delay for 2.5 seconds Network latency
post p = db.posts.Find(int.Parse(id));
// assign new values
p.totalVotes += value;
db.Entry(p).State = System.Data.EntityState.Modified;
db.SaveChanges();
string dataBack =p.totalVotes.ToString();
return dataBack;
}
This is the webmethod.
Now i tried to think loudly and i code the following function to ewxamine if the cookie is null or not.
public bool enableVoting()
{
HttpCookie cookie = Request.Cookies["enableVote"];
if (Request.Cookies["enableVote"] != null)
{
return true;
}
else
{
return false;
}
}
i know it's wrong but at least i tried.
also where to add a for each loop to add cookie whenever user vote for article.?
foreach(post p in db.posts){
HttpCookie cookie = new HttpCookie("enableVote"+p.ID);
cookie.Value = "article:"+p.ID;
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
}
A suggestion. Don't use cookies for this. They are easily manipulated. Clear browser history and you can vote again.. and again.. and again.
Instead, create a Vote table in your database and add a record with the ip of the voter and the id of the post they voted for along with a timestamp.
This way you can easily count the votes and when someone votes you do a quick check on how long ago that IP last voted for that article (or any article).
Also with a vote table in your database you can easily catch bots that are up or downvoting everything, and limit the number of votes a single ip can make on any article (no more than 1 or two votes every few minutes maybe).
If your worried about multiple people behind the same IP not being able to vote you can include the browser name and only count unique ip and browser version as a vote. This is fairly unique. It can also be manipulated but its a little bit harder for the normal user.
Update:
I use this code for the purpose of getting a somewhat unique key in one of my MVC projects. The user can switch browsers and vote again, but it takes a bit of effort and its more of a pain than just clearing browser history.
I combine the IP, browser, and Country into a string and use that as a vote key.
public class UserInfo
{
public String ip { get; private set; }
public String browser { get; private set; }
public String country { get; private set; }
public UserInfo(HttpRequestBase Request)
{
ip = Request.UserHostAddress;
browser = Request.Browser.Platform + " " + Request.Browser.Type + "/" + Request.Browser.Id + " " + Request.Browser.Version;
country = "";
if (Request.UserLanguages.Length > 0)
country += " - " + Request.UserLanguages.ElementAt(0);
}
}
I'm using this system here: http://filepublicator.com/ to check if the user has any previously uploaded files (try to upload something and close browser and go there again, it will be in the list).
In ServiceNow, I am able to get only a maximum of 250 records in a SOAP request. How to get all the records?
Web Reference Url = https://*****.service-now.com/rm_story.do?WSDL
Code:
var url = "https://*****.service-now.com/rm_story.do?SOAP";
var userName = *****;
var password = *****;
var proxy = new ServiceNow_rm_story
{
Url = url,
Credentials = new NetworkCredential(userName, password)
};
try
{
var objRecord = new Namespace.WebReference.getRecords
{
// filters..
};
var recordResults = proxy.getRecords(objRecord);
}
catch (Exception ex)
{
}
In recordResults, I am getting only 250 records. How to get all the records ?
Also see this stack overflow answer which provides info.
Get ServiceNow Records Powershell - More than 250
Note that returning a large number of records can affect performance of the response and it may be more efficient to process your query in batches using offsets (i.e., get 1-100, then 101-200, ...). This can be achieved by using a sort order and offset. The ServiceNow REST Table API actually returns link headers from Get requests providing you links for the first, next and last set of records making it easy to know the url to query the next batch of records.
See: http://wiki.servicenow.com/index.php?title=Table_API#Methods
and look under 'Response Header'.
Have u tried to pass/override __limit parameter?
Google / wiki / Users manual / Release notes are always helpful
In your code snippet in line where it says //filter you should define __limit (and potentially __first_row and __last_row as explained in the example bellow)
int Skip = 0;
int Take = 250;
while (true)
{
using (var soapClient = new ServiceNowLocations.ServiceNow_cmn_location())
{
var cred = new System.Net.NetworkCredential(_user, _pass);
soapClient.Credentials = cred;
soapClient.Url = _apiUrl + "cmn_location.do?SOAP";
var getParams = new ServiceNowLocations.getRecords()
{
__first_row = Skip.ToString(),
__last_row = (Skip + Take).ToString(),
__limit = Take.ToString()
};
var records = soapClient.getRecords(getParams);
if (records != null)
{
if (records.Count() == 0)
{
break;
}
Skip += records.Count();
if (records.Count() != Take)
{
// last batch or everything in first batch
break;
}
}
else
{
// service now web service endpoint not configured correctly
break;
}
}
}
I made an library that handles interacting with ServiceNow Rest API much easier
https://emersonbottero.github.io/ServiceNow.Core/
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.