public void Check(object sender, EventArgs e) { Lists l = new Lists(); CalculateLists(l); View.ShowDiff(true, l, Model.DiffModel); }
public static void ExecuteLists() { Lists newList = new Lists(); newList.AddNumber(1); newList.AddNumber(2); newList.AddNumber(3); newList.AddNumber(4); newList.PrintList(); }
public Trello(string key) { _restClient = new TrelloRestClient(key); Members = new Members(_restClient); Boards = new Boards(_restClient); Lists = new Lists(_restClient); Cards = new Cards(_restClient); Checklists = new Checklists(_restClient); Organizations = new Organizations(_restClient); }
public Trello(string key) { _restClient = new TrelloRestClient(key); Members = new Members(_restClient); Boards = new Boards(_restClient); Lists = new Lists(_restClient); Cards = new Cards(_restClient); Checklists = new Checklists(_restClient); Organizations = new Organizations(_restClient); Notifications = new Notifications(_restClient); Tokens = new Tokens(_restClient); Async = new AsyncTrello(_restClient); }
//INFO: dreistetraitor/programm.exe //INFO: dreistetraitor/serverdata/garrysmod/addons public void SyncLocalServer(object sender, EventArgs e) { Lists l = new Lists(); CalculateLists(l); WebClient client = CreateServerWebClient(); foreach(FTP_FAF missingLocalFaF in l.MissingLocalFAFs) { if(missingLocalFaF.File) { FtpWebRequest ftp = CreateServerWebRequest(missingLocalFaF.RelativePath); View.AddInfo("Deleting file from ftp: " + ftp.RequestUri); Debug.WriteLine("Deleting file from ftp: " + ftp.RequestUri); ftp.Method = WebRequestMethods.Ftp.DeleteFile; ftp.GetResponse().Close(); } } foreach(FTP_FAF missingLocalFaF in l.MissingLocalFAFs) { if(!missingLocalFaF.File) { FtpWebRequest ftp = CreateServerWebRequest(missingLocalFaF.RelativePath); View.AddInfo("Deleting folder from ftp: "+ftp.RequestUri); Debug.WriteLine("Deleting folder from ftp: "+ftp.RequestUri); ftp.Method = WebRequestMethods.Ftp.RemoveDirectory; ftp.GetResponse().Close(); //try { } catch(WebException ex) { View.AddWarningInfo("Could not delete folder from ftp: "+ex.InnerException.); } } } foreach(FAF missingRemoteFaF in l.MissingRemoteFAFs) { if(!missingRemoteFaF.File) { string newFolder = GMOD_ROOT + missingRemoteFaF.Name; FtpWebRequest ftp = CreateServerWebRequest(missingRemoteFaF.Name+"/"); View.AddInfo("Creating missing directory: "+newFolder+" @"+ftp.RequestUri); ftp.Method = WebRequestMethods.Ftp.MakeDirectory; ftp.GetResponse().Close(); } } foreach(FAF missingRemoteFaF in l.MissingRemoteFAFs) { if(missingRemoteFaF.File) { String newFile = GMOD_ROOT + missingRemoteFaF.Name; View.AddInfo("Uploading file: \"" + newFile + "\" and saving in location \"" + GetServerURI(missingRemoteFaF.Name) + "\""); client.UploadFile(GetServerURI(missingRemoteFaF.Name), newFile); //TODO: Implement async upload // Progress bar } } client.Dispose(); View.AddInfo("Finished syncing!"); }
public MacysDL(string spSiteURL, string listName, NetworkCredential credential, ColumnDefinition columnDefinition) { _listsSvc = new Lists { Url = spSiteURL + "/_vti_bin/lists.asmx", Credentials = credential, AllowAutoRedirect = true }; _listName = listName; _columnDefinition = columnDefinition; if (String.IsNullOrEmpty(_columnDefinition.JobCodeColumnType)) _columnDefinition.JobCodeColumnType = "Text"; if (String.IsNullOrEmpty(_columnDefinition.LocationColumnType)) _columnDefinition.LocationColumnType = "Text"; if (String.IsNullOrEmpty(_columnDefinition.TopicColumnType)) _columnDefinition.TopicColumnType = "Text"; if (String.IsNullOrEmpty(_columnDefinition.SubTopicColumnType)) _columnDefinition.SubTopicColumnType = "Text"; }
public ActionResult Edit(ListViewModel model) { string timeToday = DateTime.Now.ToString("h:mm:ss tt"); string dateToday = DateTime.Now.ToString("M/dd/yyyy"); string text_details = Request.Form["text_details"]; string check_public = Request.Form["check_public"]; if (ModelState.IsValid) { using (var dbContext = new MvcDbContext()) { Lists list = dbContext.Lists.Find(model.Id); list.Time_Edited = timeToday; list.Date_Edited = dateToday; list.Details = text_details; list.Public = check_public != null ? "YES" : "NO"; dbContext.Entry(list).State = EntityState.Modified; dbContext.SaveChanges(); return(RedirectToAction("Index")); } } return(View(model)); }
//test if an item is selected, if it is it will ask you if want to delete the item. if not it will put out an error message //created by will fritz 2/9/15 private void btnRemoveFromLists_Click(object sender, RoutedEventArgs e) { if (lvList.SelectedItems[0] == null) { lblError.Content = "You Must First Select An Item From the List, Before You Can Remove It"; } else { if (DialogBox.ShowMessageDialog(this, "Do you want to delete this item?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { try { Lists listsToDelete = (Lists)lvList.SelectedItems[0]; _prodMan.ArchiveLists(listsToDelete); FillList(); } catch (Exception) { lblError.Content = "There was an Error deleting the Lists item"; } } } }
public void IntegrationExample() { var sut = new StatisticsPrinter(); sut.StartZip("a.zip", 1, 2); sut.FoundUserKey("auser"); sut.FoundKeysInZip(Sets.NewHashSet("a1", "a2", "a3")); sut.StartZip("b.zip", 2, 2); sut.FoundUserKey("buser"); sut.FoundKeysInZip(Sets.NewHashSet("b1", "b2", "b3")); sut.FoundUsers(Sets.NewHashSet("u1", "u2", "u3")); sut.FoundKeys(Sets.NewHashSet("1", "2", "3")); sut.FoundUpes( Lists.NewList <IUserProfileEvent>(new UserProfileEvent { Id = "1" }, new UserProfileEvent { Id = "2" })); sut.FoundAssignableZips(Sets.NewHashSet("a", "b")); }
/// <summary> /// Serializes the current instance into a JSON object. /// </summary> /// <returns>The JSON representation of the current instance.</returns> public JToken ToJson() { return(new JObject { { "objName", Name }, { "variables", new JArray(Variables.Select(x => x.ToJson())) }, { "lists", new JArray(Lists.Select(x => x.ToJson())) }, { "scripts", new JArray(Scripts.Select(x => x.ToJson())) }, { "scriptComments", new JArray(Comments.Select(x => x.ToJson())) }, { "sounds", new JArray(Sounds.Select(x => x.ToJson())) }, { "costumes", new JArray(Costumes.Select(x => x.ToJson())) }, { "currentCostumeIndex", CurrentCostume }, { "scratchX", Location.X }, { "scratchY", Location.Y }, { "scale", Scale }, { "direction", Direction }, { "rotationStyle", RotationStyle.ToSerializedString() }, { "isDraggable", Draggable }, { "indexInLibrary", LibraryIndex }, { "visible", Visible }, { "spriteInfo", new JValue(SpriteInfo) } }); }
public ConnectionGroupRow GetGroupByName(string name) { string clause = string.Join(" AND ", Lists.Of( ConnectionGroupDirectory.NameFn.AsSqlClausePair(), ConnectionGroupDirectory.IsDirectConnectionFn.AsSqlClausePair() )); List <SQLiteParameter> parameters = Lists.Of( new SQLiteParameter(ConnectionGroupDirectory.NameFn, name), new SQLiteParameter(ConnectionGroupDirectory.IsDirectConnectionFn, true) ); ConnectionGroupRow row = this._storage.ConnectionGroupDirectory.GetRows( clause, parameters, 1 ) .Select(RowConverter.Convert <ConnectionGroupRow>) .FirstOrDefault(); return(row); }
public virtual void send(EntityRef entity, Event @event, Component component) { if (Thread.CurrentThread != mainThread) { pendingEvents.offer(new PendingEvent(entity, @event, component)); } else { SetMultimap <Type, EventHandlerInfo> handlers = componentSpecificHandlers[@event.GetType()]; if (handlers != null) { IList <EventHandlerInfo> eventHandlers = Lists.newArrayList(handlers.get(component.GetType())); eventHandlers.Sort(priorityComparator); foreach (EventHandlerInfo eventHandler in eventHandlers) { if (eventHandler.isValidFor(entity)) { eventHandler.invoke(entity, @event); } } } } }
public List <ServerInstanceRow> GetAllGroupInstances( long groupId, string protocolType ) { string clause = string.Join(" AND ", Lists.Of( ServerInstanceDirectory.ConnectionGroupIdFn.AsSqlClausePair(), ServerInstanceDirectory.DbTypeFn.AsSqlClausePair() )); List <SQLiteParameter> parameters = Lists.Of( new SQLiteParameter(ServerInstanceDirectory.DbTypeFn, protocolType), new SQLiteParameter(ServerInstanceDirectory.ConnectionGroupIdFn, groupId) ); List <ServerInstanceRow> rows = this._storage.ServerInstanceDirectory.GetRows( clause, parameters ).Select(ServerInstanceRow.Copy).ToList(); return(rows); }
/// <summary> /// Return a standalone instance of FSEditLog that will log into the given /// log directory. /// </summary> /// <remarks> /// Return a standalone instance of FSEditLog that will log into the given /// log directory. The returned instance is not yet opened. /// </remarks> /// <exception cref="System.IO.IOException"/> public static FSEditLog CreateStandaloneEditLog(FilePath logDir) { NUnit.Framework.Assert.IsTrue(logDir.Mkdirs() || logDir.Exists()); if (!FileUtil.FullyDeleteContents(logDir)) { throw new IOException("Unable to delete contents of " + logDir); } NNStorage storage = Org.Mockito.Mockito.Mock <NNStorage>(); Storage.StorageDirectory sd = FSImageTestUtil.MockStorageDirectory(logDir, NNStorage.NameNodeDirType .Edits); IList <Storage.StorageDirectory> sds = Lists.NewArrayList(sd); Org.Mockito.Mockito.DoReturn(sds).When(storage).DirIterable(NNStorage.NameNodeDirType .Edits); Org.Mockito.Mockito.DoReturn(sd).When(storage).GetStorageDirectory(Matchers.AnyObject <URI>()); FSEditLog editLog = new FSEditLog(new Configuration(), storage, ImmutableList.Of( logDir.ToURI())); editLog.InitJournalsForWrite(); return(editLog); }
public ILoopHeaderExpression ToLoopHeaderExpression(ICSharpExpression csExpr, IList <IStatement> body) { if (csExpr == null) { return(new UnknownExpression()); } var nestedBody = Lists.NewList <IStatement>(); var expr = ToSimpleExpression(csExpr, nestedBody); if (nestedBody.Count == 0) { return(expr); } nestedBody.Add(new ReturnStatement { Expression = expr }); return(new LoopHeaderBlockExpression { Body = nestedBody }); }
public async Task <ActionResult <Lists> > UpdateList([FromBody] Lists model) { var _list = new Lists { LISTID = model.LISTID, ListTitle = model.ListTitle, USERID = model.USERID }; var result = await _lists.UpdateList(_list); if (result == null) { return(BadRequest("Record is not updated 1")); } if (result.LISTID == -1) { return(BadRequest("Record is not updated 2")); } return(await Task.FromResult(_list)); }
public void NoPropagationContextLeaks() { int numInputs = 200; var layerSpecs = MakeLayers(); var weightCount = RNNInterop.GetWeightCount(layerSpecs, numInputs); var mem = new MemoryAnalyzer(); using (mem) { Lists.Repeat(10000, _ => { var rnnSpec = new RNNSpec(numInputs, layerSpecs, new DenseVector(weightCount)); var context = RNNInterop.CreatePropagationContext(rnnSpec); var input = MakeVector(numInputs); RNNInterop.PropagateInput(context, input.ToArray(), 1); context.Dispose(); }); } Trace.WriteLine("Mem usage before: " + mem.StartMB); Trace.WriteLine("Mem usage after: " + mem.StopMB); Assert.IsTrue(mem.StopMB - mem.StartMB < 2); }
private void SwitchMonster(int a, int b) { byte x = formation.X[a]; byte y = formation.Y[a]; byte monster = formation.Monsters[a]; bool use = formation.Use[a]; bool hide = formation.Hide[a]; // this.coordX[a].Value = formation.X[b]; this.coordY[a].Value = formation.Y[b]; this.bytes[a].Value = formation.Monsters[b]; this.use[a].Checked = formation.Use[b]; this.hide[a].Checked = formation.Hide[b]; // this.coordX[b].Value = x; this.coordY[b].Value = y; this.bytes[b].Value = monster; this.use[b].Checked = use; this.hide[b].Checked = hide; // this.formationNameList.Items[Index] = Lists.Numerize(formation.ToString(), Index, 3); }
private static IList <string> ParseParams(this string id, int open, int close) { var parameters = Lists.NewList <string>(); var cur = open + 1; // skip outer bracket while (cur != -1 && cur < close) { var openParam = id.FindNext(cur, '[', ']'); if (id[openParam] == ']') { cur = close; } else { var closeParam = id.FindCorrespondingCloseBracket(openParam); openParam++; // skip bracket var paramId = id.Substring(openParam, closeParam - openParam); parameters.Add(paramId); cur = closeParam + 1; } } return(parameters); }
public string GetFolderHierarchy(RequestObject requestObject, MatterData matterData) { string result = string.Empty; if (null != requestObject && null != matterData && ValidationHelperFunctions.CheckRequestValidatorToken()) { try { if (!string.IsNullOrWhiteSpace(matterData.MatterName) && !string.IsNullOrWhiteSpace(matterData.MatterUrl)) { using (ClientContext clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(matterData.MatterUrl), requestObject.RefreshToken)) { List list = clientContext.Web.Lists.GetByTitle(matterData.MatterName); clientContext.Load(list.RootFolder); ListItemCollection listItems = Lists.GetData(clientContext, matterData.MatterName, string.Format(CultureInfo.InvariantCulture, ServiceConstantStrings.AllFoldersQuery, matterData.MatterName)); List <FolderData> allFolders = new List <FolderData>(); allFolders = SearchHelperFunctions.GetFolderAssignment(list, listItems, allFolders); result = JsonConvert.SerializeObject(allFolders); } } else { result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, 0, TextConstants.MessageNoInputs); } } catch (Exception exception) { result = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName); } } else { result = TextConstants.MessageNoInputs; } return(result); }
//Justin Pennington 2/14/15 /// <summary> /// Updates database information and compares old information with current database values /// to ensure that the database has not been modified in the meantime /// </summary> /// <param name="oldList">Old values to ensure data has not been modified</param> /// <param name="newList">New values to be written to database</param> /// <returns> /// rowsAffected /// </returns> public static int UpdateLists(Lists oldList, Lists newList) { //connect to Database var conn = DatabaseConnection.GetDatabaseConnection(); var cmdText = "spUpdateLists"; var cmd = new SqlCommand(cmdText, conn); var rowsAffected = 0; // set command type to stored procedure and add parameters cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SupplierID", newList.SupplierID); cmd.Parameters.AddWithValue("@ItemListID", newList.ItemListID); cmd.Parameters.AddWithValue("@DateListed", newList.DateListed); cmd.Parameters.AddWithValue("@original_SupplierID", oldList.SupplierID); cmd.Parameters.AddWithValue("@original_ItemListID", oldList.ItemListID); cmd.Parameters.AddWithValue("@original_DateListed", oldList.DateListed); try { conn.Open(); rowsAffected = cmd.ExecuteNonQuery(); if (rowsAffected == 0) { throw new ApplicationException("Concurrency Violation"); } } catch (Exception) { throw; } finally { conn.Close(); } return(rowsAffected); // needs to be rows affected }
public virtual void TestRbwBlocksNotConsideredUnderReplicated() { IList <FSDataOutputStream> stms = Lists.NewArrayList(); try { // Create some junk blocks so that the NN doesn't just immediately // exit safemode on restart. DFSTestUtil.CreateFile(fs, new Path("/junk-blocks"), BlockSize * 4, (short)1, 1L); // Create several files which are left open. It's important to // create several here, because otherwise the first iteration of the // replication monitor will pull them off the replication queue and // hide this bug from the test! for (int i = 0; i < 10; i++) { FSDataOutputStream stm = fs.Create(new Path("/append-" + i), true, BlockSize, (short )1, BlockSize); stms.AddItem(stm); stm.Write(1); stm.Hflush(); } cluster.RestartNameNode(); FSNamesystem ns = cluster.GetNameNode(0).GetNamesystem(); BlockManagerTestUtil.UpdateState(ns.GetBlockManager()); NUnit.Framework.Assert.AreEqual(0, ns.GetPendingReplicationBlocks()); NUnit.Framework.Assert.AreEqual(0, ns.GetCorruptReplicaBlocks()); NUnit.Framework.Assert.AreEqual(0, ns.GetMissingBlocksCount()); } finally { foreach (FSDataOutputStream stm in stms) { IOUtils.CloseStream(stm); } cluster.Shutdown(); } }
//Justin Pennington 2/14/15 /// <summary> /// Returns a list of listing objects based on the parameters sent with the method call /// </summary> /// <param name="inSupplierID">Object holding SupplierID</param> /// <param name="inItemListID">Object holding ItemListID</param> /// <returns> /// theLists /// </returns> public static Lists GetLists(string inSupplierID, string inItemListID) { var theLists = new Lists(); // set up the database call var conn = DatabaseConnection.GetDatabaseConnection(); string cmdText = "spSelectLists"; var cmd = new SqlCommand(cmdText, conn); cmd.Parameters.AddWithValue("@SupplierID", inSupplierID); cmd.Parameters.AddWithValue("@ItemListID", inItemListID); //Put retrieved data into objects try { conn.Open(); var reader = cmd.ExecuteReader(); if (reader.HasRows == true) { theLists.SupplierID = reader.GetInt32(0); theLists.ItemListID = reader.GetInt32(1); theLists.DateListed = (DateTime)reader.GetValue(3); } else { var ax = new ApplicationException("Data not found!"); throw ax; } } catch (Exception) { throw; } finally { conn.Close(); } return(theLists); }
public static Monster.SubMonster RandomMoves(Monster.SubMonster mon) { Move[] temp = Lists.Moves(); List <int> done = new List <int>(); List <Move> potentials = new List <Move>(); int randi; for (int i = 0; i < temp.Length; i++) { for (int j = 0; j < mon.compatmovetypes.Length; j++) { if (temp[i].themove.type == mon.compatmovetypes[j]) { potentials.Add(temp[i]); } } } randi = Random.Range((int)0, (int)potentials.Count); mon.moves[0] = new Move.SubMove(potentials[randi].themove); done.Add(randi); for (int k = 1; k < 3; k++) { randi = Random.Range((int)0, (int)potentials.Count); if (!done.Contains(randi)) { done.Add(randi); mon.moves[k] = new Move.SubMove(potentials[randi].themove); } else { k--; } } return(new Monster.SubMonster(mon)); }
private void _showList(Lists aList) { ResourceLoader loader = new ResourceLoader(); switch (aList) { case Lists.Phrases: { ShowPhrasesList = true; ShowCategoryList = false; ShowSortedPhrasesList = false; ListHeaderText = loader.GetString("PhrasesListHeaderText"); break; } case Lists.Categories: { ShowPhrasesList = false; ShowCategoryList = true; ShowSortedPhrasesList = false; ListHeaderText = loader.GetString("CategoriesListHeaderText"); break; } case Lists.SortedPhrases: { ShowPhrasesList = false; ShowCategoryList = false; ShowSortedPhrasesList = true; ListHeaderText = loader.GetString("PhrasesListHeaderText"); break; } default: break; } }
public void Create() { // Arrange var name = "listname"; var mockRepository = new MockRepository(MockBehavior.Strict); var mockClient = mockRepository.Create <IClient>(); mockClient .Setup(c => c.PostAsync(ENDPOINT, It.IsAny <JObject>(), It.IsAny <CancellationToken>())) .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(SINGLE_LIST_JSON) }) .Verifiable(); var lists = new Lists(mockClient.Object, ENDPOINT); // Act var result = lists.CreateAsync(name, CancellationToken.None).Result; // Assert result.ShouldNotBeNull(); }
private void NewList_Deleted(object sender, EventArgs e) { Lists uc = sender as Lists; int Locate = -1; for (int i = 0; i < listBoards.Count; i++) { if (listBoards[i].BackColor == Color.LightBlue) { Locate = i; break; } } int listLocate = listBoards[Locate].list.IndexOf(uc); listBoards[Locate].list.Remove(uc); ListListPanel.Controls.Remove(uc); for (int i = listLocate; i < (listBoards[Locate]).list.Count; i++) { listBoards[Locate].list[i].Location = new Point(listBoards[Locate].list[i].Location.X - 300, 0); } ButtonAddList.Location = new Point(ButtonAddList.Location.X - 300, 10); ResetListPropsIneEachBoard(); }
public virtual void TestAddVolumes() { int numNewVolumes = 3; int numExistingVolumes = dataset.GetVolumes().Count; int totalVolumes = numNewVolumes + numExistingVolumes; ICollection <string> expectedVolumes = new HashSet <string>(); IList <NamespaceInfo> nsInfos = Lists.NewArrayList(); foreach (string bpid in BlockPoolIds) { nsInfos.AddItem(new NamespaceInfo(0, ClusterId, bpid, 1)); } for (int i = 0; i < numNewVolumes; i++) { string path = BaseDir + "/newData" + i; string pathUri = new Path(path).ToUri().ToString(); expectedVolumes.AddItem(new FilePath(pathUri).ToString()); StorageLocation loc = StorageLocation.Parse(pathUri); Storage.StorageDirectory sd = CreateStorageDirectory(new FilePath(path)); DataStorage.VolumeBuilder builder = new DataStorage.VolumeBuilder(storage, sd); Org.Mockito.Mockito.When(storage.PrepareVolume(Matchers.Eq(datanode), Matchers.Eq (loc.GetFile()), Matchers.AnyListOf <NamespaceInfo>())).ThenReturn(builder); dataset.AddVolume(loc, nsInfos); } NUnit.Framework.Assert.AreEqual(totalVolumes, dataset.GetVolumes().Count); NUnit.Framework.Assert.AreEqual(totalVolumes, dataset.storageMap.Count); ICollection <string> actualVolumes = new HashSet <string>(); for (int i_1 = 0; i_1 < numNewVolumes; i_1++) { actualVolumes.AddItem(dataset.GetVolumes()[numExistingVolumes + i_1].GetBasePath( )); } NUnit.Framework.Assert.AreEqual(actualVolumes.Count, expectedVolumes.Count); NUnit.Framework.Assert.IsTrue(actualVolumes.ContainsAll(expectedVolumes)); }
private List <Action> ClearActions() { bool lockTaken = false; try { Monitor.Enter(_lock, ref lockTaken); if (_queue.Count == 0) { _flushPending = false; return(Queue.Empty); } Lists.Swap(ref _queue, ref _toPass); _queue.Clear(); return(_toPass); } finally { if (lockTaken) { Monitor.Exit(_lock); } } }
public static StructBody TupleDefinition(RootNamespace root, int count) { var name = GetTupleName(count); var exists = root.Structs.FindFirstOrNull(x => x.Name == name); if (exists is StructBody sb) { return(sb); } var body = new StructBody(root, name); Lists.RangeTo(1, count).Each(i => { var gp = new TypeGenericsParameter($"a{i}"); body.Generics.Add(gp); var member = new VariableValue($"{i}"); body.LexicalScope.Add(member.Name, member); body.Body.Add(new TypeBind(member, gp)); body.Members.Add(member.Name, member); }); root.Structs.Add(body); return(body); }
private void ButtonAddList_Click(object sender, EventArgs e) { int Locate = -1; for (int i = 0; i < listBoards.Count; i++) { if (listBoards[i].BackColor == Color.LightBlue) { Locate = i; break; } } ButtonAddList.Location = new Point(ButtonAddList.Location.X + 300, ButtonAddList.Location.Y); Lists NewList = new Lists(); NewList.TextboxListName.Text = "List (" + (listBoards[Locate].list.Count + 1) + ")"; NewList.NameLists = NewList.TextboxListName.Text; NewList.Location = new Point(ButtonAddList.Location.X - 300, 0); NewList.Deleted += NewList_Deleted; NewList.SecondFormShowed += NewList_SecondFormShowed; NewList.SecondFormClosed += NewList_SecondFormClosed; listBoards[Locate].list.Add(NewList); ListListPanel.Controls.Add(NewList); Data.BoardProp boardProp = new Data.BoardProp(); boardProp = listBoards[Locate].boardProp; Data.ListProp listProp = new Data.ListProp(); listProp.Board_ID = boardProp.Board_ID; listProp.List_Name = NewList.TextboxListName.Text; listProp.List_Observing = false; listProp.List_Position = listBoards[Locate].list.Count - 1; Data.DataService.InsertList(listProp); listBoards[Locate].listProps = Data.DataService.GetListByBoardID(boardProp.Board_ID); NewList.listProp = listBoards[Locate].listProps[listBoards[Locate].listProps.Count - 1]; }
/// <summary> /// Get a collection with lists from the SharePoint Web Service. /// </summary> /// <returns>Collection with lists.</returns> public SPList[] GetLists() { List <SPList> items = new List <SPList>(); Lists lists = new Lists(); lists.Credentials = Credentials; lists.Url = Url.ToString(); lists.Proxy = GetProxy(); lists.UserAgent = "Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)"; //TrustAllCertificatePolicy cert = new TrustAllCertificatePolicy(); ServicePointManager.ServerCertificateValidationCallback += ((sender, certificate, chain, sslPolicyErrors) => true); XmlDocument doc = new XmlDocument(); doc.LoadXml(lists.GetListCollection().OuterXml); foreach (XmlNode node in RunXPathQuery(doc, "//sp:List")) { items.Add(new SPList(GetNodeAttribute(node.Attributes["Title"]), GetNodeAttribute(node.Attributes["ID"]), new Uri((GetNodeAttribute(node.Attributes["DefaultViewUrl"]) == String.Empty ? "http://moss/" : String.Format("{0}{1}", Url.ToString().Replace(Url.PathAndQuery, String.Empty), GetNodeAttribute(node.Attributes["DefaultViewUrl"])))), node)); } return(items.ToArray()); }
public void ShouldReturnImmutableMultiDictionaryMultiEntries(ImmutableMultiDictionaryCreator creator) { // given var entires = Lists.AsList( Dictionaries.Entry(1, "A"), Dictionaries.Entry(1, "B"), Dictionaries.Entry(1, "C"), Dictionaries.Entry(2, "A"), Dictionaries.Entry(3, "C")); var immutableMultiDictionary = creator.Create(entires.ToArray()); // when var result = immutableMultiDictionary.MultiEntries; // then var mutliEntriesDictionary = result.ToDictionary(element => element.Key, element => element.Value); Check.That(immutableMultiDictionary.Count).IsEqualTo(entires.Count); Check.That(result).HasSize(3); Check.That(mutliEntriesDictionary.Keys).HasSize(3).And.Contains(1, 2, 3); Check.That(mutliEntriesDictionary[1]).HasSize(3).And.Contains("A", "B", "C"); Check.That(mutliEntriesDictionary[2]).HasSize(1).And.Contains("A"); Check.That(mutliEntriesDictionary[3]).HasSize(1).And.Contains("C"); }
public void ShouldReturnMultiEntries(MultiDictionaryContext context) { // given var multiDictionary = context.Create <int, string>(); multiDictionary.Put(1, "A"); multiDictionary.Put(1, "B"); multiDictionary.Put(1, "C"); multiDictionary.Put(2, "A"); multiDictionary.PutAll(3, Lists.AsList("X", "Y", "Z")); // when var entries = multiDictionary.MultiEntries; // then Check.That(entries).HasSize(3); var entry1 = entries.First(entry => entry.Key == 1); var entry2 = entries.First(entry => entry.Key == 2); var entry3 = entries.First(entry => entry.Key == 3); Check.That(entry1.Value).IsEqualTo(context.CollectionOf("A", "B", "C")); Check.That(entry2.Value).IsEqualTo(context.CollectionOf("A")); Check.That(entry3.Value).IsEqualTo(context.CollectionOf("X", "Y", "Z")); }
static void AssertIsCrossedOverVersionOf(Tuple2 <Chromosome> curr, Tuple2 <Chromosome> prev) { var a1 = curr.Item1; var b1 = curr.Item2; var a0 = prev.Item1; var b0 = prev.Item2; Trace.WriteLine(""); Trace.WriteLine("a0: " + a0); Trace.WriteLine("a1: " + a1); Trace.WriteLine("b0: " + b0); Trace.WriteLine("b1: " + b1); a1.ShouldNotLookLike(a0); b1.ShouldNotLookLike(b0); Lists.Repeat(a1.Genes.Length, i => { var a1g = a1.Genes[i]; var b1g = b1.Genes[i]; var a0g = a0.Genes[i]; var b0g = b0.Genes[i]; if (a1g.LooksLike(a0g)) { b1g.ShouldLookLike(b0g); } else if (a1g.LooksLike(b0g)) { b1g.ShouldLookLike(a0g); } else { Assert.Fail("gene was mutated??"); } }); }
public bool SaveList(object obj) { try { var isNewObject = SelectedList.Id; var stat = _listService.InsertOrUpdate(SelectedList); if (string.IsNullOrEmpty(stat)) { if (isNewObject == 0) { Lists.Insert(0, SelectedList); } return(true); } MessageBox.Show(stat); return(false); } catch { return(false); } }
protected int PullPrjBoard(bool PullActiveOnly, bool UpdateProjects) { string output = ""; //holds label output int count = 0; //count of number of projects pulled, will return this value Lists listService = new Lists(); ProjectsBLL project = new ProjectsBLL(); listService.PreAuthenticate = true; listService.Credentials = System.Net.CredentialCache.DefaultCredentials; XmlDocument xmlDoc = new XmlDocument(); XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", ""); XmlNode ndViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", ""); XmlNode ndQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", ""); ndQueryOptions.InnerXml = "";// "<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns>" + "<DateInUtc>TRUE</DateInUtc>"; ndViewFields.InnerXml = "";// "<FieldRef Name='Title'/><FieldRef Name='Column5'/><FieldRef Name='Column4'/><FieldRef Name='Completed'/><FieldRef Name='Column12'/><FieldRef Name='Project_x0020_Site_x0020_URL'/><FieldRef Name='Project_x0020_Manager2'/><FieldRef Name='IT_x0020_Technical_x0020_Lead'/><FieldRef Name='Project_x0020_Phase'/>"; //query XML with only completed items or all items? if (PullActiveOnly) ndQuery.InnerXml = "<Where><Eq><FieldRef Name='Completed'/><Value Type='Number'>0</Value></Eq></Where>"; else ndQuery.InnerXml = ""; try { XmlNode ndListItems; Hashtable prjHash = new Hashtable(); //call web service to get all the projects from the PMO Project Board ndListItems = listService.GetListItems(PROJECT_BOARD_GUID, PROJECT_BOARD_VIEW_GUID, ndQuery, ndViewFields, null, ndQueryOptions); //create xml document so we can process XmlDocument doc = new XmlDocument(); doc.LoadXml(ndListItems.OuterXml); foreach (XmlNode element in doc.ChildNodes[0].ChildNodes[0].ChildNodes) { if (element.Attributes != null) { foreach (XmlAttribute attr in element.Attributes) { switch (attr.Name) { //TODO: This will be different based on the fields in your SharePoint list. case "ows_Title": prjHash.Add("ProjectNumber", attr.Value); break; case "ows_NSR_x002f_Project_x0020_Name": prjHash.Add("Name", attr.Value); break; case "ows_Completed": //list contains 0 if not compeleted and -1 if completed if (Convert.ToInt32(attr.Value) == 0) prjHash.Add("Active", true); else prjHash.Add("Active", false); break; case "ows_Approved": prjHash.Add("Approved", attr.Value); break; case "ows_Current_x0020_Status": prjHash.Add("Status", attr.Value); break; case "ows_Project_x0020_Site_x0020_URL": //list returns value as url,url. we only need it once, so using split we take the first one prjHash.Add("SiteURL", attr.Value.Split(',')[0]); break; case "ows_Project_x0020_Manager": prjHash.Add("ProjectManager", attr.Value.Split('#')[1]); break; case "ows_Project_x0020_Phase": prjHash.Add("PhaseID", attr.Value); break; case "ows_ID": //once the attribute equals "ows_ID" we know we can process //setup some temp holders int projectID = Convert.ToInt32(attr.Value); string number = prjHash["ProjectNumber"].ToString(); string name = prjHash["Name"].ToString(); string projectManager; if (prjHash.ContainsKey("ProjectManager")) projectManager = prjHash["ProjectManager"].ToString(); else projectManager = ""; string siteURL; if (prjHash.ContainsKey("SiteURL")) siteURL = prjHash["SiteURL"].ToString(); else siteURL = null; int phaseID; if (prjHash.ContainsKey("PhaseID")) { switch (prjHash["PhaseID"].ToString()) { case "Initiating": phaseID = 0; break; case "Planning": phaseID = 1; break; case "Execution": phaseID = 2; break; case "Monitoring": phaseID = 3; break; case "Closing": phaseID = 4; break; case "Proposals": phaseID = 5; break; case "Startups/Turndowns": phaseID = 6; break; case "Startup": phaseID = 7; break; case "Turndown": phaseID = 8; break; case "Win-awaiting NTP": phaseID = 9; break; default: phaseID = -1; break; } } else phaseID = -1; bool active; if (Convert.ToBoolean(prjHash["Active"]) && (prjHash["Approved"].ToString() == "Approved as Project" || prjHash["Approved"].ToString() == "NSR Analysis")) active = true; else active = false; //DEBUG PRINT //output += "<tr><td>Debug: " + number + " - " + name + "</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>"; //first we check to see if this project already exists if (project.ProjectIDExists(projectID) < 1) { output += "<tr><td>Adding: " + number + " - " + name + "</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>"; //add the project to the db, first checking to see if SiteURL exists and is not empty if (prjHash.ContainsKey("SiteURL") && (string)prjHash["SiteURL"] != String.Empty) project.AddProject(projectID, number, name, siteURL, active, phaseID, projectManager); else project.AddProject(projectID, number, name, null, active, phaseID, projectManager); output += "<td>Complete!</td></tr>"; count++; } else { //otherwise the project already exists and we can update it if (UpdateProjects) { TimeKeeper.ProjectsDataTable prj = project.GetProjectByProjectID(projectID); TimeKeeper.ProjectsRow prjRow = prj[0]; //output += "<tr><td>Update - " + number + " - " + name + "</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>"; //output += "<tr><td>active = " + active.ToString() + "</tr></td>"; //count++; if (prjRow.Active != active) { //RUN DEACTIVATE PROJECT CODE HERE if (active == false) { ProjectMembersBLL projectMembers = new ProjectMembersBLL(); int membersDeleted = projectMembers.DeleteProjectMembersByProjectID(projectID); output += "<tr><td>Deactivating: " + number + " - " + name + ", Removed " + membersDeleted.ToString() + " member(s)</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>"; project.UpdateProject(projectID, number, name, null, false, phaseID, projectManager); output += "<td>Complete!</td></tr>"; } else { output += "<tr><td>Activating: " + number + " - " + name + "</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>"; project.UpdateProject(projectID, number, name, null, true, phaseID, projectManager); output += "<td>Complete!</td></tr>"; } count++; } if (prjRow.ProjectNumber != number || prjRow.Name != name || prjRow.PhaseID != phaseID || prjRow.ProjectManager.ToString() != projectManager) { //it does exist, print message output += "<tr><td>Updating: " + number + " - " + name + "</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>"; if (prjHash.ContainsKey("SiteURL") && (string)prjHash["SiteURL"] != String.Empty) { project.UpdateProject(projectID, number, name, siteURL, active, phaseID, projectManager); } else { project.UpdateProject(projectID, number, name, null, active, phaseID, projectManager); } output += "<td>Complete!</td></tr>"; count++; } if (prjRow.IsTeamSiteURLNull() && prjHash.ContainsKey("SiteURL") && (string)prjHash["SiteURL"] != String.Empty) { //there is a new team site that we need to add output += "<tr><td>Team Site added: " + number + " - " + name + "</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>"; project.UpdateProject(projectID, number, name, siteURL, active, phaseID, projectManager); output += "<td>Complete!</td></tr>"; count++; } } } break; } } } //clear the hash for the next element prjHash.Clear(); } } catch (System.Web.Services.Protocols.SoapException ex) { output = ex.StackTrace; } //set label PullOutputLabel.Text = output; return count; }
public TrelloClient(string authKey, string authToken) { Boards = new Boards(authKey, authToken); Lists = new Lists(authKey, authToken); Cards = new Cards(authKey, authToken); }
/// <summary> /// Get the file from '12 Hive' Features folder and Deserialize to a class. /// </summary> /// <returns></returns> private Lists GetListsInfo(SPFeatureReceiverProperties properties) { Lists lists = new Lists(); TextReader textreader = new StreamReader(properties.Feature.Definition.RootDirectory + @"\" + Constants.CONFIG_PATH); XmlSerializer xmlSerial = new XmlSerializer(typeof(Lists)); lists = (Lists)xmlSerial.Deserialize(textreader); textreader.Close(); textreader.Dispose(); return lists; }
private void detach_Lists(Lists entity) { this.SendPropertyChanging(); entity.Users = null; }
/// <summary> /// Retrieves data from SharePoint server using web services. /// </summary> /// <returns>Dataset or XmlNode</returns> protected object GetSharePointData() { #region "Prepare credentials for authentication" ICredentials credentials = null; // If there are data in username or password use it for authentication if (String.IsNullOrEmpty(Username) && String.IsNullOrEmpty(Password)) { credentials = SharePointFunctions.GetSharePointCredetials(); } else { credentials = SharePointFunctions.GetSharePointCredetials(Username, Password, useBase64Encoding); } #endregion #region "Retrieve SharePoint data" string serviceURL = SPServiceURL; // If not direct web service specified, determine web service URL by mode if (!serviceURL.EndsWithCSafe(".asmx", true)) { // Remove trailing slash serviceURL = serviceURL.TrimEnd('/'); switch (Mode.ToLowerCSafe()) { case MODE_LIST_ITEMS: case MODE_SITE_LISTS: serviceURL += "/_vti_bin/lists.asmx"; break; case MODE_PICTURE_LIBRARIES: case MODE_PICTURE_LIBRARY_ITEMS: serviceURL += "/_vti_bin/imaging.asmx"; break; } } // Query web service try { Lists spLists; Imaging spImaging; switch (Mode.ToLowerCSafe()) { // Load list items case MODE_LIST_ITEMS: // Instantiate Lists service spLists = new Lists(serviceURL); spLists.Credentials = credentials; camlData = LoadListItems(spLists, ListName); break; // Load site lists case MODE_SITE_LISTS: // Instantiate Lists service spLists = new Lists(serviceURL); spLists.Credentials = credentials; // Get all SharePoint lists camlData = spLists.GetListCollection(); break; // Load picture libraries case MODE_PICTURE_LIBRARIES: // Instantiate imaging service spImaging = new Imaging(serviceURL); spImaging.Credentials = credentials; // Get picture libraries camlData = spImaging.ListPictureLibrary(); break; // Load picture library items case MODE_PICTURE_LIBRARY_ITEMS: // Instantiate imaging service spImaging = new Imaging(serviceURL); spImaging.Credentials = credentials; // Show error if library name empty if (String.IsNullOrEmpty(ListName)) { DisplayError(ResHelper.GetString("SharePoint.picslibunspecified")); break; } // Get pictures in libraries, directly (not in folder) camlData = spImaging.GetListItems(ListName, null); break; } } catch (Exception ex) { DisplayError(ResHelper.GetString("sharepoint.erroradta") + ResHelper.Colon + " " + ex.Message); } // No data if (camlData == null) { return null; } #endregion #region "Prepare data" // Use of XSLT transformation if (!UseClassicDataset) { dataSource = camlData; } // Use of classic dataset else { // Prepare dataset DataSet ds = new DataSet(); // If datset fields are specified if (!String.IsNullOrEmpty(Fields)) { DataTable dt = ds.Tables.Add(); string[] fields = Fields.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string field in fields) { string currentField = field.Trim(); if (!string.IsNullOrEmpty(currentField)) { try { dt.Columns.Add(field.Trim()); } catch (DuplicateNameException) { mErrorMessage = ResHelper.GetString("sharepoint.duplicateField"); } } } XmlNodeList records = GetDataRecords(camlData); List<string> fieldsCheck = new List<string>(); fieldsCheck.AddRange(fields); // Load items to dataset foreach (XmlNode record in records) { DataRow dr = dt.NewRow(); // Add fields foreach (string field in fields) { string currentField = field.Trim(); if (!string.IsNullOrEmpty(currentField)) { XmlAttribute attr = record.Attributes[currentField]; if (attr != null) { dr[currentField] = attr.Value; // At least one record has the field fieldsCheck.Remove(field); } } } dt.Rows.Add(dr); } // None of retrieved records has fields if (fieldsCheck.Count > 0) { DisplayError(String.Format(ResHelper.GetString("sharepoint.fieldnotFound"), fieldsCheck[0])); return null; } // Set daatsource dataSource = ds; } // No fields specified, use all fields else { // Only if CAML contains data record, otherwise dataset would contain wrong values if (HasData) { camlData.InnerXml = SpecialCharsRegex.Replace(camlData.InnerXml, "_"); XmlNodeReader rd = new XmlNodeReader(camlData); ds.ReadXml(rd); rd.Close(); switch (Mode.ToLowerCSafe()) { // Use last datatable as datasource case MODE_LIST_ITEMS: dataSource = ds.Tables[ds.Tables.Count - 1].DefaultView; break; // Filter hidden lists in dataset case MODE_SITE_LISTS: // Dataset structure changes based on xml, try to use last data table DataTable dt = ds.Tables[ds.Tables.Count - 1]; // Show only visible lists dt.DefaultView.RowFilter = "Hidden = 'False'"; dataSource = dt.DefaultView; break; // Dateset with picture libraries case MODE_PICTURE_LIBRARIES: dataSource = ds.Tables[ds.Tables.Count - 1].DefaultView; break; // Dataset with pictures case MODE_PICTURE_LIBRARY_ITEMS: dataSource = ds.Tables[ds.Tables.Count - 1].DefaultView; break; } } } } #endregion ShowRawResponse(camlData); return dataSource; }
/// <summary> /// Update the model to match what is in RTM /// FIXME: This is a lame implementation and needs to be optimized /// </summary> void UpdateTasks(Lists lists) { Debug.WriteLine ("RtmBackend.UpdateTasks was called"); try { foreach (var list in lists.listCollection) { Tasks tasks = null; try { tasks = rtm.TasksGetList (list.ID); } catch (Exception tglex) { Debug.WriteLine ("Exception calling TasksGetList(list.ListID) " + tglex.Message); } if (tasks != null) { foreach (var tList in tasks.ListCollection) { if (tList.TaskSeriesCollection == null) continue; foreach (var ts in tList.TaskSeriesCollection) { lock (taskLock) { Application.Instance.Dispatcher.Invoke (delegate { if (!Tasks.Any (t => ((RtmTask)t).ID == ts.TaskID)) { var rtmTask = new RtmTask (ts, this, list.ID); var cat = Categories.SingleOrDefault ( c => ((RtmCategory)c).ID == list.ID); if (cat != null) cat.Add (rtmTask); } }); } } } } } } catch (Exception e) { Debug.WriteLine ("Exception in fetch " + e.Message); Debug.WriteLine (e.ToString ()); } Debug.WriteLine ("RtmBackend.UpdateTasks is done"); }
private void LogDocumentRouting(EmailDocument document) { using (Lists listService = new Lists()) { listService.Credentials = CredentialCache.DefaultCredentials; listService.Url = Config["SharePointSiteUrl"] + "_vti_bin/lists.asmx"; try { string xml = "<Method ID='1' Cmd='New'>" + "<Field Name='ID'/>" + "<Field Name='Title'>" + document.DestinationCase + "</Field>" + "<Field Name='From'>" + document.DocumentPath + "</Field>" + "<Field Name='To'>" + document.DestinationUrl + "</Field>" + "</Method>"; /*Get Name attribute values (GUIDs) for list and view. */ System.Xml.XmlNode ndListView = listService.GetListAndView(Config["RoutingLog"].Replace("/", ""), ""); string strListID = ndListView.ChildNodes[0].Attributes["Name"].Value; string strViewID = ndListView.ChildNodes[1].Attributes["Name"].Value; /*Create an XmlDocument object and construct a Batch element and its attributes. Note that an empty ViewName parameter causes the method to use the default view. */ System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); System.Xml.XmlElement batchElement = doc.CreateElement("Batch"); batchElement.SetAttribute("OnError", "Continue"); batchElement.SetAttribute("ListVersion", "1"); batchElement.SetAttribute("ViewName", ""); /*Specify methods for the batch post using CAML. To update or delete, specify the ID of the item, and to update or add, specify the value to place in the specified column.*/ batchElement.InnerXml = xml; XmlNode item = listService.UpdateListItems(Config["RoutingLog"].Replace("/", ""), batchElement); } catch (Exception e) { Logger logger = LogManager.GetCurrentClassLogger(); logger.Log(LogLevel.Error, "LogDocumentRouting: Exception occurred when logging a successful routing of document. \nSource: " + document.DocumentPath + "\nTo: " + document.DestinationUrl, e); } } }
private List<EmailDocument> GetRoutedDocuments() { List<EmailDocument> routedDocuments = new List<EmailDocument>(); using (Lists listService = new Lists()) { listService.Credentials = CredentialCache.DefaultCredentials; listService.Url = Config["SharePointSiteUrl"] + "_vti_bin/lists.asmx"; // Query to get any items that have Patents or Trademarks XmlDocument xmlDoc = new System.Xml.XmlDocument(); XmlNode itemsQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", ""); XmlNode itemsViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", ""); XmlNode itemsQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", ""); itemsQueryOptions.InnerXml = "<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns><DateInUtc>TRUE</DateInUtc>"; itemsViewFields.InnerXml = @"<FieldRef Name='ID' /> <FieldRef Name='GUID' /> <FieldRef Name='Name' /> <FieldRef Name='Patent'/> <FieldRef Name='Trademarks'/>"; itemsQuery.InnerXml = @"<Where> <Or> <IsNotNull> <FieldRef Name='Patent' /> </IsNotNull> <IsNotNull> <FieldRef Name='Trademarks' /> </IsNotNull> </Or> </Where>"; XmlNode listItems = listService.GetListItems("Inbox", null, itemsQuery, itemsViewFields, null, itemsQueryOptions, null); XElement data = GetXElement(listItems); XElement dataRowset = data.Element(XName.Get("data", "urn:schemas-microsoft-com:rowset")); IEnumerable<XElement> documentRows = dataRowset.Elements(XName.Get("row", "#RowsetSchema")); foreach (XElement documentRow in documentRows) { try { FieldValueIdPair fileReference = GetFieldValueIdPair(documentRow, "ows_FileRef"); string fileId = fileReference.FieldId; string filePath = Config["SharePointSiteUrl"].Substring(0, Config["SharePointSiteUrl"].IndexOf("depts/")) + fileReference.FieldValue; FieldValueIdPair destinationPatent = GetFieldValueIdPair(documentRow, "ows_Patent"); FieldValueIdPair destinationTrademark = GetFieldValueIdPair(documentRow, "ows_Trademarks"); FieldValueIdPair fileNameReference = GetFieldValueIdPair(documentRow, "ows_FileLeafRef"); FieldValueIdPair uniqueId = GetFieldValueIdPair(documentRow, "ows_UniqueId"); string destinationCase = string.Empty; bool isPatent = false; bool isTrademark = false; if (destinationPatent.FieldId != null && destinationPatent.FieldId != string.Empty && !destinationPatent.FieldId.Equals("0")) { destinationCase = Config["SharePointSiteUrl"] + Config["PatentSharePointLibraryName"] + destinationPatent.FieldValue + "/" + fileNameReference.FieldValue; isPatent = true; } else if (destinationTrademark.FieldId != null && destinationTrademark.FieldId != string.Empty && !destinationTrademark.FieldId.Equals("0")) { destinationCase = Config["SharePointSiteUrl"] + Config["TrademarkSharePointLibraryName"] + destinationTrademark.FieldValue + "/" + fileNameReference.FieldValue; isTrademark = true; } routedDocuments.Add(new EmailDocument { DocumentId = fileId, DocumentPath = filePath, DestinationUrl = destinationCase, IsPatent = isPatent, IsTrademark = isTrademark, DestinationCase = (destinationPatent.FieldId != null && destinationPatent.FieldId != string.Empty && !destinationPatent.FieldId.Equals("0")) ? destinationPatent.FieldValue : destinationTrademark.FieldValue, UniqueId = uniqueId.FieldValue }); } catch (Exception e) { Logger logger = LogManager.GetCurrentClassLogger(); logger.Log(LogLevel.Error, "GetRoutedDocuments: Exception occurred when determining a routed document filepath and ID", e); } } } return routedDocuments; }
private bool DeleteRoutedDocument(EmailDocument routedDocument) { bool deletedSuccessfully = false; using (Lists listService = new Lists()) { listService.Credentials = CredentialCache.DefaultCredentials; listService.Url = Config["SharePointSiteUrl"] + "_vti_bin/lists.asmx"; if (routedDocument.RoutedSuccessfully) { try { string xml = "<Method ID='1' Cmd='Delete'>" + "<Field Name='ID'>" + routedDocument.DocumentId + "</Field>" + "<Field Name='FileRef'>" + routedDocument.DocumentPath + "</Field>" + "</Method>"; /*Get Name attribute values (GUIDs) for list and view. */ System.Xml.XmlNode ndListView = listService.GetListAndView(Config["SharePointLibraryName"].Replace("/", ""), ""); string strListID = ndListView.ChildNodes[0].Attributes["Name"].Value; string strViewID = ndListView.ChildNodes[1].Attributes["Name"].Value; /*Create an XmlDocument object and construct a Batch element and its attributes. Note that an empty ViewName parameter causes the method to use the default view. */ System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); System.Xml.XmlElement batchElement = doc.CreateElement("Batch"); batchElement.SetAttribute("OnError", "Continue"); batchElement.SetAttribute("ListVersion", "1"); batchElement.SetAttribute("ViewName", ""); /*Specify methods for the batch post using CAML. To update or delete, specify the ID of the item, and to update or add, specify the value to place in the specified column.*/ batchElement.InnerXml = xml; XmlNode item = listService.UpdateListItems(Config["SharePointLibraryName"].Replace("/", ""), batchElement); deletedSuccessfully = true; } catch (Exception e) { Logger logger = LogManager.GetCurrentClassLogger(); logger.Log(LogLevel.Error, "DeleteRoutedDocuments: Exception occurred when deleting a routed document: " + routedDocument.DocumentPath, e); } } } return deletedSuccessfully; }
/// <summary> /// Update the model to match what is in RTM /// FIXME: This is a lame implementation and needs to be optimized /// </summary> private void UpdateCategories(Lists lists) { Logger.Debug("RtmBackend.UpdateCategories was called"); try { foreach(List list in lists.listCollection) { RtmCategory rtmCategory = new RtmCategory(list); lock(catLock) { Gtk.TreeIter iter; Gtk.Application.Invoke ( delegate { if(categories.ContainsKey(rtmCategory.ID)) { iter = categories[rtmCategory.ID].Iter; categoryListStore.SetValue (iter, 0, rtmCategory); } else { iter = categoryListStore.Append(); categoryListStore.SetValue (iter, 0, rtmCategory); rtmCategory.Iter = iter; categories.Add(rtmCategory.ID, rtmCategory); } }); } } } catch (Exception e) { Logger.Debug("Exception in fetch " + e.Message); } Logger.Debug("RtmBackend.UpdateCategories is done"); }
/// <summary> /// Update the model to match what is in RTM /// FIXME: This is a lame implementation and needs to be optimized /// </summary> private void UpdateTasks(Lists lists) { Logger.Debug("RtmBackend.UpdateTasks was called"); try { foreach(List list in lists.listCollection) { Tasks tasks = null; try { tasks = rtm.TasksGetList(list.ID); } catch (Exception tglex) { Logger.Debug("Exception calling TasksGetList(list.ListID) " + tglex.Message); } if(tasks != null) { foreach(List tList in tasks.ListCollection) { if (tList.TaskSeriesCollection == null) continue; foreach(TaskSeries ts in tList.TaskSeriesCollection) { RtmTask rtmTask = new RtmTask(ts, this, list.ID); lock(taskLock) { Gtk.TreeIter iter; Gtk.Application.Invoke ( delegate { if(taskIters.ContainsKey(rtmTask.ID)) { iter = taskIters[rtmTask.ID]; } else { iter = taskStore.AppendNode (); taskIters.Add(rtmTask.ID, iter); } taskStore.SetValue (iter, 0, rtmTask); }); } } } } } } catch (Exception e) { Logger.Debug("Exception in fetch " + e.Message); Logger.Debug(e.ToString()); } Logger.Debug("RtmBackend.UpdateTasks is done"); }
/// <summary> /// Queries SharePoint for list items. /// </summary> /// <param name="listService">List service proxy class instance</param> /// <param name="listName">List name</param> /// <returns>CAML with list items</returns> protected XmlNode LoadListItems(Lists listService, string listName) { // Get all SharePoint lists XmlNode listCollectionCaml = listService.GetListCollection(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(listCollectionCaml.OwnerDocument.NameTable); nsmgr.AddNamespace("soap", "http://schemas.microsoft.com/sharepoint/soap/"); // Check list with given name exists XmlNodeList collections = listCollectionCaml.SelectNodes("/soap:List[@Title = '" + listName + "']", nsmgr); // If specified list does not exists show error if (collections.Count == 0) { DisplayError(ResHelper.GetString("SharePoint.listdoesnotexists")); return null; } #region "Advanced options" //XmlElement query = null; XmlDocument viewFields = null; XmlDocument query = null; XmlDocument queryOptions = null; // Specify search by query if (!String.IsNullOrEmpty(Query)) { //query = xmlOptions.CreateElement("Query"); //query.InnerXml = this.Query; //"<Where><Gt><FieldRef Name=\"ID\" /><Value Type=\"Counter\">0</Value></Gt></Where>"; query = new XmlDocument(); query.LoadXml(Query); } // Select item if (!String.IsNullOrEmpty(ItemIDField)) { string queryValue = QueryHelper.GetText(ItemIDField, null); if (queryValue != null) { IsSelected = true; // Set field name from ItemIDField if not set string fieldName = (String.IsNullOrEmpty(SelectedItemFieldName)) ? ItemIDField : SelectedItemFieldName; // No query was set if (query == null) { query = new XmlDocument(); } // Get or create Query node XmlNode queryNode = query.SelectSingleNode("Query"); if (queryNode == null) { queryNode = query.CreateNode(XmlNodeType.Element, "Query", null); query.AppendChild(queryNode); } // Get or create Where node XmlNode whereNode = queryNode.SelectSingleNode("Where"); if (whereNode == null) { whereNode = query.CreateNode(XmlNodeType.Element, "Where", null); queryNode.AppendChild(whereNode); } // Prepare query for selecting item string selectItem = String.Format("<Eq><FieldRef ID='{0}' /><Value Type='{1}'>{2}</Value></Eq>", fieldName, ItemIDFieldType, queryValue); // Incorporate with original query if (!String.IsNullOrEmpty(whereNode.InnerXml)) { selectItem = String.Format("<And>{0}{1}</And>", whereNode.InnerXml, selectItem); } // Update Where node whereNode.InnerXml = selectItem; } } // Specify which fields should be retrieved if (!String.IsNullOrEmpty(ViewFields)) { viewFields = new XmlDocument(); string xml = "<ViewFields>"; string[] fields = ViewFields.Split(';'); foreach (string field in fields) { xml += string.Format("<FieldRef Name=\"{0}\" />", field.Trim()); } xml += "</ViewFields>"; viewFields.LoadXml(xml); } //xmlDoc.CreateElement("QueryOptions"); //queryOptions.InnerXml = ""; // If set limit maximum count of rows string rowLimit = (RowLimit > 0) ? RowLimit.ToString() : null; #endregion // Get documents in the list XmlNode documentsXml = listService.GetListItems(ListName, null, query, viewFields, rowLimit, queryOptions, null); return documentsXml; }
/// <summary> /// Update the model to match what is in RTM /// FIXME: This is a lame implementation and needs to be optimized /// </summary> void UpdateCategories(Lists lists) { Debug.WriteLine ("RtmBackend.UpdateCategories was called"); try { foreach (var list in lists.listCollection) { lock (catLock) { Application.Instance.Dispatcher.Invoke (delegate { RtmCategory rtmCategory; if (!Categories.Any (c => ((RtmCategory)c).ID == list.ID)) { rtmCategory = new RtmCategory (list); Categories.Add (rtmCategory); } }); } } } catch (Exception e) { Debug.WriteLine ("Exception in fetch " + e.Message); } Debug.WriteLine ("RtmBackend.UpdateCategories is done"); }
private void DoInitialSync() { panel1.Visible = true; try { LabelStatus.Text = "Sync in progress..."; LabelStatus.Refresh(); Utility.Sync(); LabelStatus.Text = "Sync completed!"; LabelSyncTime.Text = DateTime.Now.ToString(); var lists = new Lists(); lists.ShowDialog(); panel1.Visible = false; } catch (Exception ex) { LabelStatus.Text = "Error in sync"; MessageBox.Show(ex.Message); } }
partial void UpdateLists(Lists instance);
public Stage() { lists = new Lists(); }
private void FTP_ListFAFs(String newDir, Lists l, bool recFiles, bool recFolder) { //TODO: Server is creating multiple connection, instead of resuing one List<FTP_FAF> FAFs = l.RemoteFAFs; WebRequest wr = CreateServerWebRequest(newDir); if(wr == null) { Debug.WriteLine("ERROR: Could not create server web request!"); return; } wr.Method = WebRequestMethods.Ftp.ListDirectoryDetails; FtpWebResponse response1 = (FtpWebResponse)wr.GetResponse(); Stream stream = response1.GetResponseStream(); if(stream == null) { Debug.WriteLine("ERROR: Response stream was empty!"); return; } StreamReader reader = new StreamReader(stream); String line; while((line = reader.ReadLine()) != null) { Regex regex = new Regex(@"^([d-])([rwxt-]{3}){3}\s+\d{1,}\s+.*?(\d{1,})\s+(\w+\s+\d{1,2}\s+(?:\d{4})?)(\d{1,2}:\d{2})?\s+(.+?)\s?$", // http://stackoverflow.com/questions/1013486/parsing-ftpwebrequests-listdirectorydetails-line RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); Match m = regex.Match(line); GroupCollection groups = m.Groups; bool file = "-".Equals(groups[1].ToString()); string permissions = groups[2].ToString(); string filesize = groups[3].ToString(); string lastModifiedDate = groups[4].ToString(); string lastModifiedTime = groups[5].ToString(); string name = groups[6].ToString(); string fullPath = newDir + "/" + name; if("".Equals(newDir)) fullPath = name; if(!file && (name.Contains(".svn") || name.Contains(".git"))) continue; //Exclude git and svn dirs FTP_FAF newFaf = new FTP_FAF(file, permissions, Convert.ToInt32(filesize), lastModifiedDate, lastModifiedTime, name, fullPath); if(!file) FTP_ListFAFs(fullPath, l, recFiles, recFolder); if(recFiles && file) FAFs.Add(newFaf); if(recFolder && !file) FAFs.Add(newFaf); } reader.Close(); stream.Close(); wr.GetResponse().Close(); response1.Close(); }
private void buttonLogin_Click(object sender, EventArgs e) { try { if (String.IsNullOrEmpty(textBoxUserName.Text.Trim())) { MessageBox.Show("UserName cannot be empty", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } var webRequest = (HttpWebRequest)WebRequest.Create(String.Format(Settings.LoginUrl, textBoxUserName.Text.Trim())); var response = (HttpWebResponse)webRequest.GetResponse(); if (response.StatusCode != HttpStatusCode.OK) { MessageBox.Show("Login failed!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } using (Stream responseStream = response.GetResponseStream()) { // Read the GUID using (var reader = new StreamReader(responseStream)) { var clientId = reader.ReadToEnd(); DataStoreHelper.ListDbFileName = clientId + ".sdf"; Settings.ClientId = clientId; } } if (String.IsNullOrEmpty(Settings.ClientId) || String.IsNullOrEmpty(DataStoreHelper.ListDbFileName)) { MessageBox.Show("Login failed!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } bool newUser = false; if (!File.Exists(DataStoreHelper.ListDbFileName)) { newUser = true; } DataStoreHelper.InitializeDataStore(); var storageHandler = new SqlCeStorageHandler(); byte[] anchor = storageHandler.GetAnchor(); if (null == anchor || 0 == anchor.Length) { newUser = true; } if (newUser) { // Do an initial sync and open the list view DoInitialSync(); } else { var lists = new Lists(); lists.ShowDialog(); } } catch (Exception exception) { MessageBox.Show(exception.Message, "Unhandled Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); } }
public void SyncServerLocal(object sender, EventArgs e) { Lists l = new Lists(); CalculateLists(l); WebClient client = CreateServerWebClient(); foreach(FAF faf in l.MissingRemoteFAFs) { if(faf.File) { string fileToDelete = GMOD_ROOT + faf.Name; View.AddInfo("Deleting file: " + fileToDelete); File.Delete(fileToDelete); } } foreach(FAF faf in l.MissingRemoteFAFs) { if(!faf.File) { string folderToDelete = GMOD_ROOT + faf.Name; View.AddInfo("Deleting folder: "+folderToDelete); Directory.Delete(folderToDelete); } } foreach(FTP_FAF faf in l.MissingLocalFAFs) { if(!faf.File) { string newFolder = GMOD_ROOT + faf.RelativePath; View.AddInfo("Creating missing directory: "+newFolder); Directory.CreateDirectory(newFolder); } } foreach(FTP_FAF faf in l.MissingLocalFAFs) { if(faf.File) { String newFile = GMOD_ROOT + faf.RelativePath; View.AddInfo("Downloading file: \""+faf.RelativePath+"\" and saving in location \""+newFile+"\""); client.DownloadFile(GetServerURI(faf.RelativePath), newFile); //TODO: Implement async download // Progress bar } } client.Dispose(); View.AddInfo("Finished syncing!"); }
partial void InsertLists(Lists instance);
/// <summary> /// News the site directory lists web service. /// </summary> /// <returns></returns> public Lists NewSiteDirectoryListsWebService() { Lists ws = new Lists(); ws.Url = SiteDirectoryListsUrl; ws.Credentials = Credentials; return ws; }
/// <summary> /// News the lists web service. /// </summary> /// <returns></returns> public Lists NewListsWebService() { Lists ws = new Lists(); ws.Url = siteUrl + "Lists.asmx"; ws.Credentials = Credentials; return ws; }
partial void DeleteLists(Lists instance);
private void attach_Lists(Lists entity) { this.SendPropertyChanging(); entity.Users = this; }