示例#1
0
 public PSAuthLoginProof(Authenticator authenticator)
     : base(LoginOpcodes.AUTH_LOGIN_PROOF)
 {
     Write((byte)AccountStatus.Ok);
     Write(authenticator.SRP6.M2);
     this.WriteNullByte(4);
 }
 public void Setup()
 {
     var driveAuthenticator = new Authenticator();
     driveAuthenticator.Authenticate("test");
     this.googleDriveServiceProvider = new GoogleDriveServiceProvider(driveAuthenticator);
     this.testee = new FileDownloader(this.googleDriveServiceProvider);
 }
        public static async Task<AadGraphClient> EnsureClientCreated(Context context)
        {
            Authenticator authenticator = new Authenticator(context);
            var authInfo = await authenticator.AuthenticateAsync(AadGraphResource);

            return new AadGraphClient(new Uri(AadGraphResource + authInfo.IdToken.TenantId), authInfo.GetAccessToken);
        }
示例#4
0
        public ClientInterface(IrcLoginCreds loginCreds, List<IrcComponent> auxComponents)
        {
            KillClient = false;
            Client = new IrcClient();
            Client.SendDelay = 200;
            Client.ActiveChannelSyncing = true;
            //Client.AutoRetry = true;
            _loginCreds = loginCreds;
            Client.CtcpVersion = "Pikatwo - Interactive chatbot with lifelike texture by zalzane.";

            _authenticator = new Authenticator();

            _components = auxComponents;
            _components.Add(_authenticator);
            _components.Add(new Reconnector());

            foreach (var component in _components){
                component.IrcInterface = this;
            }

            Client.OnChannelMessage += HandleCommands;
            Client.OnQueryMessage += HandleCommands;
            Client.OnRawMessage += ClientOnOnRawMessage;

            _debugWriter = new StreamWriter("debugOut.txt", true);
            _rawWriter = new StreamWriter("rawOut.txt", true);
        }
        public static async Task<ExchangeClient> GetClientInstance()
        {
            Authenticator authenticator = new Authenticator();
            var authInfo = await authenticator.AuthenticateAsync(ExchangeResourceId);

            return new ExchangeClient(new Uri(ExchangeServiceRoot), authInfo.GetAccessToken);
        }
        private static async Task<ExchangeClient> EnsureClientCreated()
        {
            Authenticator authenticator = new Authenticator();
            var authInfo = await authenticator.AuthenticateAsync(ExchangeResourceId);

            return new ExchangeClient(new Uri(ExchangeServiceRoot), authInfo.GetAccessToken);
        }
 public void Setup()
 {
     var authenticator = new Authenticator();
     authenticator.Authenticate("test");
     var serviceProvider = new GoogleDriveServiceProvider(authenticator);
     this.testee = new FolderSynchronizer(new FilesGetter(serviceProvider), new FileDownloader(serviceProvider));
 }
        private static async Task<SharePointClient> EnsureClientCreated()
        {
            Authenticator authenticator = new Authenticator();
            var authInfo = await authenticator.AuthenticateAsync(MyFilesCapability, ServiceIdentifierKind.Capability);

            // Create the MyFiles client proxy:
            return new SharePointClient(authInfo.ServiceUri, authInfo.GetAccessToken);
        }
示例#9
0
        public static async Task<SharePointClient> EnsureClientCreated(UIViewController context)
        {
            Authenticator authenticator = new Authenticator(context);
            var authInfo = await authenticator.AuthenticateAsync(SharePointResourceId, ServiceIdentifierKind.Resource);

            // Create the SharePoint client proxy:
            return new SharePointClient(new Uri(SharePointServiceRoot), authInfo.GetAccessToken);
        }
        public async Task Authenticate_WhereDownstreamResultEmpty_ReturnsFalse()
        {
            // arrange
            var proxy = new AuthenticatorProxyWithResult("");
            authenticator = new Authenticator(proxy);

            // act
            var result = await authenticator.Authenticate("url");

            Assert.IsFalse(result.IsSuccess);
        }
        public async Task Authenticate_WhereDownstreamResultOccurs_ReturnsSuccess()
        {
            // arrange
            var proxy = new AuthenticatorProxyWithResult("foo");
            authenticator = new Authenticator(proxy);

            // act
            var result = await authenticator.Authenticate("url");

            Assert.IsTrue(result.IsSuccess);
        }
 public static async Task EnsureClientCreated(Context context) {
   
   Authenticator authenticator = new Authenticator(context);
   var authInfo = await authenticator.AuthenticateAsync(ExchangeResourceId);
   
   _strUserId = authInfo.IdToken.UPN;
   _exchangeClient = new ExchangeClient(new Uri(ExchangeServiceRoot), authInfo.GetAccessToken);
   
   var adAuthInfo = await authInfo.ReauthenticateAsync(AdServiceResourceId);
   _adClient = new AadGraphClient(new Uri("https://graph.windows.net/" + authInfo.IdToken.TenantId), 
                                  adAuthInfo.GetAccessToken);
 }
        public async Task<ExchangeClient> EnsureExchangeClient()
        {
            if (_exchangeClient != null)
                return _exchangeClient;

            var authenticator = new Authenticator();
            _authenticationInfo = await authenticator.AuthenticateAsync(ExchangeResourceId);

            _exchangeClient = new ExchangeClient(new Uri(ExchangeServiceRoot), _authenticationInfo.GetAccessToken);
            _isAuthenticated = true;
            return _exchangeClient;
        }
 public AsyncResumableUploadData(AsyncDataHandler handler,
     Authenticator authenticator,
     AbstractEntry payload,
     string httpMethod,
     SendOrPostCallback callback,
     object userData)
     : base(null, null, userData, callback) {
     this.DataHandler = handler;
     this.authenticator = authenticator;
     this.entry = payload;
     this.HttpVerb = httpMethod;
 }
示例#15
0
    private IEnumerator LoginLogic()
    {        
        painel.GetComponent<LoadingPanelCreator>().CreateLoadingPanel();

        Authenticator authenticator = new Authenticator()
                                            .setUserName(username.text)
                                            .setPassword(password.text)
                                            .setLoginSuccesfullCallback(loginSuccesfull)
                                            .setLoginFailCallback(loginFail);

        yield return authenticator.makeLogin();    
            
        painel.GetComponent<LoadingPanelCreator>().DestroyLoadingPanel();
    }
示例#16
0
		public WebAuthenticator (Authenticator authenticator)
		{
			Shared = this;
			this.Authenticator = authenticator;
			MonitorAuthenticator ();
			//
			// Create the UI
			//
			Title = authenticator.Title;

			if (authenticator.AllowsCancel) {
				NavigationItem.LeftBarButtonItem = new UIBarButtonItem (
					UIBarButtonSystemItem.Cancel,
					delegate {
						Cancel ();
					});				
			}

			var activityStyle = UIActivityIndicatorViewStyle.White;
			if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0))
				activityStyle = UIActivityIndicatorViewStyle.Gray;

			activity = new UIActivityIndicatorView (activityStyle);
			var rightBarButtonItems = new List<UIBarButtonItem> {
				#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
				new UIBarButtonItem (UIBarButtonSystemItem.Refresh, (s, e) => BeginLoadingInitialUrl ()),
				#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
				new UIBarButtonItem (activity),
			};
			if(RightButtonItem != null)
				rightBarButtonItems.Insert(0,RightButtonItem);

			NavigationItem.RightBarButtonItems = rightBarButtonItems.ToArray();

			webView = new UIWebView (View.Bounds) {
				Delegate = new WebViewDelegate (this),
				AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight,
			};
			View.AddSubview (webView);
			View.BackgroundColor = UIColor.Black;

			//
			// Locate our initial URL
			//
			#pragma warning disable 4014
			BeginLoadingInitialUrl ();
			#pragma warning restore 4014
		}
 public AsyncResumableUploadData(AsyncDataHandler handler,
     Authenticator authenticator,
     Uri uriToUse,
     Stream payload,
     string contentType,
     string slug,
     string httpMethod,
     SendOrPostCallback callback,
     object userData)
     : base(uriToUse, null, userData, callback) {
     this.DataHandler = handler;
     this.authenticator = authenticator;
     this.contentType = contentType;
     this.DataStream = payload;
     this.slug = slug;
     this.HttpVerb = httpMethod;
 }
示例#18
0
        static void Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                {
                    AzureAccount azureAccount = new AzureAccount();
                    azureAccount.Type = AzureAccount.AccountType.User;

                    var environment = AzureEnvironment.PublicEnvironments["AzureCloud"];

                    var auth = new Authenticator(AzureRmProfileProvider.Instance.Profile);
                    auth.Login(azureAccount, environment);
                }
                else if (args.Length == 2)
                {
                    var subcriptionId = args[0];
                    var authToken = args[1];

                    Authenticator.ShowIoTHubsInSubscription(subcriptionId, authToken).Wait();
                }
                else
                {
                    Console.WriteLine("Usage:");
                    Console.WriteLine("MSAAuthenticator.exe");
                    Console.WriteLine("    Pop up a credentials gatheting windows and list all IoT Hubs under all subscriptions associated with the user");
                    Console.WriteLine("MSAAuthenticator.exe <subscription_id> <access_token>");
                    Console.WriteLine("    Lists IoT Hubs abd devices given subscription_id and access_token");
                }
            }
            catch (Exception ex)
            {
                var aggr = ex as System.AggregateException;
                if (aggr != null)
                {
                    foreach (var inner in aggr.InnerExceptions)
                    {
                        Console.WriteLine("Exception: {0}", inner.Message);
                    }
                }
                else
                {
                    Console.WriteLine("Exception: {0}", ex.Message);
                }
            }
        }
        public void Synchronize_WhenFolderIsSynchronize_ThenStructureIsCorrect()
        {
            // Arrange
            var authenticator = new Authenticator();
            authenticator.Authenticate("test");
            var filesGetter = new FilesGetter(new GoogleDriveServiceProvider(authenticator));
            var files = filesGetter.GetDriveFiles(GoogleDriveConstants.FolderMimeType).ToList();

            // Act
            string rootFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\TestGoogle";
            this.testee.SynchronizeFolder(
                files[1],
                rootFolder);

            // Assert
            Directory.Exists(rootFolder).Should().BeTrue();
            Directory.GetDirectories(rootFolder).Length.Should().Be(1);
        }
