Esempio n. 1
0
        public static void Configure()
        {
            ILog logger = new ConsoleLogger();
            ILog errorLogger = new ErrorLogger();

            LogManager.GetLog = type => type == typeof(ActionMessage) ? logger : errorLogger;
        }
Esempio n. 2
0
        public WebProjectManager(IPackageRepository source, string siteRoot, IWebMatrixHost host)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            if (String.IsNullOrEmpty(siteRoot))
            {
                throw new ArgumentException("siteRoot");
            }

            _siteRoot = siteRoot;
            string webRepositoryDirectory = GetWebRepositoryDirectory(siteRoot);

            Logger = new ErrorLogger(host);

            var project = new WebProjectSystem(siteRoot);

            project.Logger = Logger;

            _projectManager = new ProjectManager(sourceRepository: source,
                                                   pathResolver: new DefaultPackagePathResolver(webRepositoryDirectory),
                                                   localRepository: PackageRepositoryFactory.Default.CreateRepository(webRepositoryDirectory),
                                                   project: project);
        }
Esempio n. 3
0
    //checks for boxes with only 1 possible input
    public ErrorLogger checkBSP(ref bool madeChange)
    {
        ErrorLogger RV = new ErrorLogger();

        bool noChange = false;
        List<short> curList = new List<short>();
        while (!noChange)
        {
            noChange = true;
            for (int i = 0; i < 81; i++)
            {
                if (numBoxes[i].getValue() == 0)
                {
                    curList.Clear();
                    curList.AddRange(numBoxes[i].getPV());
                    if (curList.Count == 1)
                    {
                        RV = RV + insertNum(numBoxes[i], curList[0]);
                        Console.WriteLine("Single Box Insert: " + i.ToString() + " inserting value: " + curList[0].ToString());
                        noChange = false;
                        madeChange = true;
                    }
                    else if (curList.Count == 0)
                    {
                        RV = RV + new ErrorLogger(-1, "Box " + i + " has no possible values");
                    }
                }
                if (RV.hasError()) break;
            }
            if (RV.hasError()) break;
        }
        return RV;
    }
Esempio n. 4
0
		/// <summary>
		/// Constructor.  Reads the file and stores any data needed for corrections later on.
		/// </summary>
		public FwDataFixer(string filename, IProgress progress, ErrorLogger logger, ErrorCounter counter)
		{
			m_filename = filename;
			m_progress = progress;
			errorLogger = logger;
			errorCounter = counter;

			m_progress.Minimum = 0;
			m_progress.Maximum = 1000;
			m_progress.Position = 0;
			m_progress.Message = String.Format(Strings.ksReadingTheInputFile, m_filename);
			m_crt = 0;
			// The following fixers will be run on each rt element during FixErrorsAndSave()
			// Note: every change to the file MUST log an error. This is used in FixFwData to set a return code indicating whether anything changed.
			// This in turn is used in Send/Receive to determine whether we need to re-split the file before committing.
			// N.B.: Order is important here!!!!!!!
			m_rtLevelFixers.Add(new DuplicateStyleFixer());
			m_rtLevelFixers.Add(new OriginalFixer());
			m_rtLevelFixers.Add(new CustomPropertyFixer());
			m_rtLevelFixers.Add(new BasicCustomPropertyFixer());
			var senseFixer = new GrammaticalSenseFixer();
			m_rtLevelFixers.Add(senseFixer);
			m_rtLevelFixers.Add(new MorphBundleFixer(senseFixer)); // after we've possibly removed MSAs in GrammaticalSenseFixer
			m_rtLevelFixers.Add(new SequenceFixer());
			m_rtLevelFixers.Add(new HomographFixer());
			m_rtLevelFixers.Add(new DuplicateWordformFixer());
			m_rtLevelFixers.Add(new CustomListNameFixer());
			InitializeFixers(m_filename);
		}
 public static string deleteItem(string itemId)
 {
     ErrorLogger log = new ErrorLogger();
     log.ErrorLog(HttpContext.Current.Server.MapPath("Logs/Delete"), "Item with ID " + itemId + " deleted from database.");
     bool success = CatalogAccess.DeleteItem(itemId);
     return success ? "Item deleted successfully." : "There was an error processing your request.";
 }
Esempio n. 6
0
        /// <summary>
        /// csi.exe and vbi.exe entry point.
        /// </summary>
        private int RunInteractiveCore(ErrorLogger errorLogger)
        {
            Debug.Assert(_compiler.Arguments.IsScriptRunner);

            var sourceFiles = _compiler.Arguments.SourceFiles;

            if (sourceFiles.IsEmpty && _compiler.Arguments.DisplayLogo)
            {
                _compiler.PrintLogo(_console.Out);

                if (!_compiler.Arguments.DisplayHelp)
                {
                    _console.Out.WriteLine(ScriptingResources.HelpPrompt);
                }
            }

            if (_compiler.Arguments.DisplayHelp)
            {
                _compiler.PrintHelp(_console.Out);
                return 0;
            }

            SourceText code = null;

            var diagnosticsInfos = new List<DiagnosticInfo>();

            if (!sourceFiles.IsEmpty)
            {
                if (sourceFiles.Length > 1 || !sourceFiles[0].IsScript)
                {
                    diagnosticsInfos.Add(new DiagnosticInfo(_compiler.MessageProvider, _compiler.MessageProvider.ERR_ExpectedSingleScript));
                }
                else
                {
                    code = _compiler.ReadFileContent(sourceFiles[0], diagnosticsInfos);
                }
            }

            var scriptPathOpt = sourceFiles.IsEmpty ? null : sourceFiles[0].Path;
            var scriptOptions = GetScriptOptions(_compiler.Arguments, scriptPathOpt, _compiler.MessageProvider, diagnosticsInfos);

            var errors = _compiler.Arguments.Errors.Concat(diagnosticsInfos.Select(Diagnostic.Create));
            if (_compiler.ReportErrors(errors, _console.Out, errorLogger))
            {
                return CommonCompiler.Failed;
            }

            var cancellationToken = new CancellationToken();

            if (_compiler.Arguments.InteractiveMode)
            {
                RunInteractiveLoop(scriptOptions, code?.ToString(), cancellationToken);
                return CommonCompiler.Succeeded;
            }
            else
            {
                return RunScript(scriptOptions, code.ToString(), errorLogger, cancellationToken);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// csi.exe and vbi.exe entry point.
        /// </summary>
        private static int RunInteractiveCore(CommonCompiler compiler, TextWriter consoleOutput, ErrorLogger errorLogger)
        {
            Debug.Assert(compiler.Arguments.IsInteractive);

            var hasScriptFiles = compiler.Arguments.SourceFiles.Any(file => file.IsScript);

            if (compiler.Arguments.DisplayLogo && !hasScriptFiles)
            {
                compiler.PrintLogo(consoleOutput);
            }

            if (compiler.Arguments.DisplayHelp)
            {
                compiler.PrintHelp(consoleOutput);
                return 0;
            }

            // TODO (tomat):
            // When we have command line REPL enabled we'll launch it if there are no input files. 
            IEnumerable<Diagnostic> errors = compiler.Arguments.Errors;
            if (!hasScriptFiles)
            {
                errors = errors.Concat(new[] { Diagnostic.Create(compiler.MessageProvider, compiler.MessageProvider.ERR_NoScriptsSpecified) });
            }

            if (compiler.ReportErrors(errors, consoleOutput, errorLogger))
            {
                return CommonCompiler.Failed;
            }

            // arguments are always available when executing script code:
            Debug.Assert(compiler.Arguments.ScriptArguments != null);

            var compilation = compiler.CreateCompilation(consoleOutput, touchedFilesLogger: null, errorLogger: errorLogger);
            if (compilation == null)
            {
                return CommonCompiler.Failed;
            }

            byte[] compiledAssembly;
            using (MemoryStream output = new MemoryStream())
            {
                EmitResult emitResult = compilation.Emit(output);
                if (compiler.ReportErrors(emitResult.Diagnostics, consoleOutput, errorLogger))
                {
                    return CommonCompiler.Failed;
                }

                compiledAssembly = output.ToArray();
            }

            var assembly = Assembly.Load(compiledAssembly);

            return Execute(assembly, compiler.Arguments.ScriptArguments.ToArray());
        }
Esempio n. 8
0
        /// <summary>
        /// csi.exe and vbi.exe entry point.
        /// </summary>
        private int RunInteractiveCore(ErrorLogger errorLogger)
        {
            Debug.Assert(_compiler.Arguments.IsInteractive);

            var sourceFiles = _compiler.Arguments.SourceFiles;

            if (sourceFiles.IsEmpty && _compiler.Arguments.DisplayLogo)
            {
                _compiler.PrintLogo(_console.Out);
            }

            if (_compiler.Arguments.DisplayHelp)
            {
                _compiler.PrintHelp(_console.Out);
                return 0;
            }

            SourceText code = null;
            IEnumerable<Diagnostic> errors = _compiler.Arguments.Errors;
            if (!sourceFiles.IsEmpty)
            {
                if (sourceFiles.Length > 1 || !sourceFiles[0].IsScript)
                {
                    errors = errors.Concat(new[] { Diagnostic.Create(_compiler.MessageProvider, _compiler.MessageProvider.ERR_ExpectedSingleScript) });
                }
                else
                {
                    var diagnostics = new List<DiagnosticInfo>();
                    code = _compiler.ReadFileContent(sourceFiles[0], diagnostics);
                    errors = errors.Concat(diagnostics.Select(Diagnostic.Create));
                }
            }

            if (_compiler.ReportErrors(errors, _console.Out, errorLogger))
            {
                return CommonCompiler.Failed;
            }

            var cancellationToken = new CancellationToken();
            var hostObject = new CommandLineHostObject(_console.Out, _objectFormatter, cancellationToken);
            hostObject.Args = _compiler.Arguments.ScriptArguments.ToArray();

            var scriptOptions = GetScriptOptions(_compiler.Arguments);

            if (sourceFiles.IsEmpty)
            {
                RunInteractiveLoop(scriptOptions, hostObject);
            }
            else
            {
                RunScript(scriptOptions, code.ToString(), sourceFiles[0].Path, hostObject, errorLogger);
            }

            return hostObject.ExitCode;
        }
Esempio n. 9
0
        public CompileResult Compile(string source, CompileContext context)
        {
            var sourceFile = context.RootDirectory.GetFile(context.SourceFilePath);
            importedFilePaths = new HashedSet<string>();
            var parser = new Parser
            {
                Importer = new Importer(new CassetteLessFileReader(sourceFile.Directory, importedFilePaths))
            };
            var errorLogger = new ErrorLogger();
            var engine = new LessEngine(
                                    parser,
                                    errorLogger,
                                    configuration.MinifyOutput,
                                    configuration.Debug,
                                    configuration.DisableVariableRedefines,
                                    configuration.DisableColorCompression,
                                    configuration.KeepFirstSpecialComment,
                                    configuration.Plugins);

            string css;
            try
            {
                css = engine.TransformToCss(source, sourceFile.FullPath);
            }
            catch (Exception ex)
            {
                throw new LessCompileException(
                    string.Format("Error compiling {0}{1}{2}", context.SourceFilePath, Environment.NewLine, ex.Message),
                    ex
                );
            }

            if (errorLogger.HasErrors)
            {
                var exceptionMessage = string.Format(
                    "Error compiling {0}{1}{2}",
                    context.SourceFilePath,
                    Environment.NewLine,
                    errorLogger.ErrorMessage
                );
                throw new LessCompileException(exceptionMessage);
            }
            else
            {
                return new CompileResult(css, importedFilePaths);
            }
        }
Esempio n. 10
0
        protected static Sector GetPostedSector(HttpRequest request, ErrorLogger errors)
        {
            Sector sector = null;

            if (request.Files["file"] != null && request.Files["file"].ContentLength > 0)
            {
                HttpPostedFile hpf = request.Files["file"];
                sector = new Sector(hpf.InputStream, hpf.ContentType, errors);
            }
            else if (!String.IsNullOrEmpty(request.Form["data"]))
            {
                string data = request.Form["data"];
                sector = new Sector(data.ToStream(), MediaTypeNames.Text.Plain, errors);
            }
            else if (new ContentType(request.ContentType).MediaType == MediaTypeNames.Text.Plain)
            {
                sector = new Sector(request.InputStream, MediaTypeNames.Text.Plain, errors);
            }
            else
            {
                return null;
            }

            if (request.Files["metadata"] != null && request.Files["metadata"].ContentLength > 0)
            {
                HttpPostedFile hpf = request.Files["metadata"];

                string type = SectorMetadataFileParser.SniffType(hpf.InputStream);
                Sector meta = SectorMetadataFileParser.ForType(type).Parse(hpf.InputStream);
                sector.Merge(meta);
            }
            else if (!String.IsNullOrEmpty(request.Form["metadata"]))
            {
                string metadata = request.Form["metadata"];
                string type = SectorMetadataFileParser.SniffType(metadata.ToStream());
                var parser = SectorMetadataFileParser.ForType(type);
                using (var reader = new StringReader(metadata))
                {
                    Sector meta = parser.Parse(reader);
                    sector.Merge(meta);
                }
            }

            return sector;
        }
Esempio n. 11
0
        public string Compile(string source, IFile sourceFile)
        {
            var parser = new Parser
            {
                Importer = new Importer(new CassetteLessFileReader(sourceFile.Directory))
            };
            var errorLogger = new ErrorLogger();
            var engine = new LessEngine(parser, errorLogger, false);

            var css = engine.TransformToCss(source, sourceFile.FullPath);

            if (errorLogger.HasErrors)
            {
                throw new LessCompileException(errorLogger.ErrorMessage);
            }
            else
            {
                return css;
            }
        }
Esempio n. 12
0
        public override void Parse(TextReader reader, WorldCollection worlds, ErrorLogger errors)
        {
            int lineNumber = 0;
            for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
            {
                ++lineNumber;

                if (line.Length == 0)
                    continue;

                switch (line[0])
                {
                    case '#': break; // comment
                    case '$': break; // route
                    case '@': break; // subsector
                    default:
                        ParseWorld(worlds, line, lineNumber, errors ?? worlds.ErrorList);
                        break;
                }
            }
        }
    // Execute an update, delete, or insert command
    // and return the number of affect rows
    public static int ExecuteNonQuery(DbCommand command)
    {
        // the number of affected rows
        int affectedRows = -1;

        // Execute the command making sure the connection gets closed in the end
        try {
            command.Connection.Open();
            // Execute the command and get the number of affected rows
            affectedRows = command.ExecuteNonQuery();
        } catch (Exception ex) {
            // Log eventual errors and rethrow them
            ErrorLogger error = new ErrorLogger();
            error.ErrorLog(HttpContext.Current.Server.MapPath("Logs/ExecuteNonQueryErrorLog"), ex.Message);
            throw;
        } finally {
            // Close the connection
            command.Connection.Close();
        }
        return affectedRows;
    }
Esempio n. 14
0
        public override Compilation CreateCompilation(TextWriter consoleOutput, TouchedFileLogger touchedFilesLogger, ErrorLogger errorLogger)
        {
            var parseOptions = Arguments.ParseOptions;

            // We compute script parse options once so we don't have to do it repeatedly in
            // case there are many script files.
            var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script);

            bool hadErrors = false;

            var sourceFiles         = Arguments.SourceFiles;
            var trees               = new SyntaxTree[sourceFiles.Length];
            var normalizedFilePaths = new string[sourceFiles.Length];
            var diagnosticBag       = DiagnosticBag.GetInstance();

            if (Arguments.CompilationOptions.ConcurrentBuild)
            {
                Parallel.For(0, sourceFiles.Length, UICultureUtilities.WithCurrentUICulture <int>(i =>
                {
                    //NOTE: order of trees is important!!
                    trees[i] = ParseFile(parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], diagnosticBag, out normalizedFilePaths[i]);
                }));
            }
            else
            {
                for (int i = 0; i < sourceFiles.Length; i++)
                {
                    //NOTE: order of trees is important!!
                    trees[i] = ParseFile(parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], diagnosticBag, out normalizedFilePaths[i]);
                }
            }

            // If errors had been reported in ParseFile, while trying to read files, then we should simply exit.
            if (hadErrors)
            {
                Debug.Assert(diagnosticBag.HasAnyErrors());
                ReportErrors(diagnosticBag.ToReadOnlyAndFree(), consoleOutput, errorLogger);
                return(null);
            }
            else
            {
                Debug.Assert(diagnosticBag.IsEmptyWithoutResolution);
                diagnosticBag.Free();
            }

            var diagnostics = new List <DiagnosticInfo>();

            var uniqueFilePaths = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            for (int i = 0; i < sourceFiles.Length; i++)
            {
                var normalizedFilePath = normalizedFilePaths[i];
                Debug.Assert(normalizedFilePath != null);
                Debug.Assert(PathUtilities.IsAbsolute(normalizedFilePath));

                if (!uniqueFilePaths.Add(normalizedFilePath))
                {
                    // warning CS2002: Source file '{0}' specified multiple times
                    diagnostics.Add(new DiagnosticInfo(MessageProvider, (int)ErrorCode.WRN_FileAlreadyIncluded,
                                                       Arguments.PrintFullPaths ? normalizedFilePath : _diagnosticFormatter.RelativizeNormalizedPath(normalizedFilePath)));

                    trees[i] = null;
                }
            }

            if (Arguments.TouchedFilesPath != null)
            {
                foreach (var path in uniqueFilePaths)
                {
                    touchedFilesLogger.AddRead(path);
                }
            }

            var assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default;
            var appConfigPath            = this.Arguments.AppConfigPath;

            if (appConfigPath != null)
            {
                try
                {
                    using (var appConfigStream = new FileStream(appConfigPath, FileMode.Open, FileAccess.Read))
                    {
                        assemblyIdentityComparer = DesktopAssemblyIdentityComparer.LoadFromXml(appConfigStream);
                    }

                    if (touchedFilesLogger != null)
                    {
                        touchedFilesLogger.AddRead(appConfigPath);
                    }
                }
                catch (Exception ex)
                {
                    diagnostics.Add(new DiagnosticInfo(MessageProvider, (int)ErrorCode.ERR_CantReadConfigFile, appConfigPath, ex.Message));
                }
            }

            var xmlFileResolver    = new LoggingXmlFileResolver(Arguments.BaseDirectory, touchedFilesLogger);
            var sourceFileResolver = new LoggingSourceFileResolver(ImmutableArray <string> .Empty, Arguments.BaseDirectory, Arguments.PathMap, touchedFilesLogger);

            MetadataReferenceResolver referenceDirectiveResolver;
            var resolvedReferences = ResolveMetadataReferences(diagnostics, touchedFilesLogger, out referenceDirectiveResolver);

            if (ReportErrors(diagnostics, consoleOutput, errorLogger))
            {
                return(null);
            }

            var loggingFileSystem = new LoggingStrongNameFileSystem(touchedFilesLogger, _tempDirectory);

            return(CSharpCompilation.Create(
                       Arguments.CompilationName,
                       trees.WhereNotNull(),
                       resolvedReferences,
                       Arguments.CompilationOptions.
                       WithMetadataReferenceResolver(referenceDirectiveResolver).
                       WithAssemblyIdentityComparer(assemblyIdentityComparer).
                       WithXmlReferenceResolver(xmlFileResolver).
                       WithStrongNameProvider(Arguments.GetStrongNameProvider(loggingFileSystem)).
                       WithSourceReferenceResolver(sourceFileResolver)));
        }
