public static void Load(this Hashtable props, System.IO.Stream stream) { if (stream == null) { return; } using (var reader = new InputStreamReader((InputStream)stream, Encoding.UTF8)) { while (!reader.EndOfStream) { var line = reader.ReadLine(); if (!StringEx.IsNullOrWhiteSpace(line) && !line.StartsWith("#")) { var parts = line.Split('='); if (parts.Length != 2) { throw new InvalidOperationException("Properties must be key value pairs separated by an '='."); } if (!props.ContainsKey(parts[0])) { props.Add(parts[0], parts[1]); } else { props[parts[0]] = parts[1]; } } } } }
/// <summary> /// Gets the output media file. /// </summary> /// <param name="context">The context.</param> /// <param name="subdir">The subdir.</param> /// <param name="name">The name.</param> /// <param name="isPhoto">if set to <c>true</c> [is photo].</param> /// <returns>Uri.</returns> /// <exception cref="System.IO.IOException">Couldn't create directory, have you added the WRITE_EXTERNAL_STORAGE permission?</exception> private static Uri GetOutputMediaFile(Context context, string subdir, string name, bool isPhoto) { subdir = subdir ?? String.Empty; if (String.IsNullOrWhiteSpace(name)) { name = MediaFileHelpers.GetMediaFileWithPath(isPhoto, subdir, string.Empty, name); } var mediaType = (isPhoto) ? Environment.DirectoryPictures : Environment.DirectoryMovies; using (var mediaStorageDir = new Java.IO.File(context.GetExternalFilesDir(mediaType), subdir)) { if (!mediaStorageDir.Exists()) { if (!mediaStorageDir.Mkdirs()) { throw new IOException("Couldn't create directory, have you added the WRITE_EXTERNAL_STORAGE permission?"); } // Ensure this media doesn't show up in gallery apps using (var nomedia = new Java.IO.File(mediaStorageDir, ".nomedia")) nomedia.CreateNewFile(); } return(Uri.FromFile(new Java.IO.File(MediaFileHelpers.GetUniqueMediaFileWithPath(isPhoto, mediaStorageDir.Path, name, File.Exists)))); } }
public long InsertWithOnConflict(String table, String nullColumnHack, ContentValues initialValues, ConflictResolutionStrategy conflictResolutionStrategy) { if (!StringEx.IsNullOrWhiteSpace(nullColumnHack)) { var e = new InvalidOperationException("{0} does not support the 'nullColumnHack'.".Fmt(TAG)); Log.E(TAG, "Unsupported use of nullColumnHack", e); throw e; } var t = Factory.StartNew(() => { var lastInsertedId = -1L; var command = GetInsertCommand(table, initialValues, conflictResolutionStrategy); try { LastErrorCode = command.step(); command.Dispose(); if (LastErrorCode == SQLiteResult.ERROR) { throw new CouchbaseLiteException(raw.sqlite3_errmsg(_writeConnection), StatusCode.DbError); } int changes = _writeConnection.changes(); if (changes > 0) { lastInsertedId = _writeConnection.last_insert_rowid(); } if (lastInsertedId == -1L) { if (conflictResolutionStrategy != ConflictResolutionStrategy.Ignore) { Log.E(TAG, "Error inserting " + initialValues + " using " + command); throw new CouchbaseLiteException("Error inserting " + initialValues + " using " + command, StatusCode.DbError); } } else { Log.V(TAG, "Inserting row {0} into {1} with values {2}", lastInsertedId, table, initialValues); } } catch (Exception ex) { Log.E(TAG, "Error inserting into table " + table, ex); LastErrorCode = raw.sqlite3_errcode(_writeConnection); throw; } return(lastInsertedId); }); var r = t.ConfigureAwait(false).GetAwaiter().GetResult(); if (t.Exception != null) { throw t.Exception; } return(r); }
/// <summary>释放文件夹</summary> /// <param name="asm"></param> /// <param name="prefix"></param> /// <param name="dest"></param> /// <param name="overWrite"></param> /// <param name="filenameResolver"></param> public static void ReleaseFolder(Assembly asm, String prefix, String dest, Boolean overWrite, Func<String, String> filenameResolver) { if (asm == null) asm = Assembly.GetCallingAssembly(); // 找到符合条件的资源 String[] names = asm.GetManifestResourceNames(); if (names == null || names.Length < 1) return; IEnumerable<String> ns = null; if (prefix.IsNullOrWhiteSpace()) ns = names.AsEnumerable(); else ns = names.Where(e => e.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)); if (String.IsNullOrEmpty(dest)) dest = AppDomain.CurrentDomain.BaseDirectory; if (!Path.IsPathRooted(dest)) { String str = Runtime.IsWeb ? HttpRuntime.BinDirectory : AppDomain.CurrentDomain.BaseDirectory; dest = Path.Combine(str, dest); } // 开始处理 foreach (String item in ns) { Stream stream = asm.GetManifestResourceStream(item); // 计算filename String filename = null; // 去掉前缀 if (filenameResolver != null) filename = filenameResolver(item); if (String.IsNullOrEmpty(filename)) { filename = item; if (!String.IsNullOrEmpty(prefix)) filename = filename.Substring(prefix.Length); if (filename[0] == '.') filename = filename.Substring(1); String ext = Path.GetExtension(item); filename = filename.Substring(0, filename.Length - ext.Length); filename = filename.Replace(".", @"\") + ext; filename = Path.Combine(dest, filename); } if (File.Exists(filename) && !overWrite) return; String path = Path.GetDirectoryName(filename); if (!path.IsNullOrWhiteSpace() && !Directory.Exists(path)) Directory.CreateDirectory(path); try { if (File.Exists(filename)) File.Delete(filename); using (FileStream fs = File.Create(filename)) { IOHelper.CopyTo(stream, fs); } } catch { } finally { stream.Dispose(); } } }
private void DeserializeFromDisk() { var filePath = GetSaveCookiesFilePath(); if (StringEx.IsNullOrWhiteSpace(filePath)) { return; } var fileInfo = new FileInfo(filePath); if (!fileInfo.Exists) { return; } using (var reader = new StreamReader(filePath)) { var json = reader.ReadToEnd(); var cookies = Manager.GetObjectMapper().ReadValue <IList <Cookie> >(json); cookies = cookies ?? new List <Cookie>(); foreach (Cookie cookie in cookies) { Add(cookie, false); } } }
private static IRegionInfo[] LoadCustomUserRegions() { List <IRegionInfo> customRegions = new List <IRegionInfo>(); for (int x = 0; x < 9; x++) { ConfigEntry <string> regionName = UnifyPlugin.ConfigFile.Bind( $"Region {x + 1}", $"Name", "custom region"); ConfigEntry <string> regionIp = UnifyPlugin.ConfigFile.Bind( $"Region {x + 1}", "IP", ""); ConfigEntry <ushort> regionPort = UnifyPlugin.ConfigFile.Bind( $"Region {x + 1}", "Port", (ushort)22023); if (String.IsNullOrWhiteSpace(regionIp.Value)) { continue; } IRegionInfo regionInfo = new DnsRegionInfo( regionIp.Value, regionName.Value, StringNames.NoTranslation, regionIp.Value, regionPort.Value) .Cast <IRegionInfo>(); customRegions.Add(regionInfo); } return(customRegions.ToArray()); }
static Manager() { illegalCharactersPattern = new Regex(IllegalCharacters); mapper = new ObjectWriter(); DefaultOptions = ManagerOptions.Default; // // Note: Environment.SpecialFolder.LocalApplicationData returns null on Azure (and possibly other Windows Server environments) // and this is only needed by the default constructor or when accessing the SharedInstanced // So, let's only set it only when GetFolderPath returns something and allow the directory to be // manually specified via the ctor that accepts a DirectoryInfo var defaultDirectoryPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); if (!StringEx.IsNullOrWhiteSpace(defaultDirectoryPath)) { defaultDirectory = new DirectoryInfo(defaultDirectoryPath); } #if !OFFICIAL string gitVersion = String.Empty; using (Stream stream = Assembly.GetExecutingAssembly() .GetManifestResourceStream("version")) using (StreamReader reader = new StreamReader(stream)) { gitVersion = reader.ReadToEnd(); } VersionString = String.Format("Unofficial ({0})", gitVersion.TrimEnd()); #else VersionString = "1.1"; #endif }
private SavedRevision GetRevisionWithId(String revId) { if (!StringEx.IsNullOrWhiteSpace(revId) && revId.Equals(currentRevision.Id)) { return(currentRevision); } return(GetRevisionFromRev(Database.GetDocumentWithIDAndRev(Id, revId, DocumentContentOptions.None))); }
public async Task <Guid?> GetRefereeTimerIdAsync(string refereeCode) { if (String.IsNullOrWhiteSpace(refereeCode)) { return(null); } return(await _refereeCodesRepo.GetRefereeCodeTimerId(refereeCode)); }
public static void NotNullNorWhiteSpace( [CanBeNull] string arg, [NotNull, InvokerParameterName] string argName) { if (StringEx.IsNullOrWhiteSpace(arg)) { throw CodeExceptions.ArgumentNullOrWhiteSpace(argName); } }
/// <summary> /// Decrypt the encoded file and compare to original file. It returns false if the file is corrupted. /// </summary> /// <param name="key">The key used to encode the file</param> /// <param name="sourceFile">The file to decrypt complete path</param> /// <param name="destFile">Destination file complete path. If the file doesn't exist, it creates it</param> /// <returns></returns> public bool DecodeFile(string key, String sourceFile, String destFile) { if (sourceFile.IsNullOrWhiteSpace() || !File.Exists(sourceFile)) throw new FileNotFoundException("Cannot find the specified source file", sourceFile ?? "null"); if (destFile.IsNullOrWhiteSpace()) throw new ArgumentException("Please specify the path of the output path", nameof(destFile)); if (string.IsNullOrEmpty(key)) throw new ArgumentException("Please specify the key", nameof(key)); // Create a key using a random number generator. This would be the // secret key shared by sender and receiver. byte[] secretkey = key.ToByteArray(); // Initialize the keyed hash object. HMACMD5 hmacMD5 = new HMACMD5(secretkey); // Create an array to hold the keyed hash value read from the file. byte[] storedHash = new byte[hmacMD5.HashSize / 8]; // Create a FileStream for the source file. FileStream inStream = new FileStream(sourceFile, FileMode.Open); // Read in the storedHash. inStream.Read(storedHash, 0, storedHash.Length); // Compute the hash of the remaining contents of the file. // The stream is properly positioned at the beginning of the content, // immediately after the stored hash value. byte[] computedHash = hmacMD5.ComputeHash(inStream); // compare the computed hash with the stored value int i; for (i = 0; i < storedHash.Length; i++) { if (computedHash[i] != storedHash[i]) { inStream.Close(); return false; } } FileStream outStream = new FileStream(destFile, FileMode.Create); // Reset inStream to the beginning of the file. inStream.Position = i; // Copy the contents of the sourceFile to the destFile. int bytesRead; // read 1K at a time byte[] buffer = new byte[1024]; do { // Read from the wrapping CryptoStream. bytesRead = inStream.Read(buffer, 0, 1024); outStream.Write(buffer, 0, bytesRead); } while (bytesRead > 0); // Close the streams inStream.Close(); outStream.Close(); return true; }
public int Delete(String table, String whereClause, params String[] whereArgs) { if (_readOnly) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.Forbidden, TAG, "Attempting to write to a readonly database"); } Debug.Assert(!StringEx.IsNullOrWhiteSpace(table)); Log.To.TaskScheduling.V(TAG, "Scheduling Delete"); var t = Factory.StartNew(() => { Log.To.TaskScheduling.V(TAG, "Running Delete"); var resultCount = -1; var command = GetDeleteCommand(table, whereClause, whereArgs); try { var result = command.step(); if (result == raw.SQLITE_ERROR) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.DbError, TAG, "Error deleting from table {0} ({1})", table, result); } resultCount = _writeConnection.changes(); if (resultCount < 0) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.DbError, TAG, "Failed to delete the requested records"); } } catch (Exception ex) { LastErrorCode = raw.sqlite3_errcode(_writeConnection); Log.To.Database.E(TAG, String.Format("Error {0} when deleting from table {1}, rethrowing...", _writeConnection.extended_errcode(), table), ex); throw; } finally { command.Dispose(); } return(resultCount); }); // NOTE.ZJG: Just a sketch here. Needs better error handling, etc. var r = t.GetAwaiter().GetResult(); if (t.Exception != null) { //this is bad: should not arbitrarily crash the app throw t.Exception; } return(r); }
/// <summary> /// Encode a string using Base64 format /// </summary> /// <param name="sourceString">The source string to encode</param> /// <returns>The encoded string</returns> public string EncodeString(String sourceString) { if (!sourceString.IsNullOrWhiteSpace()) { byte[] filebytes = sourceString.ToByteArray(); return Convert.ToBase64String(filebytes); } else return string.Empty; }
/// <summary> /// Decode a string encoded in Base64 format /// </summary> /// <param name="sourceString">The encoded string to decode</param> /// <returns>The decoded string</returns> public string DecodeString(String sourceString) { if (!sourceString.IsNullOrWhiteSpace()) { byte[] filebytes = Convert.FromBase64String(sourceString); return Utils.ByteArrayToStr(filebytes); } else return string.Empty; }
/// <summary> /// Checks a string argument to ensure it isn't null or empty. /// </summary> /// <param name = "value">The argument value to check</param> /// <param name = "name">The name of the argument</param> public static void ArgumentNotNullOrEmptyString([ValidatedNotNull] string value, string name) { ArgumentNotNull(value, name); if (!StringExt.IsNullOrWhiteSpace(value)) { return; } throw new ArgumentException("String cannot be empty", name); }
// f : String -> Boolean private static Boolean IsValid(String email) { // need more elaborate validation if (String.IsNullOrEmpty(email) || String.IsNullOrWhiteSpace(email)) { return(false); } return(true); }
public int Update(String table, ContentValues values, String whereClause, params String[] whereArgs) { if (_readOnly) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.Forbidden, TAG, "Attempting to write to a readonly database"); } Debug.Assert(!StringEx.IsNullOrWhiteSpace(table)); Debug.Assert(values != null); Log.To.TaskScheduling.V(TAG, "Scheduling Update"); var t = Factory.StartNew(() => { Log.To.TaskScheduling.V(TAG, "Running Update"); var resultCount = 0; var command = GetUpdateCommand(table, values, whereClause, whereArgs); try { LastErrorCode = command.step(); if (LastErrorCode == raw.SQLITE_ERROR) { throw new CouchbaseLiteException(raw.sqlite3_errmsg(_writeConnection), StatusCode.DbError); } } catch (ugly.sqlite3_exception ex) { LastErrorCode = raw.sqlite3_errcode(_writeConnection); var msg = raw.sqlite3_extended_errcode(_writeConnection); Log.To.Database.E(TAG, String.Format("Error {0}: \"{1}\" while updating table {2}", ex.errcode, msg, table), ex); } resultCount = _writeConnection.changes(); if (resultCount < 0) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.DbError, TAG, "Error updating {0} with command '{1}'", values, command); } command.Dispose(); return(resultCount); }, CancellationToken.None); // NOTE.ZJG: Just a sketch here. Needs better error handling, etc. //doesn't look good var r = t.ConfigureAwait(false).GetAwaiter().GetResult(); if (t.Exception != null) { throw t.Exception; } return(r); }
/// <summary> /// Creates a new Tree in the specified repo /// </summary> /// <remarks> /// http://developer.github.com/v3/git/trees/#create-a-tree /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="newTree">The value of the new tree</param> public Task <TreeResponse> Create(long repositoryId, NewTree newTree) { Ensure.ArgumentNotNull(newTree, "newTree"); if (newTree.Tree.Any(t => StringExt.IsNullOrWhiteSpace(t.Mode))) { throw new ArgumentException("You have specified items in the tree which do not have a Mode value set."); } return(ApiConnection.Post <TreeResponse>(ApiUrls.Tree(repositoryId), newTree)); }
public void AddTorrentFromUrl(String torrentUrl, String downloadDirectory, TransmissionSettings settings) { var arguments = new Dictionary<String, Object>(); arguments.Add("filename", torrentUrl); if (!downloadDirectory.IsNullOrWhiteSpace()) { arguments.Add("download-dir", downloadDirectory); } ProcessRequest("torrent-add", arguments, settings); }
public ActionResult Index(int?pageIndex, string sortBy) { if (!pageIndex.HasValue) { pageIndex = 1; } if (String.IsNullOrWhiteSpace(sortBy)) { sortBy = "Name"; } return(Content(String.Format("pageIndex={0}&sortBy={1}", pageIndex, sortBy))); }
public void AddTorrentFromData(Byte[] torrentData, String downloadDirectory, TransmissionSettings settings) { var arguments = new Dictionary<String, Object>(); arguments.Add("metainfo", Convert.ToBase64String(torrentData)); if (!downloadDirectory.IsNullOrWhiteSpace()) { arguments.Add("download-dir", downloadDirectory); } ProcessRequest("torrent-add", arguments, settings); }
public int Update(String table, ContentValues values, String whereClause, params String[] whereArgs) { if (_readOnly) { throw new CouchbaseLiteException("Attempting to write to a readonly database", StatusCode.Forbidden); } Debug.Assert(!StringEx.IsNullOrWhiteSpace(table)); Debug.Assert(values != null); var t = Factory.StartNew(() => { var resultCount = 0; var command = GetUpdateCommand(table, values, whereClause, whereArgs); try { LastErrorCode = command.step(); if (LastErrorCode == SQLiteResult.ERROR) { throw new CouchbaseLiteException(raw.sqlite3_errmsg(_writeConnection), StatusCode.DbError); } } catch (ugly.sqlite3_exception ex) { LastErrorCode = raw.sqlite3_errcode(_writeConnection); var msg = raw.sqlite3_extended_errcode(_writeConnection); Log.E(TAG, "Error {0}: \"{1}\" while updating table {2}\r\n{3}", ex.errcode, msg, table, ex); } resultCount = _writeConnection.changes(); if (resultCount < 0) { Log.E(TAG, "Error updating " + values + " using " + command); throw new CouchbaseLiteException("Failed to update any records.", StatusCode.DbError); } command.Dispose(); return(resultCount); }, CancellationToken.None); // NOTE.ZJG: Just a sketch here. Needs better error handling, etc. //doesn't look good var r = t.ConfigureAwait(false).GetAwaiter().GetResult(); if (t.Exception != null) { throw t.Exception; } return(r); }
/// <summary> /// Creates a new Tree in the specified repo /// </summary> /// <remarks> /// http://developer.github.com/v3/git/trees/#create-a-tree /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="newTree">The value of the new tree</param> public Task <TreeResponse> Create(string owner, string name, NewTree newTree) { Ensure.ArgumentNotNullOrEmptyString(owner, "owner"); Ensure.ArgumentNotNullOrEmptyString(name, "name"); Ensure.ArgumentNotNull(newTree, "newTree"); if (newTree.Tree.Any(t => StringExt.IsNullOrWhiteSpace(t.Mode))) { throw new ArgumentException("You have specified items in the tree which do not have a Mode value set."); } return(ApiConnection.Post <TreeResponse>(ApiUrls.Tree(owner, name), newTree)); }
public static PersonaAuthorizer FromUri(Uri uri) { var personaAssertion = URIUtils.GetQueryParameter(uri, QueryParameter); if (personaAssertion != null && !StringEx.IsNullOrWhiteSpace(personaAssertion)) { var email = RegisterAssertion(personaAssertion); var authorizer = new PersonaAuthorizer(email); return(authorizer); } return(null); }
public int Delete(String table, String whereClause, params String[] whereArgs) { if (_readOnly) { throw new CouchbaseLiteException("Attempting to write to a readonly database", StatusCode.Forbidden); } Debug.Assert(!StringEx.IsNullOrWhiteSpace(table)); var t = Factory.StartNew(() => { var resultCount = -1; var command = GetDeleteCommand(table, whereClause, whereArgs); try { var result = command.step(); if (result == SQLiteResult.ERROR) { throw new CouchbaseLiteException("Error deleting from table " + table, StatusCode.DbError); } resultCount = _writeConnection.changes(); if (resultCount < 0) { throw new CouchbaseLiteException("Failed to delete the records.", StatusCode.DbError); } } catch (Exception ex) { LastErrorCode = raw.sqlite3_errcode(_writeConnection); Log.E(TAG, "Error {0} when deleting from table {1}".Fmt(_writeConnection.extended_errcode(), table), ex); throw; } finally { command.Dispose(); } return(resultCount); }); // NOTE.ZJG: Just a sketch here. Needs better error handling, etc. var r = t.GetAwaiter().GetResult(); if (t.Exception != null) { //this is bad: should not arbitrarily crash the app throw t.Exception; } return(r); }
static Manager() { illegalCharactersPattern = new Regex(IllegalCharacters); mapper = new ObjectWriter(); DefaultOptions = ManagerOptions.Default; // // Note: Environment.SpecialFolder.LocalApplicationData returns null on Azure (and possibly other Windows Server environments) // and this is only needed by the default constructor or when accessing the SharedInstanced // So, let's only set it only when GetFolderPath returns something and allow the directory to be // manually specified via the ctor that accepts a DirectoryInfo #if __UNITY__ string defaultDirectoryPath = Unity.UnityMainThreadScheduler.PersistentDataPath; #else var defaultDirectoryPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); #endif if (!StringEx.IsNullOrWhiteSpace(defaultDirectoryPath)) { defaultDirectory = new DirectoryInfo(defaultDirectoryPath); } string gitVersion = String.Empty; using (Stream stream = System.Reflection.Assembly.GetExecutingAssembly() .GetManifestResourceStream("version")) { if (stream != null) { using (StreamReader reader = new StreamReader(stream)) { gitVersion = reader.ReadToEnd(); } } else { gitVersion = "No git information"; } } #if !OFFICIAL VersionString = String.Format("Unofficial ({0})", gitVersion.TrimEnd()); #else var colonPos = gitVersion.IndexOf(':'); if (colonPos != -1) { gitVersion = gitVersion.Substring(colonPos + 2); } VersionString = String.Format("1.1.1 ({0})", gitVersion.TrimEnd()); #endif Log.I(TAG, "Starting Manager version: " + VersionString); }
/// <summary> /// Decode a File encoded in Base64 format /// </summary> /// <param name="sourceFile">The file to decrypt complete path</param> /// <param name="destFile">Destination file complete path. If the file doesn't exist, it creates it</param> public void DecodeFile(String sourceFile, String destFile) { if (sourceFile.IsNullOrWhiteSpace() || !File.Exists(sourceFile)) throw new FileNotFoundException("Cannot find the specified source file", sourceFile ?? "null"); if (destFile.IsNullOrWhiteSpace()) throw new ArgumentException("Please specify the path of the output path", nameof(destFile)); string input = File.ReadAllText(sourceFile); byte[] filebytes = Convert.FromBase64String(input); FileStream fs = new FileStream(destFile, FileMode.Create, FileAccess.Write, FileShare.None); fs.Write(filebytes, 0, filebytes.Length); fs.Close(); }
private new static Status StatusFromBulkDocsResponseItem(IDictionary <string, object> item) { try { if (!item.ContainsKey("error")) { return(new Status(StatusCode.Ok)); } var errorStr = (string)item["error"]; if (StringEx.IsNullOrWhiteSpace(errorStr)) { return(new Status(StatusCode.Ok)); } if (item.ContainsKey("status")) { var status = (Int64)item["status"]; if (status >= 400) { return(new Status((StatusCode)status)); } } // If no 'status' present, interpret magic hardcoded CouchDB error strings: if (string.Equals(errorStr, "unauthorized", StringComparison.OrdinalIgnoreCase)) { return(new Status(StatusCode.Unauthorized)); } else if (string.Equals(errorStr, "forbidding", StringComparison.OrdinalIgnoreCase)) { return(new Status(StatusCode.Forbidden)); } else if (string.Equals(errorStr, "conflict", StringComparison.OrdinalIgnoreCase)) { return(new Status(StatusCode.Conflict)); } else { return(new Status(StatusCode.UpStreamError)); } } catch (Exception e) { Log.E(Tag, "Exception getting status from " + item, e); } return(new Status(StatusCode.Ok)); }
//Tutorial 11 - Filtering the Records: //Exercise - Implment this for Movies. public IEnumerable <MovieDto> GetMovies(string query = null) { //Retrive Movies var moviesQuery = _context.Movies .Include("Genre") .Where(m => m.NumberAvailable > 0); //Filter by Param if (!String.IsNullOrWhiteSpace(query)) { moviesQuery = moviesQuery.Where(m => m.Name.Contains(query)); } return(moviesQuery.ToList().Select(Mapper.Map <Movie, MovieDto>)); }
/// <summary> /// Encode a File using Base64 format /// </summary> /// <param name="sourceFile">The file to encrypt complete path</param> /// <param name="destFile">Destination file complete path. If the file doesn't exist, it creates it</param> public void EncodeFile(String sourceFile, String destFile) { if (sourceFile.IsNullOrWhiteSpace() || !File.Exists(sourceFile)) throw new FileNotFoundException("Cannot find the specified source file", sourceFile ?? "null"); if (destFile.IsNullOrWhiteSpace()) throw new ArgumentException("Please specify the path of the output path", nameof(destFile)); using (var fs = new BufferedStream(File.OpenRead(sourceFile), 1200000)) { byte[] filebytes = new byte[fs.Length]; fs.Read(filebytes, 0, Convert.ToInt32(fs.Length)); string encodedData = Convert.ToBase64String(filebytes, Base64FormattingOptions.InsertLineBreaks); File.WriteAllText(destFile, encodedData); } }
/// <summary> /// Creates a new deploy key for a repository. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/keys/#create"> API documentation</a> for more information. /// </remarks> /// <param name="repositoryId">The Id of the repository.</param> /// <param name="newDeployKey">The deploy key to create for the repository.</param> public Task <DeployKey> Create(long repositoryId, NewDeployKey newDeployKey) { Ensure.ArgumentNotNull(newDeployKey, "newDeployKey"); if (StringExt.IsNullOrWhiteSpace(newDeployKey.Title)) { throw new ArgumentException("The new deploy key's title must not be null."); } if (StringExt.IsNullOrWhiteSpace(newDeployKey.Key)) { throw new ArgumentException("The new deploy key's key must not be null."); } return(ApiConnection.Post <DeployKey>(ApiUrls.RepositoryDeployKeys(repositoryId), newDeployKey)); }
private new static Status StatusFromBulkDocsResponseItem(IDictionary <string, object> item) { try { if (!item.ContainsKey("error")) { return(new Status(StatusCode.Ok)); } var errorStr = (string)item.Get("error"); if (StringEx.IsNullOrWhiteSpace(errorStr)) { return(new Status(StatusCode.Ok)); } // 'status' property is nonstandard; TouchDB returns it, others don't. var statusString = (string)item.Get("status"); var status = Convert.ToInt32(statusString); if (status >= 400) { return(new Status((StatusCode)status)); } // If no 'status' present, interpret magic hardcoded CouchDB error strings: if (errorStr.Equals("unauthorized", StringComparison.InvariantCultureIgnoreCase)) { return(new Status(StatusCode.Unauthorized)); } if (errorStr.Equals("forbidden", StringComparison.InvariantCultureIgnoreCase)) { return(new Status(StatusCode.Forbidden)); } if (errorStr.Equals("conflict", StringComparison.InvariantCultureIgnoreCase)) { return(new Status(StatusCode.Conflict)); } return(new Status(StatusCode.UpStreamError)); } catch (Exception e) { Log.E(Database.Tag, "Exception getting status from " + item, e); } return(new Status(StatusCode.Ok)); }
/// <summary> /// Avoids the additional database trip that using SqliteCommandBuilder requires. /// </summary> /// <returns>The update command.</returns> /// <param name="table">Table.</param> /// <param name="values">Values.</param> /// <param name="whereClause">Where clause.</param> /// <param name="whereArgs">Where arguments.</param> sqlite3_stmt GetUpdateCommand(string table, ContentValues values, string whereClause, string[] whereArgs) { if (!IsOpen) { Open(Path); } var builder = new StringBuilder("UPDATE "); builder.Append(table); builder.Append(" SET "); // Append our content column names and create our SQL parameters. var valueSet = values.ValueSet(); var paramList = new List <object>(); var index = 0; foreach (var column in valueSet) { if (index++ > 0) { builder.Append(","); } builder.AppendFormat("{0} = ?", column.Key); paramList.Add(column.Value); } if (!StringEx.IsNullOrWhiteSpace(whereClause)) { builder.Append(" WHERE "); builder.Append(whereClause); } if (whereArgs != null) { paramList.AddRange(whereArgs); } var sql = builder.ToString(); var command = _writeConnection.prepare(sql); command.bind(paramList.ToArray <object>()); return(command); }
/// <summary> /// Avoids the additional database trip that using SqliteCommandBuilder requires. /// </summary> /// <returns>The update command.</returns> /// <param name="table">Table.</param> /// <param name="values">Values.</param> /// <param name="whereClause">Where clause.</param> /// <param name="whereArgs">Where arguments.</param> sqlite3_stmt GetUpdateCommand(string table, ContentValues values, string whereClause, string[] whereArgs) { if (!IsOpen) { throw Misc.CreateExceptionAndLog(Log.To.Database, StatusCode.BadRequest, TAG, "GetUpdateCommand called on closed database"); } var builder = new StringBuilder("UPDATE "); builder.Append(table); builder.Append(" SET "); // Append our content column names and create our SQL parameters. var valueSet = values.ValueSet(); var paramList = new List <object>(); var index = 0; foreach (var column in valueSet) { if (index++ > 0) { builder.Append(","); } builder.AppendFormat("{0} = ?", column.Key); paramList.Add(column.Value); } if (!StringEx.IsNullOrWhiteSpace(whereClause)) { builder.Append(" WHERE "); builder.Append(whereClause); } if (whereArgs != null) { paramList.AddRange(whereArgs); } var sql = builder.ToString(); var command = BuildCommand(_writeConnection, sql, paramList.ToArray <object>()); return(command); }
/// <summary> /// Creates a new deploy key for a repository. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/keys/#create"> API documentation</a> for more information. /// </remarks> /// <param name="owner">The owner of the repository.</param> /// <param name="name">The name of the repository.</param> /// <param name="newDeployKey">The deploy key to create for the repository.</param> public Task <DeployKey> Create(string owner, string name, NewDeployKey newDeployKey) { Ensure.ArgumentNotNullOrEmptyString(owner, "owner"); Ensure.ArgumentNotNullOrEmptyString(name, "name"); Ensure.ArgumentNotNull(newDeployKey, "newDeployKey"); if (StringExt.IsNullOrWhiteSpace(newDeployKey.Title)) { throw new ArgumentException("The new deploy key's title must not be null."); } if (StringExt.IsNullOrWhiteSpace(newDeployKey.Key)) { throw new ArgumentException("The new deploy key's key must not be null."); } return(ApiConnection.Post <DeployKey>(ApiUrls.RepositoryDeployKeys(owner, name), newDeployKey)); }
/// <summary> /// Gets a message bus type based on the specified string <paramref name="value"/>. /// </summary> /// <param name="value">The value to convert to an message bus type (i.e., name, value or unique description).</param> /// <param name="result">The message bus type.</param> public static Boolean TryGetMessageBusType(String value, out MessageBusType result) { Int32 parsedValue; Object boxedValue = Int32.TryParse(value, out parsedValue) ? parsedValue : (Object)value; if (value.IsNullOrWhiteSpace()) { result = MessageBusType.MicrosoftMessageQueuing; return true; } if (Enum.IsDefined(typeof(MessageBusType), boxedValue)) { result = (MessageBusType)Enum.ToObject(typeof(MessageBusType), boxedValue); return true; } return KnownMessageBusTypes.TryGetValue(value, out result); }
/// <summary> /// Avoids the additional database trip that using SqliteCommandBuilder requires. /// </summary> /// <returns>The delete command.</returns> /// <param name="table">Table.</param> /// <param name="whereClause">Where clause.</param> /// <param name="whereArgs">Where arguments.</param> sqlite3_stmt GetDeleteCommand(string table, string whereClause, string[] whereArgs) { if (!IsOpen) { Open(Path); } var builder = new StringBuilder("DELETE FROM "); builder.Append(table); if (!StringEx.IsNullOrWhiteSpace(whereClause)) { builder.Append(" WHERE "); builder.Append(whereClause); } sqlite3_stmt command; command = BuildCommand(_writeConnection, builder.ToString(), whereArgs); return(command); }
/// <summary> /// Avoids the additional database trip that using SqliteCommandBuilder requires. /// </summary> /// <returns>The delete command.</returns> /// <param name="table">Table.</param> /// <param name="whereClause">Where clause.</param> /// <param name="whereArgs">Where arguments.</param> sqlite3_stmt GetDeleteCommand(string table, string whereClause, string[] whereArgs) { if (!IsOpen) { throw new CouchbaseLiteException("GetDeleteCommand called on closed database", StatusCode.BadRequest); } var builder = new StringBuilder("DELETE FROM "); builder.Append(table); if (!StringEx.IsNullOrWhiteSpace(whereClause)) { builder.Append(" WHERE "); builder.Append(whereClause); } sqlite3_stmt command; command = BuildCommand(_writeConnection, builder.ToString(), whereArgs); return(command); }
private void SerializeToDisk() { var filePath = GetSaveCookiesFilePath(); if (StringEx.IsNullOrWhiteSpace(filePath)) { return; } List <Cookie> aggregate = new List <Cookie>(); foreach (var uri in _cookieUriReference) { var collection = GetCookies(uri); aggregate.AddRange(collection.Cast <Cookie>().Where(IsNotSessionOnly)); } using (var writer = new StreamWriter(filePath)) { var json = Manager.GetObjectMapper().WriteValueAsString(aggregate); writer.Write(json); } }
public void ReturnTrueIfWhiteSpace(String value) { Assert.True(value.IsNullOrWhiteSpace()); }
/// <summary> /// Computes a keyed hash for a source file, creates a target file with the keyed hash /// prepended to the contents of the source file, then decrypts the file and compares /// the source and the decrypted files. /// </summary> /// <param name="key">The key to use to encode the file</param> /// <param name="sourceFile">The file to encrypt complete path</param> /// <param name="destFile">Destination file complete path. If the file doesn't exist, it creates it</param> public void EncodeFile(string key, String sourceFile, String destFile) { if (sourceFile.IsNullOrWhiteSpace() || !File.Exists(sourceFile)) throw new FileNotFoundException("Cannot find the specified source file", sourceFile ?? "null"); if (destFile.IsNullOrWhiteSpace()) throw new ArgumentException("Please specify the path of the output path", nameof(destFile)); if (string.IsNullOrEmpty(key)) throw new ArgumentException("Please specify the key", nameof(key)); // Create a key using a random number generator. This would be the // secret key shared by sender and receiver. byte[] secretkey = key.ToByteArray(); // Initialize the keyed hash object. HMACMD5 myhmacMD5 = new HMACMD5(secretkey); FileStream inStream = new FileStream(sourceFile, FileMode.Open); FileStream outStream = new FileStream(destFile, FileMode.Create); // Compute the hash of the input file. byte[] hashValue = myhmacMD5.ComputeHash(inStream); // Reset inStream to the beginning of the file. inStream.Position = 0; // Write the computed hash value to the output file. outStream.Write(hashValue, 0, hashValue.Length); // Copy the contents of the sourceFile to the destFile. int bytesRead; // read 1K at a time byte[] buffer = new byte[1024]; do { // Read from the wrapping CryptoStream. bytesRead = inStream.Read(buffer, 0, 1024); outStream.Write(buffer, 0, bytesRead); } while (bytesRead > 0); myhmacMD5.Clear(); // Close the streams inStream.Close(); outStream.Close(); }
/// <summary>分析</summary> /// <param name="uri"></param> public NetUri Parse(String uri) { if (uri.IsNullOrWhiteSpace()) return this; // 分析协议 var p = uri.IndexOf(Sep); if (p > 0) { Protocol = uri.Substring(0, p); uri = uri.Substring(p + Sep.Length); } // 分析端口 p = uri.LastIndexOf(":"); if (p >= 0) { var pt = uri.Substring(p + 1); Int32 port = 0; if (Int32.TryParse(pt, out port)) { Port = port; uri = uri.Substring(0, p); } } Host = uri; return this; }
public ActionResult Edit(int? id, float Price, bool? Negotiable, String Description, String Password) { User activeUser = _userLogic.GetUserById(User.Identity.Name); if (Password.IsNullOrWhiteSpace() || !activeUser.Password.Equals(Password)) { ModelState.AddModelError("badPassword", "Password errada!"); return RedirectToAction("Edit"); } Advert advert; if (id.HasValue && !(advert = _advertiselogic.GetAdvert(id.Value)).Equals(null)) { if (!advert.Price.Equals(Price) && Price > 0) advert.Price = Price; if (Negotiable.HasValue && advert.Negotiable != Negotiable.Value) advert.Negotiable = Negotiable.Value; if (!Description.IsNullOrWhiteSpace() && !advert.Description.Equals(Description)) advert.Description = Description; if (_advertiselogic.UpdateAdvert(advert)) return RedirectToAction("ManageAd", "Account"); } ModelState.AddModelError("AdvertUpdateError", "Erro! Não foi possível editar este anúncio!"); return RedirectToAction("Edit"); }
/// <summary>拆分排序字句</summary> /// <param name="orderby"></param> /// <param name="isdescs"></param> /// <returns></returns> public static String[] Split(String orderby, out Boolean[] isdescs) { isdescs = null; if (orderby.IsNullOrWhiteSpace()) return null; //2014-01-04 Modify by Apex //处理order by带有函数的情况,避免分隔时将函数拆分导致错误 foreach (Match match in Regex.Matches(orderby, @"\([^\)]*\)", RegexOptions.Singleline)) { orderby = orderby.Replace(match.Value, match.Value.Replace(",", "★")); } String[] ss = orderby.Trim().Split(","); if (ss == null || ss.Length < 1) return null; String[] keys = new String[ss.Length]; isdescs = new Boolean[ss.Length]; for (int i = 0; i < ss.Length; i++) { String[] ss2 = ss[i].Trim().Split(' '); // 拆分名称和排序,不知道是否存在多余一个空格的情况 if (ss2 != null && ss2.Length > 0) { keys[i] = ss2[0].Replace("★", ","); if (ss2.Length > 1 && ss2[1].EqualIgnoreCase("desc")) isdescs[i] = true; } } return keys; }
static Map GetConfig(String str) { // 如果不含=,表示整个str就是类型Type if (!str.Contains("=")) return new Map() { TypeName = str }; var dic = str.SplitAsDictionary(); if (dic == null || dic.Count < 1) { if (!str.IsNullOrWhiteSpace()) return new Map { TypeName = str }; return null; } var map = new Map(); foreach (var item in dic) { switch (item.Key.ToLower()) { case "name": map.Identity = item.Value; break; case "type": map.TypeName = item.Value; break; case "priority": Int32 n = 0; if (Int32.TryParse(item.Value, out n)) map.Priority = n; break; default: break; } } return map; }
/// <summary> /// Json编码 /// </summary> /// <returns></returns> private String JsonEncoding(String message) { if (message.IsNullOrWhiteSpace()) return message; else return message.Replace("\"", "'"); }
public String UpdateLibrary(XbmcSettings settings, String path) { var request = new RestRequest(); var parameters = new Dictionary<String, Object>(); parameters.Add("directory", path); if (path.IsNullOrWhiteSpace()) { parameters = null; } var response = ProcessRequest(request, settings, "VideoLibrary.Scan", parameters); return Json.Deserialize<XbmcJsonResult<String>>(response).Result; }
/// <summary>返回相差的分钟数</summary> /// <param name="time"></param> /// <param name="minutes"></param> /// <returns></returns> public static Int32 StrDateDiffMinutes(String time, Int32 minutes) { if (time.IsNullOrWhiteSpace()) { return 1; } TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddMinutes(minutes); if (ts.TotalMinutes > Int32.MaxValue) { return Int32.MaxValue; } else if (ts.TotalMinutes < Int32.MinValue) { return Int32.MinValue; } return (Int32)ts.TotalMinutes; }
/// <summary>工具方法:生成年月日时分秒字符串</summary> /// <param name="link">年月日时分秒之间的连接字符</param> /// <param name="RanLength">最后生成随机数的位数</param> /// <returns>返回年月日时分秒毫秒四位随机数字的字符串</returns> public static String FileNameStr(String link, Int32 RanLength) { if (link.IsNullOrWhiteSpace()) { link = ""; } Int32 Year = DateTime.Now.Year; //年 Int32 Month = DateTime.Now.Month; //月份 Int32 Day = DateTime.Now.Day; //日期 Int32 Hour = DateTime.Now.Hour; //小时 Int32 Minute = DateTime.Now.Minute; //分钟 Int32 Second = DateTime.Now.Second; //秒 Int32 Milli = DateTime.Now.Millisecond; //毫秒 //生成随机数字 String DataString = "0123456789"; Random rnd = new Random(); String rndstring = ""; Int32 i = 1; while (i <= RanLength) { rndstring += DataString[rnd.Next(DataString.Length)]; i++; } String FileNameStr = (Year + link + Month + link + Day + link + Hour + link + Minute + link + Second + link + Milli + link + rndstring).ToString(); return FileNameStr; }
/// <summary> /// Decode a file encripted using TripleDES with specified password and IV strings. /// </summary> /// <param name="sourceFile">The file to decrypt complete path</param> /// <param name="destFile">Destination file complete path. If the file doesn't exist, it creates it</param> /// <param name="password">The password string</param> /// <param name="IV">The IV string</param> public void DecodeFile(String sourceFile, String destFile, String password, String IV) { if (sourceFile.IsNullOrWhiteSpace() || !File.Exists(sourceFile)) throw new FileNotFoundException("Cannot find the specified source file", sourceFile ?? "null"); if (destFile.IsNullOrWhiteSpace()) throw new ArgumentException("Please specify the path of the output path", nameof(destFile)); if (string.IsNullOrEmpty(password)) throw new ArgumentException("Please specify the password", nameof(password)); if (string.IsNullOrEmpty(IV)) throw new ArgumentException("Please specify the Initialize Vector", nameof(IV)); byte[] Key = GeneratePassword(password); byte[] IVb = GeneratePassword(IV); byte[] data = File.ReadAllBytes(sourceFile); FileStream fsPlainText = new FileStream(destFile, FileMode.Create, FileAccess.Write); fsPlainText.SetLength(0); // Create a Crypto Stream that transforms the file stream using the chosen // encryption and writes it to the output FileStream object. CryptoStream cs = new CryptoStream(fsPlainText, new TripleDESCryptoServiceProvider().CreateDecryptor(Key, IVb), CryptoStreamMode.Write); cs.Write(data, 0, data.Length); cs.FlushFinalBlock(); // Clean up. There is no need to call fsCipherText.Close() because closing the // crypto stream automatically encloses the stream that was passed into it. cs.Close(); }
private void ArrangeAddressSet(AddressSet addressSet, String street, String postCode, String houseNumber, String apartmentNumber, String city) { GetWordsFromField(addressSet.wordComponents, city.PrepareString(WORDSTOREMOVE)); GetWordsFromField(addressSet.wordComponents, street.PrepareString(WORDSTOREMOVE)); if (!postCode.IsNullOrWhiteSpace()) { String tempCode = postCode.GetOnlyDigits(); if (tempCode.Length == 5) { addressSet.postalCodeComponent = tempCode.Substring(0, 2) + " " + tempCode.Substring(2, 3); } } if (!String.IsNullOrEmpty(houseNumber)) { addressSet.houseNumberComponent = houseNumber.PrepareString(); } if (!String.IsNullOrEmpty(apartmentNumber)) { addressSet.apartmentNumberComponent = apartmentNumber.PrepareString(); } }
private void GetWordsFromField(List<String> set, String input) { if (!input.IsNullOrWhiteSpace()) { if (input.Trim().Contains(" ") || input.Trim().Contains("-")) { String[] split = input.Split(new char[] {' ', '-'} ,StringSplitOptions.RemoveEmptyEntries); foreach (String piece in split) { if (!piece.IsNullOrWhiteSpace()) { set.Add(piece); } } } else { set.Add(input); } } }
/// <summary>返回相差的小时数</summary> /// <param name="time"></param> /// <param name="hours"></param> /// <returns></returns> public static Int32 StrDateDiffHours(String time, Int32 hours) { if (time.IsNullOrWhiteSpace()) { return 1; } TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddHours(hours); if (ts.TotalHours > Int32.MaxValue) { return Int32.MaxValue; } else if (ts.TotalHours < Int32.MinValue) { return Int32.MinValue; } return (Int32)ts.TotalHours; }
public ActionResult Edit(String Password, String newPassword, string fullName, string email, int? phoneNr, DistrictEnum? district, bool? isStand, string standLink, string fullAdress) { User activeUser = _userLogic.GetUserById(User.Identity.Name); if (Password.IsNullOrWhiteSpace() || !activeUser.Password.Equals(Password)) //obrigatorio { ModelState.AddModelError("badPassword", "Password errada!"); return RedirectToAction("Edit"); } if (!newPassword.IsNullOrWhiteSpace() && activeUser.Password != newPassword) activeUser.Password = newPassword; if (!fullName.IsNullOrWhiteSpace() && activeUser.FullName != fullName) activeUser.FullName = fullName; if (!email.IsNullOrWhiteSpace() && activeUser.FullName != fullName) activeUser.Email = email; if (phoneNr.HasValue && activeUser.PhoneNr != phoneNr) activeUser.PhoneNr = phoneNr.Value; if (district.HasValue && activeUser.District != district) activeUser.District = district.Value; if (isStand.HasValue && activeUser.IsStand != isStand) activeUser.IsStand = isStand.Value; if (activeUser.IsStand) // TODO verificar se checkbox está activo { if (!standLink.IsNullOrWhiteSpace() && activeUser.StandLink != standLink) activeUser.StandLink = standLink; if (!fullAdress.IsNullOrWhiteSpace() && activeUser.GeoLocalization.FullAdress != fullAdress) activeUser.GeoLocalization.FullAdress = fullAdress; } if (!_userLogic.UpdateUser(activeUser)) ModelState.AddModelError("AccountUpdateError", "Erro! Não foi possível editar esta conta!"); return RedirectToAction("Index"); }
/// <summary>拆分排序字句</summary> /// <param name="orderby"></param> /// <param name="isdescs"></param> /// <returns></returns> public static String[] Split(String orderby, out Boolean[] isdescs) { isdescs = null; if (orderby.IsNullOrWhiteSpace()) return null; String[] ss = orderby.Trim().Split(","); if (ss == null || ss.Length < 1) return null; String[] keys = new String[ss.Length]; isdescs = new Boolean[ss.Length]; for (int i = 0; i < ss.Length; i++) { String[] ss2 = ss[i].Trim().Split(' '); // 拆分名称和排序,不知道是否存在多余一个空格的情况 if (ss2 != null && ss2.Length > 0) { keys[i] = ss2[0]; if (ss2.Length > 1 && ss2[1].EqualIgnoreCase("desc")) isdescs[i] = true; } } return keys; }