Ejemplo n.º 1
0
        private LoadResult MapToLoadResult([NotNull] RazorTemplateLoadResult razorTemplateLoadResult)
        {
            if (razorTemplateLoadResult == null)
            {
                throw new ArgumentNullException(nameof(razorTemplateLoadResult));
            }

            var detail = string.Join("\n", razorTemplateLoadResult.Errors ?? new string[0]);

            Error loadError;

            switch (razorTemplateLoadResult.Status)
            {
            case RazorTemplateLoadResult.LoadResultStatus.Success:
                return(LoadResult.CreateSuccessResult());

            case RazorTemplateLoadResult.LoadResultStatus.CodeCompilationFailed:
                loadError = new RazorTemplateError(RazorTemplateErrorCodes.CodeCompilationError, detail);
                break;

            case RazorTemplateLoadResult.LoadResultStatus.CodeGenerationFailed:
                loadError = new RazorTemplateError(RazorTemplateErrorCodes.CodeGenerationError, detail);
                break;

            default:
                loadError = new RazorTemplateError(RazorTemplateErrorCodes.GeneralRazorTemplateError, detail);
                break;
            }

            return(LoadResult.CreateFailResult(loadError));
        }
Ejemplo n.º 2
0
        public async Task <ActionResult> ListaBairros(DataSourceLoadOptions loadOptions, [FromServices] IRepositoryFactory <CadBairro, CadBairroRepository> repositoryFactory)
        {
            _bairro = repositoryFactory.Create(this._inquilino);

            IEnumerable <CadBairro> lstBairros = null;

            int totalResultsCount = 0;

            try
            {
                var searchInfo = this.GetSearchInfo(loadOptions);

                lstBairros = await _bairro.ListaPaginada(searchInfo, out totalResultsCount);

                var loadResult = new LoadResult();

                loadResult.data       = lstBairros;
                loadResult.totalCount = totalResultsCount;

                return(new JsonResult(loadResult));
            }
            catch (System.Exception ex)
            {
                var erro    = AppExceptionHelper.MensagemErro = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                var detalhe = AppExceptionHelper.DetalhesErro;

                if (!string.IsNullOrEmpty(detalhe))
                {
                    throw new Exception(erro, new Exception(detalhe));
                }

                throw new Exception(erro);
            }
        }
Ejemplo n.º 3
0
        public LoadResult LoadFrom(IEnumerable <string> lines)
        {
            var regex     = new Regex(LINE_PATTERN);
            var result    = new LoadResult();
            var lineCount = 1;

            foreach (var line in lines)
            {
                if (regex.IsMatch(line))
                {
                    var info        = line.Split(",");
                    var source      = info[0].ToUpper();
                    var destination = info[1].ToUpper();

                    if (source.Equals(destination))
                    {
                        result.AddError($"CIRCULAR_REFERENCE > {source}, {destination}");
                        continue;
                    }
                    AddHub(source, destination, Convert.ToUInt32(info[2]));
                }
                else
                {
                    result.AddError($"Line [{lineCount}] input format mismatch 'string, string, uint' > {line}");
                }
                lineCount++;
            }
            return(result);
        }
Ejemplo n.º 4
0
    public IEnumerator LoadUrl(string url, Action <LoadResult> action, int timeOut = 10)
    {
        WWW   www  = new WWW(url);
        float time = Time.realtimeSinceStartup;

        while (true)
        {
            if (www.isDone)
            {
                string error = www.error;
                if (string.IsNullOrEmpty(error))
                {
                    LoadResult result = new LoadResult(LoadStatus.OK, www);
                    action(result);
                    yield break;
                }
                else
                {
                    LoadResult result = new LoadResult(LoadStatus.ERROR, www);
                    action(result);
                    yield break;
                }
            }
            else if (Time.realtimeSinceStartup - time >= timeOut && timeOut != 0)
            {
                LoadResult result = new LoadResult(LoadStatus.TIMEOUT, www);
                action(result);
                yield break;
            }
            yield return(new WaitForSeconds(1));
        }
    }
