コード例 #1
0
 /// <summary>
 /// Base Constructor..
 /// </summary>
 /// <param name="MaxBatches">Max number of concurrent batches possible</param>
 /// <param name="MaxRequestPerBatch">Max number of requests per Batch</param>
 /// <param name="traceLogger">TraceLogger</param>
 public BatchManager(DataverseTraceLogger traceLogger, int MaxBatches = 50000, int MaxRequestPerBatch = 5000)
 {
     logger = traceLogger;
     // Do a Version Check here?
     MaxNumberOfBatches          = MaxBatches;
     MaxNumberOfRequestsInABatch = MaxRequestPerBatch;
     RequestBatches = new Dictionary <Guid, RequestBatch>();
     logger.Log(string.Format(CultureInfo.InvariantCulture, "New Batch Manager Created, Max #of Batches:{0}, Max #of RequestsPerBatch:{1}", MaxBatches, MaxRequestPerBatch), System.Diagnostics.TraceEventType.Verbose);
 }
        /// <summary>
        /// Constructor with Parameter cacheFilePath
        /// </summary>
        /// <param name="cacheFilePath"></param>
        /// <param name="tokenCache"></param>
        public ClientTokenCache(ITokenCache tokenCache, string cacheFilePath)
        {
            logEntry = new DataverseTraceLogger();

            //If cacheFilePath is provided
            if (!string.IsNullOrEmpty(cacheFilePath))
            {
                _cacheFilePath = cacheFilePath;

                // Register MSAL event handlers.
                tokenCache.SetBeforeAccess(BeforeAccessNotification);
                tokenCache.SetAfterAccess(AfterAccessNotification);

                // Need to revist this for adding support for other cache providers:
                // https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-net-token-cache-serialization

                //				// Try to encrypt some data to test if Protect is available.
                //				try
                //				{
                //#pragma warning disable CS0618 // Type or member is obsolete
                //					ProtectedData.Protect(this.Serialize(), null, DataProtectionScope.CurrentUser);
                //#pragma warning restore CS0618 // Type or member is obsolete
                //				}
                //				catch (Exception ex)
                //				{
                //					_UseLocalFileEncryption = false;
                //					logEntry.Log("Encryption System not available in this environment", TraceEventType.Warning, ex);
                //				}


                // Create token cache file if one does not already exist.
                if (!File.Exists(_cacheFilePath))
                {
                    string directoryName = Path.GetDirectoryName(_cacheFilePath);

                    if (!Directory.Exists(directoryName))
                    {
                        Directory.CreateDirectory(directoryName);
                    }

                    //File.Create(string) returns an instance of the FileStream class. You need to use Close() method
                    //in order to close it and release resources which are using
                    try
                    {
                        File.Create(_cacheFilePath).Close();
                        // Encrypt the file
                        try
                        {
                            // user is using a specified file directory... encrypt file to user using Machine / FS Locking.
                            // this will lock / prevent users other then the current user from accessing this file.
                            FileInfo fi = new FileInfo(_cacheFilePath);
                            if (_UseLocalFileEncryption)
                            {
                                fi.Encrypt();
                            }
                        }
                        catch (IOException)
                        {
                            // This can happen when a certificate system on the host has failed.
                            // usually this can be fixed with the steps in this article : http://support.microsoft.com/kb/937536
                            //logEntry.Log(string.Format("{0}\r\nException Details : {1}", "Failed to Encrypt Configuration File!", encrEX), TraceEventType.Error);
                            //logEntry.Log("This problem may be related to a domain certificate in windows being out of sync with the domain, please read http://support.microsoft.com/kb/937536");
                        }
                        catch (Exception)
                        {
                            //logEntry.Log(string.Format("Failed to Encrypt Configuration File!", genEX), TraceEventType.Error);
                        }
                    }
                    catch (Exception exception)
                    {
                        logEntry.Log(string.Format("{0}\r\nException Details : {1}", "Error occurred in DataverseServiceClientTokenCache(). ", exception), TraceEventType.Error);
                    }
                }

                //// Register ADAL event handlers.
                //this.AfterAccess = AfterAccessNotification;
                //this.BeforeAccess = BeforeAccessNotification;

//				lock (_fileLocker)
//				{
//					try
//					{
//						// Read token from the persistent store and supply it to ADAL's in memory cache.
//						if (_UseLocalFileEncryption)
//#pragma warning disable CS0618 // Type or member is obsolete
//							this.Deserialize(File.Exists(_cacheFilePath) && File.ReadAllBytes(_cacheFilePath).Length != 0
//								? ProtectedData.Unprotect(File.ReadAllBytes(_cacheFilePath), null, DataProtectionScope.CurrentUser)
//								: null);
//#pragma warning restore CS0618 // Type or member is obsolete
//						else
//#pragma warning disable CS0618 // Type or member is obsolete
//							this.Deserialize(File.Exists(_cacheFilePath) && File.ReadAllBytes(_cacheFilePath).Length != 0
//								? File.ReadAllBytes(_cacheFilePath) : null);
//#pragma warning restore CS0618 // Type or member is obsolete
//					}
//					catch (Exception ex)
//					{
//						// Failed to access Local token cache file..
//						// Delete it.
//						logEntry.Log("Failed to access token cache file, resetting the token cache file", TraceEventType.Warning, ex);
//						Clear(_cacheFilePath);
//					}
//				}
            }
        }
