System.IO.Path.GetExtension(string)

Here are the examples of the csharp api System.IO.Path.GetExtension(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

4721 Examples 7

19 View Source File : VideoSource.cs
License : MIT License
Project Creator : adamfisher

public static VideoSource FromResource(string resource, replacedembly replacedembly = default(replacedembly))
        {
			if (string.IsNullOrEmpty (resource))
				return null;
			
			if (!Path.HasExtension (resource))
				throw new Exception ($"The specified resource '{resource}' must contain a valid file extension.");

            var foundResource = false;
			var format = Path.GetExtension (resource)?.Replace (".", string.Empty);
            replacedembly parameterreplacedembly = null, callingreplacedembly = null, entryreplacedembly = null;

            if (replacedembly != null)
            {
                parameterreplacedembly = replacedembly;
                foundResource = replacedembly.ContainsManifestResource(resource);
            }

            if (!foundResource)
            {
                replacedembly = replacedembly.GetCallingreplacedembly();
                callingreplacedembly = replacedembly;
                foundResource = replacedembly.ContainsManifestResource(resource);
            }

            if (!foundResource)
            {
                replacedembly = replacedembly.GetEntryreplacedembly();
                entryreplacedembly = replacedembly;
                foundResource = replacedembly.ContainsManifestResource(resource);
            }
            
            if (!foundResource)
            {
                var resourceNames = new List<string>();

                if (parameterreplacedembly != null)
                    resourceNames.AddRange(parameterreplacedembly.GetManifestResourceNames());
                if (callingreplacedembly != null)
                    resourceNames.AddRange(callingreplacedembly.GetManifestResourceNames());
                if (entryreplacedembly != null)
                    resourceNames.AddRange(entryreplacedembly.GetManifestResourceNames());

                Log.Error($"Unable to locate the embedded resource '{resource}'. " +
                          $"Possible candidates are: {Environment.NewLine}{string.Join(Environment.NewLine, resourceNames)}");

                return null;
            }

			return FromStream(() => replacedembly.GetEmbeddedResourceStream(resource), format);
        }

19 View Source File : ActivityDataAdapter.cs
License : MIT License
Project Creator : Adoxio

public PortalCommentCreateResult CreatePortalComment(PortalComment portalComment)
		{
			var serviceContext = _dependencies.GetServiceContext();
			var serviceContextForWrite = _dependencies.GetServiceContextForWrite();

			PortalCommentCreateResult result = null;

			var enreplacedyPermissionProvider = new CrmEnreplacedyPermissionProvider();
			result = new PortalCommentCreateResult(enreplacedyPermissionProvider, serviceContext, portalComment.Regarding);

			if (result.PermissionsExist && result.PermissionGranted)
			{
				var acceptMimeTypes = AnnotationDataAdapter.GetAcceptRegex(portalComment.AttachmentSettings.AcceptMimeTypes);
				var acceptExtensionTypes = AnnotationDataAdapter.GetAcceptRegex(portalComment.AttachmentSettings.AcceptExtensionTypes);
				if (portalComment.FileAttachments != null)
				{
					portalComment.FileAttachments.ForEach(attachment =>
					{
						if (!(acceptExtensionTypes.IsMatch(Path.GetExtension(attachment.FileName).ToLower()) ||
								acceptMimeTypes.IsMatch(attachment.MimeType)))
						{
							throw new AnnotationException(portalComment.AttachmentSettings.RestrictMimeTypesErrorMessage);
						}
					});
				}

				var owner = portalComment.To?.GetAttributeValue<EnreplacedyReference>("partyid");

				var enreplacedy = new Enreplacedy("adx_portalcomment");

				enreplacedy.SetAttributeValue("description", portalComment.Description);
				enreplacedy.SetAttributeValue("regardingobjectid", portalComment.Regarding);
				enreplacedy.SetAttributeValue("regardingobjecttypecode", portalComment.Regarding.LogicalName);
				enreplacedy.SetAttributeValue("from", new Enreplacedy[] { portalComment.From });
				enreplacedy.SetAttributeValue("adx_portalcommentdirectioncode", new OptionSetValue((int)portalComment.DirectionCode));
				
				if (owner != null)
				{
					enreplacedy.SetAttributeValue("ownerid", owner);

					if (!string.Equals(owner.LogicalName, "team", StringComparison.OrdinalIgnoreCase))
					{
						enreplacedy.SetAttributeValue("to", new Enreplacedy[] { portalComment.To });
					}
				}

				// Create adx_portalcomment but skip cache invalidation.
				var id = (serviceContext as IOrganizationService).ExecuteCreate(enreplacedy, RequestFlag.ByPreplacedCacheInvalidation);

				portalComment.ActivityId = enreplacedy.Id = id;
				portalComment.Enreplacedy = enreplacedy;

				// Can only change state code value after enreplacedy creation
				enreplacedy.SetAttributeValue("statecode", new OptionSetValue((int)portalComment.StateCode));
				enreplacedy.SetAttributeValue("statuscode", new OptionSetValue((int)portalComment.StatusCode));

				// Explicitly include the activityid, this way the Cache will know to add dependency on "activitypointer" for this "adx_portalcomment" enreplacedy.
				enreplacedy.SetAttributeValue("activityid", id);

				(serviceContext as IOrganizationService).ExecuteUpdate(enreplacedy);
				
				if (portalComment.FileAttachments != null)
				{
					// permission for Portal Comment implies permission for attachment to Portal Comment
					portalComment.AttachmentSettings.RespectPermissions = false;

					foreach (IAnnotationFile attachment in portalComment.FileAttachments)
					{
						IAnnotation annotation = new Annotation
						{
							Subject = string.Empty,
							NoteText = string.Empty,
							Regarding = portalComment.Enreplacedy.ToEnreplacedyReference(),
							FileAttachment = attachment
						};

						IAnnotationDataAdapter da = new AnnotationDataAdapter(_dependencies);
						da.CreateAnnotation(annotation, portalComment.AttachmentSettings);
					}
				}
			}

			return result;
		}

19 View Source File : OVRLipSyncTool.cs
License : MIT License
Project Creator : absurd-joy

public static IEnumerator ProcessClips(bool useOfflineModel)
    {
        if (clipQueue == null || clipQueue.Count == 0)
        {
            yield break;
        }

        while (clipQueue.Count > 0)
        {
            // Pop a clip off the list
            AudioClip clip = clipQueue[0];
            clipQueue.RemoveAt(0);

            if (clip.loadType != AudioClipLoadType.DecompressOnLoad)
            {
                Debug.LogError(clip.name +
                    ": Cannot process phonemes from an audio clip unless " +
                    "its load type is set to DecompressOnLoad.");
                continue;
            }

            // Update progress
            if (totalLengthOfClips > 0.0f)
            {
                EditorUtility.DisplayProgressBar("Generating Lip Sync replacedets...", "Processing clip " + clip.name + "...",
                    totalLengthOfClipsProcessed / totalLengthOfClips);
            }

            if (!clip.preloadAudioData)
            {
                clip.LoadAudioData();

                Debug.LogWarning(clip.name +
                    ": Audio data is not pre-loaded. Data will be loaded then" +
                    "unloaded on completion.");

                while (clip.loadState != AudioDataLoadState.Loaded)
                {
                    yield return new WaitForSeconds(0.1f);
                }
            }

            var sequence =
                OVRLipSyncSequence.CreateSequenceFromAudioClip(clip, useOfflineModel);
            if (sequence != null)
            {
                var path = replacedetDatabase.GetreplacedetPath(clip);
                var newPath = path.Replace(Path.GetExtension(path), "_lipSync.replacedet");
                var existingSequence = replacedetDatabase.LoadreplacedetAtPath<OVRLipSyncSequence>(newPath);
                if (existingSequence != null)
                {
                    EditorUtility.CopySerialized(sequence, existingSequence);
                    replacedetDatabase.Savereplacedets();
                }
                else
                {
                    replacedetDatabase.Createreplacedet(sequence, newPath);

                }
            }
            replacedetDatabase.Refresh();

            if (!clip.preloadAudioData)
            {
                clip.UnloadAudioData();
            }

            totalLengthOfClipsProcessed += clip.length;
        }

        EditorUtility.ClearProgressBar();
    }

19 View Source File : SuppressionFile.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

internal static bool IsSuppressionFile(string path)
		{
			return SuppressionFileExtension.Equals(System.IO.Path.GetExtension(path), StringComparison.Ordinal);
		}

19 View Source File : IOExtensions.cs
License : MIT License
Project Creator : Accelerider

public static string GetUniqueLocalPath(this string @this, Func<string, bool> predicate = null)
        {
            if (predicate == null) predicate = File.Exists;

            var directoryName = Path.GetDirectoryName(@this) ?? throw new InvalidOperationException();
            var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(@this) ?? throw new InvalidOperationException();
            fileNameWithoutExtension = FileNameCountRegex.Replace(fileNameWithoutExtension, string.Empty).Trim();
            var extension = Path.GetExtension(@this);
            for (int i = 2; predicate(@this); i++)
            {
                @this = $"{Path.Combine(directoryName, fileNameWithoutExtension)} ({i}){extension}";
            }

            return @this;
        }

19 View Source File : ImageSaver.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<CommandResult<SavedImageViewModel>> SaveImage(IFormFile image)
        {
            if (image is null)
            {
                return new CommandResult<SavedImageViewModel>(
                    new ErrorMessage
                    {
                        ErrorCode = "IMAGE.NULL",
                        Message = "Please send a valid data",
                        StatusCode = System.Net.HttpStatusCode.BadRequest
                    });
            }

            if (!ImageMimeType.Any(m => m.EqualsIC(image.ContentType))
                || !ImageExtension.Any(e => e.EqualsIC(Path.GetExtension(image.FileName))))
            {
                return new CommandResult<SavedImageViewModel>(new ErrorMessage
                {
                    ErrorCode = "IMAGE.NOT.IMAGE",
                    Message = "Please send image",
                    StatusCode = System.Net.HttpStatusCode.BadRequest
                });
            }


            if (image.Length == 0)
            {
                return new CommandResult<SavedImageViewModel>(
                    new ErrorMessage
                    {
                        ErrorCode = "IMAGE.TOO.SMALL",
                        Message = "Please send a valid image",
                        StatusCode = System.Net.HttpStatusCode.BadRequest
                    });
            }


            if (image.Length > 4 * 1024 * 1024)
            {
                return new CommandResult<SavedImageViewModel>(
                    new ErrorMessage
                    {
                        ErrorCode = "IMAGE.TOO.LARGE",
                        Message = "Please send a smaller image",
                        StatusCode = System.Net.HttpStatusCode.BadRequest
                    });
            }

            var name = Guid.NewGuid();
            var withExtension = name + Path.GetExtension(image.FileName);
            var path = Path.Combine(contentRoot, "replacedets", "Images", "Profile");
            Directory.CreateDirectory(path);
            var full = Path.Combine(path, withExtension);

            try
            {
                using (Stream s = new FileStream(full, FileMode.OpenOrCreate))
                {
                    await image.CopyToAsync(s);
                }
                
                return new CommandResult<SavedImageViewModel>(new SavedImageViewModel
                {
                    Name = name,
                    Path = full,                     
                });
            }
            catch (Exception e)
            {
                _logger.LogError(e, "An error occurred while trying to save an image to the desk");
                return new CommandResult<SavedImageViewModel>(new ErrorMessage
                {
                    ErrorCode = "IMAGE.ERROR",
                    Message = "An error occurred while trying to save the image",
                    StatusCode = System.Net.HttpStatusCode.InternalServerError
                });
            }
        }

19 View Source File : Settings.cs
License : MIT License
Project Creator : adlez27

public void LoadRecList()
        {
            if (init && File.Exists(RecListFile))
            {
                RecList.Clear();
                HashSet<string> uniqueStrings = new HashSet<string>();

                Encoding e;
                if (ReadUnicode)
                {
                    e = Encoding.UTF8;
                }
                else
                {
                    e = CodePagesEncodingProvider.Instance.GetEncoding(932);
                }

                var ext = Path.GetExtension(RecListFile);

                if (ext == ".txt")
                {
                    if (Path.GetFileName(RecListFile) == "OREMO-comment.txt")
                    {
                        var rawText = File.ReadAllLines(RecListFile, e);
                        foreach(string rawLine in rawText)
                        {
                            var line = rawLine.Split("\t");
                            if (!uniqueStrings.Contains(line[0]))
                            {
                                RecList.Add(new RecLisreplacedem(this, line[0], line[1]));
                                uniqueStrings.Add(line[0]);
                            }
                        }
                    }
                    else
                    {
                        string[] textArr;
                        if (SplitWhitespace)
                        {
                            var rawText = File.ReadAllText(RecListFile, e);
                            rawText = Regex.Replace(rawText, @"\s{2,}", " ");
                            textArr = Regex.Split(rawText, @"\s");
                        }
                        else
                        {
                            textArr = File.ReadAllLines(RecListFile, e);
                        }

                        foreach (string line in textArr)
                        {
                            if (!uniqueStrings.Contains(line))
                            {
                                RecList.Add(new RecLisreplacedem(this, line));
                                uniqueStrings.Add(line);
                            }
                        }
                    }
                }
                else if (ext == ".arl")
                {
                    var rawText = File.ReadAllText(RecListFile, e);
                    var deserializer = new Deserializer();
                    var tempDict = deserializer.Deserialize<Dictionary<string, string>>(rawText);
                    foreach (var item in tempDict)
                    {
                        RecList.Add(new RecLisreplacedem(this, item.Key, item.Value));
                    }
                }
                else if (ext == ".csv")
                {
                    using (TextFieldParser parser = new TextFieldParser(RecListFile))
                    {
                        parser.TextFieldType = FieldType.Delimited;
                        parser.SetDelimiters(",");
                        while (!parser.EndOfData)
                        {
                            string[] line = parser.ReadFields();
                            var text = line[0].Substring(0,line[0].Length - 4);
                            if (!uniqueStrings.Contains(text))
                            {
                                RecList.Add(new RecLisreplacedem(this, text, line[1]));
                                uniqueStrings.Add(text);
                            }
                        }
                    }
                    CopyIndex();
                }
                else if (ext == ".reclist")
                {
                    var rawText = File.ReadAllText(RecListFile, e);
                    var deserializer = new Deserializer();
                    var reclist = deserializer.Deserialize<WCTReclist>(rawText);
                    foreach(var line in reclist.Files)
                    {
                        if (!uniqueStrings.Contains(line.Filename))
                        {
                            RecList.Add(new RecLisreplacedem(this, line.Filename, line.Description));
                            uniqueStrings.Add(line.Filename);
                        }
                    }
                }
                else if (ext == ".ust"){
                    var rawText = File.ReadAllLines(RecListFile, e);
                    foreach (var line in rawText)
                    {
                        if (line.StartsWith("Lyric="))
                        {
                            var lyric = line.Substring(6);
                            if (lyric != "R" && lyric != "r" && lyric != "" && !uniqueStrings.Contains(lyric))
                            {
                                RecList.Add(new RecLisreplacedem(this, lyric));
                                uniqueStrings.Add(lyric);
                            }
                        }
                    }
                }
            }
        }

19 View Source File : AssetBundleUtil.cs
License : MIT License
Project Creator : 404Lcc

public static List<replacedetBundleData> BuildreplacedetBundleData(replacedetBundleRule[] replacedetBundleRules)
        {
            List<replacedetBundleData> replacedetBundleDataList = new List<replacedetBundleData>();
            List<string> replacedetNameList = new List<string>();
            foreach (replacedetBundleRule item in replacedetBundleRules)
            {
                if (item.replacedetBundleRuleType == replacedetBundleRuleType.File)
                {
                    FileInfo[] fileInfos = FileUtil.GetFiles(new DirectoryInfo(item.path), new List<FileInfo>());
                    if (fileInfos.Length == 0) continue;
                    List<FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
                    foreach (FileInfo fileInfo in fileInfoList)
                    {
                        string replacedetName = fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("replacedets")).Replace("\\", "/");
                        string md5 = MD5Util.ComputeMD5(replacedetName);
                        replacedetBundleDataList.Add(new replacedetBundleData($"{md5}.unity3d", string.Empty, uint.MinValue, long.MinValue, new string[] { replacedetName }));
                    }
                }
                if (item.replacedetBundleRuleType == replacedetBundleRuleType.Directory)
                {
                    DirectoryInfo[] directoryInfos = DirectoryUtil.GetDirectorys(new DirectoryInfo(item.path), new List<DirectoryInfo>());
                    if (directoryInfos.Length == 0) continue;
                    foreach (DirectoryInfo directoryInfo in directoryInfos)
                    {
                        FileInfo[] fileInfos = directoryInfo.GetFiles();
                        if (fileInfos.Length == 0) continue;
                        List<FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
                        foreach (FileInfo fileInfo in fileInfoList)
                        {
                            replacedetNameList.Add(fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("replacedets")).Replace("\\", "/"));
                        }
                        if (replacedetNameList.Count > 0)
                        {
                            string replacedetName = directoryInfo.FullName.Substring(directoryInfo.FullName.IndexOf("replacedets")).Replace("\\", "/");
                            string md5 = MD5Util.ComputeMD5(replacedetName);
                            replacedetBundleDataList.Add(new replacedetBundleData($"{md5}.unity3d", string.Empty, uint.MinValue, long.MinValue, replacedetNameList.ToArray()));
                            replacedetNameList.Clear();
                        }
                    }
                }
            }
            return replacedetBundleDataList;
        }

