Example #1
0
        /// <summary>
        /// Action Results for Index, OAuthToken, OAuthVerifyer and RealmID is recieved as part of Response
        /// and are stored inside Session object for future references
        /// NOTE: Session storage is only used for demonstration purpose only.
        /// </summary>
        /// <param name="sender">Sender of the event.</param>
        /// <param name="e">Event Args.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString.HasKeys())
            {
                // This value is used to Get Access Token.
                _oauthVerifyer = Request.QueryString["oauth_verifier"].ToString();

                _realmid = Request.QueryString["realmId"].ToString();
                HttpContext.Current.Session["realm"] = _realmid;

                //If dataSource is QBO call QuickBooks Online Services, else call QuickBooks Desktop Services
                _dataSource = Request.QueryString["dataSource"].ToString();
                HttpContext.Current.Session["dataSource"] = _dataSource;

                getAccessToken();

                //Production applications should securely store the Access Token.
                //In this template, encrypted Oauth access token is persisted in OauthAccessTokenStorage.xml
                OauthAccessTokenStorageHelper.StoreOauthAccessToken(Page);

                // This value is used to redirect to Default.aspx from Cleanup page when user clicks on ConnectToInuit widget.
                Session["RedirectToDefault"] = true;
            }
            else
            {
                Response.Write("No oauth token was received");
            }
        }
Example #2
0
        /// <summary>
        /// Action Results for Index, uses DotNetOpenAuth for creating OpenId Request with Intuit
        /// and handling response recieved.
        /// </summary>
        /// <returns></returns>
        public RedirectResult Index()
        {
            var openid_identifier = ConfigurationManager.AppSettings["openid_identifier"].ToString();;
            var response          = openid.GetResponse();

            if (response == null)
            {
                // Stage 2: user submitting Identifier
                Identifier id;
                if (Identifier.TryParse(openid_identifier, out id))
                {
                    try
                    {
                        IAuthenticationRequest request = openid.CreateRequest(openid_identifier);
                        FetchRequest           fetch   = new FetchRequest();
                        fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Contact.Email));
                        fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Name.FullName));
                        request.AddExtension(fetch);
                        request.RedirectToProvider();
                    }
                    catch (ProtocolException ex)
                    {
                        throw ex;
                    }
                }
            }
            else
            {
                if (response.FriendlyIdentifierForDisplay == null)
                {
                    Response.Redirect("/OpenId");
                }

                // Stage 3: OpenID Provider sending assertion response, storing the response in Session object is only for demonstration purpose
                Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay;
                FetchResponse fetch = response.GetExtension <FetchResponse>();
                if (fetch != null)
                {
                    Session["OpenIdResponse"] = "True";
                    Session["FriendlyEmail"]  = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email); // emailAddresses.Count > 0 ? emailAddresses[0] : null;
                    Session["FriendlyName"]   = fetch.GetAttributeValue(WellKnownAttributes.Name.FullName); //fullNames.Count > 0 ? fullNames[0] : null;

                    //get the Oauth Access token for the user from OauthAccessTokenStorage.xml
                    OauthAccessTokenStorageHelper.GetOauthAccessTokenForUser(Session["FriendlyEmail"].ToString(), this);
                }
            }

            string query = Request.Url.Query;

            if (!string.IsNullOrWhiteSpace(query) && query.ToLower().Contains("disconnect=true"))
            {
                Session["accessToken"]       = "dummyAccessToken";
                Session["accessTokenSecret"] = "dummyAccessTokenSecret";
                Session["Flag"] = true;
                return(Redirect("/CleanupOnDisconnect/Index"));
            }

            return(Redirect("/Home/index"));
        }
