browse list and add condition - c#

i have a function that return list of ip and his port this is the function :
public static List<ServerSocks> loadSocks()
{
var result = new List<ServerSocks>();
string fileSocks = Path.GetFullPath(Path.Combine(Application.StartupPath, "socks-list.txt"));
var input = File.ReadAllText(fileSocks);
var r = new Regex(#"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})");
foreach (Match match in r.Matches(input))
{
string ip = match.Groups[1].Value;
int port = Convert.ToInt32(match.Groups[2].Value);
ServerSocks bi = new ServerSocks();
bi.IpAddress = IPAddress.Parse(ip);
bi.Port = port;
result.Add(bi);
}
return result;
}
i want a random value from list to be the proxy settings for my oServer
List<ServerSocks> list;
List<ServerSocks> list = loadSocks();
SmtpServer oServer = new SmtpServer("");
foreach (var item in list)
{
oServer.SocksProxyServer = Convert.ToString(item.IpAddress);
oServer.SocksProxyPort = item.Port;
}
i do like this but always he give me the last ip and his port.
What i should do ??
thanks .

What happens is that you set oServer.SocksProxyServer when you first enter the loop and all consecutive runs overwrites the value. It does cycle through all your List<ServerSocks>
If you want to convert to a list of oServer then you'd create a new list outside the loop and do this inside the loop:
Add(new OServer { SocksProxyServer=item.IpAddress.ToString(), SocksProxyPort=item.Port })
It'd be great if you'd explain what you want to happen in more detail. I hope this helps you though.
Edit
You don't need a loop at all. It's sufficient to get a random index and retrieve the corresponding item.
var oServer = new SmtpServer("");
var random = new Random();
var randomIndex = random.Next(list.Count);
var socks = list[randomIndex];
oServer.SocksProxyServer = socks.IpAddress;
oServer.SocksProxyPort = socks.Port;

In order to achieve what you want to do, do this:
List<ServerSocks> list = loadSocks();
Random rnd = new Random();
int r = rnd.Next(list.Count);
oServer.SocksProxyServer = Convert.ToString(list[r].IpAddress);
oServer.SocksProxyPort = list[r].Port;
Then it will take a random Object from the ServerSocks list and use.

Related

Adding an Object of class to an array of the same class C#

Hello all
I try to convert a group of ŲStrings to a class, and then add these elements to an array or list of the same class
problem
Everything is fine, only when one element is added does it change all the values in the array to the same values as the last element
TxtCookie.Text :
1=|257|9.5|1|true|true|true|true|1-From Web, 2=|259|11.5|7|false|false|false|false|232-From Web, 3=|261|9.5|5|true|false|true|true|-From Web, 4=|267|9.5|1|true|true|true|true|-From Web
This code :
//Get The Value from Text Box To list of Strings
string[] lst = TxtCookie.Text.Split(',');
//Divide each element into a set of values
var D = (from a in lst select a.Split('|')).ToList();
//Define an object from the class
TblInvoiceContent tblInvoiceContent = new TblInvoiceContent();
//Define an List from the class
List<TblInvoiceContent> TBLIC = new List<TblInvoiceContent>();
//Here I take the values and configure them according to the class structure
foreach (var item in D)
{
tblInvoiceContent.ItremID = Convert.ToInt32(item[1]);
tblInvoiceContent.SilingPrice = Convert.ToDouble(item[2]);
tblInvoiceContent.Quantity = Convert.ToInt32(item[3]);
tblInvoiceContent.mayonnaise = Convert.ToBoolean(item[4]);
tblInvoiceContent.ketchup = Convert.ToBoolean(item[5]);
tblInvoiceContent.Hot = Convert.ToBoolean(item[6]);
tblInvoiceContent.garlic = Convert.ToBoolean(item[7]);
tblInvoiceContent.Reqomindition = item[8].ToString();
//Here I add the item to the list
TBLIC.Add(tblInvoiceContent);
}
//Here I am displaying the list items
GridView1.DataSource = TBLIC;
GridView1.DataBind();
Result :
Because you only ever create one instance of your object:
TblInvoiceContent tblInvoiceContent = new TblInvoiceContent();
Then in the loop you modify the instance each time and re-add it to the list again.
Move the instance creation into the loop:
foreach (var item in D)
{
TblInvoiceContent tblInvoiceContent = new TblInvoiceContent();
tblInvoiceContent.ItremID = Convert.ToInt32(item[1]);
tblInvoiceContent.SilingPrice = Convert.ToDouble(item[2]);
tblInvoiceContent.Quantity = Convert.ToInt32(item[3]);
tblInvoiceContent.mayonnaise = Convert.ToBoolean(item[4]);
tblInvoiceContent.ketchup = Convert.ToBoolean(item[5]);
tblInvoiceContent.Hot = Convert.ToBoolean(item[6]);
tblInvoiceContent.garlic = Convert.ToBoolean(item[7]);
tblInvoiceContent.Reqomindition = item[8].ToString();
TBLIC.Add(tblInvoiceContent);
}
That way each time the loop iterates you would create a new instance of the object.
//Get The Value from Text Box To list of Strings
string[] lst = TxtCookie.Text.Split(',');
//Divide each element into a set of values
var D = (from a in lst select a.Split('|')).ToList();
//Define an List from the class
List<TblInvoiceContent> TBLIC = new List<TblInvoiceContent>();
//Here I take the values and configure them according to the class structure
foreach (var item in D)
{
//CALL IT HERE Define an object from the class
TblInvoiceContent tblInvoiceContent = new TblInvoiceContent();
tblInvoiceContent.ItremID = Convert.ToInt32(item[1]);
tblInvoiceContent.SilingPrice = Convert.ToDouble(item[2]);
tblInvoiceContent.Quantity = Convert.ToInt32(item[3]);
tblInvoiceContent.mayonnaise = Convert.ToBoolean(item[4]);
tblInvoiceContent.ketchup = Convert.ToBoolean(item[5]);
tblInvoiceContent.Hot = Convert.ToBoolean(item[6]);
tblInvoiceContent.garlic = Convert.ToBoolean(item[7]);
tblInvoiceContent.Reqomindition = item[8].ToString();
//Here I add the item to the list
TBLIC.Add(tblInvoiceContent);
}
//Here I am displaying the list items
GridView1.DataSource = TBLIC;
GridView1.DataBind();

Object data being overwritten after creation

I am self teaching myself C# and was hoping somebody could point out what it is that I am doing wrong. I am attempting to iterate through some XML data and create objects when I get a match.
My sequence of events are
Using the foreach, iterate through until i see a specific data match
When I see a pattern1 match clear down my lists in readiness to populate them
From now on everytime we see a certain pattern match update the lists
When I see a pattern5 match create the object with the populated lists
The foreach continues
Keep iterating through until we see a pattern1 match again
Repeat from step 2
My object gets created with the populated lists in Step 4 but is subsequently overwritten when we repeat in step 2.
class XMLData {
public static List<Device> Search(XElement XE)
{
//local variables
bool DeviceCreated = false;
List<Device> Devices = new List<Device>();
string Out = "";
List<int> List1 = new List<int>();
List<int> List2 = new List<int>();
List<int> List3 = new List<int>();
IEnumerable<XElement> Logic =
from LL in XE.Descendants("Text")
select LL;
foreach (XElement XML in Logic)
{
//Regex Patterns
string pattern1 = #"(?=O\()[^\)]+(?<=S)";
string pattern2 = #"(?=O\()[^\)]+(?<=I)";
string pattern3 = #"(?=O\()[^\)]+(?<=FA)";
string pattern4 = #"(?=X\()[^\)]+(?<=F)";
string pattern5 = #"(?=O\()[^\)]+(?<=L)";
string pattern6 = #"(?=O\()[^\)]+(?<=FT).+?(?<=)";
MatchCollection All = Common.Find(XML);
if (Regex.Match(XML.Value, pattern1).Success)
{
//Clear down data ready to create a new device
DeviceCreated = false;
List1.Clear();
List2.Clear();
List3.Clear();
List1 = Common.Find(All);
}
else if (Regex.Match(XML.Value, pattern2).Success)
{
List2 = Common.Find(All);
}
else if (Regex.Match(XML.Value, pattern3).Success)
{
List3 = Common.Find(All);
}
else if (Regex.Match(XML.Value, pattern5).Success)
{
// create a device when we see this pattern as we should now have all of the data in the lists
if (!DeviceCreated)
{
Devices.Add(new Device(List1, List2, List3));
DeviceCreated = true;
}
}
else
{
//nothing
}
}
return Devices;
}
}
When you do List1 = Common.Find(All), List2 = Common.Find(All) etc, it simply overwrites the existing list.
Do an append, or in C# terms, an AddRange():
List1.AddRange(Common.Find(All));

Passing multiple line items with GP webservice

Below is the code I'm working with to pass multiple line items to create sales order through GP Web service. I can pass single Line Item without any problem , but when I pass multiple Items it is only taking the last one. The array has around 5 Item ID and I'm passing fixed Quantity as 15, Need to make both dynamic. But for the testing purpose I'm trying like this. I know the problem with the creation/initialization of some web service objects. As novice to the entire set of things I couldn't find the exact problem.
C# Code
CompanyKey companyKey;
Context context;
SalesOrder salesOrder;
SalesDocumentTypeKey salesOrderType;
CustomerKey customerKey;
BatchKey batchKey;
// SalesOrderLine salesOrderLine;
ItemKey orderedItem;
Quantity orderedAmount;
Policy salesOrderCreatePolicy;
DynamicsGPClient wsDynamicsGP = new DynamicsGPClient();
wsDynamicsGP.ClientCredentials.Windows.ClientCredential.UserName = "Admin";
wsDynamicsGP.ClientCredentials.Windows.ClientCredential.Password = "pass";
wsDynamicsGP.ClientCredentials.Windows.ClientCredential.Domain = "Gp";
System.ServiceModel.WSHttpBinding binding;
binding = new System.ServiceModel.WSHttpBinding(System.ServiceModel.SecurityMode.None);
context = new Context();
companyKey = new CompanyKey();
companyKey.Id = (1);
context.OrganizationKey = (OrganizationKey)companyKey;
salesOrder = new SalesOrder();
salesOrderType = new SalesDocumentTypeKey();
salesOrderType.Type = SalesDocumentType.Order;
salesOrder.DocumentTypeKey = salesOrderType;
customerKey = new CustomerKey();
customerKey.Id = "121001";
salesOrder.CustomerKey = customerKey;
batchKey = new BatchKey();
batchKey.Id = "RMS";
salesOrder.BatchKey = batchKey;
// SalesOrderLine[] orders = new SalesOrderLine[6];
SalesOrderLine[] lines = { };
for (int i = 1; i < 5; i++)
{
SalesOrderLine salesOrderLine = new SalesOrderLine();
orderedItem = new ItemKey();
orderedItem.Id = Arr[i].ToString();
salesOrderLine.ItemKey = orderedItem;
orderedAmount = new Quantity();
orderedAmount.Value = 15;
salesOrderLine.Quantity = orderedAmount;
lines = new SalesOrderLine[] { salesOrderLine };
MessageBox.Show(lines.Count().ToString());
}
salesOrder.Lines = lines;
//salesOrder.Lines = orders;
salesOrderCreatePolicy = wsDynamicsGP.GetPolicyByOperation("CreateSalesOrder", context);
wsDynamicsGP.CreateSalesOrder(salesOrder, context, salesOrderCreatePolicy);
if (wsDynamicsGP.State != CommunicationState.Faulted)
{
wsDynamicsGP.Close();
}
MessageBox.Show("Success");
lines = new SalesOrderLine[] { salesOrderLine }; will recreate the lines array object each time meaning you loose any previously added objects. Effectively only the final object in the loop is actually added.
Try using a List<T> like so:
SalesOrderLine[] lines = { }; Becomes List<SalesOrderLine> lines = new List<SalesOrderLine>();
lines = new SalesOrderLine[] { salesOrderLine }; Becomes: lines.Add(salesOrderLine);
If its important you end up with an array as the input:
salesOrder.Lines = lines; Becomes: salesOrder.Lines = lines.ToArray();

create NetSuite ItemFulfillment containg items with lot/serial info

I am using SuiteTalk web services (v. 2013_2) . I am trying to create an ItemFulfillment where the items in it were related to items that had a lot or serial number.
When I try to save this item fulfillment into NetSuite I get an error of :
Please commit inventorydetail on this line.
I was attempting to set the itemFulfillment.serialNumbers and itemFulfillment.binNumbers when I create the itemFulfillmentItem.
For example I set
nsIfItem.serialNumbers = "SNum(5)"
nsIfItem.binNumbers = "BNum(5)"
based on those properties being- A comma delimited list of serial or LOT numbers. If entering serial numbers there must be a number for each item.
Lot numbers must be entered in a format of LOT#(Quantity).
For example, to enter a quantity of 100 items as Lot number ABC1234, enter ABC1234(100).
Do I also need to set something else on the itemFulfillment or how do I get rid of that error.
I'm not sure if this question is still active, but I had the same issue and iI couldn't find much help on it. I solved this issue by creating the inventory assignment objects and adding to the transaction.
First, create the initialize ref for Item Fulfillment and assign the returned record to a variable:
InitializeRecord ir = new InitializeRecord();
ir.type = InitializeType.itemFulfillment;
InitializeRef iref = new InitializeRef();
iref.typeSpecified = true;
iref.type = InitializeRefType.salesOrder;
iref.internalId = 'Sales Order internalID';
ir.reference = iref;
ReadResponse getInitResp = _service.initialize(ir);
ItemFulfillment ifrec = (ItemFulfillment)getInitResp.record;
Get the list of items on the initialized transaction:
ItemFulfillmentItemList ifitemlist = ifrec.itemList;
Create a list to which to add each unique item being fulfilled:
List<ItemFulfillmentItem> ifitems = new List<ItemFulfillmentItem>();
Run the following code for each item in initialized transaction's item list:
If the current line item has already been added to the ifitems list, add the current Fulfillment line as an assignment to that item:
InventoryAssignment assignment = new InventoryAssignment
{
issueInventoryNumber = new RecordRef { internalId = 'internalID',
type = 'RecordType',
typeSpecified = true
}
};
List<InventoryAssignment> list = new List<InventoryAssignment>();
list.Add(assignment);
ifitemlist.item[b].inventoryDetail = new InventoryDetail
{
inventoryAssignmentList = new InventoryAssignmentList
{
inventoryAssignment = list.ToArray()
}
};
ifitemlist.item[b].quantity += 'quantity shipped';
If the line item has not yet been added, create new line item:
ItemFulfillmentItem ffItem = new ItemFulfillmentItem();
ffItem.item = ifitemlist.item[b].item;
ffItem.itemReceive = true;
ffItem.itemReceiveSpecified = true;
ffItem.itemIsFulfilled = true;
itemIsFulfilled = true;
ffItem.itemIsFulfilledSpecified = true;
ffItem.orderLineSpecified = true;
ffItem.orderLine = ifitemlist.item[b].orderLine;
//Check if serialized
if (Your fulfillment item contains serialized data)
{
ffItem.serialNumbers = 'Serial numbers';
InventoryAssignment assignment = new InventoryAssignment
{
issueInventoryNumber = new RecordRef {
internalId = 'Inventory internal ID',
type = RecordType,
typeSpecified = true
}
};
ffItem.inventoryDetail = new InventoryDetail
{
inventoryAssignmentList = new InventoryAssignmentList
{
inventoryAssignment = new InventoryAssignment[]
{
assignment
},
replaceAll = false
},
nullFieldList = new string[] { },
customForm = new RecordRef { }
};
}
ffItem.quantity = 'QUANTITY SHIPPED';
ffItem.quantitySpecified = true;
ifitems.Add(ffItem);
Finally, add your "ifitems" list to your Item Fulfillment and add this to NetSuite:
ItemFulfillmentItemList ifitemlistToFulfill = new ItemFulfillmentItemList();
ifitemlistToFulfill.replaceAll = false;
ifitemlistToFulfill.item = ifitems.ToArray();
ItemFulfillment newItemFulfill = new ItemFulfillment();
newItemFulfill.itemList = ifitemlistToFulfill;
_service.add(newItemFulfill);

How to get a specific field of list of objects in an array of strings

I have a list of persons like this :
foreach (GridViewRow r in gv_contactList.Rows)
{
Person p = new Person();
p.Id = int.Parse(gv_contactList.DataKeys[r.RowIndex].Value.ToString());
p.Name = r.Cells[1].Text.TrimEnd();
p.Mobile = r.Cells[2].Text.TrimEnd();
p.Email = r.Cells[3].Text.TrimEnd();
p.Pkind = 1;//ToDo
plst.Add(p);
}
How to get an array of mobile numbers in string[]
in the same previous loop where the mobile number is not null or empty .
instead of looping again through the list of persons to put the mobile numbers in the array.
Not really sure what you want. But if you want an array of string phone numbers from your Person List plst you can do:
string[] phoneArray = plist
.Where(r=>string.IsNullOrWhiteSpace(r.Mobile))
.Select(r=>r.Mobile.ToString())
.ToArray();
var mobiles = new List<string>();
foreach (GridViewRow r in gv_contactList.Rows)
{
...
p.Mobile = r.Cells[2].Text.TrimEnd();
if (!String.IsNullOrEmpty(p.Mobile)) {
mobiles.Add(p.Mobile);
}
...
}
var mobilesArray = mobiles.ToArray();
Declare an ArrayList before foreach:
ArrayList<String> mobNums = new ArrayList<String>();
within foreach add the mobile no. to it:
mobNums.Add(p.Mobile);
After foreach change it to Array:
String[] arr = mobNums.ToArray();
Assuming plst is already existing:
var plst = ...
var persons = from GridViewRow r in gv_contactList.Rows
select new Person {
Id = int.Parse(gv_contactList.DataKeys[r.RowIndex].Value.ToString()),
Name = r.Cells[1].Text.TrimEnd(),
Mobile = r.Cells[2].Text.TrimEnd(),
Email = r.Cells[3].Text.TrimEnd(),
Pkind = 1,
};
var mobiles = persons.Aggregate(new List<string>(), (acc, cur) =>
{
plst.Add(cur);
if (!string.IsNullOrEmpty(cur.Mobile))
acc.Add(cur.Mobile);
return acc;
}).ToArray();
The enumeration happens just once.

Categories

Resources