示例#20
0
    private IEnumerator SaveLogic()
    {        
        painel.GetComponent<LoadingPanelCreator>().CreateLoadingPanel();        
                
        Authenticator authenticator = new Authenticator()
                                            .setUserName(username.text)
                                            .setPassword(password.text)
                                            .setEmail(email.text)
                                            .setRegisterSuccesfullCallback(registerSuccesfull)
                                            .setRegisterFailCallback(registerFail);

        yield return authenticator.makeRegister();

        if (succesfull)
        {            
            yield return savePlayerData();
            new LevelManager().LoadLevel(SceneBook.LOADING_NAME);            
        }
                
        painel.GetComponent<LoadingPanelCreator>().DestroyLoadingPanel();
    }
        /// <summary>
        /// Note the URI passed in here, is the session URI obtained by InitiateUpload
        /// </summary>
        /// <param name="targetUri"></param>
        /// <param name="authentication"></param>
        /// <param name="payload"></param>
        /// <param name="mediaType"></param>
        public WebResponse UploadStream(string httpMethod, Uri sessionUri, Authenticator authentication,
            Stream payload, string mediaType, AsyncData data) {
            HttpWebResponse returnResponse = null;
            // upload one part at a time
            int index = 0;
            lastChunks.Add(sessionUri, 0);
            bool isDone = false;

            // if the stream passed as parameter is NOT at the beginning, we assume
            // that we are resuming
            try {
                // calculate a new index, we will resume in chunk sizes
                if (payload.Position != 0) {
                    index = (int)((double)payload.Position / (this.chunkSize * ResumableUploader.MB));
                }
            } catch (System.NotSupportedException) {
                index = 0;
            }

            do {
                HttpWebResponse response;
                try {
                    response = UploadStreamPart(index, httpMethod, sessionUri, authentication, payload, mediaType, data);
                    if (data != null && CheckIfOperationIsCancelled(data.UserData)) {
                        break;
                    }

                    index++;
                    {
                        int status = (int)response.StatusCode;
                        switch (status) {
                            case 308:
                                isDone = false;
                                break;
                            case 200:
                            case 201:
                                isDone = true;
                                returnResponse = response;
                                break;
                            default:
                                throw new ApplicationException("Unexpected return code during resumable upload");
                        }
                    }
                } finally {
                    response = null;
                }
            } while (!isDone);
            lastChunks.Remove(sessionUri);
            return returnResponse;
        }
示例#22
0
        /// <summary>
        /// Get the encoded username required to authenticate user to BWS.
        /// </summary>
        /// <param name="username">A string containing the username to encode.</param>
        /// <param name="authenticator">The authenticator.</param>
        /// <returns>Returns a string containing the encoded username if successful, and a null message string
        /// otherwise.</returns>
        public static string GetEncodedUserName(string username, Authenticator authenticator)
        {
            const string methodName = "GetEncodedUserName()";
            const string bwsApiName = "bwsUtilService.getEncodedUsername()";

            logMessage("Entering {0}", methodName);
            string returnValue = null;

            GetEncodedUsernameRequest request = new GetEncodedUsernameRequest();

            request.metadata      = Metadata;
            request.username      = username;
            request.orgUid        = Metadata.organizationUid;
            request.authenticator = authenticator;

            CredentialType credentialType = new CredentialType();

            credentialType.PASSWORD = true;
            credentialType.value    = "PASSWORD";
            request.credentialType  = credentialType;

            GetEncodedUsernameResponse response = null;

            try
            {
                logRequest(bwsApiName);
                response = bwsUtilService.getEncodedUsername(request);
                logResponse(bwsApiName, response.returnStatus.code, response.metadata);
            }
            catch (WebException e)
            {
                // Log and re-throw exception.
                logMessage("Exiting {0} with exception \"{1}\"", methodName, e.Message);
                throw e;
            }

            if (response.returnStatus.code.Equals("SUCCESS"))
            {
                returnValue = response.encodedUsername;
            }
            else
            {
                logMessage("Error Message: \"{0}\"", response.returnStatus.message);
            }

            // BES12 returns a Base64 encoded string while BES10 does not.  As a result, a BES10 encoded username
            // throws an exception when an attempt is made to decode from base64.  The try block will log the decoded
            // username if run against a BES12 system and the catch then logs the actual value returned by BES10.
            try
            {
                logMessage("Decoded value of encoded username \"{0}\"",
                           Encoding.Default.GetString(Convert.FromBase64String(returnValue)));
            }
            catch (Exception)
            {
                // Not actually base64 encoded. Show actual value
                logMessage("Value of encoded username \"{0}\"", returnValue);
            }
            logMessage("Exiting {0}", methodName);
            return(returnValue);
        }
 public void ResumeAsync(Authenticator authentication, Uri resumeUri, String httpmethod, Stream payload, string contentType, object userData) {
     AsyncResumableUploadData data = new AsyncResumableUploadData(this,
         authentication,
         resumeUri,
         payload,
         contentType,
         null,
         httpmethod,
         this.ProgressReportDelegate,
         userData);
     WorkerResumableUploadHandler workerDelegate = new WorkerResumableUploadHandler(AsyncResumeWorker);
     this.AsyncStarter(data, workerDelegate, userData);
 }
        private readonly string externalIP;         //TODO: Move this out.

        public MicrosoftFallbackAuthenticator(Authenticator underlyingAuthenticator)
        {
            this.underlyingAuthenticator = underlyingAuthenticator;
            externalIP = new WebClient().DownloadString("http://ipv4.icanhazip.com").Replace("\\r\\n", "").Replace("\\n", "").Trim();
        }
 public MicrosoftFallbackAuthenticator(Authenticator underlyingAuthenticator)
 {
     this.underlyingAuthenticator = underlyingAuthenticator;
     GetExternalIP();
 }
示例#26
0
        static void Main(string[] args)
        {
            Authenticator auth = Authenticator.Instance;

            auth.Authenticate(authUrl, clientId, clientSecret);

            foreach (Endpoint e in auth.GetEndpoints(providerId))
            {
                XPress xPress = new XPress(e.href);

                /* xLeas */
                //GetXLeas(xPress);
                //GetXLeasByXSchool(xPress);
                //GetXLeasByXRoster(xPress);
                //GetXLeasByXStaff(xPress);
                //GetXLeasByXStudent(xPress);
                //GetXLeasByXContact(xPress);
                /* xSchools */
                //GetXSchools(xPress);
                //GetXSchoolsByXLea(xPress);
                //GetXSchoolsByXCalendar(xPress);
                //GetXSchoolsByXCourse(xPress);
                //GetXSchoolsByXRoster(xPress);
                //GetXSchoolsByXStaff(xPress);
                //GetXSchoolsByXStudent(xPress);
                //GetXSchoolsByXContact(xPress);
                /* xCalendars */
                //GetXCalendars(xPress);
                //GetXCalendarsByXLea(xPress);
                //GetXCalendarsByXSchool(xPress);
                /* xCourses */
                //GetXCourses(xPress);
                //GetXCoursesByXLea(xPress);
                //GetXCoursesByXSchool(xPress);
                //GetXCoursesByXRoster(xPress);
                /* xRosters */
                //GetXRosters(xPress);
                //GetXRostersByXLea(xPress);
                //GetXRostersByXSchool(xPress);
                //GetXRostersByXCourse(xPress);
                //GetXRostersByXStaff(xPress);
                //GetXRostersByXStudent(xPress);
                /* xStaffs */
                //GetXStaffs(xPress);
                //GetXStaffsByXLea(xPress);
                //GetXStaffsByXSchool(xPress);
                //GetXStaffsByXCourse(xPress);
                //GetXStaffsByXRoster(xPress);
                //GetXStaffsByXStudent(xPress);
                /* xStudents */
                //GetXStudents(xPress);
                //GetXStudentsByXLea(xPress);
                //GetXStudentsByXSchool(xPress);
                //GetXStudentsByXRoster(xPress);
                //GetXStudentsByXStaff(xPress);
                //GetXStudentsByXContact(xPress);
                /* xContacts */
                //GetXContacts(xPress);
                //GetXContactsByXLea(xPress);
                //GetXContactsByXSchool(xPress);
                //GetXContactsByXStudent(xPress);
            }

            Console.Read();
        }
示例#27
0
 public OAuthController(Authenticator authenticator)
 {
     _authenticator = authenticator;
 }
示例#28
0
 public static void setDefault(Authenticator prm1)
 {
 }
 /// <summary>
 /// retrieves the resumable URI for the rest of the operation. This will initiate the 
 /// communication with resumable upload server by posting against the starting URI
 /// </summary>
 /// <param name="resumableUploadUri"></param>
 /// <param name="authentication"></param>
 /// <param name="entry"></param>
 /// <returns>The uri to be used for the rest of the operation</returns>
 public Uri InitiateUpload(Uri resumableUploadUri, Authenticator authentication, AbstractEntry entry) {
     return InitiateUpload(resumableUploadUri, authentication, entry, HttpMethods.Post);
 }
