Create 2 or more text files with ASP.NET - asp.net

I have created a web app which creates 1 text file. Inside this text file it is created 1000 rows with the same word "TRY AGAIN". After this each 50 rows I put a random code which means in 1000 rows, 20 rows are random.
This is my code:
static Random randNum = new Random();
public static string Random(int ran)
{
string _charachters = "ABCDEFGHIJKMLNOPQRSTUVWXYZ0123456789";
char[] chars = new char[ran];
int allowedCharCount = _charachters.Length;
for (int i = 0; i < ran; i++)
{
chars[i] = _charachters[(int)((_charachters.Length) * randNum.NextDouble())];
}
return new string(chars);
}
protected void Button1_Click(object sender, EventArgs e)
{
string pathCreate = #"C:\" + TextBox3.Text + ".txt";
if (!File.Exists(pathCreate))
{
using (StreamWriter sw = File.CreateText(pathCreate))
{
for (int i = 1; i <= int.Parse(TextBox1.Text); i++)
{
sw.WriteLine("TRY AGAIN.");
}
}
}
string pathRandom = #"C:\" + TextBox3.Text + ".txt";
string[] lines = File.ReadAllLines(pathRandom);
for (int i = 0; i < lines.Length; i += int.Parse(TextBox2.Text))
{
lines[i] = lines[i].Replace("TRY AGAIN.", Random(int.Parse("7")));
}
File.WriteAllLines(pathRandom, lines);
}
Now I want to create 2 ore more text files with one click of a button. And on each text file there will be random codes (not duplicates). Any idea?
Thank You.

I found the solution. It is late in my country and my brain barely works. :P
for(int j = 1; j <= 10; j++)
{
string pathKrijo = #"C:\inetpub\wwwroot\KODET\" + j.ToString() + ".txt";
using (StreamWriter sw = File.CreateText(pathKrijo))
{
for (int i = 1; i <= 100; i++)
{
sw.WriteLine("Provo Përsëri.");
}
}
string pathKodFitues = #"C:\inetpub\wwwroot\KODET\" + j.ToString() + ".txt";
string[] lines = File.ReadAllLines(pathKodFitues);
for (int i = 0; i < lines.Length; i += 10)
{
lines[i] = lines[i].Replace("Provo Përsëri.", Random(int.Parse("7")));
}
File.WriteAllLines(pathKodFitues, lines);
}

Related

How to solve this Range Error in my code?

