Problem with runtime compilation in C#? - c#

I want to download the code from http://pastehtml.com/view/awono3xoq.txt, save it to a string, then compile & run it when the button is clicked, but I can't seem to get the code below to work:
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.CodeDom.Compiler;
using Microsoft.CSharp;
using System.IO;
using System.Diagnostics;
using System.Net;
using System.Runtime.InteropServices;
namespace ASV
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void compile()
{
CSharpCodeProvider myCodeProvider = new CSharpCodeProvider();
ICodeCompiler myCodeCompiler = myCodeProvider.CreateCompiler();
String [] referenceAssemblies = {"System.dll"};
string myAssemblyName = "Assembly.exe";
CompilerParameters myCompilerParameters = new CompilerParameters(referenceAssemblies, myAssemblyName);
myCompilerParameters.GenerateExecutable = true;
myCompilerParameters.GenerateInMemory = true;
WebClient x = new WebClient();
Stream y = x.OpenRead("http://pastehtml.com/view/awono3xoq.txt");
StreamReader z = new StreamReader(y);
string source = z.ReadToEnd();
z.Close();
y.Close();
CompilerResults compres = myCodeCompiler.CompileAssemblyFromSource(myCompilerParameters, source);
Process.Start("Assembly.exe");
}
private void button1_Click(object sender, EventArgs e)
{
compile();
}
}
}
what am I doing wrong (other than having too many using statments :P)?

If you check CompilerResults compres it shows that there's an exception and the compilation was not successful and hence it's not writing out Assembly.exe and there is a System.IO.FileNotFound exception from Process.Start()
Try this
public void compile()
{
CSharpCodeProvider myCodeProvider = new CSharpCodeProvider();
ICodeCompiler myCodeCompiler = myCodeProvider.CreateCompiler();
string myAssemblyName = #"Assembly.exe";
CompilerParameters myCompilerParameters = new CompilerParameters
{
OutputAssembly = myAssemblyName,
GenerateExecutable = true,
GenerateInMemory = true
};
myCompilerParameters.ReferencedAssemblies.Add("System.dll");
WebClient x = new WebClient();
Stream y = x.OpenRead("http://pastehtml.com/view/awono3xoq.txt");
StreamReader z = new StreamReader(y);
string source = z.ReadToEnd();
z.Close();
y.Close();
CompilerResults compres = myCodeCompiler.CompileAssemblyFromSource(myCompilerParameters, source);
Process.Start(myAssemblyName);
}

Related

How can I save settings to a text file and read them back?

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.Diagnostics;
using System.IO;
namespace StopwatchTimer
{
public partial class Form1 : Form
{
public string settingsPath = "Settings";
private string settingsFileName = "settings.txt";
private static readonly Stopwatch watch = new Stopwatch();
private long diff = 0, previousTicks = 0, ticksDisplayed = 0;
public Form1()
{
InitializeComponent();
richTextBox1.TabStop = false;
richTextBox1.ReadOnly = true;
richTextBox1.BackColor = Color.White;
richTextBox1.Cursor = Cursors.Arrow;
richTextBox1.Enter += RichTextBox1_Enter;
settingsPath = Path.Combine(Path.GetDirectoryName(Application.LocalUserAppDataPath), settingsPath);
if (!Directory.Exists(settingsPath))
Directory.CreateDirectory(settingsPath);
settingsFileName = Path.Combine(settingsPath, settingsFileName);
if (!File.Exists(settingsFileName))
File.Create(settingsFileName);
string[] settings = File.ReadAllText(settingsFileName).Split(',');
if(settings.Length > 0)
{
}
} radioButton1.Checked = true;
}
I didn't write yet to the text file. I want for example to write to the text file the radioButton1 and radioButton2 states somewhere else in the code and then reading the states back when running the application.
So I'm using Split with ',' but how do I check if the value when reading back is belong to the radioButton1 or radioButton2 or maybe a textBox or a button1 ?
You can use the built in winforms settings:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.Username = txtUsername.Text;
Properties.Settings.Default.Password = txtPassword.Text;
Properties.Settings.Default.Save();
}
C# Setting load and save
https://learn.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-write-user-settings-at-run-time-with-csharp

error in text direction when i try to extract text from arabic pdf file using itextsharp c#

i have problem in my code
i am trying to read text from arabic rtl file using itextsharp
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 iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
namespace Masmo3
{
public partial class FrmMain : Form
{
string book = null;
public FrmMain()
{
InitializeComponent();
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
BtnOpen.Enabled = false;
book = null;
using(OpenFileDialog Ofd = new OpenFileDialog() {Filter= "PDF files (*.pdf)|*.pdf|txt files (*.txt)|*.txt",ValidateNames= true, Multiselect= false})
{
if (Ofd.ShowDialog() == DialogResult.OK)
{
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(Ofd.FileName);
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= reader.NumberOfPages; i++)
{
sb.Append(PdfTextExtractor.GetTextFromPage(reader, i));
book = sb.ToString();
}
reader.Close();
}
}
BtnOpen.Enabled = true;
}
}
}
this code show my text like "ﻢﯿﺣﺮﻟا ﻦﻤﺣﺮﻟا ﷲ ﻢﺴﺑ" its wrong because its rtl language the correct way "بسم الله الرحمن الرحيم"
what i can do to get correct text direction ?
"بسم الله الرحمن الرحيم"
please use ColumnText object to set the DIrection to be RTL
CT.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
Good luck bro

Google maps autocomplete textbox in c#