Ejemplo n.º 5
0
        public static LoadGameResult LoadSaveGameData(
            string saveName,
            string[] loadedModuleNames)
        {
            List <ModuleInfo> modules = MBSaveLoad.GetModules(loadedModuleNames);

            MBSaveLoad.InitializeAutoSaveIndex(saveName);
            string      fileName = saveName + ".sav";
            ISaveDriver driver   = MBSaveLoad._saveDriver;

            driver.SetFileName(fileName);
            ApplicationVersion applicationVersion = driver.LoadMetaData().GetApplicationVersion();

            if (applicationVersion.Major <= 1 && applicationVersion.Minor <= 4 && applicationVersion.Revision < 2)
            {
                driver = (ISaveDriver) new OldFileDriver();
                driver.SetFileName(fileName);
            }
            LoadResult loadResult = SaveManager.Load(driver, true);

            if (loadResult.Successful)
            {
                MBSaveLoad.ActiveSaveSlotName = !MBSaveLoad.IsSaveFileNameReserved(saveName) ? saveName : (string)null;
                return(new LoadGameResult(loadResult, MBSaveLoad.CheckModules(loadResult.MetaData, modules)));
            }
            Debug.Print("Error: Could not load the game!");
            return((LoadGameResult)null);
        }
Ejemplo n.º 6
0
        public static LoadResult Load(ISaveDriver driver, bool loadAsLateInitialize)
        {
            DefinitionContext definitionContext = new DefinitionContext();

            definitionContext.FillWithCurrentTypes();
            LoadContext loadContext = new LoadContext(definitionContext, driver);
            LoadData    loadData    = driver.Load();
            LoadResult  loadResult;

            if (loadContext.Load(loadData, loadAsLateInitialize))
            {
                LoadCallbackInitializator loadCallbackInitializator = (LoadCallbackInitializator)null;
                if (loadAsLateInitialize)
                {
                    loadCallbackInitializator = loadContext.CreateLoadCallbackInitializator(loadData);
                }
                loadResult = LoadResult.CreateSuccessful(loadContext.RootObject, loadData.MetaData, loadCallbackInitializator);
            }
            else
            {
                loadResult = LoadResult.CreateFailed((IEnumerable <LoadError>) new LoadError[1]
                {
                    new LoadError("Not implemented")
                });
            }
            return(loadResult);
        }
Ejemplo n.º 7
0
        private List <Triangle> getTrianglesList(LoadResult obj)
        {
            List <Triangle> TriangleLst = new List <Triangle>();
            var             faces       = obj.Groups[0].Faces;
            var             vertices    = obj.Vertices;

            for (int i = 0; i < faces.Count; i++)
            {
                var face         = faces[i];
                var vertexIndex1 = face[0].VertexIndex - 1;
                var vertex1      = new Vector3(vertices[vertexIndex1].X, vertices[vertexIndex1].Y, vertices[vertexIndex1].Z, face[0].NormalIndex);

                var vertexIndex2 = face[1].VertexIndex - 1;
                var vertex2      = new Vector3(vertices[vertexIndex2].X, vertices[vertexIndex2].Y, vertices[vertexIndex2].Z, face[1].NormalIndex);

                var vertexIndex3 = face[2].VertexIndex - 1;
                var vertex3      = new Vector3(vertices[vertexIndex3].X, vertices[vertexIndex3].Y, vertices[vertexIndex3].Z, face[2].NormalIndex);

                Triangle triangel    = new Triangle(vertex1, vertex2, vertex3);
                var      transformed = Transform(triangel);
                TriangleLst.Add(transformed);
            }

            return(TriangleLst);
        }
Ejemplo n.º 8
0
    private bool LoadAllLines(string[] lines, out bool formatChanged)
    {
        formatChanged = false;
        int num = 0;

        for (int i = 0; i < lines.Length; i++)
        {
            string line = lines[i];
            line = line.Trim();
            if ((line.Length != 0) && !line.StartsWith("#"))
            {
                int    num3;
                string str2;
                object obj2;
                bool   flag;
                if (!this.LoadLine(line, out num3, out str2, out obj2, out flag))
                {
                    Debug.LogError(string.Format("LocalOptions.LoadAllLines() - Failed to load line {0}.", i + 1));
                    num++;
                    if (num > 4)
                    {
                        this.m_loadResult = LoadResult.FAIL;
                        return(false);
                    }
                }
                else
                {
                    this.m_options[str2] = obj2;
                    formatChanged        = (formatChanged || (num3 != this.m_currentLineVersion)) || flag;
                }
            }
        }
        return(true);
    }