I'm trying to create an cipher app on android studio using flutter. Right now I'm working on a simple Atbash Cipher, but I get a range error when trying to test it. These are the encrypt and decrypt codes:
#override
String encrypt(String plaintext, {String key}) {
String alfa = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String alfaReverso = "";
for(int i = alfa.length-1; i > -1; i++){
alfaReverso += alfa[i];
}
String encryText = "";
for (int i = 0; i < plaintext.length; i++){
if(plaintext.codeUnitAt(i) == 32){
encryText += " ";
}
else{
int count = 0;
for(int j = 0; j < alfa.length; j++){
if(plaintext[i] == alfa[j]){
encryText += alfaReverso[j];
break;
}
}
}
}
return "ENCRYPT Plain = " + encryText;
}
}
#override
String decrypt(String cyphertext, {String key}) {
String alfa = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String alfaReverso = "";
for(int i = alfa.length-1; i > -1; i++){
alfaReverso += alfa[i];
}
String dencryText = "";
for (int i = 0; i < cyphertext.length; i++){
if(cyphertext.codeUnitAt(i) == 32){
dencryText += " ";
}
else{
int count = 0;
for(int j = 0; j < alfaReverso.length; j++){
if(cyphertext[i] == alfaReverso[j]){
dencryText += alfa[j];
break;
}
}
}
}
return "ENCRYPT Plain = " + dencryText;
}
When trying to run it this is the range exception I get:
I/flutter ( 6004): RangeError (index): Invalid value: Not in range 0..25, inclusive: 26
I know it has something to do with the alphabetI'm using, but I don't know how to solve it.
There is an error when you start from the highest index:
for(int i = alfa.length-1
Your index has to go down and you are using ++.
Use this:
for(int i = alfa.length-1; i > -1; i--)

ASP.NET - Input string was not in a correct format

I am getting an error saying my input string was not in a correct format when I try to get, multiply and display I stored data's in cookies.
It says there was an error in a part in total = total + (Convert.ToInt32(a[2].ToString()) * Convert.ToInt32(a[3].ToString()));
Somebody help me please. Here is my code:
protected void Page_Init(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[7] { new DataColumn("product_name"), new DataColumn("product_desc"), new DataColumn("product_price"), new DataColumn("product_qty"), new DataColumn("product_images"), new DataColumn("id"), new DataColumn("product_id") });
if (Request.Cookies["aa"] != null)
{
s = Convert.ToString(Request.Cookies["aa"].Value);
string[] strArr = s.Split('|');
for (int i = 0; i < strArr.Length; i++)
{
t = Convert.ToString(strArr[i].ToString());
string[] strArr1 = t.Split(',');
for (int j = 0; j < strArr1.Length; j++)
{
a[j] = strArr1[j].ToString();
}`enter code here`
dt.Rows.Add(a[0].ToString(), a[1].ToString(), a[2].ToString(), a[3].ToString(), a[4].ToString(), i.ToString(), a[5].ToString());
total = total + (Convert.ToInt32(a[2].ToString()) * Convert.ToInt32(a[3].ToString()));
totalcount = totalcount + 1;
cart_items.Text = totalcount.ToString();
cart_price.Text = total.ToString();
}
}
I recomment you to use int.TryParse(...) if you want to convert form string.
It could be like this:
int var2, var3 = 0;
if(int.TryParse(a[2].ToString(), out var2)
&& int.TryParse(a[3].ToString(), out var3))
{
total += (var2 * var3);
}

unable to download xlsx file using POI

Hi i working on poi poc to generate xlsx file in webapplication i was able to render excel standalone well but when i integrate codebase in my project i was getting below error.
below is code base base to download xlsx file in webapplication
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("Sheet1");
XSSFRow row = spreadsheet.createRow(0);
XSSFCell cell;
while (response.nextResultSet()) {
resultSet = response.getResultSet();
Object[] columnMetaData = resultSet.getColumnNames();
int columnCount = columnMetaData.length;
//Columns Loop
ArrayList<String> columns = new ArrayList<String>();
for (int i = 1; i < columnCount; i++) {
String columnName = (String) columnMetaData[i];
columns.add(columnName);
cell = row.createCell(i-1);
cell.setCellValue(columnName);
}
int i=1;
while (resultSet.nextRow()) {
row = spreadsheet.createRow(i);
i++; // counter for each row of data
for (int j = 0; j < columnMetaData.length; j++)
{
String keyVal = String.valueOf(columnMetaData[j]);
String value = (String)resultSet.getValue(keyVal);
cell = row.createCell(j);
cell.setCellValue(value);
}
}
log.info("value if i--->" + i);
for (int k = 1; k < columnCount; k++) {
spreadsheet.autoSizeColumn(k-1);
}
}
ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
workbook.write(outByteStream);
context.getResponse().setHeader("content-disposition", "inline;filename=" + calendar.getTimeInMillis() + ".xlsx");
context.getResponse().setContentType("application/Excel");
context.getRequest().setAttribute("called_from", "excel");
//context.getResponse().setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//context.getResponse().setHeader("Content-Disposition", "attachment; filename=testxls.xlsx");
}
OutputStream os = null;
os = context.getResponse().getOutputStream();
byte [] outArray = is.toByteArray();
context.getResponse().setContentLength(outArray.length);
os.write(outArray);
log.info(os.toString());
os.flush();

Why the line XXX showing an error saying java.lang.ArrayIndexOutOfBoundsException?