示例#30
0
        public void HandleRealmList(Socket socket)
        {
            while (socket.Connected)
            {
                System.Threading.Thread.Sleep(1);
                if (socket.Available > 0)
                {
                    byte[] buffer = new byte[socket.Available];
                    socket.Receive(buffer, buffer.Length, SocketFlags.None);

                    PacketReader packet = new PacketReader(buffer, false);
                    PacketWriter writer = new PacketWriter();

                    var op = (RealmlistOpcodes)packet.ReadByte();
                    switch (op)
                    {
                    case RealmlistOpcodes.LOGON_CHALLENGE:
                        writer.Write(Authenticator.LogonChallenge(packet));
                        break;

                    case RealmlistOpcodes.RECONNECT_CHALLENGE:
                        writer.Write(Authenticator.Reconnect_Challenge);
                        break;

                    case RealmlistOpcodes.LOGON_PROOF:
                        writer.Write(Authenticator.LogonProof(packet));
                        break;

                    case RealmlistOpcodes.RECONNECT_PROOF:
                        writer.WriteUInt8((byte)RealmlistOpcodes.RECONNECT_PROOF);
                        writer.WriteUInt8(0);
                        break;

                    case RealmlistOpcodes.REALMLIST_REQUEST:
                        // Send Realm List
                        byte[] realmName = Encoding.UTF8.GetBytes(Sandbox.Instance.RealmName);
                        byte[] redirect  = Encoding.UTF8.GetBytes("127.0.0.1:" + Sandbox.Instance.WorldPort);

                        writer.WriteUInt8(0x10);
                        writer.WriteUInt16((ushort)(21 + realmName.Length + redirect.Length)); // Packet length
                        writer.WriteUInt32(0);
                        writer.WriteUInt8(1);                                                  // Realm count
                        writer.WriteUInt32(1);                                                 // Icon
                        writer.WriteUInt8(0);                                                  // Colour
                        writer.Write(realmName);
                        writer.WriteUInt8(0);
                        writer.Write(redirect);
                        writer.WriteUInt8(0);
                        writer.WriteFloat(0);

                        writer.WriteUInt8(0);
                        writer.WriteUInt8(1);
                        writer.WriteUInt8(2);
                        writer.WriteUInt8(0);
                        writer.WriteUInt8(0x2);
                        break;
                    }

                    if (writer.BaseStream.Length > 0)
                    {
                        socket.SendData(writer, op.ToString());
                    }
                }
            }

            socket.Close();
        }
        internal void startSamples(string[] args)
        {
            Console.WriteLine("{0} Command Line Sample", ApiName);
            Console.WriteLine("============================================");

            CliOptions = new Options();
            var result = CommandLine.Parser.Default.ParseArguments <Options>(args);

            result.WithNotParsed(_ => {
                System.Environment.Exit(1);
            })
            .WithParsed(opt => {
                CliOptions = opt;
            });

            if (CliOptions.ConfigPath == null)
            {
                CliOptions.ConfigPath = DefaultPath;
            }

            initializeConfig(CliOptions.NoConfig);

            var initializer = Authenticator.authenticate(Config, Scope);

            if (initializer == null)
            {
                Console.WriteLine("Failed to authenticate, so exiting.");
                return;
            }

            var init = new BaseClientService.Initializer()
            {
                HttpClientInitializer = initializer,
                ApplicationName       = ApiName + " Samples",
            };

            if (Environment.GetEnvironmentVariable(endpointEnvVar) == null)
            {
                initializeService(init);
            }
            else
            {
                string url = Environment.GetEnvironmentVariable(endpointEnvVar);
                // BaseUri must have a trailing /.
                if (!url.EndsWith("/"))
                {
                    url += "/";
                }
                try
                {
                    var checkedUri = new Uri(url);
                    initializeService(init, checkedUri);
                    Console.WriteLine("Using non-standard API endpoint: {0}", Service.BaseUri);
                }
                catch (UriFormatException e)
                {
                    throw new ArgumentException(
                              String.Format("Error parsing base URL '{0}': {1}", url, e.Message));
                }
            }

            runCalls();
        }
 public AuthConfigViewModel(Authenticator provider)
 {
     Name   = provider.Name;
     Config = provider.BaseConfig.GetConfigValues();
 }
示例#33
0
        public TDSListener(TDSProxyService service, Configuration.ListenerElement configuration)
        {
            var insideAddresses = Dns.GetHostAddresses(configuration.ForwardToHost);

            if (0 == insideAddresses.Length)
            {
                log.ErrorFormat("Unable to resolve forwardToHost=\"{0}\" for listener {1}", configuration.ForwardToHost, configuration.Name);
                _stopped = true;
                return;
            }
            ForwardTo = new IPEndPoint(insideAddresses.First(), configuration.ForwardToPort);

            _service = service;

            var bindToEP = new IPEndPoint(configuration.BindToAddress ?? IPAddress.Any, configuration.ListenOnPort);

            try
            {
                var catalog = new AssemblyCatalog(configuration.AuthenticatorDll);
                _mefContainer = new CompositionContainer(catalog);
                var exports = _mefContainer.GetExports <IAuthenticator>().ToList();
                var export  = exports.FirstOrDefault(a => a.Value.GetType().FullName == configuration.AuthenticatorClass);
                if (null == export)
                {
                    log.ErrorFormat(
                        "Found dll {0} but not authenticator implementation {1} (DLL exported: {2})",
                        configuration.AuthenticatorDll,
                        configuration.AuthenticatorClass,
                        string.Join("; ", exports.Select(exp => exp.Value.GetType().FullName)));
                    Dispose();
                    return;
                }
                _export       = export;
                Authenticator = _export.Value;
                _mefContainer.ReleaseExports(exports.Where(e => e != _export));
            }
            catch (CompositionException ce)
            {
                log.Error(
                    "Failed to find an authenticator. Composition errors:\r\n\t" +
                    string.Join("\r\n\t", ce.Errors.Select(err => "Element: " + err.Element.DisplayName + ", Error: " + err.Description)),
                    ce);
                Dispose();
                throw;
            }
            catch (Exception e)
            {
                log.Error("Failed to find an authenticator", e);
                Dispose();
                throw;
            }

            try
            {
                log.DebugFormat("Opening SSL certificate store {0}.{1}", configuration.SslCertStoreLocation, configuration.SslCertStoreName);
                var store = new X509Store(configuration.SslCertStoreName, configuration.SslCertStoreLocation);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                var matching = store.Certificates.Find(X509FindType.FindByThumbprint, configuration.SslCertSubjectThumbprint, false);
                if (0 == matching.Count)
                {
                    var message = string.Format(
                        "Failed to find SSL certification with thumbprint '{0}' in location {1}, store {2}.",
                        configuration.SslCertSubjectThumbprint,
                        configuration.SslCertStoreLocation,
                        configuration.SslCertStoreName);
                    log.Error(message);
                    Dispose();
                    throw new InvalidOperationException(message);
                }
                Certificate = matching[0];
            }
            catch (Exception e)
            {
                log.Error("Failed to load SSL certificate", e);
                Dispose();
                throw;
            }

            _tcpListener = new TcpListener(bindToEP);
            _tcpListener.Start();
            _tcpListener.BeginAcceptTcpClient(AcceptConnection, _tcpListener);

            _service.AddListener(this);

            log.InfoFormat(
                "Listening on {0} and forwarding to {1} (SSL cert DN {2}; expires {5} serial {3}; authenticator {4})",
                bindToEP,
                ForwardTo,
                Certificate.Subject,
                Certificate.GetSerialNumberString(),
                Authenticator.GetType().FullName,
                Certificate.GetExpirationDateString());
        }
示例#34
0
        public async Task <IRawResponse> RawRequest(
            HttpMethod method,
            string path,
            Values queryParams          = null,
            object body                 = null,
            Authenticator authenticator = null,
            ITransportSettings options  = null
            )
        {
            var url     = MakeUrl(path, queryParams, authenticator);
            var request = new HttpRequestMessage(method,
                                                 url);

            request.Headers.Add(Constants.LookerAppiId, _settings.AgentTag);
            if (body != null)
            {
                if (body is string)
                {
                    request.Content = new StringContent(
                        body.ToString(),
                        Encoding.UTF8,
                        "application/x-www-form-urlencoded");
                }
                else
                {
                    request.Content =
                        new StringContent(
                            JsonSerializer.Serialize(body, new JsonSerializerOptions {
                        IgnoreNullValues = true
                    }),
                            Encoding.UTF8,
                            "application/json");
                }
            }

            if (authenticator != null)
            {
                request = await authenticator(request);
            }
            RawResponse         result   = new RawResponse();
            HttpResponseMessage response = null;

            try
            {
                response = await _client.SendAsync(request);

                result = InitRawResponse(response);
                // if (response.IsSuccessStatusCode)
                await using var stream = await response.Content.ReadAsStreamAsync();

                // Simple content conversion here to make body easily readable in consumers
                switch (SdkUtils.ResponseMode(result.ContentType))
                {
                case ResponseMode.Binary:
                    result.Body = SdkUtils.StreamToByteArray(stream);
                    break;

                case ResponseMode.String:
                    using (var sr = new StreamReader(stream))
                    {
                        result.Body = await sr.ReadToEndAsync();
                    }

                    break;

                case ResponseMode.Unknown:
                    result.Body = SdkUtils.StreamToByteArray(stream);
                    break;

                default:
                    throw new ArgumentOutOfRangeException($"Unrecognized Content Type {result.ContentType}");
                }
            }
            catch (Exception e)
            {
                result      = InitRawResponse(response);
                result.Body = e;
            }

            return(result);
        }
        private HttpWebResponse UploadStreamPart(int partIndex, string httpMethod, Uri sessionUri,
            Authenticator authentication, Stream payload, string mediaType, AsyncData data) {
            HttpWebRequest request = authentication.CreateHttpWebRequest(httpMethod, sessionUri);
            request.AllowWriteStreamBuffering = false;
            request.Timeout = 600000;

            // write the data
            request.ContentType = mediaType;
            CopyData(payload, request, partIndex, data, sessionUri);

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            return response;
        }
 private HttpWebRequest PrepareRequest(Uri target,
     Authenticator authentication,
     string slug,
     string contentType,
     long contentLength) {
     return PrepareRequest(target, authentication, slug, contentType, contentLength, HttpMethods.Post);
 }
        /// <summary>
        /// retrieves the resumable URI for the rest of the operation. This will initiate the 
        /// communication with resumable upload server by posting against the starting URI
        /// </summary>
        /// <param name="resumableUploadUri"></param>
        /// <param name="authentication"></param>
        /// <param name="entry"></param>
        /// <returns>The uri to be used for the rest of the operation</returns>
        public Uri InitiateUpload(Uri resumableUploadUri, Authenticator authentication, string contentType, string slug, long contentLength, string httpMethod) {
            HttpWebRequest request = PrepareRequest(resumableUploadUri,
                authentication,
                slug,
                contentType,
                contentLength,
                httpMethod);

            WebResponse response = request.GetResponse();
            return new Uri(response.Headers["Location"]);
        }
