Exemplo n.º 1
0
        public void ParsesDataFromFile()
        {
            var dataBefore = new ExportedData
            {
                BaseBu     = Guid.NewGuid(),
                RecordSets = new List <ExportEntity>
                {
                    new ExportEntity {
                        Id = Guid.NewGuid()
                    },
                    new ExportEntity {
                        Id = Guid.NewGuid()
                    },
                    new ExportEntity {
                        Id = Guid.NewGuid()
                    }
                }
            };

            DataWriterService.WriteDataToFile(dataBefore, WorkingDirectory);

            var dataAfter = DataReaderService.ParseDataFromFile(WorkingDirectory);

            Assert.AreEqual(3, dataAfter.RecordSets.Count);
        }
Exemplo n.º 2
0
        public static void ExportAsCsv(String a_FilePath, ExportedData a_Data)
        {
            StreamWriter file = new StreamWriter(a_FilePath);

            for (int i = 0; i < a_Data.Rows.Length; i++)
            {
                ExportedRow   currRow = a_Data.Rows[i];
                StringBuilder sb      = new StringBuilder();

                for (int j = 0; j < currRow.Cells.Length; j++)
                {
                    if (j != 0)
                    {
                        sb.Append(",");
                    }

                    String text = currRow.Cells[j];
                    sb.Append(CsvEncode(text));
                }

                file.WriteLine(sb.ToString());
            }

            file.Close();
        }
        public void WriteDataToFile(ExportedData data, string directory)
        {
            var json = JsonConvert.SerializeObject(data, Formatting.None, new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                TypeNameHandling  = TypeNameHandling.None,
                Formatting        = Formatting.None
            });

            FileManager.StoreJsonConfig(json, "ExportedData", directory);
        }
