A class for providing an instance of ID2LAppContext
        static void Main()
        {
            // This is the LMS we will interact with
            var host = new HostSpec( "https", "lms.valence.desire2learn.com", 443 );

            // The appId/appKey come from our app.config - it is good to seperate access keys from the code that uses them.
            // Ideally you wouldn't have production keys committed to source control.
            string appId = ConfigurationManager.AppSettings["appId"];
            string appKey = ConfigurationManager.AppSettings["appKey"];

            // This is the port we will temporarily host a server on to intercept the user tokens after a successful login
            int port = int.Parse( ConfigurationManager.AppSettings["serverPort"] );

            // Create url for the user to login. If they have already done so they will not actually have to type their password (maybe).
            var appContextFactory = new D2LAppContextFactory();
            var appContext = appContextFactory.Create( appId, appKey );
            var authUrl = appContext.CreateUrlForAuthentication( host, new Uri( "http://localhost:" + port + "/result/" ) );

            OpenBrowser( authUrl );

            // This call will block until we have a result
            // TODO: you'll want better control flow and error handling here
            var userContext = InterceptUserTokens( host, appContext );

            // Now we can call Valence
            DoApiStuff( host.Scheme + "://" + host.Host + ":" + host.Port, userContext );

            // Pause the terminal
            Console.ReadKey();
        }
Exemplo n.º 2
0
    protected void GetVersions(object sender, EventArgs e)
    {
        D2LAppContextFactory factory = new D2LAppContextFactory();
        ID2LAppContext appContext = factory.Create(Session["appID"].ToString(), Session["appKey"].ToString());

        int port;
        try
        {
            //try to read the port specified
            port = Convert.ToInt32(portField.Text);
        }
        catch (Exception)
        {
            //fallback to https port
            port = 443;
        }

        HostSpec hostInfo = new HostSpec("https", hostField.Text, port);

        //anonymous user context has the standard AppID/AppKey with null UserID/UserKey
        //grabs the apiHost information(scheme, hostname, port) and stores that as well
        ID2LUserContext userContext = appContext.CreateAnonymousUserContext(
        hostInfo);
        CallGetVersions(userContext, 2);
    }
Exemplo n.º 3
0
        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);
        }
Exemplo n.º 4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["appID"] == null)
        {
            Session["appID"] = _defaultAppID;
            Session["appKey"] = _defaultAppKey;
        }
        appIDField.Text = Session["appID"].ToString();
        appKeyField.Text = Session["appKey"].ToString();
        hostField.Text = "valence.desire2learn.com";
        if (!Page.IsPostBack)
        {
            var factory = new D2LAppContextFactory();

            //assigns the AppID and AppKey into the AppID and AppKey in the AppContext
            var appContext = factory.Create(Session["appID"].ToString(), Session["appKey"].ToString());

            int port;
            try
            {
                //try to read the port specified
                port = Convert.ToInt32(portField.Text);
            }
            catch (Exception error)
            {
                //fallback to https port
                port = 443;
            }
            //holds the scheme, hostname and which port to use
            HostSpec hostInfo = new HostSpec("https", hostField.Text, port);

            //saves the callback url as well as sets up the AppID, AppKey, UserID, and UserKey
            //if run without x_a, x_b, will be null
            ID2LUserContext userContext = appContext.CreateUserContext(Request.Url, hostInfo);
            if (userContext != null)
            {
                
                //This is how applications may want to store the info and handle authentication. This example must deal with changing information and therefore
                //cannot rely on an important variable being the same.
                Session["userContext"] = userContext;
                UserContextProperties properties = userContext.SaveUserContextProperties();
                Session["userID"] = properties.UserId;
                Session["userKey"] = properties.UserKey;
            }
            
        }
        if (Session["userID"] != null)
        {
            userIDField.Text = Session["userID"].ToString();
            userKeyField.Text = Session["userKey"].ToString();
        }

    }