示例#38
0
        //public override void TaskList(int actionId, ErpTask erpTasks, DateTime date, int? noParallelProcess)
        //{
        //    //DataWriter.TruncateTables(erpTasks.truncate_items, erpTasks.truncate_sales_trans_dump, erpTasks.truncate_sales_trans_refresh, erpTasks.truncate_locations_and_vendors,
        //    //    erpTasks.truncate_lookup_info, erpTasks.truncate_bom, erpTasks.truncate_po_to, erpTasks.truncate_price, erpTasks.truncate_attribute_refresh);
        //    TaskExecute exec = new TaskExecute(erpTasks.Steps, noParallelProcess.HasValue ? noParallelProcess.Value : 4 , actionId, date);
        //    exec.Execute();

        //    //foreach (var erpStep in erpTasks.Steps)
        //    //{
        //    //    ExecuteTask(actionId, erpStep, date); // possible to do some parallel processing.
        //    //}
        //    return;
        //}

        #endregion

        public override int CreateItems(int tempId, int actionId)
        {
            List <ItemToCreate> itemsToCreate = AxDbHandler.GetItemsToCreate(tempId);
            DateTime            startTime     = DateTime.Now;
            var authData = Authenticator.GetAuthData(ErpTaskStep.AuthenticationType.D365);

            if (itemsToCreate.Any())
            {
                var masterData = itemsToCreate.First();
                if (masterData.master_status < 2)
                {
                    var master = new ProductMasterWriteDTO();
                    master.ProductDimensionGroupName = "CS";
                    master.ProductNumber             = masterData.product_no;
                    master.ProductName         = masterData.product_name;
                    master.ProductSearchName   = masterData.product_name.Trim();
                    master.ProductSizeGroupId  = masterData.size_group_no;
                    master.ProductColorGroupId = masterData.color_group_no; // possible to use color_group_no
                    //master.RetailProductCategoryName = masterData.sup_department;
                    master.ProductDescription = masterData.description;

                    //var erpMaster = CreateMaster(master);
                    var erpMaster = ServiceConnector.CallOdataEndpointPost <ProductMasterWriteDTO, EnumConverter>("ProductMasters", null, master,
                                                                                                                  authData).Result;

                    if (erpMaster.Exception != null)
                    {
                        DataWriter.LogErpActionStep(actionId, "Item create: write Product Master", startTime, false, erpMaster.Exception.ErrorMessage, erpMaster.Exception.StackTrace, -1);
                        OnTaskCompleted(this, new ErpTaskCompletedArgs {
                            Exception = erpMaster.Exception, ActionId = actionId, Status = 3
                        });
                        return(actionId);
                    }
                    else if (erpMaster.WriteObject.ProductNumber.ToLower().Trim() != masterData.product_no.ToLower().Trim())
                    {
                        DataWriter.LogErpActionStep(actionId, "Item create: write Product Master", startTime, false, null, null, -1);
                        OnTaskCompleted(this, new ErpTaskCompletedArgs
                        {
                            Exception =
                                new AxBaseException
                            {
                                ApplicationException = new ApplicationException(
                                    "The product number for Product Master does not match the returned number, AX value = " + erpMaster.WriteObject.ProductNumber + " AGR number = " + masterData.product_no)
                            },
                            ActionId = actionId,
                            Status   = 3
                        });
                        return(actionId);
                    }

                    DataWriter.LogErpActionStep(actionId, "Item create: write Product Master", startTime, true, null, null, -1);
                    startTime = DateTime.Now;
                    var releasedMaster = new ReleasedProductMasterWriteDTO(master.ProductNumber, master.ProductSearchName,
                                                                           masterData.primar_vendor_no, masterData.sale_price, masterData.cost_price);
                    var erpReleasedMaster = ServiceConnector.CallOdataEndpointPost <ReleasedProductMasterWriteDTO, EnumConverter>("ReleasedProductMasters", null, releasedMaster, authData).Result;

                    if (erpReleasedMaster.Exception != null)
                    {
                        DataWriter.LogErpActionStep(actionId, "Item create: write Released Product Master", startTime, false, erpReleasedMaster.Exception.ErrorMessage, erpReleasedMaster.Exception.StackTrace, -1);
                        OnTaskCompleted(this, new ErpTaskCompletedArgs {
                            Exception = erpReleasedMaster.Exception, ActionId = actionId, Status = 3
                        });
                    }
                    else if (erpReleasedMaster.WriteObject.ItemNumber.ToLower().Trim() != master.ProductNumber.ToLower().Trim())
                    {
                        DataWriter.LogErpActionStep(actionId, "Item create: write Released Product Master", startTime, false, null, null, -1);
                        OnTaskCompleted(this, new ErpTaskCompletedArgs
                        {
                            Exception =
                                new AxBaseException
                            {
                                ApplicationException = new ApplicationException(
                                    "The item number for Released Product Master does not match the returned number, AX value = " + erpReleasedMaster.WriteObject.ItemNumber + " AGR number = " + masterData.product_no)
                            },
                            ActionId = actionId,
                            Status   = 3
                        });
                        return(actionId);
                    }
                    DataWriter.LogErpActionStep(actionId, "Item create: write Released Product Master", startTime, true, null, null, -1);
                }

                foreach (var item in itemsToCreate)
                {
                    var variant = new ReleasedProductVariantDTO
                    {
                        ItemNumber = item.product_no,
                        //ProductColorId = item.color_group_no,
                        ProductColorId         = item.color_no,
                        ProductSizeId          = item.size_no,
                        ProductConfigurationId = "",
                        ProductStyleId         = "",
                        ProductDescription     = item.description,
                        ProductName            = item.product_name + "_" + item.color_no + "_" + item.size,
                        ProductSearchName      = (item.product_name + "_" + item.color_no + "_" + item.size).Trim(),
                        ProductMasterNumber    = item.product_no
                    };
                    startTime = DateTime.Now;
                    var erpVariants = ServiceConnector.CallOdataEndpointPost <ReleasedProductVariantDTO, EnumConverter>("ReleasedProductVariants", null, variant, authData).Result;

                    if (erpVariants.Exception != null)
                    {
                        DataWriter.LogErpActionStep(actionId, "Item create: write Released Product Variant", startTime, false, erpVariants.Exception.ErrorMessage, erpVariants.Exception.StackTrace, -1);
                        OnTaskCompleted(this, new ErpTaskCompletedArgs {
                            Exception = erpVariants.Exception, ActionId = actionId, Status = 3
                        });
                        return(actionId);
                    }
                    DataWriter.LogErpActionStep(actionId, "Item create: write Released Product Variant", startTime, true, null, null, -1);
                }
            }
            OnTaskCompleted(this, new ErpTaskCompletedArgs {
                ActionId = actionId, Status = 2
            });
            return(actionId);
        }
示例#39
0
        /// <summary>
        /// NaturalLanguageUnderstandingService constructor.
        /// </summary>
        /// <param name="version">Release date of the API version you want to use. Specify dates in YYYY-MM-DD format.
        /// The current version is `2020-08-01`.</param>
        /// <param name="serviceName">The service name to be used when configuring the client instance</param>
        /// <param name="authenticator">The service authenticator.</param>
        public NaturalLanguageUnderstandingService(string version, string serviceName, Authenticator authenticator) : base(authenticator, serviceName)
        {
            Authenticator = authenticator;

            if (string.IsNullOrEmpty(version))
            {
                throw new ArgumentNullException("`version` is required");
            }
            else
            {
                Version = version;
            }

            if (string.IsNullOrEmpty(GetServiceUrl()))
            {
                SetServiceUrl(defaultServiceUrl);
            }
        }
