/// <summary>
        ///  BETA Create a section group with a given name under a given notebookId
        /// </summary>
        /// <param name="debug">Run the code under the debugger</param>
        /// <param name="notebookId">parent notebook's Id</param>
        /// <param name="sectionName">name of the section group to create</param>
        /// <param name="provider"></param>
        /// <param name="apiRoute"></param>
        /// <remarks>Create section group using a application/json content type</remarks>
        /// <returns>The converted HTTP response message</returns>
        public static async Task<ApiBaseResponse> CreateSectionGroupInNotebook(bool debug, string notebookId, string sectionGroupName, AuthProvider provider, string apiRoute)
        {
            if (debug)
            {
                Debugger.Launch();
                Debugger.Break();
            }

            var client = new HttpClient();

            // Note: API only supports JSON response.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // Not adding the Authentication header would produce an unauthorized call and the API will return a 401
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
                await Auth.GetAuthToken(provider));

            // Prepare an HTTP POST request to the SectionGroups endpoint
            // The request body content type is application/json and requires a name property
            var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute + @"notebooks/" + notebookId + "/sectiongroups")
            {
                Content = new StringContent("{ name : '" + WebUtility.UrlEncode(sectionGroupName) + "' }", Encoding.UTF8, "application/json")
            };

            HttpResponseMessage response = await client.SendAsync(createMessage);

            return await HttpUtils.TranslateResponse(response);
        }
Example #2
0
        public LoginPage(AuthProvider selectedProvider)
        {            
            dataSource = App.DataModel.Configuration;
            AuthProvider = selectedProvider;

            // We could create some alternate UI here to indicate that a login failed.
            // Have to be careful, because the contents of this page will show briefly
            // even for a successful login.
        }
Example #3
0
        protected override async Task OnInitializedAsync()
        {
            var authInfo = await AuthProvider.GetAuthenticationStateAsync();

            var authUser = authInfo.User.Identity;

            UserName ??= authUser.Name;
            var hubUri = $"{NavigationManager.BaseUri}api";

            if (NavigationManager.BaseUri.Contains("localhost"))
            {
                hubUri = "http://localhost:7071/api";
            }
            //must use API port for local host: "http://localhost:7071/api";
            hubConnection = new HubConnectionBuilder()
                            .WithUrl($"{hubUri}/", options =>
            {
                options.Headers.Add("x-ms-client-principal-id", UserName);
            })
                            .Build();

            hubConnection.On <object>("newMessage", (message) =>
            {
                var encodedMsg = $"{message}";
                Console.WriteLine($"received message: {encodedMsg}");
                messages.Add(encodedMsg);
                OnNewMessage.InvokeAsync(encodedMsg);
            });
            hubConnection.On <object>("groupMessage", (message) =>
            {
                var encodedMsg = $"{message}";
                Console.WriteLine($"received group message: {encodedMsg}");
                messages.Add(encodedMsg);
                OnNewMessage.InvokeAsync(encodedMsg);
            });
            hubConnection.On <object>("newCode", code =>
            {
                Console.WriteLine($"code received: {code}");
                CodeEditorService.SharedCodeSnippet = code.ToString();
            });
            hubConnection.On <object>("privateMessage", message =>
            {
                Console.WriteLine($"private received: {message}");
                messages.Add(message.ToString());
                OnNewMessage.InvokeAsync($"{message}");
            });
            hubConnection.On <object>("newOut", output =>
            {
                Console.WriteLine($"Output: {output}");
                OnNewMessage.InvokeAsync($"CODE OUTPUT::{output}");
            });
            await hubConnection.StartAsync();

            await JoinGroup();
        }
Example #4
0
        public static async Task <object> ExecuteApiPrereq(string uniqueId, AuthProvider provider, bool useBeta)
        {
            var apiEndPoint = ApiEndPoint(useBeta);

            switch (uniqueId)
            {
            case "Group-0-Item-0":
            case "Group-0-Item-1":
            case "Group-0-Item-2":
            case "Group-0-Item-3":
            case "Group-0-Item-4":
            case "Group-0-Item-5":
            case "Group-0-Item-6":
            case "Group-0-Item-7":
            case "Group-0-Item-8":
            case "Group-0-Item-10":
            case "Group-1-Item-7":
                return(await GetNotebooksExample.GetAllNotebooksExpand(false, provider, apiEndPoint));

            case "Group-1-Item-1":
                return(await GetPagesExample.GetAllPages(false, provider, apiEndPoint));

            case "Group-1-Item-6":
                return(await GetPagesExample.GetAllPages(false, provider, apiEndPoint));

            case "Group-2-Item-2":
                return(await GetNotebooksExample.GetAllNotebooks(false, provider, apiEndPoint));

            case "Group-2-Item-4":
                return(await GetSectionsExample.GetAllSections(false, provider, apiEndPoint));

            case "Group-2-Item-9":
                return(await GetNotebooksExample.GetAllNotebooks(false, provider, apiEndPoint));

            case "Group-2-Item-12":
                return(await GetNotebooksExample.GetAllNotebooks(false, provider, apiEndPoint));

            case "Group-2-Item-13":
                return(await GetSectionGroupsExample.GetAllSectionGroups(false, provider, apiEndPoint));

            case "Group-2-Item-14":
                return(await GetNotebooksExample.GetAllNotebooks(false, provider, apiEndPoint));

            case "Group-2-Item-15":
                return(await GetSectionGroupsExample.GetAllSectionGroups(false, provider, apiEndPoint));

            case "Group-3-Item-0":
                return(await GetPagesExample.GetAllPages(false, provider, apiEndPoint));

            case "Group-3-Item-1":
            case "Group-4-Item-0":
                return(await GetPagesExample.GetAllPages(false, provider, apiEndPoint));
            }
            return(null);
        }
Example #5
0
 internal static async Task <string> GetUserName(AuthProvider provider)
 {
     if (provider == AuthProvider.MicrosoftAccount)
     {
         return(await LiveIdAuth.GetUserName());
     }
     else
     {
         return(await O365Auth.GetUserName());
     }
 }
Example #6
0
 internal static bool IsSignedIn(AuthProvider provider)
 {
     if (provider == AuthProvider.MicrosoftAccount)
     {
         return(LiveIdAuth.IsSignedIn);
     }
     else
     {
         return(O365Auth.IsSignedIn);
     }
 }
Example #7
0
        private void Login()
        {
            //  Try out each section to see how it applies to your view screen
            string[] myACL;

            //  You can click the 'Read' button and close the window
            myACL = new string[] {
                ACL.CAN_READ,
                ACL.CAN_CLOSE
            };

            //  You can see both images but cannot click any button or close the window

            /*
             * myACL = new string[] {
             *  ACL.CAN_VIEW
             * };
             */

            //  You can close the window but cannot click any button

            /*
             * myACL = new string[] {
             *  ACL.CAN_CLOSE
             * };
             */

            //  You can see both images and click any button but cannot close the window

            /*
             * myACL = new string[] {
             *  ACL.CAN_VIEW,
             *  ACL.CAN_CREATE,
             *  ACL.CAN_READ,
             *  ACL.CAN_UPDATE,
             *  ACL.CAN_DELETE,
             * };
             */

            //  Full trust

            /*
             * myACL = new string[] {
             *  ACL.CAN_VIEW,
             *  ACL.CAN_CREATE,
             *  ACL.CAN_READ,
             *  ACL.CAN_UPDATE,
             *  ACL.CAN_DELETE,
             *  ACL.CAN_CLOSE
             * };
             */

            AuthProvider.Initialize <DefaultAuthProvider>(myACL);
        }
        public void Setup()
        {
            _authProvider   = new Mock <IAuthProvider>();
            _authController = new AuthController(_authProvider.Object);
            _config         = new Mock <IConfiguration>();
            _config.Setup(p => p["Jwt:Key"]).Returns("ThisismySecretKey");
            _authRepo = new Mock <IAuthRepo>();


            _provider = new AuthProvider(_authRepo.Object, _config.Object);
        }