Example #3
0
        /// <summary>
        /// Creates a HttpRequest with oAuthSession (OAuth Token) and gets the response with invalidating user
        /// from QuickBooks for this app
        /// For Authorization: The request header must include the OAuth parameters defined by OAuth Core 1.0 Revision A.
        ///
        /// If the disconnect is successful, then the HTTP status code is 200 and
        /// the XML response includes the <ErrorCode> element with a 0 value.
        /// If an HTTP error is detected, then the HTTP status code is not 200.
        /// If an HTTP error is not detected but the disconnect is unsuccessful,
        /// then the HTTP status code is 200 and the response XML includes the <ErrorCode> element with a non-zero value.
        /// For example,  if the OAuth access token expires or is invalid for some other reason, then the value of <ErrorCode> is 270.
        /// </summary>
        /// <param name="sender">Sender of the event.</param>
        /// <param name="e">Event args.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            OAuthConsumerContext consumerContext = new OAuthConsumerContext
            {
                ConsumerKey     = ConfigurationManager.AppSettings["consumerKey"].ToString(),
                SignatureMethod = SignatureMethod.HmacSha1,
                ConsumerSecret  = ConfigurationManager.AppSettings["consumerSecret"].ToString()
            };

            OAuthSession oSession = new OAuthSession(consumerContext, Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlRequestToken,
                                                     Constants.OauthEndPoints.AuthorizeUrl,
                                                     Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlAccessToken);

            oSession.ConsumerContext.UseHeaderForOAuthParameters = true;
            if ((Session["accessToken"] + "").Length > 0)
            {
                oSession.AccessToken = new TokenBase
                {
                    Token       = HttpContext.Current.Session["accessToken"].ToString(),
                    ConsumerKey = ConfigurationManager.AppSettings["consumerKey"].ToString(),
                    TokenSecret = HttpContext.Current.Session["accessTokenSecret"].ToString()
                };

                IConsumerRequest conReq = oSession.Request();
                conReq = conReq.Get();
                conReq = conReq.ForUrl(Constants.IaEndPoints.DisconnectUrl);
                try
                {
                    conReq = conReq.SignWithToken();
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                //Used just see the what header contains
                string header = conReq.Context.GenerateOAuthParametersForHeader();

                //This method will clean up the OAuth Token
                txtServiceResponse = conReq.ReadBody();

                //Reset All the Session Variables
                HttpContext.Current.Session.Remove("oauthToken");

                // Add the invalid access token into session for the display of the Disconnect btn
                HttpContext.Current.Session["InvalidAccessToken"] = HttpContext.Current.Session["accessToken"];

                // Dont remove the access token since this is required for Reconnect btn in the Blue dot menu
                // HttpContext.Current.Session.Remove("accessToken");

                // Dont Remove flag since we need to display the blue dot menu for Reconnect btn in the Blue dot menu
                // HttpContext.Current.Session.Remove("Flag");
                DisconnectFlg = "User is Disconnected from QuickBooks!";
                //Remove the Oauth access token from the OauthAccessTokenStorage.xml
                OauthAccessTokenStorageHelper.RemoveInvalidOauthAccessToken(Session["FriendlyEmail"].ToString(), Page);
            }
        }
Example #4
0
        /// <summary>
        /// Action Results for Index
        /// </summary>
        /// <returns>Action Result.</returns>
        public ActionResult Index()
        {
            realmId           = Session["realm"].ToString();
            accessToken       = Session["accessToken"].ToString();
            accessTokenSecret = Session["accessTokenSecret"].ToString();
            consumerKey       = ConfigurationManager.AppSettings["consumerKey"].ToString();
            consumerSecret    = ConfigurationManager.AppSettings["consumerSecret"].ToString();
            dataSourcetype    = Session["dataSource"].ToString().ToLower();


            try
            {
                IntuitServicesType intuitServicesType = new IntuitServicesType();
                switch (dataSourcetype)
                {
                case "qbo":
                    intuitServicesType = IntuitServicesType.QBO;
                    break;

                case "qbd":
                    intuitServicesType = IntuitServicesType.QBD;
                    break;

                default:
                    throw new Exception("Data source type not found.");
                    break;
                }

                OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
                ServiceContext        context        = new ServiceContext(realmId, intuitServicesType, oauthValidator);
                DataService           dataService    = new DataService(context);
                List <Customer>       customers      = dataService.FindAll(new Customer(), 1, 100).ToList();
                ViewBag.MyCollection  = customers;
                ViewBag.CustomerCount = customers.Count();
            }
            catch (InvalidTokenException exp)
            {
                //Remove the Oauth access token from the OauthAccessTokenStorage.xml
                OauthAccessTokenStorageHelper.RemoveInvalidOauthAccessToken(Session["FriendlyEmail"].ToString(), this);

                Session["show"] = true;
                return(Redirect("/Home/index"));
            }
            catch (System.Exception exp)
            {
                throw exp;
            }

            return(View());
        }