//Firstly I need to create a 2-D array of floating points(randomly generated) and store them in a text file no of rows and columns are user input
import java.io.;
import java.util.;
public class ClaransS {
public static void main(String args[]) throws IOException {
// *********************************************************************
// Variables declaration n-no.of rows k-forget it for now n_o_d-no. of
// columns
// *********************************************************************
int n, k, n_o_d;
// *********************************************************************
// Creating the text file to store data
// *********************************************************************
File f = new File("C:/x/y/clarans.text");
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
// *********************************************************************
// Taking user inputs
// *********************************************************************
Scanner userInputScanner = new Scanner(System.in);
System.out.println("Enter the no. of data you want to cluster");
n = userInputScanner.nextInt();
System.out.println(n);
System.out.println("Enter the no. of clusters you want to form");
k = userInputScanner.nextInt();
System.out.println(k);
System.out
.println("Enter the no. of dimensions each data will be in a space of");
n_o_d = userInputScanner.nextInt();
System.out.println(n_o_d);
userInputScanner.close();
// *********************************************************************
// Storing random data in the data-set
// *********************************************************************
double data_set[][] = new double[n][n_o_d];
int count = 1;
int i = 0;
int j = 1;
for (i = 0; i < n; i++) {
data_set[i][0] = count;
for (j = 1; j <= n_o_d; j++) {
//THIS LINE GIVES ERROR
data_set[i][j] = (double) Math.random();//YES THIS ONE XXX
}
count++;
}
for (i = 0; i < n; i++) {
for (j = 0; j <= n_o_d; j++) {
try (PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(f, true)))) {
out.print(data_set[i][j] + "\t");
} catch (IOException e) {
}
}
try (PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(f, true)))) {
out.println();
}
}
}
}
The error is in test condition of for
(j = 1; j <= n_o_d; j++).
Test condition will be j < n_o_d

saving data from datagrid c#

hi guys i am new to c# and i was making a text editor program using data grid view. The problem is when i open a text file to my data grid, then when i press save i get the error saying "Index was outside the bounds of the array". I included my code below. Any suggestions can be a big help for me. I included my code below.
// edit file button
dataGridView1.Columns.Add("colname", "Question");
dataGridView1.Columns.Add("colname", "Answer 1");
dataGridView1.Columns.Add("colname", "Answer 2");
dataGridView1.Columns.Add("colname", "Answer 3");
dataGridView1.Columns.Add("colname", "Answer 4");
dataGridView1.Columns.Add("colname", "Correct Answer");
dataGridView1.Columns[5].ReadOnly = true;
dataGridView1.Columns[5].DefaultCellStyle.BackColor = Color.DimGray;
dataGridView1.AllowUserToAddRows = true;
StreamReader sr = new StreamReader(fName);
string Contents = sr.ReadToEnd();
string[] strArray = { Contents };
for (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
{
for (int c = 0; c <= dataGridView1.Columns.Count - 1; c++)
{
dataGridView1.Rows.Add(strArray[r].Split('|')); //getting the error here
}
}
//save button
private void button2_Click(object sender, EventArgs e)
{
//dataGridView1.AllowUserToAddRows = false;
if (dataGridView1.Visible)
{
string fName = "C:\\Documents and Settings\\" + txtFileName.Text + ".txt";
System.IO.StreamWriter file = new System.IO.StreamWriter(fName);
string sLine = "";
for (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
{
for (int c = 0; c <= dataGridView1.Columns.Count - 1; c++)
{
sLine = sLine + dataGridView1.Rows[r].Cells[c].Value;
if (c != dataGridView1.Columns.Count - 1)
{
sLine = sLine + "|";
}
}
file.WriteLine(sLine);
sLine = "";
}
file.Close();
System.Windows.Forms.MessageBox.Show("Save Complete.", "Program Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
dataGridView1.DataSource = "";
dataGridView1.Visible = false;
}
else
{
string cap = "Confirmation";
string message = "Nothing to save";
MessageBoxButtons Btn2 = MessageBoxButtons.OK;
MessageBox.Show(message, cap, Btn2);
}
}
Thanks again for the help
Initially there is a dataGridView1.Rows.Count
Inside the loop u r doing this
dataGridView1.Rows.Add, which increments dataGridView1.Rows.Count by 1 every single time
so it comes back into the loop after the processing
try declaring int gridRowcount = dataGridView1.Rows.Count;
and then replace (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
for (int r = 0; r <= gridRowcount - 1; r++) and try
just guessing

Resources