Example #9
0
 public UnityRpcClient(String network = "mainnet", AuthProvider authProvider = null, JsonSerializerSettings jsonSerializerSettings = null)
 {
     this.authProvider = authProvider ?? BitskiSDK.AuthProviderImpl;
     if (jsonSerializerSettings == null)
     {
         jsonSerializerSettings = DefaultJsonSerializerSettingsFactory.BuildDefaultJsonSerializerSettings();
     }
     this.network = network;
     //check for nulls
     JsonSerializerSettings = jsonSerializerSettings;
 }
Example #10
0
        public ActionResult Index()
        {
            if (Request.IsAuthenticated)
            {
                return(AuthProvider.SignOutAndRedirect());
            }

            ViewBag.error  = 0;
            ViewBag.Titulo = "Login";
            return(View());
        }
Example #11
0
        public string RenewAuthToken(string uid)
        {
            Dictionary <string, object> clains = new Dictionary <string, object>();
            UserModel user = UserRepository.GetUserByUid(uid);

            clains.Add("role", user.Role.Name);
            clains.Add("roleId", user.RoleId);
            string token = AuthProvider.RenewCustomAuthToken(uid, clains);

            return(token);
        }
        public HttpResponseMessage login(UserLoginRequestModel userLoginRequestModel)
        {
            AuthProvider authProvider = new AuthProvider();
            ErrorModel   errorModel   = new ErrorModel();

            APIResponseModel responseModel = new APIResponseModel();

            responseModel.Response = authProvider.login(userLoginRequestModel, out errorModel);
            responseModel.Error    = errorModel;
            return(Request.CreateResponse(HttpStatusCode.OK, responseModel));
        }
Example #13
0
        public AuthProviderTests()
        {
            string key       = "ServerKey";
            var    configMoq = new Mock <IConfigurationService>();

            configMoq.Setup(config => config.GetValue(key)).Returns(GetServerKey());
            _authProvider = new AuthProvider(configMoq.Object);
            _device       = new Device {
                CarID = 1, ID = 1, OriginalID = "EF5ON3EOVH9X37", SecretKey = "adb6f6367722183007041ce6745dbe133d61e62e360fea0dd4c6ee5be1da5c53"
            };
        }
		internal static async Task SignOut(AuthProvider provider)
		{
			if (provider == AuthProvider.MicrosoftAccount)
			{
				await LiveIdAuth.SignOut();
			}
			else
			{
				await O365Auth.SignOut();
			}
		}
		internal static bool IsSignedIn(AuthProvider provider)
		{
			if (provider == AuthProvider.MicrosoftAccount)
			{
				return LiveIdAuth.IsSignedIn;
			}
			else
			{
				return O365Auth.IsSignedIn;
			}
		}
		internal static async Task<string> GetUserName(AuthProvider provider)
		{
			if (provider == AuthProvider.MicrosoftAccount)
			{
				return await LiveIdAuth.GetUserName();
			}
			else
			{
				return await O365Auth.GetUserName();
			}
		}
Example #17
0
 internal static async Task SignOut(AuthProvider provider)
 {
     if (provider == AuthProvider.MicrosoftAccount)
     {
         await LiveIdAuth.SignOut();
     }
     else
     {
         await O365Auth.SignOut();
     }
 }
Example #18
0
        private void AuthForm()
        {
            Login login = new Login();

            if (!login.ShowDialog().Value)
            {
                throw new Exception("Authorized exception has been occured.");
            }

            authProvider = login.AuthProvider;
        }
Example #19
0
        protected override object Run(LogoutData request)
        {
            AuthProvider.Logout(request.SessionId);

            return(new LogoutResponse()
            {
                ResponseStatus = new ResponseStatus()
                {
                    Message = "Hasta pronto...."
                }
            });
        }
        public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
        {
            if (AuthService.AuthProviders == null)
            {
                throw new InvalidOperationException("The AuthService must be initialized by calling "
                                                    + "AuthService.Init to use an authenticate attribute");
            }

            var matchingOAuthConfigs = AuthService.AuthProviders.Where(x =>
                                                                       this.Provider.IsNullOrEmpty() ||
                                                                       x.Provider == this.Provider).ToList();

            if (matchingOAuthConfigs.Count == 0)
            {
                res.WriteError(req, requestDto, "No OAuth Configs found matching {0} provider"
                               .Fmt(this.Provider ?? "any"));
                res.EndServiceStackRequest();
                return;
            }

            if (matchingOAuthConfigs.Any(x => x.Provider == DigestAuthProvider.Name))
            {
                AuthenticateIfDigestAuth(req, res);
            }

            if (matchingOAuthConfigs.Any(x => x.Provider == BasicAuthProvider.Name))
            {
                AuthenticateIfBasicAuth(req, res);
            }

            using (var cache = req.GetCacheClient())
            {
                var session = req.GetSession();

                if (session == null || !matchingOAuthConfigs.Any(x => session.IsAuthorized(x.Provider)))
                {
                    var htmlRedirect = HtmlRedirect ?? AuthService.HtmlRedirect;
                    if (htmlRedirect != null && req.ResponseContentType.MatchesContentType(ContentType.Html))
                    {
                        var url = htmlRedirect;
                        if (url.SafeSubstring(0, 2) == "~/")
                        {
                            url = req.GetBaseUrl().CombineWith(url.Substring(2));
                        }
                        url = url.AddQueryParam("redirect", req.AbsoluteUri);
                        res.RedirectToUrl(url);
                        return;
                    }

                    AuthProvider.HandleFailedAuth(matchingOAuthConfigs[0], session, req, res);
                }
            }
        }
Example #21
0
 public void GetNewToken()
 {
     try {
         var ap = new AuthProvider(_clientId, _clientSecret, _redirectUri, _webAgent);
         AccessToken           = ap.GetOAuthToken(_uname, _pass);
         _webAgent.AccessToken = AccessToken;
     }
     catch { //TODO error handling
         _timerState.TimerRunning = false;
         throw;
     }
 }
Example #22
0
        /// <summary>
        /// Update single entity
        /// </summary>
        public User Put(User user)
        {
            using (var scope = Scope("Put"))
            {
                AuthProvider.Authenticate(); // throws UnauthenticatedException or we have CurrentUser after this

                // prepare
                Helper.Expect(user, user.UserId);

                user.UserName = user.Email;

                if (user.UserId != null)
                {
                    user.UserId = user.UserId.ToLower();
                }

                var ownProfile = string.Compare(user.UserId, AuthProvider.CurrentUser.UserId, true) == 0;
                var oldUser    = UserManager.GetById(user.UserId); // throws EntityNotFoundException

                // authorize
                if (ownProfile)
                {
                    AuthProvider.Authorize(Permission.User_EditProfile);
                }
                else if (oldUser.Role == RoleType.Manager || oldUser.Role == RoleType.Admin)
                {
                    AuthProvider.Authorize(Permission.User_Management_EditAdmins); // only Admin can edit Admin
                }
                else
                {
                    AuthProvider.Authorize(Permission.User_Management);
                }

                // only Admin can set roles other than User
                if (!AuthProvider.HasPermission(Permission.User_Management_SetRole) && oldUser.Role != user.Role)
                {
                    throw new ValidationException("Role cannot be set.", false);
                }

                // validate
                Helper.ValidateModel(user, true);

                // process
                var entity = user.ToEntity();
                UserManager.Update(entity);

                return(scope.Complete(
                           () => new User(entity),
                           t => $"User has been updated with Id={t.UserId}."
                           ));
            }
        }
