/// <summary> /// Removes the "Allow" read permissions, and adds the "Deny" read permission /// on the HOSTS file. If the Hosts file cannot be locked, the exception error /// will be logged in the App error log /// </summary> public bool Lock() { // Make sure we have a security object if (Security == null) { return(false); } // Donot allow Read for the Everyone Sid. This prevents the BF2 client from reading the hosts file Security.RemoveAccessRule(new FileSystemAccessRule(WorldSid, FileSystemRights.ReadData, AccessControlType.Allow)); Security.AddAccessRule(new FileSystemAccessRule(WorldSid, FileSystemRights.ReadData, AccessControlType.Deny)); // Try and set the new access control try { HostFile.SetAccessControl(Security); IsLocked = true; return(true); } catch (Exception e) { TraceLog.TraceError("Unable to REMOVE the Readonly rule on Hosts File: " + e.Message); LastException = e; return(false); } }
/// <summary> /// Removes the "Deny" read permissions, and adds the "Allow" read permission /// on the HOSTS file. If the Hosts file cannot be unlocked, the exception error /// will be logged in the App error log /// </summary> public bool UnLock() { // Make sure we have a security object if (Security == null) { return(false); } // Allow ReadData Security.RemoveAccessRule(new FileSystemAccessRule(WorldSid, FileSystemRights.ReadData, AccessControlType.Deny)); Security.AddAccessRule(new FileSystemAccessRule(WorldSid, FileSystemRights.ReadData, AccessControlType.Allow)); // Try and set the new access control try { HostFile.SetAccessControl(Security); IsLocked = false; return(true); } catch (Exception e) { TraceLog.TraceError("Unable to REMOVE the Readonly rule on Hosts File: " + e.Message); LastException = e; return(false); } }
/// <summary> /// Combines and sort several hosts files content into one by removing duplicates. /// Use one line for each host entry. /// </summary> public static async Task <HostFile> CombineHostFilesAsync(List <HostFile> hostFiles) => await Task.Run(() => { var resultHostFile = new HostFile(); hostFiles.ForEach(hostFile => hostFile.Hosts.ToList().ForEach(host => resultHostFile.Hosts.Add(host)) ); return(resultHostFile); });
/// <summary> /// Loads the specified <see cref="HostsFileProfile"/>. /// </summary> /// <param name="sourceProfile">A <see cref="HostsFileProfile"/> object.</param> /// <returns>True if the specified <paramref name="sourceProfile"/> was loaded successfully; otherwise false.</returns> public bool LoadProfile(HostsFileProfile sourceProfile) { if (this.HostFileInstance != null) { HostFile hf = HostfileManager.Current.GetProfile(sourceProfile.ProfilePath); if (hf != null) { this.HostFileInstance = hf; return(true); } } return(false); }
/// <summary>Save the specified <paramref name="hostFile"/> to the specified <paramref name="targetPath"/>.</summary> /// <param name="hostFile">The <see cref="HostFile"/> object that shall be converted to a profile.</param> /// <param name="targetPath">The target path.</param> /// <returns>True if the profile was saved successfully; otherwise false.</returns> public bool SaveToProfile(HostFile hostFile, string targetPath) { if (hostFile == null) { throw new ArgumentNullException("hostFile"); } if (string.IsNullOrEmpty(targetPath)) { throw new ArgumentNullException("targetPath"); } return(this.DataAccess.SaveToProfile(this.ConvertHostfileToText(hostFile), targetPath)); }
/// <summary> /// Updates the user-interface with the values from the new hosts-file content. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">An <see cref="FileSystemEventArgs"/> that contains the event data.</param> private void HostsFileContentChanged(object sender, FileSystemEventArgs e) { if (string.IsNullOrEmpty(e.FullPath) || File.Exists(e.FullPath) == false) { return; } HostFile newHostsFile = HostfileManager.Current.GetHostsFile(e.FullPath); if (newHostsFile != null) { /* attach new data-model */ this.HostFileInstance = newHostsFile; } }
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> /// <param name="disposing">A flag indicating whether this object is currently disposing.</param> protected override void Dispose(bool disposing) { if (this.disposed == false) { if (disposing) { this.hostFileInstance = null; HostfileManager.Current.Dispose(); } // Free your own state (unmanaged objects). // Set large fields to null. this.disposed = true; } base.Dispose(disposing); }
public void OneClick() { setStatus("Set default DNS to google's DNS..."); HightLevelNetworkControll.setGoogleDNS(); setStatus("Getting hosts file data..."); string WriteData = HostFile.ReadDataWithoughtanstring("facebook") + Environment.NewLine; setStatus("Resolving IP Address..."); WriteData += HightLevelNetworkControll.ResolvedData(); setStatus("Restoring default DNS..."); HightLevelNetworkControll.RestoreDNS(); setStatus("Writing data to hosts file..."); HostFile.WriteHostData(WriteData); }
/// <summary>Loads the hosts file with specified <paramref name="filePath"/>.</summary> /// <param name="filePath">The file path to a hosts file or a hosts file profile.</param> /// <returns>True if the specified <paramref name="filePath"/> was loaded successfully; otherwise false.</returns> public bool LoadFile(string filePath) { if (string.IsNullOrEmpty(filePath)) { throw new ArgumentNullException("filePath"); } if (this.HostFileInstance != null) { HostFile hf = HostfileManager.Current.GetHostsFile(filePath); if (hf != null) { this.HostFileInstance = hf; return(true); } } return(false); }
/// <summary>Get a <see cref="HostFile"/> object for the host file with the specified <paramref name="hostFilePath"/>.</summary> /// <param name="hostFilePath">The host file path.</param> /// <returns>An initialized <see cref="HostFile"/> object.</returns> private HostFile GetHostfile(string hostFilePath) { List <string> lines = this.DataAccess.GetHostfileContent(hostFilePath); HostFile hostFile = HostFile.CreateHostFile(hostFilePath); HostfileLineByLineNavigator navigator = new HostfileLineByLineNavigator(lines); HostfileEntryCollection collection = new HostfileEntryCollection(hostFile.PropertyChangedCallBack); foreach (HostfileLine line in navigator) { if (line.IsMultiLineComment) { /* multi line comment */ if (collection.GetElementBy(HostfileEntryType.Comment, line.MultiLineCommentText) == null) { collection.Add(new Comment(line.MultiLineCommentText, hostFile.PropertyChangedCallBack)); } } else if (line.IsToggleModeOption) { string value = line.Values.FirstOrDefault(); if (value != null) { /* group toggle-mode */ if (value.Equals("group", StringComparison.OrdinalIgnoreCase)) { hostFile.ExclusiveGroupToggleModeIsEnabled = true; } /* host toggle-mode */ if (value.Equals("host", StringComparison.OrdinalIgnoreCase)) { hostFile.ExclusiveHostToggleModeIsEnabled = true; } } } else if (line.IsGlobalComment) { /* single comment */ collection.Add(new Comment(line.Values.FirstOrDefault(), hostFile.PropertyChangedCallBack)); } else if (line.IsGroupStart) { /* host group */ HostGroup group = new HostGroup(line.GroupName, line.DescriptionText, hostFile.PropertyChangedCallBack); collection.Add(group); } else if (line.IsHost) { /* host */ IHostfileEntry parentItem = line.IsMemberOfHostGroup ? collection.GetElementBy( HostfileEntryType.HostGroup, line.GroupName) : null; HostGroup parentGroup = parentItem != null ? parentItem as HostGroup : null; Host host = new Host(parentGroup, line.Values.FirstOrDefault(), line.DescriptionText, hostFile.PropertyChangedCallBack) { IsActive = line.IsActive }; /* domains */ string domainString = line.Values.LastOrDefault(); if (string.IsNullOrEmpty(domainString) == false) { List <string> domainNames = domainString.Split(' ').Select(domain => domain.Trim()).ToList(); foreach (string domainName in domainNames) { host.Childs.Add(new Domain(host, domainName, hostFile.PropertyChangedCallBack)); } } if (parentGroup != null) { parentGroup.Childs.Add(host); } else { collection.Add(host); } } } /* attach entry collection to host file */ hostFile.Childs = collection; return(hostFile); }
/// <summary> /// Convert the specified <see cref="HostFile"/> object to text. /// </summary> /// <param name="file">A <see cref="HostFile"/> object instance.</param> /// <returns>The text-representation of the specified <paramref name="file"/>.</returns> public string ConvertHostfileToText(HostFile file) { return(file != null?file.GetText() : string.Empty); }
/// <summary> /// Save a <see cref="HostFile"/> object to its corresponding file. /// </summary> /// <param name="hostFile">A <see cref="HostFile"/> object instance.</param> /// <param name="filepath">The path to the file.</param> /// <returns>True if the <see cref="HostFile"/> object was successfully saved to its corresponding file on the users' hard drive (<see cref="HostFile.FilePath"/>). Otherwise false.</returns> public bool SaveHostsFileContent(HostFile hostFile, string filepath) { return(this.DataAccess.SaveHostsFileContent(this.ConvertHostfileToText(hostFile), filepath)); }
/// <summary> /// Convert the specified <see cref="HostFile"/> object to text. /// </summary> /// <param name="file">A <see cref="HostFile"/> object instance.</param> /// <returns>The text-representation of the specified <paramref name="file"/>.</returns> public string ConvertHostfileToText(HostFile file) { return file != null ? file.GetText() : string.Empty; }
private async Task UpdateLocalHostFileAsync(HostFile hostFile) => await this.fileWrapper.WriteAllTextAsync(HostsFilePath, hostFile.ToString());
/// <summary>Save the specified <paramref name="hostFile"/> to the specified <paramref name="targetPath"/>.</summary> /// <param name="hostFile">The <see cref="HostFile"/> object that shall be converted to a profile.</param> /// <param name="targetPath">The target path.</param> /// <returns>True if the profile was saved successfully; otherwise false.</returns> public bool SaveToProfile(HostFile hostFile, string targetPath) { if (hostFile == null) { throw new ArgumentNullException("hostFile"); } if (string.IsNullOrEmpty(targetPath)) { throw new ArgumentNullException("targetPath"); } return this.DataAccess.SaveToProfile(this.ConvertHostfileToText(hostFile), targetPath); }
/// <summary> /// Save a <see cref="HostFile"/> object to its corresponding file. /// </summary> /// <param name="hostFile">A <see cref="HostFile"/> object instance.</param> /// <param name="filepath">The path to the file.</param> /// <returns>True if the <see cref="HostFile"/> object was successfully saved to its corresponding file on the users' hard drive (<see cref="HostFile.FilePath"/>). Otherwise false.</returns> public bool SaveHostsFileContent(HostFile hostFile, string filepath) { return this.DataAccess.SaveHostsFileContent(this.ConvertHostfileToText(hostFile), filepath); }
/// <summary> /// Evaluate language agnostic command line arguments. /// </summary> /// <param name="e">A <see cref="StartupEventArgs"/> that contains the event data.</param> private void EvaluateLanguageAgnosticCommandLineArguments(StartupEventArgs e) { if (e == null || e.Args.Length <= 0) { return; } /* set user-interface culture */ Regex regExUserInterfaceCulture = new Regex(string.Concat(Constants.CommandLineArgumentPrefix, Constants.CommandLineArgumentPatternSetUserInterfaceCulture), RegexOptions.IgnoreCase); string cultureArg = e.Args.FirstOrDefault(regExUserInterfaceCulture.IsMatch); if (string.IsNullOrEmpty(cultureArg) == false) { MatchCollection matches = regExUserInterfaceCulture.Matches(cultureArg); if (matches.Count > 0) { Match match = matches[0]; if (match.Groups.Count > 0) { Group g = match.Groups[match.Groups.Count - 1]; string cultureCode = g.Value; /* try to set the ui culture */ if (TranslationManager.Instance.SetUserInterfaceLanguage(cultureCode)) { this.userInterfaceCultureHasBeenSet = true; } } } } /* load profile */ Regex regExProfilePath = new Regex(string.Concat(Constants.CommandLineArgumentPrefix, Constants.CommandLineArgumentPatternLoadProfile), RegexOptions.IgnoreCase); string profilePathArg = e.Args.FirstOrDefault(regExProfilePath.IsMatch); if (string.IsNullOrEmpty(profilePathArg) == false) { MatchCollection matches = regExProfilePath.Matches(profilePathArg); if (matches.Count > 0) { Match match = matches[0]; if (match.Groups.Count > 0) { Group g = match.Groups[match.Groups.Count - 1]; string profilePath = g.Value; /* copy profile to hosts file */ HostfileManager.Current.UseProfile(profilePath); } } } /* set a new hosts file path */ Regex regExHostsFilePath = new Regex(string.Concat(Constants.CommandLineArgumentPrefix, Constants.CommandLineArgumentPatternHostsFilePath), RegexOptions.IgnoreCase); string hostsFilePathArg = e.Args.FirstOrDefault(regExHostsFilePath.IsMatch); if (string.IsNullOrEmpty(hostsFilePathArg) == false) { MatchCollection matches = regExHostsFilePath.Matches(hostsFilePathArg); if (matches.Count > 0) { Match match = matches[0]; if (match.Groups.Count > 0) { Group g = match.Groups[match.Groups.Count - 1]; string newHostsFilePath = g.Value; HostfileManager.Current.ComputerHostFilePath = newHostsFilePath; } } } /* set group status */ Regex regExSetGroupStatus = new Regex(string.Concat(Constants.CommandLineArgumentPrefix, Constants.CommandLineArgumentPatternSetGroupStatus), RegexOptions.IgnoreCase); string groupStatusArg = e.Args.FirstOrDefault(regExSetGroupStatus.IsMatch); if (string.IsNullOrEmpty(groupStatusArg) == false) { MatchCollection matches = regExSetGroupStatus.Matches(groupStatusArg); if (matches.Count > 0) { Match match = matches[0]; if (match.Groups.Count > 2) { Group actionGroup = match.Groups[match.Groups.Count - 2]; Group modifierGroup = match.Groups[match.Groups.Count - 1]; if (actionGroup.Success && modifierGroup.Success) { bool newStatus = actionGroup.Value.Equals(Constants.CommandLineArgumentComponentGroupStatusEnable, StringComparison.OrdinalIgnoreCase) ? true : false; string modifierValue = modifierGroup.Value; /* set new group status */ HostFile hf = HostfileManager.Current.GetHostsFile(); foreach (HostGroup group in hf.Childs.Where(group => group.EntryType.Equals(HostfileEntryType.HostGroup) && (group.Name.Equals(modifierValue, StringComparison.OrdinalIgnoreCase) || modifierValue.Equals("all", StringComparison.OrdinalIgnoreCase))).OfType <HostGroup>().Where(group => group != null)) { group.IsActive = newStatus; } /* save changes */ HostfileManager.Current.SaveHostsFileContent(hf, hf.FilePath); } } } } /* disable hardware acceleration */ string cmdArgDisableHardwareAcceleration = string.Concat(Constants.CommandLineArgumentPrefix, Constants.CommandLineArgumentDisableHardwareAcceleration); string disableHardwareAccelerationArg = e.Args.FirstOrDefault(arg => arg.Equals(cmdArgDisableHardwareAcceleration, StringComparison.OrdinalIgnoreCase)); if (string.IsNullOrEmpty(disableHardwareAccelerationArg) == false) { ApplicationSettingsManager.Current.Settings.DisableWpfHardwareAcceleration = true; } /* open profile directory */ string cmdArgOpenProfileDirectory = string.Concat(Constants.CommandLineArgumentPrefix, Constants.CommandLineArgumentOpenProfileDirectory); string openProfileDirectoryArg = e.Args.FirstOrDefault(arg => arg.Equals(cmdArgOpenProfileDirectory, StringComparison.OrdinalIgnoreCase)); if (string.IsNullOrEmpty(openProfileDirectoryArg) == false) { string profileDirectoryPath = HostfileManager.Current.GetProfileDirectory(); if (string.IsNullOrEmpty(profileDirectoryPath) == false) { Process.Start(new ProcessStartInfo(profileDirectoryPath)); } } /* console only */ string cmdArgConsoleOnly = string.Concat(Constants.CommandLineArgumentPrefix, Constants.CommandLineArgumentConsoleOnly); string consoleOnlyArg = e.Args.FirstOrDefault(arg => arg.Equals(cmdArgConsoleOnly, StringComparison.OrdinalIgnoreCase)); if (string.IsNullOrEmpty(consoleOnlyArg) == false) { this.ConsoleOnly = true; } /* reset application settings */ string cmdArgReset = string.Concat(Constants.CommandLineArgumentPrefix, Constants.CommandLineArgumentResetApplicationSettings); string resetArg = e.Args.FirstOrDefault(arg => arg.Equals(cmdArgReset, StringComparison.OrdinalIgnoreCase)); if (string.IsNullOrEmpty(resetArg) == false) { ApplicationSettingsManager.Current.ResetApplicationSettings(); } }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string name = context.Request["name"]; string serverid = ""; var fid = Utility.IO.Context.GetRequestInt("minsnsId", 0); var accid = Utility.IO.Context.GetRequest("accountId", ""); int voicetime = 0, voicetype = 0, convertstate = 0; int.TryParse(context.Request["voicetime"], out voicetime); int.TryParse(context.Request["voicetype"], out voicetype); if (voicetype == 1) //1录音文件 0本地音频 { serverid = "app_" + DateTime.Now.ToString(); //前端显示需要用到serverid convertstate = 1; // 前端显示需要用到 标识已转换成功 } Guid _accountId = Guid.Empty; try { if (string.IsNullOrEmpty(accid)) { accid = CookieHelper.GetCookie("UserCookieNew"); } _accountId = Guid.Parse(accid); } catch (Exception) { log4net.LogHelper.WriteInfo(this.GetType(), "guid转换失败,上传音频_accountId=" + accid); context.Response.Write(new JavaScriptSerializer().Serialize(new { result = 0, msg = "账号信息错误!" })); } /*如果有openId,发帖人用微信帐号 xiaowei 2015-10-27 11:21:54*/ Account account = AccountBLL.SingleModel.GetModel(_accountId); if (null == account) { context.Response.Write(new JavaScriptSerializer().Serialize(new { result = 0, msg = "账号信息错误!" })); } OAuthUser artUser = null; int userid = 0; if (null != account && !string.IsNullOrEmpty(account.OpenId)) { artUser = new OAuthUserBll(fid).GetUserByOpenId(account.OpenId, fid); userid = artUser.Id; } HttpPostedFile file = context.Request.Files[name]; string time = string.Empty; string fileType = System.IO.Path.GetExtension(file.FileName).ToLower(); List <string> extents = new List <string> { ".cda", ".wav", ".mp3", ".wma", ".ra", ".midi", ".ogg", ".ape", ".flac", ".aac", ".amr" }; if (!extents.Contains(fileType)) { context.Response.Write(new JavaScriptSerializer().Serialize(new { result = 0, msg = "音频格式不对" })); } int convertState = 1; var size = file.ContentLength; string aliTempImgKey = string.Empty; if (fileType != ".mp3") { convertState = -9; } var filePath = @"\\share3.vzan.cc\share\temp\pc" + DateTime.Now.ToFileTime().ToString() + fileType; file.SaveAs(filePath); var fileStream = file.InputStream; var byteData = new byte[size]; if (null != fileStream) { using (System.IO.BinaryReader br = new System.IO.BinaryReader(fileStream)) { byteData = br.ReadBytes(size); } //同步到AliOss //上传的目录 var aliTempImgFolder = AliOSSHelper.GetOssVoiceKey(fileType.Replace(".", ""), true, "voice/folder", out aliTempImgKey); var putResult = AliOSSHelper.PutObjectFromByteArray(aliTempImgFolder, byteData, 1, fileType); if (!putResult) { log4net.LogHelper.WriteInfo(this.GetType(), "语音同步到Ali失败!"); } }// 上传的文件为空 else { log4net.LogHelper.WriteInfo(this.GetType(), "fileStream为null!"); context.Response.Write(new JavaScriptSerializer().Serialize(new { error = aliTempImgKey, msg = "上传失败" })); } Voices voice = new Voices(); voice.ServerId = ""; voice.MessageText = ""; voice.DownLoadFile = aliTempImgKey; voice.TransFilePath = aliTempImgKey; voice.UserId = userid; voice.FId = fid; voice.VoiceTime = voicetime; voice.VoiceType = voicetype; voice.ServerId = serverid; //录音文件 voice.ConvertState = convertstate; //1 已转换 0为转换 voice.CreateDate = DateTime.Now; if (convertState == 1)//是mp3--获取音频信息必须保存到本地才能获得 { HostFile.GetVoiceFromPath(ref voice, filePath); } else { if (File.Exists(filePath)) { try { File.Delete(filePath); } catch (Exception) { } } } if (string.IsNullOrEmpty(voice.SongName)) { voice.SongName = file.FileName; } if (string.IsNullOrEmpty(voice.SongPic)) { voice.SongPic = "//j.vzan.cc/manager/images/yinping.jpg?v=0.1"; } int voiceId = Convert.ToInt32(VoicesBll.SingleModel.Add(voice)); if (voiceId > 0) { context.Response.Write(new JavaScriptSerializer().Serialize(new { result = 1, msg = "上传成功", time = voice.VoiceTime, url = aliTempImgKey, songpic = voice.SongPic, songname = voice.SongName, singer = voice.Singer, album = voice.Album, id = voiceId, createdate = voice.CreateDate.ToString("yyyy-MM-dd") })); } else { context.Response.Write(new JavaScriptSerializer().Serialize(new { result = 0, msg = "上传错误" })); } }