Example #5
0
        /// <summary>
        /// Action Results for Index
        /// </summary>
        /// <returns>Action Result.</returns>
        public ActionResult Index()
        {
            realmId           = Session["realm"].ToString();
            accessToken       = Session["accessToken"].ToString();
            accessTokenSecret = Session["accessTokenSecret"].ToString();
            consumerKey       = ConfigurationManager.AppSettings["consumerKey"].ToString();
            consumerSecret    = ConfigurationManager.AppSettings["consumerSecret"].ToString();
            dataSourcetype    = Session["dataSource"].ToString();

            OAuthRequestValidator oauthValidator = Initializer.InitializeOAuthValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
            ServiceContext        context        = Initializer.InitializeServiceContext(oauthValidator, realmId, string.Empty, string.Empty, dataSourcetype);
            DataServices          commonService  = new DataServices(context);

            try
            {
                // Specify a Request validator
                if (dataSourcetype.ToLower() == "qbd")
                {
                    Intuit.Ipp.Data.Qbd.CustomerQuery qbdCustomerQuery = new Intuit.Ipp.Data.Qbd.CustomerQuery();
                    qbdCustomerQuery.ItemElementName = Intuit.Ipp.Data.Qbd.ItemChoiceType4.StartPage;
                    qbdCustomerQuery.Item            = "1";
                    qbdCustomerQuery.ChunkSize       = "10";
                    IEnumerable <Intuit.Ipp.Data.Qbd.Customer> customers = qbdCustomerQuery.ExecuteQuery <Intuit.Ipp.Data.Qbd.Customer>
                                                                               (context) as IEnumerable <Intuit.Ipp.Data.Qbd.Customer>;
                }
                else
                {
                    Intuit.Ipp.Data.Qbo.Customer qboCustomer             = new Intuit.Ipp.Data.Qbo.Customer();
                    IEnumerable <Intuit.Ipp.Data.Qbo.Customer> customers = commonService.FindAll(qboCustomer, 1, 10) as IEnumerable <Intuit.Ipp.Data.Qbo.Customer>;
                    ViewBag.MyCollection  = customers;
                    ViewBag.CustomerCount = customers.Count();
                }
            }
            catch (Intuit.Ipp.Exception.InvalidTokenException exp)
            {
                //Remove the Oauth access token from the OauthAccessTokenStorage.xml
                OauthAccessTokenStorageHelper.RemoveInvalidOauthAccessToken(Session["FriendlyEmail"].ToString(), this);
                //show a message to the user that token is invalid
                string message = "<SCRIPT LANGUAGE='JavaScript' >alert('Your authorization to this application to access your quickbook data is no longer Valid.Please provide authorization again.')</SCRIPT>";
                // show user the connect to quickbook page again
                Response.Write(message);
                Redirect("/Home/index");
            }
            catch (System.Exception exp)
            {
                throw exp;
            }

            return(View());
        }
        /// <summary>
        /// Page Load Event, pulls data from QuickBooks using SDK and Binds it to Grid
        /// </summary>
        /// <param name="sender">Sender of the event.</param>
        /// <param name="e">Event Args.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (HttpContext.Current.Session.Keys.Count > 0)
            {
                realmId           = HttpContext.Current.Session["realm"].ToString();
                accessToken       = HttpContext.Current.Session["accessToken"].ToString();
                accessTokenSecret = HttpContext.Current.Session["accessTokenSecret"].ToString();
                consumerKey       = ConfigurationManager.AppSettings["consumerKey"].ToString();
                consumerSecret    = ConfigurationManager.AppSettings["consumerSecret"].ToString();
                dataSourcetype    = HttpContext.Current.Session["dataSource"].ToString();

                OAuthRequestValidator oauthValidator = Initializer.InitializeOAuthValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
                ServiceContext        context        = Initializer.InitializeServiceContext(oauthValidator, realmId, string.Empty, string.Empty, dataSourcetype);
                try
                {
                    Intuit.Ipp.QueryFilter.QueryService <Intuit.Ipp.Data.Customer> customerQueryService =
                        new Intuit.Ipp.QueryFilter.QueryService <Intuit.Ipp.Data.Customer>(context);
                    List <Intuit.Ipp.Data.Customer> customers = customerQueryService.Select(s => s).ToList();
                    GridView1.DataSource = customers;
                    GridView1.DataBind();
                    if (GridView1.Rows.Count > 0)
                    {
                        GridLocation.Visible    = true;
                        MessageLocation.Visible = false;
                    }
                    else
                    {
                        GridLocation.Visible    = false;
                        MessageLocation.Visible = true;
                    }
                }
                catch (Intuit.Ipp.Exception.InvalidTokenException exp)
                {
                    //Remove the Oauth access token from the OauthAccessTokenStorage.xml
                    OauthAccessTokenStorageHelper.RemoveInvalidOauthAccessToken(Session["FriendlyEmail"].ToString(), Page);
                    //show a message to the user that token is invalid
                    string message = "<SCRIPT LANGUAGE='JavaScript' >alert('Your authorization to this application to access your quickbook data is no longer Valid.Please provide authorization again.')</SCRIPT>";
                    // show user the connect to quickbook page again
                    Response.Write(message);
                    Response.Redirect("default.aspx");
                }
                catch (System.Exception exp)
                {
                    throw exp;
                }
            }
        }