Esempio n. 15
0
        public void Log_InvalidError_ThrowArgumentNullException(string error)
        {
            var logger = new ErrorLogger();

            Assert.That(() => logger.Log(error), Throws.ArgumentNullException);
        }
Esempio n. 16
0
    public static void ProcessRequest(HttpContext context)
    {
        try
        {
            string LogMessage = context.Request.Params.ToRawString();
            ErrorLogger.Log(LogMessage, LogType.OfferWalls);

            //Force refresh
            AppSettings.Offerwalls.Reload();

            string payload   = context.Request["payload"];
            string signature = context.Request["signature"];

            string myhash = SHA1HashStringForUTF8String(payload + AppSettings.Offerwalls.CrowdFlowerKey);

            if (myhash == signature)
            {
                //All ok
                //Lets check if we have First or second request
                if (payload.Contains("conversion_id"))
                {
                    //2
                    var data = JsonConvert.DeserializeObject <RecData2>(payload);

                    string title = data.job_title;

                    if (title.Length > 80)
                    {
                        title = title.Substring(0, 79);
                    }

                    string conversionID = data.conversion_id.Substring(1);

                    CrowdflowerTask task = new CrowdflowerTask(Convert.ToInt32(conversionID));
                    task.Title = title;

                    decimal points = data.adjusted_amount;

                    //Not to duplicate the entries
                    if (task.Points == -1)
                    {
                        try
                        {
                            CreditUser(task.Username, points, "CrowdFlower", data.job_title);
                        }
                        catch (Exception ex) { ErrorLogger.Log(ex); }
                    }

                    task.Points = Convert.ToInt32(points);
                    task.Save();

                    context.Response.Write("OK");
                }
                else
                {
                    //1
                    var data = JsonConvert.DeserializeObject <RecData1>(payload);

                    CrowdflowerTask task = new CrowdflowerTask();
                    task.Date     = DateTime.Now;
                    task.Points   = -1;
                    task.Username = data.uid;
                    task.Save();

                    context.Response.Write("0" + task.Id.ToString());
                }
            }
            else
            {
                context.Response.StatusCode = 403;
                context.Response.Status     = "403 Access Denied";
            }
        }
        catch (Exception ex) { Prem.PTC.ErrorLogger.Log(ex); }
    }
Esempio n. 17
0
        public async Task ProcessEventsAsync(PartitionContext context, IEnumerable <EventData> messages)
        {
            if (!IsInitialized)
            {
                Logger.AddRow("Processor not initialized. Throwing exception.");
                throw new Exception("Processor not initialized. Run Init() before starting");
            }

            AddNewInfo(_id, "Processing");

            try
            {
                var parsedData = messages.Select(eventData => Encoding.UTF8.GetString(eventData.GetBytes())).Select(JsonConvert.DeserializeObject <SystemEvent>).ToList();
                var workInfo   = await EventStore.StoreEventsAsync(parsedData);

                if (string.IsNullOrEmpty(workInfo))
                {
                    RemoveInfo(_id);
                }
                else
                {
                    AddNewInfo(_id, workInfo);
                }
                if (Engine.EngineIsRunning)
                {
                    await Engine.AddToMainQueue(parsedData);

                    AddNewInfo(_id, parsedData.Count + " events added to engine");
                }
                else
                {
                    AddNewInfo(_id, "Engine is not running. Cannot add events. Aborting.");
                    return;
                }
            }
            catch (Exception ex)
            {
                AddNewInfo(_id, "!ERROR! " + ex.Message);
                ErrorLogger.AddRow("!ERROR! In event processor");
                ErrorLogger.AddRow(ex.ToString());
            }
            finally
            {
                AddNewInfo(_id, "Setting Checkpoint");
                try
                {
                    await context.CheckpointAsync();

                    AddNewInfo(_id, "Checkpoint set");
                }
                catch (Exception ex) when(ex.Message.Contains("lease for the blob has expired"))
                {
                    Logger.AddRow("Lease for the blob has expired");
                    RemoveInfo(_id);
                }
                catch (Exception ex) when(ex.Message.Contains("System.TimeoutException"))
                {
                    Logger.AddRow("System.TimeoutException");
                    RemoveInfo(_id);
                }
                catch (LeaseLostException)
                {
                    Logger.AddRow("LeaseLostException");
                    RemoveInfo(_id);
                }
            }
        }
Esempio n. 18
0
        public override Compilation CreateCompilation(TextWriter consoleOutput, TouchedFileLogger touchedFilesLogger, ErrorLogger errorLogger)
        {
            var parseOptions = Arguments.ParseOptions;
            var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script);

            bool hadErrors = false;

            var sourceFiles = Arguments.SourceFiles;
            var trees = new SyntaxTree[sourceFiles.Length];
            var normalizedFilePaths = new String[sourceFiles.Length];

            if (Arguments.CompilationOptions.ConcurrentBuild)
            {
                Parallel.For(0, sourceFiles.Length, UICultureUtilities.WithCurrentUICulture<int>(i =>
                {
                    //NOTE: order of trees is important!!
                    trees[i] = ParseFile(consoleOutput, parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], errorLogger, out normalizedFilePaths[i]);
                }));
            }
            else
            {
                for (int i = 0; i < sourceFiles.Length; i++)
                {
                    //NOTE: order of trees is important!!
                    trees[i] = ParseFile(consoleOutput, parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], errorLogger, out normalizedFilePaths[i]);
                }
            }

            // If errors had been reported in ParseFile, while trying to read files, then we should simply exit.
            if (hadErrors)
            {
                return null;
            }

            var diagnostics = new List<DiagnosticInfo>();

            var uniqueFilePaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            for (int i = 0; i < sourceFiles.Length; i++)
            {
                var normalizedFilePath = normalizedFilePaths[i];
                Debug.Assert(normalizedFilePath != null);
                Debug.Assert(PathUtilities.IsAbsolute(normalizedFilePath));

                if (!uniqueFilePaths.Add(normalizedFilePath))
                {
                    // warning CS2002: Source file '{0}' specified multiple times
                    diagnostics.Add(new DiagnosticInfo(MessageProvider, (int)ErrorCode.WRN_FileAlreadyIncluded,
                        Arguments.PrintFullPaths ? normalizedFilePath : _diagnosticFormatter.RelativizeNormalizedPath(normalizedFilePath)));

                    trees[i] = null;
                }
            }

            if (Arguments.TouchedFilesPath != null)
            {
                foreach (var path in uniqueFilePaths)
                {
                    touchedFilesLogger.AddRead(path);
                }
            }

            var assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default;
            var appConfigPath = this.Arguments.AppConfigPath;
            if (appConfigPath != null)
            {
                try
                {
                    using (var appConfigStream = PortableShim.FileStream.Create(appConfigPath, PortableShim.FileMode.Open, PortableShim.FileAccess.Read))
                    {
                        assemblyIdentityComparer = DesktopAssemblyIdentityComparer.LoadFromXml(appConfigStream);
                    }

                    if (touchedFilesLogger != null)
                    {
                        touchedFilesLogger.AddRead(appConfigPath);
                    }
                }
                catch (Exception ex)
                {
                    diagnostics.Add(new DiagnosticInfo(MessageProvider, (int)ErrorCode.ERR_CantReadConfigFile, appConfigPath, ex.Message));
                }
            }

            var xmlFileResolver = new LoggingXmlFileResolver(Arguments.BaseDirectory, touchedFilesLogger);
            var sourceFileResolver = new LoggingSourceFileResolver(ImmutableArray<string>.Empty, Arguments.BaseDirectory, touchedFilesLogger);

            MetadataReferenceResolver referenceDirectiveResolver;
            var resolvedReferences = ResolveMetadataReferences(diagnostics, touchedFilesLogger, out referenceDirectiveResolver);
            if (ReportErrors(diagnostics, consoleOutput, errorLogger))
            {
                return null;
            }

            var strongNameProvider = new LoggingStrongNameProvider(Arguments.KeyFileSearchPaths, touchedFilesLogger);

            var compilation = CSharpCompilation.Create(
                Arguments.CompilationName,
                trees.WhereNotNull(),
                resolvedReferences,
                Arguments.CompilationOptions.
                    WithMetadataReferenceResolver(referenceDirectiveResolver).
                    WithAssemblyIdentityComparer(assemblyIdentityComparer).
                    WithStrongNameProvider(strongNameProvider).
                    WithXmlReferenceResolver(xmlFileResolver).
                    WithSourceReferenceResolver(sourceFileResolver));

            return compilation;
        }