コード例 #3
0
        /// <summary>
        /// Constructor for building the hook to call into the platform.
        /// </summary>
        public DataverseTelemetryBehaviors(ConnectionService cli)
        {
            _callerCdsConnectionServiceHandler = cli;

            // reading overrides from app config if present..
            // these values override the values that are set on the client from the server.
            DataverseTraceLogger logg = new DataverseTraceLogger();

            try
            {
                // Initialize user agent
                _userAgent = "Unknown";
                if (AppDomain.CurrentDomain != null)
                {
                    _userAgent = AppDomain.CurrentDomain.FriendlyName;
                }

                _userAgent = $"{_userAgent} (CdsSvcClient:{Environs.FileVersion})";

                if (_maxFaultSize == -1 && ConfigurationManager.AppSettings.AllKeys.Contains("MaxFaultSizeOverride"))
                {
                    var maxFaultSz = ConfigurationManager.AppSettings["MaxFaultSizeOverride"];
                    if (maxFaultSz is string && !string.IsNullOrWhiteSpace(maxFaultSz))
                    {
                        int.TryParse(maxFaultSz, out _maxFaultSize);
                        if (_maxFaultSize != -1)
                        {
                            if (_maxFaultSize < MAXFAULTSIZEDEFAULT)
                            {
                                _maxFaultSize = -1;
                                logg.Log($"Failed to set MaxFaultSizeOverride property. Value found: {maxFaultSz}. Size must be larger then {MAXFAULTSIZEDEFAULT}.", System.Diagnostics.TraceEventType.Warning);
                            }
                        }
                    }
                    else
                    {
                        logg.Log($"Failed to parse MaxFaultSizeOverride property. Value found: {maxFaultSz}. MaxFaultSizeOverride must be a valid integer.", System.Diagnostics.TraceEventType.Warning);
                    }
                }

                if (_maxReceivedMessageSize == -1 && ConfigurationManager.AppSettings.AllKeys.Contains("MaxReceivedMessageSizeOverride"))
                {
                    var maxRecvSz = ConfigurationManager.AppSettings["MaxReceivedMessageSizeOverride"];
                    if (maxRecvSz is string && !string.IsNullOrWhiteSpace(maxRecvSz))
                    {
                        int.TryParse(maxRecvSz, out _maxReceivedMessageSize);
                        if (_maxReceivedMessageSize != -1)
                        {
                            if (_maxReceivedMessageSize < MAXRECVMESSAGESIZEDEFAULT)
                            {
                                _maxReceivedMessageSize = -1;
                                logg.Log($"Failed to set MaxReceivedMessageSizeOverride property. Value found: {maxRecvSz}. Size must be larger then {MAXRECVMESSAGESIZEDEFAULT}.", System.Diagnostics.TraceEventType.Warning);
                            }
                        }
                    }
                    else
                    {
                        logg.Log($"Failed to parse MaxReceivedMessageSizeOverride property. Value found: {maxRecvSz}. MaxReceivedMessageSizeOverride must be a valid integer.", System.Diagnostics.TraceEventType.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                logg.Log("Failed to process binding override properties,  Only MaxFaultSizeOverride and MaxReceivedMessageSizeOverride are supported and must be integers.", System.Diagnostics.TraceEventType.Warning, ex);
            }
            finally
            {
                logg.Dispose();
            }
        }
        private DataverseConnectionStringProcessor(string serviceUri, string userName, string password, string domain, string homeRealmUri, string authType, string requireNewInstance, string clientId, string redirectUri,
                                                   string tokenCacheStorePath, string loginPrompt, string certStoreName, string certThumbprint, string skipDiscovery, string IntegratedSecurity, string clientSecret, ILogger logger)
        {
            DataverseTraceLogger logEntry = new DataverseTraceLogger();
            Uri _serviceuriName, _realmUri;

            bool tempbool = false;

            if (bool.TryParse(skipDiscovery, out tempbool))
            {
                SkipDiscovery = tempbool;
            }
            else
            {
                SkipDiscovery = true;                  // changed to change defaulting behavior of skip discovery.
            }
            ServiceUri          = GetValidUri(serviceUri, out _serviceuriName) ? _serviceuriName : null;
            HomeRealmUri        = GetValidUri(homeRealmUri, out _realmUri) ? _realmUri : null;
            DomainName          = !string.IsNullOrWhiteSpace(domain) ? domain : string.Empty;
            UserId              = !string.IsNullOrWhiteSpace(userName) ? userName : string.Empty;
            Password            = !string.IsNullOrWhiteSpace(password) ? password : string.Empty;
            ClientId            = !string.IsNullOrWhiteSpace(clientId) ? clientId : string.Empty;
            ClientSecret        = !string.IsNullOrWhiteSpace(clientSecret) ? clientSecret : string.Empty;
            TokenCacheStorePath = !string.IsNullOrWhiteSpace(tokenCacheStorePath) ? tokenCacheStorePath : string.Empty;
            RedirectUri         = ((Uri.IsWellFormedUriString(redirectUri, UriKind.RelativeOrAbsolute)) ? new Uri(redirectUri) : null);
            CertStoreName       = certStoreName;
            CertThumbprint      = certThumbprint;

            // Check to see if use current user is configured.
            bool _IntegratedSecurity = false;

            if (!string.IsNullOrEmpty(IntegratedSecurity))
            {
                bool.TryParse(IntegratedSecurity, out _IntegratedSecurity);
            }

            bool useUniqueConnection = true;              // Set default to true to follow the old behavior.

            if (!string.IsNullOrEmpty(requireNewInstance))
            {
                bool.TryParse(requireNewInstance, out useUniqueConnection);
            }
            UseUniqueConnectionInstance = useUniqueConnection;

            //UserIdentifier = !string.IsNullOrWhiteSpace(UserId) ? new UserIdentifier(UserId, UserIdentifierType.OptionalDisplayableId) : null;

            AuthenticationType authenticationType;

            if (Enum.TryParse(authType, out authenticationType))
            {
                AuthenticationType = authenticationType;
            }
            else
            {
                logEntry?.Log($"Authentication Type \"{authType}\" is not a valid Authentication Type.", System.Diagnostics.TraceEventType.Error);
                AuthenticationType = AuthenticationType.InvalidConnection;
            }

            PromptBehavior loginBehavior;

            if (Enum.TryParse(loginPrompt, out loginBehavior))
            {
                PromptBehavior = loginBehavior;
            }
            else
            {
                PromptBehavior = PromptBehavior.Auto;
            }

            if (ServiceUri != null)
            {
                SetOrgnameAndOnlineRegion(ServiceUri);
            }

            //if the client Id was not passed, use Sample AppID
            if (string.IsNullOrWhiteSpace(ClientId))
            {
                logEntry.Log($"Client ID not supplied, using SDK Sample Client ID for this connection", System.Diagnostics.TraceEventType.Warning);
                ClientId = sampleClientId;                // sample client ID
                if (RedirectUri == null)
                {
                    RedirectUri = new Uri(sampleRedirectUrl);                     // Sample app Redirect URI
                }
            }

            if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
            {
                ClientCredentials clientCredentials = new ClientCredentials();
                clientCredentials.UserName.UserName = userName;
                clientCredentials.UserName.Password = password;
                ClientCredentials = clientCredentials;
            }

            logEntry.Dispose();
        }