private IEnumerable <Tuple <string, string> > GetAllNodeNameDescriptionPairs() { var pmExtension = dynamoViewModel.Model.GetPackageManagerExtension(); var pkgLoader = pmExtension.PackageLoader; var workspaces = new List <CustomNodeWorkspaceModel>(); foreach (var def in AllFuncDefs()) { CustomNodeWorkspaceModel ws; if (dynamoViewModel.Model.CustomNodeManager.TryGetFunctionWorkspace( def.FunctionId, DynamoModel.IsTestMode, out ws)) { workspaces.Add(ws); } } // collect the name-description pairs for every custom node return (workspaces .Where( p => (pkgLoader.IsUnderPackageControl(p.FileName) && pkgLoader.GetOwnerPackage(p.FileName).Name == Name) || !pmExtension.PackageLoader.IsUnderPackageControl(p.FileName)) .Select( x => new Tuple <string, string>( x.Name, !String.IsNullOrEmpty(x.Description) ? x.Description : Wpf.Properties.Resources.MessageNoNodeDescription))); }
public void ExportVertexButton_OnClick() { bool shiftHeld = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift); string filePath = StandaloneFileBrowser.SaveFilePanel("Save Vertices", LastUsedDirectory, "points", ".json"); if (!String.IsNullOrEmpty(filePath)) { LastUsedDirectory = Path.GetDirectoryName(filePath); if (shiftHeld) { ExportVectorArray(); } if (!shiftHeld) { ExportNamedVectors(); } } void ExportVectorArray() { VectorArrayExportFileFormat data = new VectorArrayExportFileFormat(); foreach (GameObject point in PointManager.PointObjects) { data.points.Add(new float[3] { point.transform.position.x, point.transform.position.y, point.transform.position.z }); } string json = JsonConvert.SerializeObject(data); if (File.Exists(filePath)) { File.Delete(filePath); } File.WriteAllText(filePath, json); } void ExportNamedVectors() { NamedVectorArrayExportFileFormat data = new NamedVectorArrayExportFileFormat(); foreach (GameObject point in PointManager.PointObjects) { data.points.Add(new NamedVector3() { x = point.transform.position.x, y = point.transform.position.y, z = point.transform.position.z }); } string json = JsonConvert.SerializeObject(data); if (File.Exists(filePath)) { File.Delete(filePath); } File.WriteAllText(filePath, json); } }
/// <summary> /// Create the credentials based on a base64 encoded string which comes from a HTTP header Authentication: /// </summary> /// <param name="HTTPHeaderCredential"></param> public HTTPBasicAuthentication(String HTTPHeaderCredential) { #region Initial checks if (HTTPHeaderCredential.IsNullOrEmpty()) throw new ArgumentNullException("HTTPHeaderCredential", "The given credential string must not be null or empty!"); #endregion var splitted = HTTPHeaderCredential.Split(new[] { ' ' }); if (splitted.IsNullOrEmpty()) throw new ArgumentException("invalid credentials " + HTTPHeaderCredential); if (splitted[0].ToLower() == "basic") { HTTPCredentialType = HTTPAuthenticationTypes.Basic; var usernamePassword = splitted[1].FromBase64().Split(new[] { ':' }); if (usernamePassword.IsNullOrEmpty()) throw new ArgumentException("invalid username/password " + splitted[1].FromBase64()); Username = usernamePassword[0]; Password = usernamePassword[1]; } else throw new ArgumentException("invalid credentialType " + splitted[0]); }
/// <summary> /// Save to a specific file path, if the path is null or empty, does nothing. /// If successful, the CurrentWorkspace.FilePath field is updated as a side effect /// </summary> /// <param name="newPath">The path to save to</param> public virtual bool SaveAs(string newPath) { if (String.IsNullOrEmpty(newPath)) { return(false); } DynamoLogger.Instance.Log("Saving " + newPath + "..."); try { var xmlDoc = this.GetXml(); xmlDoc.Save(newPath); this.FileName = newPath; this.OnWorkspaceSaved(); } catch (Exception ex) { //Log(ex); DynamoLogger.Instance.Log(ex.Message); DynamoLogger.Instance.Log(ex.StackTrace); Debug.WriteLine(ex.Message + " : " + ex.StackTrace); return(false); } return(true); }
private static bool CheckArchiver(string gameDir) { if (IoC.Archiver.CheckArchiverLib()) { return(true); } if (String.IsNullOrEmpty(gameDir)) { gameDir = new GameSearch().FindSteamGameDir(SteamGameName); if (String.IsNullOrEmpty(gameDir)) { Console.WriteLine("Cannot get oodle library, Cannot find game and no game directory specified."); return(false); } } try { IoC.Archiver.GetLibrary().Wait(); } catch (Exception ex) { Console.WriteLine($"Cannot get oodle library, {ex.Message}."); return(false); } return(true); }
/// <summary> /// Save to a specific file path, if the path is null or empty, does nothing. /// If successful, the CurrentWorkspace.FilePath field is updated as a side effect /// </summary> /// <param name="newPath">The path to save to</param> /// <param name="core"></param> public virtual bool SaveAs(string newPath, ProtoCore.Core core) { if (String.IsNullOrEmpty(newPath)) { return(false); } Log("Saving " + newPath + "..."); try { if (SaveInternal(newPath, core)) { OnWorkspaceSaved(); } } catch (Exception ex) { //Log(ex); Log(ex.Message); Log(ex.StackTrace); Debug.WriteLine(ex.Message + " : " + ex.StackTrace); return(false); } return(true); }
/// <summary> /// Save to a specific file path, if the path is null or empty, does nothing. /// If successful, the CurrentWorkspace.FilePath field is updated as a side effect /// </summary> /// <param name="newPath">The path to save to</param> public virtual bool SaveAs(string newPath) { if (String.IsNullOrEmpty(newPath)) { return(false); } dynSettings.Controller.DynamoLogger.Log("Saving " + newPath + "..."); try { if (SaveInternal(newPath)) { OnWorkspaceSaved(); } } catch (Exception ex) { //Log(ex); dynSettings.Controller.DynamoLogger.Log(ex.Message); dynSettings.Controller.DynamoLogger.Log(ex.StackTrace); Debug.WriteLine(ex.Message + " : " + ex.StackTrace); return(false); } return(true); }
public static String DecryptString(String Text, String Key) { if (Text.IsNullOrEmpty()) throw new BPAExtensionException("DecryptString Text Not Found!"); RijndaelManaged RijndaelCipher = new RijndaelManaged(); byte[] EncryptedData = Convert.FromBase64String(Text.Replace("_", "/").Replace("-", "+")); byte[] Salt = new UTF8Encoding().GetBytes(Key.Length.ToString()); PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Key, Salt); ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(16), SecretKey.GetBytes(16)); MemoryStream memoryStream = new MemoryStream(EncryptedData); CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read); byte[] PlainText = new byte[EncryptedData.Length]; int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length); memoryStream.Close(); cryptoStream.Close(); String DecryptedData = new UTF8Encoding().GetString(PlainText, 0, DecryptedCount); if (HttpContext.Current != null) return HttpContext.Current.Server.HtmlDecode(DecryptedData); else return DecryptedData; }
private void OpenButton_Click(object sender, RoutedEventArgs e) { if (String.IsNullOrEmpty(filePath.Text)) { MessageBox.Show("Путь к файлу не может быть пустым!", "Ошибка", MessageBoxButton.OK); filePath.Text = String.Empty; return; } if (!File.Exists(filePath.Text)) { this.Close(); var fileNotFoundWindow = new FileNotFoundMessageWindow(); fileNotFoundWindow.Show(); return; } MainWindow.FilePath = filePath.Text; var formatter = new XmlSerializer(typeof(ObservableCollection <Data>)); using (var fs = new FileStream(MainWindow.FilePath, FileMode.OpenOrCreate)) { var data = (ObservableCollection <Data>)formatter.Deserialize(fs); MainWindow.Data = data; } this.Close(); MainWindow.MainWindowFrame.NavigationService.Navigate(new Uri("View/FullDataGrid.xaml", UriKind.Relative)); }
// note. we need this constructor to provide information // about method's parameters without having to decompile it // // the point is that to get sig's symbols we've got to know their ids // but the ids need to be synchronized with Refs in decompiled body // that's why a simple call to Sig::Syms need to decompile the entire body public ParamInfo(Sig sig, int index, String name, Type type) { Sig = sig; Index = index; Name = name.IsNullOrEmpty() ? "$p" + index : name; Type = type; }
private IEnumerable<String> PrettyPrintImpl(String js) { var newLineDelims = new []{".Select(", ".Where(", ".OrderBy(", ".GroupBy"}; Func<int> delimPos = () => js.IsNullOrEmpty() ? -1 : newLineDelims .Select(delim => js.IndexOf(delim,1 )) .Aggregate(-1, (running, curr) => curr <= 0 ? running : (running == -1 ? curr : Math.Min(running, curr))); while(delimPos() != -1) { yield return js.Substring(0, delimPos()).ToVerbatimCSharpCopy(); js = js.Substring(delimPos()); } if (!js.IsNullOrEmpty()) yield return js; }
internal bool ContainsFile(string path) { if (String.IsNullOrEmpty(RootDirectory) || !Directory.Exists(RootDirectory)) { return(false); } return(Directory.EnumerateFiles(RootDirectory, "*", SearchOption.AllDirectories).Any(s => s == path)); }
void _sv_QueryTextChange(object sender, SearchView.QueryTextChangeEventArgs e) { if (!String.IsNullOrEmpty(e.NewText)) { _newAdapter.Filter.InvokeFilter(e.NewText); } _lv.Adapter = _newAdapter; }
public static string GetDynamoDirectory() { if (String.IsNullOrEmpty(_dynamoDirectory)) { var dynamoAssembly = Assembly.GetExecutingAssembly(); _dynamoDirectory = Path.GetDirectoryName(dynamoAssembly.Location); } return(_dynamoDirectory); }
public IEnumerable <string> EnumerateAssemblyFilesInBinDirectory() { if (String.IsNullOrEmpty(RootDirectory) || !Directory.Exists(RootDirectory)) { return(new List <string>()); } return(Directory.EnumerateFiles(RootDirectory, "*.dll", SearchOption.AllDirectories)); }
/// <summary> /// Example: String.Format("/Utility/Img/{0}?width=300&height=100", Utility.ImageGetHash("img", "img_contenttye", "photo", "id_photo", "1")); /// "?width=300&height=100" is optional but when used need to send both /// </summary> /// <param name="id">"id" is the default MVC param</param> /// <returns>The Image to be Displed</returns> public ActionResult Img(String id) { if (id.IsNullOrEmpty()) return View(); System.Web.HttpContext hc = System.Web.HttpContext.Current; try { String[] spl = Security.DecryptString(id, Security.Key).Split('#'); Hashtables lst = DBAction.Select( String.Format("SELECT {0}, {1} FROM {2} WHERE {3} = #id ", spl[0], spl[1], spl[2], spl[3]), new Parameters() { new Parameter("#id", spl[4], System.Data.DbType.Int32) } ); Stream s = new MemoryStream((byte[])lst[0][spl[0]]); byte[] b; if (hc.Request.QueryString.Count == 0) { b = ((MemoryStream)s).ToArray(); } else { Image img = Image.FromStream(s); img = ImageUtility.FixedSize(img, hc.Request.QueryString["width"].ToInt32(), hc.Request.QueryString["height"].ToInt32()); MemoryStream ms = new MemoryStream(); img.Save(ms, ImageFormat.Jpeg); b = ms.ToArray(); } hc.Response.Clear(); hc.Response.ContentType = lst[0][spl[1]].ToString(); hc.Response.BinaryWrite(b); } catch (Exception) { throw; } finally { hc.Response.End(); } return View(); }
// 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 static INode AddNode(this IGraph myIGraph, String myId) { if (myIGraph == null) throw new ArgumentNullException("myIGraph must not be null!"); if (myId.IsNullOrEmpty()) throw new ArgumentNullException("myId must not be null or empty!"); return myIGraph.AddNode(new Node(myId)); }
private async void xuiButton1_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(this.user)) { #region ListUsers var usersList = new List <string>(); usersList.Add(user1.Value.Pk.ToString()); usersList.Add(user2.Value.Pk.ToString()); usersList.Add(user3.Value.Pk.ToString()); usersList.Add(user4.Value.Pk.ToString()); usersList.Add(user5.Value.Pk.ToString()); #endregion var recipients = string.Join(",", usersList); var directText = await ApiManage.instaApi.MessagingProcessor .SendDirectTextAsync(recipients, null, txtCaption.Text); if (directText.Succeeded) { FMessegeBox.FarsiMessegeBox.Show($"آخی خستم کردی یه خسته نباشی بگو لاقل به اینا یه پیامی دادم \n" + $" {user1.Value.UserName} || " + $"{user2.Value.UserName} ||" + $" {user3.Value.UserName} || " + $"{user4.Value.UserName} || " + $"{user5.Value.UserName} " , "حوصله سر رفته ", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Information); } else { FMessegeBox.FarsiMessegeBox.Show("خستمه نمیتونم پیام بدم اونم 5 تا اوووووووو", "خسته هستم ", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Information); } } else { var user = await ApiManage.instaApi.UserProcessor.GetUserAsync(txtUserName.Text); var direct = await ApiManage.instaApi.MessagingProcessor.SendDirectTextAsync(user.Value.Pk.ToString(), null, txtCaption.Text); if (direct.Succeeded) { FMessegeBox.FarsiMessegeBox.Show($"منم ربات خوب بازیگوش پیام دادم به ایشون {user.Value.FullName} ", "ارسال شد", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Information); } } }
public static void CheckDirectory(string dir) { if (String.IsNullOrEmpty(dir)) { return; } if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } }
public NaturalLanguageProcessor(String language = null) { if (language.IsNullOrEmpty()) { language = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName; } _positionOfSpeechTags = PositionOfSpeechTags.CreatePositionOfSpeechTags(language); _language = language; }
private IEnumerable <Tuple <string, string> > GetAllNodeNameDescriptionPairs() { // TODO: include descriptions for all compiled nodes // collect the name-description pairs for every custom node return (AllFuncDefs() .Where(p => (dynSettings.PackageLoader.IsUnderPackageControl(p) && dynSettings.PackageLoader.GetOwnerPackage(p).Name == this.Name) || !dynSettings.PackageLoader.IsUnderPackageControl(p)) .Select(x => new Tuple <string, string>(x.WorkspaceModel.Name, !String.IsNullOrEmpty(x.WorkspaceModel.Description) ? x.WorkspaceModel.Description : "No description provided"))); }
private static Boolean CheckCNPJ(String CNPJ) { if (CNPJ.IsNullOrEmpty()) return false; int[] multiplicador1 = new int[12] { 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 }; int[] multiplicador2 = new int[13] { 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 }; int soma; int resto; string digito; string tempCnpj; CNPJ = CNPJ.Trim().Replace(".", "").Replace("-", "").Replace("/", ""); if (CNPJ.Length != 14) return false; tempCnpj = CNPJ.Substring(0, 12); soma = 0; for (int i = 0; i < 12; i++) soma += int.Parse(tempCnpj[i].ToString()) * multiplicador1[i]; resto = (soma % 11); if (resto < 2) resto = 0; else resto = 11 - resto; digito = resto.ToString(); tempCnpj = tempCnpj + digito; soma = 0; for (int i = 0; i < 13; i++) soma += int.Parse(tempCnpj[i].ToString()) * multiplicador2[i]; resto = (soma % 11); if (resto < 2) resto = 0; else resto = 11 - resto; digito = digito + resto.ToString(); return CNPJ.EndsWith(digito); }
private void tbxProductNameSearch_TextChanged(object sender, EventArgs e) { var text = tbxProductNameSearch.Text; if (!String.IsNullOrEmpty(text)) { dgwProducts.DataSource = _productService.GetByProductName(text); } else { LoadProducts(); } }
public void Initialize(Environment env, string alias) { if (CSString.IsNullOrEmpty(alias)) { //no alias, put these in the global scope env.Define("LoadCharacter", loadCharacter, true); env.Define("LoadBackground", loadBackground, true); } else { env.Define(alias, new VisualBundle(), true); } }
void CreateDialog() { _picker = new APicker(_context); _picker.MinValue = _min; _picker.MaxValue = _max; if (_NumberPickerCell.Number.HasValue) { _picker.Value = _NumberPickerCell.Number.Value; } if (!String.IsNullOrEmpty(_NumberPickerCell.Unit)) { _picker.SetFormatter(new UnitFormatter(_NumberPickerCell.Unit)); ApplyInitialFormattingBugfix(_picker); } if (_dialog == null) { using (var builder = new AlertDialog.Builder(_context)) { builder.SetTitle(_title); Android.Widget.FrameLayout parent = new Android.Widget.FrameLayout(_context); parent.AddView(_picker, new Android.Widget.FrameLayout.LayoutParams( ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent, GravityFlags.Center)); builder.SetView(parent); builder.SetNegativeButton(global::Android.Resource.String.Cancel, (o, args) => { ClearFocus(); }); builder.SetPositiveButton(global::Android.Resource.String.Ok, (o, args) => { _NumberPickerCell.Number = _picker.Value; _command?.Execute(_picker.Value); ClearFocus(); }); _dialog = builder.Create(); } _dialog.SetCanceledOnTouchOutside(true); _dialog.DismissEvent += (ss, ee) => { DestroyDialog(); }; _dialog.Show(); } }
void FilterTextTextChanged(object sender, glAndroid.Text.TextChangedEventArgs e) { var searchTerm = _filterText.Text; if (String.IsNullOrEmpty(searchTerm)) { ((ReportTemplateListAdapter)_listReportTemplete.Adapter).ResetSearch(); } else { Search(searchTerm); ((ReportTemplateListAdapter)_listReportTemplete.Adapter).Filter.InvokeFilter(searchTerm); } }
public override void OnInspectorGUI() { base.OnInspectorGUI(); Framewriter writer = (Framewriter)target; if (GUILayout.Button("Write Frame")) { string filePath = EditorUtility.SaveFilePanel("Save Frame...", "%userprofile%", "Frame", "json"); if (!String.IsNullOrEmpty(filePath)) { Frame frame = writer.MakeFrame(); writer.WriteFrame(frame, filePath); } } }
internal static Throwable ToThrowable(Exception exception) { while (exception is AggregateException) { exception = exception.InnerException; } var throwable = exception as Throwable; if (throwable != null) { return(throwable); } throwable = new Throwable(exception.Message); var stackTrace = new List <StackTraceElement>(); if (exception.StackTrace != null) { foreach (Match match in StackTraceRegex.Matches(exception.StackTrace)) { var cls = match.Groups[1].Value; var method = match.Groups[2].Value; var file = match.Groups[3].Value; var line = Convert.ToInt32(match.Groups[4].Value); if (!cls.StartsWith("System.Runtime.ExceptionServices") && !cls.StartsWith("System.Runtime.CompilerServices")) { if (String.IsNullOrEmpty(file)) { file = "filename unknown"; } stackTrace.Add(new StackTraceElement(cls, method, file, line)); } } } throwable.SetStackTrace(stackTrace.ToArray()); if (exception.InnerException != null) { throwable.InitCause(ToThrowable(exception.InnerException)); } return(throwable); }
/// <summary> /// Repaint an image cell with an image in an image /// list. Run this method in the CellPainting event /// of the DataGridView. /// /// This method ignores invalid parameters. Provide /// it with empty or invalid indices to cause it to /// abort. /// </summary> public static void PaintImageCell(this DataGridView dataGridView, DataGridViewCellPaintingEventArgs e, ImageList imageList, String imageKey) { //Abort if any parameter is null or if the image does not exist if (e == null || imageList == null || imageKey.IsNullOrEmpty()) return; if (!imageList.Images.ContainsKey(imageKey)) return; //Paint the image e.PaintBackground(e.ClipBounds, false); var pt = e.CellBounds.Location; pt.X += (e.CellBounds.Width - imageList.ImageSize.Width) / 2; pt.Y += 4; imageList.Draw(e.Graphics, pt, imageList.Images.IndexOfKey(imageKey)); e.Handled = true; }
private void frmDirect_Load(object sender, EventArgs e) { if (String.IsNullOrEmpty(user)) { #region Visible txtUserName1.Visible = true; txtUserName2.Visible = true; txtUserName3.Visible = true; txtUserName4.Visible = true; lblUserName1.Visible = true; lblUserName2.Visible = true; lblUserName3.Visible = true; lblUserName4.Visible = true; #endregion #region SetText txtUserName.Text = user1.Value.UserName; txtUserName1.Text = user2.Value.UserName; txtUserName2.Text = user3.Value.UserName; txtUserName3.Text = user4.Value.UserName; txtUserName4.Text = user5.Value.UserName; btnSend.Text = "ارسال چندگانه "; #endregion } else { txtUserName.Text = user.ToString(); #region Visible txtUserName1.Visible = false; txtUserName2.Visible = false; txtUserName3.Visible = false; txtUserName4.Visible = false; lblUserName1.Visible = false; lblUserName2.Visible = false; lblUserName3.Visible = false; lblUserName4.Visible = false; #endregion } }
public void EnumerateAdditionalFiles() { if (String.IsNullOrEmpty(RootDirectory) || !Directory.Exists(RootDirectory)) { return; } var nonDyfDllFiles = Directory.EnumerateFiles( RootDirectory, "*", SearchOption.AllDirectories) .Where(x => !x.ToLower().EndsWith(".dyf") && !x.ToLower().EndsWith(".dll") && !x.ToLower().EndsWith("pkg.json") && !x.ToLower().EndsWith(".backup")) .Select(x => new PackageFileInfo(RootDirectory, x)); AdditionalFiles.Clear(); AdditionalFiles.AddRange(nonDyfDllFiles); }
public static string PrepareView(this ControllerBase controller, Object model, String viewName = null) { if (model == null) throw new ArgumentNullException("model"); if (viewName == null) throw new ArgumentNullException("viewName"); if (viewName.IsNullOrEmpty()) { viewName = controller.ControllerContext.RouteData.GetRequiredString("action"); } var viewPath = GetVirtualViewPath(controller, viewName); var result = RenderRazorViewToString(controller, viewPath, model); return result; }
/// <summary> /// Create the credentials based on a base64 encoded string which comes from a HTTP header Authentication: /// </summary> /// <param name="Username">The username.</param> /// <param name="Password">The password.</param> public HTTPBasicAuthentication(String Username, String Password) { #region Initial checks if (Username.IsNullOrEmpty()) throw new ArgumentNullException(nameof(Username), "The given username must not be null or empty!"); if (Password.IsNullOrEmpty()) throw new ArgumentNullException(nameof(Password), "The given password must not be null or empty!"); #endregion this._HTTPCredentialType = HTTPAuthenticationTypes.Basic; this._Username = Username; this._Password = Password; }
/// <summary> /// Удаляет из входной строки указанную начальную и конечную подстроки, если они есть. Если нет хотя бы одной из них, то возвращается исходная строка. /// Если во входной строке содержится множество вложенных один в другой начальных и конечных токенов, метод удалит их все рекурсивно. /// </summary> /// <param name="Input">Входная строка, из которой необходимо удалить все указанные начальные и конечные токены.</param> /// <param name="StartToken">Начальный токен</param> /// <param name="EndToken">Конечный токен</param> /// <param name="CompOpt"></param> /// <returns>Новая строка, содержащая копию старой с удалёнными токенами</returns> public static String DeleteStartAndEndTokens(String Input, String StartToken, String EndToken, StringComparison CompOpt) { if (StartToken.IsNullOrEmpty() == true) { throw new ArgumentException("Начальный токен не может быть NULL или пустой строкой", "Input"); } if (EndToken == null) { throw new ArgumentException("Конечный токен не может быть NULL или пустой строкой", "EndToken"); } if (Input.IsStringNullEmptyWhiteSpace() == true) { return Input; } if (Input.StartsWith(StartToken, CompOpt) == true && Input.EndsWith(EndToken, CompOpt) == true) { Input = Input.Remove(0, StartToken.Length); Input = Input.Remove(Input.Length - EndToken.Length, EndToken.Length); return DeleteStartAndEndTokens(Input, StartToken, EndToken, CompOpt); } else { return Input; } }
public void Initialize(Environment env, string alias) { if (CSString.IsNullOrEmpty(alias)) { //no alias, put these in the global scope env.Define("Clock", clock, true); env.Define("Random", random, true); env.Define("RandomSeed", randomSeed, true); env.Define("ToNumber", toNumber, true); env.Define("ToString", toStringCallable, true); env.Define("ToBoolean", toBoolean, true); env.Define("GetType", getTypeCallable, true); env.Define("IsSame", isSame, true); } else { env.Define(alias, new StandardBundle(), true); } }
/// <summary> /// Stores the given IGEXF graph on disk /// </summary> /// <param name="myFileName">The filename for storing the graph</param> public static IGEXF Save(this IGEXF myIGEXF, String myFileName) { #region Initial checks if (myIGEXF == null) throw new ArgumentNullException("myIGEXF must not be null!"); if (myFileName.IsNullOrEmpty()) throw new ArgumentNullException("myFileName must not be null!"); #endregion if (!myFileName.Contains(".")) myFileName += ".gexf"; myIGEXF.ToXML().Save(myFileName); return myIGEXF; }
private void LoadByPrice() { var minPrice = tbxByPriceMin.Text; decimal min = _productService.GetMinPrice(); decimal max = _productService.GetMaxPrice(); if (!String.IsNullOrEmpty(minPrice)) { min = Convert.ToDecimal(minPrice); } var maxPrice = tbxByPriceMax.Text; if (!String.IsNullOrEmpty(maxPrice)) { max = Convert.ToDecimal(maxPrice); } dgwProducts.DataSource = _productService.GetByPrice(min, max); }
public bool CanReach(string remoteUri) { HttpWebRequest request; var uri = new Uri(remoteUri); var credentials = uri.UserInfo; if (!StringExt.IsNullOrEmpty(credentials)) { remoteUri = string.Format("{0}://{1}{2}", uri.Scheme, uri.Authority, uri.PathAndQuery); request = WebRequest.CreateHttp(remoteUri); request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials))); request.PreAuthenticate = true; } else { request = WebRequest.CreateHttp(remoteUri); } request.AllowWriteStreamBuffering = true; request.Timeout = 10000; request.Method = "GET"; try { using (var response = (HttpWebResponse)request.GetResponse()) { return(true); //We only care that the server responded } } catch (Exception e) { var we = e as WebException; if (we != null && we.Status == WebExceptionStatus.ProtocolError) { return(true); //Getting an HTTP error technically means we can connect } Log.I(TAG, "Didn't get successful connection to {0}", remoteUri); Log.D(TAG, " Cause: ", e); LastError = e; return(false); } }
/// <summary> /// Example: String.Format("/Utility/Download/{0}", Utility.DownloadGetHash("img", "img_contenttype", "img_name", "photos", "id_photo", "1")); /// </summary> /// <param name="id">"id" is the default MVC param</param> /// <returns>The File to be Downloaded</returns> public ActionResult Download(String id) { if (id.IsNullOrEmpty()) return View(); System.Web.HttpContext hc = System.Web.HttpContext.Current; try { String[] spl = Security.DecryptString(id, Security.Key).Split('#'); Hashtables lst = DBAction.Select( String.Format("SELECT {0}, {1}, {2} FROM {3} WHERE {4} = #id ", spl[0], spl[1], spl[2], spl[3], spl[4]), new Parameters() { new Parameter("#id", spl[5], System.Data.DbType.Int32) } ); Stream s = new MemoryStream((byte[])lst[0][spl[0]]); hc.Response.Clear(); hc.Response.AddHeader("Content-Disposition", "attachment; filename=" + lst[0][spl[2]].ToString().Replace(" ", "_")); hc.Response.AddHeader("Content-Length", s.Length.ToString()); hc.Response.ContentType = lst[0][spl[2]].ToString(); hc.Response.BinaryWrite(((MemoryStream)s).ToArray()); } catch (Exception) { throw; } finally { hc.Response.End(); } return View(); }
/// <summary> /// Create an abstract HTTP client. /// </summary> /// <param name="ClientId">A unqiue identification of this client.</param> /// <param name="Hostname">The hostname to connect to.</param> /// <param name="RemotePort">The remote TCP port to connect to.</param> /// <param name="RemoteCertificateValidator">A delegate to verify the remote TLS certificate.</param> /// <param name="ClientCert">The TLS client certificate to use.</param> /// <param name="HTTPVirtualHost">An optional HTTP virtual host name to use.</param> /// <param name="UserAgent">An optional HTTP user agent to use.</param> /// <param name="QueryTimeout">An optional timeout for upstream queries.</param> /// <param name="DNSClient">An optional DNS client.</param> public AHTTPClient(String ClientId, String Hostname, IPPort RemotePort, RemoteCertificateValidationCallback RemoteCertificateValidator = null, X509Certificate ClientCert = null, String HTTPVirtualHost = null, String UserAgent = DefaultHTTPUserAgent, TimeSpan? QueryTimeout = null, DNSClient DNSClient = null) { #region Initial checks if (Hostname.IsNullOrEmpty()) throw new ArgumentNullException(nameof(Hostname), "The given parameter must not be null or empty!"); #endregion this.ClientId = ClientId; this.Hostname = Hostname; this.RemotePort = RemotePort ?? DefaultRemotePort; this.RemoteCertificateValidator = RemoteCertificateValidator; this.ClientCert = ClientCert; this.HTTPVirtualHost = HTTPVirtualHost.IsNotNullOrEmpty() ? HTTPVirtualHost : Hostname; this.UserAgent = UserAgent ?? DefaultHTTPUserAgent; this.RequestTimeout = QueryTimeout != null ? QueryTimeout.Value : DefaultQueryTimeout; this.DNSClient = DNSClient == null ? new DNSClient() : DNSClient; }
/// <summary>加载插件</summary> /// <param name="typeName"></param> /// <param name="disname"></param> /// <param name="dll"></param> /// <param name="linkName"></param> /// <param name="url"></param> /// <returns></returns> public static Type LoadPlugin(String typeName, String disname, String dll, String linkName, String url) { var type = typeName.GetTypeEx(true); if (type != null) return type; if (dll.IsNullOrEmpty()) return null; // 先检查当前目录,再检查插件目录 var file = dll.GetFullPath(); if (!File.Exists(file) && Runtime.IsWeb) file = "Bin".GetFullPath().CombinePath(dll); if (!File.Exists(file)) file = Setting.Current.GetPluginPath().CombinePath(dll); // 如果本地没有数据库,则从网络下载 if (!File.Exists(file)) { XTrace.WriteLine("{0}不存在或平台版本不正确,准备联网获取 {1}", disname ?? dll, url); var client = new WebClientX(true, true); client.Log = XTrace.Log; var dir = Path.GetDirectoryName(file); var file2 = client.DownloadLinkAndExtract(url, linkName, dir); } if (!File.Exists(file)) { XTrace.WriteLine("未找到 {0} {1}", disname, dll); return null; } type = typeName.GetTypeEx(true); if (type != null) return type; //var assembly = Assembly.LoadFrom(file); //if (assembly == null) return null; //type = assembly.GetType(typeName); //if (type == null) type = AssemblyX.Create(assembly).GetType(typeName); return type; }
public static string StoreImage(this Bitmap image, Context context, string imagesFolder, string imageFileName = "") { File pictureFile = null; if (String.IsNullOrEmpty(imageFileName)) { pictureFile = context.GetOutputMediaFile(imagesFolder); } else { pictureFile = context.GetOutputMediaFileName(imagesFolder, imageFileName); } if (pictureFile == null) { Log.Debug(Tag, "Error creating media file, check storage permissions: "); return(""); } try { var stream = new FileStream(pictureFile.AbsolutePath, FileMode.OpenOrCreate); image.Compress(Bitmap.CompressFormat.Png, 90, stream); stream.Close(); return(pictureFile.Name); } catch (FileNotFoundException ex) { Log.Debug(Tag, "File not found: " + ex.Message); return(""); } catch (IOException exx) { Log.Debug(Tag, "Error accessing file: " + exx.Message); return(""); } }
public static String EncryptString(String Text, String Key) { if (Text.IsNullOrEmpty()) throw new BPAExtensionException("EncryptString Text Not Found!"); RijndaelManaged RijndaelCipher = new RijndaelManaged(); byte[] PlainText = new UTF8Encoding().GetBytes(Text); byte[] Salt = new UTF8Encoding().GetBytes(Key.Length.ToString()); PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Key, Salt); ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(16), SecretKey.GetBytes(16)); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write); cryptoStream.Write(PlainText, 0, PlainText.Length); cryptoStream.FlushFinalBlock(); byte[] CipherBytes = memoryStream.ToArray(); memoryStream.Close(); cryptoStream.Close(); return Convert.ToBase64String(CipherBytes).Replace("/", "_").Replace("+", "-"); }
protected override void Start() { if (rosConnector == null) { rosConnector = GetComponent <RosConnector>(); } if (rosConnector != null) { canBroadcastFrames = true; } if (!String.IsNullOrEmpty(framePath)) { canWriteFrames = true; if (!Directory.Exists(framePath)) { Directory.CreateDirectory(framePath); } if (!framePath.EndsWith("\\") && !framePath.EndsWith("/")) { framePath += "/"; } // framePath += "\\"; <-- Caused problems on Linux } }
public static String ToMediaRSS(this QueryResult myQueryResult, String myGalleryTitle = "GreenIris", String myGalleryDescription = "Generated by a sones GraphDS graph traversal", String myGalleryCopyright = null, String myGalleryLanguage = "en-en") { var myStringBuilder = new StringBuilder(); myStringBuilder.AppendLine("<channel>").AppendLine(); #region Successful, or... if (myQueryResult.ResultType == ResultType.Successful) { if (myGalleryTitle != "") myStringBuilder.Append("<title>").Append(myGalleryTitle).AppendLine("</title>"); if (myGalleryDescription != "") myStringBuilder.Append("<description>").Append(myGalleryDescription).AppendLine("</description>"); if (!myGalleryCopyright.IsNullOrEmpty()) myStringBuilder.Append("<copyright>").Append(myGalleryCopyright).AppendLine("</copyright>"); if (myGalleryLanguage != "") myStringBuilder.Append("<language>").Append(myGalleryLanguage).AppendLine("</language>"); myStringBuilder.AppendLine(); //<!-- <logo url="pl_images/logo.gif" /> --> //<!-- <atom:icon>http://www.mywebsite.com/images/logo.gif</atom:icon> --> //<!-- <link>http://www.ahzf.de/cooliris.html</link> --> if (myQueryResult != null && myQueryResult.Vertices != null) if (myQueryResult.Vertices != null && myQueryResult.Vertices != null) foreach (var _Vertex in myQueryResult) if (_Vertex != null) myStringBuilder.Append(_Vertex.ToMediaRSS()); } #endregion #region ...error(s) occurred! else { myStringBuilder.Append("<title>Error(s) occurred!</title>"); myStringBuilder.AppendLine("<description>"); if (myQueryResult != null && myQueryResult.Errors != null) foreach (var _Error in myQueryResult.Errors) { myStringBuilder.AppendLine("ErrorCode: " + _Error.GetType().ToString()); myStringBuilder.AppendLine("ErrorDescription: " + _Error.ToString()); } myStringBuilder.AppendLine("</description>"); myStringBuilder.Append("<language>en-en</language>"); } #endregion myStringBuilder.AppendLine().AppendLine("</channel>"); return myStringBuilder.ToString(); }
public static EMailAddress Parse(String EMailString) { if (EMailString.IsNullOrEmpty()) return null; var b = EMailString.IndexOf('<'); var c = EMailString.IndexOf('>'); if (b >= 0 && c > b) return new EMailAddress(EMailString.Remove(b, c-b+1).Trim(), SimpleEMailAddress.Parse(EMailString.Substring(b+1, c-b-1).Trim())); return new EMailAddress(SimpleEMailAddress.Parse(EMailString)); }
private static Boolean CheckCPF(String CPF) { if (CPF.IsNullOrEmpty()) return false; int[] multiplicador1 = new int[9] { 10, 9, 8, 7, 6, 5, 4, 3, 2 }; int[] multiplicador2 = new int[10] { 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 }; string tempCpf; string digito; int soma; int resto; CPF = CPF.Trim().Replace(".", "").Replace("-", ""); if (CPF.Length != 11) return false; for (int i = 0; i < 9; i++) { string n = i.ToString(); if (CPF == n.Replace(n, (n + n + n + n + n + n + n + n + n + n + n))) return false; } tempCpf = CPF.Substring(0, 9); soma = 0; for (int i = 0; i < 9; i++) soma += int.Parse(tempCpf[i].ToString()) * multiplicador1[i]; resto = soma % 11; if (resto < 2) resto = 0; else resto = 11 - resto; digito = resto.ToString(); tempCpf = tempCpf + digito; soma = 0; for (int i = 0; i < 10; i++) soma += int.Parse(tempCpf[i].ToString()) * multiplicador2[i]; resto = soma % 11; if (resto < 2) resto = 0; else resto = 11 - resto; digito = digito + resto.ToString(); return CPF.EndsWith(digito); }
public static HtmlBuilder internalLink(this HtmlBuilder builder, String text, String cls, String relDoc, String section) { String url = "#" + relDoc; builder .e("a") .att("href", url) .att("dox:doc", relDoc) .attCls(cls); if (!section.IsNullOrEmpty()) builder.att("dox:section", section); return builder.text(text).c(); }
//IPlugin public void Initialize(Environment env, string alias) { env.Define(CSString.IsNullOrEmpty(alias) ? "Toy" : alias, this, true); }
/// <summary> /// Initialize the OCPI HTTP server using IPAddress.Any, http port 8080 and maybe start the server. /// </summary> internal GenericAPI(RoamingNetwork RoamingNetwork, HTTPServer HTTPServer, String URIPrefix = "/ext/OCPI", Func<String, Stream> GetRessources = null, String ServiceName = DefaultHTTPServerName, EMailAddress APIEMailAddress = null, PgpPublicKeyRing APIPublicKeyRing = null, PgpSecretKeyRing APISecretKeyRing = null, String APIPassphrase = null, EMailAddressList APIAdminEMail = null, SMTPClient APISMTPClient = null, String LogfileName = DefaultLogfileName) { #region Initial checks if (RoamingNetwork == null) throw new ArgumentNullException("RoamingNetwork", "The given parameter must not be null!"); if (HTTPServer == null) throw new ArgumentNullException("HTTPServer", "The given parameter must not be null!"); if (URIPrefix.IsNullOrEmpty()) throw new ArgumentNullException("URIPrefix", "The given parameter must not be null or empty!"); if (!URIPrefix.StartsWith("/")) URIPrefix = "/" + URIPrefix; #endregion #region Init data this._HTTPServer = HTTPServer; this._GetRessources = GetRessources; this._URIPrefix = URIPrefix; this._ServiceName = ServiceName; this._APIEMailAddress = APIEMailAddress; this._APIPublicKeyRing = APIPublicKeyRing; this._APISecretKeyRing = APISecretKeyRing; this._APIPassphrase = APIPassphrase; this._APIAdminEMail = APIAdminEMail; this._APISMTPClient = APISMTPClient; this._DNSClient = HTTPServer.DNSClient; #endregion RegisterURITemplates(); }
/// <summary> /// Уплотняет пробелы в указанной строке, сокращая множественные идущие подряд пробелы до одного /// </summary> /// <param name="Input">Строка, которую следует уплотнить. Если NULL или пустая - будет возвращена без изменений.</param> /// <returns></returns> public static String ShrinkSpaces(String Input) { if (Input.IsNullOrEmpty() == true) { return Input; } StringBuilder output = new StringBuilder(Input.Length); const Char space = ' '; Int32 spaces_count = 0; foreach (Char c in Input) { if (Char.IsControl(c) == true || Char.IsWhiteSpace(c) == false) { if (spaces_count > 0) { spaces_count = 0; output.Append(space); } output.Append(c); } else { spaces_count++; } } if (spaces_count > 0) { output.Append(space); } return output.ToString(); }
public static IMetadata SetCreator(this IMetadata myIMetadata, String myCreator) { if (myIMetadata == null) throw new ArgumentNullException("myIMetadata must not be null!"); if (myCreator.IsNullOrEmpty()) throw new ArgumentNullException("myCreator must not be null!"); myIMetadata.Creator = myCreator; return myIMetadata; }
/// <summary> /// Ищет и возвращает из входной строки все найденные подстроки, если они там присутствуют /// </summary> /// <param name="Input">Входная строка, в которой происходит поиск подстрок</param> /// <param name="Target">Целевая подстрока, которая ищется во входной строке</param> /// <param name="StartIndex">Начальная позиция входной строки, с которой включительно начинается поиск. Если 0 - поиск ведётся с начала. /// Если меньше 0 или больше длины входной строки, выбрасывается исключение.</param> /// <param name="ComparisonType">Опции сравнения строк между собой, по которым будет вести поиск целевой подстроки во входной строке</param> /// <returns>Список найденных подстрок. Если не будет найдена ни одна, метод возвратит пустой список.</returns> public static List<Substring> FindSubstring(String Input, String Target, Int32 StartIndex, StringComparison ComparisonType) { if (Input == null) { throw new ArgumentNullException("Input", "Входная строка не может быть NULL"); } if(Input.Length == 0) {throw new ArgumentException("Входная строка не может быть пустой", "Input");} if (Target.IsNullOrEmpty() == true) { throw new ArgumentException("Целевая подстрока не может быть NULL или пустой", "Target"); } if (StartIndex < 0) { throw new ArgumentOutOfRangeException("StartIndex", StartIndex, "Начальная позиция не может быть меньше 0"); } if (StartIndex >= Input.Length) { throw new ArgumentOutOfRangeException("StartIndex", StartIndex, String.Format("Начальная позиция ('{0}') не может быть больше или равна длине строки ('{1}')", StartIndex, Input.Length)); } List<Substring> output = new List<Substring>(); Int32 search_offset = StartIndex; while (true) { Int32 found_position = Input.IndexOf(Target, search_offset, ComparisonType); if(found_position < 0) {break;} search_offset = found_position + Target.Length; Substring found = Substring.FromIndexWithLength(Input, found_position, Target.Length); output.Add(found); } return output; }
private void InitAclGrid() { aclDataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; aclDataGridView.MultiSelect = true; aclDataGridView.RowHeadersVisible = false; aclDataGridView.AutoGenerateColumns = false; aclDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; aclDataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; aclDataGridView.CellFormatting += delegate(object sender, DataGridViewCellFormattingEventArgs args) { if (null != aclDataGridView.DataSource) { if (aclDataGridView.IsCurrentCellInEditMode || args.ColumnIndex != 0) { return; } if (String.IsNullOrEmpty(args.Value as String)) { args.Value = ((InfoController.UserAndRoleEntry)aclDataGridView.Rows[args.RowIndex].DataBoundItem) .getUser().getPlaceholder(); args.CellStyle.ForeColor = Color.Gray; args.CellStyle.Font = new Font(args.CellStyle.Font, FontStyle.Italic); } } }; //make combobox directly editable without multiple clicks aclDataGridView.CellClick += delegate(object o, DataGridViewCellEventArgs a) { if (a.RowIndex < 0) { return; // Header } if (a.ColumnIndex != 1) { return; // Filter out other columns } aclDataGridView.BeginEdit(true); ComboBox comboBox = (ComboBox)aclDataGridView.EditingControl; comboBox.DroppedDown = true; }; aclDataGridView.CellBeginEdit += delegate(object sender, DataGridViewCellCancelEventArgs args) { if (args.ColumnIndex == 0) { args.Cancel = !((InfoController.UserAndRoleEntry)aclDataGridView.Rows[args.RowIndex].DataBoundItem).getUser() .isEditable(); } }; DataGridViewTextBoxColumn userColumn = new DataGridViewTextBoxColumn(); userColumn.HeaderText = "Grantee"; userColumn.DataPropertyName = AclColumnName.User.ToString(); userColumn.DefaultCellStyle.NullValue = String.Empty; userColumn.Name = AclColumnName.User.ToString(); DataGridViewComboBoxColumn rolesColumn = new DataGridViewComboBoxColumn(); rolesColumn.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing; rolesColumn.DataPropertyName = AclColumnName.Role.ToString(); rolesColumn.HeaderText = "Permission"; rolesColumn.Name = AclColumnName.Role.ToString(); aclDataGridView.Columns.Add(userColumn); aclDataGridView.Columns.Add(rolesColumn); }
public void ReturnFalseIfNotNullOrEmpty(String value) { Assert.False(value.IsNullOrEmpty()); }
public void ProcessRequest(HttpContext context) { try { SessionVarName = context.Request.QueryString["SessionVarName"]; IEnumerable retrievedData = (IEnumerable)context.Session[SessionVarName]; if (retrievedData.IsNull()) return; AggregateColumn = context.Request.QueryString["AggregateColumn"]; if (AggregateColumn.IsNullOrEmpty()) AggregateColumn = String.Empty; UserDataString = context.Request.QueryString["FooterRowCaption"]; if (UserDataString.IsNullOrEmpty()) UserDataString = String.Empty; String vid_Ref = context.Request.QueryString["vid_Ref"]; String parentColumnName = context.Request.QueryString["ParentColumnName"]; String parentColumnValue = context.Request.QueryString["ParentColumnValue"]; if (vid_Ref.IsNotNullOrEmpty() && vid_Ref.NotEquals("null")) { filterRetrievedData(ref retrievedData, vid_Ref); OnDataSourceViewSelectCallback(retrievedData); } else if (parentColumnName.IsNotNullOrEmpty() && parentColumnValue.IsNotNullOrEmpty()) filterRetrievedDataDataSourceView(retrievedData, parentColumnName, parentColumnValue); else OnDataSourceViewSelectCallback(retrievedData); } catch (Exception ex) { throw ex; } }
public Object GetActualValueFromGridRow(String dataType, String value, String format) { try { switch (dataType) { case "System.DateTime": if (value.IsNullOrEmpty()) return DateTime.MinValue; if (format.IsNotNullOrEmpty()) { CultureInfo provider = CultureInfo.InvariantCulture; return DateTime.ParseExact(value, format, provider); } else return DateTime.Parse(value); case "System.Decimal": return Decimal.Parse(value.IfEmptyThenZero()); case "System.Int16": return Int16.Parse(value.IfEmptyThenZero()); case "System.Int32": return Int32.Parse(value.IfEmptyThenZero()); case "System.Int64": return Int64.Parse(value.IfEmptyThenZero()); case "System.Double": return Double.Parse(value.IfEmptyThenZero()); case "System.Boolean": //The following checkings are needed as JqGrid check box re if (value.ToString().ToLower().Equals("no")) return false; else if (value.ToString().ToLower().Equals("yes")) return true; else if (value.ToString().ToLower().Equals("0")) return false; else if (value.ToString().ToLower().Equals("1")) return true; else if (value.ToString().ToLower().Equals("off")) return false; else if (value.ToString().ToLower().Equals("on")) return true; else return Boolean.Parse(value); default: return value; } } catch (Exception ex) { throw ex; } }
public static IMetadata SetDescription(this IMetadata myIMetadata, String myDescription) { if (myIMetadata == null) throw new ArgumentNullException("myIMetadata must not be null!"); if (myDescription.IsNullOrEmpty()) throw new ArgumentNullException("myDescription must not be null!"); myIMetadata.Description = myDescription; return myIMetadata; }
/// <summary> /// Возвращает искомую подстроку из указанной строки, которые находятся между наборами указанных начальных и конечных токенов /// в правильной последовательности. Если каких-либо или всех указанных токенов не найдено, или их реальный порядок не совпадает с указанным, /// возвращается пустой список подстрок. /// </summary> /// <param name="Input">Входная строка, содержащая токены, и внутри которой происходит поиск. Входная строка не может быть NULL, пустой или состоящей из одних пробелов.</param> /// <param name="StartTokens">Список начальных токенов в определённой последовательности, которая будет соблюдена при поиске подстрок. /// Не может быть NULL или пустым, но может содержать единственный элемент.</param> /// <param name="EndTokens">Список конечных токенов в определённой последовательности, которая будет соблюдена при поиске подстрок. /// Не может быть NULL или пустым, но может содержать единственный элемент.</param> /// <param name="EndTokensSearchDirection">Задаёт направление поиска конечных токенов после того, как найдены все начальные. /// FromEndToStart - поиск ведётся от самого конца строки и продвигается до последнего начального токена до тех пор, пока не найдёт все конечные токены. /// FromStartToEnd - поиск ведётся от конца последнего начального токена до конца строки.</param> /// <param name="StartIndex">Позиция (включительная) начала поиска во входной строке. Если 0 - поиск ведётся с начала. /// Если меньше 0 или больше длины входной строки - выбрасывается исключение.</param> /// <param name="CompOpt">Опции сравнения строк между собой</param> /// <exception cref="ArgumentException"></exception> /// <returns>Искомая подстрока. Если не найдена, возвращается NULL.</returns> public static Substring GetInnerStringBetweenTokensSet(String Input, String[] StartTokens, String[] EndTokens, StringTools.Direction EndTokensSearchDirection, Int32 StartIndex, StringComparison CompOpt) { if(Input == null){throw new ArgumentNullException("Input");} if (Input.IsStringNullEmptyWhiteSpace() == true) { throw new ArgumentException("Входная строка не может быть NULL, пустой или состоящей из одних пробелов", "Input"); } if (StartTokens.IsNullOrEmpty()) { throw new ArgumentException("Список начальных токенов не может быть NULL или пустым", "StartTokens"); } if (EndTokens.IsNullOrEmpty()) { throw new ArgumentException("Список конечных токенов не может быть NULL или пустым", "EndTokens"); } if (StartIndex < 0) { throw new ArgumentOutOfRangeException("StartIndex", StartIndex, "Позиция начала поиска не может быть меньше 0"); } if (StartIndex >= Input.Length) { throw new ArgumentOutOfRangeException("StartIndex", StartIndex, String.Format("Позиция начала поиска ('{0}') не может быть больше или равна длине строки ('{1}')", StartIndex, Input.Length)); } if (Enum.IsDefined(typeof(StringTools.Direction), EndTokensSearchDirection) == false) { throw new InvalidEnumArgumentException("EndTokensSearchDirection", (Int32)EndTokensSearchDirection, typeof(StringTools.Direction)); } if (Enum.IsDefined(typeof(StringComparison), (Int32)CompOpt) == false) { throw new InvalidEnumArgumentException("CompOpt", (Int32)CompOpt, typeof(StringComparison)); } Int32 internal_offset = StartIndex; for (Int32 one_start_token_index = 0; one_start_token_index < StartTokens.Length; one_start_token_index++) { String current_start_token = StartTokens[one_start_token_index]; Int32 current_start_token_pos = Input.IndexOf(current_start_token, internal_offset, CompOpt); if (current_start_token_pos == -1) { return null; } else { internal_offset = current_start_token_pos + current_start_token.Length; } } Int32 final_substr_start_index = internal_offset; if (EndTokensSearchDirection == StringTools.Direction.FromEndToStart) { Int32 end_offset = Input.Length - 1; for (Int32 one_end_token_index = EndTokens.Length - 1; one_end_token_index >= 0; one_end_token_index--) { String current_end_token = EndTokens[one_end_token_index]; Int32 count_to_search = end_offset - final_substr_start_index; Int32 current_end_token_pos = Input.LastIndexOf(current_end_token, end_offset, count_to_search, CompOpt); if (current_end_token_pos == -1) { return null; } else { end_offset = current_end_token_pos; } } return Substring.FromIndexToIndex(Input, final_substr_start_index, end_offset - 1); } else// if (EndTokensSearchDirection == StringTools.Direction.FromStartToEnd) { Int32 final_substr_end_index = 0; for (Int32 one_end_token_index = 0; one_end_token_index < EndTokens.Length; one_end_token_index++) { String current_end_token = EndTokens[one_end_token_index]; Int32 current_end_token_pos = Input.IndexOf(current_end_token, internal_offset, CompOpt); if (current_end_token_pos == -1) { return null; } internal_offset = current_end_token_pos + current_end_token.Length; if (final_substr_end_index == 0) { final_substr_end_index = current_end_token_pos; } } return Substring.FromIndexToIndex(Input, final_substr_start_index, final_substr_end_index - 1); } }