Example #7
0
        /// <summary>
        /// Action Results for Index
        /// </summary>
        /// <returns>Action Result.</returns>
        public ActionResult Index()
        {
            realmId           = Session["realm"].ToString();
            accessToken       = Session["accessToken"].ToString();
            accessTokenSecret = Session["accessTokenSecret"].ToString();
            consumerKey       = ConfigurationManager.AppSettings["consumerKey"].ToString();
            consumerSecret    = ConfigurationManager.AppSettings["consumerSecret"].ToString();
            dataSourcetype    = Session["dataSource"].ToString();

            OAuthRequestValidator oauthValidator = Initializer.InitializeOAuthValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
            ServiceContext        context        = Initializer.InitializeServiceContext(oauthValidator, realmId, string.Empty, string.Empty, dataSourcetype);

            try
            {
                Intuit.Ipp.QueryFilter.QueryService <Intuit.Ipp.Data.Customer> customerQueryService = new Intuit.Ipp.QueryFilter.QueryService <Intuit.Ipp.Data.Customer>(context);
                List <Intuit.Ipp.Data.Customer> customers = customerQueryService.Select(s => s).ToList();
                ViewBag.MyCollection  = customers;
                ViewBag.CustomerCount = customers.Count();
            }
            catch (Intuit.Ipp.Exception.InvalidTokenException exp)
            {
                //Remove the Oauth access token from the OauthAccessTokenStorage.xml
                OauthAccessTokenStorageHelper.RemoveInvalidOauthAccessToken(Session["FriendlyEmail"].ToString(), this);
                //show a message to the user that token is invalid
                string message = "<SCRIPT LANGUAGE='JavaScript' >alert('Your authorization to this application to access your quickbook data is no longer Valid.Please provide authorization again.')</SCRIPT>";
                // show user the connect to quickbook page again
                Response.Write(message);
                Redirect("/Home/index");
            }
            catch (System.Exception exp)
            {
                throw exp;
            }

            return(View());
        }
