c#: Random Choose from web and ignore blank lines - c#

I'm fresh in c# forms i have an important question.
I want to make randomly text writer one line from url "list"
Let Me explain, i wanna to get a random line from pastebin, and rename a label with the random line chosed, and ignore blank lines.
This is a error:
Severity Code Description Project File Line Suppression State
Error CS0103 The name 'randomline' does not exist in the current context SNPCorp C:\Users\GhostStru\Desktop\SNP\Tester\Generator.cs 45 Active
i have that code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net.Security;
using System.Threading;
using System.Net.Http;
using System.Web;
using System.Net.WebSockets;
using System.Net;
using System.IO;
namespace Tester
{
public partial class Generator : Form
{
public Generator()
{
InitializeComponent();
}
private void Generator_Load(object sender, EventArgs e)
{
WebClient web = new WebClient();
string text = web.DownloadString("https://pastebin.com/raw/test");
var lines = text.Split(new string[] { "." }, StringSplitOptions.None);
Random rnd = new Random();
int randomLineIndex = rnd.Next(0, lines.Count());
var randomline = lines[randomLineIndex];
}
private void button3_Click(object sender, EventArgs e)
{
label11 = (randomline);
}
}
}

Your question has some things that aren't clear but I'll try with it. First, I define a method to get a random line:
private static string GetRandomLine()
{
using (var web = new WebClient())
{
var html = web.DownloadString("https://pastebin.com/raw/test");
var lines = html.Split(new string[] { "." }, StringSplitOptions.None);
var rnd = new Random();
int index = rnd.Next(0, lines.Length);
return lines[index];
}
}
Then, you can use that method to set Text property of your label. You must set the Text property, not the label variable
private void button3_Click(object sender, EventArgs e)
{
label11.Text = GetRandomLine();
}
The DownloadString is not working for me. Is that the Url? In any case, if you use a lot this method, is interesting save into a variable the HTML and use it some time (one hour... depending of your needs) as a cache instead of make a request each time. WebClient implements IDisposable so you must invoke Dispose after use it or allow to "using" do it automatically.

I'll try to answer your question even though you haven't explained some points clearly.
Create a function to return the random line
In button3_Click event, call a function that will return a random line, then set the text value of button3 to that returned value.
public static string GetRanLine()
{
using (var WC = new WebClient())
{
var Response = WC.DownloadString("https://pastebin.com/raw/test");
var AllLines = Response.Split(new string[] { "."}, StringSplitOptions.None);
var RanLine = AllLines[new Random().Next(0, AllLines.Length - 1)];
return RanLine;
}
}
private void button3_Click(object sender, EventArgs e)
{
label11 = GetRanLine();
}

Related

Access to file denied in C# .NET 3.1 forms

Hello I was writing a basic text editor in C# on visual studio windows form using the .NET framework 3.1 long term support version everything worked fine until I wrote the save file script
Here's the code for "Form1.cs" which is where the open and save file functions reside
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Security.Principal;
namespace Text_Editor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string locsave;
private void openbtn_Click(object sender, EventArgs e)
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
if (principal.IsInRole(WindowsBuiltInRole.Administrator) != true)
{
MessageBox.Show("Run as Admin");
System.Windows.Forms.Application.ExitThread();
}
else
{
OpenFileDialog openfile = new OpenFileDialog();
if (openfile.ShowDialog() == DialogResult.OK)
{
var locationArray = openfile.FileName;
string location = "";
locsave = locationArray;
foreach (char peice in locationArray)
{
location = location + peice;
}
var contentArray = File.ReadAllText(location);
string content = "";
label4.Text = location;
foreach (char peice in contentArray)
{
content = content + peice;
}
richTextBox1.Text = content;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine("Test");
}
private void savebtn_Click(object sender, EventArgs e)
{
if (#label4.Text == "")
{
MessageBox.Show("Open a text file first");
}
else
{
StreamWriter outputfile = new StreamWriter(locsave);
outputfile.Write(richTextBox1.Text); //this is where the error occures and it throws the error of access denyed
outputfile.Close();
}
}
}
}
Does anyone have a suggestion about what to do I looked around on google for a solution but it seemed most did not work and some others I did not understand.

Vlc.dotnet.form pause video with a button

