public override List <InputDefinition> DefineInput() { // // This is an example for selecting two points; change this to suit your needs. // List <InputDefinition> inputs = new List <InputDefinition>(); DrawingHandler drawingHandler = new DrawingHandler(); if (drawingHandler.GetConnectionStatus()) { Picker picker = drawingHandler.GetPicker(); ViewBase view = null; PointList points = new PointList(); StringList prompts = new StringList(); prompts.Add("Pick first point"); prompts.Add("Pick second point"); picker.PickPoints(2, prompts, out points, out view); inputs.Add(InputDefinitionFactory.CreateInputDefinition(view, points)); } return(inputs); }
static void Main(string[] args) { Console.WriteLine(GenericCollections.About); var stringDictionary = new StringDictionary(); stringDictionary.Add(7, "Irena"); stringDictionary.Add(4, "Sammy"); stringDictionary.Add(25, "Ben"); stringDictionary.Add(42, "Seth"); stringDictionary.Add(97, "Ken"); stringDictionary.Add(55, "Kellan"); stringDictionary.Add(3, "Chris"); var a = stringDictionary.Get(42); Console.WriteLine($"The person with the fav nbr of 42 is {stringDictionary.Get(42)}"); foreach (var data in stringDictionary.Values()) { Console.WriteLine(data); } var strings = new StringList(); strings.Add("abc"); strings.Add("def"); strings.Add("ghi"); strings.Add("xxx", "yyy"); strings.Add("aaa", "bbb", "ccc", "ddd", "eee", "fff"); foreach (var str in strings) { Console.WriteLine(str); } }
public void SerializeTest() { StringList target = new StringList(); MemoryStream stream = new MemoryStream(); IBinaryWriter writer = new XmlWriterMock(new StreamAdapter(stream)); // empty list target.Serialize(writer); string expected = "<string></string>"; string actual = Encoding.UTF8.GetString(stream.ToArray()); Assert.AreEqual(expected, actual); // 1 item in list target.Add("A"); stream.Position = 0; target.Serialize(writer); expected = "<string>A</string>"; actual = Encoding.UTF8.GetString(stream.ToArray()); Assert.AreEqual(expected, actual); // 2 items in list target.Add("B"); stream.Position = 0; target.Serialize(writer); expected = "<string>A,B</string>"; actual = Encoding.UTF8.GetString(stream.ToArray()); Assert.AreEqual(expected, actual); }
static void Main(string[] args) { var stringDictionary = new StringDictionary(); stringDictionary.Add(7, "Irene"); stringDictionary.Add(4, "Sammy"); stringDictionary.Add(25, "Ben"); stringDictionary.Add(42, "Seth"); stringDictionary.Add(97, "Ken"); stringDictionary.Add(55, "Kellen"); stringDictionary.Add(3, "Chris"); Console.WriteLine($"The person with Key # 42 is {stringDictionary.Get(42)}"); foreach (var Name in stringDictionary.Names()) { Console.WriteLine(Name); } var strings = new StringList(); strings.Add("ABC"); strings.Add("DEF"); strings.Add("GHI"); strings.Add("jklm", "nopq", "rstu", "vwxyz"); foreach (var str in strings) { Console.WriteLine(str); } }
/////////////////////////////////////////////////////////////////////// private static StringList GetMatchList( Match match ) { if (match == null) { return(null); } GroupCollection groups = match.Groups; if (groups == null) { return(null); } StringList list = new StringList(); foreach (Group group in groups) { if (group != null) { list.Add(group.Value); } else { list.Add((string)null); } } return(list); }
private void WriteEntityAttributes(EntityInfo entity) { // printout keys and indexes var attrList = new StringList(); attrList.Add(StringHelper.SafeFormat("Entity(TableName = \"{0}\")", entity.TableName)); foreach (var key in entity.Keys) { if (key.KeyType.IsSet(KeyType.ForeignKey)) { continue; } //Skip single-column indexes - we set [Index] attribute directly on property; also skip erroneous keys with no members (if table has no PK, VITA creates PK with no columns) if (IsPropertyKey(key) || key.KeyMembers.Count == 0) { continue; } var attrSpec = GetKeyAttribute(key, onProperty: false); attrList.Add(attrSpec); } // If PK is not found in database, system creates an empty fake PK /* * if(entity.PrimaryKey.KeyMembers.Count == 0) { * var warn = StringHelper.SafeFormat(" Warning: Table {0} has no primary key.", entity.TableName); * _warnings.Add(warn); * _feedback.SendFeedback(FeedbackType.Warning, warn); * } */ _output.Write(" [{0}]\r\n", string.Join(", ", attrList)); }
protected void Filter() { // backwards due to modify by remove for (int i = filteredData.Count - 1; i >= 0; i--) { if (!IsFilterMatch(filteredData[i])) { filteredData.RemoveAt(i); } } foreach (RsbResourceID obj in currentFile.StringResources) { if (IsFilterMatch(obj) && !filteredData.Contains(obj)) { filteredData.Add(obj); } } /*filteredData.Clear(); * * foreach (RsbResourceID obj in currentFile.StringResources) * filteredData.Add(obj);*/ lblShown.Text = filteredData.Count.ToString(); }
public void CollectTips(StringList tipsList) { if (tipsList == null) { throw new ArgumentNullException("tipsList"); } try { try { DateTime dtNow = DateTime.Now.Date; bool firstTip = true; for (int i = 0; i < fHolidays.Holidays.Length; i++) { var holiday = fHolidays.Holidays[i]; int days = SysUtils.DaysBetween(dtNow, holiday.XDate); if (days >= 0 && 3 > days) { string tip; if (firstTip) { tipsList.Add("#" + LangMan.LS(LSID.LSID_Holidays)); firstTip = false; } if (0 == days) { tip = string.Format( LangMan.LS(LSID.LSID_HolidayToday), holiday.Name); } else if (1 == days) { tip = string.Format( LangMan.LS(LSID.LSID_HolidayTomorrow), holiday.Name); } else { tip = string.Format( LangMan.LS(LSID.LSID_DaysRemainedBeforeHoliday), holiday.Name, days); } tipsList.Add(tip); } } } finally { // temp stub, remove try/finally here? } } catch (Exception ex) { Logger.LogWrite("Holidays.CollectTips(): " + ex.Message); } }
/// <summary> /// read all lines /// </summary> /// <param name="fileName"></param> /// <returns>Lines</returns> public StringList readLine(string fileName, bool withHeader = false) { StringList elements = new StringList(); using (var reader = new StreamReader(fileName)) { int count = 0; while (!reader.EndOfStream) { var line = reader.ReadLine(); if (count == 0 && HasHeader) { CheckCorrectHeader(line); if (withHeader) { elements.Add(line); } } else { elements.Add(line); } count++; } } return(elements); }
void CONFIG(StringList list) { ConfigField thisField; var tmpStartIndex = la.charPos; Expect(6); Expect(5); list.Add(t.val); thisField = this.MainField.GetKey(string.Join("/", list.ToArray()), ConfigField.KeyMode.CreateNew); if (!thisField.IsClass) { thisField.ToClass(); } thisField.Name = t.val; if (this.Range != null && string.Concat("/", string.Join("/", list.ToArray())).Equals(KeyToFind, StringComparison.InvariantCultureIgnoreCase)) { this.Range.WholeStart = tmpStartIndex; this.Range.NameStart = t.charPos; this.Range.NameEnd = t.charPos + t.val.Length; } ; if (la.kind == 7) { Get(); Expect(5); thisField.ConfigParentName = t.val; } if (la.kind == 8) { Get(); var beginIndex = la.charPos; while (la.kind == 5 || la.kind == 6) { if (la.kind == 5) { FIELD(list); } else { CONFIG(list); } } if (this.Range != null && string.Concat("/", string.Join("/", list.ToArray())).Equals(KeyToFind, StringComparison.InvariantCultureIgnoreCase)) { this.Range.ValueStart = beginIndex; this.Range.ValueEnd = t.charPos + t.val.Length; } Expect(9); } Expect(10); if (this.Range != null && string.Concat("/", string.Join("/", list.ToArray())).Equals(KeyToFind, StringComparison.InvariantCultureIgnoreCase)) { this.Range.WholeEnd = t.charPos + t.val.Length; } KeysAdded.Add(string.Join("/", this.MainField.Key, string.Join("/", list.ToArray())).Replace("//", "/")); list.Remove(list.Last()); }
public void ActionFire(string who, string what, string atwho) { string temp = who + " launched " + what + " at " + who; _StringList.Add(temp); UpdateHistory.Raise(); // Actions.Add(temp); // OverViewHistory.GetComponent<OverviewHistoryUI>().CreateNewEntry(temp); }
private void DeleteSearched() { StringList param = new StringList(); param.Add(m_AdminForm.ToString()); param.Add(_Request.Get("updatePoint", Method.Post, "1")); TaskManager.BeginTask(MyUserID, new DeleteBlogArticleTask(), param.ToString()); }
public void Count() { _list.Add("foo"); _list.Add("bar"); Assert.AreEqual(5, _list.Count); _list.RemoveAt(4); Assert.AreEqual(4, _list.Count); }
public RelativeFolderPath GetSiblingFolderPath(string folderName) { NameHelper.EnsureValidFilenameCharacters(folderName); StringList parts = Parts.Clone(); parts.Add(".."); parts.Add(folderName); return(new RelativeFolderPath(parts)); }
public override string ParseString(string strValue) { fLines.Clear(); if (!string.IsNullOrEmpty(strValue)) { fLines.Add(strValue); } return(string.Empty); }
private void DeleteBySearch() { StringList param = new StringList(); param.Add(m_Filter.ToString()); param.Add(_Request.Get("updatePoint", Method.Post, "1")); TaskManager.BeginTask(MyUserID, new DeleteCommentTask(), param.ToString()); }
public RelativeFilePath GetSiblingFilePath(string fileNameWithExtension) { NameHelper.EnsureValidFilenameCharacters(fileNameWithExtension); StringList parts = Parts.Clone(); parts.Add(".."); parts.Add(fileNameWithExtension); return(new RelativeFilePath(parts)); }
public static StringList GetAlgorithmNames() { StringList names = new StringList(); names.Add("CyclicalImmediate"); names.Add("Immediate"); names.Add("BlinkCyclicalImmediate"); names.Add("BlinkImmediate"); return(names); }
/// <summary> /// Constructor /// </summary> public CustomViewEngine(params string[] additionalLocations) { StringList viewLocations = new StringList(); viewLocations.Add("~/Views/{1}/{0}.cshtml"); viewLocations.Add("~/Views/Shared/{0}.cshtml"); viewLocations.AddRange(additionalLocations); this.PartialViewLocationFormats = viewLocations.ToArray(); this.ViewLocationFormats = viewLocations.ToArray(); }
public bool carregarTodosArquivos(string sDiretorio, StringList listaLocal) { FileInfo dirPesquisado; string sCaminho, sSeparador; if (Rotinas.SubString(sDiretorio, sDiretorio.Length, 1). Equals(Path.DirectorySeparatorChar)) { sSeparador = ""; } else { sSeparador = Path.DirectorySeparatorChar.ToString(); } sCaminho = sDiretorio + sSeparador; dirPesquisado = new FileInfo(sCaminho); if (dirPesquisado.Directory.Exists) { sCaminho = sDiretorio + sSeparador + dirPesquisado.Name; if (Rotinas.FileExists(sCaminho)) { listaLocal.Add(sCaminho); } else if (Rotinas.DirectoryExists(sCaminho)) { if ((!dirPesquisado.Name.Equals(".")) && (!dirPesquisado.Name.Equals(".."))) { carregarTodosArquivos(sCaminho, listaLocal); } } foreach (FileInfo dirPesquisado2 in Rotinas.listFiles(dirPesquisado.FullName)) { sCaminho = sDiretorio + sSeparador + dirPesquisado2.Name; if (Rotinas.FileExists(sCaminho)) { listaLocal.Add(sCaminho); } else if (Rotinas.DirectoryExists(sCaminho)) { if ((!dirPesquisado2.Name.Equals(".")) && (!dirPesquisado2.Name.Equals(".."))) { carregarTodosArquivos(sCaminho, listaLocal); } } } } return(listaLocal.Count > 0); }
public void TestAdd() { StringList list = new StringList(); list.Add("testInsert"); Assert.AreEqual(1, list.Count); list.Add(new GenericObject("testInsert2")); Assert.AreEqual(2, list.Count); Assert.AreEqual(1, list.IndexOf("testInsert2")); }
//------------------------------------------------------------------------------ /// code + bool internal static void AddCommand(StringList commandList, int code, bool boolvalue) { if (boolvalue) { commandList.Add(String.Format("{0,5}{1,11}", code, 1)); } else { commandList.Add(String.Format("{0,5}{1,11}", code, 0)); } }
public static StringList GetAlgorithmNames() { StringList names = new StringList(); names.Add("Random"); names.Add("SmallestQueueWorkload"); names.Add("EarliestExpectedFinishTime"); names.Add("MinimumeEstimatedFlowTime"); names.Add("AlternativeRouteingsDirectedDynamically"); return(names); }
public string GetValue() { StringList list = new StringList(); list.Add(this.SortOrder.ToString()); list.Add(this.GroupName); list.Add(this.DirectoryName); list.Add(this.Disabled.ToString()); list.Add(this.Emoticons.GetValue()); return(list.ToString()); }
public void TestRemove() { StringList list = new StringList(); list.Add("test"); list.Add(new GenericObject("testInsert2")); Assert.IsTrue(list.Remove("test")); Assert.IsTrue(list.Remove(new GenericObject("testInsert2"))); Assert.IsTrue(list.Count == 0); }
public void TestContains() { StringList list = new StringList(); list.Add("test"); list.Add(new GenericObject("testInsert2")); Assert.IsTrue(list.Contains("test")); Assert.IsTrue(list.Contains("testInsert2")); Assert.IsTrue(list.Contains(new GenericObject("testInsert2"))); }
public static void Main(String[] args) { StringList ss = new StringList(); ss.Add("Cop"); ss.Add("en"); ss.Add("cabana"); ss[2] = "hagen"; ss[0] += "en" + ss[2]; Console.WriteLine("A total of {0} strings", ss.Count); String last = ss[2]; // Correct type Console.WriteLine(ss["0"] + "/" + last); // Prints: Copenhagen/hagen }
private StringList GetIpGateways(IPHelper.IP_ADDR_STRING addr) { StringList result = new StringList(); result.Add(addr.IpAddress.address); while (addr.Next != 0) { addr = (IPHelper.IP_ADDR_STRING)Marshal.PtrToStructure((IntPtr)addr.Next, typeof(IPHelper.IP_ADDR_STRING)); result.Add(addr.IpAddress.address); } return(result); }
private void DeletedSearchResult() { PostFilter filter = PostForm;//TopicFilter.GetFromFilter("filter"); StringList param = new StringList(); param.Add(filter.ToString()); param.Add(_Request.Get("updatePoint", Method.Post, "1")); if (TaskManager.BeginTask(MyUserID, new DeletePostTask(), param.ToString())) { } }
public void ReviewsTest() { P4Server pserver = null; P4User target = new P4User(pserver, "Fred"); StringList expected = new StringList(); expected.Add("//depot/poetry"); expected.Add("//depot/movies"); StringList actual; target.Reviews = expected; actual = target.Reviews; Assert.AreEqual(expected, actual); }
public void AltRootsTest() { P4Server pserver = null; P4Workspace target = new P4Workspace(pserver, "Fred"); StringList expected = new StringList(); expected.Add("Pooh Bear"); expected.Add("Smokey Bear"); StringList actual; target.AltRoots = expected; actual = target.AltRoots; Assert.AreEqual(expected, actual); }
public override IList<string> GetFirsts() { var firsts = new StringList(); foreach (var t in LineTerminators) firsts.Add(t.ToString()); return firsts; }
public string GetValue() { StringTable table = new StringTable(); //table.Add("LimitType", LimitType.ToString()); table.Add("LimitType", ((byte)LimitType).ToString()); foreach (KeyValuePair<Guid, List<Guid>> item in ExcludeRoles) { if (item.Value != null) { StringList roles = new StringList(); foreach (Guid roleID in item.Value) { roles.Add(roleID.ToString()); } table.Add("ExcludeRoles-" + item.Key.ToString("N"), roles.ToString()); } } return table.ToString(); }
public static EntityMemberMask Create(EntityInfo entity, string propertiesOrGroups) { var invalidNames = new StringList(); var mask = new EntityMemberMask(propertiesOrGroups, entity); var props = propertiesOrGroups.SplitNames(',', ';'); foreach (var name in props) { //first try member if (string.IsNullOrWhiteSpace(name)) continue; var grp = entity.GetPropertyGroup(name); if (grp != null) { foreach (var m in grp.Members) mask.Set(m); continue; } var member = entity.GetMember(name); if (member != null) { mask.Set(member); continue; } //name is invalid invalidNames.Add(name); } if (invalidNames.Count > 0) Util.Throw("Properties/subgroups [{0}] not found in entity {1}.", string.Join(",", invalidNames), entity.EntityType); return mask; }
public static string FormatSqlParameters(ICollection prms, string format = "{0}={1}", string delimiter = ", ", int maxValueLen = 50) { var sValues = new StringList(); foreach (IDbDataParameter prm in prms) sValues.Add(FormatSqlParameter(prm, format, maxValueLen)); var result = string.Join(delimiter, sValues); return result; }
public override void Compute() { StringList list = new StringList(); foreach (string theString in DevelopmentKit.IO.Generics.ImportStrings(_config.FileName.Absolute)) { list.Add(theString); } Workspace.Store("ListOfStrings", list); }
internal void Run(StringList values) { if (string.IsNullOrEmpty(Command)) { return; } List<Item> items = new List<Item>(); StringList othervalues = new StringList(); foreach (var val in values) { ItemUri uri = ItemUri.Parse(val); if (uri != null) { items.Add(Sitecore.Data.Database.GetItem(uri)); } else { othervalues.Add(val); } } Command command = CommandManager.GetCommand(Command); Debug.Assert(command != null, Command + " not found."); // If our command can hanlde more than one item in the context we run it once if (!SingleItemContext) { CommandContext cc = new CommandContext(items.ToArray()); cc.CustomData = othervalues; command.Execute(cc); } //otherwise we have to generate as many commands as items else { if (items.Count > 0) { foreach (var item in items) { CommandContext cc = new CommandContext(item); command.Execute(cc); } } if (othervalues.Count > 0) { foreach (var othervalue in othervalues) { CommandContext cc = new CommandContext(); cc.CustomData = othervalue; command.Execute(cc); } } } }
public void ToStringTest() { StringList target = new StringList(); // empty list string expected = string.Empty; string actual = target.ToString(); Assert.AreEqual(expected, actual); // 1 item in list target.Add("test1"); expected = "test1"; actual = target.ToString(); Assert.AreEqual(expected, actual); // 2 items in list target.Add("test2"); expected = "test1,test2"; actual = target.ToString(); Assert.AreEqual(expected, actual); }
public override IList<string> GetFirsts() { StringList result = new StringList(); result.AddRange(base.Prefixes); //we assume that prefix is always optional, so number can always start with plain digit result.AddRange(new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }); // Python float numbers can start with a dot if (IsSet(TermOptions.NumberAllowStartEndDot)) result.Add(DecimalSeparator.ToString()); return result; }
public void SetBannedSpiders(IEnumerable<string> spiderNames) { StringList bannedNames = new StringList(); if (spiderNames != null) { foreach (string spiderName in spiderNames) { bannedNames.Add(spiderName); } } m_BannedNames = bannedNames; m_BannedSpiders = null; }
// public override DbCommandInfo BuildSqlInsertCommand(EntityCommand entityCommand) { const string SqlInsertTemplate = @" INSERT INTO {0} ({1}) VALUES ({2}); {3} "; bool useStoredProc = this.DbModel.Config.Options.IsSet(DbOptions.UseStoredProcs); var table = DbModel.LookupDbObject<DbTableInfo>(entityCommand.TargetEntityInfo, throwNotFound: true); var idClause = string.Empty; var listColumns = new List<DbColumnInfo>(); var listValues = new StringList(); var cmdName = ModelConfig.NamingPolicy.ConstructDbCommandName(entityCommand, table.TableName, "Insert"); var dbCmdInfo = CreateDbCommandInfo(entityCommand, cmdName, table, DbExecutionType.NonQuery, null); foreach (var prm in dbCmdInfo.Parameters) { var col = prm.SourceColumn; if (!col.Flags.IsSet(DbColumnFlags.NoInsert)) { listColumns.Add(col); listValues.Add(prm.Name); } // identity if (col.Flags.IsSet(DbColumnFlags.Identity)) { if (useStoredProc) //append to stored proc idClause = string.Format("SET {0} = LAST_INSERT_ID();", prm.Name); else dbCmdInfo.PostUpdateActions.Add((conn, cmd, rec) => { var idCmd = conn.DbConnection.CreateCommand(); idCmd.CommandText = "Select LAST_INSERT_ID();"; idCmd.Transaction = conn.DbTransaction; var id = conn.Database.ExecuteDbCommand(idCmd, conn, DbExecutionType.Scalar); //it is decimal var intId = Convert.ChangeType(id, prm.SourceColumn.Member.DataType); rec.SetValueDirect(prm.SourceColumn.Member, intId); }); }//if identity } // this.ModelConfig.Options.IsSet(DbOptions.us) //build SQL var strColumns = listColumns.GetSqlNameList(); var strValues = string.Join(", ", listValues); dbCmdInfo.Sql = string.Format(SqlInsertTemplate, table.FullName, strColumns, strValues, idClause); return dbCmdInfo; }
// For cached queries, local values are passed in closure object. The problem is that a single closure is created for a method, // and a query might use only some of closure values. So for each field in closure we check that it is actually used in the query we report. private static string FormatClosureValues(string fromExpression, string paramName, object obj) { if (obj == null) return paramName + "=null"; var type = obj.GetType(); if (!type.IsAnonymousType()) return paramName + "=" + LoggingExtensions.ToLogString(obj); //Anonymous type var fields = type.GetFields(); var strValues = new StringList(); for (int i = 0; i < fields.Length; i++ ) { var fld = fields[i]; var fullRefName = paramName + "." + fld.Name; if (fromExpression.Contains(fullRefName)) strValues.Add(fullRefName + "=" + LoggingExtensions.ToLogString(fld.GetValue(obj))); } return string.Join(", ", strValues); }
public override string ToString() { var list = new StringList(); foreach (var entry in entries) list.Add(entry.ToString()); return string.Join(" ", list.ToArray()); }
private StringList GetCurrentExpectedSymbols() { BnfTermList inputElements = new BnfTermList(); StringSet inputKeys = new StringSet(); inputKeys.AddRange(_currentState.Actions.Keys); //First check all NonTerminals foreach (NonTerminal nt in Data.NonTerminals) { if (!inputKeys.Contains(nt.Key)) continue; //nt is one of our available inputs; check if it has an alias. If not, don't add it to element list; // and we have already all its "Firsts" keys in the list. // If yes, add nt to element list and remove // all its "fists" symbols from the list. These removed symbols will be represented by single nt alias. if (string.IsNullOrEmpty(nt.DisplayName)) inputKeys.Remove(nt.Key); else { inputElements.Add(nt); foreach(string first in nt.Firsts) inputKeys.Remove(first); } } //Now terminals foreach (Terminal term in Data.Terminals) { if (inputKeys.Contains(term.Key)) inputElements.Add(term); } StringList result = new StringList(); foreach(BnfTerm term in inputElements) result.Add(string.IsNullOrEmpty(term.DisplayName)? term.Name : term.DisplayName); result.Sort(); return result; }
private void SaveValidateRole() { MessageDisplay msgDisplay = CreateMessageDisplay(); string actiontype = _Request.Get("actiontype", Method.Get, string.Empty); string roleIDString = _Request.Get("validateCodeRole", Method.Post, string.Empty); if (roleIDString.Length == 0) return; bool isInvalidActionType = true; foreach (ValidateCodeAction action in ValidateCodeManager.GetAllValidateCodeActions()) { if (string.Compare(action.Type, actiontype, true) == 0) { if (action.CanSetExceptRoleId == false) { msgDisplay.AddError(string.Format(Lang_Error.ValidateCode_ValidateCodeActionCannotSetExceptRoleID, action.Name)); return; } isInvalidActionType = false; break; } } if (isInvalidActionType == true) { msgDisplay.AddError(new InvalidParamError("actiontype").Message); } StringList exceptRoleIDs = new StringList(); foreach (string roleID in roleIDString.Split(',')) { exceptRoleIDs.Add(roleID); } ValidateCodeCollection tempValidateCodes = new ValidateCodeCollection(); bool hasAdd = false; foreach (ValidateCode validateCode in AllSettings.Current.ValidateCodeSettings.ValidateCodes) { if (string.Compare(validateCode.ActionType, actiontype, true) == 0) { ValidateCode tempValidateCode = (ValidateCode)validateCode.Clone(); tempValidateCode.ExceptRoleIds = exceptRoleIDs; tempValidateCodes.Add(tempValidateCode); hasAdd = true; } else { tempValidateCodes.Add(validateCode); } } if (hasAdd == false) { ValidateCode validateCode = new ValidateCode(); validateCode.ExceptRoleIds = exceptRoleIDs; validateCode.ActionType = actiontype; tempValidateCodes.Add(validateCode); } try { using (new ErrorScope()) { ValidateCodeSettings setting = (ValidateCodeSettings)AllSettings.Current.ValidateCodeSettings.Clone(); setting.ValidateCodes = tempValidateCodes; bool success = SettingManager.SaveSettings(setting); if (!success) { CatchError<ErrorInfo>(delegate(ErrorInfo error) { msgDisplay.AddError(error); }); } else { Return(true); } } } catch (Exception ex) { msgDisplay.AddError(ex.Message); } }
internal void Run(StringList values) { if (string.IsNullOrEmpty(Command)) { return; } List<Item> items = new List<Item>(); StringList othervalues = new StringList(); foreach (var val in values) { ItemUri uri = ItemUri.Parse(val); if (uri != null) { items.Add(Sitecore.Data.Database.GetItem(uri)); } else { othervalues.Add(val); } } Command command = CommandManager.GetCommand(Command) ?? (Command)ReflectionUtil.CreateObject(Command); Debug.Assert(command != null, Command + " not found."); //pass parameters var indexSt = Command.IndexOf('(')+1; if (indexSt > 0) { var length = Command.IndexOf(')') - indexSt; if(length > 0) { ReflectionUtil.SetProperties(command, Command.Substring(indexSt, length)); } } // If our command can hanlde more than one item in the context we run it once if (!SingleItemContext) { CommandContext cc = new CommandContext(items.ToArray()); cc.CustomData = othervalues; command.Execute(cc); } //otherwise we have to generate as many commands as items else { if (items.Count > 0) { foreach (var item in items) { CommandContext cc = new CommandContext(item); command.Execute(cc); } } if (othervalues.Count > 0) { foreach (var othervalue in othervalues) { CommandContext cc = new CommandContext(); cc.CustomData = othervalue; command.Execute(cc); } } } }
private void DeleteBySearch() { StringList param = new StringList(); param.Add(m_Filter.ToString()); param.Add(_Request.Get("updatePoint", Method.Post, "1")); TaskManager.BeginTask(MyUserID, new DeleteCommentTask(), param.ToString()); }
public void SerializeTest() { StringList target = new StringList(); MemoryStream stream = new MemoryStream(); IBinaryWriter writer = new XmlWriterMock(new StreamAdapter(stream)); // empty list target.Serialize(writer); string expected = "<string></string>"; string actual = Encoding.UTF8.GetString(stream.ToArray()); Assert.AreEqual(expected, actual); // 1 item in list target.Add("A"); stream.Position = 0; target.Serialize(writer); expected = "<string>A</string>"; actual = Encoding.UTF8.GetString(stream.ToArray()); Assert.AreEqual(expected, actual); // 2 items in list target.Add("B"); stream.Position = 0; target.Serialize(writer); expected = "<string>A,B</string>"; actual = Encoding.UTF8.GetString(stream.ToArray()); Assert.AreEqual(expected, actual); }
// public override DbCommandInfo BuildSqlInsertCommand(EntityCommand entityCommand) { const string SqlInsertTemplate = @" INSERT INTO {0} ({1}) VALUES ({2}); {3} {4} "; const string SqlGetIdentityTemplate = "\r\nSET {0} = SCOPE_IDENTITY();"; const string SqlGetRowVersionTemplate = "\r\nSET {0} = @@DBTS;"; var table = DbModel.LookupDbObject<DbTableInfo>(entityCommand.TargetEntityInfo, throwNotFound: true); var idClause = string.Empty; var rvClause = string.Empty; var listColumns = new List<DbColumnInfo>(); var listValues = new StringList(); var cmdName = ModelConfig.NamingPolicy.ConstructDbCommandName(entityCommand, table.TableName, "Insert"); var dbCmdInfo = CreateDbCommandInfo(entityCommand, cmdName, table, DbExecutionType.NonQuery, null); foreach (var prm in dbCmdInfo.Parameters) { var col = prm.SourceColumn; if (col.Flags.IsSet(DbColumnFlags.Identity)) idClause = string.Format(SqlGetIdentityTemplate, prm.Name); if (col.Member.Flags.IsSet(EntityMemberFlags.RowVersion)) rvClause = string.Format(SqlGetRowVersionTemplate, prm.Name); if (!col.Flags.IsSet(DbColumnFlags.NoInsert)) { listColumns.Add(col); listValues.Add(prm.Name); } } //build SQL var strColumns = listColumns.GetSqlNameList(); var strValues = string.Join(", ", listValues); dbCmdInfo.Sql = string.Format(SqlInsertTemplate, table.FullName, strColumns, strValues, idClause, rvClause); return dbCmdInfo; }
private void DeleteSearch() { StringList param = new StringList(); param.Add(m_AdminForm.ToString()); param.Add(_Request.Get("updatePoint", Method.Post, "1")); param.Add(_Request.Get("deleteArticle", Method.Post, "1")); TaskManager.BeginTask(MyUserID, new DeleteBlogCategoryTask(), param.ToString()); }
private static void CloneTestSpecs(string rootBranch, string targetBranch, IDictionary<string, object> parameters) { if (parameters.ContainsKey(TestSpecs) && parameters[TestSpecs] != null) { var testSpecList = parameters[TestSpecs] as TestSpecList; if (testSpecList == null) { return; } foreach (var spec in testSpecList) { var assemblySpec = spec as TestAssemblySpec; if (assemblySpec != null) { if (!string.IsNullOrEmpty(assemblySpec.TestSettingsFileName) && assemblySpec.TestSettingsFileName.StartsWith(rootBranch, StringComparison.OrdinalIgnoreCase)) { assemblySpec.TestSettingsFileName = assemblySpec.TestSettingsFileName.Replace(rootBranch, targetBranch); } } var metadataFileSpec = spec as TestMetadataFileSpec; if (metadataFileSpec != null) { var modifiedTestLists = new StringList(); foreach (var list in metadataFileSpec.TestLists) { string modifiedTestList = list; if (modifiedTestList.StartsWith(rootBranch, StringComparison.OrdinalIgnoreCase)) { modifiedTestList = modifiedTestList.Replace(rootBranch, targetBranch); } modifiedTestLists.Add(modifiedTestList); } if (!string.IsNullOrEmpty(metadataFileSpec.MetadataFileName) && metadataFileSpec.MetadataFileName.StartsWith(rootBranch, StringComparison.OrdinalIgnoreCase)) { metadataFileSpec.MetadataFileName = metadataFileSpec.MetadataFileName.Replace(rootBranch, targetBranch); } } } } }
/// <summary> /// Updates Strains /// </summary> /// <param name="strains">StrainList Object</param> /// <returns></returns> public virtual StringList UpdateStrains(StrainList strains) { string source_id = GetSourceID(); StrainMgr mgr = StrainMgr.Instance; if (strains == null) { StrainSearch search = StrainSearch.New(); search.HasPhenotypeData = true; strains = mgr.GetStrains(search, SecurityContext.New()); } StringList output = new StringList(); foreach (Strain strain in strains) { string result; if (mgr.StrainHasPublications(strain.ID)) { PublicationSearch pub_search = PublicationSearch.New(); pub_search.StrainID = strain.ID; PublicationList pubs = PublicationMgr.Instance.GetPublications(pub_search, SecurityContext.New()); foreach (Publication pub in pubs) { string pubmedid = pub.ExternalReference.ExternalID; result = UpdateResource(ObjectToResource(source_id, strain.HtmlName, strain.ID.ToString(), strain.StrainDescription, GetUrl("Strain") + strain.ID.ToString(), "mouse", "Mouse Strain", strain.History.CreationDate, GetGeneIDsFromStrain(strain.ID), null, pubmedid)); output.Add(result); } } else { result = UpdateResource(ObjectToResource(source_id, strain.HtmlName, strain.ID.ToString(), strain.StrainDescription, GetUrl("Strain") + strain.ID.ToString(), "mouse", "Mouse Strain", strain.History.CreationDate, GetGeneIDsFromStrain(strain.ID), null, null)); output.Add(result); } } return output; }
/// <summary> /// Get ResourceTypes /// </summary> /// <returns>StringList object</returns> public virtual StringList GetResourceTypesAsStringList() { try { if (webservice == null) return new StringList(); int typesCount = webservice.getResourceTypes().Length; dkCOIN.typeResourceType[] resourceTypes = new dkCOIN.typeResourceType[typesCount]; resourceTypes = webservice.getResourceTypes(); StringList resourceTypeList = new StringList(); for (int i = 0; i < typesCount; i++) { string resourceType = ""; resourceType = resourceTypes[i].name; resourceTypeList.Add(resourceType); } return resourceTypeList; } catch (Exception e) { EmailErrorNotification(e.Message, "Attempting to execute StringList GetResourceTypes()"); return null; } }
public StringList HistoryListAdd(string str, StringList stl, int MaxInt) { string str2 = str; if (str2.IndexOf(" ") > -1) { str2 = str2.Remove(str2.IndexOf(" ")); } for (int i = 0; i < stl.Count; i++) { string str3 = stl[i]; if (str3.IndexOf(" ") > -1) { str3 = str3.Remove(str3.IndexOf(" ")); } if (str3 == str2) { stl.RemoveAt(i); break; } } if (stl.Count >= MaxInt) { stl.RemoveAt(0); } stl.Add(str); return stl; }
protected virtual string BuildWhereClause(List<DbParamInfo> keyParameters, string tableAlias = null) { string colPrefix = string.IsNullOrEmpty(tableAlias) ? string.Empty : tableAlias + "."; var whereExprs = new StringList(); foreach (var prm in keyParameters) whereExprs.Add(colPrefix + "\"" + prm.SourceColumn.ColumnName + "\"" + " = " + prm.Name); return string.Join(" AND ", whereExprs); }
public override string ToString() { if (!string.IsNullOrWhiteSpace(Key)) return Key; var memberNames = new StringList(); foreach (var member in Entity.Members) if (Bits[member.ValueIndex]) memberNames.Add(member.MemberName); return Entity.Name + ":" + string.Join(",", memberNames); }
public WhartonEWSResponse GetCalendarItemsDetailed( String apiKey, String emlUserAddress, String dtRangeBegin, String dtRangeEnd ) { WhartonEWSResponse rsp = new WhartonEWSResponse(); Boolean success = true; String miscData = ""; try { // Initialize EWS service. ExchangeService service = getService(emlUserAddress, apiKey); FindItemsResults<Appointment> myAppointments = getCalItemsBase(apiKey, emlUserAddress, dtRangeBegin, dtRangeEnd); // Create a DataTable. DataTable table = new DataTable("Appointments"); #region table column definitions DataColumn dcSubject = new DataColumn(); dcSubject.DataType = System.Type.GetType("System.String"); dcSubject.AllowDBNull = true; dcSubject.Caption = "Subject"; dcSubject.ColumnName = "Subject"; dcSubject.DefaultValue = ""; // Add the column to the table. table.Columns.Add(dcSubject); DataColumn dcLocation = new DataColumn(); dcLocation.DataType = System.Type.GetType("System.String"); dcLocation.AllowDBNull = true; dcLocation.Caption = "Location"; dcLocation.ColumnName = "Location"; dcLocation.DefaultValue = ""; // Add the column to the table. table.Columns.Add(dcLocation); DataColumn dcLink = new DataColumn(); dcLink.DataType = System.Type.GetType("System.String"); dcLink.AllowDBNull = true; dcLink.Caption = "Link"; dcLink.ColumnName = "Link"; dcLink.DefaultValue = ""; // Add the column to the table. table.Columns.Add(dcLink); DataColumn dcStart = new DataColumn(); dcStart.DataType = System.Type.GetType("System.DateTime"); dcStart.AllowDBNull = true; dcStart.Caption = "Start"; dcStart.ColumnName = "Start"; // Add the column to the table. table.Columns.Add(dcStart); DataColumn dcEnd = new DataColumn(); dcEnd.DataType = System.Type.GetType("System.DateTime"); dcEnd.AllowDBNull = true; dcEnd.Caption = "End"; dcEnd.ColumnName = "End"; // Add the column to the table. table.Columns.Add(dcEnd); DataColumn dcAllDay = new DataColumn(); dcAllDay.DataType = System.Type.GetType("System.String"); dcAllDay.AllowDBNull = true; dcAllDay.Caption = "AllDay"; dcAllDay.ColumnName = "AllDay"; dcAllDay.DefaultValue = ""; // Add the column to the table. table.Columns.Add(dcAllDay); DataColumn dcBody = new DataColumn(); dcBody.DataType = System.Type.GetType("System.String"); dcBody.AllowDBNull = true; dcBody.Caption = "Body"; dcBody.ColumnName = "Body"; dcBody.DefaultValue = ""; // Add the column to the table. table.Columns.Add(dcBody); DataColumn dcCategories = new DataColumn(); dcCategories.DataType = System.Type.GetType("System.String"); dcCategories.AllowDBNull = true; dcCategories.Caption = "Categories"; dcCategories.ColumnName = "Categories"; dcCategories.DefaultValue = ""; // Add the column to the table. table.Columns.Add(dcCategories); DataColumn dcReqAttendees = new DataColumn(); dcReqAttendees.DataType = System.Type.GetType("System.String"); dcReqAttendees.AllowDBNull = true; dcReqAttendees.Caption = "ReqAttendees"; dcReqAttendees.ColumnName = "ReqAttendees"; dcReqAttendees.DefaultValue = ""; // Add the column to the table. table.Columns.Add(dcReqAttendees); DataColumn dcOptAttendees = new DataColumn(); dcOptAttendees.DataType = System.Type.GetType("System.String"); dcOptAttendees.AllowDBNull = true; dcOptAttendees.Caption = "OptAttendees"; dcOptAttendees.ColumnName = "OptAttendees"; dcOptAttendees.DefaultValue = ""; // Add the column to the table. table.Columns.Add(dcOptAttendees); DataColumn dcId = new DataColumn(); dcId.DataType = System.Type.GetType("System.String"); dcId.AllowDBNull = true; dcId.Caption = "Id"; dcId.ColumnName = "Id"; dcId.DefaultValue = ""; // Add the column to the table. table.Columns.Add(dcId); #endregion // Add rows and set values. DataRow row; //load properties List<Item> items = new List<Item>(); if (myAppointments.Items.Count > 0) { foreach (Appointment a in myAppointments) { items.Add(a); } } service.LoadPropertiesForItems(items, PropertySet.FirstClassProperties); ////Write out the subject of each appointment I have this week foreach (Appointment appointment in myAppointments) { string openItemUrl = ItemUrlProtocol + service.Url.Host + ItemUrlFolder + appointment.WebClientReadFormQueryString; row = table.NewRow(); row["Subject"] = cleanHighAsciiForXML(appointment.Subject); row["Location"] = cleanHighAsciiForXML(appointment.Location); row["Start"] = appointment.Start; row["End"] = appointment.End; row["Body"] = appointment.Body.Text; row["Categories"] = appointment.Categories; row["Id"] = appointment.Id; //required attendees AttendeeCollection req = appointment.RequiredAttendees; StringList tmp = new StringList(); foreach (Attendee att in req) { tmp.Add(att.Address); } row["ReqAttendees"] = tmp.ToString(); //optional attendees AttendeeCollection opt = appointment.OptionalAttendees; tmp = new StringList(); foreach (Attendee att in opt) { tmp.Add(att.Address); } row["OptAttendees"] = tmp.ToString(); try { row["AllDay"] = appointment.IsAllDayEvent.ToString(); } catch (Exception e) { row["AllDay"] = false; //default to false } row["Link"] = openItemUrl; // Be sure to add the new row to the // DataRowCollection. table.Rows.Add(row); } rsp.TableData = table; } catch (Exception e) { if (!(int.TryParse(e.Message, out rsp.StatusCode))) { //if the parsing fails, then set a default value of 500 rsp.StatusCode = 500; } rsp.Msg = e.Message; success = false; miscData = "{ \"ErrMsg\":\"" + rsp.Msg + "\" }"; rsp.StackTrace = e.StackTrace; if (e.InnerException != null) { rsp.InnerException = e.InnerException.ToString(); } } //audit addAuditLog(apiKey, emlUserAddress, "GetCalendarItems", success, miscData); return rsp; }
public virtual DbCommandInfo BuildSqlInsertCommand(EntityCommand entityCommand) { const string SqlInsertTemplate = "INSERT INTO {0} \r\n ({1}) \r\n VALUES \r\n ({2});"; var table = DbModel.LookupDbObject<DbTableInfo>(entityCommand.TargetEntityInfo, throwNotFound: true); var idClause = string.Empty; var listColumns = new List<DbColumnInfo>(); var listValues = new StringList(); var cmdName = ModelConfig.NamingPolicy.ConstructDbCommandName(entityCommand, table.TableName, "Insert"); var dbCmdInfo = CreateDbCommandInfo(entityCommand, cmdName, table, DbExecutionType.NonQuery, null); foreach (var prm in dbCmdInfo.Parameters) { var col = prm.SourceColumn; if (!col.Flags.IsSet(DbColumnFlags.NoInsert)) { listColumns.Add(col); listValues.Add(prm.Name); } } //build SQL var strColumns = listColumns.GetSqlNameList(); var strValues = string.Join(", ", listValues); dbCmdInfo.Sql = string.Format(SqlInsertTemplate, table.FullName, strColumns, strValues) + idClause; return dbCmdInfo; }
/// <summary> /// 上传文件 /// </summary> /// <param name="userID"></param> /// <param name="uploadActionName"></param> /// <param name="filename"></param> /// <param name="searchInfo"></param> /// <param name="customParams"></param> /// <returns></returns> public static TempUploadFile Upload(int userID, string uploadActionName, string filename, string searchInfo, NameValueCollection queryString, ref object customResult, params string[] customParams) { if (userID <= 0) return null; if (searchInfo == null) searchInfo = string.Empty; FileActionBase uploadAction; if (s_UploadActions.TryGetValue(uploadActionName, out uploadAction) == false) return null; uploadAction = uploadAction.CreateInstance(); HttpContext context = HttpContext.Current; TempUploadFile uploadedFile; string tempFileDirectory = Globals.GetPath(SystemDirecotry.Temp_Upload); string tempFilename = string.Concat(DateTimeUtil.Now.ToString("yyyy_MM_dd_"), Guid.NewGuid().ToString("N"), Consts.FileSystem_TempFileExtendName); string tempFilePath = IOUtil.JoinPath(tempFileDirectory, tempFilename); if (!Directory.Exists(tempFileDirectory)) Directory.CreateDirectory(tempFileDirectory); if (uploadAction.BeforeUpload(context, filename, tempFilePath, queryString, ref customResult) == false) return null; string md5; long fileSize; //if (1 == 1) //{ //if (context.Request.Files.Count > 0) //{ //HttpPostedFile postedFile = context.Request.Files[0]; //if (string.IsNullOrEmpty(filename)) // filename = postedFile.FileName; //fileSize = postedFile.ContentLength; //md5 = IOUtil.GetFileMD5Code(postedFile.InputStream); //postedFile.SaveAs(tempFilePath); FileManagerUploadPolicy uploadPolicy = new FileManagerUploadPolicy(tempFilePath); try { using (FileUploader uploader = new FileUploader(uploadPolicy)) { uploader.BeginUpload(); } } catch(System.Security.SecurityException)// ex) { using (Stream stream = uploadPolicy.CreateFileStream(context.Request.Files[0].FileName)) { byte[] buffer = new byte[10240]; int readed = 0; while (readed != buffer.Length) { int l = context.Request.Files[0].InputStream.Read(buffer, readed, buffer.Length); stream.Write(buffer, 0, l); readed += l; } } } if (string.IsNullOrEmpty(filename)) filename = context.Request.Form["filename"]; if (string.IsNullOrEmpty(filename)) filename = uploadPolicy.UploadFileName; fileSize = uploadPolicy.UploadFileSize; md5 = uploadPolicy.UploadFileMD5; if (uploadAction.Uploading(context, filename, tempFilePath, fileSize, fileSize, ref customResult) == false) return null; StringList customParamList = new StringList(); if (customParams != null) { foreach (string customParam in customParams) customParamList.Add(customParam); } uploadedFile = new TempUploadFile(filename, tempFilePath, fileSize, md5); uploadedFile.TempUploadFileID = FileDao.Instance.CreateTempUploadFile(userID, uploadActionName, searchInfo, customParamList, filename, tempFilename, md5, fileSize, uploadedFile.FileID); //} //else // return null; //} //else //{ // //Uploader uploader = new Uploader(); // //uploader.IsSwfUploader = true; // //if (uploader.BeginUpload(tempFilePath, new Uploader.UploadOnProcess(delegate // //{ // // if (uploadAction.Uploading(filename, tempFilePath, uploader.FileSize, uploader.TotalReceived) == false) // // return false; // // return true; // //}))) // //{ // // fileSize = uploader.TotalFileReceived; // // md5 = uploader.MD5Code; // // uploadedFile = uploader; // //} // //else // // return null; //} if (uploadAction.AfterUpload(context, filename, tempFilePath, fileSize, uploadedFile.TempUploadFileID, md5, queryString, ref customResult) == false) return null; return uploadedFile; }
public virtual DbCommandInfo BuildSqlUpdateCommand(EntityCommand entityCommand) { const string SqlUpdateTemplate = @"UPDATE {0} SET {1} WHERE {2};"; var table = DbModel.LookupDbObject<DbTableInfo>(entityCommand.TargetEntityInfo, throwNotFound: true); if (entityCommand == null) return null; var cmdName = ModelConfig.NamingPolicy.ConstructDbCommandName(entityCommand, table.TableName, "Update"); var cmdInfo = CreateDbCommandInfo(entityCommand, cmdName, table, DbExecutionType.NonQuery, null); var pkParams = cmdInfo.Parameters.Where(p => p.SourceColumn.Flags.IsSet(DbColumnFlags.PrimaryKey)); // find members to update. For partial update, with explicitly specified members to update, we ignore NoUpdate flag var excludeFlags = DbColumnFlags.PrimaryKey; if (entityCommand.Kind == EntityCommandKind.Update) excludeFlags |= DbColumnFlags.NoUpdate; var updateParams = cmdInfo.Parameters.Where(p => !p.SourceColumn.Flags.IsSet(excludeFlags)); // Some tables (like many-to-many link entities) might have no columns to update if (!updateParams.Any()) return null; //Build Where expression var whereExpr = BuildWhereClause(pkParams.ToList()); //Build Update clause var qt = "\""; var updList = new StringList(); foreach (var prm in updateParams) updList.Add(qt + prm.SourceColumn.ColumnName + qt + " = " + prm.Name); var strUpdates = string.Join(", ", updList); //Build SQL cmdInfo.Sql = string.Format(SqlUpdateTemplate, table.FullName, strUpdates, whereExpr); return cmdInfo; }