Ejemplo n.º 9
0
        public LoadResult <T> Load <T>(string filename)
        {
            byte[] bytes;
            try
            {
                var result = Resolver.LoadBytes(filename);
                if (!result.Succeeded)
                {
                    return(result.CreateFailed <T>());
                }
                bytes = result.value;
            }
            catch (System.Exception ex)
            {
                Debug.LogException(ex);
                return(LoadResult <T> .CreateError(ex));
            }

            try
            {
                var t = SerialzieResolver.Deserialize <T>(bytes);
                return(new LoadResult <T>(t));
            }
            catch (System.Exception ex)
            {
                Debug.LogError(filename + " broken");
                Debug.LogException(ex);
                return(LoadResult <T> .CreateFailedDeserialize(ex));
            }
        }
Ejemplo n.º 10
0
    private bool Load()
    {
        string[] strArray;
        this.Clear();
        if (!System.IO.File.Exists(this.m_path))
        {
            this.m_loadResult = LoadResult.SUCCESS;
            return(true);
        }
        if (!this.LoadFile(out strArray))
        {
            this.m_loadResult = LoadResult.FAIL;
            return(false);
        }
        bool formatChanged = false;

        if (!this.LoadAllLines(strArray, out formatChanged))
        {
            this.m_loadResult = LoadResult.FAIL;
            return(false);
        }
        foreach (string str in this.m_options.Keys)
        {
            this.m_sortedKeys.Add(str);
        }
        this.SortKeys();
        this.m_loadResult = LoadResult.SUCCESS;
        if (formatChanged)
        {
            this.m_dirty = true;
            this.Save();
        }
        return(true);
    }
Ejemplo n.º 11
0
    public void Update( )
    {
        if (_omeFileRequest)
        {
            if (!(_loaded))
            {
                Debug.Log("World: Update: parsing OME stream");

                _omeStream  = new MemoryStream(_omeFileBytes);
                _loadResult = _omeLoader.Load(_omeStream);

                Debug.Log("World: Update: OME file loaded");

                //
                // load header data
                //

                for (int i = 0; i < _loadResult.Octrees.Count; i++)
                {
                    _octrees.Add(_loadResult.Octrees[i]);
                }

                for (int i = 0; i < _loadResult.Vertices.Count; i++)
                {
                    _vertices.Add(_loadResult.Vertices[i]);
                }

                _chunks = new OmeGenerator[_octrees.Count];
                _loaded = true;
            }
        }
    }
Ejemplo n.º 12
0
        protected ModelVisual3D MakeVisualModel(LoadResult objmesh, ZipArchiveEntry texture)
        {
            var r = new ModelVisual3D();

            r.Content = MakeModel(objmesh, texture);
            Points.Freeze();               // We won't change them anymore
            Normals.Freeze();
            Indices.Freeze();
            TexCoords.Freeze();

            r.Transform = new Transform3DGroup();
            Transform3DGroup     transformGroup = r.Transform as Transform3DGroup;
            TranslateTransform3D translation    = new TranslateTransform3D(
                -(r.Content.Bounds.X + r.Content.Bounds.SizeX / 2),
                -(r.Content.Bounds.Y + r.Content.Bounds.SizeY / 2),
                -(r.Content.Bounds.Z + r.Content.Bounds.SizeZ / 2)
                );

            transformGroup.Children.Add(translation);

            double scale = Math.Abs(1 / (r.Content.Bounds.SizeX));

            scale = Math.Min(scale, Math.Abs(1 / (r.Content.Bounds.SizeY)));
            scale = Math.Min(scale, Math.Abs(1 / (r.Content.Bounds.SizeZ)));
            ScaleTransform3D scaletr = new ScaleTransform3D(scale, scale, scale);

            transformGroup.Children.Add(scaletr);

            return(r);
        }
Ejemplo n.º 13
0
        public static void load(ContentManager content, string mapName, Color floorColour, Color wallColour, out MapWalls walls, out MapFloor floor)
        {
            LoadResult loadResult = GWNorthEngine.Tools.TilePlacer.MapLoader.load(content, mapName);

            walls = loadMapWalls(wallColour, loadResult);
            floor = loadMapFloor(floorColour, loadResult);
        }