19 View Source File : LocalFileSystem.cs
License : MIT License
Project Creator : Adoxio

private JObject GetTemplateMetadata(IEnumerable<FileInfo> files)
		{
			var metadataFile = files
				.FirstOrDefault(e => string.Equals(Path.GetExtension(e.Name), ".json", StringComparison.InvariantCulture));

			return metadataFile == null
				? null
				: GetTemplateMetadata(metadataFile);
		}

19 View Source File : Server.cs
License : MIT License
Project Creator : 5minlab

static void FindFileType(RequestContext context, bool download, out string path, out string type) {
            path = Path.Combine(fileRoot, context.match.Groups[1].Value);

            string ext = Path.GetExtension(path).ToLower().TrimStart(new char[] { '.' });
            if (download || !fileTypes.TryGetValue(ext, out type))
                type = "application/octet-stream";
        }

19 View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro

private void OnOpenDoreplacedentMenuItemClick(object sender, RoutedEventArgs e) {
			// Show a file open dialog
			var dialog = new OpenFileDialog();
			dialog.CheckFileExists = true;
			dialog.Multiselect = false;
			dialog.Filter = "Code files (*.txt;*.cs;*.js;*.py;*.vb;*.xml)|*.txt;*.cs;*.js;*.py;*.vb;*.xml|All files (*.*)|*.*";
			if (dialog.ShowDialog() == true)
				this.CreateSyntaxEditorDoreplacedent(Path.GetExtension(dialog.FileName), dialog.FileName, String.Empty);
		}

19 View Source File : RunnerService.cs
License : MIT License
Project Creator : actions

private RunnerUpdateResult HandleRunnerUpdate()
        {
            // sleep 5 seconds wait for upgrade script to finish
            Thread.Sleep(5000);

            // looking update result record under _diag folder (the log file itself will indicate the result)
            // SelfUpdate-20160711-160300.log.succeed or SelfUpdate-20160711-160300.log.fail
            // Find the latest upgrade log, make sure the log is created less than 15 seconds.
            // When log file named as SelfUpdate-20160711-160300.log.succeedneedrestart, Exit(int.max), during Exit() throw Exception, this will trigger SCM to recovery the service by restart it
            // since SCM cache the ServiceHost in memory, sometime we need update the servicehost as well, in this way we can upgrade the ServiceHost as well.

            DirectoryInfo dirInfo = new DirectoryInfo(GetDiagnosticFolderPath());
            FileInfo[] updateLogs = dirInfo.GetFiles("SelfUpdate-*-*.log.*") ?? new FileInfo[0];
            if (updateLogs.Length == 0)
            {
                // totally wrong, we are not even get a update log.
                return RunnerUpdateResult.Failed;
            }
            else
            {
                FileInfo latestLogFile = null;
                DateTime latestLogTimestamp = DateTime.MinValue;
                foreach (var logFile in updateLogs)
                {
                    int timestampStartIndex = logFile.Name.IndexOf("-") + 1;
                    int timestampEndIndex = logFile.Name.LastIndexOf(".log") - 1;
                    string timestamp = logFile.Name.Substring(timestampStartIndex, timestampEndIndex - timestampStartIndex + 1);
                    DateTime updateTime;
                    if (DateTime.TryParseExact(timestamp, "yyyyMMdd-HHmmss", null, DateTimeStyles.None, out updateTime) &&
                        updateTime > latestLogTimestamp)
                    {
                        latestLogFile = logFile;
                        latestLogTimestamp = updateTime;
                    }
                }

                if (latestLogFile == null || latestLogTimestamp == DateTime.MinValue)
                {
                    // we can't find update log with expected naming convention.
                    return RunnerUpdateResult.Failed;
                }

                latestLogFile.Refresh();
                if (DateTime.UtcNow - latestLogFile.LastWriteTimeUtc > TimeSpan.FromSeconds(15))
                {
                    // the latest update log we find is more than 15 sec old, the update process is busted.
                    return RunnerUpdateResult.Failed;
                }
                else
                {
                    string resultString = Path.GetExtension(latestLogFile.Name).TrimStart('.');
                    RunnerUpdateResult result;
                    if (Enum.TryParse<RunnerUpdateResult>(resultString, true, out result))
                    {
                        // return the result indicated by the update log.
                        return result;
                    }
                    else
                    {
                        // can't convert the result string, return failed to stop the service.
                        return RunnerUpdateResult.Failed;
                    }
                }
            }
        }

