Beispiel #1
0
        /// <summary>
        /// Common exception handler for all channels.
        /// </summary>
        /// <param name="exception">A communication or service exception.</param>
        public static void HandleException(Exception exception)
        {
            // When the endpoint isn't available, the client will sleep for a few milliseconds and try again.
            if (exception is EndpointNotFoundException)
            {
                Thread.Sleep(1000);
            }

            // This will allow the user to try another identity.  There doesn't appear to be any way to just tell a channel to
            // prompt the client again for the credentials, so a new channel needs to be constructed.
            if (exception is SecurityAccessDeniedException || exception is MessageSecurityException)
            {
                ChannelStatus.IsPrompted = true;
            }

            // This exception comes from the user aborting out of a set of user credentials.  In this situation, it wouldn't be
            // useful to prompt the user again: they must have had a good reason for cancelling instead of just re-entering the
            // credentials.  This will prevent any further activity on any of the channels until the user decides to try again.
            // An external thread will need to reset this signal for the communications to start up again.
            if (exception is CommunicationObjectAbortedException)
            {
                ChannelStatus.LoginEvent.Reset();
            }

            // Write the error and stack trace out to the debug listener.
            EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace);
        }
        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="message">fault message</param>
        /// <param name="eventType">Logging level for this fault TraceEventType.Stop == No logging</param>
        protected FaultBase(string message, TraceEventType eventType)
        {
            this.Message = message;

            switch (eventType)
            {
            case TraceEventType.Error:
            case TraceEventType.Information:
            case TraceEventType.Warning:
                break;

            default:
                return;
            }

            string stackTrace = UnhandledExceptionHelper.GetStackString();

            string logString = string.Format("{0}\r\n{1}\r\n{2}", this.GetType().Name, message, stackTrace);

            switch (eventType)
            {
            case TraceEventType.Error:
                EventLog.Error(logString);
                break;

            case TraceEventType.Information:
                EventLog.Information(logString);
                break;

            case TraceEventType.Warning:
                EventLog.Warning(logString);
                break;
            }
        }
        /// <summary>
        /// Prompts the user for a certificate to authenticate that user on the channel.
        /// </summary>
        /// <param name="state">A generic parameter used to initialize the thread.</param>
        private void PromptBasic(object state)
        {
            // Extract the thread parameters.
            PromptData promptData = state as PromptData;

            // This creates the Basic credentials prompt and initializes it with the current user name and password.
            WindowUserName windowUsername = new WindowUserName();

            windowUsername.NetworkCredentials = promptData.NetworkCredentials;
            windowUsername.EndpointAddress    = promptData.EndpointAddress;
            try
            {
                // This presents the credentials to the user and allows them to be modified.
                if (windowUsername.ShowDialog() == true)
                {
                    promptData.IsCanceled         = false;
                    promptData.NetworkCredentials = windowUsername.NetworkCredentials;
                }
                else
                {
                    promptData.IsCanceled = true;
                }
            }
            catch (InvalidOperationException ioe)
            {
                // TODO: Re-visit this later for now we are going to silently log that we got this exception.
                //  Some case we are getting duplicate login dialog boxes.
                EventLog.Error(string.Format("{0} {1}\n {2}", ioe.Message, ioe.ToString(), ioe.StackTrace));
            }
        }