Exemplo n.º 4
0
        public static void ExportAsHtml(String a_FilePath, ExportedData a_Data)
        {
            StreamWriter file = new StreamWriter(a_FilePath);

            file.WriteLine("<html>");
            file.WriteLine("\t<style type=\"text/css\">");
            file.WriteLine("\ttable {");
            file.WriteLine("\tborder-bottom-color: #c3c3c3;");
            file.WriteLine("\tborder-bottom-style: solid;");
            file.WriteLine("\tborder-bottom-width: 1px;");
            file.WriteLine("\tborder-collapse: collapse;");
            file.WriteLine("\tborder-left-color: #c3c3c3;");
            file.WriteLine("\tborder-left-style: solid;");
            file.WriteLine("\tborder-left-width: 1px;");
            file.WriteLine("\tborder-right-color: #c3c3c3;");
            file.WriteLine("\tborder-right-style: solid;");
            file.WriteLine("\tborder-right-width: 1px;");
            file.WriteLine("\tborder-top-color: #c3c3c3;");
            file.WriteLine("\tborder-top-style: solid;");
            file.WriteLine("\tborder-top-width: 1px;");
            file.WriteLine("</style>");
            file.WriteLine("</head>");

            file.WriteLine("<body>");
            file.WriteLine("<table cellspacing=\"0\" cellpadding=\"0\" border=\"1\">");

            for (int i = 0; i < a_Data.Rows.Length; i++)
            {
                ExportedRow currRow = a_Data.Rows[i];
                file.WriteLine("\t<tr bgcolor=\"#{0:X2}{1:X2}{2:X2}\">", currRow.Color.R, currRow.Color.G, currRow.Color.B);

                for (int j = 0; j < currRow.Cells.Length; j++)
                {
                    HorizontalAlignment align = a_Data.Aligns[j];
                    String text = currRow.Cells[j];
                    file.WriteLine("\t\t<td align=\"{0}\">{1}</td>", GetHtmlAlignName(align), HtmlEncode(text));
                }

                file.WriteLine("\t</tr>");
            }

            file.WriteLine("</table>");
            file.WriteLine("</body>");
            file.WriteLine("</html>");

            file.Close();
        }
        public void WritesDataToFile()
        {
            Assert.IsFalse(FileManager.FileSystem.File.Exists(@"C:\ExportedData\ExportedData.json"));

            var exportedData = new ExportedData();

            exportedData.RecordSets = new List <ExportEntity>
            {
                new ExportEntity
                {
                    Id = Guid.NewGuid()
                }
            };

            DataWriterService.WriteDataToFile(exportedData, @"C:\ExportedData\");

            Assert.IsTrue(FileManager.FileSystem.File.Exists(@"C:\ExportedData\ExportedData.json"));
        }
        public List <Entity> TransformDataForCrm(ExportedData exportedData)
        {
            var data = exportedData.RecordSets;

            return(TransformExportedEntityList(data));
        }
 public DataWriterService(IOrganizationService service, IFileManager fileManager)
 {
     Service      = service ?? throw new ArgumentNullException(nameof(service));
     ExportedData = new ExportedData();
     FileManager  = fileManager ?? new FileManager();
 }
Exemplo n.º 8
0
        public bool ImportRecords(string rawData)
        {
            var splitRawData = rawData.Split(new[] { "<|||>" }, StringSplitOptions.RemoveEmptyEntries);

            if (!splitRawData.Any())
            {
                throw new Exception("Data given is empty.");
            }

            var rawStringData = splitRawData[0];

            if (splitRawData.Length > 1 && splitRawData[1] == "TRUE")
            {
                data = Helpers.Helpers.Decompress <ExportedData>(rawStringData);

                if (splitRawData.Length > 2)
                {
                    options = ImportOptions.FromJson(splitRawData[2]);
                }
            }
            else
            {
                data = Helpers.Helpers.Deserialise <ExportedData>(Encoding.UTF8.GetBytes(rawStringData));
            }

            if (data?.EntityDefinition == null)
            {
                log.LogWarning("Import data is empty, skipping ...");
                return(true);
            }

            log.Log($"Importing {data.EntityDefinition?.Count} records.");
            log.Log($"Importing {data.RelationDefinition?.Count} relations.");

            Initialise();

            ProcessObsoleteRecordsRemoval();

            var dependencyRequests = ProcessDependencies(recordsMap.Values.ToArray()).ToList();

            var requests = GetSyncRequests();

            idsMap = requests
                     .ToDictionary(e => GetIdFromRequestResponse(e) ?? Guid.Empty, e => GetIdFromRequestResponse(e) ?? Guid.Empty);

            foreach (var key in recordsMap.Keys.Except(idsMap.Keys))
            {
                idsMap[key] = key;
            }

            idsMap[Guid.Empty] = Guid.Empty;

            var keyedRecords = recordsMap
                               .Where(e => e.Value.IsUseAlternateKeys && e.Value.Record.KeyAttributes.Any())
                               .Select(e => e.Value.Record).ToArray();

            log.Log($"Clearing IDs of ${keyedRecords.Length} keyed records ...");
            foreach (var record in keyedRecords)
            {
                record.Id = Guid.Empty;
            }

            var responses = ExecuteRequests(requests, "Failed in record sync step.");

            MapOldIdsToNewIds(requests, responses.Values);

            UpdateRelationRequestIds();
            ProcessObsoleteRelationsRemoval();

            UpdateLookupRequestIds(dependencyRequests);
            ExecuteRequests(dependencyRequests.Cast <OrganizationRequest>().ToList(),
                            "Failed in lookup dependencies update step.");

            var associateRequests = CreateAssociateRequests().ToArray();

            ExecuteRequests(associateRequests.Cast <OrganizationRequest>().ToList(), "Failed in association step.",
                            faultMessage => faultMessage != null && !faultMessage.Contains("Cannot insert duplicate key"));

            return(true);
        }
Exemplo n.º 9
0
        private void RecursiveSearch(GameObject root, ExportedData data)
        {
            if (!root.activeInHierarchy)
            {
                return;
            }

            Component[] comps = root.GetComponents <Component>();

            for (int i = 0; i < comps.Length; i++)
            {
                Component comp = comps[i];
                if (comp == null)
                {
                    continue;
                }

                if (comp is MeshRenderer)
                {
                    MeshRenderer meshRen = (MeshRenderer)comp;
                    MeshFilter   filter  = comps.FirstOrDefault(c => c is MeshFilter) as MeshFilter;
                    if (filter == null)
                    {
                        continue;
                    }

                    Mesh mesh = filter.sharedMesh;
                    if (mesh == null)
                    {
                        continue;
                    }

                    // Only export the mesh if we never exported this one mesh
                    if (!meshesExported.Contains(mesh))
                    {
                        meshesExported.Add(mesh);
                    }

                    ExportedObject exp = data.exportedObjs.FirstOrDefault(c => c.GameObject == root);
                    if (exp == null)
                    {
                        exp            = new ExportedObject();
                        exp.GameObject = root;
                        data.exportedObjs.Add(exp);
                    }
                    exp.Mesh = mesh;

                    // export textures
                    if (lightmapExportType != LightmapExportType.BakedMaterial && exportMaterials) // if were baking we dont need the original textures
                    {
                        Material[] mats = meshRen.sharedMaterials;
                        for (int j = 0; j < mats.Length; j++)
                        {
                            Material mat = mats[j];
                            if (mat == null)
                            {
                                continue;
                            }

                            Shader shader = mat.shader;
                            int    props  = ShaderUtil.GetPropertyCount(shader);
                            for (int k = 0; k < props; k++)
                            {
                                string name = ShaderUtil.GetPropertyName(shader, k);

                                if (ShaderUtil.GetPropertyType(shader, k) == ShaderUtil.ShaderPropertyType.TexEnv)
                                {
                                    if (mainTexSemantics.Contains(name.ToLower()))
                                    {
                                        Texture2D tex = (Texture2D)mat.GetTexture(name);
                                        if (tex == null)
                                        {
                                            continue;
                                        }

                                        exp.DiffuseMapTex = tex;
                                        if (!texturesExported.Contains(tex))
                                        {
                                            texturesExported.Add(tex);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    int lightMap = meshRen.lightmapIndex;
                    if (lightMap != -1)
                    {
                        // Register mesh for lightmap render
                        List <GameObject> toRender;
                        if (!lightmapped.TryGetValue(lightMap, out toRender))
                        {
                            toRender = new List <GameObject>();
                            lightmapped.Add(lightMap, toRender);
                        }

                        toRender.Add(root);
                    }
                }
                else if (comp is Collider)
                {
                    Collider col = (Collider)comp;

                    ExportedObject exp = data.exportedObjs.FirstOrDefault(c => c.GameObject == root);
                    if (exp == null)
                    {
                        exp            = new ExportedObject();
                        exp.GameObject = root;
                        data.exportedObjs.Add(exp);
                    }
                    exp.Col = col;
                }
            }

            foreach (Transform child in root.transform)
            {
                RecursiveSearch(child.gameObject, data);
            }
        }
Exemplo n.º 10
0
        private void PreExport()
        {
            Clean();

            texturesExported     = new List <Texture2D>();
            texturesExportedData = new List <TextureExportData>();

            meshesExported     = new List <Mesh>();
            meshesExportedData = new List <MeshExportData>();
            meshesNames        = new Dictionary <Mesh, string>();
            meshesCount        = 0;

            Scene scene = SceneManager.GetActiveScene();

            GameObject[] roots = scene.GetRootGameObjects();

            lightmapped = new Dictionary <int, List <GameObject> >();
            exported    = new ExportedData();

            for (int i = 0; i < roots.Length; i++)
            {
                RecursiveSearch(roots[i], exported);
            }

            if (exportSkybox)
            {
                // look for skybox and grab all 6 textures if it's 6-sided
                Material skybox = RenderSettings.skybox;
                if (skybox != null)
                {
                    bool proceed = true;
                    for (int i = 0; i < skyboxTexNames.Length; i++)
                    {
                        if (!skybox.HasProperty(skyboxTexNames[i]))
                        {
                            proceed = false;
                        }
                    }

                    if (proceed)
                    {
                        for (int i = 0; i < skyboxTexNames.Length; i++)
                        {
                            Texture2D tex = (Texture2D)skybox.GetTexture(skyboxTexNames[i]);
                            if (!texturesExported.Contains(tex))
                            {
                                texturesExported.Add(tex);
                            }
                        }
                    }
                }
            }

            if (lightmapExportType != LightmapExportType.None &&
                lightmapped.Count > 0)
            {
                string scenePath = scene.path;
                scenePath = Path.GetDirectoryName(scenePath);
                string lightMapsFolder = Path.Combine(scenePath, scene.name);

                switch (lightmapExportType)
                {
                case LightmapExportType.BakedMaterial:
                    #region Baked
                {
                    // only load shader now, so if the user is not exporting lightmaps
                    // he doesn't need to have it on his project folder
                    Shader lightMapShader = Shader.Find("Hidden/LMapBaked");
                    AssertShader(lightMapShader);

                    Material lightMap = new Material(lightMapShader);
                    lightMap.SetPass(0);

                    // export lightmaps
                    int lmap = 0;
                    foreach (var lightPair in lightmapped)
                    {
                        int id = lightPair.Key;
                        List <GameObject> toRender = lightPair.Value;

                        // get the path to the lightmap file
                        string    lightMapFile = Path.Combine(lightMapsFolder, "Lightmap-" + id + "_comp_light.exr");
                        Texture2D texture      = AssetDatabase.LoadAssetAtPath <Texture2D>(lightMapFile);
                        if (texture == null)
                        {
                            continue;
                        }

                        lightMap.SetTexture("_LightMapTex", texture);

                        for (int i = 0; i < toRender.Count; i++)
                        {
                            GameObject   obj      = toRender[i];
                            MeshRenderer renderer = obj.GetComponent <MeshRenderer>();
                            MeshFilter   filter   = obj.GetComponent <MeshFilter>();

                            Mesh      mesh  = filter.sharedMesh;
                            Transform trans = obj.transform;
                            Matrix4x4 world = Matrix4x4.TRS(trans.position, trans.rotation, trans.lossyScale);

                            Vector4 scaleOffset = renderer.lightmapScaleOffset;
                            float   width       = (1 - scaleOffset.z) * scaleOffset.x;
                            float   height      = (1 - scaleOffset.w) * scaleOffset.y;
                            float   size        = Math.Max(width, height);

                            int lightMapSize = (int)(maxLightMapResolution * size);
                            lightMapSize = (int)Math.Pow(2, Math.Ceiling(Math.Log(lightMapSize) / Math.Log(2)));
                            lightMapSize = Math.Min(maxLightMapResolution, Math.Max(lightMapSize, 16));

                            RenderTexture renderTexture = RenderTexture.GetTemporary(lightMapSize, lightMapSize, 0, RenderTextureFormat.ARGB32);
                            Graphics.SetRenderTarget(renderTexture);
                            GL.Clear(true, true, new Color(0, 0, 0, 0));         // clear to transparent

                            Material[] mats = renderer.sharedMaterials;
                            for (int j = 0; j < mats.Length; j++)
                            {
                                Material mat = mats[j];

                                lightMap.SetTexture("_MainTex", null);

                                Shader shader = mat.shader;
                                int    props  = ShaderUtil.GetPropertyCount(shader);
                                for (int k = 0; k < props; k++)
                                {
                                    string name = ShaderUtil.GetPropertyName(shader, k);

                                    if (ShaderUtil.GetPropertyType(shader, k) == ShaderUtil.ShaderPropertyType.TexEnv)
                                    {
                                        if (mainTexSemantics.Contains(name.ToLower()))
                                        {
                                            // main texture texture
                                            lightMap.SetTexture("_MainTex", mat.GetTexture(name));
                                        }
                                    }
                                }

                                lightMap.SetVector("_LightMapUV", renderer.lightmapScaleOffset);
                                lightMap.SetPass(0);
                                Graphics.DrawMeshNow(mesh, world, j);
                            }

                            // This is the only way to access data from a RenderTexture
                            Texture2D tex = new Texture2D(renderTexture.width, renderTexture.height);
                            tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0);
                            tex.name = "Lightmap" + lmap;
                            tex.Apply();         // send the data back to the GPU so we can draw it on the preview area

                            if (!texturesExported.Contains(tex))
                            {
                                texturesExported.Add(tex);
                            }

                            ExportedObject eobj = exported.exportedObjs.First(c => c.GameObject == obj);
                            eobj.DiffuseMapTex = tex;

                            Graphics.SetRenderTarget(null);
                            RenderTexture.ReleaseTemporary(renderTexture);

                            lmap++;
                        }
                    }
                    UnityEngine.Object.DestroyImmediate(lightMap);
                }
                    #endregion
                    break;

                case LightmapExportType.Packed:
                    #region Packed
                {
                    Shader lightMapShader = Shader.Find("Hidden/LMapPacked");
                    AssertShader(lightMapShader);

                    Material lightMap = new Material(lightMapShader);
                    lightMap.SetPass(0);

                    // just pass the textures forward
                    // export lightmaps
                    foreach (var lightPair in lightmapped)
                    {
                        int id = lightPair.Key;
                        List <GameObject> toRender = lightPair.Value;

                        // get the path to the lightmap file
                        string    lightMapFile = Path.Combine(lightMapsFolder, "Lightmap-" + id + "_comp_light.exr");
                        Texture2D texture      = AssetDatabase.LoadAssetAtPath <Texture2D>(lightMapFile);
                        if (texture == null)
                        {
                            continue;
                        }

                        lightMap.SetTexture("_LightMapTex", texture);

                        // We need to access unity_Lightmap_HDR to decode the lightmap,
                        // but we can't, so we have to render everything to a custom RenderTexture!
                        Texture2D decTex = new Texture2D(texture.width, texture.height);
                        decTex.name = "Lightmap" + id;
                        texturesExported.Add(decTex);

                        RenderTexture renderTexture = RenderTexture.GetTemporary(texture.width, texture.height);
                        Graphics.SetRenderTarget(renderTexture);
                        GL.Clear(true, true, new Color(0, 0, 0, 0));         // clear to transparent

                        for (int i = 0; i < toRender.Count; i++)
                        {
                            GameObject   obj      = toRender[i];
                            MeshRenderer renderer = obj.GetComponent <MeshRenderer>();
                            MeshFilter   filter   = obj.GetComponent <MeshFilter>();

                            Mesh      mesh  = filter.sharedMesh;
                            Transform trans = obj.transform;
                            Matrix4x4 world = Matrix4x4.TRS(trans.position, trans.rotation, trans.lossyScale);

                            lightMap.SetVector("_LightMapUV", renderer.lightmapScaleOffset);
                            lightMap.SetPass(0);
                            Graphics.DrawMeshNow(mesh, Matrix4x4.identity);

                            ExportedObject eobj = exported.exportedObjs.First(c => c.GameObject == obj);
                            eobj.LightMapTex = decTex;
                        }

                        decTex.ReadPixels(new Rect(0, 0, decTex.width, decTex.height), 0, 0);
                        decTex.Apply();         // send the data back to the GPU so we can draw it on the preview area

                        Graphics.SetRenderTarget(null);
                        RenderTexture.ReleaseTemporary(renderTexture);
                    }
                    UObject.DestroyImmediate(lightMap);
                }
                    #endregion
                    break;

                case LightmapExportType.Unpacked:
                    #region Unpacked
                {
                    Shader lightMapShader = Shader.Find("Hidden/LMapUnpacked");
                    AssertShader(lightMapShader);

                    Material lightMap = new Material(lightMapShader);
                    lightMap.SetPass(0);

                    // export lightmaps
                    int lmap = 0;
                    foreach (var lightPair in lightmapped)
                    {
                        int id = lightPair.Key;
                        List <GameObject> toRender = lightPair.Value;

                        // get the path to the lightmap file
                        string    lightMapFile = Path.Combine(lightMapsFolder, "Lightmap-" + id + "_comp_light.exr");
                        Texture2D texture      = AssetDatabase.LoadAssetAtPath <Texture2D>(lightMapFile);
                        if (texture == null)
                        {
                            continue;
                        }

                        lightMap.SetTexture("_LightMapTex", texture);

                        for (int i = 0; i < toRender.Count; i++)
                        {
                            GameObject   obj      = toRender[i];
                            MeshRenderer renderer = obj.GetComponent <MeshRenderer>();
                            MeshFilter   filter   = obj.GetComponent <MeshFilter>();

                            Mesh      mesh  = filter.sharedMesh;
                            Transform trans = obj.transform;
                            Matrix4x4 world = Matrix4x4.TRS(trans.position, trans.rotation, trans.lossyScale);

                            Vector4 scaleOffset = renderer.lightmapScaleOffset;
                            float   width       = (1 - scaleOffset.z) * scaleOffset.x;
                            float   height      = (1 - scaleOffset.w) * scaleOffset.y;
                            float   size        = Math.Max(width, height);

                            int lightMapSize = (int)(maxLightMapResolution * size);
                            lightMapSize = (int)Math.Pow(2, Math.Ceiling(Math.Log(lightMapSize) / Math.Log(2)));
                            lightMapSize = Math.Min(maxLightMapResolution, Math.Max(lightMapSize, 16));

                            RenderTexture renderTexture = RenderTexture.GetTemporary(lightMapSize, lightMapSize, 0, RenderTextureFormat.ARGB32);
                            Graphics.SetRenderTarget(renderTexture);
                            GL.Clear(true, true, new Color(0, 0, 0, 0));         // clear to transparent

                            Material[] mats = renderer.sharedMaterials;
                            for (int j = 0; j < mats.Length; j++)
                            {
                                Material mat = mats[j];

                                lightMap.SetVector("_LightMapUV", renderer.lightmapScaleOffset);
                                lightMap.SetPass(0);
                                Graphics.DrawMeshNow(mesh, world, j);
                            }

                            // This is the only way to access data from a RenderTexture
                            Texture2D tex = new Texture2D(renderTexture.width, renderTexture.height);
                            tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0);
                            tex.name = "Lightmap" + lmap;
                            tex.Apply();         // send the data back to the GPU so we can draw it on the preview area

                            if (!texturesExported.Contains(tex))
                            {
                                texturesExported.Add(tex);
                            }

                            ExportedObject eobj = exported.exportedObjs.First(c => c.GameObject == obj);
                            eobj.LightMapTex = tex;

                            Graphics.SetRenderTarget(null);
                            RenderTexture.ReleaseTemporary(renderTexture);

                            lmap++;
                        }
                    }
                    UObject.DestroyImmediate(lightMap);
                }
                    #endregion
                    break;
                }
            }

            for (int i = 0; i < texturesExported.Count; i++)
            {
                Texture2D         tex  = texturesExported[i];
                TextureExportData data = new TextureExportData();
                string            path = AssetDatabase.GetAssetPath(tex);

                data.Created    = string.IsNullOrEmpty(path);
                data.Format     = this.defaultTexFormat; // start up with a default format
                data.Texture    = tex;
                data.Resolution = tex.width;
                data.Quality    = defaultQuality;

                if (tex.width <= PreviewSize && tex.height <= PreviewSize)
                {
                    data.Preview = data.Texture;
                }
                else
                {
                    if (data.Created)
                    {
                        data.Preview     = TextureUtil.ScaleTexture(data, PreviewSize, true);
                        data.ExportAlpha = false;
                    }
                    else
                    {
                        TextureImporter       importer    = (TextureImporter)TextureImporter.GetAtPath(path);
                        bool                  wasReadable = importer.isReadable;
                        TextureImporterFormat lastFormat  = importer.textureFormat;
                        if (!importer.isReadable || importer.textureFormat != TextureImporterFormat.ARGB32) // only reimport if truly needed
                        {
                            importer.isReadable = true;
                            if (!tex.name.Contains("comp_light"))
                            {
                                importer.textureFormat = TextureImporterFormat.ARGB32;
                            }
                        }

                        AssetDatabase.Refresh();
                        AssetDatabase.ImportAsset(path);

                        data.Preview     = TextureUtil.ScaleTexture(data, PreviewSize, true);
                        data.ExportAlpha = importer.alphaIsTransparency;

                        if (!wasReadable)
                        {
                            importer.isReadable    = false;
                            importer.textureFormat = lastFormat;
                        }
                    }
                }

                texturesExportedData.Add(data);
            }

            for (int i = 0; i < meshesExported.Count; i++)
            {
                Mesh           mesh = meshesExported[i];
                MeshExportData data = new MeshExportData();
                data.Format  = this.defaultMeshFormat;
                data.Mesh    = mesh;
                data.Preview = AssetPreview.GetAssetPreview(mesh);

                string name = mesh.name;
                if (string.IsNullOrEmpty(name))
                {
                    meshesCount++;
                    name = "ExportedMesh" + meshesCount;
                }
                meshesNames.Add(mesh, name);

                meshesExportedData.Add(data);
            }
        }
Exemplo n.º 11
0
        public MainWindow()
        {
            ExportedData.Init();
            AutoScroll = true;

            Application.Current.DispatcherUnhandledException += (o, args) =>
            {
                Exception ex = (Exception)args.Exception;
                log.Debug("UI exception: ");
                log.Debug(ex);
                //throw ex;
            };

            int status;

            legit = false;

            try
            {
                LexActivator.SetGracePeriodForNetworkError(0);
                LexActivator.SetDayIntervalForServerCheck(1);
            }
            catch (Exception e)
            {
                log.Debug(e);
            }

            status = LexActivator.SetProductFile("Product.dat");
            if (status != LexActivator.LA_OK)
            {
                MessageBox.Show("Corrupted files! Please redownload the software.");
                Environment.Exit(0);
            }

            status = LexActivator.SetVersionGUID("014FF53D-5C6C-5266-7A89-E9601F37F5B1",
                                                 LexActivator.PermissionFlags.LA_USER);
            if (status != LexActivator.LA_OK)
            {
                MessageBox.Show("Corrupted data!");
                Environment.Exit(0);
            }

            LexActivator.ActivateProduct();
            status = LexActivator.IsProductGenuine();
            if (status == LexActivator.LA_OK || status == LexActivator.LA_GP_OVER)
            {
                legit = true;
            }

            status = LexActivator.IsTrialGenuine();
            if (status == LexActivator.LA_OK)
            {
                legit = true;
                uint daysLeft = 0;
                LexActivator.GetTrialDaysLeft(ref daysLeft, LexActivator.TrialType.LA_V_TRIAL);
                MessageBox.Show($"Trial days left: {daysLeft}");
            }

            else if (status == LexActivator.LA_T_EXPIRED && !legit)
            {
                MessageBox.Show("Trial has expired!");
            }

            if (!legit)
            {
                var _loginForm = new LoginForm();
                _loginForm.ShowDialog();
            }

            if (!legit)
            {
                MessageBox.Show("Failed atuh.");
                Environment.Exit(0);
            }

            pSelf            = this;
            ViewModel        = new ViewModel();
            this.DataContext = ViewModel;
            //var bot = new L2Bot(new Injector(23, 123));
            //bot.Engine.Init(bot.PlayerData,
            //    new H5ActionsController(bot.PlayerData,
            //        new Client(new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))));
            //bot.PlayerData.Skills.Add(123, new Skill() {SkillId = 22});

            InitializeComponent();
            //LogHelper.GetLogger($"\\ RONIN .cs").Info($"L2 Ronin BETA {Assembly.GetEntryAssembly().GetName().Version}");
            versionLabel.Text = $"L2 Ronin BETA Release v{Assembly.GetEntryAssembly().GetName().Version}";
            this.Title        = RandomString(10);
            //log.Debug(Title);



            CrackCheckThread = new Thread(delegate()
            {
                while (true)
                {
                    Thread.Sleep(30 * 60 * 1000);
                    LexActivator.ActivateProduct();
                    status = LexActivator.IsProductGenuine();
                    if (status != LexActivator.LA_OK && status != LexActivator.LA_GP_OVER)
                    {
                        Environment.Exit(0);
                    }
                }
            });
            CrackCheckThread.Start();

            Style itemContainerStyle = new Style(typeof(ListBoxItem));

            itemContainerStyle.Setters.Add(new EventSetter(ListBoxItem.MouseDoubleClickEvent,
                                                           new MouseButtonEventHandler(ListBox_MouseDoubleClick)));
            BotsList.ItemContainerStyle = itemContainerStyle;

            log.Debug(Assembly.GetEntryAssembly().GetName().Version);
            log.Debug(getOSInfo());
            string OStype = "";

            if (Environment.Is64BitOperatingSystem)
            {
                OStype = "64-Bit, ";
            }
            else
            {
                OStype = "32-Bit, ";
            }
            OStype += Environment.ProcessorCount.ToString() + " Processor";
            log.Debug(OStype);


            var l2rerouterThread = new Thread(Injectora.RerouteL2s);

            l2rerouterThread.SetApartmentState(ApartmentState.STA);
            l2rerouterThread.Start();

            //Hierarchy h = (Hierarchy)LogManager.GetRepository();
            //h.Root.Level = Level.All;
            //h.Root.AddAppender(new TextBoxAppender());
            //h.Configured = true;
        }
        public string ExportRecords(ExportConfiguration configuration)
        {
            try
            {
                log.Log(new LogEntry("Exporting records using provided configuration.", information: configuration.ToJson()));

                options = configuration.ExportOptions;

                log.Log($"Going over {configuration.Records.Count} record definitions in parallel ...");
                Parallel.ForEach(configuration.Records,
                                 new ParallelOptions
                {
                    MaxDegreeOfParallelism = CrmService.Threads
                },
                                 recordsConfig => LoadEntities(recordsConfig));
                log.Log($"Finished going over record definitions.");

                if (configuration.ExportOptions.IsExcludeOwner == true)
                {
                    log.Log("Removing owner values from all records ...");
                    foreach (var record in recordsMap.Values
                             .Select(e => e.Record)
                             .Where(e => e.Attributes.Keys.Intersect(ownerFields).Any()))
                    {
                        var recordOwnerFields = record.Attributes.Keys.Intersect(ownerFields).ToArray();

                        foreach (var field in recordOwnerFields)
                        {
                            record.Attributes.Remove(field);
                        }
                        log.Log($"Removed '${recordOwnerFields.Aggregate((f1, f2) => $"{f1},{f2}")}'.");
                    }
                    log.Log("Finished removing owner values from all records.");
                }

                log.Log("Clearing formatted values from all records ...");
                foreach (var formattedValues in recordsMap.Values
                         .Select(e => e.Record.FormattedValues)
                         .Where(f => f.Any()))
                {
                    formattedValues.Clear();
                }
                log.Log("Finished cleared formatted values from all records.");

                var exportedData =
                    new ExportedData
                {
                    Configuration      = configuration,
                    EntityDefinition   = recordsMap,
                    RelationDefinition = relationsMap,
                    Queries            = queries
                };

                log.Log("Serialising exported data ...");
                var serialisedData = configuration.ExportOptions.IsCompressData == true
                                        ? Helpers.Helpers.Compress(exportedData)
                                        : Encoding.UTF8.GetString(Helpers.Helpers.Serialise(exportedData));

                log.Log("Finished serialising exported data.");

                log.Log($"Finished exporting records using provided configuration.");

                return(serialisedData);
            }
            catch (AggregateException exception)
            {
                throw new Exception(exception.InnerExceptions
                                    .Select(e => $"{e.GetType()} => {e.Message}"
                                            + $"{(e.InnerException == null ? "" : $"{e.InnerException.GetType()} => {e.InnerException.Message}")}")
                                    .Aggregate((e1, e2) => $"{e1} ||| {e2}"));
            }
        }