19 View Source File : UMAAssetIndexerEditor.cs
License : Apache License 2.0
Project Creator : A7ocin

private void RecursiveScanFoldersForreplacedets(string path)
		{
			var replacedetFiles = System.IO.Directory.GetFiles(path);

			foreach (var replacedetFile in replacedetFiles)
			{
				string Extension = System.IO.Path.GetExtension(replacedetFile).ToLower();
				if (Extension == ".replacedet" || Extension == ".controller" || Extension == ".txt")
				{
					Object o = replacedetDatabase.LoadMainreplacedetAtPath(replacedetFile);

					if (o)
					{
						AddedDuringGui.Add(o);
					}
				}
			}
			foreach (var subFolder in System.IO.Directory.GetDirectories(path))
			{
				RecursiveScanFoldersForreplacedets(subFolder.Replace('\\', '/'));
			}
		}

19 View Source File : ProjectConfig.cs
License : MIT License
Project Creator : adamant

public static ProjectConfig Load(string path)
        {
            var extension = Path.GetExtension(path);
            string projectFilePath;
            if (Directory.Exists(path))
            {
                projectFilePath = Path.Combine(path, FileName);
            }
            else if (extension == "vson")
            {
                projectFilePath = path;
            }
            else
            {
                throw new Exception($"Unexpected project file extension '.{extension}'");
            }

            projectFilePath = Path.GetFullPath(projectFilePath);

            using var file = new JsonTextReader(File.OpenText(projectFilePath));
            var serializer = new JsonSerializer();
            var projectFile = serializer.Deserialize<ProjectConfig>(file) ?? throw new NullReferenceException();
            projectFile.FullPath = projectFilePath;
            return projectFile;
        }

19 View Source File : FileExt.cs
License : MIT License
Project Creator : 3F

public static ProjectType GetProjectTypeByFile(string file)
        {
            if(string.IsNullOrWhiteSpace(file)) {
                return ProjectType.Unknown;
            }
            return GetProjectTypeByExt(Path.GetExtension(file));
        }

19 View Source File : AssertFile.cs
License : Apache License 2.0
Project Creator : adamralph

public static async Task Contains(string expectedPath, string actual)
        {
            var actualPath = Path.Combine(
                Path.GetDirectoryName(expectedPath) ?? "",
                Path.GetFileNameWithoutExtension(expectedPath) + "-actual" + Path.GetExtension(expectedPath));

            if (File.Exists(actualPath))
            {
                File.Delete(actualPath);
            }

            var expected = await File.ReadAllTextAsync(expectedPath);

            try
            {
                replacedert.Equal(expected, actual);
            }
            catch (EqualException ex)
            {
                await File.WriteAllTextAsync(actualPath, actual, Encoding.UTF8);

                throw new XunitException(
                    $"{ex.Message}{Environment.NewLine}{Environment.NewLine}Expected file: {expectedPath}{Environment.NewLine}Actual file: {actualPath}");
            }
        }

19 View Source File : ScriptedImporterAssetReimporter.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static void OnPostprocessAllreplacedets(string[] importedreplacedets, string[] deletedreplacedets, string[] movedreplacedets, string[] movedFromreplacedetPaths)
        {
            foreach (string replacedet in importedreplacedets)
            {
                string extension = Path.GetExtension(replacedet);
                if (extension == ".room" || extension == ".glb" || extension == ".gltf")
                {
                    Type replacedetType = replacedetDatabase.GetMainreplacedetTypeAtPath(replacedet);
                    if (replacedetType == typeof(Defaultreplacedet))
                    {
                        if (!replacedetsAttemptedToReimport.TryGetValue(replacedet, out int numAttempts))
                        {
                            numAttempts = 0;
                        }

                        replacedetsAttemptedToReimport[replacedet] = ++numAttempts;

                        if (numAttempts <= 3)
                        {
                            Debug.LogWarning($"replacedet '{replacedet}' appears to have failed importing, will attempt to re-import. Attempt: {numAttempts}");
                            replacedetDatabase.Importreplacedet(replacedet);
                        }
                        else
                        {
                            Debug.LogWarning($"replacedet '{replacedet}' appears to have failed the re-import 3 times, will not try again.");
                        }
                    }
                }
            }
        }

19 View Source File : ReloadCommand.cs
License : MIT License
Project Creator : adospace

private async void Execute(object sender, EventArgs e)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            //ThreadHelper.ThrowIfNotOnUIThread();
            var generalPane = GetVsOutputWindow();

            var selectedProject = GetFormsProjects().FirstOrDefault();

            if (selectedProject == null)
            {
                generalPane.OutputString($"Solution doesn't contain a valid ReactorUI hot reload project{Environment.NewLine}");
                generalPane.OutputString($"1) Ensure it references XamarinReactorUI.HotReload package and call WithHotReload() on RxApplication{Environment.NewLine}");
                generalPane.OutputString($"2) Ensure that Visual Studio has finished loading the solution{Environment.NewLine}");
                generalPane.Activate(); // Brings this pane into view
                return;
            }

            string projectPath = selectedProject.FullName;

            var outputFilePath = Path.Combine(Path.GetDirectoryName(projectPath), 
                selectedProject.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value.ToString(),
                selectedProject.Properties.Item("OutputFileName").Value.ToString());

            if (Path.GetExtension(outputFilePath) != ".dll")
                return;

            var now = DateTime.Now;

            generalPane.Activate(); // Brings this pane into view
            generalPane.OutputString($"Building {outputFilePath}...{Environment.NewLine}");
            generalPane.Activate(); // Brings this pane into view

            //_dte.Solution.SolutionBuild.BuildProject(selectedProject.ConfigurationManager.ActiveConfiguration.ConfigurationName, selectedProject.UniqueName, true);

            _dte.Doreplacedents.SaveAll();
            
            if (!RunMsBuild(selectedProject, generalPane))
            {
                // Show a message box to inform user that build was completed with errors
                VsShellUtilities.ShowMessageBox(
                    this.package,
                    "Build FAILED with errors: please review them in the output window and try again",
                    "ReactorUI Hot Reload",
                    OLEMSGICON.OLEMSGICON_WARNING,
                    OLEMSGBUTTON.OLEMSGBUTTON_OK,
                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);

                generalPane.OutputString($"Unable to build Xamarin Forms project, it may contains errors{Environment.NewLine}");
                generalPane.Activate(); // Brings this pane into view
                return;
            }

            if (!ExecutePortForwardCommmand(generalPane))
            {
                generalPane.OutputString($"Unable to setup connection with the device or emulator using adb: plese ensure it's correctly installed (please note that only Android platform is supported so far under Windows){Environment.NewLine}");
                generalPane.Activate(); // Brings this pane into view
                return;
            }

            if (await SendreplacedemblyToEmulatorAsync(outputFilePath, generalPane, _dte.Debugger.CurrentMode != dbgDebugMode.dbgDesignMode))
            {
                generalPane.OutputString($"Hot reload completed in {(DateTime.Now - now).TotalMilliseconds}ms{Environment.NewLine}");
                generalPane.Activate(); // Brings this pane into view
            }


            // Show a message box to prove we were here
            //VsShellUtilities.ShowMessageBox(
            //    package,
            //    message,
            //    outputFilePath,
            //    OLEMSGICON.OLEMSGICON_INFO,
            //    OLEMSGBUTTON.OLEMSGBUTTON_OK,
            //    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);

            //string message = string.Format(CultureInfo.CurrentCulture, "Inside {0}.MenuItemCallback()", this.GetType().FullName);
            //string replacedle = "ReloadCommand";

            //IVsHierarchy hierarchy = null;
            //uint itemid = VSConstants.VSITEMID_NIL;

            //if (!IsSingleProjecreplacedemSelection(out hierarchy, out itemid)) return;

            //var currentProject = ((IVsProject)hierarchy);

            //// Show a message box to prove we were here
            //VsShellUtilities.ShowMessageBox(
            //    this.package,
            //    message,
            //    replacedle,
            //    OLEMSGICON.OLEMSGICON_INFO,
            //    OLEMSGBUTTON.OLEMSGBUTTON_OK,
            //    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 13xforever

static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage:");
                Console.WriteLine("  gvas-converter path_to_save_file|path_to_json");
                return;
            }

            var ext = Path.GetExtension(args[0]).ToLower();
            if (ext == ".json")
            {
                Console.WriteLine("Not implemented atm");
            }
            else
            {
                Console.WriteLine("Parsing UE4 save file structure...");
                Gvas save;
                using (var stream = File.Open(args[0], FileMode.Open, FileAccess.Read, FileShare.Read))
                    save = UESerializer.Read(stream);

                Console.WriteLine("Converting to json...");
                var json = JsonConvert.SerializeObject(save, new JsonSerializerSettings{Formatting = Formatting.Indented});

                Console.WriteLine("Saving json...");
                using (var stream = File.Open(args[0] + ".json", FileMode.Create, FileAccess.Write, FileShare.Read))
                using (var writer = new StreamWriter(stream, new UTF8Encoding(false)))
                    writer.Write(json);
            }
            Console.WriteLine("Done.");
            Console.ReadKey(true);
        }

19 View Source File : LocalFileSystem.cs
License : MIT License
Project Creator : Adoxio

public IEnumerable<TemplateFileInfo> GetTemplateFiles()
		{
			var root = new DirectoryInfo(Root);

			if (!root.Exists)
			{
				return Enumerable.Empty<TemplateFileInfo>();
			}

			var rootUri = new Uri(
				root.FullName.EndsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture))
					? root.FullName
					: root.FullName + Path.DirectorySeparatorChar);

			return root.EnumerateFiles("*", SearchOption.AllDirectories)
				.Where(file => string.Equals(Path.GetExtension(file.Name), ".liquid", StringComparison.InvariantCulture) || string.Equals(Path.GetExtension(file.Name), ".json", StringComparison.InvariantCulture))
				.GroupBy(file => GetTemplateFileName(rootUri, file), e => e, StringComparer.InvariantCulture)
				.Where(e => Regex.IsMatch(e.Key, @"^[a-zA-Z0-9_\/]+$"))
				.Select(e => new TemplateFileInfo(e.Key, GetTemplateMetadata(e)));
		}