Example #8
0
        /// <summary>
        /// Page Load Event, pulls data from QuickBooks using SDK and Binds it to Grid
        /// </summary>
        /// <param name="sender">Sender of the event.</param>
        /// <param name="e">Event Args.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (HttpContext.Current.Session.Keys.Count > 0)
            {
                realmId           = HttpContext.Current.Session["realm"].ToString();
                accessToken       = HttpContext.Current.Session["accessToken"].ToString();
                accessTokenSecret = HttpContext.Current.Session["accessTokenSecret"].ToString();
                consumerKey       = ConfigurationManager.AppSettings["consumerKey"].ToString();
                consumerSecret    = ConfigurationManager.AppSettings["consumerSecret"].ToString();
                dataSourcetype    = HttpContext.Current.Session["dataSource"].ToString();

                OAuthRequestValidator oauthValidator = Initializer.InitializeOAuthValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
                ServiceContext        context        = Initializer.InitializeServiceContext(oauthValidator, realmId, string.Empty, string.Empty, dataSourcetype);
                DataServices          commonService  = new DataServices(context);

                try
                {
                    // Specify a Request validator
                    if (dataSourcetype.ToLower() == "qbd")
                    {
                        Intuit.Ipp.Data.Qbd.CustomerQuery qbdCustomerQuery = new Intuit.Ipp.Data.Qbd.CustomerQuery();
                        qbdCustomerQuery.ItemElementName = Intuit.Ipp.Data.Qbd.ItemChoiceType4.StartPage;
                        qbdCustomerQuery.Item            = "1";
                        qbdCustomerQuery.ChunkSize       = "10";
                        IEnumerable <Intuit.Ipp.Data.Qbd.Customer> customers = qbdCustomerQuery.ExecuteQuery <Intuit.Ipp.Data.Qbd.Customer>
                                                                                   (context) as IEnumerable <Intuit.Ipp.Data.Qbd.Customer>;
                        GridView1.DataSource = customers;
                    }
                    else
                    {
                        Intuit.Ipp.Data.Qbo.Customer qboCustomer             = new Intuit.Ipp.Data.Qbo.Customer();
                        IEnumerable <Intuit.Ipp.Data.Qbo.Customer> customers = commonService.FindAll(qboCustomer, 1, 10) as IEnumerable <Intuit.Ipp.Data.Qbo.Customer>;
                        GridView1.DataSource = customers;
                    }

                    GridView1.DataBind();
                    if (GridView1.Rows.Count > 0)
                    {
                        GridLocation.Visible    = true;
                        MessageLocation.Visible = false;
                    }
                    else
                    {
                        GridLocation.Visible    = false;
                        MessageLocation.Visible = true;
                    }
                }
                catch (Intuit.Ipp.Exception.InvalidTokenException exp)
                {
                    //Remove the Oauth access token from the OauthAccessTokenStorage.xml
                    OauthAccessTokenStorageHelper.RemoveInvalidOauthAccessToken(Session["FriendlyEmail"].ToString(), Page);
                    //show a message to the user that token is invalid
                    string message = "<SCRIPT LANGUAGE='JavaScript' >alert('Your authorization to this application to access your quickbook data is no longer Valid.Please provide authorization again.')</SCRIPT>";
                    // show user the connect to quickbook page again
                    Response.Write(message);
                    Response.Redirect("default.aspx");
                }
                catch (System.Exception exp)
                {
                    throw exp;
                }
            }
        }