示例#40
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post")]
            HttpRequest req,
            [StorageAccount("StorageConnectionString")]
            CloudStorageAccount storageAccount,
            TraceWriter log
            )
        {
            var    client       = storageAccount.CreateCloudTableClient();
            string partitionKey = await Authenticator.Authenticate(client, req);

            if (string.IsNullOrEmpty(partitionKey))
            {
                return(new UnauthorizedResult());
            }

            var partitions = await PartionUtility.GetAllPartitions(log, client, partitionKey);

            log.Info($"Received a request from {partitionKey} to erase the account");

            // Foreach partition: Delete all items
            var itemTable = client.GetTableReference(ItemV2.TableName);

            foreach (var partition in partitions)
            {
                var query   = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partition.RowKey);
                var exQuery = new TableQuery <ItemV2>().Where(query);
                var items   = await QueryHelper.ListAll(itemTable, exQuery);

                log.Info($"Deleting stored items in partition {partition.RowKey} for {partitionKey}");
                BatchDelete(log, itemTable, partition.RowKey, items);
            }

            // Delete the 'removed items' entries
            foreach (var partition in partitions)
            {
                log.Info($"Deleting removed items in partition {partition.RowKey} for {partitionKey}");
                DeleteDeletedItems(log, client, partition.RowKey);
            }

            // Delete the partition entries
            var partitionTable = client.GetTableReference(PartitionV2.TableName);

            foreach (var partition in partitions)
            {
                log.Info($"Deleting partition {partition.RowKey} for {partitionKey}");
                await partitionTable.ExecuteAsync(TableOperation.Delete(partition));
            }

            // Delete auth entry used for logins
            try {
                var table = client.GetTableReference(Authentication.TableName);
                await table.CreateIfNotExistsAsync();

                var query = TableQuery.CombineFilters(
                    TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, Authentication.PartitionName),
                    TableOperators.And,
                    TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, req.Headers["Simple-Auth"])
                    );

                var exQuery            = new TableQuery <Authentication>().Where(query);
                var authenticationKeys = await QueryHelper.ListAll(table, exQuery);

                BatchDelete(log, table, Authentication.PartitionName, authenticationKeys);
            }
            catch (Exception ex) {
                log.Warning("Error deleting auth entry", ex.StackTrace);
            }

            return(new OkObjectResult(""));
        }
示例#41
0
 /// <summary>
 /// Bare bones constructor in case someone wants none of the automatic behavior at all
 /// </summary>
 public ApiMethods()
 {
     _authenticator = request => AuthSession.Authenticate(request);
 }
示例#42
0
        /// <summary>
        /// Analyze text.
        ///
        /// Analyzes text, HTML, or a public webpage for the following features:
        /// - Categories
        /// - Concepts
        /// - Emotion
        /// - Entities
        /// - Keywords
        /// - Metadata
        /// - Relations
        /// - Semantic roles
        /// - Sentiment
        /// - Syntax (Experimental).
        ///
        /// If a language for the input text is not specified with the `language` parameter, the service [automatically
        /// detects the
        /// language](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-detectable-languages).
        /// </summary>
        /// <param name="callback">The callback function that is invoked when the operation completes.</param>
        /// <param name="features">Specific features to analyze the document for.</param>
        /// <param name="text">The plain text to analyze. One of the `text`, `html`, or `url` parameters is required.
        /// (optional)</param>
        /// <param name="html">The HTML file to analyze. One of the `text`, `html`, or `url` parameters is required.
        /// (optional)</param>
        /// <param name="url">The webpage to analyze. One of the `text`, `html`, or `url` parameters is required.
        /// (optional)</param>
        /// <param name="clean">Set this to `false` to disable webpage cleaning. To learn more about webpage cleaning,
        /// see the [Analyzing
        /// webpages](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages)
        /// documentation. (optional, default to true)</param>
        /// <param name="xpath">An [XPath
        /// query](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages#xpath)
        /// to perform on `html` or `url` input. Results of the query will be appended to the cleaned webpage text
        /// before it is analyzed. To analyze only the results of the XPath query, set the `clean` parameter to `false`.
        /// (optional)</param>
        /// <param name="fallbackToRaw">Whether to use raw HTML content if text cleaning fails. (optional, default to
        /// true)</param>
        /// <param name="returnAnalyzedText">Whether or not to return the analyzed text. (optional, default to
        /// false)</param>
        /// <param name="language">ISO 639-1 code that specifies the language of your text. This overrides automatic
        /// language detection. Language support differs depending on the features you include in your analysis. See
        /// [Language
        /// support](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-language-support)
        /// for more information. (optional)</param>
        /// <param name="limitTextCharacters">Sets the maximum number of characters that are processed by the service.
        /// (optional)</param>
        /// <returns><see cref="AnalysisResults" />AnalysisResults</returns>
        public bool Analyze(Callback <AnalysisResults> callback, Features features, string text = null, string html = null, string url = null, bool?clean = null, string xpath = null, bool?fallbackToRaw = null, bool?returnAnalyzedText = null, string language = null, long?limitTextCharacters = null)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("`callback` is required for `Analyze`");
            }
            if (features == null)
            {
                throw new ArgumentNullException("`features` is required for `Analyze`");
            }

            RequestObject <AnalysisResults> req = new RequestObject <AnalysisResults>
            {
                Callback               = callback,
                HttpMethod             = UnityWebRequest.kHttpVerbPOST,
                DisableSslVerification = DisableSslVerification
            };

            foreach (KeyValuePair <string, string> kvp in customRequestHeaders)
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            ClearCustomRequestHeaders();

            foreach (KeyValuePair <string, string> kvp in Common.GetSdkHeaders("natural-language-understanding", "V1", "Analyze"))
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            req.Parameters["version"]   = VersionDate;
            req.Headers["Content-Type"] = "application/json";
            req.Headers["Accept"]       = "application/json";

            JObject bodyObject = new JObject();

            if (features != null)
            {
                bodyObject["features"] = JToken.FromObject(features);
            }
            if (!string.IsNullOrEmpty(text))
            {
                bodyObject["text"] = text;
            }
            if (!string.IsNullOrEmpty(html))
            {
                bodyObject["html"] = html;
            }
            if (!string.IsNullOrEmpty(url))
            {
                bodyObject["url"] = url;
            }
            if (clean != null)
            {
                bodyObject["clean"] = JToken.FromObject(clean);
            }
            if (!string.IsNullOrEmpty(xpath))
            {
                bodyObject["xpath"] = xpath;
            }
            if (fallbackToRaw != null)
            {
                bodyObject["fallback_to_raw"] = JToken.FromObject(fallbackToRaw);
            }
            if (returnAnalyzedText != null)
            {
                bodyObject["return_analyzed_text"] = JToken.FromObject(returnAnalyzedText);
            }
            if (!string.IsNullOrEmpty(language))
            {
                bodyObject["language"] = language;
            }
            if (limitTextCharacters != null)
            {
                bodyObject["limit_text_characters"] = JToken.FromObject(limitTextCharacters);
            }
            req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject));

            req.OnResponse = OnAnalyzeResponse;

            Connector.URL = GetServiceUrl() + "/v1/analyze";
            Authenticator.Authenticate(Connector);

            return(Connector.Send(req));
        }
示例#43
0
 private bool IsValid(BasicAuthRequest auth)
 {
     return(Authenticator.Invoke(auth.Username, auth.Credentials.Last()));
 }