19 View Source File : AutomationTestBase.cs
License : MIT License
Project Creator : ABTSoftware

public void ExportActual(WriteableBitmap actualBitmap, string fileName)
        {
            if (!Directory.Exists(ExportActualPath))
            {
                Directory.CreateDirectory(ExportActualPath);
            }

            var pathString = Path.Combine(ExportActualPath, fileName);

            if (Path.GetExtension(fileName).ToUpper() == ".BMP")
            {
                SaveToBmp(pathString, actualBitmap);
            }
            else
            {
                SaveToPng(pathString, actualBitmap);
            }

            ProcessStartInfo startInfo = new ProcessStartInfo(pathString);
            Process.Start(startInfo);
        }

19 View Source File : AutomationTestBase.cs
License : MIT License
Project Creator : ABTSoftware

public WriteableBitmap LoadResource(string resourceName)
        {
            resourceName = resourceName.Replace("/", ".");
            WriteableBitmap expectedBitmap = null;
            var replacedembly = GetType().replacedembly;

            // For testing purposes, to see all the resources available
            var resourcePath = replacedembly.GetManifestResourceNames().FirstOrDefault(x => x.ToUpper().Contains(resourceName.ToUpper()));

            using (var resourceStream = replacedembly.GetManifestResourceStream(resourcePath))
            {
                expectedBitmap = Path.GetExtension(resourceName).ToUpper() == ".BMP"
                    ? DecodeBmpStream(resourceStream)
                    : DecodePngStream(resourceStream);
            }

            return expectedBitmap;
        }

19 View Source File : DiscordRPforVSPackage.cs
License : GNU Affero General Public License v3.0
Project Creator : 1thenikita

public async System.Threading.Tasks.Task UpdatePresenceAsync(Doreplacedent doreplacedent, Boolean overrideTimestampReset = false)
        {
            try
            {
                await this.JoinableTaskFactory.SwitchToMainThreadAsync();

                if (!Settings.enabled)
                {
                    if (!this.Discord.IsInitialized && !this.Discord.IsDisposed)
                        if (!this.Discord.Initialize())
                            ActivityLog.LogError("DiscordRPforVS", $"{Translates.LogError(Settings.Default.translates)}");

                    this.Discord.ClearPresence();
                    return;
                }

                this.Presence.Details = this.Presence.State = this.replacedets.LargeImageKey = this.replacedets.LargeImageText = this.replacedets.SmallImageKey = this.replacedets.SmallImageText = String.Empty;

                if (Settings.secretMode)
                {
                    this.Presence.Details = Translates.PresenceDetails(Settings.Default.translates);
                    this.Presence.State = Translates.PresenceState(Settings.Default.translates);
                    this.replacedets.LargeImageKey = this.versionImageKey;
                    this.replacedets.LargeImageText = this.versionString;
                    this.replacedets.SmallImageKey = this.replacedets.SmallImageText = "";
                    goto finish;
                }

                this.Presence.Details = this.Presence.State = "";
                String[] language = Array.Empty<String>();

                if (doreplacedent != null)
                {
                    String filename = Path.GetFileName(path: doreplacedent.FullName).ToUpperInvariant(), ext = Path.GetExtension(filename);
                    List<KeyValuePair<String[], String[]>> list = Constants.Languages.Where(lang => Array.IndexOf(lang.Key, filename) > -1 || Array.IndexOf(lang.Key, ext) > -1).ToList();
                    language = list.Count > 0 ? list[0].Value : Array.Empty<String>();
                }

                Boolean supported = language.Length > 0;
                this.replacedets.LargeImageKey = Settings.largeLanguage ? supported ? language[0] : "text" : this.versionImageKey;
                this.replacedets.LargeImageText = Settings.largeLanguage ? supported ? language[1] + " " + Translates.File(Settings.Default.translates) : Translates.UnrecognizedExtension(Settings.Default.translates) : this.versionString;
                this.replacedets.SmallImageKey = Settings.largeLanguage ? this.versionImageKey : supported ? language[0] : "text";
                this.replacedets.SmallImageText = Settings.largeLanguage ? this.versionString : supported ? language[1] + " " + Translates.File(Settings.Default.translates) : Translates.UnrecognizedExtension(Settings.Default.translates);

                if (Settings.showFileName)
                    this.Presence.Details = !(doreplacedent is null) ? Path.GetFileName(doreplacedent.FullName) : Translates.NoFile(Settings.Default.translates);

                if (Settings.showSolutionName)
                {
                    Boolean idling = ide.Solution is null || String.IsNullOrEmpty(ide.Solution.FullName);
                    this.Presence.State = idling ? Translates.Idling(Settings.Default.translates) : $"{Translates.Developing(Settings.Default.translates)} {Path.GetFileNameWithoutExtension(ide.Solution.FileName)}";

                    if (idling)
                    {
                        this.replacedets.LargeImageKey = this.versionImageKey;
                        this.replacedets.LargeImageText = this.versionString;
                        this.replacedets.SmallImageKey = this.replacedets.SmallImageText = "";
                    }
                }

                if (Settings.showTimestamp && doreplacedent != null)
                {
                    if (!this.InitializedTimestamp)
                    {
                        this.InitialTimestamps = this.Presence.Timestamps = new Timestamps() { Start = DateTime.UtcNow };
                        this.InitializedTimestamp = true;
                    }

                    if (Settings.resetTimestamp && !overrideTimestampReset)
                        this.Presence.Timestamps = new Timestamps() { Start = DateTime.UtcNow };
                    else if (Settings.resetTimestamp && overrideTimestampReset)
                        this.Presence.Timestamps = this.CurrentTimestamps;
                    else if (!Settings.resetTimestamp && !overrideTimestampReset)
                        this.Presence.Timestamps = this.InitialTimestamps;

                    this.CurrentTimestamps = this.Presence.Timestamps;
                }

                finish:;
                this.Presence.replacedets = this.replacedets;

                if (!this.Discord.IsInitialized && !this.Discord.IsDisposed)
                    if (!this.Discord.Initialize())
                        ActivityLog.LogError("DiscordRPforVS", Translates.LogError(Settings.Default.translates));

                this.Discord.SetPresence(this.Presence);
            }
            catch (ArgumentException e)
            {
                ActivityLog.LogError(e.Source, e.Message);
            }
        }

19 View Source File : FileLocatorExtensions.cs
License : MIT License
Project Creator : Accelerider

public static FileType GetFileType(this FileLocator fileLocator)
		{
			if (fileLocator == null || string.IsNullOrWhiteSpace(fileLocator.FileName)) return default;
			var extension = Path.GetExtension(fileLocator.FileName);

			var fileExtension = string.IsNullOrEmpty(extension) ? string.Empty : extension.Substring(1);
			return (from item in FileTypeMapping where item.Value.Contains(fileExtension) select item.Key).FirstOrDefault();
		}

19 View Source File : UserCenterController.cs
License : Apache License 2.0
Project Creator : 91270

[HttpPost]
        [Authorization]
        public IActionResult AvatarUpload([FromForm(Name = "file")] IFormFile file)
        {
            try
            {

                if (Convert.ToBoolean(AppSettings.Configuration["AppSettings:Demo"]))
                {
                    return toResponse(StatusCodeType.Error, "当前为演示模式 , 您无权修改任何数据");
                }

                var fileExtName = Path.GetExtension(file.FileName).ToLower();

                var fileName = DateTime.Now.Ticks.ToString() + fileExtName;

                string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".jpeg" };

                int MaxContentLength = 1024 * 1024 * 4;

                if (!AllowedFileExtensions.Contains(fileExtName))
                {
                    return toResponse(StatusCodeType.Error, "上传失败,未经允许上传类型");
                }


                if (file.Length > MaxContentLength)
                {
                    return toResponse(StatusCodeType.Error, "上传图片过大,不能超过 " + (MaxContentLength / 1024).ToString() + " MB");
                }

                var filePath = $"/{DateTime.Now:yyyyMMdd}/";

                var avatarDirectory = $"{AppSettings.Configuration["AvatarUpload:AvatarDirectory"]}{filePath}";

                if (!Directory.Exists(avatarDirectory))
                {
                    Directory.CreateDirectory(avatarDirectory);
                }

                using (var stream = new FileStream($"{avatarDirectory}{fileName}", FileMode.Create))
                {
                    file.CopyTo(stream);
                }

                var avatarUrl = $"{AppSettings.Configuration["AvatarUpload:AvatarUrl"]}{filePath}{fileName}";

                var userSession = _tokenManager.GetSessionInfo();

                #region 更新用户信息
                var response = _usersService.Update(m => m.UserID == userSession.UserID, m => new Sys_Users
                {
                    AvatarUrl = avatarUrl,
                    UpdateID = userSession.UserID,
                    UpdateName = userSession.UserName,
                    UpdateTime = DateTime.Now
                });
                #endregion

                #region 更新登录会话记录

                _tokenManager.RefreshSession(userSession.UserID);

                #endregion

                return toResponse(avatarUrl);
            }
            catch (Exception)
            {
                throw;
            }
        }

19 View Source File : CodeViewerWindow.xaml.cs
License : MIT License
Project Creator : Actipro

private void UpdateSourcePane() {
			var selectedShellObject = shellListBox.SelectedShellObject;
			if (selectedShellObject != null) {
				if (selectedShellObject.IsFolder) {
					editorDockPanel.Visibility = Visibility.Collapsed;
				}
				else {
					// NOTE: Any changes to supported extensions need to be made in CodeViewerTreeFilter as well
					switch (Path.GetExtension(selectedShellObject.ParsingName).ToUpperInvariant()) {
						case ".CS":
							editor.Doreplacedent.Language = this.ViewModel.SyntaxLanguageCSharp;
							break;
						case ".XAML":
							editor.Doreplacedent.Language = this.ViewModel.SyntaxLanguageXaml;
							break;
						default:
							editor.Doreplacedent.Language = SyntaxLanguage.PlainText;
							break;
					}

					// Load the file
					try {
						editor.Doreplacedent.LoadFile(selectedShellObject.ParsingName);
					}
					catch (Exception ex) {
						editor.Doreplacedent.Language = SyntaxLanguage.PlainText;
						editor.Doreplacedent.SetText(String.Format("An exception occurred while loading the file '{0}':\r\n\r\n{1}", selectedShellObject.ParsingName, ex.Message));
					}

					editorDockPanel.Visibility = Visibility.Visible;
				}
			}
		}

19 View Source File : EditorDocumentWindow.xaml.cs
License : MIT License
Project Creator : Actipro

