public ActionResult Index() { var param = Session[SESSION_KEY] as SessionParameters; if (param == null) { ViewBag.ErrorMessage = "Unable to retrieve required session param."; return(View("BookError")); } if (param.LtiUri == null) { ViewBag.ErrorMessage = "LTI param are not valid."; return(View("BookError")); } // retrieve the required version information from the LMS var factory = new D2LAppContextFactory(); var appContext = factory.Create(m_defaultAppId, m_defaultAppKey); var hostInfo = new HostSpec(param.LtiUri.Scheme, param.LtiUri.Host, param.LtiUri.Port); ID2LUserContext context = appContext.CreateUserContext(Request.Url, hostInfo); if (context == null) { ViewBag.ErrorMessage = "Unable to create user context."; return(View("BookError")); } param.UserContext = context; return(RedirectToAction("Assigned")); }
public Models.Enrollment.EnrollmentData EnrollUser(int OrgUnitID, int UserID, int RoleId) { m_valenceUserContext = m_valenceAppContext.CreateUserContext(m_userId, m_userKey, m_valenceHost); Models.Enrollment.EnrollmentData rtnValue = new Models.Enrollment.EnrollmentData(); Models.Enrollment.CreateEnrollmentData model = new Models.Enrollment.CreateEnrollmentData(OrgUnitID, UserID, RoleId ); var client = new RestClient("https://" + LMS_URL); var authenticator = new ValenceAuthenticator(m_valenceUserContext); var request = new RestRequest( USER_CREATE_ENROLLMENT, Method.POST); RestSharp.Parameter p = new Parameter (); p.Type = ParameterType.RequestBody; p.Name = "CreateEnrollmentData"; p.Value = SimpleJson.SerializeObject(model); request.AddParameter(p); authenticator.Authenticate(client, request); var response = client.Execute (request); return null; }
public void SetUpAppContext() { var timestampProvider = TestUtils.CreateTimestampProviderStub(TestConstants.TIMESTAMP_MILLISECONDS); m_appContext = TestUtils.CreateAppContextUnderTest(timestampProvider); m_userContext = CreateUserContextUnderTest(); m_anonContext = CreateAnonymousContextUnderTest(); }
/* * Creates a new ID2LUserContext object * * @return * an instance of a ID2LUserContext */ public static ID2LUserContext GetD2LUserContext() { D2LAppContextFactory factory = new D2LAppContextFactory(); ID2LAppContext appContext = factory.Create(Utility.GetAppIdValence(), Utility.GetAppKeyValence()); HostSpec hostInfo = new HostSpec(Utility.GetSchemaValence(), Utility.GetHostValence(), Utility.GetPortValence()); ID2LUserContext userContext = appContext.CreateUserContext(Utility.GetUserIdValence(), Utility.GetUserKeyValence(), hostInfo); return(userContext); }
public ValenceAuthenticator CreateAuthenticator() { D2LAppContextFactory contextFactory = new D2LAppContextFactory(); ID2LAppContext appContext = contextFactory.Create(m_appId, m_appKey); HostSpec valenceHost = new HostSpec("https", m_lmsUrl, 443); ID2LUserContext userContext = appContext.CreateUserContext(m_userId, m_userKey, valenceHost); return(new ValenceAuthenticator(userContext)); }
private static HttpWebRequest CreateGetRequestForRoute( ID2LUserContext opContext, string route) { var mainUri = opContext.CreateAuthenticatedUri(route, "GET"); var request = (HttpWebRequest)WebRequest.Create(mainUri); request.Method = "GET"; return(request); }
static void Main(string[] args) { ConfigManager.SetAppConfigurationValue(); //Create a user context to make Valence API call ID2LUserContext userContext = APIUtility.GetD2LUserContext(); //Download data zip file and extract it. APIUtility.DownloadFile(userContext); }
public Valence() { var appFactory = new D2LAppContextFactory(); m_valenceAppContext = appFactory.Create(m_appId, m_appKey); m_valenceHost = new HostSpec("https", LMS_URL, 443); // Note Using existing authenicated Tokens m_valenceUserContext = m_valenceAppContext.CreateUserContext(m_userId, m_userKey, m_valenceHost); }
public void SendRequest_WhenBadHostSpec_UnhandledException() { HostSpec badApiHost = new HostSpec(ChangeScheme(ConfigHelper.Scheme), ConfigHelper.Host, ConfigHelper.Port); ID2LUserContext badAnonContext = ContextProvider.AnonUserContext(badApiHost); HttpWebRequest request = RequestProvider.PrepareApiRequest(badAnonContext, RouteProvider.VersionsRoute); Assert.Throws <WebException>(() => { using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { } }); }
public ActionResult Index( ) { m_valenceUserContext = Session["valenceUserContext"] as ID2LUserContext; if (m_valenceUserContext == null) { return RedirectToAction( "NeedsAuth" ); } ViewBag.user = WhoAmI(); return View(); }
public ActionResult Index( ) { m_valenceUserContext = Session["valenceUserContext"] as ID2LUserContext; if (m_valenceUserContext == null) { return(RedirectToAction("NeedsAuth")); } ViewBag.user = WhoAmI(); return(View()); }
public void SendRequestWithBadKeys_ResponseInterpretationIs_InvalidSig() { ID2LUserContext badContext = ContextProvider.BadUserContext(); HttpWebRequest request = RequestProvider.PrepareApiRequest(badContext, RouteProvider.OrganizationInfoRoute); try { using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { } } catch (WebException ex) { var exceptionWrapper = new D2LWebException(ex); var interpretation = badContext.InterpretResult(exceptionWrapper); Assert.AreEqual(RequestResult.RESULT_INVALID_SIG, interpretation); } }
private static void DoApiStuff( string host, ID2LUserContext userContext ) { const string WHOAMI_ROUTE = "/d2l/api/lp/1.0/users/whoami"; var client = new RestClient( host ); var valenceAuthenticator = new D2L.Extensibility.AuthSdk.Restsharp.ValenceAuthenticator( userContext ); var request = new RestRequest( WHOAMI_ROUTE, Method.GET ); valenceAuthenticator.Authenticate( client, request ); var response = client.Execute<WhoAmIResponse>( request ); Console.WriteLine( "Hello, " + response.Data.FirstName + " " + response.Data.LastName ); }
private HttpWebResponse RetryGetRequest(ID2LUserContext opContext, string route) { var mainRequest = CreateGetRequestForRoute(opContext, route); try { return(mainRequest.GetResponse() as HttpWebResponse); } catch (WebException ex) { var exWrapper = new D2LWebException(ex); opContext.InterpretResult(exWrapper); } var retryRequest = CreateGetRequestForRoute(opContext, route); return(retryRequest.GetResponse() as HttpWebResponse); }
private static void DoApiStuff(string host, ID2LUserContext userContext) { const string WHOAMI_ROUTE = "/d2l/api/lp/1.0/users/whoami"; var client = new RestClient(host); var valenceAuthenticator = new D2L.Extensibility.AuthSdk.Restsharp.ValenceAuthenticator(userContext); var request = new RestRequest(WHOAMI_ROUTE, Method.GET); valenceAuthenticator.Authenticate(client, request); var response = client.Execute <WhoAmIResponse>(request); Console.WriteLine("Hello, " + response.Data.FirstName + " " + response.Data.LastName); }
public bool DeleteUser(int OrgUnitID, int UserID) { m_valenceUserContext = m_valenceAppContext.CreateUserContext(m_userId, m_userKey, m_valenceHost); Models.Enrollment.EnrollmentData rtnValue = new Models.Enrollment.EnrollmentData(); var client = new RestClient("https://" + LMS_URL); var authenticator = new ValenceAuthenticator(m_valenceUserContext); string url = string.Format(USER_ENROLL_REMOVE, OrgUnitID.ToString(), UserID.ToString()); var request = new RestRequest(url, Method.DELETE); authenticator.Authenticate(client, request); var response = client.Execute(request); return true; }
public Context(Configuration config) { var appFactory = new D2LAppContextFactory(); ValenceAppContext = appFactory.Create(config["appId"], config["appKey"]); ValenceHost = new HostSpec("https", config["lmsUrl"], 443); Client = new RestClient("https://" + config["lmsUrl"]); if (File.Exists(".bs-auth")) { ValenceUserContext = ValenceAppContext.CreateUserContext(new Uri(File.ReadAllText(".bs-auth")), ValenceHost); } else { ValenceUserContext = null; } }
public void SendAuthenticatedRequestWithDelayedTimestamp_ResponseMustContainTimeOffset() { ID2LAppContext appContext = CreateAppContextWithDelay(ConfigHelper.AppId, ConfigHelper.AppKey, TEST_TIME_DELAY); ID2LUserContext userContext = ContextProvider.UserContext(appContext); Uri uri = userContext.CreateAuthenticatedUri(RouteProvider.OrganizationInfoRoute, "GET"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.Method = "GET"; try { using (request.GetResponse() as HttpWebResponse) { } } catch (WebException ex) { string responseContents = StringHelper.ReadResponseContents(ex.Response as HttpWebResponse); StringAssert.IsMatch("Timestamp out of range\\s?(\\d+)", responseContents); return; } Assert.Fail("Expected WebException was not thrown"); }
public static void Perform(HttpWebRequest request, ID2LUserContext userContext, HandleResponse responseHandler, HandleError errorHandler, int retryAttempts = 0) { try { using (var response = (HttpWebResponse)request.GetResponse()) { using (var stream = response.GetResponseStream()) { using (var reader = new StreamReader(stream, Encoding.UTF8)) { string responseBody = reader.ReadToEnd(); responseHandler(responseBody); } } } } catch (WebException we) { var exceptionWrapper = new D2LWebException(we); var result = userContext.InterpretResult(exceptionWrapper); switch (result) { case RequestResult.RESULT_INVALID_TIMESTAMP: if (retryAttempts > 0) { // re-create the request to ensure the new url accounts for calculated skew Uri uri = userContext.CreateAuthenticatedUri(request.RequestUri.AbsoluteUri, request.Method); request = (HttpWebRequest)WebRequest.Create(uri); Perform(request, userContext, responseHandler, errorHandler, retryAttempts - 1); } break; } errorHandler(result, request.RequestUri); } catch (ArgumentException) { errorHandler(RequestResult.RESULT_UNKNOWN, request.RequestUri); } }
public static void Perform( HttpWebRequest request, ID2LUserContext userContext, HandleResponse responseHandler, HandleError errorHandler, int retryAttempts = 0) { try { using (var response = (HttpWebResponse) request.GetResponse()) { using (var stream = response.GetResponseStream()) { using (var reader = new StreamReader( stream, Encoding.UTF8 )) { string responseBody = reader.ReadToEnd(); responseHandler( responseBody ); } } } } catch (WebException we) { var exceptionWrapper = new D2LWebException( we ); var result = userContext.InterpretResult( exceptionWrapper ); switch (result) { case RequestResult.RESULT_INVALID_TIMESTAMP: if (retryAttempts > 0) { // re-create the request to ensure the new url accounts for calculated skew Uri uri = userContext.CreateAuthenticatedUri( request.RequestUri.AbsoluteUri, request.Method ); request = (HttpWebRequest) WebRequest.Create( uri ); Perform( request, userContext, responseHandler, errorHandler, retryAttempts - 1 ); } break; } errorHandler( result, request.RequestUri ); } catch (ArgumentException) { errorHandler( RequestResult.RESULT_UNKNOWN, request.RequestUri ); } }
private T MakeApiCall <T>(ID2LUserContext userContext, string hostUrl, string apiUrl) where T : new() { if (userContext == null) { throw new Exception("This method can only be used for an authenticated user"); } var client = new RestClient(HttpScheme.Https + hostUrl); var authenticator = new ValenceAuthenticator(userContext); var request = new RestRequest(apiUrl); authenticator.Authenticate(client, request); var response = client.Execute <T>(request); if (response.StatusCode != HttpStatusCode.OK) { _logger.InfoFormat("[D2L API call] Url: {0}, Status: {1}-{2}, ErrorMessage:{3}, Content:{4}", apiUrl, (int)response.StatusCode, response.StatusDescription, response.ErrorMessage, response.Content); } return(response.Data); }
public void RetryAuthenticatedRequestWithCorrectedTimestamp_ResultCodeIs200() { ID2LAppContext appContext = CreateAppContextWithDelay(ConfigHelper.AppId, ConfigHelper.AppKey, TEST_TIME_DELAY); ID2LUserContext userContext = ContextProvider.UserContext(appContext); Uri uri = userContext.CreateAuthenticatedUri(RouteProvider.OrganizationInfoRoute, "GET"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.Method = "GET"; try { using (request.GetResponse() as HttpWebResponse) { } } catch (WebException ex) { var exWrapper = new D2LWebException(ex); userContext.InterpretResult(exWrapper); } Uri retryUri = userContext.CreateAuthenticatedUri(RouteProvider.OrganizationInfoRoute, "GET"); HttpWebRequest retryRequest = (HttpWebRequest)WebRequest.Create(retryUri); retryRequest.Method = "GET"; Assert.DoesNotThrow(() => { using (HttpWebResponse response = retryRequest.GetResponse() as HttpWebResponse) { } }); }
internal static HttpWebRequest PrepareApiRequest( ID2LUserContext userContext, string route ) { Uri apiUri = userContext.CreateAuthenticatedUri( route, "GET" ); return CreateRequest( apiUri ); }
public void SetUpTestUserContext() { m_userContext = TestUtils.CreateTestUserContext(); }
public ValenceAuthenticator( ID2LUserContext context ) { m_context = context; }
protected void CallGetVersions(ID2LUserContext userContext, int retryAttempts) { //in this case we are using an anonymous user Uri uri = userContext.CreateAuthenticatedUri( "/d2l/api/versions/", "GET"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.Method = "GET"; try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { string responseBody = reader.ReadToEnd(); JavaScriptSerializer serializer = new JavaScriptSerializer(); ProductVersions[] versions = serializer.Deserialize<ProductVersions[]>(responseBody); String output = ""; foreach (ProductVersions v in versions) { output += v.ProductCode + ": " + v.LatestVersion + "<br />"; } resultBox.InnerHtml = output; } } } } //catches status codes in the 4 and 5 hundred series catch (WebException we) { D2LWebException exceptionWrapper = new D2LWebException(we); RequestResult result = userContext.InterpretResult(exceptionWrapper); switch (result) { //if the timestamp is invalid and we haven't exceeded the retry limit then the call is made again with the adjusted timestamp case RequestResult.RESULT_INVALID_TIMESTAMP: if (retryAttempts > 0) { CallWhoAmI(userContext, retryAttempts - 1); } break; } } }
public bool UpdateCourseActivation(string orgUnitId, bool Activation) { // Get Course Object Models.Course.CourseOffering course = GetCourseOffering(orgUnitId); Models.Course.CourseOfferingInfo model = new Models.Course.CourseOfferingInfo(course); model.IsActive = Activation.ToString(); m_valenceUserContext = m_valenceAppContext.CreateUserContext(m_userId, m_userKey, m_valenceHost); var client = new RestClient("https://" + LMS_URL); var authenticator = new ValenceAuthenticator(m_valenceUserContext); var request = new RestRequest(string.Format(COURSE_UPDATE,orgUnitId), Method.PUT ); RestSharp.Parameter p = new Parameter(); p.Type = ParameterType.RequestBody; p.Name = "CourseOfferingInfo"; p.Value = SimpleJson.SerializeObject(model); request.AddParameter(p); authenticator.Authenticate(client, request); var response = client.Execute(request); return true; }
public ValenceAuthenticator(ID2LUserContext context) { this.context = context; }
public void SetUpAppContext() { m_appContext = TestUtils.CreateAppContextUnderTest(); TestUtils.SetUpTimestampProviderStub( TestConstants.TIMESTAMP_MILLISECONDS ); m_userContext = CreateUserContextUnderTest(); m_anonContext = CreateAnonymousContextUnderTest(); }
protected void CallWhoAmI(ID2LUserContext userContext,int retryAttempts) { Uri uri = userContext.CreateAuthenticatedUri( "/d2l/api/lp/1.0/users/whoami?fakeparam=lol", "GET"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.Method = "GET"; request.AllowAutoRedirect = false; try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { string responseBody = reader.ReadToEnd(); JavaScriptSerializer serializer = new JavaScriptSerializer(); WhoAmIUser user = serializer.Deserialize<WhoAmIUser>(responseBody); resultBox.InnerHtml = "<div>First Name: " + user.FirstName + "</div><div>Last Name: " + user.LastName + "</div><div>D2LID: " + user.Identifier + "</div>"; ; } } } } //catches status codes in the 4 and 5 hundred series catch (WebException we) { D2LWebException exceptionWrapper = new D2LWebException(we); RequestResult result = userContext.InterpretResult(exceptionWrapper); System.Diagnostics.Debug.WriteLine(result.ToString()); switch (result) { //if there is no user or the current user doesn't have permission to perform the action case RequestResult.RESULT_INVALID_SIG: resultBox.InnerHtml = "Error Must Authenticate as User With Permission"; break; //if the timestamp is invalid and we haven't exceeded the retry limit then the call is made again with the adjusted timestamp case RequestResult.RESULT_INVALID_TIMESTAMP: if (retryAttempts > 0) { CallWhoAmI(userContext, retryAttempts - 1); } break; } } }
internal static HttpWebRequest PrepareApiRequest(ID2LUserContext userContext, string route) { Uri apiUri = userContext.CreateAuthenticatedUri(route, "GET"); return(CreateRequest(apiUri)); }
/* * Download zip file and extract * * @param userContext * an instance of ID2LUserContext to create verivied credentials * * @return * nothing.... */ public static void DownloadFile(ID2LUserContext userContext) { // Data Path string dataPath = Utility.GetDownloadDataPathValence(); // Log Path string logPath = Utility.GetLogPathValence(); // Error Log Path string errorlogPath = "/home/justin/temp/ErrorLog.txt"; // Status Log Path string statusLogPath = "/home/justin/temp/StatusLog.txt"; //save zip file string zipPath = @"" + dataPath + "D2LDataFile.zip"; //File path for extract string extractPath = @"" + dataPath + "ExtractD2lDataFile"; //API version string apiVersion = Utility.GetApiVersion(); //File path for destination string destPath = @"" + dataPath + "CombinedD2LDataFile\\"; // Check to see if directories are on the disk // if not then create them // Utility.CreateOrCheckDirectory (destPath); Utility.CreateOrCheckDirectory(errorlogPath); Utility.CreateOrCheckDirectory(statusLogPath); //Create a request string request = "/d2l/api/lp/" + apiVersion + "/dataExport/bds/list"; //URI Uri getListUri = userContext.CreateAuthenticatedUri(request, "GET"); try{ //Start the clock so we know how long the download took var startTime = DateTime.Now; // Flag for any errors in downloading var flag = false; // strat a web client using (WebClient wc = new WebClient()) { wc.Headers.Add("User-Agent:Other"); // Get a list of PuginID from the web service byte[] response = wc.DownloadData(getListUri); // convert the list into a string string str = wc.Encoding.GetString(response); var strList = str.Split('{').Skip(1); // get a name of to ignore string skipFileName = Utility.GetSkipFileName(); // create a list of the file names to skip var skipList = skipFileName.Split(','); // (Loop through the donwloaded data) for (int z = 0; z < strList.Count(); z++) { //foreach(string s in strList){ // This is all failry slow, is there any way we can speed it up? string s = strList.ElementAt(z); // I do not think that string ops is slowing it down // Extract the pluginID from the string var pluginId = ExtractStringValue(s, 0, 12, 1); // Extract the fileName from the string var name = ExtractStringValue(s, 1, 8, 1).Replace(" ", ""); // Extract the Download link from the string var dLink = ExtractStringValue(s, 4, 15, 0); // Now check if download link is available and if the name does not belong to the // list of names to skip.... if (dLink.Length > 6 && !skipList.Any(name.Contains)) { using (WebClient wc1 = new WebClient()){ //Create a webrequest and URI to download the data string request1 = "/d2l/api/lp/" + apiVersion + "/dataExport/bds/download/" + pluginId; //Acturally create the URI Uri uri = userContext.CreateAuthenticatedUri(request1, "GET"); //D Download the file and store it zip Console.WriteLine((z + 1) + ": Downloading: " + name); wc1.DownloadFile(uri, zipPath); // this is where it is slow (I think) // Now extract the zip contents and store them //Print out a message to display what were downloading for debugging purposes Console.WriteLine((z + 1) + ": Extracting : " + name); System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, "/home/justin/temp/"); } // Now copy the files to the specified folder and get rid of any unwanted directories // var st = Directory.GetFiles((extractPath), "*.csv"); // File.Copy(st[0], Path.GetFileName(st[0]), true); // Directory.Delete((extractPath), true); //debugging purposes // if(z == 2) // break; } else { //Log any names that were skipped if (skipList.Any(name.Contains)) { Utility.WriteToFile(errorlogPath, name, "The download skipped for file name"); } else { //Log any names that were not downloaded but not meant to be skipped Utility.WriteToFile(errorlogPath, name, "The download failed for file name"); flag = true; } } } // string targetDest = "/home/justin/temp/"; // string cwd = "/home/justin/Downloads/StudentSuccess/StudentSuccess"; // string[] files = Directory.GetFiles(cwd, "*.csv *.txt *.zip"); // foreach(string s in files){ // System.IO.File.Copy(s, targetDest,true); // } } //Donwload should be complete so stop the clock var endTime = DateTime.Now; if (flag == false) { // All files were download succesfully, log this Utility.WriteToFile(statusLogPath, "All Files", "Download Completed", String.Format(" Download Time {0}", (endTime - startTime))); } else { // Not all files were donwloaded, log this Utility.WriteToFile(statusLogPath, "Some Files", "Download partially Completed", String.Format(" Download Time {0}", (endTime - startTime))); } } catch (Exception e) { /* * if download fails for whatever reason * ie we were unable to connect, Log this into the * log file and print out the exception */ Utility.WriteToFile(statusLogPath, "All Files", "Download Failed", e.Message); } }