private void Form1_Load(object sender, EventArgs e)
{
string filePath =
#"C:\Users\User\Documents\flower.txt";
List<string> lines =
File.ReadAllLines(filePath).ToList();
int count = lines.Count();
Random rnd = new Random();
//label1.Text = rnd.Next().ToString();
QuestionsWithAnswer qtn = new.
QuestionsWithAnswer();
string[] line = lines[count - 1].Split(',');
lblQuestion.Text = qtn.question1 = line[0];
radOpt1.Text = qtn.opt1 = line[1];
radOpt2.Text = qtn.opt2 = line[2];
radOpt3.Text = qtn.opt3 = line[3];
radOpt4.Text = qtn.opt4 = line[4];
radOpt5.Text = qtn.opt5 = line[5];
radOpt4.Checked = true;
label1.Text = rnd.Next(count).ToString();
}
I am developing a multiple choice application. This app reads from a text file for its question and options. I want the questions to be generated randomly. The code is working but it's bring same question whenever I load the app the first time even with my random class.
Probably you meant ordering the questions randomly. An easy way would be:
List<string> lines = File
.ReadAllLines(filePath)
.OrderBy(x => Guid.NewGuid()).ToList();
Note: Why wouldn't you use a database instead of a text file.
Related
I have this program where I want to create a button base from Products on my database(ProductTbl). I found a way to do that
Here's the code:
public void DynamicButton() //Function for retrieving record and creating a button for each product
{
string select = "select ProductID,ProductDesc,ProductPrice,ProductPic from ProductTbl" ;
sda = new SqlDataAdapter(select,sqlConn);
sda.Fill(dataTable);
for (int i = 0; i < dataTable.Rows.Count; i++)
{
ExtendedButton prodBtn = new ExtendedButton(); //with ExtendedButton this time
prodBtn._itemName = dataTable.Rows[i][1].ToString();//this asigns the product name to the extended button
prodBtn._itemID = Convert.ToInt32(dataTable.Rows[i][0]);
prodBtn._myPrice = Convert.ToDecimal(dataTable.Rows[i][2]);
prodBtn.BackgroundImageLayout = ImageLayout.Stretch;
prodBtn.Click += new EventHandler(OnButtonClick);
prodBtn.Height = 100;
prodBtn.Width = 100;
System.Drawing.Font f1 = SystemFonts.DefaultFont;
prodBtn.Font = new System.Drawing.Font(f1.FontFamily,f1.Size,FontStyle.Bold);
prodBtn.Text = dataTable.Rows[i][1].ToString();
prodBtn.TextAlign = ContentAlignment.BottomCenter;
prodBtn.ForeColor = Color.White;
prodBtn.BackgroundImageLayout = ImageLayout.Zoom;
toolTip1.Show(prodBtn.Text, prodBtn);
byte[] image = (byte[])dataTable.Rows[i][3];
prodBtn.BackgroundImage = imgConverter.byteArrayToImage(image);
prodBtn.TextAlign = ContentAlignment.MiddleCenter;
flowPanel.Controls.Add(prodBtn);
}
}
//You can see this at codeproject
Now the problem is that whenever i add a product on that table using Stored procedure. I don't know how i can sync updates to the datatable that I use with this one. Any ideas and suggestion will be highly appreciated. Thanks sorry for the long post
You can use ASP.Net Caching with SqlCacheDependency.
See this page for details:
https://msdn.microsoft.com/en-us/library/ms178604.aspx
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.
When the add button is clicked second time, there is supposed to be two lines of data rows in the GridView ( the first row is the first click and the second row is the newly added data). However there is only one data row.
List<DonationReceivedItem> drList = new List<DonationReceivedItem>();
protected void lbnAdd_Click(object sender, EventArgs e)
{
DonationReceivedItem temp = new DonationReceivedItem();
temp.donation = dID;
temp.productVariant = gvSelectVairant.SelectedRow.Cells[1].Text;
temp.productQuantity = tbQuantity.Text;
temp.isDistributed = "0";
drList.Add(temp);
gvNonExpired.DataSource = drList;
gvNonExpired.DataBind();
}
Try changing the following code:
DonationReceivedItem temp = new DonationReceivedItem();
temp.donation = dID;
temp.productVariant = gvSelectVairant.SelectedRow.Cells[1].Text;
temp.productQuantity = tbQuantity.Text;
temp.isDistributed = "0";
drList.Add(temp);
gvNonExpired.DataSource = drList;
gvNonExpired.DataBind();
to:
DonationReceivedItem temp = new DonationReceivedItem();
drList = gvNonExpired.DataSource;
temp.donation = dID;
temp.productVariant = gvSelectVairant.SelectedRow.Cells[1].Text;
temp.productQuantity = tbQuantity.Text;
temp.isDistributed = "0";
drList.Add(temp);
gvNonExpired.DataSource = drList;
gvNonExpired.DataBind();
See if that makes a difference :)
Because you are creating a new list you are wiping the previous data. First instantiate the list with the old data, then add the new data.
With the below code I'm able to process the requests one by one. This is an asynchronous process so I don't need to get a response. I am only passing the requests.
class Program
{
static void Main(string[] args)
{
ProfileRequestData();
}
private static void ProfileRequestData()
{
ProfileRequest.Request[] req = new ProfileRequest.Request[4];
//req.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
req[0] = new ProfileRequest.Request();
req[1] = new ProfileRequest.Request();
req[2] = new ProfileRequest.Request();
req[3] = new ProfileRequest.Request();
req[0].Record = new ProfileRequest.RequestRecord();
req[1].Record = new ProfileRequest.RequestRecord();
req[2].Record = new ProfileRequest.RequestRecord();
req[3].Record = new ProfileRequest.RequestRecord();
req[0].Record.Id = "asdasd123";
req[1].Record.Id = "asdasd456";
req[2].Record.Id = "asdasd789";
req[3].Record.Id = "addjlk123";
ProfileRequest.ProfileRequestClient serviceClient = new ProfileRequest.ProfileRequestClient();
serviceClient.ClientCredentials.UserName.UserName = #"Liberty\nzy0105";
serviceClient.ClientCredentials.UserName.Password = "abcddf";
serviceClient.ProfileRequest(req[0]);
serviceClient.ProfileRequest(req[1]);
serviceClient.ProfileRequest(req[2]);
serviceClient.ProfileRequest(req[3]);
}
}
What I want to do is to process all the requests at a time not one by one.
Can anyone, please, provide the code for the requirement???
For simultaneous jobs like this you should use a threading mechanism. Here you can use backgroundworkers.
var asyncServiceRequester = new BackgroundWorker();
asyncServiceRequester.DoWork += asyncServiceRequester_DoWork;
foreach(var request in req)
{
asyncServiceRequester.RunWorkerAsync(req);
}
this is the code snippet that you should use instead of:
serviceClient.ProfileRequest(req[0]);
serviceClient.ProfileRequest(req[1]);
serviceClient.ProfileRequest(req[2]);
serviceClient.ProfileRequest(req[3]);
and here is the DoWork method of the backgroundworker:
static void asyncServiceRequester_DoWork(object sender, DoWorkEventArgs e)
{
var request = e.Argument as ProfileRequest;//whatever your request type is
serviceClient.ProfileRequest(request);
}
UPDATE:
I am assuming that your user inputs are in a list for dynamic purposes, since you didn't gave any specific information about it. In this case you'll traverse through the list of inputs, and extract the values into your object array. Here is how you would first fill the list of inputs, then how you'll assign those values to your object array.
List<TextBox> inputs = new List<TextBox>();
inputs.Add(input1);
inputs.Add(input2);
...
inputs.Add(inputN);
If your inputs are static than this is how you do it, else;
List<TextBox> inputs = new List<TextBox>();
for(int i = 0; i < someNumber; i++)
{
inputs.Add(new TextBox(){
Text = "some text",
Location = new Point(10, i * 75),
Height = 60,
Width = 150,
Font = new Font(ActiveControl.Font.FontFamily, 10, FontStyle.Regular)
});
}
Rest is pretty straightforward;
var index = 0;
foreach(var tb in inputs)
{
var newReq = new ProfileRequest.Request(){
Record = new ProfileRequest.RequestRecord(){
Id = tb.Text
}
}
req[index++] = req;
// I would suggest you to use generic lists here too since they are simpler and more flexible.
// req.Add(newReq);
}
Gathering the input from a text file or xml should be the topic of another question, but you can do them in the same manner. Just read the file, or xml then extract the values in dynamic manner.
You can create threads to process requests in parallel -
for (int i = 0; i < req.Length; i++)
{
new System.Threading.Thread(() => serviceClient.ProfileRequest(req[i])).Start();
}
I'm trying to make a small program that take the user input and store it on a file but I want that file to cap at 100 elements:
Let's say the user add 100 names and the next name the user add it will show a message "List is full"
Here is the code I have done so far:
public Form1()
{
InitializeComponent();
}
private string SongName, ArtistName;
public void Registry()
{
List<Name> MusicList = new List<Name>(); //Create a List
MusicList.Add(new Name(SongName = txtSongName.Text, ArtistName = txtArtistName.Text)); //Add new elements to the NameClass
//check if the input is correct
if (txtSongName.TextLength < 1 || txtArtistName.TextLength < 1)
{
Info info = new Info();
info.Show();
}
else //if input is correct data will be stored
{
//Create a file to store data
StreamWriter FileSaving = new StreamWriter("MusicList", true);
for (int i = 0; i < MusicList.Count; i++)
{
string sName = MusicList[i].songName; //Create new variable to hold the name
string aName = MusicList[i].artistName; //Create new variable to hold the name
FileSaving.Write(sName + " by "); //Add SongName to the save file
FileSaving.WriteLine(aName); //Add ArtistName to the save file
}
FileSaving.Close();
}
}
private void btnEnter_Click(object sender, EventArgs e)
{
Registry();
//Set the textbox to empty so the user can enter new data
txtArtistName.Text = "";
txtSongName.Text = "";
}
private void btnClose_Click(object sender, EventArgs e)
{
Application.Exit();
}
private const int MAX_STORED_SONGS = 100;//as class level field
for (int i = 0; i < MusicList.Count && i < MAX_STORED_SONGS; i++)
//...after the loop
if( MusicList.Count > MAX_STORED_SONGS )
errorMessageLabel.Text = "List is full, only 100 items added"
I'm not sure what your list picker looks like, but you would probably want to actually prevent them from selecting more than 100 items, by using some javascript/validation client side before the page is submitted.
What is not clear about your code, is while it appears the user submits a single song, you create a new empty MusicList, add a single item to it, but you loop through it as if there is more than one item. Perhaps you should begin by reading the file to determine how many songs are in it, so you can determine when it is at 100 songs.
You may wish to try using xml to give your data some structure.
If you want to keep it in the current format your only option is to count NewLines in your file and see if that count plus any new items in your music list puts you over your limit.
List<string> lines = new List<string>(System.IO.File.ReadAllLines(MyFile));
lines.Add(sName + " by " + aName);
int lineCount = lines.Count;
//limit reached
if(lineCount > 100 )
{
//TODO: overlimit code
} else {
System.IO.File.WriteAllLines(MyFile, lines.ToArray());
}