private void replacedignLanguageAndTextForFileType(string text) {
			var requiresDefaultText = (text == null);
			if (!requiresDefaultText)
				editor.Doreplacedent.SetText(text);

			var extension = Path.GetExtension(this.Data.FileName).ToLowerInvariant();
			editor.Doreplacedent.Language = this.GetOrCreateLanguage(extension);
			if (requiresDefaultText)
				editor.Doreplacedent.SetText(this.GetDefaultText(extension));

			// Update symbol selector visibility
			symbolSelectorBorder.Visibility = (editor.Doreplacedent.Language.GetNavigableSymbolProvider() != null ? Visibility.Visible : Visibility.Collapsed);
			symbolSelector.AreMemberSymbolsSupported = (editor.Doreplacedent.Language.Key != "Python");
		}

19 View Source File : UserLicense.cs
License : GNU General Public License v3.0
Project Creator : a2659802

public static void ShowLicense()
        {
            if(!agreeLicense)
            {
                string bundleN = "userlicense";
                replacedetBundle ab = null;  // You probably want this to be defined somewhere more global.
                replacedembly asm = replacedembly.GetExecutingreplacedembly();
                foreach (string res in asm.GetManifestResourceNames()) 
                {
                    using (Stream s = asm.GetManifestResourceStream(res))
                    {
                        if (s == null) continue;
                        byte[] buffer = new byte[s.Length];
                        s.Read(buffer, 0, buffer.Length);
                        s.Dispose();
                        string bundleName = Path.GetExtension(res).Substring(1);
                        if (bundleName != bundleN) continue;
                        Logger.Log("Loading bundle " + bundleName);
                        ab = replacedetBundle.LoadFromMemory(buffer); // Store this somewhere you can access again.
                    }
                }
                var _canvas = ab.Loadreplacedet<GameObject>("userlicense");
                UnityEngine.Object.Instantiate(_canvas);
                Logger.Log("Show User License");
            }
        }

19 View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro

private void AddStatsForFile(StatData data, string path) {
			if (!File.Exists(path))
				return;

			// Get the file text
			try {
				string text = File.ReadAllText(path);

				// Calculate stats
				ActiproSoftware.Text.Implementation.TextStatistics statistics = new ActiproSoftware.Text.Implementation.TextStatistics(text);

				// Append stats
				switch (Path.GetExtension(path).ToLower()) {
					case ".cs":
						data.CSharpFileCount++;
						break;
					case ".vb":
						data.VBFileCount++;
						break;
					case ".xaml":
						data.XamlFileCount++;
						break;
				}
				data.NonWhitespaceLineCount += statistics.NonWhitespaceLines;
				data.WhitespaceLineCount += statistics.WhitespaceLines;
			}
			catch {}
		}

19 View Source File : StringExtension.cs
License : MIT License
Project Creator : 3F

public static Dictionary<string, string> GetFileProperties(this string file)
        {
            if(string.IsNullOrEmpty(file))
            {
                return new Dictionary<string, string>()
                {
                    [PropertyNames.SLN_DIR]     = PropertyNames.UNDEFINED,
                    [PropertyNames.SLN_EXT]     = PropertyNames.UNDEFINED,
                    [PropertyNames.SLN_FNAME]   = PropertyNames.UNDEFINED,
                    [PropertyNames.SLN_NAME]    = PropertyNames.UNDEFINED,
                    [PropertyNames.SLN_PATH]    = PropertyNames.UNDEFINED,
                };
            }

            return new Dictionary<string, string>()
            {
                [PropertyNames.SLN_DIR]     = GetDirectoryFromFile(file),
                [PropertyNames.SLN_EXT]     = Path.GetExtension(file),
                [PropertyNames.SLN_FNAME]   = Path.GetFileName(file),
                [PropertyNames.SLN_NAME]    = Path.GetFileNameWithoutExtension(file),
                [PropertyNames.SLN_PATH]    = file,
            };
        }

19 View Source File : ParsedDocument.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static bool IsSupportedFileType(Doreplacedent doreplacedent) => allowedExtensions.Contains(Path.GetExtension(doreplacedent.FilePath));

19 View Source File : DataBaseManager.cs
License : MIT License
Project Creator : Abdesol

public string ExportData(string path)
        {
            if (Path.GetExtension(path) != ".whl") return "This type of file are not supported!";
            _db.Close();
            var bytes = File.ReadAllBytes(dbpath);
            File.WriteAllBytes(path, bytes);
            OpenDB();

            return "Successfully exported your codes!";
        }

19 View Source File : CLangCompiler.cs
License : MIT License
Project Creator : adamant

public int Compile(
            ICompilerOutput output,
            string[] sourceFiles,
            string[] headerSearchPaths,
            string outputPath)
        {
            // used to have: -Wno-incompatible-pointer-types
            var options = "-std=c11 -fsanitize=undefined -fsanitize=integer -fsanitize=nullability -Wall -Wno-unused-label";
            // Next thing is needed for windows
            options += " -Xclang -flto-visibility-public-std";
            if (Path.GetExtension(outputPath) == ".dll") // TODO take this as an argument or something
                options += " --shared";
            var sources = string.Join(' ', sourceFiles);
            var headers = string.Join(' ', headerSearchPaths.Select(h => "--include-directory " + h));
            var arguments = $"{sources} -o {outputPath} {headers} {options}";
            output.WriteLine("clang arguments:");
            output.WriteLine(arguments);
            var startInfo = new ProcessStartInfo("clang", arguments)
            {
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true,
                UseShellExecute = false,
            };
            var process = new Process() { StartInfo = startInfo };
            // To prevent blocking on a full buffer, we have to process output as it happens
            process.OutputDataReceived += ProcessOutput;
            process.ErrorDataReceived += ProcessOutput;
            output.WriteLine("clang output:");
            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            process.WaitForExit();
            return process.ExitCode;

            void ProcessOutput(object s, DataReceivedEventArgs e)
            {
                output.WriteLine(e.Data);
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 0x727

public static void Copy(string inputfile, string randomname, string min)
        {
            string appdataFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string sourceFile = [email protected]"{inputfile}";
            //获取拓展名
            string extension = Path.GetExtension(sourceFile);
            string destinationFile = appdataFile + [email protected]"\Microsoft\Windows\Themes\{randomname}" + extension;
            if (File.Exists(destinationFile))
            {
                Console.WriteLine($"\n[x] File name exists: {destinationFile}");
                return;
            }
            else
            {
                File.Copy(sourceFile, destinationFile);
                //File.Move(sourceFile, destinationFile);
                Console.WriteLine($"\n[*] Copy File location: \n{destinationFile}");
                CreateTask(randomname, destinationFile, min);
            }
        }

19 View Source File : AssertFile.cs
License : Apache License 2.0
Project Creator : adamralph

public static async Task Contains(string expectedPath, string actual)
        {
            var actualPath = Path.Combine(
                Path.GetDirectoryName(expectedPath),
                Path.GetFileNameWithoutExtension(expectedPath) + "-actual" + Path.GetExtension(expectedPath));

            if (File.Exists(actualPath))
            {
                File.Delete(actualPath);
            }

            var expected = await File.ReadAllTextAsync(expectedPath);

            try
            {
                replacedert.Equal(expected, actual);
            }
            catch (EqualException ex)
            {
                await File.WriteAllTextAsync(actualPath, actual, Encoding.UTF8);

                throw new XunitException(
                    $"{ex.Message}{Environment.NewLine}{Environment.NewLine}Expected file: {expectedPath}{Environment.NewLine}Actual file: {actualPath}");
            }
        }

19 View Source File : ScriptableObjectExtensions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static ScriptableObject Createreplacedet(this ScriptableObject scriptableObject, string path = null, string fileName = null)
        {
            var name = string.IsNullOrEmpty(fileName) ? $"{scriptableObject.GetType().Name}" : fileName;

            if (string.IsNullOrEmpty(path))
            {
                path = "replacedets";
            }

            if (Path.GetExtension(path) != string.Empty)
            {
                var subtractedPath = path.Substring(path.LastIndexOf("/", StringComparison.Ordinal));
                path = path.Replace(subtractedPath, string.Empty);
            }

            if (!Directory.Exists(Path.GetFullPath(path)))
            {
                Directory.CreateDirectory(Path.GetFullPath(path));
            }

            string replacedetPathAndName = replacedetDatabase.GenerateUniquereplacedetPath($"{path}/{name}.replacedet");

            replacedetDatabase.Createreplacedet(scriptableObject, replacedetPathAndName);
            replacedetDatabase.Savereplacedets();
            replacedetDatabase.Refresh();
            EditorGUIUtility.PingObject(scriptableObject);
            return scriptableObject;
        }

19 View Source File : ExtendedViewLocalizer.cs
License : MIT License
Project Creator : adams85

private static string BuildBaseName(string path, string location)
        {
            var extension = Path.GetExtension(path);
            var startIndex = path[0] == '/' || path[0] == '\\' ? 1 : 0;
            var length = path.Length - startIndex - extension.Length;
            var capacity = length + location.Length + 1;
            var builder = new StringBuilder(path, startIndex, length, capacity);

            builder.Replace('/', '.').Replace('\\', '.');

            // Prepend the application name
            builder.Insert(0, '.');
            builder.Insert(0, location);

            return builder.ToString();
        }

19 View Source File : AssetBundleUtil.cs
License : MIT License
Project Creator : 404Lcc

public static void BuildreplacedetBundle(replacedetBundleSetting replacedetBundleSetting)
        {
            Dictionary<string, replacedetBundleData> replacedetBundleDataDict = new Dictionary<string, replacedetBundleData>();
            Dictionary<string, replacedetBundleRuleType> replacedetBundleRuleTypeDict = new Dictionary<string, replacedetBundleRuleType>();
            string path = PathUtil.GetPath(PathType.DataPath, replacedetBundleSetting.outputPath, GetPlatformForreplacedetBundle(EditorUserBuildSettings.activeBuildTarget));
            foreach (DirectoryInfo item in DirectoryUtil.GetDirectorys(new DirectoryInfo(path), new List<DirectoryInfo>()))
            {
                item.Delete();
            }
            foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(path), new List<FileInfo>()))
            {
                item.Delete();
            }
            List<replacedetBundleBuild> replacedetBundleBuildList = new List<replacedetBundleBuild>();
            foreach (replacedetBundleRule item in replacedetBundleSetting.replacedetBundleRuleList)
            {
                if (item.replacedetBundleRuleType == replacedetBundleRuleType.File)
                {
                    FileInfo[] fileInfos = FileUtil.GetFiles(new DirectoryInfo(item.path), new List<FileInfo>());
                    if (fileInfos.Length == 0) continue;
                    List<FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
                    foreach (FileInfo fileInfo in fileInfoList)
                    {
                        replacedetBundleRuleTypeDict.Add(fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("replacedets")).Replace("\\", "/"), replacedetBundleRuleType.File);
                    }
                }
                if (item.replacedetBundleRuleType == replacedetBundleRuleType.Directory)
                {
                    DirectoryInfo[] directoryInfos = DirectoryUtil.GetDirectorys(new DirectoryInfo(item.path), new List<DirectoryInfo>());
                    if (directoryInfos.Length == 0) continue;
                    foreach (DirectoryInfo directoryInfo in directoryInfos)
                    {
                        FileInfo[] fileInfos = directoryInfo.GetFiles();
                        if (fileInfos.Length == 0) continue;
                        List<FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
                        foreach (FileInfo fileInfo in fileInfoList)
                        {
                            replacedetBundleRuleTypeDict.Add(fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("replacedets")).Replace("\\", "/"), replacedetBundleRuleType.Directory);
                        }
                    }
                }
            }
            foreach (replacedetBundleData item in replacedetBundleSetting.replacedetBundleDataList)
            {
                replacedetBundleBuildList.Add(new replacedetBundleBuild()
                {
                    replacedetBundleName = item.replacedetBundleName,
                    replacedetNames = item.replacedetNames,
                });
            }
            replacedetBundleManifest replacedetBundleManifest = BuildPipeline.BuildreplacedetBundles(path, replacedetBundleBuildList.ToArray(), BuildreplacedetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget);
            foreach (replacedetBundleData item in replacedetBundleSetting.replacedetBundleDataList)
            {
                item.replacedetBundleHash = replacedetBundleManifest.GetreplacedetBundleHash(item.replacedetBundleName).ToString();
                BuildPipeline.GetCRCForreplacedetBundle($"{path}/{item.replacedetBundleName}", out item.replacedetBundleCRC);
                item.fileSize = FileUtil.GetFileSize($"{path}/{item.replacedetBundleName}");
                replacedetBundleDataDict.Add(Path.GetFileNameWithoutExtension(item.replacedetBundleName), item);
            }
            replacedetBundleConfig replacedetBundleConfig = new replacedetBundleConfig(replacedetBundleSetting.buildId, replacedetBundleDataDict, replacedetBundleRuleTypeDict);
            FileUtil.Savereplacedet(path, "replacedetBundleConfig.json", JsonUtil.ToJson(replacedetBundleConfig));
            if (replacedetBundleSetting.isCopyStreamingreplacedets)
            {
                string copyPath = PathUtil.GetPath(PathType.StreamingreplacedetsPath, "Res", GetPlatformForreplacedetBundle(EditorUserBuildSettings.activeBuildTarget));
                foreach (DirectoryInfo item in DirectoryUtil.GetDirectorys(new DirectoryInfo(copyPath), new List<DirectoryInfo>()))
                {
                    item.Delete();
                }
                foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(copyPath), new List<FileInfo>()))
                {
                    item.Delete();
                }
                foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(path), new List<FileInfo>()))
                {
                    if (Path.GetExtension(item.Name) == ".meta") continue;
                    File.Copy(item.FullName, $"{PathUtil.GetPath(PathType.StreamingreplacedetsPath, "Res", GetPlatformForreplacedetBundle(EditorUserBuildSettings.activeBuildTarget))}/{item.Name}");
                }
            }
            replacedetDatabase.Refresh();
        }