I am hoping someone can help me in getting an issue of mine to work, I feel as if it is an easy one, however not having any luck in fixing what I am trying to do. I want to be able to pause a video which I am playing using vlc.dotnet below is a brief summary of the structure of my code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;
using Vlc.DotNet.Forms;
using System.Threading;
using Vlc.DotNet.Core;
using System.Diagnostics;
namespace TS1_C
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
button8.Click += new EventHandler(this.button8_Click);
}
void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
string chosen = listBox1.SelectedItem.ToString();
string final = selectedpath2 + "\\" + chosen; //Path
playfile(final);
}
void playfile(string final)
{
var control = new VlcControl();
var currentAssembly = Assembly.GetEntryAssembly();
var currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName;
// Default installation path of VideoLAN.LibVLC.Windows
var libDirectory = new DirectoryInfo(Path.Combine(currentDirectory, "libvlc", IntPtr.Size == 4 ? "win-x86" : "win-x64"));
control.BeginInit();
control.VlcLibDirectory = libDirectory;
control.Dock = DockStyle.Fill;
control.EndInit();
panel1.Controls.Add(control);
control.Play();
}
private void button8_Click(object sender, EventArgs e)
{
}
}
}
As you can see I have one method which takes a double click from an item in a list box and plays it using the method playfile. However I want to be able to pause the video using my button known as button8. I have tried many things even this
control.Paused += new System.EventHandler<VlcMediaPlayerPausedEventArgs>(button8_Click);
Which I put into the playfile method, however nothing seems to work. I am wondering if my whole method in which I play a file using playfile(); is completely wrong. I am hoping someone can help me in trying to achieve what I need
Thank you
Your control should be initialized only once:
private VlcControl control;
public Form1()
{
InitializeComponent();
control = new VlcControl();
var currentAssembly = Assembly.GetEntryAssembly();
var currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName;
// Default installation path of VideoLAN.LibVLC.Windows
var libDirectory = new DirectoryInfo(Path.Combine(currentDirectory, "libvlc", IntPtr.Size == 4 ? "win-x86" : "win-x64"));
control.BeginInit();
control.VlcLibDirectory = libDirectory;
control.Dock = DockStyle.Fill;
control.EndInit();
panel1.Controls.Add(control);
}
then, your play method could be simplified:
void playfile(string url)
{
control.Play(url);
}
And for your pause method:
private void button8_Click(object sender, EventArgs e)
{
control.Pause();
}

ArgumentException "parameter is incorrect"

I'm trying to make a code that converts memorystream to a png image, but I'm getting a ArgumentException "parameter is incorrect" error on using(Image img = Image.FromStream(ms)). It doesn't specify it any further so I don't know why I'm getting the error and what am I supposed to do to it.
Also, how do I use the Width parameter with img.Save(filename + ".png", ImageFormat.Png);? I know I can add parameters and it recognizes "Width", but I have no idea how it should be formatted so visual studio would accept it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
MemoryStream ms = new MemoryStream();
public string filename;
private void button1_Click(object sender, EventArgs e)
{
OpenFile();
}
private void button2_Click(object sender, EventArgs e)
{
ConvertFile();
}
private void OpenFile()
{
OpenFileDialog d = new OpenFileDialog();
if(d.ShowDialog() == DialogResult.OK)
{
filename = d.FileName;
var fs = d.OpenFile();
fs.CopyTo(ms);
}
}
private void ConvertFile()
{
using(Image img = Image.FromStream(ms))
{
img.Save(filename + ".png", ImageFormat.Png);
}
}
}
}
I suspect the problem is with how you're reading the file here:
fs.CopyTo(ms);
You're copying the content of the file into the MemoryStream, but then leaving the MemoryStream positioned at the end of the data rather than the start. You can fix that by adding:
// "Rewind" the memory stream after copying data into it, so it's ready to read.
ms.Position = 0;
You should consider what happens if you click on the buttons multiple times though... and I'd strongly advise you to use a using directive for your FileStream, as currently you're leaving it open.

When Connecting R with RdotNet It says Set Environment Variable 'PATH'