Beispiel #4
0
 public WebPage(params object[] parameter)
 {
     try
     {
         // Initialize the object.
         this.Uri = new System.Uri((string)parameter[0]);
     }
     catch (Exception exception)
     {
         EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace);
     }
 }
 /// <summary>
 /// call the worker thread callback with the state
 /// </summary>
 public void Invoke()
 {
     try
     {
         this.callBack(this.state);
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.Assert(false, ex.Message, ex.ToString());
         //catch the exception and log
         EventLog.Error(ex);
     }
 }
        /// <summary>
        /// Validate the credentials.
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        public override void Validate(string lookupId, string password)
        {
            bool      authenticated = false;
            ErrorCode errorCode     = ErrorCode.AccessDenied;

            if (String.IsNullOrEmpty(lookupId))
            {
                throw CreateAccessDeniedFault(ErrorCode.UserNotFound);
            }

            if (String.IsNullOrEmpty(password))
            {
                throw CreateAccessDeniedFault(ErrorCode.BadPassword);
            }


            try
            {
                ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings["ADConnectionString"];
                if (String.IsNullOrEmpty(connectionStringSettings.ConnectionString) == true && password != "q")
                {
                    return;
                }

                //put the correct partition distinguished name.
                DirectoryEntry directory = new DirectoryEntry(connectionStringSettings.ConnectionString + "RootDSE", lookupId, password,
                                                              AuthenticationTypes.None);

                //Bind to AD. If this succeedes then we have valid credentials
                object obj = directory.NativeObject;
                authenticated = true;
            }
            catch (DirectoryServicesCOMException deCOMException)
            {
                errorCode = ParseADErrorMessage(deCOMException.ExtendedErrorMessage);
                EventLog.Error(deCOMException);
            }
            catch (Exception exception)
            {
                EventLog.Error(exception);
            }

            //Send a fault back to the client.
            if (authenticated == false)
            {
                throw CreateAccessDeniedFault(errorCode);
            }
        }
        /// <summary>
        /// Parses a section of the configuration file for information about the persistent stores.
        /// </summary>
        /// <param name="parent">The configuration settings in a corresponding parent configuration section.</param>
        /// <param name="configContext">An HttpConfigurationContext when Create is called from the ASP.NET configuration system.
        /// Otherwise, this parameter is reserved and is a null reference.</param>
        /// <param name="section">The XmlNode that contains the configuration information from the configuration file. Provides direct access to the XML contents of the configuration section.</param>
        /// <returns>A ToolSection object created from the data in the configuration file.</returns>
        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            // Create an object to hold the data from the 'tool' section of the application configuration file.
            ToolSection toolSection = new ToolSection();

            try
            {
                // Read each of the nodes that contain information about the persistent stores and place them in the table.
                foreach (XmlNode xmlNode in section.SelectNodes("add"))
                {
                    // The 'type' section of the configuration file is modeled after other places in the OS where the type and
                    // assembly information are combined in the same string.  A simpler method might have been to break aprart the
                    // type string from the assembly string, but it's also a good idea to use standards where you find them.  In
                    // any event, when the 'type' specification is done this way, the padded spaces need to be removed from the
                    // values onced they're broken out from the original string.
                    XmlAttribute keyAttribute = xmlNode.Attributes["key"];
                    if (keyAttribute == null)
                    {
                        throw new Exception("Syntax error in configuration file section 'tools'.");
                    }
                    string name = keyAttribute.Value;

                    // The text appears in the 'Tools' menu.
                    XmlAttribute textAttribute = xmlNode.Attributes["text"];
                    if (textAttribute == null)
                    {
                        throw new Exception("Syntax error in configuration file section 'tools'.");
                    }
                    string text = textAttribute.Value;

                    // Pull apart the tool specification from the attributes.
                    XmlAttribute toolSpecificationAttribute = xmlNode.Attributes["tool"];
                    if (toolSpecificationAttribute == null)
                    {
                        throw new Exception("Syntax error in configuration file section 'tools'.");
                    }
                    string[] toolParts = toolSpecificationAttribute.Value.Split(new char[] { ',' });
                    if (toolParts.Length != 2)
                    {
                        throw new Exception("Syntax error in configuration file section 'tools'.");
                    }

                    // Attempt to load the tool into memory and find the type used to instantiate the tool.
                    Assembly    toolAssembly = Assembly.Load(toolParts[ToolSectionHandler.AssemblyIndex].Trim());
                    System.Type toolType     = toolAssembly.GetType(toolParts[ToolSectionHandler.TypeIndex]);

                    // Add the tool information to the section.  Each of these ToolInfo items describes what kind of object the
                    // tool is associated with and where to find the tool.
                    toolSection.Add(new ToolInfo(name, text, toolType));
                }
            }
            catch (Exception exception)
            {
                // Make sure that any errors caught while trying to load the tool info is recorded in the log.  A system
                // administrator can look through these to figure out why the tool information isn't formatted correctly.
                EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace);
            }

            // This object can be used to find a persistent store by nane and connect to it.
            return(toolSection);
        }
 /// <summary>
 /// Log the exception
 /// </summary>
 /// <param name="error"></param>
 /// <returns></returns>
 public bool HandleError(Exception error)
 {
     EventLog.Error(error);
     return(true);
 }