19 View Source File : SettingsWindowViewModel.cs
License : MIT License
Project Creator : adlez27

public void GenerateRecListFromFolder()
        {
            recList = new ObservableCollection<RecLisreplacedem>();
            var allFiles = Directory.GetFiles(DestinationFolder);
            foreach(var file in allFiles)
            {
                if (Path.GetExtension(file) == ".wav")
                    recList.Add(new RecLisreplacedem(settings,Path.GetFileNameWithoutExtension(file)));
            }
            newRecList = true;
            recListFromFolder = true;
            RecListFile = "List generated from files in folder.";
        }

19 View Source File : GltfEditorImporter.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static async void OnImportGltfreplacedet(replacedetImportContext context)
        {
            var importedObject = await GltfUtility.ImportGltfObjectFromPathAsync(context.replacedetPath);

            if (importedObject == null ||
                importedObject.GameObjectReference == null)
            {
                Debug.LogError("Failed to import glTF object");
                return;
            }

            var gltfreplacedet = (Gltfreplacedet)ScriptableObject.CreateInstance(typeof(Gltfreplacedet));

            gltfreplacedet.GltfObject = importedObject;
            gltfreplacedet.name = $"{gltfreplacedet.GltfObject.Name}{Path.GetExtension(context.replacedetPath)}";
            gltfreplacedet.Model = importedObject.GameObjectReference;
            context.AddObjectToreplacedet("main", gltfreplacedet.Model);
            context.SetMainObject(importedObject.GameObjectReference);
            context.AddObjectToreplacedet("glTF data", gltfreplacedet);

            bool reImport = false;

            for (var i = 0; i < gltfreplacedet.GltfObject.textures?.Length; i++)
            {
                GltfTexture gltfTexture = gltfreplacedet.GltfObject.textures[i];

                if (gltfTexture == null) { continue; }

                var path = replacedetDatabase.GetreplacedetPath(gltfTexture.Texture);

                if (string.IsNullOrWhiteSpace(path))
                {
                    var textureName = gltfTexture.name;

                    if (string.IsNullOrWhiteSpace(textureName))
                    {
                        textureName = $"Texture_{i}";
                        gltfTexture.Texture.name = textureName;
                    }

                    context.AddObjectToreplacedet(textureName, gltfTexture.Texture);
                }
                else
                {
                    if (!gltfTexture.Texture.isReadable)
                    {
                        var textureImporter = replacedetImporter.GetAtPath(path) as TextureImporter;
                        if (textureImporter != null)
                        {
                            textureImporter.isReadable = true;
                            textureImporter.SetPlatformTextureSettings(new TextureImporterPlatformSettings { format = TextureImporterFormat.RGBA32 });
                            textureImporter.SaveAndReimport();
                            reImport = true;
                        }
                    }
                }
            }

            if (reImport)
            {
                var importer = replacedetImporter.GetAtPath(context.replacedetPath);
                importer.SaveAndReimport();
                return;
            }

            for (var i = 0; i < gltfreplacedet.GltfObject.meshes?.Length; i++)
            {
                GltfMesh gltfMesh = gltfreplacedet.GltfObject.meshes[i];

                string meshName = string.IsNullOrWhiteSpace(gltfMesh.name) ? $"Mesh_{i}" : gltfMesh.name;

                gltfMesh.Mesh.name = meshName;
                context.AddObjectToreplacedet($"{meshName}", gltfMesh.Mesh);
            }

            if (gltfreplacedet.GltfObject.materials != null)
            {
                foreach (GltfMaterial gltfMaterial in gltfreplacedet.GltfObject.materials)
                {
                    if (context.replacedetPath.EndsWith(".glb"))
                    {
                        context.AddObjectToreplacedet(gltfMaterial.name, gltfMaterial.Material);
                    }
                    else
                    {
                        var relativePath = Path.GetFullPath(Path.GetDirectoryName(context.replacedetPath)).Replace(Path.GetFullPath(Application.dataPath), "replacedets");
                        relativePath = Path.Combine(relativePath, $"{gltfMaterial.name}.mat");
                        replacedetDatabase.Createreplacedet(gltfMaterial.Material, relativePath);
                        gltfMaterial.Material = replacedetDatabase.LoadreplacedetAtPath<Material>(relativePath);
                    }
                }
            }
        }

19 View Source File : RealXamlPacakge.cs
License : MIT License
Project Creator : admaiorastudio

public int OnAfterSave(uint docCookie)
        {
            if (!UpdateManager.Current.IsConnected)
            {
                System.Diagnostics.Debug.WriteLine("RealXaml was unable to send the xaml. No connection to the notifier.");
                return VSConstants.S_OK;
            }

            ThreadHelper.ThrowIfNotOnUIThread();

            if (_dte == null)
                return VSConstants.S_OK;

            try
            {
                Doreplacedent doc = FindDoreplacedentByCookie(docCookie);
                if (doc == null)
                    return VSConstants.S_OK;

                string kind = doc.Kind;
                string lang = doc.Language;

                string filePath = doc.FullName;
                string fileExt = Path.GetExtension(filePath)?.ToLower() ?? ".unknown";
                if (fileExt != ".xaml")
                    return VSConstants.S_OK;

                XDoreplacedent xdoc = XDoreplacedent.Load(filePath);
                XNamespace xnsp = "http://schemas.microsoft.com/winfx/2009/xaml";
                string pageId = xdoc.Root.Attribute(xnsp + "Clreplaced").Value;

                TextDoreplacedent textdoc = (TextDoreplacedent)(doc.Object("TextDoreplacedent"));
                var p = textdoc.StartPoint.CreateEditPoint();
                string xaml = p.GetText(textdoc.EndPoint);

                _xamlCache[pageId] = xaml;

                // Save is due to a project build
                // Xaml will be sent after the build
                if (!this.IsBuilding)
                {
                    Task.Run(
                        async () =>
                        {
                            try
                            {
                                await UpdateManager.Current.SendXamlAsync(pageId, xaml, true);
                            }
                            catch (Exception ex)
                            {
                                _outputPane.OutputString($"Something went wrong! RealXaml was unable to send the xaml.");
                                _outputPane.OutputString(Environment.NewLine);
                                _outputPane.OutputString(ex.ToString());
                                _outputPane.OutputString(Environment.NewLine);

                                System.Diagnostics.Debug.WriteLine("Something went wrong! RealXaml was unable to send the xaml.");
                                System.Diagnostics.Debug.WriteLine(ex);

                            }
                        });
                }
            }
            catch (Exception ex)
            {
                _outputPane.OutputString($"Something went wrong! RealXaml was unable to send the xaml.");
                _outputPane.OutputString(Environment.NewLine);
                _outputPane.OutputString(ex.ToString());
                _outputPane.OutputString(Environment.NewLine);

                System.Diagnostics.Debug.WriteLine("Something went wrong! RealXaml was unable to send the xaml.");
                System.Diagnostics.Debug.WriteLine(ex);
            }

            return VSConstants.S_OK;
        }

19 View Source File : EdisFace.cs
License : MIT License
Project Creator : 0ffffffffh

