I want to retrieve object data from an ArrayList;
public class Form1
{
ArrayList list = new ArrayList();
private void OnSockMessage(object sender, SockEventArgs e)
{
Regex MyRegex = new Regex("^[<][A-Za-z]");
if (e.SockMsg != null)
{
string y = e.SockMsg.ToString();
if (MyRegex.IsMatch(y) == true)
{
rrr = y;
string ipdd = SocClient[e.SocketRef].Soc.RemoteEndPoint.ToString();
//serverkey seckey;
list.Add(new serverkey(ipdd,rrr));
}
else
{
string curipadd = SocClient[e.SocketRef].Soc.RemoteEndPoint.ToString();
for (int i = 0; i < list.Count-1; i++)
{
//serverkey pk = list[i] as serverkey;
//string jj = list[i].ToString();
// serverkey pk = new serverkey(list[i].ToString());
/*********************************************
here i want to retrieve data from array list
*********************************************/
string ipadd;
if (curipadd == ipadd )
{
y = DecryptString(e.SockMsg, rrr);
listBox1.Items.Add(txtIP.Text + " <<" + y);
}
}
}
}
public class serverkey : Form1
{
string ipaddress;
string secertkey;
public serverkey(string IPAdd, string Seckey)
{
ipaddress = IPAdd;
secertkey = Seckey;
}
public string ip
{
get { return ipaddress; }
}
public string key
{
get { return secertkey; }
}
You'd be better off using a strongly typed generic List<serverkey> and a foreach loop rather than a for loop. It'll be something like
List<serverkey> list = new List<serverkey>();
//add your items as you already are
foreach(var item in list)
{
item.ip ...// use item as a serverkey
}
Having said that, if you can you use a generic for some reason, use an 'as'
ArrayList list = new ArrayList();
//add your items as you already are
foreach(var item in list)
{
var sk = item as serverkey;
sk.ip ...// use item as a serverkey
}
Related
I am making console app using Array class that has username as object, this is member.cs
Class Member{
public string username;
public Member(){
}
public Member(string username){
username = username;
}
}
And this is my Collection.cs
Class Collection{
static Member[] members = new Member[100];
public void Adduser(){
console.writeLine("username?");
string user_input = console.ReadLine();
members = new Member[]{
new Member(user_input)
};
}
public Member[] get() {
return members;
}
}
but every time the Adduser() functions is called, it only stores one member and keeps updating to a new member, in here I am expecting to have 100 usernames at most.
How should I store multiple values in side the constructor or Array object?
Should I create a new array in member class to store multiple-member?
Even after I implemented index, I get nullexception error in side foreach
public void showMember()
{
var data = record.get();
foreach (var value in data)
{
Console.WriteLine(value.Username);
Console.WriteLine(value.Phonenum);
Console.WriteLine(value.Password);
Console.WriteLine(value.Borrowedmovie);
}
}
that's because you renew the array every time.this might help.
int index=0;
public void Adduser(){
console.writeLine("username?");
string user_input = console.ReadLine();
if(index<members.Length)
{
members[index]=new Member(user_input)
index++;
}
else console.writeLine("overflow");
}
}
also I think it's better if you use list instead of array
static List<Member> members = new List<Member>();
public void Adduser(){
console.writeLine("username?");
string user_input = console.ReadLine();
members.Add(new Member(user_input));
}
Instead of an array you should use an List object.
Class Collection{
static List<Member> members = new List<Member>();
public void Adduser(){
console.writeLine("username?");
string user_input = console.ReadLine();
members.Add(new Member(user_input));
}
}
Use index variable and update it everytime u add an item.
Class Collection{
static Member[] members = new Member[100];
int index = 0;
public void Adduser(){
console.writeLine("username?");
string user_input = console.ReadLine();
members[index] = new Member(user_input);
index++;
}
}
Since array is already instantiated with 100 elements, we can not check length of array to check whether elements exists or not.
Array.length will always give the max length of array since the memory is allocated for 100 elements.
But you can check whether last element exists or not and then you can add the new element.
Below code snippet can help you:
class Member
{
public string _username;
public Member()
{
}
public Member(string username)
{
_username = username;
}
}
class Collection
{
private Member[] members = new Member[100];
private int index = 0;
public void Adduser()
{
Console.WriteLine("username?");
string user_input = Console.ReadLine();
var lastElement = members[members.Length - 1];
if (lastElement != null)
{
Console.WriteLine("members array is already full");
return;
}
members[index] = new Member(user_input);
index++;
}
public void DisplayMembers()
{
foreach (var item in members)
{
if (item != null)
{
Console.WriteLine("UserName {0}", item._username);
}
}
}
}
Following is a code for testing the functionality:
static void Main(string[] args)
{
Collection collection = new Collection();
collection.Adduser();
collection.Adduser();
collection.Adduser();
collection.Adduser();
collection.Adduser();
collection.Adduser();
collection.DisplayMembers();
Console.WriteLine("Start second collection");
Collection collection2 = new Collection();
collection2.Adduser();
collection2.Adduser();
collection2.Adduser();
collection2.Adduser();
collection2.Adduser();
collection2.DisplayMembers();
Console.ReadLine();
}
Good day,
I try that when I connect two documents, the numbered lists are reset. As in the example below.
I use the Xceed.Words.NET DocX libary.
In this Sample, the Template is :
Test Header
List:
1) <-This should be one
And the Result is:
Test Header
List:
1) <-This should be one
Test Header
List:
2) <-This should be one
Test Header
List:
3) <-This should be one
With the following code I am able to create the lists with similar formatting, but the formatting does not match 100%. Does anyone have any idea which way to try otherwise?
Note the number of existing paragraphs and call the function to reset the list after inserting the document.
/// <summary>
/// Insert complete WordFile
/// </summary>
/// <param name="wordFile"></param>
public void InsertWordTemplate(IWordFile wordFile, bool InsertPageBreak)
{
if (wordFile != null && wordFile.IsFileOk)
{
int pargraphCount = Document.Paragraphs.Count - 1;
// NotNeeded for this Problem wordFile.RemoveStyles();
// NotNeeded for this Problem RemoveHeaderAndFooter(wordFile);
Document.InsertDocument(wordFile.Document);
// NotNeeded for this Problem ReplaceSectionBreak(InsertPageBreak, pargraphCount);
ResetNumberedList(pargraphCount);
logger.Info("Word file inserted: " + wordFile.File.FullName);
}
else
{
logger.Warn("Word file is not okay - will not be inserted: " + wordFile?.File?.FullName);
}
}
In the Word document, three different names are used in a list, only from the 4th level is worked with a level. For other Word templates they are called different.
private void ResetNumberedList(int pargraphCount)
{
string styleName1 = "ListNumbers";
string styleName2 = "PIgeordneteListe2Ebene";
string styleName3 = "PIgeordneteListe3Ebene";
NumberedListReset numberedListReset = new NumberedListReset(Document, styleName1, styleName2, styleName3);
bool OnlyFirstFoundList = true;
numberedListReset.Reset(pargraphCount, OnlyFirstFoundList);
}
Below is the helper class with which I try to reset the numbering. I do this by myself
I notice the formatting of the individual list items, create new lists, fill them with the old values, set the styles correctly again and then insert everything into old place.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Xceed.Document.NET;
using Xceed.Words.NET;
namespace PIB.Report.DataWriter.WordExport
{
public class NumberedListReset
{
private readonly DocX _Document;
private readonly string _StyleName1;
private readonly string _StyleName2;
private readonly string _StyleName3;
public NumberedListReset(DocX Document, string StyleName1, string StyleName2, string StyleName3)
{
_Document = Document;
_StyleName1 = StyleName1;
_StyleName2 = StyleName2;
_StyleName3 = StyleName3;
}
public void Reset(int StartParagraphNumber, bool OnlyFirstFinding)
{
for (int i = StartParagraphNumber; i < _Document.Paragraphs.Count; i++)
{
var paragraph = _Document.Paragraphs[i];
if (paragraph.IsListItem == true && paragraph.ListItemType == ListItemType.Numbered && paragraph.StyleName == _StyleName1)
{
//int? numId = GetNumId(paragraph);
//if (numId != -1)
//{
//}
ResetFoundList(ref i);
if (OnlyFirstFinding == true)
{
break;
}
}
}
}
private void ResetFoundList(ref int ParagraphCounter)
{
List<ParagraphMemorize> ParagraphMemorizes = CreateMemorizeListItems(ParagraphCounter);
if (ParagraphMemorizes.Count != 0)
{
RemoveOldParagraphsFromDocument(ParagraphMemorizes);
List numberedList = CreateNewDocumentList();
FillDocumentList(ParagraphMemorizes, numberedList);
List<Paragraph> actualListData = numberedList.Items;
ResetSyleNames(ParagraphMemorizes, actualListData);
InsertNewParagraphsToDocument(ParagraphCounter, actualListData);
ParagraphCounter += ParagraphMemorizes.Count;
}
}
private List<ParagraphMemorize> CreateMemorizeListItems(int ParagraphCounter)
{
List<ParagraphMemorize> ParagraphMemorizes = new List<ParagraphMemorize>();
for (int ii = ParagraphCounter; ii < _Document.Paragraphs.Count; ii++)
{
var paragraph = _Document.Paragraphs[ii];
if (!NameIsKnown(paragraph.StyleName))
{
break;
}
ParagraphMemorize paragraphMemorize = new ParagraphMemorize(paragraph);
paragraphMemorize.ListLevel = GetListLevel(paragraph);
ParagraphMemorizes.Add(paragraphMemorize);
}
return ParagraphMemorizes;
}
private void RemoveOldParagraphsFromDocument(List<ParagraphMemorize> ParagraphMemorizes)
{
ParagraphMemorizes.ForEach(m => _Document.RemoveParagraph(m.Paragraph));
}
private List CreateNewDocumentList()
{
return _Document.AddList(startNumber: 1);
}
private void FillDocumentList(List<ParagraphMemorize> ParagraphMemorizes, List numberedList)
{
for (var ii = 0; ii < ParagraphMemorizes.Count; ii++)
{
//numberedList.AddItem(ParagraphMemorizes[ii].Paragraph); //Raised an Error
ParagraphMemorize paragraphMemorize = ParagraphMemorizes[ii];
int listLevel = GetListLevel(paragraphMemorize);
_Document.AddListItem(numberedList, paragraphMemorize.Text, listLevel);
}
}
private static void ResetSyleNames(List<ParagraphMemorize> ParagraphMemorizes, List<Paragraph> actualListData)
{
for (int ii = 0; ii < actualListData.Count; ii++)
{
actualListData[ii].StyleName = ParagraphMemorizes[ii].StyleName;
}
}
private void InsertNewParagraphsToDocument(int i, List<Paragraph> actualListData)
{
Paragraph paragraph = _Document.Paragraphs[i];
for (int ii = 0; ii < actualListData.Count; ii++)
{
paragraph.InsertParagraphBeforeSelf(actualListData[ii]);
}
}
private bool NameIsKnown(string Name)
{
return Name == _StyleName1 | Name == _StyleName2 | Name == _StyleName3;
}
private int GetListLevel(ParagraphMemorize paragraphMemorize)
{
if (paragraphMemorize.StyleName == _StyleName1)
{
return 0;
}
else if (paragraphMemorize.StyleName == _StyleName2)
{
return 1;
}
else if (paragraphMemorize.StyleName == _StyleName3)
{
return (int)paragraphMemorize.ListLevel;
}
else
{
return 0;
}
}
private int? GetNumId(Paragraph paragraph)
{
var numIds = paragraph.ParagraphNumberProperties.Descendants().Where(e => e.Name.LocalName.Equals("numId"));
foreach (var numId in numIds)
{
XNamespace nsW = Namespace.WordNamespace;
var values = numId.Attributes(XName.Get("val", nsW.ToString()));
foreach (var value in values)
{
int resultId = 0;
int.TryParse(value.Value, out resultId);
return resultId;
}
}
return null;
}
private int? GetListLevel(Paragraph paragraph)
{
var numIds = paragraph.ParagraphNumberProperties.Descendants().Where(e => e.Name.LocalName.Equals("ilvl"));
foreach (var numId in numIds)
{
XNamespace nsW = Namespace.WordNamespace;
var values = numId.Attributes(XName.Get("val", nsW.ToString()));
foreach (var value in values)
{
int resultId = 0;
int.TryParse(value.Value, out resultId);
return resultId;
}
}
return null;
}
private class ParagraphMemorize
{
public Paragraph Paragraph { get; set; }
public string Text { get; set; }
public string StyleName { get; set; }
public int? ListLevel { get; set; }
public ParagraphMemorize(Paragraph Paragraph)
{
this.Paragraph = Paragraph;
this.Text = Paragraph.Text;
this.StyleName = Paragraph.StyleName;
}
}
}
}
I need to set the property SortOrder in the GridEx,
and this property is only get.
What can I do?
the code:
private void M_Grid_ColumnHeaderClick(object sender, Janus.Windows.GridEX.ColumnActionEventArgs e)
{
if (e.Column.DataMember == "Filed1")
{
var list = m_Grid.DataSource;
if (e.Column.SortOrder == Janus.Windows.GridEX.SortOrder.Descending)
{
list = list.OrderBy(p => p.ParticipationDate).ToList();
e.Column.SortOrder = Janus.Windows.GridEX.SortIndicator.Ascending;// it's not good
}
else
{
list = list.OrderByDescending(p => p.ParticipationDate).ToList();
e.Column.SortOrder = Janus.Windows.GridEX.SortIndicator.Descending;// it's not good
}
m_Grid.DataSource = list;
}
}
Not recommended way:
private void M_Grid_ColumnHeaderClick(object sender, Janus.Windows.GridEX.ColumnActionEventArgs e)
{
if (e.Column.DataMember == "Filed1")
{
var list = m_Grid.DataSource;
if (e.Column.SortOrder == Janus.Windows.GridEX.SortOrder.Descending)
{
list = list.OrderBy(p => p.ParticipationDate).ToList();
// e.Column.SortOrder = Janus.Windows.GridEX.SortIndicator.Ascending;
}
else
{
list = list.OrderByDescending(p => p.ParticipationDate).ToList();
// e.Column.SortOrder = Janus.Windows.GridEX.SortIndicator.Descending;
}
m_Grid.DataSource = list;
m_Grid.Refetch();
}
}
Another approach working with sortkeys for example:
private void M_Grid_ColumnHeaderClick(object sender, Janus.Windows.GridEX.ColumnActionEventArgs e)
{
if (e.Column.DataMember == "Filed1")
{
//Removing any sort key that may be present in the table
m_Grid.RootTable.SortKeys.Clear(); //or can be removed only specific
// sortkey
// get the column to be sorted
column = e.Column;
if (e.Column.SortOrder == Janus.Windows.GridEX.SortOrder.Descending)
{
sortKey = new GridEXSortKey(column, SortOrder.Ascending);
}
else
{
sortKey = new GridEXSortKey(column, SortOrder.Descending);
}
m_Grid.RootTable.SortKeys.Add(sortKey);
}
}
After a lot of experimenting and being the right answer.
In case you want to sort a particular field by any other value and not by default
Use the property: SortComparer and implement the Compare() function of the IComparer class
For example, what I did is:
On the load of the component write:
m_Grid.RootTable.Columns["Field1"].SortComparer = new Field1Sort();
The class to implement:
public class Field1Sort: IComparer
{
public Field1Sort()
{
}
public int Compare(object x, object y)
{
var xString = (string)x;
var yString = (string)y;
var date1 = xString.Substring(0, 10).ToDateTime();
var date2 = yString.Substring(0, 10).ToDateTime();
if (date1 < date2)
return -1;
if (date1 > date2)
return 1;
else
return 0;
}
}
I am currently creating a class library for an API. Here is my current issue:
The API has support for multi-call functionality in which I can get data for multiple submissions (i.e. a Skin, Model, Script, etc.) all at the same time in the form of an array holding an object for each of the submissions. The link I will be providing is completely for testing purposes as it returns the same submission three times and can be found here.
The goal is to grab the raw JSON data for each object and put it into a string array so that I can go through each of the objects and deserialize them individually. The reason for this is that the api could return any kind of object (as specified above) and this system must adjust to each object that goes through it. Here's the current code:
Program.cs
class Program
{
static WebClient web = new WebClient();
static void Main(string[] args)
{
APICaller ApiManager = new APICaller(web);
Model exampleObject = new Model(3962);
Model exampleObject2 = new Model(3962);
Model exampleObject3 = new Model(3962);
List<Model> SubmissionInstances = new List<Model>() { exampleObject, exampleObject2, exampleObject3 };
int[] IDs = new int[] { exampleObject.itemID, exampleObject2.itemID, exampleObject3.itemID };
string[] fields = new string[] { exampleObject.fields, exampleObject2.fields, exampleObject3.fields };
ApiManager.Data(SubmissionInstances, IDs, fields);
}
}
APICaller.cs
public List<object> Data<T>(List<T> type, int[] itemid, string[] fields)
{
//Same as the first function but supports multi-call
string itemTypes = "";
string itemIDs = "";
string itemFields = "";
string finalURL = "http://api.gamebanana.com/Core/Item/Data?";
int i = 0;
foreach (object obj in type)
{
itemTypes += "&itemtype[]=" + obj.GetType().Name;
types[i] = obj.GetType();
i++;
}
foreach (int ID in itemid)
{
itemIDs += "&itemid[]=" + ID;
}
foreach (string field in fields)
{
itemFields += "&fields[]=" + field;
}
finalURL += itemTypes + itemIDs + itemFields + "&return_object=1";
string[] JSONObjects = JsonConvert.DeserializeObject<string[]>(client.DownloadString(finalURL));
List<object> toReturn = new List<object>();
i = 0;
foreach (string str in JSONObjects)
{
toReturn.Add(DeserializeObject(type[i], str));
i++;
}
return toReturn;
}
public T DeserializeObject<T> (T obj, dynamic JSONObj)
{
return JsonConvert.DeserializeObject<T>(JSONObj);
}
I have a class called rateTime
class rateTime
{
private List<string> t = new List<string>();
private List<string> s = new List<string>();
public rateTime(string[] time, string[] sender)
{
for (int i = 0; i < time.Length; i++)
{
t.Add(time[i]);
s.Add(sender[i]);
}
}
~rateTime() { }
public List<string> Time
{
get { return t;}
set { t = value; }
}
public List<string> Sender
{
get { return s; }
set { s = value; }
}
}
The DataSource of my combobox is set as follows:
rateTime rt = new rateTime(time, rateSender);
cb_rateTime.DataSource = rt.Time;
cb_rateTime.DisplayMember = "time";
In both lists I have 28 strings. I set items from List t as combobox items. And if I chose an item from the combobox with index, for example 10, I want know how can I get the string from list s with index 10.
try elementAt(index) - http://msdn.microsoft.com/en-us/library/bb299233.aspx
or indexer - yourList[index]
I don't know if I understood well, but:
var index = cb_rateTime.SelectedIndex;
var itemS = rt.Sender.elementAt(index);
or
var selected = cb_rateTime.SelectedText;
var itemS = rt.Sender[selected];
That should resolve.
Access it by index as in
MyRateTime.Sender[10]