Exemplo n.º 5
0
        private static int Main( string[] args )
        {
            var options = new Options();
            try {
                if (!Parser.Default.ParseArguments( args, options )) {
                    return -1;
                }
            }
            catch (TargetInvocationException e) {
                Console.Error.Write( options.GetUsage() );
                Console.Error.WriteLine( e.InnerException.InnerException.Message );
                return -2;
            }

            var host = new Uri( options.Host );
            var appContextFactory = new D2LAppContextFactory();
            var appContext = appContextFactory.Create( options.AppId, options.AppKey );
            var userContext = appContext.CreateAnonymousUserContext( new HostSpec( host.Scheme, host.Host, host.Port ) );

            const int MAX_ATTEMPTS = 3;
            var attempts = 0;
            IRestResponse response;
            bool again;
            do {
                if (options.Verbose && attempts != 0) {
                    Console.WriteLine( "Making attempt #" + ( attempts + 1 ) );
                }
                var client = new RestClient( host.ToString() );
                var authenticator = new ValenceAuthenticator( userContext );
                var request = new RestRequest( VERSIONS_ROUTE, Method.GET );
                authenticator.Authenticate( client, request );

                response = client.Execute( request );

                again = false;
                if (response.StatusCode == HttpStatusCode.Forbidden && response.Content.StartsWith( "Timestamp out of range" )) {
                    var serverTime = 1000*long.Parse( new string( response.Content.SkipWhile( x => !char.IsNumber( x ) ).ToArray() ) );
                    userContext.ServerSkewMillis = serverTime - GetTime();
                    again = true;
                }

                attempts++;
            } while (again & attempts < MAX_ATTEMPTS);

            if (options.Verbose && attempts == MAX_ATTEMPTS) {
                Console.WriteLine( "Too much timestamp skew, giving up." );
            }

            if (response.StatusCode == HttpStatusCode.OK) {
                try {
                    JsonConvert.DeserializeObject<List<VersionsItem>>( response.Content );
                }
                catch (JsonSerializationException e) {
                    Console.Error.WriteLine( "Call succeeded but could not deserialize the response." );
                    Console.Error.Write( "Error: " );
                    Console.Error.WriteLine( Indent( e.Message ) );
                    if (!string.IsNullOrEmpty( response.Content )) {
                        Console.Error.WriteLine( "Response:" );
                        Console.Error.WriteLine( Indent( response.Content ) );
                    }
                    return -3;
                }
                Console.WriteLine( "Ok" );
                if (options.Verbose) {
                    Console.WriteLine( "Response headers:" );
                    PrintHeaders( Console.Out, response );
                    Console.WriteLine( "Response body:" );
                    Console.WriteLine( Indent( response.Content ) );
                }
                return 0;
            }

            if (options.Guess) {
                if (response.StatusCode == HttpStatusCode.Forbidden && response.Content == "Invalid token") {
                    Console.WriteLine( "App not synced to LMS or explicitly denied in Manage Extensibility." );
                }
                else if (response.StatusCode == HttpStatusCode.Forbidden && response.Content.StartsWith( "Timestamp out of range" )) {
                    Console.WriteLine( "Timestamp skew could not be rectified." );
                }
                else if (!string.IsNullOrEmpty( response.ErrorMessage )) {
                    Console.WriteLine( response.ErrorMessage );
                }
                else {
                    Console.WriteLine( "Unknown error" );
                }
            }
            else {
                Console.Error.WriteLine( "Failure!" );
                if (response.ErrorMessage != null) {
                    Console.Error.WriteLine( "Error: " );
                    Console.Error.WriteLine( Indent( response.ErrorMessage ) );
                }
                if (response.StatusDescription != null) {
                    Console.Error.WriteLine( "Response status: " );
                    Console.Error.WriteLine( Indent( response.StatusDescription ) );
                }
                if (response.Headers != null) {
                    PrintHeaders( Console.Error, response );
                }
                if (!String.IsNullOrEmpty( response.Content )) {
                    Console.Error.WriteLine( "Response: " );
                    Console.Error.WriteLine( Indent( response.Content ) );
                }
            }
            return -4;
        }
 public HomeController( )
 {
     var appFactory = new D2LAppContextFactory();
     m_valenceAppContext = appFactory.Create( m_appId, m_appKey );
     m_valenceHost = new HostSpec( "https", LMS_URL, 443 );
 }
 static ContextProvider()
 {
     m_appContextFactory = new D2LAppContextFactory();
     m_appContext = m_appContextFactory.Create( ConfigHelper.AppId, ConfigHelper.AppKey );
 }
Exemplo n.º 8
0
    protected void WhoAmI(object sender, EventArgs e)
    {
        //if the settings couldn't be changed between calls the next few steps would be replaced with using Session["userContext"] 
        D2LAppContextFactory factory = new D2LAppContextFactory();
        ID2LAppContext appContext = factory.Create(Session["appID"].ToString(), Session["appKey"].ToString());

        int port;
        try
        {
            //try to read the port specified
            port = Convert.ToInt32(portField.Text);
        }
        catch (Exception error)
        {
            //fallback to https port
            port = 443;
        }

        String userID = "t";
        String userKey = "t";
        if (Session["userID"] != null)
        {
            userID = Session["userID"].ToString(); 
            userKey = Session["userKey"].ToString();
        }
        HostSpec hostInfo = new HostSpec("https", hostField.Text, port);
        ID2LUserContext userContext = appContext.CreateUserContext(
           userID, userKey, hostInfo);
        CallWhoAmI(userContext, 2);
       
    }
Exemplo n.º 9
0
    protected void Authenticate(object sender, EventArgs e)
    {
        //These would normally not be stored in the session and would not change. In this sample we save them to the session to accomodate testing to see new ID's and keys are working. 
        Session["appID"] = appIDField.Text;
        Session["appKey"] = appKeyField.Text;
        
        D2LAppContextFactory factory = new D2LAppContextFactory();
        
        ID2LAppContext appContext = factory.Create(Session["appID"].ToString(), Session["appKey"].ToString());
        
        int port;
        try
        {
            //try to read the port specified
            port = Convert.ToInt32(portField.Text);
        }
        catch (Exception)
        {
            //fallback to https port
            port = 443;
        }


        Uri resultUri = new UriBuilder(Request.Url.Scheme, Request.Url.Host, Request.Url.Port, Request.Url.AbsolutePath).Uri;
        Uri uri = appContext.CreateUrlForAuthentication(new HostSpec("https",hostField.Text, port), resultUri);

        Response.Redirect(uri.ToString());
    }
Exemplo n.º 10
0
        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" );
        }
Exemplo n.º 11
0
        private Uri GenerateAuthRedirect( Uri returnUri, Uri requestUri )
        {
            if(( requestUri == null ) || ( returnUri == null )) {
                throw new ArgumentNullException();
            }

            var factory = new D2LAppContextFactory();
            var appContext = factory.Create( m_defaultAppId, m_defaultAppKey );

            var resultUri = new UriBuilder( requestUri.Scheme,
                                            requestUri.Host,
                                            requestUri.Port,
                                            requestUri.AbsolutePath ).Uri;

            var host = new HostSpec( returnUri.Scheme, returnUri.Host, returnUri.Port );
            var redirectUri = appContext.CreateUrlForAuthentication( host, resultUri );

            return redirectUri;
        }