Esempio n. 19
0
        private int RunScript(ScriptOptions options, string code, ErrorLogger errorLogger, CancellationToken cancellationToken)
        {
            var globals = new CommandLineScriptGlobals(_console.Out, _objectFormatter);
            globals.Args.AddRange(_compiler.Arguments.ScriptArguments);

            var script = Script.CreateInitialScript<int>(_scriptCompiler, code, options, globals.GetType(), assemblyLoaderOpt: null);
            try
            {
                return script.RunAsync(globals, cancellationToken).Result.ReturnValue;
            }
            catch (CompilationErrorException e)
            {
                _compiler.ReportErrors(e.Diagnostics, _console.Out, errorLogger);
                return CommonCompiler.Failed;
            }
        }
Esempio n. 20
0
 public void Post([FromBody] ErrorRecord error)
 {
     using (ErrorLogger logger = new ErrorLogger())
         logger.LogError(error);
 }
Esempio n. 21
0
        public override void Process(System.Web.HttpContext context)
        {
            // NOTE: This (re)initializes a static data structure used for
            // resolving names into sector locations, so needs to be run
            // before any other objects (e.g. Worlds) are loaded.
            ResourceManager resourceManager = new ResourceManager(context.Server, context.Cache);

            Selector selector;
            RectangleF tileRect = new RectangleF();
            MapOptions options = MapOptions.SectorGrid | MapOptions.SubsectorGrid | MapOptions.BordersMajor | MapOptions.BordersMinor | MapOptions.NamesMajor | MapOptions.NamesMinor | MapOptions.WorldsCapitals | MapOptions.WorldsHomeworlds;
            Stylesheet.Style style = Stylesheet.Style.Poster;
            ParseOptions(context, ref options, ref style);
            string title;
            bool clipOutsectorBorders;

            if (HasOption(context, "x1") && HasOption(context, "x2") &&
                HasOption(context, "y1") && HasOption(context, "y2"))
            {
                // Arbitrary rectangle

                int x1 = GetIntOption(context, "x1", 0);
                int x2 = GetIntOption(context, "x2", 0);
                int y1 = GetIntOption(context, "y1", 0);
                int y2 = GetIntOption(context, "y2", 0);

                tileRect.X = Math.Min(x1, x2);
                tileRect.Y = Math.Min(y1, y2);
                tileRect.Width = Math.Max(x1, x2) - tileRect.X;
                tileRect.Height = Math.Max(y1, y2) - tileRect.Y;

                SectorMap map = SectorMap.FromName(SectorMap.DefaultSetting, resourceManager);
                selector = new RectSelector(map, resourceManager, tileRect);
                selector.Slop = false;

                tileRect.Offset(-1, -1);
                tileRect.Width += 1;
                tileRect.Height += 1;

                title = String.Format("Poster ({0},{1}) - ({2},{3})", x1, y1, x2, y2);
                clipOutsectorBorders = true;
            }
            else if (HasOption(context, "domain"))
            {
                string domain = GetStringOption(context, "domain");
                int x, y, w = 2, h = 2;
                switch (domain.ToLowerInvariant()) {
                    case "deneb": x = -4; y = -1; title = "Domain of Deneb"; break;
                    case "vland": x = -2; y = -1; title = "Domain of Vland";  break;
                    case "ilelish": x = -2; y = 1; title = "Domain of Ilelish";  break;
                    case "antares": x = 0; y = -2; title = "Domain of Antares";  break;
                    case "sylea": x = 0; y = 0; title = "Domain of Sylea";  break;
                    case "sol": x = 0; y = 2; title = "Domain of Sol";  break;
                    case "gateway": x = 2; y = 0; title = "Domain of Gateway"; break;

                        // And these aren't domains, but...
                    case "foreven": x = -6; y = -1; title = "Land Grab / Foreven"; break;
                    case "imperium": x = -4; y = -1; w = 7; h = 5; title = "Third Imperium"; break;
                    case "solomani": x = -2; y = 2; w = 5; h = 3; title = "Solomani Confederacy"; break;
                    case "zhodani": x = -8; y = -3; w = 5; h = 3; title = "Zhodani Consulate"; break;
                    case "hive":
                    case "hiver": x = 2; y = 1; w = 6; h = 4; title = "Hiver Federation"; break;
                    case "aslan": x = -8; y = 1; w = 7; h = 4; title = "Aslan Hierate"; break;
                    case "vargr": x = -4; y = -4; w = 8; h = 3; title = "Vargr Extents"; break;
                    // TODO: K'kree
                    // TODO: Zhodani provinces

                    case "jg": x = 160; y = 0; w = 2; h = 2; title = "Judges Guild"; break;

                    default:
                        SendError(context.Response, 404, "Not Found", String.Format("Unknown domain: {0}", domain));
                        return;
                }

                int x1 = x * Astrometrics.SectorWidth - Astrometrics.ReferenceHex.X + 1;
                int y1 = y * Astrometrics.SectorHeight - Astrometrics.ReferenceHex.Y + 1;
                int x2 = x1 + w * Astrometrics.SectorWidth - 1;
                int y2 = y1 + h * Astrometrics.SectorHeight - 1;

                tileRect.X = Math.Min(x1, x2);
                tileRect.Y = Math.Min(y1, y2);
                tileRect.Width = Math.Max(x1, x2) - tileRect.X;
                tileRect.Height = Math.Max(y1, y2) - tileRect.Y;

                SectorMap map = SectorMap.FromName(SectorMap.DefaultSetting, resourceManager);
                selector = new RectSelector(map, resourceManager, tileRect);
                selector.Slop = false;

                tileRect.Offset(-1, -1);
                tileRect.Width += 1;
                tileRect.Height += 1;

                // Account for jagged hexes
                tileRect.Height += 0.5f;
                tileRect.Inflate(0.25f, 0.10f);
                if (style == Stylesheet.Style.Candy)
                    tileRect.Width += 0.75f;

                clipOutsectorBorders = true;
            }
            else
            {
                // Sector - either POSTed or specified by name
                Sector sector = null;
                options = options & ~MapOptions.SectorGrid;

                if (context.Request.HttpMethod == "POST")
                {
                    try
                    {
                        bool lint = GetBoolOption(context, "lint", defaultValue: false);
                        ErrorLogger errors = new ErrorLogger();
                        sector = GetPostedSector(context.Request, errors);
                        if (lint && !errors.Empty)
                        {
                            SendError(context.Response, 400, "Bad Request", errors.ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        SendError(context.Response, 400, "Bad Request", ex.Message);
                        return;
                    }

                    if (sector == null)
                    {
                        SendError(context.Response, 400, "Bad Request", "Either file or data must be supplied in the POST data.");
                        return;
                    }

                    title = "User Data";

                    // TODO: Suppress all OTU rendering.
                    options = options & ~MapOptions.WorldsHomeworlds & ~MapOptions.WorldsCapitals;
                }
                else
                {
                    string sectorName = GetStringOption(context, "sector");
                    if (sectorName == null)
                    {
                        SendError(context.Response, 400, "Bad Request", "No sector specified.");
                        return;
                    }

                    SectorMap map = SectorMap.FromName(SectorMap.DefaultSetting, resourceManager);

                    sector = map.FromName(sectorName);
                    if (sector == null)
                    {
                        SendError(context.Response, 404, "Not Found", String.Format("The specified sector '{0}' was not found.", sectorName));
                        return;
                    }

                    title = sector.Names[0].Text;
                }

                if (sector != null && HasOption(context, "subsector") && GetStringOption(context, "subsector").Length > 0)
                {
                    options = options & ~MapOptions.SubsectorGrid;
                    string subsector = GetStringOption(context, "subsector");
                    int index = sector.SubsectorIndexFor(subsector);
                    if (index == -1)
                    {
                        SendError(context.Response, 404, "Not Found", String.Format("The specified subsector '{0}' was not found.", subsector));
                        return;
                    }

                    selector = new SubsectorSelector(resourceManager, sector, index);

                    tileRect = sector.SubsectorBounds(index);

                    options &= ~(MapOptions.SectorGrid | MapOptions.SubsectorGrid);

                    title = String.Format("{0} - Subsector {1}", title, 'A' + index);
                }
                else if (sector != null && HasOption(context, "quadrant") && GetStringOption(context, "quadrant").Length > 0)
                {
                    string quadrant = GetStringOption(context, "quadrant");
                    int index;
                    switch (quadrant.ToLowerInvariant()) {
                        case "alpha": index = 0; quadrant = "Alpha";  break;
                        case "beta": index = 1; quadrant = "Beta"; break;
                        case "gamma": index = 2; quadrant = "Gamma"; break;
                        case "delta": index = 3; quadrant = "Delta"; break;
                        default:
                            SendError(context.Response, 400, "Bad Request", String.Format("The specified quadrant '{0}' is invalid.", quadrant));
                            return;
                    }

                    selector = new QuadrantSelector(resourceManager, sector, index);
                    tileRect = sector.QuadrantBounds(index);

                    options &= ~(MapOptions.SectorGrid | MapOptions.SubsectorGrid | MapOptions.SectorsMask);

                    title = String.Format("{0} - {1} Quadrant", title, quadrant);
                }
                else
                {
                    selector = new SectorSelector(resourceManager, sector);
                    tileRect = sector.Bounds;

                    options &= ~(MapOptions.SectorGrid);
                }

                // Account for jagged hexes
                tileRect.Height += 0.5f;
                tileRect.Inflate(0.25f, 0.10f);
                if (style == Stylesheet.Style.Candy)
                    tileRect.Width += 0.75f;
                clipOutsectorBorders = false;
            }

            const double NormalScale = 64; // pixels/parsec - standard subsector-rendering scale
            double scale = Util.Clamp(GetDoubleOption(context, "scale", NormalScale), MinScale, MaxScale);

            int rot = GetIntOption(context, "rotation", 0) % 4;
            bool thumb = GetBoolOption(context, "thumb", false);

            Stylesheet stylesheet = new Stylesheet(scale, options, style);

            Size tileSize = new Size((int)Math.Floor(tileRect.Width * scale * Astrometrics.ParsecScaleX), (int)Math.Floor(tileRect.Height * scale * Astrometrics.ParsecScaleY));

            if (thumb)
            {
                tileSize.Width = (int)Math.Floor(16 * tileSize.Width / scale);
                tileSize.Height = (int)Math.Floor(16 * tileSize.Height / scale);
                scale = 16;
            }

            int bitmapWidth = tileSize.Width, bitmapHeight = tileSize.Height;
            float translateX = 0, translateY = 0, angle = rot * 90;
            switch (rot)
            {
                case 1: // 90 degrees clockwise
                    Util.Swap(ref bitmapWidth, ref bitmapHeight);
                    translateX = bitmapWidth;
                    break;
                case 2: // 180 degrees
                    translateX = bitmapWidth; translateY = bitmapHeight;
                    break;
                case 3: // 270 degrees clockwise
                    Util.Swap(ref bitmapWidth, ref bitmapHeight);
                    translateY = bitmapHeight;
                    break;
            }

            Render.RenderContext ctx = new Render.RenderContext();
            ctx.resourceManager = resourceManager;
            ctx.selector = selector;
            ctx.tileRect = tileRect;
            ctx.scale = scale;
            ctx.options = options;
            ctx.styles = stylesheet;
            ctx.tileSize = tileSize;
            ctx.clipOutsectorBorders = clipOutsectorBorders;
            ProduceResponse(context, title, ctx, new Size(bitmapWidth, bitmapHeight), rot, translateX, translateY);
        }
Esempio n. 22
0
 // GET: Error
 public IEnumerable <ErrorRecord> Get()
 {
     using (ErrorLogger logger = new ErrorLogger())
         return(logger.GetAll());
 }
Esempio n. 23
0
 public ErrorRecord Get(int id)
 {
     using (ErrorLogger logger = new ErrorLogger())
         return(logger.GetError(id));
 }
Esempio n. 24
0
        public ActionResult EditLeaseType(LeaseType incidentType)
        {
            ModelState.Clear();
            ViewBag.LoadStatus = "0";
            try
            {
                if (Session["_product"] == null)
                {
                    incidentType.Error     = "Session has expired";
                    incidentType.ErrorCode = 0;
                    return(Json(incidentType, JsonRequestBehavior.AllowGet));
                }

                var oldLeaseType = Session["_product"] as LeaseType;

                if (oldLeaseType == null || oldLeaseType.LeaseTypeId < 1)
                {
                    incidentType.Error     = "Session has expired";
                    incidentType.ErrorCode = 0;
                    return(Json(incidentType, JsonRequestBehavior.AllowGet));
                }

                if (!ModelState.IsValid)
                {
                    incidentType.Error     = "Please supply all required fields and try again";
                    incidentType.ErrorCode = -1;
                    return(Json(incidentType, JsonRequestBehavior.AllowGet));
                }

                var wx = ValidateControl(incidentType);

                if (wx.Code < 1)
                {
                    incidentType.Error     = wx.Error;
                    incidentType.ErrorCode = -1;
                    return(Json(incidentType, JsonRequestBehavior.AllowGet));
                }

                oldLeaseType.Name        = incidentType.Name.Trim();
                oldLeaseType.Description = incidentType.Description.Trim();

                var k = new LeaseTypeServices().UpdateLeaseTypeCheckDuplicate(oldLeaseType);
                if (k < 1)
                {
                    if (k == -3)
                    {
                        incidentType.Error     = "Lease Type already exists";
                        incidentType.ErrorCode = 0;
                        return(Json(incidentType, JsonRequestBehavior.AllowGet));
                    }

                    incidentType.Error     = "Process Failed! Please contact the Admin or try again later";
                    incidentType.ErrorCode = 0;
                    return(Json(incidentType, JsonRequestBehavior.AllowGet));
                }

                incidentType.Error     = "Lease Type Information was successfully updated";
                incidentType.ErrorCode = 1;
                return(Json(incidentType, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                ErrorLogger.LogEror(ex.StackTrace, ex.Source, ex.Message);
                incidentType.Error     = "An unknown error was encountered. Request could not be serviced. Please try again later.";
                incidentType.ErrorCode = 0;
                return(Json(incidentType, JsonRequestBehavior.AllowGet));
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Recounts all GLOBAL statistics (do NOT handle user statistics)
        /// </summary>
        public static void CRON()
        {
            try
            {
                //TraficGridDailyMoneyLeft daily update
                AppSettings.TrafficGrid.TrafficGridDailyMoneyLeft = AppSettings.TrafficGrid.Limit;
                AppSettings.TrafficGrid.Save();

                //First lets update with current situation
                CheckAndUpdateStatistics(StatisticsType.TotalMembersCount);
                CheckAndUpdateStatistics(StatisticsType.AvailableReferrals);
                CheckAndUpdateStatistics(StatisticsType.NormalRentedReferrals);
                CheckAndUpdateStatistics(StatisticsType.BotRentedReferrals);
                CheckAndUpdateStatistics(StatisticsType.PointsInSystem);
                CheckAndUpdateStatistics(StatisticsType.PointsGenerated);
                CheckAndUpdateStatistics(StatisticsType.MoneyDistributedPerAdPack);

                //Move to yesterday
                var YesterdayStat     = new Statistics(StatisticsType.PointsGenerated);
                var YesterdayStatList = TableHelper.GetIntListFromString(YesterdayStat.Data1);
                AppSettings.Points.TotalGeneratedUpToYesterday += YesterdayStatList[0];
                AppSettings.Points.Save();

                //Now we can recount
                var statlist = TableHelper.SelectAllRows <Statistics>();
                foreach (var elem in statlist)
                {
                    if (elem.Type != StatisticsType.AvailableFunds)
                    {
                        elem.Data1 = TableHelper.FastRecalculate(elem.Data1);
                    }

                    if (!string.IsNullOrEmpty(elem.Data2))
                    {
                        elem.Data2 = TableHelper.FastRecalculate(elem.Data2);
                    }

                    elem.Save();
                }

                //And populate the cashflow
                Statistics Stat  = new Statistics(StatisticsType.Cashflow);
                var        list1 = TableHelper.GetMoneyListFromString(Stat.Data1);
                var        list2 = TableHelper.GetMoneyListFromString(Stat.Data2);

                list1[0]   = list1[1];
                Stat.Data1 = TableHelper.GetStringFromMoneyList(list1);

                list2[0]   = list2[1];
                Stat.Data2 = TableHelper.GetStringFromMoneyList(list2);

                Stat.Save();


                //Last, the most risky with exceptions
                CheckAndUpdateStatistics(StatisticsType.AvailableFunds);
            }
            catch (Exception ex)
            {
                ErrorLogger.Log(ex);
            }
        }
Esempio n. 26
0
        public ActionResult Create(RegisterModel model)
        {
            string restrictedErr = "Sorry, access from your host is restricted. It is possible this restriction is no longer valid. If you think this is the case, please contact support.";

            if (!ModelState.IsValidField("Extra"))
            {
                log.Warn("An attempt was made to fill the bot decoy field from {0} with the value '{1}'.", Hostname, ModelState["Extra"]);
                ipRuleManager.AddTempBannedIP(Hostname, "Attempt to fill the bot decoy field");
                return(View(model));
            }

            if (config.SiteSettings.SignupsDisabled)
            {
                ModelState.AddModelError(string.Empty, "Signups are disabled");
            }

            var recaptchaResult = ReCaptcha2.Validate(Request, AppConfig.ReCAPTCHAKey);

            if (!recaptchaResult.Success)
            {
                ErrorLogger.LogMessage(Request, string.Format("Invalid CAPTCHA (error {0})", recaptchaResult.Error), LogLevel.Warn);
                otherService.AuditLog("failed CAPTCHA", Hostname, AuditLogCategory.UserCreateFailCaptcha);
                ModelState.AddModelError("CAPTCHA", ViewRes.User.CreateStrings.CaptchaInvalid);
            }

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            if (!ipRuleManager.IsAllowed(Hostname))
            {
                log.Warn("Restricting blocked IP {0}.", Hostname);
                ModelState.AddModelError("Restricted", restrictedErr);
                return(View(model));
            }

            var time = TimeSpan.FromTicks(DateTime.Now.Ticks - model.EntryTime);

            // Attempt to register the user
            try {
                var url  = VocaUriBuilder.CreateAbsolute(Url.Action("VerifyEmail", "User")).ToString();
                var user = Data.Create(model.UserName, model.Password, model.Email ?? string.Empty, Hostname,
                                       WebHelper.GetInterfaceCultureName(Request),
                                       time, ipRuleManager.TempBannedIPs, url);
                FormsAuthentication.SetAuthCookie(user.Name, false);
                return(RedirectToAction("Index", "Home"));
            } catch (UserNameAlreadyExistsException) {
                ModelState.AddModelError("UserName", ViewRes.User.CreateStrings.UsernameTaken);
                return(View(model));
            } catch (UserEmailAlreadyExistsException) {
                ModelState.AddModelError("Email", ViewRes.User.CreateStrings.EmailTaken);
                return(View(model));
            } catch (InvalidEmailFormatException) {
                ModelState.AddModelError("Email", ViewRes.User.MySettingsStrings.InvalidEmail);
                return(View(model));
            } catch (TooFastRegistrationException) {
                ModelState.AddModelError("Restricted", restrictedErr);
                return(View(model));
            }
        }
Esempio n. 27
0
 public override Compilation CreateCompilation(TextWriter consoleOutput, TouchedFileLogger touchedFilesLogger, ErrorLogger errorLogger)
 {
     Compilation = base.CreateCompilation(consoleOutput, touchedFilesLogger, errorLogger);
     return(Compilation);
 }
Esempio n. 28
0
        /// <summary>
        /// Creates an instance of <see cref="App"/> class.
        /// </summary>
        public App()
        {
            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

            m_errorLogger = new ErrorLogger
            {
                ErrorTextMethod          = ErrorText,
                ExitOnUnhandledException = false,
                HandleUnhandledException = true,
                LogToEmail      = false,
                LogToEventLog   = true,
                LogToFile       = true,
                LogToScreenshot = true,
                LogToUI         = true
            };

            m_errorLogger.Initialize();

            m_defaultErrorText = m_errorLogger.ErrorTextMethod;

            Title = AssemblyInfo.EntryAssembly.Title;

            // Setup default cache for measurement keys and associated Guid based signal ID's
            AdoDataConnection database = null;

            try
            {
                database = new AdoDataConnection(CommonFunctions.DefaultSettingsCategory);

                if (!Environment.CommandLine.Contains("-elevated"))
                {
                    ConfigurationFile configurationFile = ConfigurationFile.Current;
                    CategorizedSettingsElementCollection systemSettings = configurationFile.Settings["SystemSettings"];
                    string elevateSetting = systemSettings["ElevateProcess"]?.Value;

                    bool elevateProcess = !string.IsNullOrEmpty(elevateSetting) ? elevateSetting.ParseBoolean() : database.IsSqlite;

                    if (elevateProcess)
                    {
                        ProcessStartInfo startInfo = new ProcessStartInfo
                        {
                            FileName        = Environment.GetCommandLineArgs()[0],
                            Arguments       = string.Join(" ", Environment.GetCommandLineArgs().Skip(1)) + " -elevated",
                            UseShellExecute = true,
                            Verb            = "runas"
                        };

                        using (Process.Start(startInfo)) { }
                        Environment.Exit(0);
                    }
                }

                MeasurementKey.EstablishDefaultCache(database.Connection, database.AdapterType);
            }
            catch (Exception ex)
            {
                // First attempt to display a modal dialog will fail to block this
                // thread -- modal dialog displayed by the error logger will block now
                MessageBox.Show(ex.Message);

                // Log and display error, then exit application - manager must connect to database to continue
                m_errorLogger.Log(new InvalidOperationException($"{Title} cannot connect to database: {ex.Message}", ex), true);
            }
            finally
            {
                database?.Dispose();
            }

            IsolatedStorageManager.WriteToIsolatedStorage("MirrorMode", false);
        }
Esempio n. 29
0
        public bool Connect()
        {
            // *** Connects the socket and returns true if successful ***

            bool returnVal = false;

            // Get host related information.
            try
            {
                // *** Check the port ***
                if ((this.ServerPort >= IPEndPoint.MinPort) && (this.ServerPort <= IPEndPoint.MaxPort))
                {
                    IPHostEntry hostEntry = Dns.GetHostEntry(this.ServerName);

                    // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
                    // an exception that occurs when the host IP Address is not compatible with the address family
                    // (typical in the IPv6 case).
                    foreach (IPAddress address in hostEntry.AddressList)
                    {
                        // *** Create an endpoint ***
                        IPEndPoint ipe = new IPEndPoint(address, this.ServerPort);

                        // TODO: Support IPv6

                        // *** Check address family ***
                        if (ipe.AddressFamily == AddressFamily.InterNetwork)
                        {
                            // *** Create the socket ***
                            Socket tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                            // *** Connect the socket ***
                            try
                            {
                                tempSocket.Connect(ipe);
                            }
                            catch (SocketException ex)
                            {
                                ErrorLogger.Log(ex, string.Format("Could not connect to the socket: {0}", ipe.ToString()));
                            }

                            try
                            {
                                // *** Check if connected ***
                                if (tempSocket.Connected)
                                {
                                    // *** Use as our current socket ***
                                    this.currentSocket = tempSocket;

                                    // *** Set the timeout to a very long value ***
                                    //this.currentSocket.ReceiveTimeout = 180000;
                                    this.currentSocket.ReceiveTimeout = 3600000;

                                    // *** Indicate success ***
                                    returnVal = true;

                                    // *** Set last operation ***
                                    this.lastOperation = DateTime.Now;

                                    // *** Finished ***
                                    break;
                                }
                                else
                                {
                                    // *** Try next address ***
                                    continue;
                                }
                            }
                            catch { }
                        }
                    }
                }
            }
            catch (SocketException ex)
            {
                ErrorLogger.Log(ex, "Error in RpcSocket.Connect");
            }

            return(returnVal);
        }
Esempio n. 30
0
        public void CreateMapFromImage(WzImage mapImage, string mapName, string streetName, string categoryName, WzSubProperty strMapProp, PageCollection Tabs, MultiBoard multiBoard, EventHandler[] rightClickHandler)
        {
            if (!mapImage.Parsed)
            {
                mapImage.ParseImage();
            }
            List <string> copyPropNames = VerifyMapPropsKnown(mapImage, false);
            MapInfo       info          = new MapInfo(mapImage, mapName, streetName, categoryName);

            foreach (string copyPropName in copyPropNames)
            {
                info.additionalNonInfoProps.Add(mapImage[copyPropName]);
            }
            MapType type = GetMapType(mapImage);

            if (type == MapType.RegularMap)
            {
                info.id = int.Parse(WzInfoTools.RemoveLeadingZeros(WzInfoTools.RemoveExtension(mapImage.Name)));
            }
            info.mapType = type;

            Rectangle VR            = new Rectangle();
            Point     center        = new Point();
            Point     size          = new Point();
            Point     minimapSize   = new Point();
            Point     minimapCenter = new Point();
            bool      hasMinimap    = false;
            bool      hasVR         = false;

            try
            {
                GetMapDimensions(mapImage, out VR, out center, out size, out minimapCenter, out minimapSize, out hasVR, out hasMinimap);
            }
            catch (NoVRException)
            {
                MessageBox.Show("Error - map does not contain size information and HaCreator was unable to generate it. An error has been logged.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ErrorLogger.Log(ErrorLevel.IncorrectStructure, "no size @map " + info.id.ToString());
                return;
            }

            lock (multiBoard)
            {
                CreateMap(mapName, WzInfoTools.RemoveLeadingZeros(WzInfoTools.RemoveExtension(mapImage.Name)), CreateStandardMapMenu(rightClickHandler), size, center, 8, Tabs, multiBoard);
                Board mapBoard = multiBoard.SelectedBoard;
                mapBoard.Loading = true; // prevents TS Change callbacks
                mapBoard.MapInfo = info;
                if (hasMinimap)
                {
                    mapBoard.MiniMap = ((WzCanvasProperty)mapImage["miniMap"]["canvas"]).PngProperty.GetPNG(false);
                    System.Drawing.Point mmPos = new System.Drawing.Point(-minimapCenter.X, -minimapCenter.Y);
                    mapBoard.MinimapPosition  = mmPos;
                    mapBoard.MinimapRectangle = new MinimapRectangle(mapBoard, new Rectangle(mmPos.X, mmPos.Y, minimapSize.X, minimapSize.Y));
                }
                if (hasVR)
                {
                    mapBoard.VRRectangle = new VRRectangle(mapBoard, VR);
                }
                LoadLayers(mapImage, mapBoard);
                LoadLife(mapImage, mapBoard);
                LoadFootholds(mapImage, mapBoard);
                GenerateDefaultZms(mapBoard);
                LoadRopes(mapImage, mapBoard);
                LoadChairs(mapImage, mapBoard);
                LoadPortals(mapImage, mapBoard);
                LoadReactors(mapImage, mapBoard);
                LoadToolTips(mapImage, mapBoard);
                LoadBackgrounds(mapImage, mapBoard);
                LoadMisc(mapImage, mapBoard);

                mapBoard.BoardItems.Sort();
                mapBoard.Loading = false;
            }
            if (ErrorLogger.ErrorsPresent())
            {
                ErrorLogger.SaveToFile("errors.txt");
                if (UserSettings.ShowErrorsMessage)
                {
                    MessageBox.Show("Errors were encountered during the loading process. These errors were saved to \"errors.txt\". Please send this file to the author, either via mail (" + ApplicationSettings.AuthorEmail + ") or from the site you got this software from.\n\n(In the case that this program was not updated in so long that this message is now thrown on every map load, you may cancel this message from the settings)", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                ErrorLogger.ClearErrors();
            }
        }
        /// <summary>
        /// Create a <see cref="QuartzScheduler" /> with the given configuration
        /// properties.
        /// </summary>
        /// <seealso cref="QuartzSchedulerResources" />
        public QuartzScheduler(QuartzSchedulerResources resources, SchedulingContext ctxt, TimeSpan idleWaitTime, TimeSpan dbRetryInterval)
        {
            Log = LogManager.GetLogger(GetType());
            this.resources = resources;
            try
            {
                Bind();
            }
            catch (Exception re)
            {
                throw new SchedulerException("Unable to bind scheduler to remoting context.", re);
            }

            schedThread = new QuartzSchedulerThread(this, resources, ctxt);
            if (idleWaitTime > TimeSpan.Zero)
            {
                schedThread.IdleWaitTime = idleWaitTime;
            }
            if (dbRetryInterval > TimeSpan.Zero)
            {
                schedThread.DbFailureRetryInterval = dbRetryInterval;
            }

            jobMgr = new ExecutingJobsManager();
            AddGlobalJobListener(jobMgr);
            errLogger = new ErrorLogger();
            AddSchedulerListener(errLogger);

            signaler = new SchedulerSignalerImpl(this, this.schedThread);

            Log.Info(string.Format(CultureInfo.InvariantCulture, "Quartz Scheduler v.{0} created.", Version));
        }
Esempio n. 32
0
 static void CurrentProcess_ErrorDataReceived(string Data)
 {
     ErrorLogger.Log("Error occured: " + Data, ErrorType.Error, ErrorOrigin.Program);
 }
Esempio n. 33
0
        /// <summary>
        /// 
        /// </summary>
        public static bool ReloadScripts()
        {
            if (SceneManager.GameProject == null) return false;

            lock (locker)
            {

                try
                {
                    if (File.Exists(SceneManager.GameProject.ProjectPath + @"\_Scripts.csproj"))
                        File.Delete(SceneManager.GameProject.ProjectPath + @"\_Scripts.csproj");
                    //search for .sln and .csproj files
                    foreach (string filename in Directory.GetFiles(SceneManager.GameProject.ProjectPath))
                    {
                        if (System.IO.Path.GetExtension(filename).ToLower().Equals(".csproj"))
                        {
                            UserPreferences.Instance.ProjectCsProjFilePath = filename;
                        }
                        else if (System.IO.Path.GetExtension(filename).ToLower().Equals(".sln"))
                        {
                            UserPreferences.Instance.ProjectSlnFilePath = filename;
                        }
                    }

                    // Check if scripts were removed:
                    bool removed = false;

                    string projectFileName = UserPreferences.Instance.ProjectCsProjFilePath;
                    XmlDocument doc = new XmlDocument();
                    doc.Load(projectFileName);

                    while (doc.GetElementsByTagName("ItemGroup").Count < 2)
                        doc.GetElementsByTagName("Project").Item(0).AppendChild(doc.CreateElement("ItemGroup"));

                    foreach (XmlNode _node in doc.GetElementsByTagName("ItemGroup").Item(1).ChildNodes)
                    {
                        if (_node.Name.ToLower().Equals("compile"))
                        {
                            if (!File.Exists(SceneManager.GameProject.ProjectPath + "\\" + _node.Attributes.GetNamedItem("Include").Value))
                            {
                                doc.GetElementsByTagName("ItemGroup").Item(1).RemoveChild(_node);
                                removed = true;
                            }
                        }
                    }

                    if (removed)
                        doc.Save(projectFileName);

                    string tmpProjectFileName = SceneManager.GameProject.ProjectPath + @"\_Scripts.csproj";
                    string hash = string.Empty;

                    hash = GibboHelper.EncryptMD5(DateTime.Now.ToString());

                    //try
                    //{
                        /* Change the assembly Name */
                        doc = new XmlDocument();
                        doc.Load(projectFileName);
                        doc.GetElementsByTagName("Project").Item(0).ChildNodes[0]["AssemblyName"].InnerText = hash;
                        doc.Save(tmpProjectFileName);
                    //}
                    //catch (Exception ex)
                    //{
                    //    Console.WriteLine(ex.Message);
                    //}

                    /* Compile project */
                    ProjectCollection projectCollection = new ProjectCollection();
                    Dictionary<string, string> GlobalProperty = new Dictionary<string, string>();
                    GlobalProperty.Add("Configuration", SceneManager.GameProject.Debug ? "Debug" : "Release");
                    GlobalProperty.Add("Platform", "x86");

                    //FileLogger logger = new FileLogger() { Parameters = @"logfile=C:\gibbo_log.txt" };
                    logger = new ErrorLogger();

                    BuildRequestData buildRequest = new BuildRequestData(tmpProjectFileName, GlobalProperty, null, new string[] { "Build" }, null);
                    BuildResult buildResult = BuildManager.DefaultBuildManager.Build(
                            new BuildParameters(projectCollection)
                            {
                                BuildThreadPriority = System.Threading.ThreadPriority.AboveNormal,
                                Loggers = new List<ILogger>() { logger }
                            },
                            buildRequest);

                    //foreach (var tr in logger.Errors)
                    //{
                    //    Console.WriteLine(tr.ToString());
                    //}

                    //Console.WriteLine(buildResult.OverallResult);

                    string cPath = SceneManager.GameProject.ProjectPath + @"\bin\" + (SceneManager.GameProject.Debug ? "Debug" : "Release") + "\\" + hash + ".dll";

                    if (File.Exists(cPath))
                    {
                        /* read assembly to memory without locking the file */
                        byte[] readAllBytes = File.ReadAllBytes(cPath);
                        SceneManager.ScriptsAssembly = Assembly.Load(readAllBytes);

                        if (SceneManager.ActiveScene != null)
                        {
                            SceneManager.ActiveScene.SaveComponentValues();
                            SceneManager.ActiveScene.Initialize();
                        }

                        //Console.WriteLine("Path: " + SceneManager.ScriptsAssembly.GetName().Name);
                    }
                    else
                    {
                        File.Delete(tmpProjectFileName);
                        return false;
                    }

                    File.Delete(tmpProjectFileName);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                return true;
            }
        }
Esempio n. 34
0
 static void CurrentProcess_OutputDataReceived(string Data)
 {
     ErrorLogger.Log(Data, ErrorType.Message, ErrorOrigin.Program);
 }
Esempio n. 35
0
        public void Should_log_configuration_errors()
        {
            var validator = new Validator { IsValid = true };
            var errorLogger = new ErrorLogger();
            var configurationStore = new ConfigurationStore().Initialize(validator, errorLogger);

            const string config = "{child1:{field1:1,field2:2},child2:{field1:99,field2:98}}";
            configurationStore.UpdateConfiguration(config);

            Assert.AreEqual(0, errorLogger.Errors.Count);

            var value = configurationStore.Get("child1/field1", new TestClassA{Field1 = 45});

            Assert.AreEqual(1, errorLogger.Errors.Count);
            Assert.AreEqual(45, value.Field1);
        }
 public void Initialize() => _errorLogger = new ErrorLogger();
//-1^ERROR MESSAGE

//ID^DT OF TRACKING^DFN^LASTNAME,FIRSTNAME^USER^TRACKING TYPE^SOURCE^REASON|REASON
//ID^COMMENT

        protected override void ProcessResponse()
        {
            // *** Make sure we have something to work with ***
            if (string.IsNullOrWhiteSpace(this.Response.Data))
            {
                // *** Set response info ***
                this.Response.Status = RpcResponseStatus.Fail;
                this.Response.InformationalMessage = "No data returned";
            }
            else
            {
                // *** Check first piece for success/failure ***
                string first = Util.Piece(this.Response.Lines[0], Caret, 1);

                char[] chars = first.ToCharArray();

                if ((int)chars[0] == 24)
                {
                    this.Response.Status = RpcResponseStatus.Fail;
                    this.Response.InformationalMessage = "An internal error has occurred";
                    ErrorLogger.Log(string.Format("M Error Calling RPC '{0}': {1}", this.RpcName, this.Response.Data));
                }
                else if (first == "-1")
                {
                    // *** -1 is fail ***
                    this.Response.Status = RpcResponseStatus.Fail;
                    this.Response.InformationalMessage = Util.Piece(this.Response.Lines[0], "^", 2);

                    // *** Ok if no matches ***
                    if (this.Response.InformationalMessage.ToUpper().StartsWith("NO ENTRIES"))
                    {
                        this.Response.Status = RpcResponseStatus.Success;
                        this.TrackingItems   = new List <DsioTrackingItem>();
                    }
                }
                else if (first == "0")
                {
                    this.Response.Status = RpcResponseStatus.Success;
                    this.TrackingItems   = new List <DsioTrackingItem>();
                    this.Response.InformationalMessage = "Nothing Found";
                    this.TotalResults = 0;
                }
                else
                {
                    switch (this.operation)
                    {
                    case DsioGetTrackingOperation.All:
                    case DsioGetTrackingOperation.PatientFlags:
                        ProcessAll();
                        break;

                    case DsioGetTrackingOperation.Flagged:
                        ProcessFlagged();
                        break;

                    case DsioGetTrackingOperation.Tracked:
                        ProcessTracked();
                        break;
                    }
                }
            }
        }
Esempio n. 38
0
        public ActionResult EditWellWorkOverReason(WellWorkOverReason wellWorkOverReason)
        {
            ModelState.Clear();
            ViewBag.LoadStatus = "0";
            try
            {
                if (Session["_wellWorkOverReason"] == null)
                {
                    wellWorkOverReason.Error     = "Session has expired";
                    wellWorkOverReason.ErrorCode = 0;
                    return(Json(wellWorkOverReason, JsonRequestBehavior.AllowGet));
                }

                var oldWellWorkOverReason = Session["_wellWorkOverReason"] as WellWorkOverReason;

                if (oldWellWorkOverReason == null || oldWellWorkOverReason.WellWorkOverReasonId < 1)
                {
                    wellWorkOverReason.Error     = "Session has expired";
                    wellWorkOverReason.ErrorCode = 0;
                    return(Json(wellWorkOverReason, JsonRequestBehavior.AllowGet));
                }

                if (!ModelState.IsValid)
                {
                    wellWorkOverReason.Error     = "Please supply all required fields and try again";
                    wellWorkOverReason.ErrorCode = -1;
                    return(Json(wellWorkOverReason, JsonRequestBehavior.AllowGet));
                }

                var wx = ValidateControl(wellWorkOverReason);

                if (wx.Code < 1)
                {
                    wellWorkOverReason.Error     = wx.Error;
                    wellWorkOverReason.ErrorCode = -1;
                    return(Json(wellWorkOverReason, JsonRequestBehavior.AllowGet));
                }

                oldWellWorkOverReason.Title       = wellWorkOverReason.Title;
                oldWellWorkOverReason.Description = wellWorkOverReason.Description;

                var k = new WellWorkOverReasonServices().UpdateWellWorkOverReason(oldWellWorkOverReason);
                if (k < 1)
                {
                    if (k == -3)
                    {
                        wellWorkOverReason.Error     = "Well Workover Reason already exists";
                        wellWorkOverReason.ErrorCode = 0;
                        return(Json(wellWorkOverReason, JsonRequestBehavior.AllowGet));
                    }

                    wellWorkOverReason.Error     = "Process Failed! Please contact the Admin or try again later";
                    wellWorkOverReason.ErrorCode = 0;
                    return(Json(wellWorkOverReason, JsonRequestBehavior.AllowGet));
                }

                wellWorkOverReason.Error     = "Well Workover Reason Information was successfully updated";
                wellWorkOverReason.ErrorCode = 1;
                return(Json(wellWorkOverReason, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                ErrorLogger.LogEror(ex.StackTrace, ex.Source, ex.Message);
                wellWorkOverReason.Error     = "An unknown error was encountered. Request could not be serviced. Please try again later.";
                wellWorkOverReason.ErrorCode = 0;
                return(Json(wellWorkOverReason, JsonRequestBehavior.AllowGet));
            }
        }
Esempio n. 39
0
        public List <StoreItemObject> GetStoreItemObjects(int?itemsPerPage, int?pageNumber)
        {
            try
            {
                List <StoreItem> storeItemEntityList;
                if ((itemsPerPage != null && itemsPerPage > 0) && (pageNumber != null && pageNumber >= 0))
                {
                    var tpageNumber = (int)pageNumber;
                    var tsize       = (int)itemsPerPage;
                    storeItemEntityList = _repository.GetWithPaging(m => m.StoreItemId, tpageNumber, tsize, "ChartOfAccount, StoreItemBrand, StoreItemCategory, StoreItemType").ToList();
                }

                else
                {
                    storeItemEntityList = _repository.GetAll("ChartOfAccount, StoreItemBrand, StoreItemCategory, StoreItemType").ToList();
                }

                if (!storeItemEntityList.Any())
                {
                    return(new List <StoreItemObject>());
                }
                var storeItemObjList = new List <StoreItemObject>();
                storeItemEntityList.ForEach(m =>
                {
                    var storeItemObject = ModelCrossMapper.Map <StoreItem, StoreItemObject>(m);
                    if (storeItemObject != null && storeItemObject.StoreItemId > 0)
                    {
                        storeItemObject.ChartOfAccountTypeName = m.ChartOfAccount.AccountType;
                        storeItemObject.StoreItemCategoryName  = m.StoreItemCategory.Name;
                        storeItemObject.StoreItemTypeName      = m.StoreItemType.Name;
                        storeItemObject.StoreItemBrandName     = m.StoreItemBrand.Name;
                        if (storeItemObject.ParentItemId > 0)
                        {
                            var parentItem = new StoreItem();
                            parentItem     = storeItemEntityList.Find(x => x.StoreItemId == storeItemObject.ParentItemId);
                            if (parentItem != null && parentItem.StoreItemId > 0)
                            {
                                storeItemObject.ParentItemName = parentItem.Name;
                            }
                            else
                            {
                                parentItem = _repository.GetById(storeItemObject.ParentItemId);
                                if (parentItem != null && parentItem.StoreItemId > 0)
                                {
                                    storeItemObject.ParentItemName = parentItem.Name;
                                }
                            }
                        }
                        else
                        {
                            storeItemObject.ParentItemName = " ";
                        }

                        storeItemObjList.Add(storeItemObject);
                    }
                });

                return(storeItemObjList);
            }
            catch (Exception ex)
            {
                ErrorLogger.LogError(ex.StackTrace, ex.Source, ex.Message);
                return(new List <StoreItemObject>());
            }
        }
Esempio n. 40
0
 internal Sector(Stream stream, string mediaType, ErrorLogger errors)
     : this()
 {
     WorldCollection wc = new WorldCollection();
     wc.Deserialize(stream, mediaType, errors);
     foreach (World world in wc)
         world.Sector = this;
     worlds = wc;
 }
Esempio n. 41
0
 public FieldChecker(StringDictionary dict, ErrorLogger errors, int lineNumber, string line)
 {
     this.dict = dict;
     this.errors = errors;
     this.lineNumber = lineNumber;
     this.line = line;
 }
Esempio n. 42
0
 internal void DownloadMod(UIMouseEvent evt, UIElement listeningElement)
 {
     Main.PlaySound(SoundID.MenuTick);
     try
     {
         if (UIModBrowser.PlatformSupportsTls12)                                 // Needed for downloads from Github
         {
             ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072; // SecurityProtocolType.Tls12
         }
         using (WebClient client = new WebClient())
         {
             ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => { return(true); });
             Interface.modBrowser.selectedItem = this;
             Interface.downloadMod.SetDownloading(displayname);
             Interface.downloadMod.SetCancel(client.CancelAsync);
             client.DownloadProgressChanged += (s, e) =>
             {
                 Interface.downloadMod.SetProgress(e);
             };
             client.DownloadFileCompleted += (s, e) =>
             {
                 Main.menuMode = Interface.modBrowserID;
                 if (e.Error != null)
                 {
                     if (e.Cancelled)
                     {
                     }
                     else
                     {
                         HttpStatusCode httpStatusCode = GetHttpStatusCode(e.Error);
                         if (httpStatusCode == HttpStatusCode.ServiceUnavailable)
                         {
                             Interface.errorMessage.SetMessage("The Mod Browser server has exceeded its daily bandwidth allotment. Please consult this mod's homepage for an alternate download or try again later.");
                             Interface.errorMessage.SetGotoMenu(0);
                             Interface.errorMessage.SetFile(ErrorLogger.LogPath);
                             Main.gameMenu = true;
                             Main.menuMode = Interface.errorMessageID;
                         }
                         else
                         {
                             Interface.errorMessage.SetMessage("Unknown Mod Browser Error. Try again later.");
                             Interface.errorMessage.SetGotoMenu(0);
                             Interface.errorMessage.SetFile(ErrorLogger.LogPath);
                             Main.gameMenu = true;
                             Main.menuMode = Interface.errorMessageID;
                         }
                     }
                 }
                 else if (!e.Cancelled)
                 {
                     // Downloaded OK
                     File.Copy(ModLoader.ModPath + Path.DirectorySeparatorChar + "temporaryDownload.tmod", ModLoader.ModPath + Path.DirectorySeparatorChar + mod + ".tmod", true);
                     if (!update)
                     {
                         Interface.modBrowser.aNewModDownloaded = true;
                     }
                     else
                     {
                         Interface.modBrowser.aModUpdated = true;
                     }
                     RemoveChild(updateButton);
                 }
                 // Clean up: Delete temp
                 File.Delete(ModLoader.ModPath + Path.DirectorySeparatorChar + "temporaryDownload.tmod");
             };
             client.DownloadFileAsync(new Uri(download), ModLoader.ModPath + Path.DirectorySeparatorChar + "temporaryDownload.tmod");
             //client.DownloadFileAsync(new Uri(download), ModLoader.ModPath + Path.DirectorySeparatorChar + mod + ".tmod");
         }
         Main.menuMode = Interface.downloadModID;
     }
     catch (WebException e)
     {
         ErrorLogger.LogModBrowserException(e);
     }
 }
 public void SetUp()
 {
     _logger = new ErrorLogger();
 }
 public void Setup()
 {
     ErrorLogger.SetToTest();
     StaticDatabaseConnection.SetToTest(databasePath);
     StaticDatabaseConnection.OpenDBConnection();
 }
Esempio n. 45
0
        public RpcResponse SendMessage(string msg)
        {
            // *** Send RPC as bytes on socket and receive bytes back ***

            RpcResponseBuilder returnBuilder = new RpcResponseBuilder();

            //TraceLogger.Log(string.Format("RpcSocket.SendMessage - TimedOut={0}", this.TimedOut));

            lock (this.currentSocket)
            {
                // *** Convert to bytes ***
                byte[] bytes = Encoding.ASCII.GetBytes(msg);

                try
                {
                    // *** Send bytes to socket ***
                    this.currentSocket.Send(bytes);

                    // *** Set last operation ***
                    this.lastOperation = DateTime.Now;

                    // *** Get server packet bytes ***
                    byte[] packetBytes = GetServerPacket();

                    // *** Add to result ***
                    returnBuilder.SetSecuritySegment(packetBytes);

                    // *** Get application packet bytes ***
                    packetBytes = GetServerPacket();

                    // *** Add to result ***
                    returnBuilder.SetApplicationSegment(packetBytes);

                    byte[] socketBuffer = new byte[1024];
                    int    retries      = 0;
                    bool   keepGoing    = true;

                    // *** Receive bytes from socket in a loop ***
                    while (keepGoing)
                    {
                        // *** Receive bytes ***
                        int bytesRead = this.currentSocket.Receive(socketBuffer);

                        // *** Check number of bytes read ***
                        if (bytesRead > 0)
                        {
                            byte[] actualBytes = new byte[bytesRead];

                            Array.Copy(socketBuffer, actualBytes, bytesRead);

                            // *** Append bytes to the result ***
                            bool reachedEnd = returnBuilder.AppendData(actualBytes);

                            // *** Check if end reached ***
                            if (reachedEnd)
                            {
                                keepGoing = false; // *** Done ***
                            }
                        }
                        else
                        {
                            // *** No bytes read, retry ***
                            if (retries < 3)
                            {
                                // *** Ok to retry, sleep 1/2 sec ***
                                retries++;
                                Thread.Sleep(500);
                            }
                            else
                            {
                                // *** Too many retries ***
                                returnBuilder.SetInformationalMessage("Data could not be received from socket");
                                returnBuilder.SetFailType(RpcResponseFailType.Retries);

                                // *** Stop looping ***
                                keepGoing = false;
                            }
                        }
                    }
                }
                catch (SocketException sockEx)
                {
                    string timeoutMsg = string.Format("(TimedOut={0})", this.TimedOut);
                    VistaLogger.Log(timeoutMsg, "", -1, null, "");
                    ErrorLogger.Log(sockEx, "A problem occurred communicating with the socket. " + timeoutMsg);
                    returnBuilder.SetInformationalMessage("A problem occurred communicating with the socket.");
                    returnBuilder.SetFailType(RpcResponseFailType.SocketError);
                }
            }

            return(returnBuilder.ToResponse());
        }
Esempio n. 46
0
 public override void Parse(TextReader reader, WorldCollection worlds, ErrorLogger errors)
 {
     TSVParser parser = new TSVParser(reader);
     foreach (var row in parser.Data)
         ParseWorld(worlds, row.dict, row.line, row.lineNumber, errors);
 }
Esempio n. 47
0
        protected static void ParseWorld(WorldCollection worlds, StringDictionary dict, string line, int lineNumber, ErrorLogger errors)
        {
            try
            {
                FieldChecker checker = new FieldChecker(dict, errors, lineNumber, line);
                World world = new World();
                world.Hex = checker.Check("Hex", HEX_REGEX);
                world.Name = dict["Name"];
                world.UWP = checker.Check("UWP", UWP_REGEX);
                world.Remarks = checker.Check(new string[] { "Remarks", "Trade Codes", "Comments" });
                world.Importance = checker.Check(new string[] { "{Ix}", "{ Ix }", "Ix" });
                world.Economic = checker.Check(new string[] { "(Ex)", "( Ex )", "Ex" });
                world.Cultural = checker.Check(new string[] { "[Cx]", "[ Cx ]", "Cx" });
                world.Nobility = checker.Check(new string[] { "N", "Nobility" }, NOBILITY_REGEX, CheckOptions.EmptyIfDash);
                world.Bases = checker.Check(new string[] { "B", "Bases" }, BASES_REGEX, CheckOptions.EmptyIfDash);
                world.Zone = checker.Check(new string[] { "Z", "Zone" }, ZONE_REGEX, CheckOptions.EmptyIfDash);
                world.PBG = checker.Check("PBG", PBG_REGEX);
                world.Allegiance = checker.Check(new string[] { "A", "Al", "Allegiance" },
                    // TODO: Allow unofficial sectors to have locally declared allegiances.
                    a => a.Length != 4 || SecondSurvey.IsKnownT5Allegiance(a));
                world.Stellar = checker.Check(new string[] { "Stellar", "Stars", "Stellar Data" }, STARS_REGEX, CheckOptions.Warning);

                int w;
                if (Int32.TryParse(checker.Check(new string[] { "W", "Worlds" }), NumberStyles.Integer, CultureInfo.InvariantCulture, out w))
                    world.Worlds = w;

                int ru;
                if (Int32.TryParse(dict["RU"], NumberStyles.Integer | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out ru))
                    world.ResourceUnits = ru;

                // Cleanup known placeholders
                if (world.Name == world.Name.ToUpperInvariant() && world.IsHi)
                    world.Name = Util.FixCapitalization(world.Name);

                if (worlds[world.X, world.Y] != null && errors != null)
                    errors.Warning("Duplicate World", lineNumber, line);

                if (!checker.HadError)
                {
                    worlds[world.X, world.Y] = world;
                }
            }
            catch (Exception e)
            {
                errors.Error("Parse Error: " + e.Message, lineNumber, line);
                //throw new Exception(String.Format("UWP Parse Error in line {0}:\n{1}\n{2}", lineNumber, e.Message, line));
            }
        }
Esempio n. 48
0
        public override void Update(NPC npc)
        {
            try
            {
                int rotDistance = 64;
                int rotTimeLeft = 36000;

                if (rotMissile != null)
                {
                    if (rotMissile.projectile.active && npc.active)
                    {
                        goto Secondary;
                    }
                    else
                    {
                        rotMissile.projectile.Kill();
                    }
                }

                Projectile proj1 =
                    Main.projectile[
                        Projectile.NewProjectile(npc.Center, new Vector2(0f, -1.5f),
                                                 kNPC.mod.ProjectileType <ProceduralSpellProj>(), npc.damage, 3f)];
                proj1.hostile  = true;
                proj1.friendly = false;
                ProceduralSpellProj ps1 = (ProceduralSpellProj)proj1.modProjectile;
                ps1.origin = proj1.position;
                Cross cross1 = Main.rand.Next(2) == 0 ? (Cross) new Cross_Red() : new Cross_Violet();
                ps1.ai.Add(delegate(ProceduralSpellProj spell)
                {
                    cross1.GetAIAction()(spell);

                    float displacementAngle      = (float)API.Tau / 4f;
                    Vector2 displacementVelocity = Vector2.Zero;
                    if (rotTimeLeft - spell.projectile.timeLeft >= rotDistance * 2 / 3)
                    {
                        Vector2 unitRelativePos = spell.RelativePos(spell.caster.Center);
                        unitRelativePos.Normalize();
                        spell.projectile.Center = spell.caster.Center + unitRelativePos * rotDistance;
                        displacementVelocity    =
                            new Vector2(-2f, 0f).RotatedBy((spell.RelativePos(spell.caster.Center)).ToRotation() +
                                                           (float)API.Tau / 4f);

                        float angle = displacementAngle -
                                      0.06f * (float)(rotTimeLeft - spell.projectile.timeLeft - rotDistance * 2 / 3);
                        spell.projectile.Center = spell.caster.Center + new Vector2(0f, -rotDistance).RotatedBy(angle);
                    }
                    else
                    {
                        spell.projectile.Center = spell.caster.Center +
                                                  new Vector2(0f, -1.5f).RotatedBy(displacementAngle) *
                                                  (rotTimeLeft - spell.projectile.timeLeft);
                    }

                    spell.projectile.velocity = displacementVelocity + spell.caster.velocity;
                    spell.basePosition        = spell.caster.position;
                });
                ps1.init.Add(cross1.GetInitAction());
                ps1.caster = npc;
                ps1.Initialize();
                ps1.projectile.penetrate = -1;
                ps1.projectile.timeLeft  = rotTimeLeft;
                rotMissile = ps1;

Secondary:

                if (rotSecondary != null)
                {
                    if (rotSecondary.projectile.active && npc.active)
                    {
                        return;
                    }
                    else
                    {
                        rotSecondary.projectile.Kill();
                    }
                }

                Projectile proj2 =
                    Main.projectile[
                        Projectile.NewProjectile(npc.Center, new Vector2(0f, 1.5f),
                                                 kNPC.mod.ProjectileType <ProceduralSpellProj>(), npc.damage, 3f)];
                proj2.hostile  = true;
                proj2.friendly = false;
                ProceduralSpellProj ps2 = (ProceduralSpellProj)proj2.modProjectile;
                ps2.origin = proj2.position;
                Cross cross2 = Main.rand.Next(2) == 0 ? (Cross) new Cross_Blue() : new Cross_Purple();
                ps2.ai.Add(delegate(ProceduralSpellProj spell)
                {
                    cross2.GetAIAction()(spell);

                    float displacementAngle      = (float)API.Tau / 4f + (float)Math.PI;
                    Vector2 displacementVelocity = Vector2.Zero;
                    if (rotTimeLeft - spell.projectile.timeLeft >= rotDistance * 2 / 3)
                    {
                        Vector2 unitRelativePos = spell.RelativePos(spell.caster.Center);
                        unitRelativePos.Normalize();
                        spell.projectile.Center = spell.caster.Center + unitRelativePos * rotDistance;
                        displacementVelocity    =
                            new Vector2(-2f, 0f).RotatedBy((spell.RelativePos(spell.caster.Center)).ToRotation() +
                                                           (float)API.Tau / 4f);

                        float angle = displacementAngle -
                                      0.06f * (float)(rotTimeLeft - spell.projectile.timeLeft - rotDistance * 2 / 3);
                        spell.projectile.Center = spell.caster.Center + new Vector2(0f, -rotDistance).RotatedBy(angle);
                    }
                    else
                    {
                        spell.projectile.Center = spell.caster.Center +
                                                  new Vector2(0f, 1.5f).RotatedBy(displacementAngle) *
                                                  (rotTimeLeft - spell.projectile.timeLeft);
                    }

                    spell.projectile.velocity = displacementVelocity + spell.caster.velocity;
                    spell.basePosition        = spell.caster.position;
                });
                ps2.init.Add(cross2.GetInitAction());
                ps2.caster = npc;
                ps2.Initialize();
                ps2.projectile.penetrate = -1;
                ps2.projectile.timeLeft  = rotTimeLeft;
                rotSecondary             = ps2;
            }
            catch (SystemException e)
            {
                Main.NewText(e.ToString());
                ErrorLogger.Log(e.ToString());
            }
        }
Esempio n. 49
0
 public abstract void Parse(TextReader reader, WorldCollection worlds, ErrorLogger errors);
Esempio n. 50
0
        private int RunScript(ScriptOptions options, string code, ErrorLogger errorLogger, CancellationToken cancellationToken)
        {
            var globals = new CommandLineScriptGlobals(_console.Out, _objectFormatter);
            globals.Args.AddRange(_compiler.Arguments.ScriptArguments);

            var script = Script.CreateInitialScript<object>(_scriptCompiler, code, options, globals.GetType(), assemblyLoaderOpt: null);
            try
            {
                script.RunAsync(globals, cancellationToken).Wait();

                // TODO: use the return value of the script https://github.com/dotnet/roslyn/issues/5773
                return CommonCompiler.Succeeded;
            }
            catch (CompilationErrorException e)
            {
                _compiler.ReportErrors(e.Diagnostics, _console.Out, errorLogger);
                return CommonCompiler.Failed;
            }
        }
Esempio n. 51
0
        private SyntaxTree ParseFile(
            TextWriter consoleOutput,
            CSharpParseOptions parseOptions,
            CSharpParseOptions scriptParseOptions,
            ref bool hadErrors,
            CommandLineSourceFile file,
            ErrorLogger errorLogger,
            out string normalizedFilePath)
        {
            var fileReadDiagnostics = new List<DiagnosticInfo>();
            var content = ReadFileContent(file, fileReadDiagnostics, out normalizedFilePath);

            if (content == null)
            {
                ReportErrors(fileReadDiagnostics, consoleOutput, errorLogger);
                fileReadDiagnostics.Clear();
                hadErrors = true;
                return null;
            }
            else
            {
                return ParseFile(parseOptions, scriptParseOptions, content, file);
            }
        }
Esempio n. 52
0
 public void Parse(Stream stream, WorldCollection worlds, ErrorLogger errors)
 {
     using (var reader = new StreamReader(stream, Encoding, detectEncodingFromByteOrderMarks: true, bufferSize: BUFFER_SIZE))
     {
         Parse(reader, worlds, errors ?? worlds.ErrorList);
     }
 }
Esempio n. 53
0
 private IEnumerable<string> PerformLoggedAction(Action action)
 {
     var logger = new ErrorLogger();
     _projectManager.Logger = logger;
     try
     {
         action();
     }
     finally
     {
         _projectManager.Logger = null;
     }
     return logger.Errors;
 }
Esempio n. 54
0
        public override void HandlePacket(BinaryReader reader, int whoAmI)
        {
            ExampleModMessageType msgType = (ExampleModMessageType)reader.ReadByte();

            switch (msgType)
            {
            // This message sent by the server to initialize the Volcano Tremor on clients
            case ExampleModMessageType.SetTremorTime:
                int          tremorTime = reader.ReadInt32();
                ExampleWorld world      = GetModWorld <ExampleWorld>();
                world.VolcanoTremorTime = tremorTime;
                break;

            // This message sent by the server to initialize the Volcano Rubble.
            case ExampleModMessageType.VolcanicRubbleMultiplayerFix:
                int numberProjectiles = reader.ReadInt32();
                for (int i = 0; i < numberProjectiles; i++)
                {
                    int  identity = reader.ReadInt32();
                    bool found    = false;
                    for (int j = 0; j < 1000; j++)
                    {
                        if (Main.projectile[j].owner == 255 && Main.projectile[j].identity == identity && Main.projectile[j].active)
                        {
                            Main.projectile[j].hostile = true;
                            Main.projectile[j].name    = "Volcanic Rubble";
                            found = true;
                            break;
                        }
                    }
                    if (!found)
                    {
                        ErrorLogger.Log("Error: Projectile not found");
                    }
                }
                break;

            case ExampleModMessageType.PuritySpirit:
                PuritySpirit spirit = Main.npc[reader.ReadInt32()].modNPC as PuritySpirit;
                if (spirit != null && spirit.npc.active)
                {
                    spirit.HandlePacket(reader);
                }
                break;

            case ExampleModMessageType.HeroLives:
                Player player = Main.player[reader.ReadInt32()];
                int    lives  = reader.ReadInt32();
                player.GetModPlayer <ExamplePlayer>(this).heroLives = lives;
                if (lives > 0)
                {
                    string text = player.name + " has " + lives;
                    if (lives == 1)
                    {
                        text += " life left!";
                    }
                    else
                    {
                        text += " lives left!";
                    }
                    NetMessage.SendData(25, -1, -1, text, 255, 255, 25, 25);
                }
                break;

            default:
                ErrorLogger.Log("ExampleMod: Unknown Message type: " + msgType);
                break;
            }
        }
 public override Compilation CreateCompilation(TextWriter consoleOutput, TouchedFileLogger touchedFilesLogger, ErrorLogger errorLogger)
 {
     Compilation = base.CreateCompilation(consoleOutput, touchedFilesLogger, errorLogger);
     return Compilation;
 }
Esempio n. 56
0
        public ActionResult SendSupportRequest(IssueObject issue)
        {
            var gVal = new GenericValidator();

            try
            {
                var importerInfo = GetLoggedOnUserInfo();
                if (importerInfo.Id < 1)
                {
                    gVal.Code  = -1;
                    gVal.Error = "Your session has timed out. Please refresh the page.";
                    return(Json(gVal, JsonRequestBehavior.AllowGet));
                }

                var validationResult = ValidateIssue(issue);

                if (validationResult.Code == 1)
                {
                    return(Json(validationResult, JsonRequestBehavior.AllowGet));
                }
                issue.IssueLogObject.DateCreated = DateTime.Now;
                issue.AffectedUserId             = importerInfo.UserProfileObject.Id;
                issue.Status = IssueStatusEnum.Pending.ToString();

                var appStatus = new IssueServices().AddIssue(issue);
                if (appStatus < 1)
                {
                    validationResult.Code  = -1;
                    validationResult.Error = "Your request/complaint could not be processed. Please try again.";
                    return(Json(validationResult, JsonRequestBehavior.AllowGet));
                }

                if (Request.Url != null)
                {
                    #region Using SendGrid

                    var config   = WebConfigurationManager.OpenWebConfiguration(HttpContext.Request.ApplicationPath);
                    var settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");

                    if (settings == null)
                    {
                        gVal.Code  = -1;
                        gVal.Error = "Internal server error. Your request could not be processed. Please try again.";
                        return(Json(gVal, JsonRequestBehavior.AllowGet));
                    }

                    var str = "<b>Issue Category : </b> " + "<b>" + issue.IssueCategoryName + "</b>";
                    str += "<b>Affected Company : </b> " + "<b>" + importerInfo.Name + "</b>";
                    str += "<b>Request/Issue : </b> " + "<b>" + issue.IssueLogObject.Issue + "</b>";

                    var mail = new MailMessage(new MailAddress(settings.Smtp.From), new MailAddress("*****@*****.**"))
                    {
                        Subject    = issue.IssueCategoryName,
                        Body       = str,
                        IsBodyHtml = true
                    };

                    var smtp = new SmtpClient(settings.Smtp.Network.Host)
                    {
                        Credentials = new NetworkCredential(settings.Smtp.Network.UserName, settings.Smtp.Network.Password),
                        EnableSsl   = true,
                        Port        = settings.Smtp.Network.Port
                    };

                    smtp.Send(mail);
                    gVal.Code  = 5;
                    gVal.Error = "Your message has been sent. Be rest assured it will be handled as soon as possible.";
                    return(Json(gVal, JsonRequestBehavior.AllowGet));

                    #endregion
                }

                gVal.Code  = -1;
                gVal.Error = "Internal server error. Your request could not be processed. Please try again.";
                return(Json(gVal, JsonRequestBehavior.AllowGet));
            }
            catch (Exception e)
            {
                ErrorLogger.LoggError(e.StackTrace, e.Source, e.Message);
                gVal.Code  = -1;
                gVal.Error = "Internal server error. Your request could not be processed. Please try again.";
                return(Json(gVal, JsonRequestBehavior.AllowGet));
            }
        }
Esempio n. 57
0
 private void PopulateFromJSON(TmodFile[] installedMods, string json)
 {
     try
     {
         JObject jsonObject   = JObject.Parse(json);
         JObject updateObject = (JObject)jsonObject["update"];
         if (updateObject != null)
         {
             updateAvailable = true;
             updateText      = (string)updateObject["message"];
             updateURL       = (string)updateObject["url"];
         }
         JArray modlist = (JArray)jsonObject["modlist"];
         foreach (JObject mod in modlist.Children <JObject>())
         {
             string displayname = (string)mod["displayname"];
             //reloadButton.SetText("Adding " + displayname + "...");
             string name      = (string)mod["name"];
             string version   = (string)mod["version"];
             string author    = (string)mod["author"];
             string download  = (string)mod["download"];
             int    downloads = (int)mod["downloads"];
             int    hot       = (int)mod["hot"];            // for now, hotness is just downloadsYesterday
             string timeStamp = (string)mod["updateTimeStamp"];
             //string[] modreferences = ((string)mod["modreferences"]).Split(',');
             string  modreferences = (string)mod["modreferences"];
             ModSide modside       = ModSide.Both;               // TODO: add filter option for modside.
             string  modsideString = (string)mod["modside"];
             if (modsideString == "Client")
             {
                 modside = ModSide.Client;
             }
             if (modsideString == "Server")
             {
                 modside = ModSide.Server;
             }
             if (modsideString == "NoSync")
             {
                 modside = ModSide.NoSync;
             }
             bool exists            = false;
             bool update            = false;
             bool updateIsDowngrade = false;
             var  installed         = installedMods.SingleOrDefault(m => m.name == name);
             if (installed != null)
             {
                 exists = true;
                 var cVersion = new Version(version.Substring(1));
                 if (cVersion > installed.version)
                 {
                     update = true;
                 }
                 else if (cVersion < installed.version)
                 {
                     update = updateIsDowngrade = true;
                 }
             }
             UIModDownloadItem modItem = new UIModDownloadItem(displayname, name, version, author, modreferences, modside, download, downloads, hot, timeStamp, update, updateIsDowngrade, installed);
             modListAll._items.Add(modItem);                     //add directly to the underlying, SortList will repopulate it anyway
         }
         SortList();
     }
     catch (Exception e)
     {
         ErrorLogger.LogModBrowserException(e);
         return;
     }
 }
Esempio n. 58
0
        public override void Process(System.Web.HttpContext context)
        {
            // NOTE: This (re)initializes a static data structure used for
            // resolving names into sector locations, so needs to be run
            // before any other objects (e.g. Worlds) are loaded.
            ResourceManager resourceManager = new ResourceManager(context.Server, context.Cache);

            //
            // Jump
            //
            int jump = Util.Clamp(GetIntOption(context, "jump", 6), 0, 12);

            //
            // Content & Coordinates
            //
            Selector selector;
            Location loc;
            if (context.Request.HttpMethod == "POST")
            {
                Sector sector;
                try
                {
                    bool lint = GetBoolOption(context, "lint", defaultValue: false);
                    ErrorLogger errors = new ErrorLogger();
                    sector = GetPostedSector(context.Request, errors);
                    if (lint && !errors.Empty)
                    {
                        SendError(context.Response, 400, "Bad Request", errors.ToString());
                    }
                }
                catch (Exception ex)
                {
                    SendError(context.Response, 400, "Bad Request", ex.Message);
                    return;
                }

                if (sector == null)
                {
                    SendError(context.Response, 400, "Bad Request", "Either file or data must be supplied in the POST data.");
                    return;
                }

                int hex = GetIntOption(context, "hex", Astrometrics.SectorCentralHex);
                loc = new Location(new Point(0, 0), hex);
                selector = new HexSectorSelector(resourceManager, sector, loc.HexLocation, jump);
            }
            else
            {
                SectorMap map = SectorMap.FromName(SectorMap.DefaultSetting, resourceManager);

                if (HasOption(context, "sector") && HasOption(context, "hex"))
                {
                    string sectorName = GetStringOption(context, "sector");
                    int hex = GetIntOption(context, "hex", 0);
                    Sector sector = map.FromName(sectorName);
                    if (sector == null)
                    {
                        SendError(context.Response, 404, "Not Found", String.Format("The specified sector '{0}' was not found.", sectorName));
                        return;
                    }

                    loc = new Location(sector.Location, hex);
                }
                else if (HasOption(context, "sx") && HasOption(context, "sy") && HasOption(context, "hx") && HasOption(context, "hy"))
                {
                    int sx = GetIntOption(context, "sx", 0);
                    int sy = GetIntOption(context, "sy", 0);
                    int hx = GetIntOption(context, "hx", 0);
                    int hy = GetIntOption(context, "hy", 0);
                    loc = new Location(map.FromLocation(sx, sy).Location, hx * 100 + hy);
                }
                else if (HasOption(context, "x") && HasOption(context, "y"))
                {
                    loc = Astrometrics.CoordinatesToLocation(GetIntOption(context, "x", 0), GetIntOption(context, "y", 0));
                }
                else
                {
                    loc = new Location(map.FromName("Spinward Marches").Location, 1910);
                }
                selector = new HexSelector(map, resourceManager, loc, jump);
            }

            //
            // Scale
            //
            double scale = Util.Clamp(GetDoubleOption(context, "scale", 64), MinScale, MaxScale);

            //
            // Options & Style
            //
            MapOptions options = MapOptions.BordersMajor | MapOptions.BordersMinor | MapOptions.ForceHexes;
            Stylesheet.Style style = Stylesheet.Style.Poster;
            ParseOptions(context, ref options, ref style);

            //
            // Border
            //
            bool border = GetBoolOption(context, "border", defaultValue: true);

            //
            // Clip
            //
            bool clip = GetBoolOption(context, "clip", defaultValue: true);

            //
            // What to render
            //

            RectangleF tileRect = new RectangleF();

            Point coords = Astrometrics.LocationToCoordinates(loc);
            tileRect.X = coords.X - jump - 1;
            tileRect.Width = jump + 1 + jump;
            tileRect.Y = coords.Y - jump - 1;
            tileRect.Height = jump + 1 + jump;

            // Account for jagged hexes
            tileRect.Y += (coords.X % 2 == 0) ? 0 : 0.5f;
            tileRect.Inflate(0.35f, 0.15f);

            Size tileSize = new Size((int)Math.Floor(tileRect.Width * scale * Astrometrics.ParsecScaleX), (int)Math.Floor(tileRect.Height * scale * Astrometrics.ParsecScaleY));

            // Construct clipping path
            List<Point> clipPath = new List<Point>(jump * 6 + 1);
            Point cur = coords;
            for (int i = 0; i < jump; ++i)
            {
                // Move J parsecs to the upper-left (start of border path logic)
                cur = Astrometrics.HexNeighbor(cur, 1);
            }
            clipPath.Add(cur);
            for (int dir = 0; dir < 6; ++dir)
            {
                for (int i = 0; i < jump; ++i)
                {
                    cur = Astrometrics.HexNeighbor(cur, (dir + 3) % 6); // Clockwise from upper left
                    clipPath.Add(cur);
                }
            }

            Stylesheet styles = new Stylesheet(scale, options, style);

            // If any names are showing, show them all
            if (styles.worldDetails.HasFlag(WorldDetails.KeyNames))
                styles.worldDetails |= WorldDetails.AllNames;

            // Compute path
            float[] edgeX, edgeY;
            RenderUtil.HexEdges(styles.hexStyle == HexStyle.Square ? PathUtil.PathType.Square : PathUtil.PathType.Hex,
                out edgeX, out edgeY);
            PointF[] boundingPathCoords;
            byte[] boundingPathTypes;
            PathUtil.ComputeBorderPath(clipPath, edgeX, edgeY, out boundingPathCoords, out boundingPathTypes);

            Render.RenderContext ctx = new Render.RenderContext();
            ctx.resourceManager = resourceManager;
            ctx.selector = selector;
            ctx.tileRect = tileRect;
            ctx.scale = scale;
            ctx.options = options;
            ctx.styles = styles;
            ctx.tileSize = tileSize;
            ctx.border = border;
            ctx.clipOutsectorBorders = true;

            // TODO: Widen path to allow for single-pixel border
            ctx.clipPath = clip ? new XGraphicsPath(boundingPathCoords, boundingPathTypes, XFillMode.Alternate) : null;
            ProduceResponse(context, "Jump Map", ctx, tileSize, transparent: clip);
        }
Esempio n. 59
0
        public ActionResult EditZone(Zone zone)
        {
            ModelState.Clear();
            ViewBag.LoadStatus = "0";
            try
            {
                if (Session["_zone"] == null)
                {
                    zone.Error     = "Session has expired";
                    zone.ErrorCode = 0;
                    return(Json(zone, JsonRequestBehavior.AllowGet));
                }

                var oldZone = Session["_zone"] as Zone;

                if (oldZone == null || oldZone.ZoneId < 1)
                {
                    zone.Error     = "Session has expired";
                    zone.ErrorCode = 0;
                    return(Json(zone, JsonRequestBehavior.AllowGet));
                }

                if (!ModelState.IsValid)
                {
                    zone.Error     = "Please supply all required fields and try again";
                    zone.ErrorCode = -1;
                    return(Json(zone, JsonRequestBehavior.AllowGet));
                }

                var wx = ValidateControl(zone);

                if (wx.Code < 1)
                {
                    zone.Error     = wx.Error;
                    zone.ErrorCode = -1;
                    return(Json(zone, JsonRequestBehavior.AllowGet));
                }

                oldZone.Name = zone.Name;

                var k = new ZoneServices().UpdateZoneCheckDuplicate(oldZone);
                if (k < 1)
                {
                    if (k == -3)
                    {
                        zone.Error     = "Zone already exists";
                        zone.ErrorCode = 0;
                        return(Json(zone, JsonRequestBehavior.AllowGet));
                    }

                    zone.Error     = "Process Failed! Please contact the Admin or try again later";
                    zone.ErrorCode = 0;
                    return(Json(zone, JsonRequestBehavior.AllowGet));
                }

                zone.Error     = "Zone Information was successfully updated";
                zone.ErrorCode = 1;
                return(Json(zone, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                ErrorLogger.LogEror(ex.StackTrace, ex.Source, ex.Message);
                zone.Error     = "An unknown error was encountered. Request could not be serviced. Please try again later.";
                zone.ErrorCode = 0;
                return(Json(zone, JsonRequestBehavior.AllowGet));
            }
        }
        public ActionResult BulkUpload(HttpPostedFileBase file)
        {
            var gVal = new GenericValidator();

            try
            {
                if (file.ContentLength > 0)
                {
                    const string folderPath = "~/BulkUploads";

                    var fileName = file.FileName;
                    var path     = Server.MapPath(folderPath + "/" + fileName);

                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path);
                    }

                    file.SaveAs(path);

                    var filePath = Server.MapPath(folderPath + "/" + "permits.json");

                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }

                    var msg               = string.Empty;
                    var errorList         = new List <long>();
                    var permits           = new List <PermitObject>();
                    var successfulUploads = ReadExcelData(path, "Permits", ref errorList, ref msg, ref permits);
                    var saveCount         = 0;
                    if (!successfulUploads.Any())
                    {
                        gVal.Code  = -1;
                        gVal.Error = msg;
                        return(Json(gVal, JsonRequestBehavior.AllowGet));
                    }

                    using (var fs = System.IO.File.Open(filePath, FileMode.CreateNew))

                        using (var sw = new StreamWriter(fs))

                            using (var jw = new JsonTextWriter(sw))
                            {
                                jw.Formatting = Formatting.Indented;
                                var serializer = new JsonSerializer();
                                serializer.Serialize(jw, permits.ToArray());
                                saveCount = permits.Count;
                            }

                    if (errorList.Any() && successfulUploads.Any())
                    {
                        var feedbackMessage = successfulUploads.Count + " records were successfully uploaded." +
                                              "\n" + errorList.Count + " record(s) could not be uploaded due to specified/unspecified errors.";
                        if (msg.Length > 0)
                        {
                            feedbackMessage += "<br/>" + msg;
                        }

                        gVal.Code  = -1;
                        gVal.Error = feedbackMessage;
                        return(Json(gVal, JsonRequestBehavior.AllowGet));
                    }

                    if (saveCount != permits.Count)
                    {
                        var feedbackMessage = saveCount + " records were successfully uploaded." +
                                              "\n" + (permits.Count - saveCount) + " record(s) could not be uploaded due to specified/unspecified errors.";
                        if (msg.Length > 0)
                        {
                            feedbackMessage += "<br/>" + msg;
                        }

                        gVal.Code  = -1;
                        gVal.Error = feedbackMessage;
                        return(Json(gVal, JsonRequestBehavior.AllowGet));
                    }

                    if (errorList.Any() && !successfulUploads.Any())
                    {
                        var feedbackMessage = errorList.Count + " record(s) could not be uploaded due to specified/unspecified errors.";
                        ViewBag.ErrorCode = -1;

                        if (msg.Length > 0)
                        {
                            feedbackMessage += "<br/>" + msg;
                        }

                        gVal.Code  = -1;
                        gVal.Error = feedbackMessage;
                        return(Json(gVal, JsonRequestBehavior.AllowGet));
                    }

                    if (!errorList.Any() && successfulUploads.Any())
                    {
                        var feedbackMessage = successfulUploads.Count + " records were successfully uploaded.";

                        if (msg.Length > 0)
                        {
                            feedbackMessage += "<br/>" + msg;
                        }

                        gVal.Code  = 5;
                        gVal.Error = feedbackMessage;
                        return(Json(gVal, JsonRequestBehavior.AllowGet));
                    }
                }
                gVal.Code  = -1;
                gVal.Error = "The selected file is invalid";
                return(Json(gVal, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                ErrorLogger.LoggError(ex.StackTrace, ex.Source, ex.Message);
                gVal.Code  = -1;
                gVal.Error = "File processing failed.";
                return(Json(gVal, JsonRequestBehavior.AllowGet));
            }
        }