Example #23
0
        /// <summary>
        /// Update single entity
        /// </summary>
        public ServiceResult Put(User user)
        {
            try
            {
                AuthProvider.Authenticate(); // throws UnauthenticatedException or we have CurrentUser after this

                using (var context = PostContext(true, true))
                {
                    // prepare
                    Expect(user, user.UserId);

                    var ownProfile = string.Compare(user.UserId, AuthProvider.CurrentUser.UserId, true) == 0;
                    var oldUser    = UserManager.Get(user.UserId, true); // throws EntityNotFoundException

                    // authorize
                    if (ownProfile)
                    {
                        AuthProvider.Demand(Permission.User_EditProfile);
                    }
                    else if (oldUser.Group == Group.Admin)
                    {
                        AuthProvider.Demand(Permission.User_Management_EditAdmins); // only Admin can edit Admin
                    }
                    else
                    {
                        AuthProvider.Demand(Permission.User_Management);
                    }

                    // only Admin can set roles other than User
                    if (!AuthProvider.Authorized(Permission.User_Management_SetRole) && oldUser.Group != user.Group)
                    {
                        return(ValidationError("Group cannot be set."));
                    }

                    // validate
                    if (!ServiceModelValidator.ModelState.IsValid)
                    {
                        return(ValidationError(ServiceModelValidator.ModelState));
                    }

                    // process
                    UserManager.Update(user.ToEntity());

                    context.Complete();
                    return(OK());
                }
            }
            catch (Exception ex)
            {
                return(HandleException(ex));
            }
        }
        public void FailedTokenGenarationTest()
        {
            Mock <IConfiguration> config = new Mock <IConfiguration>();

            config.Setup(p => p["Jwt:Key"]).Returns("ThisismySecretKey");
            Mock <ICredentialsRepo> mock = new Mock <ICredentialsRepo>();

            mock.Setup(p => p.GetCredentials()).Returns(dc);
            AuthProvider cp     = new AuthProvider(mock.Object);
            string       result = cp.GenerateJSONWebToken(null, config.Object);

            Assert.IsNull(result);
        }
Example #25
0
        public async Task <IActionResult> Login(string refreshToken, AuthProvider provider)
        {
            var authService = authServices.Where(a => a.Provider == provider).FirstOrDefault();

            if (authService == null)
            {
                throw new DenialException($"Invalid provider: {provider}");
            }

            var token = await authService.RefreshTokenAsync(refreshToken);

            return(Ok(token));
        }
Example #26
0
        public ErrorCode Authenticate(string email, ref AuthProvider authProvider, out User user)
        {
            var statusCode = ErrorCode.Default;

            user = null;

            do
            {
                // No register
                if (!TryGetAuthProvider(authProvider.Id, out var dbAuth) || dbAuth == null)
                {
                    var inputEmail = authProvider.Email ?? email;

                    if (string.IsNullOrWhiteSpace(inputEmail))
                    {
                        statusCode = ErrorCode.AuthProviderMissingEmail;
                        break;
                    }
                    else
                    {
                        // Check whether email is exist or not
                        if (!TryGetUsers(inputEmail, out user))
                        {
                            statusCode = Register(authProvider.Name, authProvider.Email ?? email, null, null, out user);
                            if (statusCode != ErrorCode.Success)
                            {
                                break;
                            }
                        }

                        if (!TryAddAuthProvider(authProvider, user))
                        {
                            TryRemoveUser(user.Id);
                            break;
                        }
                    }
                }
                // Da dang ky
                else
                {
                    // Dang loi cho nay, cai dbAuth ko lay ve cai user
                    TryGetUsers(dbAuth.UserId, out user);
                }

                GenerateToken(user);
                statusCode = ErrorCode.Success;
            } while (false);

            return(statusCode);
        }
Example #27
0
 /// <summary>
 /// Returns whether authentication variables were previously saved to persistent storage.
 /// </summary>
 /// <returns>Whether authentication variables were previously saved to persistent storage.</returns>
 public bool LoginSaved()
 {
     // Set runtime variables to stored data (if it exists)
     if (PlayerPrefs.HasKey("username"))
     {
         Username      = PlayerPrefs.GetString("username");
         LoginProvider = (AuthProvider)PlayerPrefs.GetInt("loginProvider");
         LoginId       = PlayerPrefs.GetString("loginId");
         LoginToken    = PlayerPrefs.GetString("loginToken");
         Debug.Log("SAVED LOGIN: "******"/" + LoginProvider + "/" + LoginId + "/" + LoginToken);
         return(true);
     }
     Debug.Log("SAVED LOGIN: N/A");
     return(false);
 }
Example #28
0
        public void UpdateCurrentOperatorAndPermission(SysOperator currentOperator)
        {
            CurrentOperatorInfo = currentOperator;

            var roles = new List <SysRole>();

            currentOperator.SysOperatorRoles.ForEach(x => roles.Add(_sysRoleRepo.GetByKey(x.RoleID)));
            AuthorizationPermissions = roles.SelectMany(x => x.SysRolePermissions).ToList();

            var accessControlList = new List <string>();

            accessControlList.AddRange(AuthorizationPermissions.FindAll(x => x.ModuleInfo != null).Select(x => x.ModuleInfo.ModuleCode));
            accessControlList.AddRange(AuthorizationPermissions.FindAll(x => x.ElementInfo != null).Select(x => x.ElementInfo.ElementCode));
            AuthProvider.Initialize <DefaultAuthProvider>(accessControlList.ToArray());
        }
Example #29
0
        public async Task <HttpResponseMessage> Login([FromUri] string refreshToken, [FromUri] AuthProvider provider)
        {
            var authService = authServices.Where(a => a.Provider == provider).FirstOrDefault();

            if (authService == null)
            {
                throw new DenialException($"Invalid provider: {provider}");
            }

            var token = await authService.RefreshTokenAsync(refreshToken);

            var response = Request.CreateResponse(HttpStatusCode.OK, token);

            return(response);
        }
Example #30
0
        /// <summary>
        /// Update single entity
        /// </summary>
        public void Put(Models.Bikes.Bike bike)
        {
            using (var scope = Scope("Put"))
            {
                // authorize
                AuthProvider.Authorize(Permission.Bike_Management); // throws UnauthorizedException or we have CurrentUser after this

                // prepare
                Helper.Expect(bike, bike.BikeId);

                // validate
                Helper.ValidateModel(bike, true);

                // process
                var saveImage = !string.IsNullOrEmpty(bike.ImageToUploadContentBase64) && !string.IsNullOrEmpty(bike.ImageToUploadFileName);
                var entity    = bike.ToEntity();
                BusinessEntities.Bikes.Bike prevEntity = null;

                if (saveImage)
                {
                    prevEntity = BikeManager.GetById(entity.BikeId);

                    // increment seq
                    entity.ImageSeq    = prevEntity.ImageSeq.GetValueOrDefault() + 1;
                    entity.ImageFormat = ContentManager.GetFormat(BikeManager.GetImageContentRef(entity, false)).FileFormat.GetValueOrDefault(); // image will be validated when saving
                }

                BikeManager.Update(entity);

                scope.Complete(
                    () =>
                {
                    // after commit
                    if (saveImage)
                    {
                        // delete previous image
                        if (prevEntity.ImageSeq.HasValue && prevEntity.ImageFormat.HasValue)
                        {
                            BikeManager.DeleteImage(prevEntity);
                        }

                        // save new image
                        BikeManager.SaveImage(entity, ContentManager.DecodeBase64Image(bike.ImageToUploadContentBase64));
                    }
                },
                    () => $"Bike has been updated with Id={bike.BikeId}.");
            }
        }
Example #31
0
        private bool TryGetAuthProvider(string id, out AuthProvider authProvider)
        {
            authProvider = null;

            try
            {
                DbService.ConnectDb(out _context);
                authProvider = _context.AuthProviders.FirstOrDefault(a => a.Id == id);
            }
            finally
            {
                DbService.DisconnectDb(ref _context);
            }

            return(true);
        }
        public void WrongCredProviderTest(string name, string pass)
        {
            Mock <ICredentialsRepo> mock = new Mock <ICredentialsRepo>();

            mock.Setup(p => p.GetCredentials()).Returns(dc);

            AuthProvider cp   = new AuthProvider(mock.Object);
            Authenticate user = new Authenticate()
            {
                Name     = name,
                Password = pass
            };
            Authenticate result = cp.AuthenticateUser(user);

            Assert.IsNull(result);
        }