Ejemplo n.º 14
0
        //Load file, make backup if needed
        public LoadResult Load(string filename, bool autoBackup = false)
        {
            LoadResult result = LoadResult.Success;

            _fileInfo = new FileInfo(filename);
            _entries  = null;

            if (_fileInfo.Exists)
            {
                _mbm = new MBM(_fileInfo.FullName);

                string backupFilePath = _fileInfo.FullName + ".bak";
                if (File.Exists(backupFilePath))
                {
                    _mbmBackup = new MBM(backupFilePath);
                }
                else if (autoBackup || MessageBox.Show("Would you like to create a backup of " + _fileInfo.Name + "?\r\nA backup allows the Original text box to display the source text before edits were made.", "Create Backup", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    File.Copy(_fileInfo.FullName, backupFilePath);
                    _mbmBackup = new MBM(backupFilePath);
                }
                else
                {
                    _mbmBackup = null;
                }
            }
            else
            {
                result = LoadResult.FileNotFound;
            }

            return(result);
        }
Ejemplo n.º 15
0
        public LoadResult Load(string filename, bool autoBackup = false)
        {
            LoadResult result = LoadResult.Success;

            FileInfo = new FileInfo(filename);
            _entries = null;

            if (FileInfo.Exists)
            {
                _smas = new SMAS(FileInfo.OpenRead());

                string backupFilePath = FileInfo.FullName + ".bak";
                if (!File.Exists(backupFilePath))
                {
                    File.Copy(FileInfo.FullName, backupFilePath);
                }
                _smasBackup = new SMAS(File.OpenRead(backupFilePath));
            }
            else
            {
                result = LoadResult.FileNotFound;
            }

            return(result);
        }
Ejemplo n.º 16
0
 private static void GetNormals(LoadResult loadResult)
 {
     foreach (var normal in loadResult.Normals)
     {
         ObjectModel.VerticesNormals.Add(new System.Numerics.Vector3(normal.X, normal.Y, normal.Z));
     }
 }
Ejemplo n.º 17
0
 private static void GetTextures(LoadResult loadResult)
 {
     foreach (var texture in loadResult.Textures)
     {
         ObjectModel.Textures.Add(texture);
     }
 }
Ejemplo n.º 18
0
        private static List <Voxel> transformVerticesToVoxels(LoadResult result)
        {
            var    listVoxels = new List <CartesianCoordinate>();
            double resolution = 0;

            foreach (var group in result.Groups)
            {
                var faces = @group.Faces.Where(x => x.All(y => y.NormalIndex == 1));

                foreach (var face in faces)
                {
                    var x = face.Min(i => result.Vertices[i.VertexIndex - 1].X);
                    var y = face.Min(i => result.Vertices[i.VertexIndex - 1].Y);
                    var z = face.Min(i => result.Vertices[i.VertexIndex - 1].Z);

                    listVoxels.Add(new CartesianCoordinate(x, y, z));

                    if (resolution <= double.Epsilon)
                    {
                        var sibling1 = result.Vertices[face[0].VertexIndex - 1];
                        var sibling2 = result.Vertices[face[1].VertexIndex - 1];

                        resolution = Math.Max(
                            Math.Max(Math.Abs(sibling1.X - sibling2.X), Math.Abs(sibling1.Y - sibling2.Y)),
                            Math.Abs(sibling1.Z - sibling2.Z));
                    }
                }
            }

            var min = new CartesianCoordinate(listVoxels.Min(x => x.X), listVoxels.Min(x => x.Y), listVoxels.Min(x => x.Z));

            var transform = listVoxels.Select(x => new Voxel((x - min) / resolution)).ToList();

            return(transform);
        }
Ejemplo n.º 19
0
 private static void GetVertices(LoadResult loadResult)
 {
     foreach (var vertex in loadResult.Vertices)
     {
         ObjectModel.Vertices.Add(new System.Numerics.Vector3(vertex.X, vertex.Y, vertex.Z));
     }
 }
Ejemplo n.º 20
0
    public string LoadText(string sType)
    {
        List <LoadResult> oResults = new List <LoadResult>();

        using (SqlConnection oCN = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CN_INSIDER"].ConnectionString))
        {
            oCN.Open();
            using (SqlCommand oCMD = new SqlCommand())
            {
                oCMD.Connection  = oCN;
                oCMD.CommandText = "SELECT sText"
                                   + " FROM TextBoard"
                                   + " WHERE sBoard = @sBoard"
                                   + " ORDER BY dtCreated ASC";
                oCMD.Parameters.AddWithValue("@sBoard", sType);

                using (SqlDataReader oDR = oCMD.ExecuteReader())
                {
                    while (oDR.Read())
                    {
                        LoadResult oR = new LoadResult();
                        oR.sText = oDR["sText"].ToString();
                        oResults.Add(oR);
                    }
                }
            }
        }

        return(new JavaScriptSerializer().Serialize(oResults));
    }
Ejemplo n.º 21
0
        public async UniTask <LoadResult <byte[]> > LoadBytesAsync(string filename)
        {
            await UniTask.WaitWhile(() => processCount > 0);

            ++processCount;
            try
            {
                var fullPath = GetPath(filename);

                try
                {
                    using (var fileStream = System.IO.File.OpenRead(fullPath))
                    {
                        var bytes = new byte[fileStream.Length];
                        await fileStream.ReadAsync(bytes, 0, bytes.Length).AsUniTask();

                        return(new LoadResult <byte[]>(bytes));
                    }
                }
                catch (DirectoryNotFoundException ex)
                {
                    return(LoadResult <byte[]> .CreateNotFound(ex));
                }
                catch (FileNotFoundException ex)
                {
                    return(LoadResult <byte[]> .CreateNotFound(ex));
                }
            }
            finally
            {
                --processCount;
            }
        }
Ejemplo n.º 22
0
        public static void Main()
        {
            try
            {
                using (IEngine engine = EngineFactory.Create(new EngineOptions.Builder().Build()))
                {
                    Console.WriteLine("Engine created");

                    using (IBrowser browser = engine.CreateBrowser())
                    {
                        Console.WriteLine("Browser created");
                        engine.Network.CanGetCookiesHandler =
                            new Handler <CanGetCookiesParameters, CanGetCookiesResponse>(CanGetCookies);
                        engine.Network.CanSetCookieHandler =
                            new Handler <CanSetCookieParameters, CanSetCookieResponse>(CanSetCookie);
                        LoadResult result = browser.Navigation.LoadUrl("https://www.google.com").Result;
                        Console.WriteLine("LoadResult: " + result);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Console.WriteLine("Press any key to terminate...");
            Console.ReadKey();
        }
Ejemplo n.º 23
0
        public LoadResult Load(string filename)
        {
            LoadResult result = LoadResult.Success;

            _fileInfo = new FileInfo(filename);

            if (_fileInfo.Exists)
            {
                using (var br = new BinaryReaderX(File.OpenRead(_fileInfo.FullName)))
                    if (br.ReadString(4) == "CTPK")
                    {
                        _ctpk = new CTPK(_fileInfo.FullName);
                    }
                    else
                    {
                        _ctpk = new CTPK(_fileInfo.FullName, true);
                    }
            }
            else
            {
                result = LoadResult.FileNotFound;
            }

            return(result);
        }
Ejemplo n.º 24
0
        public static LoadResult LoadLobbies(List <Filter> filtersList)
        {
            List <Lobby>        lobbies;
            List <Lobby>        matchingLobbies;
            List <DisplayLobby> displayLobbies;
            List <Player>       players;

            LoadResult loadResult = new LoadResult();
            LobbyStats stats      = new LobbyStats();

            try
            {
                lobbies         = Fetcher.GetLobbies();
                matchingLobbies = Matching.GetMatchingLobbies(lobbies, filtersList);
                displayLobbies  = LobbyToDisplayLobbyConverter.FromLobbies(matchingLobbies);
                players         = lobbies.SelectMany(l => l.Players.Where(p => p != null && !string.IsNullOrWhiteSpace(p.Name))).ToList();
            }
            catch (Exception ex)
            {
                loadResult.ErrorMessage = "Error updating lobbies:\r\n" + ex.Message + "\r\n" + ex.StackTrace;
                return(loadResult);
            }

            stats.TotalLobbies    = lobbies.Count;
            stats.MatchingLobbies = displayLobbies.Count;
            stats.TotalPlayers    = players.Count;

            loadResult.LobbyStats     = stats;
            loadResult.DisplayLobbies = displayLobbies;

            return(loadResult);
        }
Ejemplo n.º 25
0
        protected void DefaultResourceCallBack(LoadResult result)
        {
            string assetName = string.Empty;

            if (result.assetNames != null && result.assetNames.Length > 0)
            {
                assetName = result.assetNames[0];
            }

            if (!assetName.IsNE() && this.m_vResourceCallBackDic.ContainsKey(assetName))
            {
                List <LoadAssetCallback> callBacks = m_vResourceCallBackDic[assetName];
                if (callBacks != null && callBacks.Count > 0)
                {
                    for (int i = callBacks.Count - 1; i >= 0; i--)
                    {
                        callBacks[i].Invoke(result);
                        callBacks.RemoveAt(i);
                    }
                }
                if (callBacks.Count == 0)
                {
                    this.m_vResourceCallBackDic.ForceRemove(assetName);
                }
            }
        }
Ejemplo n.º 26
0
        protected void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                if (!connect)
                {
                    return;
                }
                string code = port.ReadExisting();

                while (code.IndexOf("\u001d") != -1)
                {
                    code = code.Replace("\u001d", "и");
                }

                if (SetResult(FormingOrder(code), _Orders, false))
                {
                    LoadResult?.Invoke(_Orders);
                }
            }
            catch (Exception Ex)
            {
                SystemArgs.PrintLog(Ex.ToString());
                MessageBox.Show(Ex.Message);
            }
        }
Ejemplo n.º 27
0
        private void GetModelRawData(LoadResult model, float[] vertices, float[] uvCoordinates, int[] indices)
        {
            int vertexNr = 0;

            foreach (var vertex in model.Vertices)
            {
                vertices[vertexNr++] = vertex.X;
                vertices[vertexNr++] = vertex.Y;
                vertices[vertexNr++] = vertex.Z;
            }

            int indexNr = 0;

            foreach (var group in model.Groups)
            {
                foreach (var face in group.Faces)
                {
                    for (int faceVertexIndex = 0; faceVertexIndex < face.Count; faceVertexIndex++)
                    {
                        var faceVertex   = face[faceVertexIndex];
                        var vertexIndex  = faceVertex.VertexIndex - 1;
                        var uvIndex      = vertexIndex * 2u;
                        var textureIndex = faceVertex.TextureIndex - 1;
                        indices[indexNr++]         = vertexIndex;
                        uvCoordinates[uvIndex]     = model.Textures[textureIndex].X;
                        uvCoordinates[uvIndex + 1] = model.Textures[textureIndex].Y;
                    }
                }
            }
        }
Ejemplo n.º 28
0
        protected Model3D MakeModel(LoadResult objmesh, ZipArchiveEntry texture)
        {
            GeometryModel3D ret = new GeometryModel3D(MakeGeometry(objmesh), MakeMaterial(objmesh, texture));

            ret.BackMaterial = MakeBackMaterial();
            return(ret);
        }
Ejemplo n.º 29
0
        public VMAPLoadResult LoadMap(uint mapId, uint x, uint y)
        {
            var result = VMAPLoadResult.Ignored;

            if (IsMapLoadingEnabled())
            {
                LoadResult parentLoadResult = LoadSingleMap(mapId, x, y);
                if (parentLoadResult == LoadResult.Success || parentLoadResult == LoadResult.FileNotFound)
                {
                    if (parentLoadResult == LoadResult.Success)
                    {
                        result = VMAPLoadResult.OK;
                    }
                    // else VMAP_LOAD_RESULT_IGNORED

                    var childMaps = iChildMapData.LookupByKey(mapId);
                    foreach (uint childMapId in childMaps)
                    {
                        LoadResult childLoadResult = LoadSingleMap(childMapId, x, y);
                        if (childLoadResult != LoadResult.Success && childLoadResult != LoadResult.FileNotFound)
                        {
                            result = VMAPLoadResult.Error;
                        }
                    }
                }
                else
                {
                    result = VMAPLoadResult.Error;
                }
            }

            return(result);
        }
Ejemplo n.º 30
0
        public async Task <PEFile> GetPEFileAsync()
        {
            LoadResult loadResult = await loadingTask.ConfigureAwait(false);

            if (loadResult is LoadResult.Successful success)
            {
                return(success.PEFile);
            }
            else if (loadResult is LoadResult.FileNotFound)
            {
                string fileName = loadResult.File.FullName;
                throw new FileNotFoundException(message: "The assembly or package file \"" + fileName + "\" could not be found.", fileName: fileName);
            }
            else if (loadResult is LoadResult.PackageFallback package)
            {
                string fileName = loadResult.File.FullName;
                throw new InvalidOperationException(message: "The file \"" + fileName + "\" was loaded as a package, not a PE file.", innerException: package.PEFileLoadException);
            }
            else if (loadResult is LoadResult.Failed failed)
            {
                string fileName = loadResult.File.FullName;
                throw new InvalidOperationException(message: "The assembly or package file \"" + fileName + "\" could not be loaded.", innerException: failed.PackageLoadException);
            }
            else
            {
                throw new InvalidOperationException(message: "Unexpected LoadResult type: " + loadResult?.GetType().FullName);
            }
        }
Ejemplo n.º 31
0
 public TextureLoader(string name, string basedir)
 {
     try
     {
         using (var stream = ObtainStream(name, basedir, out _actualLocation))
         {
             Debug.Assert(stream != null);
             SetFromStream(stream);
         }
     }
     catch(Exception) 
     {
         _result = LoadResult.FileNotFound;
     }
 }
Ejemplo n.º 32
0
		public LoadResult Load(string rootDir = null)
		{
			LoadResult rlt = new LoadResult();
			if (rootDir == null)
			{
				rootDir = RootDir;
			}
			else
			{
				RootDir = rootDir;
			}
			if (!Directory.Exists(RootDir))
			{
				rlt.LastError = new DirectoryNotFoundException(RootDir);
			}
			else
			{
				string[] dirs = Directory.GetDirectories(rootDir);
				foreach (string i in dirs)
				{
					//DirectoryInfo di = new DirectoryInfo(i);
					string name = i.PathLastName();
					EntityGroup g = StorageManager.Instance.Create(name);
					if (g != null)
					{
						foreach (string j in Directory.EnumerateFiles(i))
						{
							Entity e = LoadEntity(j, false);
							if (e != null)
							{
								g.AddEntity(e);
							}
						}
					}
				}
				rlt.Result = StorageManager.Instance;
			}
			return rlt;
		}
Ejemplo n.º 33
0
 protected TextureLoader()
 {
     _result = LoadResult.UnknownFileFormat;
 }
Ejemplo n.º 34
0
        protected void SetFromStream(Stream stream)
        {
            // try loading using standard .net first
            try
            {
                // We need to copy the stream over to a new, in-memory bitmap to
                // avoid keeping the input stream open.
                // See http://support.microsoft.com/kb/814675/en-us
                using(var img = Image.FromStream(stream))
                {
                    _image = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppArgb);

                    using (var gfx = Graphics.FromImage(_image))
                    {
                        gfx.DrawImage(img, 0, 0, img.Width, img.Height);
                    }

                    _result = LoadResult.Good;
                }         
            }
            catch (Exception)
            {
                // if this fails, load using DevIL
                using (var imp = new DevIL.ImageImporter())
                {
                    try
                    {
                        using(var devilImage = imp.LoadImageFromStream(stream))
                        {
                            devilImage.Bind();

                            var info = DevIL.Unmanaged.IL.GetImageInfo();
                            var bitmap = new Bitmap(info.Width, info.Height, PixelFormat.Format32bppArgb);
                            var rect = new Rectangle(0, 0, info.Width, info.Height);
                            var data = bitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

                            DevIL.Unmanaged.IL.CopyPixels(0, 0, 0, info.Width, info.Height, 1, DataFormat.BGRA, DataType.UnsignedByte, data.Scan0);

                            bitmap.UnlockBits(data);
                            _image = bitmap;
                            _result = LoadResult.Good;
                        }                
                    }
                    catch (Exception)
                    {
                        // TODO any other viable fall back image loaders?
                        _result = LoadResult.UnknownFileFormat;
                    }
                }
            }
        }
Ejemplo n.º 35
0
        public LoadResult LoadEntityModelFromCSProj(string csprojFilePath, NHConfigFile nhConfigFile)
        {
            _progress.SetCurrentState("Loading Entities From Visual Studio Project", ProgressState.Normal);

            EntityLoader entityLoader = new EntityLoader(new FileController());

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(fileController.ReadAllText(csprojFilePath));
            CSProjFile csProjFile = new CSProjFile(doc, csprojFilePath);
            var hbmFiles = GetHBMFilesFromCSProj(csProjFile);

            if (IsFluentProject(csProjFile))
            {
                ArchAngel.Interfaces.SharedData.CurrentProject.SetUserOption("UseFluentNHibernate", true);
                string tempFluentPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Visual NHibernate" + Path.DirectorySeparatorChar + "Temp" + Path.DirectorySeparatorChar + "FluentTemp");
                var fluentHbmFiles = GetHBMFilesForFluentFromCSProj(csProjFile, tempFluentPath);
                // Combine the actual HBM files with the ones derived from FluentNH
                hbmFiles = hbmFiles.Union(fluentHbmFiles);
            }
            else
                ArchAngel.Interfaces.SharedData.CurrentProject.SetUserOption("UseFluentNHibernate", false);

            var csFiles = GetCSharpFilesFromCSProj(doc, csprojFilePath);
            var nhvFiles = GetNHVFilesFromCSProj(doc, csprojFilePath);

            //NHConfigFile nhConfigFile = GetNhConfigFile(csProjFile, fileController);

            var databaseConnector = nhConfigFile == null ? null : nhConfigFile.DatabaseConnector;

            //////// GFH
            // We need to fetch ALL tables, because HBM mappings don't include association tables, or at least it's difficult to find them.
            List<SchemaData> tablesToFetch = null;// entityLoader.GetTablesFromHbmFiles(hbmFiles);

            IDatabaseLoader loader = null;
            IDatabase database = null;

            if (databaseConnector != null)
                database = GetDatabase(databaseConnector, out loader, tablesToFetch);

            _progress.SetCurrentState("Parsing your existing Model Project", ProgressState.Normal);
            var parseResults = ParseResults.ParseCSharpFiles(csFiles);

            _progress.SetCurrentState("Loading Mapping Information From NHibernate Mapping Files", ProgressState.Normal);
            var mappingSet = entityLoader.GetEntities(hbmFiles, parseResults, database);
            entityLoader.ApplyConstraints(mappingSet, nhvFiles, parseResults);

            #region Create References

            // Get a set of all Guids for tables that we will want to create references from
            HashSet<Guid> existingTables = new HashSet<Guid>(database.Tables.Select(t => t.InternalIdentifier));

            foreach (var mappedTable in mappingSet.Mappings.Select(m => m.FromTable))
                existingTables.Add(mappedTable.InternalIdentifier);

            HashSet<Guid> processedRelationships = new HashSet<Guid>();
            foreach (var table in database.Tables)
            {
                foreach (var directedRel in table.DirectedRelationships)
                {
                    var relationship = directedRel.Relationship;

                    if (processedRelationships.Contains(relationship.InternalIdentifier))
                        continue; // Skip relationships that have already been handled.
                    if (relationship.MappedReferences().Any())
                        continue; // Skip relationships that have been mapped by the user.
                    if (existingTables.Contains(directedRel.ToTable.InternalIdentifier) == false)
                        continue; // Skip relationships that have tables that have no mapped Entity

                    if (relationship.PrimaryTable.MappedEntities().FirstOrDefault() == null ||
                        relationship.ForeignTable.MappedEntities().FirstOrDefault() == null)
                    {
                        continue;
                    }
                    ArchAngel.Providers.EntityModel.Controller.MappingLayer.MappingProcessor.ProcessRelationshipInternal(mappingSet, relationship, new ArchAngel.Providers.EntityModel.Controller.MappingLayer.OneToOneEntityProcessor());
                    processedRelationships.Add(relationship.InternalIdentifier);
                }
            }
            #endregion

            foreach (var entity in mappingSet.EntitySet.Entities)
                foreach (var reference in entity.References)
                    if (!mappingSet.EntitySet.References.Contains(reference))
                        mappingSet.EntitySet.AddReference(reference);

            LoadResult result = new LoadResult();
            result.MappingSet = mappingSet;
            result.DatabaseLoader = loader;
            result.NhConfigFile = nhConfigFile;
            result.CsProjFile = csProjFile;
            return result;
        }