private void RequestHandler(IAsyncResult result)
        {
            Dictionary<string, string> form;

            string objectName,path;
            HttpListenerContext ctx;

            if (!this.httpListener.IsListening)
                return;

            try
            {
                ctx = this.httpListener.EndGetContext(result);
            }
            catch (Exception e)
            {
                Log.Error("request completion error: " + e.Message);
                RegisterRequestWaiter(null);
                return;
            }

            form = BuildForm(ctx);

            objectName = ctx.Request.Url.LocalPath;

            var ext = Path.GetExtension(objectName);
            objectName = Path.GetFileNameWithoutExtension(objectName);

            objectName = objectName.
                Replace(".", "").
                Replace("/","").
                Replace("\\","");

            if (string.IsNullOrEmpty(objectName))
                objectName = "\\";
            else
                objectName = "\\" + objectName + ext;

            path = Config.Get().HtmlContentRoot + objectName;
            
            RegisterRequestWaiter(null);

            if (objectName == "\\")
            {
                if (ctx.Request.HttpMethod.ToLower() == "post")
                {
                    HandlePost(ctx, form);
                }
                else
                    ReplyIndex(ctx, string.Empty);
            }
            else
            {
                ReplyWithFile(ctx, path);
            }
            
            ctx.Response.Close();
        }

19 View Source File : AnnotationDataAdapter.cs
License : MIT License
Project Creator : Adoxio

public IAnnotationResult CreateAnnotation(IAnnotation note, IAnnotationSettings settings = null)
		{
			var serviceContext = _dependencies.GetServiceContext();
			var serviceContextForWrite = _dependencies.GetServiceContextForWrite();

			if (settings == null)
			{
				settings = new AnnotationSettings(serviceContext);
			}
			
			var storageAccount = GetStorageAccount(serviceContext);
			if (settings.StorageLocation == StorageLocation.AzureBlobStorage && storageAccount == null)
			{
				settings.StorageLocation = StorageLocation.CrmDoreplacedent;
			}

			AnnotationCreateResult result = null;

			if (settings.RespectPermissions)
			{
				var enreplacedyPermissionProvider = new CrmEnreplacedyPermissionProvider();
				result = new AnnotationCreateResult(enreplacedyPermissionProvider, serviceContext, note.Regarding);
			}

			// ReSharper disable once PossibleNullReferenceException
			if (!settings.RespectPermissions ||
				(result.PermissionsExist && result.PermissionGranted))
			{
				var enreplacedy = new Enreplacedy("annotation");

				if (note.Owner != null)
				{
					enreplacedy.SetAttributeValue("ownerid", note.Owner);
				}

				enreplacedy.SetAttributeValue("subject", note.Subject);
				enreplacedy.SetAttributeValue("notetext", note.NoteText);
				enreplacedy.SetAttributeValue("objectid", note.Regarding);
				enreplacedy.SetAttributeValue("objecttypecode", note.Regarding.LogicalName);

				if (note.FileAttachment != null)
				{
					var acceptMimeTypes = AnnotationDataAdapter.GetAcceptRegex(settings.AcceptMimeTypes);
					var acceptExtensionTypes = AnnotationDataAdapter.GetAcceptRegex(settings.AcceptExtensionTypes);
					if (!(acceptExtensionTypes.IsMatch(Path.GetExtension(note.FileAttachment.FileName).ToLower()) ||
							acceptMimeTypes.IsMatch(note.FileAttachment.MimeType)))
					{
						throw new AnnotationException(settings.RestrictMimeTypesErrorMessage);
					}

					if (settings.MaxFileSize.HasValue && note.FileAttachment.FileSize > settings.MaxFileSize)
					{
						throw new AnnotationException(settings.MaxFileSizeErrorMessage);
					}

					note.FileAttachment.Annotation = enreplacedy;

					switch (settings.StorageLocation)
					{
					case StorageLocation.CrmDoreplacedent:
						var crmFile = note.FileAttachment as CrmAnnotationFile;
						if (crmFile == null)
						{
							break;
						}

						if (!string.IsNullOrEmpty(settings.RestrictedFileExtensions))
						{
							var blocked = new Regex(@"\.({0})$".FormatWith(settings.RestrictedFileExtensions.Replace(";", "|")));
							if (blocked.IsMatch(crmFile.FileName))
							{
								throw new AnnotationException(settings.RestrictedFileExtensionsErrorMessage);
							}
						}

						enreplacedy.SetAttributeValue("filename", crmFile.FileName);
						enreplacedy.SetAttributeValue("mimetype", crmFile.MimeType);
						enreplacedy.SetAttributeValue("doreplacedentbody", Convert.ToBase64String(crmFile.Doreplacedent));
						break;
					case StorageLocation.AzureBlobStorage:
						enreplacedy.SetAttributeValue("filename", note.FileAttachment.FileName + ".azure.txt");
						enreplacedy.SetAttributeValue("mimetype", "text/plain");
						var fileMetadata = new
						{
							Name = note.FileAttachment.FileName,
							Type = note.FileAttachment.MimeType,
							Size = (ulong)note.FileAttachment.FileSize,
							Url = string.Empty
						};
						enreplacedy.SetAttributeValue("doreplacedentbody",
							Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileMetadata, Formatting.Indented))));
						break;
					}
				}

				// Create annotaion but skip cache invalidation.
				var id = (serviceContext as IOrganizationService).ExecuteCreate(enreplacedy, RequestFlag.ByPreplacedCacheInvalidation);

				if (result != null) result.Annotation = note;

				note.AnnotationId = enreplacedy.Id = id;
				note.Enreplacedy = enreplacedy;

				if (note.FileAttachment is AzureAnnotationFile && settings.StorageLocation == StorageLocation.AzureBlobStorage)
				{
					var container = GetBlobContainer(storageAccount, _containerName);

					var azureFile = (AzureAnnotationFile)note.FileAttachment;

					azureFile.BlockBlob = UploadBlob(azureFile, container, note.AnnotationId);

					var fileMetadata = new
					{
						Name = azureFile.FileName,
						Type = azureFile.MimeType,
						Size = (ulong)azureFile.FileSize,
						Url = azureFile.BlockBlob.Uri.AbsoluteUri
					};
					enreplacedy.SetAttributeValue("doreplacedentbody",
						Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileMetadata, Formatting.Indented))));
					serviceContextForWrite.UpdateObject(enreplacedy);
					serviceContextForWrite.SaveChanges();

					// NB: This is basically a hack to support replication. Keys are gathered up and stored during replication, and the
					// actual blob replication is handled here.
					var key = note.AnnotationId.ToString("N");
					if (HttpContext.Current.Application.AllKeys.Contains(NoteReplication.BlobReplicationKey))
					{
						var replication =
							HttpContext.Current.Application[NoteReplication.BlobReplicationKey] as Dictionary<string, Tuple<Guid, Guid>[]>;
						if (replication != null && replication.ContainsKey(key))
						{
							CopyBlob(note, replication[key]);
							replication.Remove(key);
						}
					}
				} 
			}

			if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
			{
				PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Note, HttpContext.Current, "create_note", 1, note.Enreplacedy.ToEnreplacedyReference(), "create");
			}

			return result;
		}

19 View Source File : OVRCubemapCapture.cs
License : MIT License
Project Creator : absurd-joy

public static bool SaveCubemapCapture(Cubemap cubemap, string pathName = null)
	{
		string fileName;
		string dirName;
		int width = cubemap.width;
		int height = cubemap.height;
		int x = 0;
		int y = 0;
		bool saveToPNG = true;

		if (string.IsNullOrEmpty(pathName))
		{
			dirName = Application.persistentDataPath + "/OVR_ScreenShot360/";
			fileName = null;
		}
		else
		{
			dirName = Path.GetDirectoryName(pathName);
			fileName = Path.GetFileName(pathName);

			if (dirName[dirName.Length - 1] != '/' || dirName[dirName.Length - 1] != '\\')
				dirName += "/";
		}

		if (string.IsNullOrEmpty(fileName))
			fileName = "OVR_" + System.DateTime.Now.ToString("hh_mm_ss") + ".png";

		string extName = Path.GetExtension(fileName);
		if (extName == ".png")
		{
			saveToPNG = true;
		}
		else if (extName == ".jpg")
		{
			saveToPNG = false;
		}
		else
		{
            Debug.LogError("Unsupported file format" + extName);
			return false;
		}

		// Validate path
		try
		{
			System.IO.Directory.CreateDirectory(dirName);
		}
		catch (System.Exception e)
		{
            Debug.LogError("Failed to create path " + dirName + " since " + e.ToString());
			return false;
		}


		// Create the new texture
		Texture2D tex = new Texture2D(width * 6, height, TextureFormat.RGB24, false);
		if (tex == null)
		{
			Debug.LogError("[OVRScreenshotWizard] Failed creating the texture!");
			return false;
		}

		// Merge all the cubemap faces into the texture
		// Reference cubemap format: http://docs.unity3d.com/Manual/clreplaced-Cubemap.html
		CubemapFace[] faces = new CubemapFace[] { CubemapFace.PositiveX, CubemapFace.NegativeX, CubemapFace.PositiveY, CubemapFace.NegativeY, CubemapFace.PositiveZ, CubemapFace.NegativeZ };
		for (int i = 0; i < faces.Length; i++)
		{
			// get the pixels from the cubemap
			Color[] srcPixels = null;
			Color[] pixels = cubemap.GetPixels(faces[i]);
			// if desired, flip them as they are ordered left to right, bottom to top
			srcPixels = new Color[pixels.Length];
			for (int y1 = 0; y1 < height; y1++)
			{
				for (int x1 = 0; x1 < width; x1++)
				{
					srcPixels[y1 * width + x1] = pixels[((height - 1 - y1) * width) + x1];
				}
			}
			// Copy them to the dest texture
			tex.SetPixels(x, y, width, height, srcPixels);
			x += width;
		}

        try
        {
            // Encode the texture and save it to disk
            byte[] bytes = saveToPNG ? tex.EncodeToPNG() : tex.EncodeToJPG();

            System.IO.File.WriteAllBytes(dirName + fileName, bytes);
            Debug.Log("Cubemap file created " + dirName + fileName);
        }
        catch (System.Exception e)
        {
            Debug.LogError("Failed to save cubemap file since " + e.ToString());
			return false;
        }

		DestroyImmediate(tex);
		return true;
	}

19 View Source File : AliyunOssManager.cs
License : MIT License
Project Creator : 52ABP

public  OssFileData UpLoad(string key, string fileToUpload)
        {
            var fileExtensionName = Path.GetExtension(fileToUpload);//文件扩展名
            var filePath = $"{key}{fileExtensionName}";//云文件保存路径  
            try
            {
                Client.PutObject(AliyunOssConfigInfo.BucketName, filePath, fileToUpload);
                var fielData = new OssFileData
                {
                    Url = AliyunOssConfigInfo.BucketName + "." + AliyunOssConfigInfo.Endpoint + "/" + filePath
                };
                return fielData;
            }
            catch (Exception e)
            {
                throw new UserFriendlyException($"文件上传失败:{e.Message}");
            }
        }