Example #33
0
        /// <summary>
        /// Returns current user, if logged in.
        /// Can be requested to log off the current user.
        /// Others initialization parameters can be returned by inheriting from AntiForgeryTokenResult.
        /// </summary>
        public AppUser Get()
        {
            try
            {
                AuthProvider.Authenticate(); // throws UnauthenticatedException or we have CurrentUser after this

                using (var context = GetContext(false))
                {
                    return(OK(new AppUser(AuthProvider.CurrentUser)));
                }
            }
            catch (Exception ex)
            {
                return(HandleException <AppUser>(ex));
            }
        }
Example #34
0
    protected void bnt_login_Click(object sender, EventArgs e)
    {
        AuthProvider authprovider = new AuthProvider();
        string       bankname     = hf_bankname.Value;
        string       username     = txt_username.Value;
        string       pwd          = txt_pwd.Value;

        if (authprovider.ValidateUser(bankname, username, pwd))
        {
            FormsAuthentication.RedirectFromLoginPage(HttpContext.Current.User.Identity.Name, true, FormsAuthentication.FormsCookieName);
        }
        else
        {
            ScriptManager.RegisterStartupScript(Page, GetType(), "", "alert('登录失败!');", true);
            return;
        }
    }
Example #35
0
        public Result UpdateUser(UserModel curentUser)
        {
            Result result = new Result();

            if (!IsValidUser(curentUser, result, true))
            {
                result.Message     = result.GetMessages(" - ");
                result.FlowControl = FlowOptions.Failed;
                result.Data        = curentUser;
                return(result);
            }
            var updatedUser = UpdateUser(curentUser);

            if (updatedUser.Item1 != null && updatedUser.Item2 != null)
            {
                result.Data        = updatedUser.Item2;
                result.FlowControl = FlowOptions.Success;
                result.Message     = UserResource.Updated;
                return(result);
            }
            if (updatedUser.Item1 == null || updatedUser.Item2 == null)
            {
                result.Data        = curentUser;
                result.FlowControl = FlowOptions.Failed;
                result.Message     = result.GetMessages(" - ");
            }
            return(result);

            (UserModel, UserModel) UpdateUser(UserModel user)
            {
                UserModel authUser  = new UserModel();
                UserModel localUser = new UserModel();

                try
                {
                    authUser  = AuthProvider.UpdateUserAuth(user);
                    localUser = UserRepository.UpdateUser(user);
                    return(authUser, localUser);
                }
                catch (Exception ex)
                {
                    result.AddMessageToList(ex?.InnerException?.Message ?? ex.Message);
                    return(authUser.Uid != null ? authUser : null, localUser.Uid != null ? localUser : null);
                }
            }
        }
		/// <summary>
		/// Append to the default outline in the content of an existing page
		/// </summary>
		/// <param name="debug">Run the code under the debugger</param>
		/// <param name="pageId">The identifier of the page whose content to append to</param>
		/// <param name="provider"></param>
		/// <param name="apiRoute"></param>
		/// <remarks>Create page using a single part text/html content type</remarks>
		/// <returns>The converted HTTP response message</returns>
		public static async Task<ApiBaseResponse> AppendToDefaultOutlineInPageContent(bool debug, string pageId, AuthProvider provider, string apiRoute)
		{
			if (debug)
			{
				Debugger.Launch();
				Debugger.Break();
			}
			
			var client = new HttpClient();

			// Note: API only supports JSON response.
			client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

			// Not adding the Authentication header would produce an unauthorized call and the API will return a 401
			client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
				await Auth.GetAuthToken(provider));

			//The request content must be a JSON list of commands
			var commands = new List<PatchCommand>();

			//Each command must contain atleast a target and an action. Specifying content may be optional or mandatory depending on the action specified.
			var appendCommand = new PatchCommand();
			appendCommand.Target = "body";
			//While in this case the PATCH action is append, the API supports replace (to replace existing page content) and insert (insert new page content relative to existing content) actions as well.
			appendCommand.Action = "append";
			appendCommand.Content = "<p>New trailing content</p>";

			commands.Add(appendCommand);

			var appendRequestContent = JsonConvert.SerializeObject(commands);

			// Prepare an HTTP PATCH request to the Pages/{pageId}/content endpoint
			// The request body content type is application/json
			var createMessage = new HttpRequestMessage(new HttpMethod("PATCH"), apiRoute + "pages/" + pageId + "/content")
			{
				Content = new StringContent(appendRequestContent, Encoding.UTF8, "application/json")
			};

			HttpResponseMessage response = await client.SendAsync(createMessage);

			return await TranslatePatchResponse(response);
		}
		/// <summary>
		/// Create a very simple page with some formatted text.
		/// </summary>
		/// <param name="debug">Run the code under the debugger</param>
		/// <param name="sectionId"></param>
		/// <param name="provider"></param>
		/// <param name="apiRoute"></param>
		/// <remarks>Create page using a single part text/html content type</remarks>
		/// <returns>The converted HTTP response message</returns>
		public static async Task<ApiBaseResponse> CreateSimplePage(bool debug, AuthProvider provider, string apiRoute)
		{
			if (debug)
			{
				Debugger.Launch();
				Debugger.Break();
			}

			var client = new HttpClient();

			// Note: API only supports JSON response.
			client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

			// Not adding the Authentication header would produce an unauthorized call and the API will return a 401
			client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await Auth.GetAuthToken(provider));

			string date = GetDate();
			string simpleHtml = "<html>" +
								"<head>" +
								"<title>A simple page created from basic HTML-formatted text</title>" +
								"<meta name=\"created\" content=\"" + date + "\" />" +
								"</head>" +
								"<body>" +
								"<p>This is a page that just contains some simple <i>formatted</i> <b>text</b></p>" +
								"<p>Here is a <a href=\"http://www.microsoft.com\">link</a></p>" +
								"</body>" +
								"</html>";

			// Prepare an HTTP POST request to the Pages endpoint
			// The request body content type is text/html
			var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute + "/pages")
			{
				Content = new StringContent(simpleHtml, Encoding.UTF8, "text/html")
			};

			HttpResponseMessage response = await client.SendAsync(createMessage);

			return await HttpUtils.TranslateResponse(response);
		}
		/// <summary>
		/// Get info for ALL  of the user's notebooks
		/// This include the user's notebooks as well as notebooks shared with this user by others.
		/// </summary>
		/// <param name="debug">Run the code under the debugger</param>
		/// <param name="provider"></param>
		/// <param name="apiRoute"></param>
		/// <returns>The converted HTTP response message</returns>
		public static async Task<List<ApiBaseResponse>> GetAllNotebooks(bool debug, AuthProvider provider, string apiRoute)
		{
			if (debug)
			{
				Debugger.Launch();
				Debugger.Break();
			}

			var client = new HttpClient();

			// Note: API only supports JSON response.
			client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

			// Not adding the Authentication header would produce an unauthorized call and the API will return a 401
			client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await Auth.GetAuthToken(provider));

			// Prepare an HTTP GET request to the Notebooks endpoint
			var getMessage = new HttpRequestMessage(HttpMethod.Get, apiRoute + "notebooks");

			HttpResponseMessage response = await client.SendAsync(getMessage);

			return await TranslateListOfNotebooksResponse(response);
		}
		/// <summary>
		///     Delete a page.
		/// </summary>
		/// <param name="debug">Run the code under the debugger</param>
		/// <param name="pageId"></param>
		/// <param name="provider"></param>
		/// <param name="apiRoute"></param>
		/// <remarks>Delete a specified page by ID.</remarks>
		/// <returns>The converted HTTP response message</returns>
		public static async Task<ApiBaseResponse> DeletePage(bool debug, string pageId, AuthProvider provider, string apiRoute)
		{
			if (debug)
			{
				Debugger.Launch();
				Debugger.Break();
			}

			var client = new HttpClient();

			// Note: API only supports JSON response.
			client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

			// Not adding the Authentication header would produce an unauthorized call and the API will return a 401
			client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
				await Auth.GetAuthToken(provider));

			// Prepare an HTTP DELETE request to the Pages endpoint
			// The request body content type is text/html
			var deleteMessage = new HttpRequestMessage(HttpMethod.Delete, apiRoute + "pages/" + pageId);
			var response = await client.SendAsync(deleteMessage);

			return await HttpUtils.TranslateResponse(response);
		}
		/// <summary>
		/// Create a page with auto-extracted business card on it.
		/// http://blogs.msdn.com/b/onenotedev/archive/2014/12/08/new-api-to-auto-extract-business-cards-recipe-urls-and-product-urls-now-in-beta.aspx
		/// Currently we can extract business cards from images and recipes, product info from urls.
		/// </summary>
		/// <param name="debug">Run the code under the debugger</param>
		/// <param name="sectionId"></param>
		/// <param name="provider"></param>
		/// <param name="apiRoute"></param>
		/// <remarks>Create page using a multipart/form-data content type</remarks>
		/// <returns>The converted HTTP response message</returns>
		public static async Task<ApiBaseResponse> CreatePageWithAutoExtractBusinessCard(bool debug, string sectionId, AuthProvider provider, string apiRoute)
		{
			if (debug)
			{
				Debugger.Launch();
				Debugger.Break();
			}

			var client = new HttpClient();

			// Note: API only supports JSON return type.
			client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

			// Not adding the Authentication header would produce an unauthorized call and the API will return a 401
			client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
				await Auth.GetAuthToken(provider));

			const string imagePartName = "image1";
			string date = GetDate();
			string simpleHtml = "<html>" +
								"<head>" +
								"<title>A page with auto-extracted business card from an image</title>" +
								"<meta name=\"created\" content=\"" + date + "\" />" +
								"</head>" +
								"<body>" +
								"<h1>This is a page with an extracted business card from an image</h1>" +
								"<div data-render-method=\"extract\" + " +
									"data-render-src=\"name:" + imagePartName +
									"\" data-render-fallback=\"none\" />" +
								"<p> This is the original image from which the business card was extracted: </p>" +
								"<img src=\"name:" + imagePartName + "\" />" +
								"</body>" +
								"</html>";

			// Create the image part - make sure it is disposed after we've sent the message in order to close the stream.
			HttpResponseMessage response;
			using (var imageContent = new StreamContent(await GetBinaryStream("assets\\BizCard.png")))
			{
				imageContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
				var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute + "sections/" + sectionId + "/pages")
				{
					Content = new MultipartFormDataContent
					{
						{new StringContent(simpleHtml, Encoding.UTF8, "text/html"), "Presentation"},
						{imageContent, imagePartName}
					}
				};

				// Must send the request within the using block, or the image stream will have been disposed.
				response = await client.SendAsync(createMessage);
			}

			return await HttpUtils.TranslateResponse(response);
		}
		/// <summary>
		/// Get selected info for ALL notebooks ordered in a given way
		/// </summary>
		/// <param name="debug">Run the code under the debugger</param>
		/// <param name="orderByFieldName">the field that is used to order the results</param>
		/// <param name="selectFieldNames">meta data fields to return in the response</param>
		/// <param name="provider"></param>
		/// <param name="apiRoute"></param>
		/// <returns>The converted HTTP response message</returns>
		/// <example>https://www.onenote.com/api/v1.0/notebooks?$select=id,name&$orderby=createdTime
		/// returns only the id and name meta data values sorting the result chronologically by createdTime (ascending order by default)</example>
		public static async Task<List<ApiBaseResponse>> GetAllNotebooksWithOrderByAndSelectQueryParams(bool debug, string orderByFieldName, string selectFieldNames, AuthProvider provider, string apiRoute)
		{
			if (debug)
			{
				Debugger.Launch();
				Debugger.Break();
			}

			var client = new HttpClient();

			// Note: API only supports JSON response.
			client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

			// Not adding the Authentication header would produce an unauthorized call and the API will return a 401
			client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await Auth.GetAuthToken(provider));

			// Prepare an HTTP GET request to the Notebooks endpoint
			var getMessage = new HttpRequestMessage(HttpMethod.Get,
				String.Format(apiRoute + "notebooks?$select={0}&$orderby={1}",
					WebUtility.UrlEncode(selectFieldNames),
					WebUtility.UrlEncode(orderByFieldName)));

			HttpResponseMessage response = await client.SendAsync(getMessage);

			return await TranslateListOfNotebooksResponse(response);
		}
		/// <summary>
		/// Get the content for a specific page
		/// Previously example showed us how to get page meta data. This example shows how to get the content of the page.
		/// </summary>
		/// <param name="debug">Run the code under the debugger</param>
		/// <param name="pageId">Id of the page for which the content is returned</param>
		/// <param name="provider"></param>
		/// <param name="apiRoute"></param>
		/// <remarks>  The pageId can be fetched from an earlier GET/POST response of pages endpoint (e.g. GET https://www.onenote.com/api/v1.0/pages ).
		/// </remarks>
		/// <returns>The converted HTTP response message</returns>
		public static async Task<ApiBaseResponse> GetASpecificPageContent(bool debug, string pageId, AuthProvider provider, string apiRoute)
		{
			if (debug)
			{
				Debugger.Launch();
				Debugger.Break();
			}

			var client = new HttpClient();

			// Note: Page content is returned in a same HTML fashion supported by POST Pages
			client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));

			// Not adding the Authentication header would produce an unauthorized call and the API will return a 401
			client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
				await Auth.GetAuthToken(provider));

			// Prepare an HTTP GET request to the Pages endpoint
			var getMessage = new HttpRequestMessage(HttpMethod.Get, apiRoute + "pages/" + pageId + "/content");

			HttpResponseMessage response = await client.SendAsync(getMessage);

			return await TranslatePageContentResponse(response);
		}
		/// <summary>
		/// Create a page with auto-extracted product info on it.
		/// http://blogs.msdn.com/b/onenotedev/archive/2014/12/08/new-api-to-auto-extract-business-cards-recipe-urls-and-product-urls-now-in-beta.aspx
		/// Currently we can extract business cards from images and recipes, product info from urls.
		/// </summary>
		/// <param name="debug">Run the code under the debugger</param>
		/// <param name="sectionId"></param>
		/// <param name="provider"></param>
		/// <param name="apiRoute"></param>
		/// <remarks>Create page using a multipart/form-data content type</remarks>
		/// <returns>The converted HTTP response message</returns>
		public static async Task<ApiBaseResponse> CreatePageWithAutoExtractProduct(bool debug, string sectionId, AuthProvider provider, string apiRoute)
		{
			if (debug)
			{
				Debugger.Launch();
				Debugger.Break();
			}

			var client = new HttpClient();

			// Note: API only supports JSON return type.
			client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

			// Not adding the Authentication header would produce an unauthorized call and the API will return a 401
			client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
				await Auth.GetAuthToken(provider));

			string date = GetDate();
			string simpleHtml = "<html>" +
			                    "<head>" +
			                    "<title>A page with auto-extracted product info from a URL</title>" +
			                    "<meta name=\"created\" content=\"" + date + "\" />" +
			                    "</head>" +
			                    "<body>" +
			                    "<h1>This is a page with an extracted product info from a URL: http://www.amazon.com/Xbox-One/dp/B00KAI3KW2 </h1>" +
			                    "<div data-render-method=\"extract\" + " +
			                    "data-render-src=\"http://www.amazon.com/Xbox-One/dp/B00KAI3KW2\"" +
			                    "data-render-fallback=\"none\" />" +
			                    "<p> This is a screenshot of the original URL from which the recipe was extracted: </p>" +
			                    "<img data-render-src=\"http://www.amazon.com/Xbox-One/dp/B00KAI3KW2\" />" +
			                    "</body>" +
			                    "</html>";

			var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute + "sections/" + sectionId + "/pages")
			{
				Content = new StringContent(simpleHtml, Encoding.UTF8, "text/html")
			};

			HttpResponseMessage response = await client.SendAsync(createMessage);

			return await HttpUtils.TranslateResponse(response);
		}
		/// <summary>
		/// Create a page with note tags in it.
		/// http://blogs.msdn.com/b/onenotedev/archive/2014/10/17/announcing-tag-support.aspx
		/// </summary>
		/// <param name="debug">Run the code under the debugger</param>
		/// <param name="sectionId"></param>
		/// <param name="provider"></param>
		/// <param name="apiRoute"></param>
		/// <remarks>Create page using a multipart/form-data content type</remarks>
		/// <returns>The converted HTTP response message</returns>
		public static async Task<ApiBaseResponse> CreatePageWithNoteTags(bool debug, string sectionId, AuthProvider provider, string apiRoute)
		{
			if (debug)
			{
				Debugger.Launch();
				Debugger.Break();
			}

			var client = new HttpClient();

			// Note: API only supports JSON return type.
			client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

			// Not adding the Authentication header would produce an unauthorized call and the API will return a 401
			client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
				await Auth.GetAuthToken(provider));

			string date = GetDate();
			string simpleHtml = @"<html>" +
								"<head>" +
								"<title data-tag=\"to-do:completed\">A page created with note tags</title>" +
								"<meta name=\"created\" content=\"" + date + "\" />" +
								"</head>" +
								"<body>" +
								"<h1 data-tag=\"important\">Paragraphs with predefined note tags</h1>" +
								"<p data-tag=\"to-do\">Paragraph with note tag to-do (data-tag=\"to-do\")</p>" +
								"<p data-tag=\"important\">Paragraph with note tag important (data-tag=\"important\")</p>" +
								"<p data-tag=\"question\">Paragraph with note tag question (data-tag=\"question\")</p>" +
								"<p data-tag=\"definition\">Paragraph with note tag definition (data-tag=\"definition\")</p>" +
								"<p data-tag=\"highlight\">Paragraph with note tag highlight (data-tag=\"contact\")</p>" +
								"<p data-tag=\"contact\">Paragraph with note tag contact (data-tag=\"contact\")</p>" +
								"<p data-tag=\"address\">Paragraph with note tag address (data-tag=\"address\")</p>" +
								"<p data-tag=\"phone-number\">Paragraph with note tag phone-number (data-tag=\"phone-number\")</p>" +
								"<p data-tag=\"web-site-to-visit\">Paragraph with note tag web-site-to-visit (data-tag=\"web-site-to-visit\")</p>" +
								"<p data-tag=\"idea\">Paragraph with note tag idea (data-tag=\"idea\")</p>" +
								"<p data-tag=\"password\">Paragraph with note tag password (data-tag=\"critical\")</p>" +
								"<p data-tag=\"critical\">Paragraph with note tag critical (data-tag=\"project-a\")</p>" +
								"<p data-tag=\"project-a\">Paragraph with note tag project-a (data-tag=\"project-b\")</p>" +
								"<p data-tag=\"project-b\">Paragraph with note tag project-b (data-tag=\"remember-for-later\")</p>" +
								"<p data-tag=\"remember-for-later\">Paragraph with note tag remember-for-later (data-tag=\"remember-for-later\")</p>" +
								"<p data-tag=\"movie-to-see\">Paragraph with note tag movie-to-see (data-tag=\"movie-to-see\")</p>" +
								"<p data-tag=\"book-to-read\">Paragraph with note tag book-to-read (data-tag=\"book-to-read\")</p>" +
								"<p data-tag=\"music-to-listen-to\">Paragraph with note tag music-to-listen-to (data-tag=\"music-to-listen-to\")</p>" +
								"<p data-tag=\"source-for-article\">Paragraph with note tag source-for-article (data-tag=\"source-for-article\")</p>" +
								"<p data-tag=\"remember-for-blog\">Paragraph with note tag remember-for-blog (data-tag=\"remember-for-blog\")</p>" +
								"<p data-tag=\"discuss-with-person-a\">Paragraph with note tag discuss-with-person-a (data-tag=\"discuss-with-person-a\")</p>" +
								"<p data-tag=\"discuss-with-person-b\">Paragraph with note tag discuss-with-person-b (data-tag=\"discuss-with-person-a\")</p>" +
								"<p data-tag=\"discuss-with-manager\">Paragraph with note tag discuss-with-manager (data-tag=\"discuss-with-manager\")</p>" +
								"<p data-tag=\"send-in-email\">Paragraph with note tag send-in-email (data-tag=\"send-in-email\")</p>" +
								"<p data-tag=\"schedule-meeting\">Paragraph with note tag schedule-meeting (data-tag=\"schedule-meeting\")</p>" +
								"<p data-tag=\"call-back\">Paragraph with note tag call-back (data-tag=\"call-back\")</p>" +
								"<p data-tag=\"to-do-priority-1\">Paragraph with note tag to-do-priority-1 (data-tag=\"to-do-priority-1\")</p>" +
								"<p data-tag=\"to-do-priority-2\">Paragraph with note tag to-do-priority-2 (data-tag=\"to-do-priority-2\")</p>" +
								"<p data-tag=\"client-request\">Paragraph with note tag client-request (data-tag=\"client-request\")</p>" +
								"<br/>" +
								"<p style=\"font-size: 16px; font-family: Calibri, sans-serif\">Paragraphs with note tag status</p>" +
								"<p data-tag=\"to-do:completed\">Paragraph with note tag status completed</p>" +
								"<p data-tag=\"call-back:completed\">Paragraph with note tag status completed</p>" +
								"<br/>" +
								"<p style=\"font-size: 16px; font-family: Calibri, sans-serif\">Paragraph with multiple note tags</p>" +
								"<p data-tag=\"critical, question\">Paragraph with two note tags</p>" +
								"<p data-tag=\"password, send-in-email\">Multiple note tags</p>" +
								"<h1>List Item with a note tag</h1>" +
								"<li data-tag=\"to-do\" id=\"todoitem2\">Build a todo app with OneNote APIs</li>" +
								"<p style=\"font-size: 16px; font-family: Calibri, sans-serif\">Image with note tag</p>" +
								"<img data-tag=\"important\" src=\"http://placecorgi.com/300\" />" +
								"</body>" +
								"</html>";

			var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute + "sections/" + sectionId + "/pages")
			{
				Content = new StringContent(simpleHtml, Encoding.UTF8, "text/html")
			};

			HttpResponseMessage response = await client.SendAsync(createMessage);

			return await HttpUtils.TranslateResponse(response);
		}
		public static async Task<object> ExecuteApiPrereq(string uniqueId, AuthProvider provider, bool useBeta)
		{
			var apiEndPoint = ApiEndPoint(useBeta);
			switch (uniqueId)
			{
				case "Group-0-Item-0":
				case "Group-0-Item-1":
				case "Group-0-Item-2":
				case "Group-0-Item-3":
				case "Group-0-Item-4":
				case "Group-0-Item-5":
				case "Group-0-Item-6":
				case "Group-0-Item-7":
				case "Group-0-Item-8":
				case "Group-0-Item-10":
                case "Group-1-Item-7":
					return await GetNotebooksExample.GetAllNotebooksExpand(false, provider, apiEndPoint);
				case "Group-1-Item-1":
					return await GetPagesExample.GetAllPages(false, provider, apiEndPoint);
				case "Group-1-Item-6":
					return await GetPagesExample.GetAllPages(false, provider, apiEndPoint);
				case "Group-2-Item-2":
					return await GetNotebooksExample.GetAllNotebooks(false, provider, apiEndPoint);
				case "Group-2-Item-4":
					return await GetSectionsExample.GetAllSections(false, provider, apiEndPoint);
				case "Group-2-Item-9":
					return await GetNotebooksExample.GetAllNotebooks(false, provider, apiEndPoint);
				case "Group-2-Item-12":
                    return await GetNotebooksExample.GetAllNotebooks(false, provider, apiEndPoint);
                case "Group-2-Item-13":
                    return await GetSectionGroupsExample.GetAllSectionGroups(false, provider, apiEndPoint);
                case "Group-2-Item-14":
                    return await GetNotebooksExample.GetAllNotebooks(false, provider, apiEndPoint);
                case "Group-2-Item-15":
                    return await GetSectionGroupsExample.GetAllSectionGroups(false, provider, apiEndPoint);
				case "Group-3-Item-0":
					return await GetPagesExample.GetAllPages(false, provider, apiEndPoint);
				case "Group-3-Item-1":
				case "Group-4-Item-0":
					return await GetPagesExample.GetAllPages(false, provider, apiEndPoint);

			}
			return null;
		}
		/// <summary>
		/// Create a page with an image of an embedded web page on it.
		/// </summary>
		/// <param name="debug">Run the code under the debugger</param>
		/// <param name="sectionId"></param>
		/// <param name="provider"></param>
		/// <param name="apiRoute"></param>
		/// <remarks>Create page using a multipart/form-data content type</remarks>
		/// <returns>The converted HTTP response message</returns>
		public static async Task<ApiBaseResponse> CreatePageWithEmbeddedWebPage(bool debug, string sectionId, AuthProvider provider, string apiRoute)
		{
			if (debug)
			{
				Debugger.Launch();
				Debugger.Break();
			}

			var client = new HttpClient();

			// Note: API only supports JSON return type.
			client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

			// Not adding the Authentication header would produce an unauthorized call and the API will return a 401
			client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
				await Auth.GetAuthToken(provider));

			const string embeddedPartName = "embedded1";
			const string embeddedWebPage =
				"<html>" +
				"<head>" +
				"<title>An embedded webpage</title>" +
				"</head>" +
				"<body>" +
				"<h1>This is a screen grab of a web page</h1>" +
				"<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam vehicula magna quis mauris accumsan, nec imperdiet nisi tempus. Suspendisse potenti. " +
				"Duis vel nulla sit amet turpis venenatis elementum. Cras laoreet quis nisi et sagittis. Donec euismod at tortor ut porta. Duis libero urna, viverra id " +
				"aliquam in, ornare sed orci. Pellentesque condimentum gravida felis, sed pulvinar erat suscipit sit amet. Nulla id felis quis sem blandit dapibus. Ut " +
				"viverra auctor nisi ac egestas. Quisque ac neque nec velit fringilla sagittis porttitor sit amet quam.</p>" +
				"</body>" +
				"</html>";

			string date = GetDate();

			string simpleHtml = "<html>" +
								"<head>" +
								"<title>A page created with an image of an html page on it</title>" +
								"<meta name=\"created\" content=\"" + date + "\" />" +
								"</head>" +
								"<body>" +
								"<h1>This is a page with an image of an html page on it.</h1>" +
								"<img data-render-src=\"name:" + embeddedPartName +
								"\" alt=\"A website screen grab\" />" +
								"</body>" +
								"</html>";

			var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute + "sections/" + sectionId + "/pages")
			{
				Content = new MultipartFormDataContent
				{
					{new StringContent(simpleHtml, Encoding.UTF8, "text/html"), "Presentation"},
					{new StringContent(embeddedWebPage, Encoding.UTF8, "text/html"), embeddedPartName}
				}
			};

			HttpResponseMessage response = await client.SendAsync(createMessage);

			return await HttpUtils.TranslateResponse(response);
		}