示例#44
0
        // This method is auto-detected by the OWIN pipeline. DO NOT RENAME IT!
        public static void Configuration(IAppBuilder app)
        {
            // Tune ServicePointManager
            // (based on http://social.technet.microsoft.com/Forums/en-US/windowsazuredata/thread/d84ba34b-b0e0-4961-a167-bbe7618beb83 and https://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.aspx)
            ServicePointManager.DefaultConnectionLimit = 500;
            ServicePointManager.UseNagleAlgorithm      = false;
            ServicePointManager.Expect100Continue      = false;

            // Ensure that SSLv3 is disabled and that Tls v1.2 is enabled.
            ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3;
            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;

            // Setting time out for all RegEx objects. Noted in remarks at https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.matchtimeout%28v=vs.110%29.aspx
            AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(10));

            // Register IoC
            app.UseAutofacInjection(GlobalConfiguration.Configuration);
            var dependencyResolver = DependencyResolver.Current;

            // Register Elmah
            var elmahServiceCenter = new DependencyResolverServiceProviderAdapter(dependencyResolver);

            ServiceCenter.Current = _ => elmahServiceCenter;

            // Get config
            var config = dependencyResolver.GetService <IGalleryConfigurationService>();
            var auth   = dependencyResolver.GetService <AuthenticationService>();

            // Configure machine key for session persistence across slots
            SessionPersistence.Setup(config);
            // Refresh the content for the ContentObjectService to guarantee it has loaded the latest configuration on startup.
            var contentObjectService = dependencyResolver.GetService <IContentObjectService>();

            HostingEnvironment.QueueBackgroundWorkItem(async token =>
            {
                while (!token.IsCancellationRequested)
                {
                    await contentObjectService.Refresh();
                    await Task.Delay(ContentObjectService.RefreshInterval, token);
                }
            });

            // Setup telemetry
            var instrumentationKey = config.Current.AppInsightsInstrumentationKey;

            if (!string.IsNullOrEmpty(instrumentationKey))
            {
                TelemetryConfiguration.Active.InstrumentationKey = instrumentationKey;

                // Add enrichers
                TelemetryConfiguration.Active.TelemetryInitializers.Add(new ClientInformationTelemetryEnricher());

                var telemetryProcessorChainBuilder = TelemetryConfiguration.Active.TelemetryProcessorChainBuilder;

                // Add processors
                telemetryProcessorChainBuilder.Use(next =>
                {
                    var processor = new RequestTelemetryProcessor(next);

                    processor.SuccessfulResponseCodes.Add(400);
                    processor.SuccessfulResponseCodes.Add(404);
                    processor.SuccessfulResponseCodes.Add(405);

                    return(processor);
                });

                telemetryProcessorChainBuilder.Use(next => new ClientTelemetryPIIProcessor(next));

                var telemetry = dependencyResolver.GetService <TelemetryClientWrapper>();
                telemetryProcessorChainBuilder.Use(
                    next => new ExceptionTelemetryProcessor(next, telemetry.UnderlyingClient));

                // Note: sampling rate must be a factor 100/N where N is a whole number
                // e.g.: 50 (= 100/2), 33.33 (= 100/3), 25 (= 100/4), ...
                // https://azure.microsoft.com/en-us/documentation/articles/app-insights-sampling/
                var instrumentationSamplingPercentage = config.Current.AppInsightsSamplingPercentage;
                if (instrumentationSamplingPercentage > 0 && instrumentationSamplingPercentage < 100)
                {
                    telemetryProcessorChainBuilder.UseSampling(instrumentationSamplingPercentage);
                }

                telemetryProcessorChainBuilder.Build();
            }

            // Configure logging
            app.SetLoggerFactory(new DiagnosticsLoggerFactory());

            // Remove X-AspNetMvc-Version header
            MvcHandler.DisableMvcResponseHeader = true;

            if (config.Current.RequireSSL)
            {
                // Put a middleware at the top of the stack to force the user over to SSL
                if (config.Current.ForceSslExclusion == null)
                {
                    app.UseForceSsl(config.Current.SSLPort);
                }
                else
                {
                    app.UseForceSsl(config.Current.SSLPort, config.Current.ForceSslExclusion);
                }
            }

            // Get the local user auth provider, if present and attach it first
            Authenticator localUserAuthenticator;

            if (auth.Authenticators.TryGetValue(Authenticator.GetName(typeof(LocalUserAuthenticator)), out localUserAuthenticator))
            {
                // Configure cookie auth now
                localUserAuthenticator.Startup(config, app).Wait();
            }

            // Attach external sign-in cookie middleware
            app.SetDefaultSignInAsAuthenticationType(AuthenticationTypes.External);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = AuthenticationTypes.External,
                AuthenticationMode = AuthenticationMode.Passive,
                CookieName         = ".AspNet." + AuthenticationTypes.External,
                ExpireTimeSpan     = TimeSpan.FromMinutes(5)
            });

            // Attach non-cookie auth providers
            var nonCookieAuthers = auth
                                   .Authenticators
                                   .Where(p => !String.Equals(
                                              p.Key,
                                              Authenticator.GetName(typeof(LocalUserAuthenticator)),
                                              StringComparison.OrdinalIgnoreCase))
                                   .Select(p => p.Value);

            foreach (var auther in nonCookieAuthers)
            {
                auther.Startup(config, app).Wait();
            }

            // Catch unobserved exceptions from threads before they cause IIS to crash:
            TaskScheduler.UnobservedTaskException += (sender, exArgs) =>
            {
                // Send to AppInsights
                try
                {
                    var telemetryClient = new TelemetryClient();
                    telemetryClient.TrackException(exArgs.Exception, new Dictionary <string, string>()
                    {
                        { "ExceptionOrigin", "UnobservedTaskException" }
                    });
                }
                catch (Exception)
                {
                    // this is a tragic moment... swallow Exception to prevent crashing IIS
                }

                // Send to ELMAH
                try
                {
                    HttpContext current = HttpContext.Current;
                    if (current != null)
                    {
                        var errorSignal = ErrorSignal.FromContext(current);
                        if (errorSignal != null)
                        {
                            errorSignal.Raise(exArgs.Exception, current);
                        }
                    }
                }
                catch (Exception)
                {
                    // more tragedy... swallow Exception to prevent crashing IIS
                }

                exArgs.SetObserved();
            };

            HasRun = true;
        }
示例#45
0
 public SendMessageMenuItem(Authenticator authenticator)
 {
     this.authenticator = authenticator;
     this.Icon          = "Images/message.png";
     this.DisplayName   = Resources.MenuItem_SendMessage;
 }
示例#46
0
        internal WebRequest CreateWebRequest(Action <WebRequest> onRequestReady)
        {
            HttpWebRequest httpRequest = BuildRequest();

            // Create the request.
            Authenticator.ApplyAuthenticationToRequest(httpRequest);

            // Insert the content type and user agent.
            httpRequest.ContentType = string.Format(
                "{0}; charset={1}", GetReturnMimeType(), ContentCharset.WebName);

            // The UserAgent header can only be set on a non-Silverlight platform.
            // Silverlight uses the user agent of the browser instead.
#if !SILVERLIGHT
            var osPlatform = Environment.OSVersion.Platform;
            var osVersion  = Environment.OSVersion.Version;
            var clrVersion = Environment.Version;
            httpRequest.UserAgent = String.Format(UserAgent, ApplicationName, ApiVersion,
                                                  osPlatform, osVersion, clrVersion);
#endif

            // Add the E-tag header:
            if (!string.IsNullOrEmpty(ETag))
            {
                ETagAction action = this.ETagAction;
                if (action == ETagAction.Default)
                {
                    action = GetDefaultETagAction(httpRequest.Method);
                }

                switch (action)
                {
                case ETagAction.IfMatch:
                    httpRequest.Headers[HttpRequestHeader.IfMatch] = ETag;
                    break;

                case ETagAction.IfNoneMatch:
                    httpRequest.Headers[HttpRequestHeader.IfNoneMatch] = ETag;
                    break;
                }
            }

#if !SILVERLIGHT
            // Check if compression is supported.
            if (Service.GZipEnabled)
            {
                httpRequest.UserAgent += GZipUserAgentSuffix;
                httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            }
#endif

            // Attach a body if a POST and there is something to attach.
            if (HttpMethodHasBody(httpRequest.Method))
            {
                if (!string.IsNullOrEmpty(Body))
                {
                    AttachBody(httpRequest, onRequestReady);
                    return(httpRequest);
                }
                else
                {
                    // Set the "Content-Length" header, which is required for every http method declaring a body. This
                    // is required as e.g. the google servers will throw a "411 - Length required" error otherwise.
#if !SILVERLIGHT
                    httpRequest.ContentLength = 0;
#else
                    // Set by the browser on Silverlight. Cannot be modified by the user.
#endif
                }
            }

            onRequestReady(httpRequest);
            return(httpRequest);
        }
        /// <summary>
        /// Translate document.
        ///
        /// Submit a document for translation. You can submit the document contents in the `file` parameter, or you can
        /// reference a previously submitted document by document ID.
        /// </summary>
        /// <param name="callback">The callback function that is invoked when the operation completes.</param>
        /// <param name="file">The contents of the source file to translate.
        ///
        /// [Supported file
        /// types](https://cloud.ibm.com/docs/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats)
        ///
        /// Maximum file size: **20 MB**.</param>
        /// <param name="filename">The filename for file.</param>
        /// <param name="fileContentType">The content type of file. (optional)</param>
        /// <param name="modelId">The model to use for translation. For example, `en-de` selects the IBM provided base
        /// model for English to German translation. A model ID overrides the source and target parameters and is
        /// required if you use a custom model. If no model ID is specified, you must specify a target language.
        /// (optional)</param>
        /// <param name="source">Language code that specifies the language of the source document. (optional)</param>
        /// <param name="target">Language code that specifies the target language for translation. Required if model ID
        /// is not specified. (optional)</param>
        /// <param name="documentId">To use a previously submitted document as the source for a new translation, enter
        /// the `document_id` of the document. (optional)</param>
        /// <returns><see cref="DocumentStatus" />DocumentStatus</returns>
        public bool TranslateDocument(Callback <DocumentStatus> callback, System.IO.MemoryStream file, string filename, string fileContentType = null, string modelId = null, string source = null, string target = null, string documentId = null)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("`callback` is required for `TranslateDocument`");
            }
            if (file == null)
            {
                throw new ArgumentNullException("`file` is required for `TranslateDocument`");
            }
            if (string.IsNullOrEmpty(filename))
            {
                throw new ArgumentNullException("`filename` is required for `TranslateDocument`");
            }

            RequestObject <DocumentStatus> req = new RequestObject <DocumentStatus>
            {
                Callback               = callback,
                HttpMethod             = UnityWebRequest.kHttpVerbPOST,
                DisableSslVerification = DisableSslVerification
            };

            foreach (KeyValuePair <string, string> kvp in customRequestHeaders)
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            ClearCustomRequestHeaders();

            foreach (KeyValuePair <string, string> kvp in Common.GetSdkHeaders("language_translator", "V3", "TranslateDocument"))
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            req.Parameters["version"] = VersionDate;
            req.Forms = new Dictionary <string, RESTConnector.Form>();
            if (file != null)
            {
                req.Forms["file"] = new RESTConnector.Form(file, filename, fileContentType);
            }
            if (!string.IsNullOrEmpty(modelId))
            {
                req.Forms["model_id"] = new RESTConnector.Form(modelId);
            }
            if (!string.IsNullOrEmpty(source))
            {
                req.Forms["source"] = new RESTConnector.Form(source);
            }
            if (!string.IsNullOrEmpty(target))
            {
                req.Forms["target"] = new RESTConnector.Form(target);
            }
            if (!string.IsNullOrEmpty(documentId))
            {
                req.Forms["document_id"] = new RESTConnector.Form(documentId);
            }

            req.OnResponse = OnTranslateDocumentResponse;

            Connector.URL = GetServiceUrl() + "/v3/documents";
            Authenticator.Authenticate(Connector);

            return(Connector.Send(req));
        }