19 View Source File : EdisFace.cs
License : MIT License
Project Creator : 0ffffffffh

private bool ReplyWithFile(HttpListenerContext ctx, string fileName)
        {
            Stream fs;

            if (!File.Exists(fileName))
                return false;

            try
            {
                fs = File.OpenRead(fileName);
            }
            catch(Exception e)
            {
                Log.Error("{0} - {1}", fileName, e.Message);
                return false;
            }

            ctx.Response.ContentLength64 = fs.Length;
            ctx.Response.StatusCode = 200;

            ctx.Response.ContentEncoding = Encoding.ASCII;
            ctx.Response.ContentType = MimeTypeFromExt(Path.GetExtension(fileName));

            fs.CopyTo(ctx.Response.OutputStream);

            fs.Close();
            fs.Dispose();

            return true;
        }

19 View Source File : XnaToFnaUtil.cs
License : zlib License
Project Creator : 0x0ade

public void ScanPath(string path) {
            if (Directory.Exists(path)) {
                // Use the directory as "dependency directory" and scan in it.
                if (Directories.Contains(path))
                    // No need to scan the dir if the dir is scanned...
                    return;

                RestoreBackup(path);

                Log($"[ScanPath] Scanning directory {path}");
                Directories.Add(path);
                replacedemblyResolver.AddSearchDirectory(path); // Needs to be added manually as DependencyDirs was already added

                // Most probably the actual game directory - let's just copy XnaToFna.exe to there to be referenced properly.
                string xtfPath = Path.Combine(path, Path.GetFileName(Thisreplacedembly.Location));
                if (Path.GetDirectoryName(Thisreplacedembly.Location) != path) {
                    Log($"[ScanPath] Found separate game directory - copying XnaToFna.exe and FNA.dll");
                    File.Copy(Thisreplacedembly.Location, xtfPath, true);

                    string dbExt = null;
                    if (File.Exists(Path.ChangeExtension(Thisreplacedembly.Location, "pdb")))
                        dbExt = "pdb";
                    if (File.Exists(Path.ChangeExtension(Thisreplacedembly.Location, "mdb")))
                        dbExt = "mdb";
                    if (dbExt != null)
                        File.Copy(Path.ChangeExtension(Thisreplacedembly.Location, dbExt), Path.ChangeExtension(xtfPath, dbExt), true);

                    if (File.Exists(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll")))
                        File.Copy(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll"), Path.Combine(path, "FNA.dll"), true);
                    else if (File.Exists(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll.tmp")))
                        File.Copy(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll.tmp"), Path.Combine(path, "FNA.dll"), true);

                }

                ScanPaths(Directory.GetFiles(path));
                return;
            }

            if (File.Exists(path + ".xex")) {
                if (!ExtractedXEX.Contains(path)) {
                    // Remove the original file - let XnaToFna unpack and handle it later.
                    File.Delete(path);
                } else {
                    // XnaToFna will handle the .xex instead.
                }
                return;
            }

            if (path.EndsWith(".xex")) {
                string pathTarget = path.Substring(0, path.Length - 4);
                if (string.IsNullOrEmpty(Path.GetExtension(pathTarget)))
                    return;

                using (Stream streamXEX = File.OpenRead(path))
                using (BinaryReader reader = new BinaryReader(streamXEX))
                using (Stream streamRAW = File.OpenWrite(pathTarget)) {
                    XEXImageData data = new XEXImageData(reader);

                    int offset = 0;
                    int size = data.m_memorySize;

                    // Check if this file is a PE containing an embedded PE.
                    if (data.m_memorySize > 0x10000) { // One default segment alignment.
                        using (MemoryStream streamMEM = new MemoryStream(data.m_memoryData))
                        using (BinaryReader mem = new BinaryReader(streamMEM)) {
                            if (mem.ReadUInt32() != 0x00905A4D) // MZ
                                goto WriteRaw;
                            // This is horrible.
                            streamMEM.Seek(0x00000280, SeekOrigin.Begin);
                            if (mem.ReadUInt64() != 0x000061746164692E) // ".idata\0\0"
                                goto WriteRaw;
                            streamMEM.Seek(0x00000288, SeekOrigin.Begin);
                            mem.ReadInt32(); // Virtual size; It's somewhat incorrect?
                            offset = mem.ReadInt32(); // Virtual offset.
                            // mem.ReadInt32(); // Raw size; Still incorrect.
                            // Let's just write everything...
                            size = data.m_memorySize - offset;
                        }
                    }

                    WriteRaw:
                    streamRAW.Write(data.m_memoryData, offset, size);
                }

                path = pathTarget;
                ExtractedXEX.Add(pathTarget);
            } else if (!path.EndsWith(".dll") && !path.EndsWith(".exe"))
                return;

            // Check if .dll is CLR replacedembly
            replacedemblyName name;
            try {
                name = replacedemblyName.GetreplacedemblyName(path);
            } catch {
                return;
            }

            ReaderParameters modReaderParams = Modder.GenReaderParameters(false);
            // Don't ReadWrite if the module being read is XnaToFna or a relink target.
            bool isReadWrite =
#if !CECIL0_9
            modReaderParams.ReadWrite =
#endif
                path != Thisreplacedembly.Location &&
                !Mappings.Exists(mappings => name.Name == mappings.Target);
            // Only read debug info if it exists
            if (!File.Exists(path + ".mdb") && !File.Exists(Path.ChangeExtension(path, "pdb")))
                modReaderParams.ReadSymbols = false;
            Log($"[ScanPath] Checking replacedembly {name.Name} ({(isReadWrite ? "rw" : "r-")})");
            ModuleDefinition mod;
            try {
                mod = MonoModExt.ReadModule(path, modReaderParams);
            } catch (Exception e) {
                Log($"[ScanPath] WARNING: Cannot load replacedembly: {e}");
                return;
            }
            bool add = !isReadWrite || name.Name == ThisreplacedemblyName;

            if ((mod.Attributes & ModuleAttributes.ILOnly) != ModuleAttributes.ILOnly) {
                // Mono.Cecil can't handle mixed mode replacedemblies.
                Log($"[ScanPath] WARNING: Cannot handle mixed mode replacedembly {name.Name}");
                if (MixedDeps == MixedDepAction.Stub) {
                    ModulesToStub.Add(mod);
                    add = true;
                } else {
                    if (MixedDeps == MixedDepAction.Remove) {
                        RemoveDeps.Add(name.Name);
                    }
#if !CECIL0_9
                    mod.Dispose();
#endif
                    return;
                }
            }

            if (add && !isReadWrite) { // XNA replacement
                foreach (XnaToFnaMapping mapping in Mappings)
                    if (name.Name == mapping.Target) {
                        mapping.IsActive = true;
                        mapping.Module = mod;
                        foreach (string from in mapping.Sources) {
                            Log($"[ScanPath] Mapping {from} -> {name.Name}");
                            Modder.RelinkModuleMap[from] = mod;
                        }
                    }
            } else if (!add) {
                foreach (XnaToFnaMapping mapping in Mappings)
                    if (mod.replacedemblyReferences.Any(dep => mapping.Sources.Contains(dep.Name))) {
                        add = true;
                        Log($"[ScanPath] XnaToFna-ing {name.Name}");
                        goto BreakMappings;
                    }
            }
            BreakMappings:

            if (add) {
                Modules.Add(mod);
                ModulePaths[mod] = path;
            } else {
#if !CECIL0_9
                mod.Dispose();
#endif
            }

        }

19 View Source File : SlnTest.cs
License : MIT License
Project Creator : 3F

[Fact]
        public void SlnResultTest1()
        {
            using(var sln = new Sln(SlnItems.Projects, SlnSamplesResource.vsSolutionBuildEvent))
            {
                replacedert.Equal("\\", sln.Result.SolutionDir);
                replacedert.Equal(SlnParser.MEM_FILE, sln.Result.Properties[PropertyNames.SLN_PATH]);

                replacedert.Equal(sln.Result.SolutionDir, sln.Result.Properties[PropertyNames.SLN_DIR]);
                replacedert.Equal(Path.GetExtension(SlnParser.MEM_FILE), sln.Result.Properties[PropertyNames.SLN_EXT]);
                replacedert.Equal(Path.GetFileName(SlnParser.MEM_FILE), sln.Result.Properties[PropertyNames.SLN_FNAME]);
                replacedert.Equal(Path.GetFileNameWithoutExtension(SlnParser.MEM_FILE), sln.Result.Properties[PropertyNames.SLN_NAME]);
                replacedert.Null(sln.Result.Properties[PropertyNames.CONFIG]);
                replacedert.Null(sln.Result.Properties[PropertyNames.PLATFORM]);
            }
        }

19 View Source File : SelectFm.cs
License : GNU General Public License v3.0
Project Creator : a4004

private async Task ListSoftwareOptions(string option)
        {
            string[] availableFiles = API.GithubManager.GetReleaseNames("spacehuhntech/esp8266_deauther", option);

            if (availableFiles == null || availableFiles.Length < 1)
            {
                MessageBox.Show("The version you selected does not have any precompiled binaries available for it, to use this version you will" +
                    " need to build the software from source and flash it as a local image from this PC.", "No Files Available", MessageBoxButtons.OK,
                    MessageBoxIcon.Warning);
                return;
            }

            foreach (string file in availableFiles)
            {
                try
                {
                    string type = Path.GetExtension(file).Replace(".", "").ToUpper();

                    Invoke(new Action(() =>
                    {
                        listView.Items.Add(new ListViewItem(new string[] { "SpacehuhnTech", Path.GetFileNameWithoutExtension(file), type}));
                    }));                
                }
                catch (Exception e)
                {
                    Program.Debug("selectfm", $"Failed to parse filename: {file}, error: {e.Message}", Event.Critical);
                    await Task.Delay(100);
                }
            }
        }

19 View Source File : CodeViewerTreeFilter.cs
License : MIT License
Project Creator : Actipro

public override DataFilterResult Filter(object item, object context) {
			var shellObject = item as ShellObjectViewModel;
			if (shellObject != null) {
				if (shellObject.IsFolder)
					return DataFilterResult.IncludedWithDescendants;
				else {
					var parsingName = shellObject.RelativeParsingName;
					if (!string.IsNullOrEmpty(parsingName)) {
						var extension = Path.GetExtension(parsingName);
						if (!string.IsNullOrEmpty(extension)) {
							extension = extension.ToUpperInvariant();
							switch (extension) {
								case ".CS":
								case ".XAML":
									return DataFilterResult.Included;
							}
						}
					}
				}
			}

			return DataFilterResult.Excluded;
		}

See More Examples