When I Run the Warning
RDotNet.NativeLibrary.UnmanagedDll.SetDllDirectory(string) is obsolete Set environment variable 'PATH' instead.
I don't know how to do that. how to set variable path please help quickly please.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RDotNet;
namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
string dlldir = #"C:\Program Files\R\R-3.1.1\bin\x64";
REngine.SetDllDirectory(dlldir);
REngine.CreateInstance("RDotNet");
}
private void button1_Click(object sender, EventArgs e)
{
REngine engine = REngine.GetInstanceFromID("RDotNet");
try
{
// import csv file
engine.Evaluate("dataset<-read.table(file.choose(), header=TRUE, sep = ',')");
// retrieve the data frame
DataFrame dataset = engine.Evaluate("dataset").AsDataFrame();
for (int i = 0; i < dataset.ColumnCount; ++i)
{
dataGridView1.ColumnCount++;
dataGridView1.Columns[i].Name = dataset.ColumnNames[i];
}
for (int i = 0; i < dataset.RowCount; ++i)
{
dataGridView1.RowCount++;
dataGridView1.Rows[i].HeaderCell.Value = dataset.RowNames[i];
for (int k = 0; k < dataset.ColumnCount; ++k)
{
dataGridView1[k, i].Value = dataset[i,k];
}
}
}
catch
{
MessageBox.Show(#"Equation error.");
}
}
}
}
If you want to know how can you set or edit environment variables in windows, you can use this link:
Set Environment Variable
PATH includes several addresses, and maybe you should add your dlldir address to this variable.
You are using an outdated version of R.NET; see the online documentation for instruction and sample code on how to install and use the current API (version 1.5.15 or above)

How can i check if a text file contain more then one line of text inside?

I have this code:
BeginInvoke(new Action(() => tempNamesAndTexts.ForEach(Item => textBox1.AppendText(DateTime.Now + "===> " + Item + Environment.NewLine))));
foreach (string items in tempNamesAndTexts)
{
Logger.Write(items);
}
Once im running the program it will do: Logger.Write(items);
Then the text file will look like:
Danie hello
Ron hi
Yael bye
Josh everyone ok
Next time im running the program it will write to the text file the same strings.
I want to check if this string already exist in the text file dont write them again else do write so the result will be that each time im running the program it will write to the logger(text file) only new strings if there are any.
This is the string variable of the logger text file:
full_path_log_file_name
This variable inside have:
C:\\Users\\Chocolade\\AppData\\Local\\ChatrollLogger\\ChatrollLogger\\log\\logger.txt
This is the complete code untill this part wich is the part that DoWork always do one time when im running the program:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using DannyGeneral;
namespace ChatrollLogger
{
public partial class Form1 : Form
{
string log_file_name = #"\logger.txt";
string full_path_log_file_name;
string path_log;
bool result;
List<string> namesAndTexts;
WebResponse response;
StreamReader reader;
string profileName;
string profileNameText;
string url;
string testingUrl;
int index;
List<string> names;
List<string> texts;
WebClient wc;
public Form1()
{
InitializeComponent();
Logger.exist();
wc = new WebClient();
result = true;
url = "http://chatroll.com/rotternet";
testingUrl = "http://chatroll.com/testings";
backgroundWorker1.RunWorkerAsync();
path_log = Path.GetDirectoryName(Application.LocalUserAppDataPath) + #"\log";
full_path_log_file_name = path_log + log_file_name;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
List<string> tempNamesAndTexts = new List<string>();
string tempDownload = downloadContent();
GetProfileNames(tempDownload);
GetTextFromProfile(tempDownload);
for (int i = 0; i < names.Count; i++)
{
tempNamesAndTexts.Add(names[i] + " " + texts[i]);
}
if (InvokeRequired)
{
BeginInvoke(new Action(() => tempNamesAndTexts.ForEach(Item => textBox1.AppendText(DateTime.Now + "===> " + Item + Environment.NewLine))));
foreach (string items in tempNamesAndTexts)
{
Logger.Write(items);
string t = full_path_log_file_name;
}
}
Something like this?
string path = "test.txt";
string valueToWrite = "....";
//only write to the file, if the specified string is not already there
if(!File.ReadLines(path).Any(l => string.Equals(l, valueToWrite)))
{
File.AppendAllText(path, valueToWrite);
}
Use File.ReadAllLines
string[] array = File.ReadAllLines("test.txt");
if(array.Length > 0)
{
// lines exist
}

Categories

Resources