示例#48
0
        public void Login(Authenticator authenticator)
        {
            authenticator.Completed += OnAuthCompleted;

            PlatformLogin(authenticator);
        }
 private WebResponse Resume(Authenticator authentication, Uri resumeUri,
     String httpmethod, Stream payload, string contentType,
     AsyncData data) {
     return UploadStream(httpmethod, resumeUri, authentication, payload, contentType, data);
 }
 public LogInfoViewModelTypeChangesWithPrevRevisionMenuItem(Authenticator authenticator)
 {
     this.authenticator = authenticator;
     this.DisplayName   = Resources.MenuItem_CompareWithPreviousResivision;
 }
        /// <summary>
        /// Translate.
        ///
        /// Translates the input text from the source language to the target language. A target language or translation
        /// model ID is required. The service attempts to detect the language of the source text if it is not specified.
        /// </summary>
        /// <param name="callback">The callback function that is invoked when the operation completes.</param>
        /// <param name="text">Input text in UTF-8 encoding. Multiple entries will result in multiple translations in
        /// the response.</param>
        /// <param name="modelId">The model to use for translation. For example, `en-de` selects the IBM provided base
        /// model for English to German translation. A model ID overrides the source and target parameters and is
        /// required if you use a custom model. If no model ID is specified, you must specify a target language.
        /// (optional)</param>
        /// <param name="source">Language code that specifies the language of the source document. (optional)</param>
        /// <param name="target">Language code that specifies the target language for translation. Required if model ID
        /// is not specified. (optional)</param>
        /// <returns><see cref="TranslationResult" />TranslationResult</returns>
        public bool Translate(Callback <TranslationResult> callback, List <string> text, string modelId = null, string source = null, string target = null)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("`callback` is required for `Translate`");
            }
            if (text == null)
            {
                throw new ArgumentNullException("`text` is required for `Translate`");
            }

            RequestObject <TranslationResult> req = new RequestObject <TranslationResult>
            {
                Callback               = callback,
                HttpMethod             = UnityWebRequest.kHttpVerbPOST,
                DisableSslVerification = DisableSslVerification
            };

            foreach (KeyValuePair <string, string> kvp in customRequestHeaders)
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            ClearCustomRequestHeaders();

            foreach (KeyValuePair <string, string> kvp in Common.GetSdkHeaders("language_translator", "V3", "Translate"))
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            req.Parameters["version"]   = VersionDate;
            req.Headers["Content-Type"] = "application/json";
            req.Headers["Accept"]       = "application/json";

            JObject bodyObject = new JObject();

            if (text != null && text.Count > 0)
            {
                bodyObject["text"] = JToken.FromObject(text);
            }
            if (!string.IsNullOrEmpty(modelId))
            {
                bodyObject["model_id"] = modelId;
            }
            if (!string.IsNullOrEmpty(source))
            {
                bodyObject["source"] = source;
            }
            if (!string.IsNullOrEmpty(target))
            {
                bodyObject["target"] = target;
            }
            req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject));

            req.OnResponse = OnTranslateResponse;

            Connector.URL = GetServiceUrl() + "/v3/translate";
            Authenticator.Authenticate(Connector);

            return(Connector.Send(req));
        }