Example #47
0
        public async Task UpdateOrAddAuthProviderAsync(AuthProvider ap)
        {            
            List<AuthProvider> results = await database.QueryAsync<AuthProvider>("select * from AuthProvider where Name='" + ap.Name + "'");
            AuthProvider current = results.FirstOrDefault<AuthProvider>();            

            if (current != null)
            {                
                await database.UpdateAsync(ap);
            }
            else
            {                
                await database.InsertAsync(ap);
            }
        }
		/// <summary>
		/// Get info for ALL sections matching a filter criteria
		/// In this example the filter criteria is searching for an exact matching section name
		/// </summary>
		/// <param name="debug">Run the code under the debugger</param>
		/// <param name="nameFilterString">search for the given section name</param>
		/// <param name="provider"></param>
		/// <param name="apiRoute"></param>
		/// <returns>The converted HTTP response message</returns>
		/// <example>https://www.onenote.com/api/v1.0/sections?$filter=name%20eq%20'API' 
		///  returns all sections with name equals (case-sensitive) 'API'</example>
		public static async Task<List<ApiBaseResponse>> GetAllSectionsWithNameMatchingFilterQueryParam(bool debug, string nameFilterString, AuthProvider provider, string apiRoute)
		{
			if (debug)
			{
				Debugger.Launch();
				Debugger.Break();
			}

			var client = new HttpClient();

			// Note: API only supports JSON response.
			client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

			// Not adding the Authentication header would produce an unauthorized call and the API will return a 401
			client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
				await Auth.GetAuthToken(provider));

			// Prepare an HTTP GET request to the Sections endpoint
			var createMessage = new HttpRequestMessage(HttpMethod.Get,
				String.Format(apiRoute + "sections?$filter=name eq '{0}'", WebUtility.UrlEncode(nameFilterString)));

			HttpResponseMessage response = await client.SendAsync(createMessage);

			return await TranslateListOfSectionsResponse(response);
		}
		public static void AddPlugins(List<IPlugin> plugins)
		{
			AppSettings appSettings = new AppSettings();
			SSAuthInterfaces.AuthUserSession authUserSession = new SSAuthInterfaces.AuthUserSession();
			AuthProvider authProvider = new AuthProvider();
			SSAuthInterfaces.IAuthProvider[] authProviders = new SSAuthInterfaces.IAuthProvider[] { authProvider };
			RequestLogsFeature requestLogsFeature = new RequestLogsFeature();

			requestLogsFeature.RequiredRoles = new string[] { };

			plugins.Add(new AuthFeature(() => authUserSession, authProviders) { });
			plugins.Add(requestLogsFeature);
			plugins.Add(new RegistrationFeature());
			plugins.Add(new ValidationFeature());
		}
		/// <summary>
		/// Create a page with a file attachment
		/// </summary>
		/// <param name="debug">Determines whether to execute this method under the debugger</param>
		/// <param name="sectionId"></param>
		/// <param name="provider"></param>
		/// <param name="apiRoute"></param>
		/// <remarks>Create page using a multipart/form-data content type</remarks>
		/// <returns>The converted HTTP response message</returns>
		public static async Task<ApiBaseResponse> CreatePageWithAttachedFile(bool debug, string sectionId, AuthProvider provider, string apiRoute)
		{
			if (debug)
			{
				Debugger.Launch();
				Debugger.Break();
			}

			var client = new HttpClient();
			string date = GetDate();
			//Note: API only supports JSON return type
			client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

			// Not adding the Authentication header would produce an unauthorized call and the API will return a 401
			client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
				await Auth.GetAuthToken(provider));

			const string attachmentPartName = "pdfattachment1";
			string attachmentRequestHtml = "<html>" +
										   "<head>" +
										   "<title>A page created with a file attachment</title>" +
										   "<meta name=\"created\" content=\"" + date + "\" />" +
										   "</head>" +
										   "<body>" +
										   "<h1>This is a page with a pdf file attachment</h1>" +
										   "<img data-render-src=\"name:" + attachmentPartName + "\" />" +
										   "<br />" +
										   "<object data-attachment=\"attachment.pdf\" data=\"name:" +
										   attachmentPartName + "\" />" +
										   "</body>" +
										   "</html>";

			HttpResponseMessage response;
			using (var attachmentContent = new StreamContent(await GetBinaryStream("assets\\attachment.pdf")))
			{
				attachmentContent.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
				var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute + "sections/" + sectionId + "/pages")
				{
					Content = new MultipartFormDataContent
					{
						{new StringContent(attachmentRequestHtml, Encoding.UTF8, "text/html"), "Presentation"},
						{attachmentContent, attachmentPartName}
					}
				};
				// Must send the request within the using block, or the binary stream will have been disposed.
				response = await client.SendAsync(createMessage);
			}
			return await HttpUtils.TranslateResponse(response);
		}
		public static async Task<object> ExecuteApi(string uniqueId, bool debug, string requiredSelectedId, 
												string requiredInputText, AuthProvider provider, bool useBeta)
		{
			var apiEndPoint = ApiEndPoint(useBeta);
			switch (uniqueId)
			{
				case "Group-0-Item-0":
					return await PostPagesExample.CreateSimplePage(debug, provider, apiEndPoint);
				case "Group-0-Item-1":
					return await PostPagesExample.CreatePageWithImage(debug, requiredSelectedId, provider, apiEndPoint);
				case "Group-0-Item-2":
					return await PostPagesExample.CreatePageWithEmbeddedWebPage(debug, requiredSelectedId, provider, apiEndPoint);
				case "Group-0-Item-3":
					return await PostPagesExample.CreatePageWithUrl(debug, requiredSelectedId, provider, apiEndPoint);
				case "Group-0-Item-4":
					return await PostPagesExample.CreatePageWithAttachedFile(debug, requiredSelectedId, provider, apiEndPoint);
				case "Group-0-Item-5":
					return await PostPagesExample.CreatePageWithNoteTags(debug, requiredSelectedId, provider, apiEndPoint);
				case "Group-0-Item-6":
					return await PostPagesExample.CreatePageWithAutoExtractBusinessCard(debug, requiredSelectedId, provider, apiEndPoint);
				case "Group-0-Item-7":
					return await PostPagesExample.CreatePageWithAutoExtractRecipe(debug, requiredSelectedId, provider, apiEndPoint);
				case "Group-0-Item-8":
					return await PostPagesExample.CreatePageWithAutoExtractProduct(debug, requiredSelectedId, provider, apiEndPoint);
				case "Group-0-Item-9":
					return await PostPagesExample.CreateSimplePageInAGivenSectionName(debug, requiredInputText, provider, apiEndPoint);
				case "Group-1-Item-0":
					return await GetPagesExample.GetAllPages(debug, provider, apiEndPoint);
				case "Group-1-Item-1":
					return await GetPagesExample.GetASpecificPageMetadata(debug, requiredSelectedId, provider, apiEndPoint);
				case "Group-1-Item-2":
					return await GetPagesExample.GetAllPagesWithTitleContainsFilterQueryParams(debug, requiredInputText, provider, apiEndPoint);
				case "Group-1-Item-3":
					return await GetPagesExample.GetAllPagesWithSkipAndTopQueryParams(debug, 20, 3, provider, apiEndPoint);
				case "Group-1-Item-4":
					return await GetPagesExample.GetAllPagesWithOrderByAndSelectQueryParams(debug, "title asc", "id,title", provider, apiEndPoint);
				case "Group-1-Item-5":
					return await GetPagesExample.SearchAllPages(debug, requiredInputText, provider, apiEndPoint);
				case "Group-1-Item-6":
					return await GetPagesExample.GetASpecificPageContent(debug, requiredSelectedId, provider, apiEndPoint);
                case "Group-1-Item-7":
					return await GetPagesExample.GetAllPagesUnderASpecificSectionId(debug, requiredSelectedId, provider, apiEndPoint);
				case "Group-2-Item-0":
					return await GetNotebooksExample.GetAllNotebooksExpand(debug, provider, apiEndPoint);
				case "Group-2-Item-1":
					return await GetNotebooksExample.GetAllNotebooks(debug, provider, apiEndPoint);
				case "Group-2-Item-2":
					return await GetNotebooksExample.GetASpecificNotebook(debug, requiredSelectedId, provider, apiEndPoint);
				case "Group-2-Item-3":
					return await GetSectionsExample.GetAllSections(debug, provider, apiEndPoint);
				case "Group-2-Item-4":
					return await GetSectionsExample.GetASpecificSection(debug, requiredSelectedId, provider, apiEndPoint);
				case "Group-2-Item-5":
					return await GetSectionGroupsExample.GetAllSectionGroups(debug, provider, apiEndPoint);
				case "Group-2-Item-6":
					return await GetNotebooksExample.GetAllNotebooksWithNameMatchingFilterQueryParam(debug, requiredInputText, provider, apiEndPoint);
				case "Group-2-Item-7":
					return await GetNotebooksExample.GetAllNotebooksWithUserRoleAsNotOwnerFilterQueryParam(debug, provider, apiEndPoint);
				case "Group-2-Item-8":
					return await GetNotebooksExample.GetAllNotebooksWithOrderByAndSelectQueryParams(debug, "name asc", "id,name", provider, apiEndPoint);
				case "Group-2-Item-9":
					return await GetSectionsExample.GetSectionsUnderASpecificNotebook(debug, requiredSelectedId, provider, apiEndPoint);
				case "Group-2-Item-10":
					return await GetSectionsExample.GetAllSectionsWithNameMatchingFilterQueryParam(debug, requiredInputText, provider, apiEndPoint);
				case "Group-2-Item-11":
					return await PostNotebooksExample.CreateSimpleNotebook(debug, requiredInputText, provider, apiEndPoint);
				case "Group-2-Item-12":
                    return await PostSectionsExample.CreateSectionInNotebook(debug, requiredSelectedId, requiredInputText, provider, apiEndPoint);
                case "Group-2-Item-13":
                    return await PostSectionsExample.CreateSectionInSectionGroup(debug, requiredSelectedId, requiredInputText, provider, apiEndPoint);
                case "Group-2-Item-14":
                    return await PostSectionGroupsExample.CreateSectionGroupInNotebook(debug, requiredSelectedId, requiredInputText, provider, apiEndPoint);
                case "Group-2-Item-15":
                    return await PostSectionGroupsExample.CreateSectionGroupInSectionGroup(debug, requiredSelectedId, requiredInputText, provider, apiEndPoint);
				case "Group-3-Item-0":
					return await PatchPagesExample.AppendToDefaultOutlineInPageContent(debug, requiredSelectedId, provider, apiEndPoint);
				case "Group-4-Item-0":
					return await DeletePagesExample.DeletePage(debug, requiredSelectedId, provider, apiEndPoint);
			}
			return null;
		}
		/// <summary>
		/// Create a page with an image of a URL on it.
		/// </summary>
		/// <param name="debug">Run the code under the debugger</param>
		/// <param name="sectionId"></param>
		/// <param name="provider"></param>
		/// <param name="apiRoute"></param>
		/// <remarks>Create page using a multipart/form-data content type</remarks>
		/// <returns>The converted HTTP response message</returns>
		public static async Task<ApiBaseResponse> CreatePageWithUrl(bool debug, string sectionId, AuthProvider provider, string apiRoute)
		{
			if (debug)
			{
				Debugger.Launch();
				Debugger.Break();
			}

			var client = new HttpClient();

			// Note: API only supports JSON return type.
			client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

			// Not adding the Authentication header would produce an unauthorized call and the API will return a 401
			client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
				await Auth.GetAuthToken(provider));

			string date = GetDate();
			string simpleHtml = @"<html>" +
								"<head>" +
								"<title>A page created with an image from a URL on it</title>" +
								"<meta name=\"created\" content=\"" + date + "\" />" +
								"</head>" +
								"<body>" +
								"<p>This is a page with an image of an html page rendered from a URL on it.</p>" +
								"<img data-render-src=\"http://www.onenote.com\" alt=\"An important web page\"/>" +
								"</body>" +
								"</html>";

			var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute + "sections/" + sectionId + "/pages")
			{
				Content = new StringContent(simpleHtml, Encoding.UTF8, "text/html")
			};

			HttpResponseMessage response = await client.SendAsync(createMessage);

			return await HttpUtils.TranslateResponse(response);
		}