Beispiel #9
0
        private void LoadUnsafe()
        {
            // This flag is set when an error occurs anywhere in the processing of the XML file.
            this.HasErrors = false;

            // Read the XML data from the specified file.
            if (NotifyMessage != null)
            {
                this.NotifyMessage(this, new MessageEventArgs(string.Format("Loading {0}", FileName)));
            }

            XDocument xDocument = XDocument.Load(this.FileName);

            if (NotifyMessage != null)
            {
                this.NotifyMessage(this, new MessageEventArgs("Processing"));
            }

            // The script name is stored in the root node.  The name is used in status and debugging messages.
            XAttribute nameAttribute = xDocument.Root.Attribute("name");

            this.ScriptName = nameAttribute == null ? "Unnamed Transaction" : nameAttribute.Value;

            // This will force the user interface to appear the next time a channel is opened.  It also releases any threads that
            // may have been waiting for the user to provide a set of credentials.  Threads enter this waiting state when the user
            // hits the 'Cancel' button on any screen that prompts for credentials.
            if (this.ForceLogin && this.LocalMode == false)
            {
                ChannelStatus.IsPrompted = true;
            }

            if (this.LocalMode == false)
            {
                ChannelStatus.LoginEvent.Set();
            }

            List <XElement> xElementList = new List <XElement>();

            foreach (XElement xElement in xDocument.Root.Elements())
            {
                xElementList.Add(xElement);
            }

            //default to be 10%
            int tickPercent = xElementList.Count / 10;

            if (tickPercent < 50)
            {
                tickPercent = 50;
            }
            else if (tickPercent > 1000)
            {
                tickPercent = 1000;
            }

            // Cycle through all of the children of the root node.  Transactions are executed as a unit.  Methods outside of a
            // transaction element are executed alone.
            for (int elementIndex = 0; elementIndex < xElementList.Count; elementIndex++)
            {
                XElement xElement = xElementList[elementIndex];
                try
                {
                    if (NotifyMessage != null && elementIndex % tickPercent == 0)
                    {
                        MessageEventArgs mea = new MessageEventArgs("Next Tick");
                        mea.IsProgressTick = true;
                        this.NotifyMessage(this, mea);
                    }

                    switch (xElement.Name.LocalName)
                    {
                    case "client":

                        // A channel is required for each endpont that will be contacted during his load.
                        CreateClient(xElement);
                        break;

                    case "method":
                        if (this.tranactionScopeStack.Count == 0)
                        {
                            using (TransactionScope transactionScope = new TransactionScope())
                            {
                                // Parse and execute a single method out of the script.
                                if (ExecuteMethod(xElement))
                                {
                                    this.MethodCount++;
                                }

                                transactionScope.Complete();
                            }
                        }
                        else
                        {
                            // Parse and execute a single method out of the script.
                            if (ExecuteMethod(xElement))
                            {
                                this.MethodCount++;
                            }
                        }
                        break;

                    case "transaction":

                        // This creates a collection of methods that are executed as a unit.
                        ExecuteTransaction(xElement);
                        break;
                    }
                }
                catch (Exception exception)
                {
                    EventLog.Error(string.Format("{0} {1} {2}", exception.Message, exception.ToString(), exception.StackTrace));

                    ScriptLoaderException slEx = new ScriptLoaderException("Error in " + this.FileName, exception, xElement, this.MethodCount);

                    if (NotifyMessage != null)
                    {
                        this.NotifyMessage(this, new MessageEventArgs(slEx.Message));
                    }

                    throw slEx;
                }
            }

            if (NotifyMessage != null)
            {
                this.NotifyMessage(this, new MessageEventArgs(string.Format("Processed {0} methods in file: {1}", MethodCount, Path.GetFileName(FileName))));
            }

            // One or more channels may have been created dynamicall from the information in the scripts.  These dynamic channels
            // should be shut down gracefully before exiting.
            if (this.LocalMode == false)
            {
                foreach (KeyValuePair <String, ClientChannel> clientPair in this.clientTable)
                {
                    MethodInfo closeMethod = clientPair.Value.ChannelType.GetMethod("Close");
                    closeMethod.Invoke(clientPair.Value.ChannelObject, null);
                }
            }
        }