示例#52
0
        public void Run()
        {
            var authent = new Authenticator(_agent, _storage);

            authent.SetupParameters();
            var state = authent.ObserveState();

            authent.CheckEncryptionKey();
            var sender = new MessageSender(_agent);



            var notify = new NotificationSource(_agent);
            var notif  = notify.MessagesNotifications();

            notif.Accept(async notifications =>
            {
                try
                {
                    var mg = notifications.Message.Content as TdApi.MessageContent.MessageText;
                    if (mg.Text.Text.HasValue())
                    {
                        var r = await _dialer.ExecuteAsync(new TdApi.OpenChat {
                            ChatId = notifications.Message.ChatId
                        });

                        var chats = await _dialer.ExecuteAsync(new TdApi.GetChatHistory
                        {
                            ChatId    = notifications.Message.ChatId,
                            Limit     = 10,
                            Offset    = 0,
                            OnlyLocal = false
                        });

                        var result = await _dialer.ExecuteAsync(new TdApi.ViewMessages {
                            ChatId = notifications.Message.ChatId, MessageIds = new[] { notifications.Message.Id }
                        });

                        var rxt = Taker.Talk(mg.Text.Text);

                        var rz = rxt;

                        for (int i = 0; i < 1; i++)
                        {
                            rz += i;

                            var rrr = await _dialer.ExecuteAsync(
                                new TdApi.SendChatAction {
                                ChatId = notifications.Message.ChatId, Action = new TdApi.ChatAction.ChatActionTyping()
                            }
                                );

                            var res = await _dialer.ExecuteAsync(
                                new TdApi.SetChatDraftMessage
                            {
                                ChatId         = notifications.Message.ChatId
                                , DraftMessage = new TdApi.DraftMessage
                                {
                                    InputMessageText = new TdApi.InputMessageContent.InputMessageText
                                    {
                                        Text = new TdApi.FormattedText {
                                            Text = rz
                                        }
                                    }
                                }
                            });
                            Thread.Sleep(5000);
                        }
                        var returnMsg = new TdApi.InputMessageContent.InputMessageText {
                            Text = new TdApi.FormattedText {
                                Text = rxt
                            }, ClearDraft = true
                        };
                        sender.SendMessage(notifications.Chat, returnMsg);

                        var r1 = await _dialer.ExecuteAsync(new TdApi.CloseChat {
                            ChatId = notifications.Message.ChatId
                        });
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            });


            _hub.Start();
        }
 /// <summary>
 /// retrieves the resumable URI for the rest of the operation. This will initiate the 
 /// communication with resumable upload server by posting against the starting URI
 /// </summary>
 /// <param name="resumableUploadUri"></param>
 /// <param name="authentication"></param>
 /// <param name="entry"></param>
 /// <returns>The uri to be used for the rest of the operation</returns>
 public Uri InitiateUpload(Uri resumableUploadUri, Authenticator authentication, string contentType, string slug, long contentLength) {
     return InitiateUpload(resumableUploadUri, authentication, contentType, slug, contentLength, HttpMethods.Post);
 }
示例#54
0
 /// <summary>
 /// NaturalLanguageUnderstandingService constructor.
 /// </summary>
 /// <param name="version">Release date of the API version you want to use. Specify dates in YYYY-MM-DD format.
 /// The current version is `2020-08-01`.</param>
 /// <param name="authenticator">The service authenticator.</param>
 public NaturalLanguageUnderstandingService(string version, Authenticator authenticator) : this(version, defaultServiceName, authenticator)
 {
 }
示例#55
0
 public void IsMockBuildTest()
 {
     Assert.That(Authenticator.IsMockBuild(), Is.True);
 }
示例#56
0
 public LoginPage(Authenticator authenticator)
 {
     _authenticator = authenticator ?? throw new ArgumentNullException(nameof(authenticator));
     InitializeComponent();
 }
        /// <summary>
        /// retrieves the resumable URI for the rest of the operation. This will initiate the 
        /// communication with resumable upload server by posting against the starting URI
        /// </summary>
        /// <param name="resumableUploadUri"></param>
        /// <param name="authentication"></param>
        /// <param name="entry"></param>
        /// <returns>The uri to be used for the rest of the operation</returns>
        public Uri InitiateUpload(Uri resumableUploadUri, Authenticator authentication, AbstractEntry entry, string httpMethod) {
            HttpWebRequest request = PrepareRequest(resumableUploadUri,
                authentication,
                entry.MediaSource.Name,
                entry.MediaSource.ContentType,
                entry.MediaSource.ContentLength,
                httpMethod);

            IVersionAware v = entry as IVersionAware;
            if (v != null) {
                // need to add the version header to the request
                request.Headers.Add(GDataGAuthRequestFactory.GDataVersion, v.ProtocolMajor.ToString() + "." + v.ProtocolMinor.ToString());
            }

            ISupportsEtag e = entry as ISupportsEtag;
            if (e != null && !Utilities.IsWeakETag(e)) {
                request.Headers.Add(GDataRequestFactory.IfMatch, e.Etag);
            }

            Stream outputStream = request.GetRequestStream();
            entry.SaveToXml(outputStream);
            outputStream.Close();

            /// this is the contenttype for the xml post
            request.ContentType = GDataRequestFactory.DefaultContentType;

            WebResponse response = request.GetResponse();
            return new Uri(response.Headers["Location"]);
        }
示例#58
0
        static void Main(string[] args)
        {
            Console.WriteLine("Enter 1 for Factory Pattern. \n" +
                              "Enter 2 for Observer Pattern.");
            int choice = Convert.ToInt32(Console.ReadLine());

            switch (choice)
            {
            case 1:
                var ef = new EmployeeFactory();
                Console.WriteLine(ef.GetEmployee(1).GetBonus());
                Console.ReadLine();
                break;

            case 2:
                var observable = new TemperatureMonitor();
                var observer   = new TemperatureReporter();
                observer.Subscribe(observable);
                observable.GetTemperature();
                break;

            case 3:
                var editor  = new Editor();
                var history = new Momento.History();

                editor.SetContent("a");
                history.Push(editor.CreateState());
                editor.SetContent("b");
                history.Push(editor.CreateState());
                editor.SetContent("c");
                history.Push(editor.CreateState());
                editor.Restore(history.Pop());
                editor.Restore(history.Pop());

                Console.WriteLine(editor.GetContent());
                break;

            case 4:

                Canvas canvas = new Canvas();
                canvas.SelectTool(new BrushTool());
                canvas.MouseDown();
                canvas.MouseUp();
                break;

            case 5:

                BrowseHistory browseHistory = new BrowseHistory();
                browseHistory.Push("www.google.com");
                browseHistory.Push("www.yahoo.com");
                browseHistory.Push("www.reddif.com");
                browseHistory.Push("www.youtube.com");

                IIterator <string> iterator = browseHistory.CreateIterator();
                while (iterator.HasNext())
                {
                    var url = iterator.Current();
                    Console.WriteLine(url);
                    iterator.next();
                }
                break;

            case 6:
                //The difference between State and Strategy pattern is that in state pattern there is only a single state of the object and the behaviour is determined by the implementation injected.
                //In strategy pattern there could be multiple behaviours in form of multiple properties inside class such as IFilter & ICompression. The implementation injected further changes the behaviour.
                PhotoProcessor photoProcessor = new PhotoProcessor(new BnW(), new JPEG());
                photoProcessor.ProcessPhoto();
                break;

            case 7:     //template
                AbstractPreFlightCheckList flightChecklist = new F16PreFlightCheckList();
                flightChecklist.runChecklist();

                break;

            case 8:     //command
                var service = new CustomerService();
                var command = new AddCustomerCommand(service);
                var button  = new Command.Button(command);
                button.click();

                var composite = new CompositeCommand();
                composite.Add(new ResizeCommand());
                composite.Add(new BlackAndWHiteCommand());
                var button2 = new Command.Button(composite);
                button2.click();

                var commandHisotry = new Command.Undo.History();

                var doc = new Command.Undo.HtmlDocument();
                doc.SetContent("Hello World");
                var boldCommand = new BoldCommand(doc, commandHisotry);
                boldCommand.Execute();
                Console.WriteLine(doc.GetContent());

                var undoCommand = new UndoCommand(commandHisotry);
                undoCommand.Execute();
                Console.WriteLine(doc.GetContent());

                break;

            case 9:     //Observer
                DataSource dataSource = new DataSource();
                dataSource.AddObserver(new Chart());
                dataSource.AddObserver(new SpreadSheet(dataSource));
                dataSource.SetValue("value changed");
                break;

            case 10:     //Mediator //the pattern is applied to encapsulate or centralize the interactions amongst a number of objects
                var dialog = new ArticlesDialogBox();
                dialog.SimulateUsserInteraction();
                break;

            case 11:     //Chain of Responsibility
                //autehnticator --> logger --> compressor --> null
                var compressor    = new Compressor(null);
                var logger        = new Logger(compressor);
                var authenticator = new Authenticator(logger);
                var server        = new WebServer(authenticator);
                server.handle(new HttpRequest()
                {
                    UserName = "******", Password = "******"
                });
                break;

            case 12:     //Visitor
                var document = new Visitor.HtmlDocument();
                document.Add(new HeadingNode());
                document.Add(new AnchorNode());
                document.Execute(new HighlighOperation());
                break;

            case 13:     // Composite
                var shape1 = new Shape();
                var shape2 = new Shape();
                var group1 = new Group();
                group1.Add(shape1);
                group1.Add(shape2);
                var group2 = new Group();
                var shape3 = new Shape();
                group2.Add(shape3);
                group1.Add(group2);
                group1.render();
                break;

            case 14:     //Adapter
                Image       image       = new Image();
                ImageViewer imageViewer = new ImageViewer(image);
                imageViewer.Apply(new SepiaFilter());
                imageViewer.Apply(new FancyAdapter(new FancyFilter()));
                break;

            case 15:     //Decorator
                var cloudStream  = new CloudStream();
                var encryptData  = new EncryptStream(cloudStream);
                var compressData = new CompressStream(encryptData);
                compressData.write("some random data");
                break;

            case 16:     //Facade
                NotificationService notificationService = new NotificationService();
                notificationService.Send("Hello..", "17.0.0.1");
                break;

            case 17:     //Flyweight
                PointService pointService = new PointService(new PointFactory());
                var          points       = pointService.getPoints();
                foreach (var p in points)
                {
                    p.draw();
                }
                break;

            case 18:     //Bridge
                AdvancedRemoteControl remote = new AdvancedRemoteControl(new SonyTv());
                remote.setChannel(1);
                break;

            case 19:     //Proxy
                Library       lib       = new Library();
                List <string> bookNames = new List <string>()
                {
                    "a", "b", "c"
                };
                foreach (var book in bookNames)
                {
                    lib.eBooks.Add(book, new EBookProxy(book));
                }
                lib.OpenEbook("a");
                break;

            case 20:     //Factory Method
                FactoryMethod.Employee emp          = new FactoryMethod.Employee();
                BaseEmployeeFactory    permanentEmp = new PermanentEmployeeFactory(emp);
                permanentEmp.ApplySalary();
                Console.WriteLine(emp.HouseAllowance);
                break;

            case 21:     //Abstract Factory
                AbstractFactory.Employee emp1 = new AbstractFactory.Employee();
                emp1.EmployeeTypeID = 1;
                emp1.JobDescription = "Manager";
                EmployeeSystemFactory esf = new EmployeeSystemFactory();
                var computerFactory       = esf.Create(emp1);
                Console.WriteLine($"{computerFactory.GetType()}, {computerFactory.Processor()}, {computerFactory.SystemType()}, {computerFactory.Brand()}");
                break;

            case 22:     //Builder
                Builder.IToyBuilder toyBuilder  = new Builder.PremiumToyBuilder();
                Builder.ToyDirector toyDirector = new Builder.ToyDirector(toyBuilder);
                toyDirector.CreateFullFledgedToy();
                Console.WriteLine(toyDirector.GetToy());
                break;

            case 23:     //Fluent Builder
                //Difference of implementation is visible in Director class.
                FluentBuilder.IToyBuilder toyBuilder1  = new FluentBuilder.PremiumToyBuilder();
                FluentBuilder.ToyDirector toyDirector1 = new FluentBuilder.ToyDirector(toyBuilder1);
                toyDirector1.CreateFullFledgedToy();
                Console.WriteLine(toyDirector1.GetToy());
                break;

            case 24:    //Object Pool
                ObjectPool <OneExpensiveObjToCreate> objPool = new ObjectPool <OneExpensiveObjToCreate>();
                OneExpensiveObjToCreate obj = objPool.Get();
                objPool.Release(obj);
                break;
            }

            Console.ReadLine();
        }
        private HttpWebRequest PrepareRequest(Uri target,
            Authenticator authentication,
            string slug,
            string contentType,
            long contentLength,
            string httpMethod) {
            HttpWebRequest request = authentication.CreateHttpWebRequest(httpMethod, target);
            request.Headers.Add(GDataRequestFactory.SlugHeader + ": " + slug);
            request.Headers.Add(GDataRequestFactory.ContentOverrideHeader + ": " + contentType);
            if (contentLength != -1) {
                request.Headers.Add(GDataRequestFactory.ContentLengthOverrideHeader + ": " + contentLength);
            }

            return request;
        }
示例#60
0
        ISalesforceUser RefreshSessionToken()         // Request a new access_token and return the user with the updated token
        {
            //
            // [email protected] 2015.01.08
            //
            // RefreshSessionToken was failing if the user had logged in during the current session. This is because
            // the SalesforceClient constructor sets AccessTokenUrl to null when a login is needed in order to force
            // the OAuth2Authenticator to use the implicit flow rather than the web server flow. Since AccessTokenUrl
            // is null in the Authenticator, the WebRequest.Create() call in the Authenticator throws an exception
            // when this refresh code executes.
            //
            // Refresh did work if the user logged in, saved the user to disk, closed the app, and restarted it since
            // then the SalesforceClient constructor did not set AccessTokenUrl to null in the Authenticator.
            //
            // The added lines of code below reload the AccessTokenUrl into the Authenticator if needed.
            // We then reset to null to preserve all other behavior in SalesforceClient that might rely on
            // AccessTokenUrl being null (e.g. if the app asks the user to login again, the AccessTokenUrl
            // must be null for the OAuth2Authenticator to choose the User-Agent Flow...if it's not null
            // the authenticator will perform the Web-Server Flow).
            //
            // This code is not ideal but it fixes a bug. Perhaps two OAuth2Authenticators should be used by SalesforceClient,
            // one for login and one for refresh. Using a single Authenticator for both is confusing and error prone as
            // demonstrated by the need for this patch. Using two would also allow the login Authenticator to use
            // the constructor intended for the User-Agent Flow...right now they use the constructor that should
            // perform the Web-Server Flow and then set AccessTokenUrl to null to change the behavior.
            //
            bool updateAccessTokenUrl = false;                                 // [email protected] 2015.01.08

            if (Authenticator.AccessTokenUrl == null)                          // [email protected] 2015.01.08
            {
                updateAccessTokenUrl         = true;                           // [email protected] 2015.01.08
                Authenticator.AccessTokenUrl = new Uri(TokenPath);             // [email protected] 2015.01.08
            }

            var queryOptions = new Dictionary <string, string>
            {
                { "grant_type", "refresh_token" },
                { "client_id", ClientId },
                { "client_secret", ClientSecret },
                { "refresh_token", CurrentUser.Properties["refresh_token"] }
            };

            var refreshTask = Authenticator.RequestAccessTokenAsync(queryOptions).ContinueWith(response =>
            {
                if (updateAccessTokenUrl)                                        // [email protected] 2015.01.08
                {
                    Authenticator.AccessTokenUrl = null;                         // [email protected] 2015.01.08
                }
                if (!response.IsFaulted)
                {
                    ForceUserReauthorization(false);

                    return(response.Result);
                }

                ForceUserReauthorization(true);

                var responseBody = ProcessResponseBody(response);
                Debug.WriteLine(responseBody);
                var responseData = JsonValue.Parse(responseBody);

                if (responseData.ContainsKey("error") && responseData["error"] == "invalid_grant")
                {
                    throw new InvalidSessionException(responseData["error_description"]);
                }

                return(response.Result);
            }, TaskScheduler.Default);

            // Don't need to await here, b/c we're already inside of a task.
            refreshTask.Wait(TimeSpan.FromSeconds(DefaultNetworkTimeout));
            CurrentUser.Properties ["access_token"] = refreshTask.Result ["access_token"];
            return(CurrentUser);
        }