Exemplo n.º 1
0
        /// <summary>
        /// Creates new file for logging
        /// </summary>
        private void InitializeFileLogger(IEventSource eventSource, int nodeCount)
        {
            // Prepend the default setting of "forcenoalign": no alignment is needed as we're
            // writing to a file
            string parameters = Parameters;

            if (parameters != null)
            {
                Parameters = "FORCENOALIGN;" + parameters;
            }
            else
            {
                Parameters = "FORCENOALIGN;";
            }

            this.ParseFileLoggerParameters();

            // Finally, ask the base console logger class to initialize. It may
            // want to make decisions based on our verbosity, so we do this last.
            base.Initialize(eventSource, nodeCount);

            try
            {
                _fileWriter = new StreamWriter(_logFileName, _append, _encoding);

                _fileWriter.AutoFlush = _autoFlush;
            }
            catch (Exception e) when(ExceptionHandling.IsIoRelatedException(e))
            {
                string errorCode;
                string helpKeyword;
                string message = ResourceUtilities.FormatResourceString(out errorCode, out helpKeyword, "InvalidFileLoggerFile", _logFileName, e.Message);

                if (_fileWriter != null)
                {
                    _fileWriter.Close();
                }
                throw new LoggerException(message, e.InnerException, errorCode, helpKeyword);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Searches %PATH% for the location of Tracker.exe, and returns the first
        /// path that matches.
        /// <returns>Matching full path to Tracker.exe or null if a matching path is not found.</returns>
        /// </summary>
        public static string FindTrackerOnPath()
        {
            string[] paths = Environment.GetEnvironmentVariable("PATH").Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string path in paths)
            {
                string trackerPath;

                try
                {
                    if (!Path.IsPathRooted(path))
                    {
                        trackerPath = Path.GetFullPath(path);
                    }
                    else
                    {
                        trackerPath = path;
                    }

                    trackerPath = Path.Combine(trackerPath, s_TrackerFilename);

                    if (File.Exists(trackerPath))
                    {
                        return(trackerPath);
                    }
                }
                catch (Exception e)
                {
                    if (ExceptionHandling.NotExpectedException(e))
                    {
                        throw;
                    }

                    // Otherwise, just ignore this path and move on -- it's just bad for some reason.
                }
            }

            // Still haven't found it.
            return(null);
        }
Exemplo n.º 3
0
        private bool CopyLauncherToOutputDirectory(string strOutputExe)
        {
            if (!FileSystems.Default.FileExists(LauncherPath))
            {
                _results.AddMessage(BuildMessage.CreateMessage(BuildMessageSeverity.Error, "GenerateLauncher.MissingLauncherExe", LauncherPath));
                return(false);
            }

            try
            {
                EnsureFolderExists(Path.GetDirectoryName(strOutputExe));
                File.Copy(LauncherPath, strOutputExe, true);
                ClearReadOnlyAttribute(strOutputExe);
            }
            catch (Exception ex) when(ExceptionHandling.IsIoRelatedException(ex))
            {
                _results.AddMessage(BuildMessage.CreateMessage(BuildMessageSeverity.Error, "GenerateLauncher.CopyError", LauncherPath, strOutputExe, ex.Message));
                return(false);
            }

            return(true);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Read a lightup key from either HKLM or HKCU depending on what is passed in root.
        /// The key may either be a string, in which case it needs to be like "true" or "false"
        /// or it may be a DWORD in which case it should be 0 or !=0.
        /// </summary>
        private static bool? ReadLightupBool(string root, string valueName)
        {
            try
            {
                string key = String.Format(CultureInfo.InvariantCulture, @"{0}\software\microsoft\msbuild\{1}", root, MSBuildConstants.CurrentProductVersion);
                object value = Registry.GetValue(key, valueName, null);
                if (value != null)
                {
                    switch (System.Type.GetTypeCode(value.GetType()))
                    {
                        case TypeCode.Int32:
                            return ((int)value) != 0;
                        case TypeCode.String:
                            bool result;
                            if (bool.TryParse((string)value, out result))
                            {
                                return result;
                            }
                            return null;
                        default:
                            // Recover by assuming the flag is not set.
                            Debug.Assert(false, "Could not read debugger enabled flag. Key was found but it had type {0}" + value.GetType().ToString());
                            return null;
                    }
                }
                return null;
            }
            catch (Exception e)
            {
                if (ExceptionHandling.IsCriticalException(e))
                {
                    throw;
                }

                // Recover by assuming the flag is not set.
                Debug.Assert(false, "Could not read debugger enabled flag. {0}" + e.ToString());
                return null;
            }
        }
Exemplo n.º 5
0
 public int SaveRoomInventory(RoomInventory roomInventory)
 {
     try
     {
         SqlParameter[] sqlParameter = new SqlParameter[8];
         sqlParameter[0] = new SqlParameter("@RoomID", roomInventory.RoomID);
         sqlParameter[1] = new SqlParameter("@RoomType", roomInventory.RoomType);
         sqlParameter[2] = new SqlParameter("@HotelID", roomInventory.HotelID);
         sqlParameter[3] = new SqlParameter("@AgentID", HttpContext.Current.Session["AgentId"].ToString());
         sqlParameter[4] = new SqlParameter("@StartDate", roomInventory.StartDate);
         sqlParameter[5] = new SqlParameter("@EndDate", roomInventory.EndDate);
         sqlParameter[6] = new SqlParameter("@DaysOfWeek", roomInventory.DaysOfWeek);
         sqlParameter[7] = new SqlParameter("@Available", roomInventory.Available);
         SqlHelper.ExecuteNonQuery(sqlconn, CommandType.StoredProcedure, "sp_ManageRoomInventory", sqlParameter);
         return(1);
     }
     catch (Exception ex)
     {
         ExceptionHandling.WriteException(ex);
         return(0);
     }
 }
Exemplo n.º 6
0
    public void SetString(GameObject g, string a)
    {
        try
        {
            if (g != null)
            {
                if (g.GetComponent <TextMesh>() != null)
                {
                    g.GetComponent <TextMesh>().text = a;
                }
                else if (g.GetComponent <Text>() != null)
                {
                    g.GetComponent <Text>().text = a;
                }
            }
        }

        catch (Exception e)
        {
            ExceptionHandling.ExceptionHandler(e);
        }
    }
Exemplo n.º 7
0
        /// <summary>
        /// Prepopulates the SftpConnectionPool with servers defined in config file.
        /// </summary>
        /// <param name="section"></param>
        public static void Load(XmlNode section)
        {
            try
            {
                DefaultConnectionLimit = int.Parse(section.SelectSingleNode("SftpConnectionPool").Attributes["defaultConnectionLimit"].Value);
                Trace.WriteLine("[SftpConnectionPool] DefaultConnectionLimit set to " + DefaultConnectionLimit.ToString());

                foreach (XmlNode node in section.SelectNodes("SftpConnectionPool/Host"))
                {
                    string name      = node.Attributes["hostName"].Value;
                    int    connLimit = int.Parse(node.Attributes["connectionLimit"].Value);
                    Hosts.Add(new SftpHost(name, connLimit, true));
                    Trace.WriteLine("[SftpConnectionPool] A limited connections(" + connLimit.ToString() + ") given to " + name + ".");
                }
                Trace.WriteLine("[SftpConnectionPool] SftpConnectionPool was loaded with " + Hosts.Count.ToString() + " hosts.");
            }
            catch (Exception e)
            {
                throw ExceptionHandling.HandleComponentException(System.Reflection.MethodBase.GetCurrentMethod(),
                                                                 new Exception("SftpConnectionPool Load Configuration failed", e));
            }
        }
Exemplo n.º 8
0
 public void SetSprite(GameObject g, Texture2D Texture)
 {
     try
     {
         if (g != null && Texture != null)
         {
             Sprite _Sprite = Texture2DToSprite(Texture);
             if (g.GetComponent <SpriteRenderer>() != null)
             {
                 g.GetComponent <SpriteRenderer>().sprite = _Sprite;
             }
             else if (g.GetComponent <Image>() != null)
             {
                 g.GetComponent <Image>().sprite = _Sprite;
             }
         }
     }
     catch (Exception e)
     {
         ExceptionHandling.ExceptionHandler(e);
     }
 }
Exemplo n.º 9
0
        /// <summary>
        /// Deletes the state file from disk
        /// </summary>
        /// <param name="stateFile"></param>
        /// <param name="log"></param>
        static internal void DeleteFile(string stateFile, TaskLoggingHelper log)
        {
            try
            {
                if (stateFile != null && stateFile.Length > 0)
                {
                    if (File.Exists(stateFile))
                    {
                        File.Delete(stateFile);
                    }
                }
            }
            catch (Exception e)
            {
                // If there was a problem deleting the file (like it's read-only or locked on disk, for
                // example), then eat the exception and log a warning.  Otherwise, rethrow.
                if (ExceptionHandling.NotExpectedException(e))
                    throw;

                log.LogWarningWithCodeFromResources("General.CouldNotDeleteStateFile", stateFile, e.Message);
            }
        }
Exemplo n.º 10
0
        public string CreateAgent(string Email, string Password, string HotelType, string FullName)
        {
            Guid guid = Guid.Empty;

            try
            {
                List <SqlParameter> lstsqlparam = new List <SqlParameter>();
                lstsqlparam.Add(new SqlParameter("@AgentFullName", FullName));
                lstsqlparam.Add(new SqlParameter("@AgentType", HotelType));
                lstsqlparam.Add(new SqlParameter("@AgentEmail", Email));
                lstsqlparam.Add(new SqlParameter("@Password", Password));
                guid = (Guid)SqlHelper.ExecuteScalar(sqlconn, "sp_AgentLogin", lstsqlparam.ToArray());
            }
            catch (Exception ex)
            {
                ExceptionHandling.WriteException(ex);
            }
            finally
            {
            }
            return(guid.ToString());
        }
Exemplo n.º 11
0
 public void SetPositionExpandShrink(GameObject g, float height, bool Expand = true)
 {
     try
     {
         float SizeDeltaY        = g.GetComponent <RectTransform>().sizeDelta.y;
         float anchoredPositionY = g.GetComponent <RectTransform>().anchoredPosition.y;
         if (Expand)
         {
             g.GetComponent <RectTransform>().sizeDelta        = new Vector2(0, SizeDeltaY + height);
             g.GetComponent <RectTransform>().anchoredPosition = new Vector2(0, anchoredPositionY - (height / 2f));
         }
         else
         {
             g.GetComponent <RectTransform>().sizeDelta        = new Vector2(0, SizeDeltaY - height);
             g.GetComponent <RectTransform>().anchoredPosition = new Vector2(0, anchoredPositionY + (height / 2f));
         }
     }
     catch (Exception e)
     {
         ExceptionHandling.ExceptionHandler(e);
     }
 }
Exemplo n.º 12
0
        private bool WaitForConnectionFromProcess(AnonymousPipeServerStream clientToServerStream,
                                                  AnonymousPipeServerStream serverToClientStream,
                                                  int nodeProcessId, long hostHandshake, long clientHandshake)
        {
            try
            {
                CommunicationsUtilities.Trace("Attempting to handshake with PID {0}", nodeProcessId);

                CommunicationsUtilities.Trace("Writing handshake to pipe");
                serverToClientStream.WriteLongForHandshake(hostHandshake);

                CommunicationsUtilities.Trace("Reading handshake from pipe");
                long handshake = clientToServerStream.ReadLongForHandshake();

                if (handshake != clientHandshake)
                {
                    CommunicationsUtilities.Trace("Handshake failed. Received {0} from client not {1}. Probably the client is a different MSBuild build.", handshake, clientHandshake);
                    throw new InvalidOperationException();
                }

                // We got a connection.
                CommunicationsUtilities.Trace("Successfully connected got connection from PID {0}...!", nodeProcessId);
                return(true);
            }
            catch (Exception ex)
            {
                if (ExceptionHandling.IsCriticalException(ex))
                {
                    throw;
                }

                CommunicationsUtilities.Trace("Failed to get connection from PID {0}. {1}", nodeProcessId, ex.ToString());

                clientToServerStream.Dispose();
                serverToClientStream.Dispose();

                return(false);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Convert the raw value provided in the metadata to the type
        /// that has been inferred based on the parameter position or name.
        /// Returns the converted value as a CodeExpression if successful, or the raw value
        /// as a CodeExpression if conversion fails. No errors are logged if the conversion fails.
        /// </summary>
        private CodeExpression ConvertParameterValueToInferredType(Type inferredType, string rawValue, string parameterName)
        {
            // If we don't know what type the parameter should be, then we
            // can't convert the type. We'll just treat is as a string.
            if (inferredType is null)
            {
                Log.LogMessageFromResources("WriteCodeFragment.CouldNotInferParameterType", parameterName);
                return(new CodePrimitiveExpression(rawValue));
            }

            try
            {
                return(ConvertToCodeExpression(rawValue, inferredType));
            }
            catch (Exception ex) when(!ExceptionHandling.IsCriticalException(ex))
            {
                // The conversion failed, but since we are inferring the type,
                // we won't fail. We'll just treat the value as a string.
                Log.LogMessageFromResources("WriteCodeFragment.CouldNotConvertToInferredType", parameterName, inferredType.Name, ex.Message);
                return(new CodePrimitiveExpression(rawValue));
            }
        }
Exemplo n.º 14
0
 /// <summary>
 /// The handler for the write delegate of the console logger we are deriving from.
 /// </summary>
 /// <owner>KieranMo</owner>
 /// <param name="text">The text to write to the log</param>
 private void Write(string text)
 {
     try
     {
         fileWriter.Write(text);
     }
     catch (Exception ex) // Catching Exception, but rethrowing unless it's a well-known exception.
     {
         if (ExceptionHandling.NotExpectedException(ex))
         {
             throw;
         }
         string errorCode;
         string helpKeyword;
         string message = ResourceUtilities.FormatResourceString(out errorCode, out helpKeyword, "InvalidFileLoggerFile", logFileName, ex.Message);
         if (fileWriter != null)
         {
             fileWriter.Close();
         }
         throw new LoggerException(message, ex.InnerException, errorCode, helpKeyword);
     }
 }
Exemplo n.º 15
0
        /// <summary>
        /// Read the contents of this object out to the specified file.
        /// TODO: once all classes derived from StateFileBase adopt the new serialization, we should consider moving this into the base class
        /// </summary>
        internal static SystemState DeserializeCacheByTranslator(string stateFile, TaskLoggingHelper log)
        {
            // First, we read the cache from disk if one exists, or if one does not exist, we create one.
            try
            {
                if (!string.IsNullOrEmpty(stateFile) && FileSystems.Default.FileExists(stateFile))
                {
                    using FileStream s = File.OpenRead(stateFile);
                    var translator = BinaryTranslator.GetReadTranslator(s, buffer: null); // TODO: shared buffering?

                    // verify file signature
                    var contractSignature = translator.Reader.ReadBytes(TranslateContractSignature.Length);
                    var contractVersion   = translator.Reader.ReadByte();

                    if (!contractSignature.SequenceEqual(TranslateContractSignature) || contractVersion != TranslateContractVersion)
                    {
                        log.LogMessageFromResources("General.CouldNotReadStateFileMessage", stateFile, log.FormatResourceString("General.IncompatibleStateFileType"));
                        return(null);
                    }

                    SystemState systemState = new SystemState();
                    systemState.Translate(translator);
                    systemState.isDirty = false;

                    return(systemState);
                }
            }
            catch (Exception e) when(!ExceptionHandling.IsCriticalException(e))
            {
                // The deserialization process seems like it can throw just about
                // any exception imaginable.  Catch them all here.
                // Not being able to deserialize the cache is not an error, but we let the user know anyway.
                // Don't want to hold up processing just because we couldn't read the file.
                log.LogMessageFromResources("General.CouldNotReadStateFileMessage", stateFile, e.Message);
            }

            return(null);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Get the framework name from the assembly.
        /// </summary>
        private FrameworkName GetFrameworkName()
        {
            FrameworkName frameworkAttribute = null;

            try
            {
                IMetaDataImport2 import2  = (IMetaDataImport2)_assemblyImport;
                IntPtr           data     = IntPtr.Zero;
                UInt32           valueLen = 0;
                string           frameworkNameAttribute = null;
                UInt32           assemblyScope;

                _assemblyImport.GetAssemblyFromScope(out assemblyScope);
                int hr = import2.GetCustomAttributeByName(assemblyScope, s_targetFrameworkAttribute, out data, out valueLen);

                // get the AssemblyTitle
                if (hr == NativeMethodsShared.S_OK)
                {
                    // if an AssemblyTitle exists, parse the contents of the blob
                    if (NativeMethods.TryReadMetadataString(_sourceFile, data, valueLen, out frameworkNameAttribute))
                    {
                        if (!String.IsNullOrEmpty(frameworkNameAttribute))
                        {
                            frameworkAttribute = new FrameworkName(frameworkNameAttribute);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (ExceptionHandling.IsCriticalException(e))
                {
                    throw;
                }
            }

            return(frameworkAttribute);
        }
Exemplo n.º 17
0
 public bool ExpireCookie()
 {
     try
     {
         HttpCookie aCookie;
         string     cookieName;
         int        limit = Request.Cookies.Count;
         for (int i = 0; i < limit; i++)
         {
             cookieName = Request.Cookies[i].Name;
             aCookie    = new HttpCookie(cookieName)
             {
                 Expires = DateTime.Now.AddDays(-1)
             };
             System.Web.HttpContext.Current.Response.Cookies.Add(aCookie);
         }
         if (Request.Cookies["StockOrion"] != null)
         {
             HttpCookie myCookie = new HttpCookie("StockOrion");
             myCookie.Expires = DateTime.Now.AddDays(-1d);
             Response.Cookies.Add(myCookie);
             DataBaseClass.Global.IntLoginID       = 0;
             DataBaseClass.Global.StrLoginName     = "";
             DataBaseClass.Global.StrLoginUserName = "";
             DataBaseClass.Global.StrUserBrowser   = "";
             DataBaseClass.Global.StrLoginIP       = "";
             Session.Abandon();
             Session.Clear();
             Session.RemoveAll();
             System.Web.Security.FormsAuthentication.SignOut();
         }
     }
     catch (Exception ex)
     {
         ExceptionHandling.CatchAndLogError(ex, "Error while trying to ExpireCookie()", "AdminController.cs", DataBaseClass.Global.StrLoginName, "LoginModel.cs", "public bool ExpireCookie()");
     }
     return(true);
 }
Exemplo n.º 18
0
        /// <summary>
        /// Read the .config from a file.
        /// </summary>
        /// <param name="appConfigFile"></param>
        internal void Load(string appConfigFile)
        {
            XmlTextReader reader = null;

            try
            {
                reader = new XmlTextReader(appConfigFile);
                reader.DtdProcessing = DtdProcessing.Ignore;
                Read(reader);
            }
            catch (XmlException e)
            {
                throw new AppConfigException(e.Message, appConfigFile, (reader != null ? reader.LineNumber : 0), (reader != null ? reader.LinePosition : 0), e);
            }
            catch (Exception e) when(ExceptionHandling.IsIoRelatedException(e))
            {
                throw new AppConfigException(e.Message, appConfigFile, (reader != null ? reader.LineNumber : 0), (reader != null ? reader.LinePosition : 0), e);
            }
            finally
            {
                reader?.Close();
            }
        }
Exemplo n.º 19
0
 public string RegisterAgent(AgentDetail agentDetail)
 {
     try
     {
         string Email     = agentDetail.EmailID;
         string Password  = agentDetail.Password;
         string HotelType = agentDetail.HotelType;
         string FullName  = agentDetail.FullName;
         Agent  agent     = new Agent();
         string Guid      = agent.CreateAgent(Email, Password, HotelType, FullName);
         string body      = "Hello " + FullName + ",";
         body += "<br /><br />Please click the following link to activate your account";
         body += "<br /><a href = '" + string.Format("{0}://{1}/Agent/AgentComfirmation/{2}", Request.Url.Scheme, Request.Url.Authority, Guid) + "'>Click here to activate your account.</a>";
         body += "<br /><br />Thanks";
         Common.SendEmail(body, "clickhere", Email);
         return("1");
     }
     catch (Exception ex)
     {
         ExceptionHandling.WriteException(ex);
         return("-1");
     }
 }
Exemplo n.º 20
0
        /// <summary>
        /// Creating a ToolsetConfigurationReader, and also reading toolsets from the
        /// configuration file, are a little expensive. To try to avoid this cost if it's
        /// not necessary, we'll check if the file exists first. If it exists, we'll scan for
        /// the string "toolsVersion" to see if it might actually have any tools versions
        /// defined in it.
        /// </summary>
        /// <returns>True if there may be toolset definitions, otherwise false</returns>
        private static bool ConfigurationFileMayHaveToolsets()
        {
            bool result;

            try
            {
                result = (File.Exists(FileUtilities.CurrentExecutableConfigurationFilePath) &&
                          File.ReadAllText(FileUtilities.CurrentExecutableConfigurationFilePath).Contains("toolsVersion"));
            }
            catch (Exception e) // Catching Exception, but rethrowing unless it's an IO related exception.
            {
                if (ExceptionHandling.NotExpectedException(e))
                {
                    throw;
                }

                // There was some problem reading the config file: let the configuration reader
                // encounter it
                result = true;
            }

            return(result);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Attempts to convert the raw value provided in the metadata to the type with the specified name.
        /// Returns true if conversion is successful. An error is logged and false is returned if the conversion fails.
        /// </summary>
        private bool TryConvertParameterValue(string typeName, string rawValue, out CodeExpression value)
        {
            var parameterType = Type.GetType(typeName, throwOnError: false);

            if (parameterType is null)
            {
                Log.LogErrorWithCodeFromResources("WriteCodeFragment.ParameterTypeNotFound", typeName);
                value = null;
                return(false);
            }

            try
            {
                value = ConvertToCodeExpression(rawValue, parameterType);
                return(true);
            }
            catch (Exception ex) when(!ExceptionHandling.IsCriticalException(ex))
            {
                Log.LogErrorWithCodeFromResources("WriteCodeFragment.CouldNotConvertValue", rawValue, typeName, ex.Message);
                value = null;
                return(false);
            }
        }
Exemplo n.º 22
0
 /// <summary>
 /// Disconnects from sever
 /// </summary>
 public void Disconnect()
 {
     if (this.DebugTrace)
     {
         Trace.WriteLine("[SftpConnectionPool] Disconnecting from " + _host);
     }
     try
     {
         if (this._sftp.Connected)
         {
             this._sftp.Close();
             this._sftp = new SshTransfer(this._host, this._user, this._password);
         }
     }
     catch (Exception ex)
     {
         throw ExceptionHandling.HandleComponentException(System.Reflection.MethodBase.GetCurrentMethod(), ex);
     }
     finally
     {
         RaiseOnDisconnect();
     }
 }
 /// <summary>
 /// ühgt der Infotext Liste einen weiteren Eintrag hinzu
 /// </summary>
 public void AddInfoTextLine(object sender, string line)
 {
     try
     {
         if (this.DispatcherObject.Thread != System.Threading.Thread.CurrentThread)
         {
             this.DispatcherObject.Invoke(new Action(() => this.AddInfoTextLine(sender, line)));
         }
         else
         {
             lock (this.lockThis)
             {
                 System.Windows.Controls.TextBlock block = new System.Windows.Controls.TextBlock();
                 block.Text = line;
                 this.InfoTextList.Add(block);
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ExceptionHandling.GetExceptionText(new System.Exception(string.Format("Exception In: {0}", CallerName()), ex)));
     }
 }
Exemplo n.º 24
0
 /// <summary>
 /// Disconnects from sever
 /// </summary>
 public void Disconnect()
 {
     if (DebugTrace)
     {
         Trace.WriteLine("[SftpConnectionPool] Disconnecting from " + _host);
     }
     try
     {
         if (_sftp.IsConnected)
         {
             _sftp.Disconnect();
             _sftp = new SftpClient(_host, _user, _password);
         }
     }
     catch (Exception ex)
     {
         throw ExceptionHandling.HandleComponentException(System.Reflection.MethodBase.GetCurrentMethod(), ex);
     }
     finally
     {
         RaiseOnDisconnect();
     }
 }
        public void Main_InputInvalidAge_ExceptionCatching()
        {
            bool   flag = false;
            string view =
                @"<<Inigo
xyz
>>";

            try
            {
                IntelliTect.ConsoleView.Tester.Test(view,
                                                    () =>
                {
                    ExceptionHandling.Main();
                });
            }
            catch (FormatException)
            {
                flag = true;
            }

            Assert.IsTrue(flag);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Given a path, de-relativizes it using the location of the currently
        /// executing .exe as the base directory. For example, the path "..\foo"
        /// becomes "c:\windows\microsoft.net\framework\foo" if the current exe is
        /// "c:\windows\microsoft.net\framework\v3.5.1234\msbuild.exe".
        /// If the path is not relative, it is returned without modification.
        /// If the path is invalid, it is returned without modification.
        /// </summary>
        private string ExpandRelativePathsRelativeToExeLocation(string path)
        {
            try
            {
                // Trim, because we don't want to do anything with empty values
                // (those should cause an error)
                string trimmedValue = path.Trim();
                if (trimmedValue.Length > 0 && !Path.IsPathRooted(trimmedValue))
                {
                    path = Path.GetFullPath(
                        Path.Combine(BuildEnvironmentHelper.Instance.CurrentMSBuildToolsDirectory, trimmedValue));
                }
            }
            catch (Exception e) when(ExceptionHandling.IsIoRelatedException(e))
            {
                // This means that the path looked relative, but was an invalid path. In this case, we'll
                // just not expand it, and carry on - to be consistent with what happens when there's a
                // non-relative bin path with invalid characters. The problem will be detected later when
                // it's used in a project file.
            }

            return(path);
        }
Exemplo n.º 27
0
        public int AddUpdate()
        {
            int IntStatus = 0;

            try
            {
                SqlParameter[] objSqlParameter = new SqlParameter[6];
                objSqlParameter[0]           = new SqlParameter("@IntClientID", IntClientID);
                objSqlParameter[1]           = new SqlParameter("@StrDate", StrDate);
                objSqlParameter[2]           = new SqlParameter("@FltCRDR", FltCRDR);
                objSqlParameter[3]           = new SqlParameter("@IntStatus", IntStatus);
                objSqlParameter[3].Direction = ParameterDirection.Output;
                objSqlParameter[4]           = new SqlParameter("@IntMode", IntMode);
                objSqlParameter[5]           = new SqlParameter("@IntLoginID", DataBaseClass.Global.IntLoginID);
                SqlHelper.ExecuteNonQuery(objConnection.GetConnection(), CommandType.StoredProcedure, "SP_AddUpdateTrade", objSqlParameter);
                IntStatus = Convert.ToInt32(objSqlParameter[3].Value);
            }
            catch (Exception ex)
            {
                ExceptionHandling.CatchAndLogError(ex, "Error while trying to public int AddUpdate()", "TradeApiController.cs", DataBaseClass.Global.StrLoginName, "ClientModel.cs", "AddUpdate()");
            }
            return(IntStatus);
        }
Exemplo n.º 28
0
        public bool GetHasEarnedIncomeCredits(UserDTO userDTO)
        {
            bool hasEarnedIncomeCredits = false;

            try
            {
                BusinessObject.Tax1040 taxObject = Utilities.GetTaxObjectByUserIdAndUserDataId(userDTO.UserId, userDTO.UserDataId);
                if (taxObject != null && taxObject.Credits != null && taxObject.Credits.HasEarnedIncomeCredits.HasValue)
                {
                    hasEarnedIncomeCredits = taxObject.Credits.HasEarnedIncomeCredits.Value;
                }

                //Vincent, 2-sep-14, Persist Audit information
                string description = "Has EarnedIncomeCredits, ClassName: {0}, Method Name: {1}";
                Utilities.PersistAuditInfo(userDTO.UserId, userDTO.UserDataId, description, this.GetType().Name, Constants.Tab_EARNED_INCOME_CREDITS, Constants.TOPIC_EARNED_INCOME_CREDIT);
            }
            catch (Exception ex)
            {
                ExceptionHandling.LogException(userDTO.UserId, "Class:W2Repository,Method Name:GetHasEarnedIncomeCredits", ex);
            }

            return(hasEarnedIncomeCredits);
        }
Exemplo n.º 29
0
        internal void SubmitFiles(ControlledTermination control, IList <string> filesInProcess)
        {
            if (Files == null || Files.Count == 0)
            {
                return;
            }

            _filesInProcess = filesInProcess;

            try
            {
                using (SyncReceiveSubmitBatch batch = new SyncReceiveSubmitBatch(_transportProxy, control, Files.Count))
                {
                    foreach (BatchMessage file in Files)
                    {
                        batch.SubmitMessage(file.Message, file.UserData);
                    }
                    batch.Done();

                    TraceMessage("[SftpReceiverEndpoint] SubmitFiles (firstAttempt) about to wait on BatchComplete");
                    if (batch.Wait())
                    {
                        TraceMessage("[SftpReceiverEndpoint] SubmitFiles (firstAttempt) overall success");
                        OnBatchComplete(this, new StatusEventArgs {
                            OverallStatus = true
                        });
                    }
                }
                TraceMessage("[SftpReceiverEndpoint] Leaving SubmitFiles");
            }
            catch (Exception ex)
            {
                throw ExceptionHandling.HandleComponentException(
                          EventLogEventIDs.UnableToSubmitBizTalkMessage,
                          System.Reflection.MethodBase.GetCurrentMethod(), ex);
            }
        }
Exemplo n.º 30
0
 public int UploadHomeReport(string id, string hotelName, int hotelId)
 {
     try
     {
         string drive      = ConfigurationManager.AppSettings["PicDrive"];
         string folderName = ConfigurationManager.AppSettings["FolderName"];
         folderName = folderName + "/" + hotelName + "~" + hotelId;
         string           driveToSave = Path.Combine(drive, folderName);
         HotelInformation hInfo       = new HotelInformation();
         RoomImages       roomImg     = new RoomImages();
         int result = 0;
         if (CheckDirectory(driveToSave))
         {
             if (Request.Files.Count > 0)
             {
                 foreach (string file in Request.Files)
                 {
                     HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                     hpf.SaveAs(Path.Combine(driveToSave, hpf.FileName));
                     roomImg.PicName  = hpf.FileName;
                     roomImg.RoomID   = id;
                     roomImg.HotelID  = hotelId;
                     roomImg.IsEnable = 0;
                     roomImg.Flag     = "A";
                     result           = hInfo.SaveRoomImages(roomImg);
                 }
             }
         }
         return(result);
     }
     catch (Exception ex)
     {
         ExceptionHandling.WriteException(ex);
         Response.StatusCode = (int)HttpStatusCode.BadRequest;
         return(0);
     }
 }
Exemplo n.º 31
0
        public void LoadConfig()
        {
            string iniFilePath = IniConfigFileName;

            if (!File.Exists(iniFilePath))
                SaveConfig(); // Generate default config file

            IniFile iniFile = new IniFile();
            iniFile.TryLoad(iniFilePath);

            if (iniFile.ContainsKey("sourcePath"))
                sourcePath = iniFile["sourcePath"];
            if (iniFile.ContainsKey("destinationPath"))
                destinationPath = iniFile["destinationPath"];
            if (iniFile.ContainsKey("recursive"))
                Recursive = iniFile["recursive"].ToBool();
            if (iniFile.ContainsKey("locale"))
                Locale = new CultureInfo(iniFile["locale"]);
            if (iniFile.ContainsKey("patternImage"))
                DestinationPatternImage = iniFile["patternImage"];
            if (iniFile.ContainsKey("patternAudio"))
                DestinationPatternAudio = iniFile["patternAudio"];
            if (iniFile.ContainsKey("patternVideo"))
                DestinationPatternVideo = iniFile["patternVideo"];
            if (iniFile.ContainsKey("precondition"))
                CopyPrecondition = iniFile["precondition"].ToEnum<CopyPrecondition>();
            if (iniFile.ContainsKey("comparator"))
                FileComparator = iniFile["comparator"].ToEnum<FileComparator>();
            if (iniFile.ContainsKey("copyMode"))
                CopyMode = iniFile["copyMode"].ToEnum<CopyMode>();
            if (iniFile.ContainsKey("exceptionHandling"))
                ExceptionHandling = iniFile["exceptionHandling"].ToEnum<ExceptionHandling>();
            if (iniFile.ContainsKey("verifyFiles"))
                VerifyFiles = iniFile["verifyFiles"].ToBool();
        }
Exemplo n.º 32
0
 public static bool Lookup(string baseFileName, int level, int version, RazorCache cache, Key key, out Value value, ExceptionHandling exceptionHandling, Action<string> logger)
 {
     SortedBlockTable sbt = new SortedBlockTable (cache, baseFileName, level, version);
     try {
         int dataBlockNum = FindBlockForKey (baseFileName, level, version, cache, key);
         if (dataBlockNum >= 0 && dataBlockNum < sbt._dataBlocks) {
             byte[] block = sbt.ReadBlock (LocalThreadAllocatedBlock (), dataBlockNum);
             return SearchBlockForKey (block, key, out value);
         }
     } finally {
         sbt.Close ();
     }
     value = Value.Empty;
     return false;
 }
Exemplo n.º 33
0
        public static IEnumerable<PageRecord> MergeTables(RazorCache cache, Manifest mf, int destinationLevel, IEnumerable<PageRef> tableSpecs, ExceptionHandling exceptionHandling, Action<string> logger)
        {
            var orderedTableSpecs = tableSpecs.OrderByPagePriority ();
            var outputTables = new List<PageRecord> ();
            SortedBlockTableWriter writer = null;

            Key firstKey = new Key ();
            Key lastKey = new Key ();
            Key maxKey = new Key (); // Maximum key we can span with this table to avoid covering more than 10 pages in the destination

            Action<KeyValuePair<Key, Value>> OpenPage = (pair) => {
                writer = new SortedBlockTableWriter (mf.BaseFileName, destinationLevel, mf.NextVersion (destinationLevel));
                firstKey = pair.Key;
                using (var m = mf.GetLatestManifest())
                    maxKey = m.FindSpanningLimit (destinationLevel + 1, firstKey);
            };

            Action ClosePage = () => {
                writer.Close ();
                outputTables.Add (new PageRecord (destinationLevel, writer.Version, firstKey, lastKey));
                writer = null;
            };

            foreach (var pair in EnumerateMergedTablesPreCached(cache, mf.BaseFileName, orderedTableSpecs, exceptionHandling, logger)) {
                if (writer == null)
                    OpenPage (pair);
                if (writer.WrittenSize >= Config.MaxSortedBlockTableSize || (!maxKey.IsEmpty && pair.Key.CompareTo (maxKey) >= 0))
                    ClosePage ();
                writer.WritePair (pair.Key, pair.Value);
                lastKey = pair.Key;
            }
            if (writer != null)
                ClosePage ();

            return outputTables;
        }
Exemplo n.º 34
0
 public static IEnumerable<KeyValuePair<Key, Value>> EnumerateMergedTablesPreCached(RazorCache cache, string baseFileName, IEnumerable<PageRef> tableSpecs, ExceptionHandling exceptionHandling, Action<string> logger)
 {
     var tables = tableSpecs.Select (pageRef => new SortedBlockTable (cache, baseFileName, pageRef.Level, pageRef.Version)).ToList ();
     try {
         foreach (var pair in MergeEnumerator.Merge(tables.Select(t => t.Enumerate().ToList().AsEnumerable()), t => t.Key))
             yield return pair;
     } finally {
         tables.ForEach (t => t.Close ());
     }
 }
Exemplo n.º 35
0
 public DaemonErrorHandler(IDaemon daemon, IDaemonLogger logger, ExceptionHandling handling)
 {
     _daemon = daemon;
     _logger = logger;
     _handling = handling;
 }
 /// <summary>
 /// Submits the fault message to the configured ESB service
 /// </summary>
 /// <param name="faultMessage">Fault message to submit</param>
 private static void SubmitFault(FaultMessage faultMessage)
 {
     using (ExceptionHandling proxy = new ExceptionHandling())
     {
         proxy.Url = ServiceProviderErrorHandlerConfiguration.Current.ExceptionHandlingUrl;
         proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
         proxy.SubmitFault(faultMessage);
     }
 }