I have a restaurant delivery WINFORM c# application where in user needs to enter the address, as to avoid human error we are trying to integrate google map's autocomplete functionality into textbox. I have googled and all I saw was for asp nothing for WINFORM. I tried one code however its namespace is missing and i am not sure which one it is
Namespace used :
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 Google.Api.Maps ;
using GoogleApi.Helpers;
Heres the code :
private void textBox1_TextChanged(object sender, EventArgs e)
{
var autoCompleteListCollection = new AutoCompleteStringCollection();
autoCompleteListCollection.AddRange(new GoogleApi.Instance.GetAddressPredictionsByInput(textBox1.Text).ToArray());
textBox1.AutoCompleteCustomSource = autoCompleteListCollection;
}
Error :
Error 1 The type or namespace name 'Instance' does not exist in the namespace 'GoogleApi' (are you missing an assembly reference?)
I think this might work. So please let me know right namespace or guide me how to achieve above requirement
Finally I got it to work, but it crashes the app, heres the code :
private void textBox1_TextChanged(object sender, EventArgs e)
{
string url = "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" + var + "&types=geocode&key=YOURAPIKEY";
string content = fileGetContents(url);
JObject o = JObject.Parse(content);
List<string> add = new List<string>();
try
{
JObject jObj = (JObject)JsonConvert.DeserializeObject(content);
int count = jObj.Count;
for (int i = 0; i < count; i++)
{
add.Add((string)o.SelectToken("predictions["+i+"].description"));
}
var collection = new AutoCompleteStringCollection();
collection.AddRange(add.ToArray());
textBox1.AutoCompleteCustomSource = collection;
textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }
{
}
protected string fileGetContents(string fileName)
{
string sContents = string.Empty;
string me = string.Empty;
try
{
if (fileName.ToLower().IndexOf("https:") > -1)
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] response = wc.DownloadData(fileName);
sContents = System.Text.Encoding.ASCII.GetString(response);
}
else
{
System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
sContents = sr.ReadToEnd();
sr.Close();
}
}
catch { sContents = "unable to connect to server "; }
return sContents;
}
Everytime I run after few attempts it crashes.
Thanks

C# adapt code to a button click event

I am trying to adapt the following code so that the functionality is on a click event ...
Here is the code as is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string IN_FILENAME = #"c:\temp\testin.csv";
const string OUT_FILENAME = #"c:\temp\testout.csv";
static void Main(string[] args)
{
StreamReader reader = new StreamReader(IN_FILENAME);
StreamWriter writer = new StreamWriter(OUT_FILENAME);
string inputLine = "";
while ((inputLine = reader.ReadLine()) != null)
{
List<string> inputArray = inputLine.Split(new char[] { ',' }).ToList();
inputArray.Add(inputArray[3]);
writer.WriteLine(string.Join(",", inputArray));
}
reader.Close();
writer.Flush();
writer.Close();
}
}
}
Then I need to add the functionality to a click even so this is where I am:
private void button1_Click(object sender, EventArgs e)
{
const string IN_FILENAME = #"c:\temp\testin.csv";
const string OUT_FILENAME = #"c:\temp\testout.csv";
StreamReader reader = new StreamReader(IN_FILENAME);
StreamWriter writer = new StreamWriter(OUT_FILENAME);
}
and I can't do anymore because it's telling me StreamReader cannot be found.
Can anyone help me adapt this code to the click event?
The StreamReader is a class define in the System.IO namespace. Using this namespace at the start of your file, you would resolve it.
using System.IO;

C# Using Youtube API - How do I check the last time a particular user uploaded a video to Youtube?

I know how to upload a video to Youtube using Youtube API within C#
But I'd like to use the Youtube API to return a date when a particular user last uploaded a video.
My code for uploading a video using C# is below, but I really don't know how to do the above???
Form1.cs
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 Google.GData.Client;
using Google.YouTube;
using Google.GData.Extensions.MediaRss;
using Google.GData.YouTube;
using Google.GData.Extensions.Location;
namespace UploadLimit
{
public partial class Form1 : Form
{
string key = "somegarbage";
string appName = "SlowUpload";
string username = "blarg";
string password = "blarg";
public Form1()
{
InitializeComponent();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
DialogResult result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
txtFile.Text = dialog.FileName;
}
private void btnUpload_Click(object sender, EventArgs e)
{
YouTubeRequestSettings settings = new YouTubeRequestSettings(appName, key, username, password);
YouTubeRequest request = new YouTubeRequest(settings);
Video newVideo = new Video();
newVideo.Title = "My Test Movie";
newVideo.Tags.Add(new MediaCategory("Autos", YouTubeNameTable.CategorySchema));
newVideo.Keywords = "cars, funny";
newVideo.Description = "My description";
newVideo.YouTubeEntry.Private = false;
newVideo.Tags.Add(new MediaCategory("mydevtag, anotherdevtag",
YouTubeNameTable.DeveloperTagSchema));
newVideo.YouTubeEntry.Location = new GeoRssWhere(37, -122);
// alternatively, you could just specify a descriptive string
// newVideo.YouTubeEntry.setYouTubeExtension("location", "Mountain View, CA");
newVideo.YouTubeEntry.MediaSource = new MediaFileSource(txtFile.Text, "video/quicktime");
Video createdVideo = request.Upload(newVideo);
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UploadLimit
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
You can get all the user's videos and get the latest date:
var videos = new YouTubeRequest().GetVideoFeed(userId).Entries
DateTime lastUploadDate = videos.Max(video => video.YouTubeEntry.Published)
To get the actual video's title:
var lastVideo = videos.Where(video => video.YouTubeEntry.Published == lastUploadDate).First();
var name = lastVideo.Title

Categories