public partial class Loginform : Form
{
public Loginform()
{
InitializeComponent();
}
private void btnlogin_Click(object sender, EventArgs e)
{
string dir = "D://Login.hhh";
if (!File.Exists(dir))
{
File.Create(dir);
}
string filePath = dir;
string s = System.Environment.GetEnvironmentVariable("COMPUTERNAME");
string s1 = getIP();
using (StreamWriter swrObj = new StreamWriter(filePath, true))
{
swrObj.Write(s1 + "|" + s + "|" + Txtusername.Text + "|" + "user logged in on :|" + DateTime.Now.ToShortDateString() + " at " + DateTime.Now.ToShortTimeString());
swrObj.Write("\t\t");
swrObj.Write("\t\t");
swrObj.WriteLine();
MessageBox.Show("Login success");
}
}
private void Loginform_Load(object sender, EventArgs e)
{
}
private string getIP()
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily.ToString() == "InterNetwork")
{
localIP = ip.ToString();
}
}
return localIP;
}
}
I want to apply log file for project in C#, I am using above method to to create log file for getting system name, IP address and user login, but it is applicable in single user environment, if apply this in multi-user environment, How to get all users log info? please any one help me?
i assume that you want to create Log file for each user , then you can just do it like this:-
private void btnlogin_Click(object sender, EventArgs e)
{
string s1 = getIP();
string dir = "D://"+s1+"-"+DateTime.Now+"Login.hhh";
if (!File.Exists(dir))
{
File.Create(dir);
}
string filePath = dir;
string s = System.Environment.GetEnvironmentVariable("COMPUTERNAME");
using (StreamWriter swrObj = new StreamWriter(filePath, true))
{
swrObj.Write(s1 + "|" + s + "|" + Txtusername.Text + "|" + "user logged in on :|" + DateTime.Now.ToShortDateString() + " at " + DateTime.Now.ToShortTimeString());
swrObj.Write("\t\t");
swrObj.Write("\t\t");
swrObj.WriteLine();
MessageBox.Show("Login success");
}
}
Related
I've an API secured by Bearer token to be consumed in a MVC project. I want to take the values to send from a text file every time a text file is created in a Windows folder, I used fileSystemWatcher to monitor the folder and I use a routine to read the lines from the new text file. I'm stuck creating a new record in a Business Central customer table.
namespace MonitorChanges
{
public partial class Form1 : Form
{
string Path = #"D:\...", Ruta;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
fileSystemWatcher1.Path = Path;
GetFiles();
}
public void GetFiles()
{
string[] lst = Directory.GetFiles(Path);
textBox1.Text = "";
foreach(var sFile in lst)
{
textBox1.Text += sFile + Environment.NewLine;
Ruta = sFile;
}
}
private void fileSystemWatcher1_Changed(object sender, FileSystemEventArgs e)
{
}
private async void fileSystemWatcher1_Created(object sender, FileSystemEventArgs e)
{
GetFiles();
await GetToken(GetRuta());
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private string GetRuta()
{
return Ruta;
}
static async Task GetToken(string ruta)
{
string ClientId = "2825017b...";
string ClientSecret = "cGO8Q~...";
string TenantId = "36393c6b...";
string URL = "https://login.microsoftonline.com/" + TenantId + "/oauth2/v2.0/token";
HttpClient client = new HttpClient();
var content = new StringContent("grant_type = client_credentials" +
"&scope=https://api.businesscentral.dynamics.com/.default" +
"&client_id=" + HttpUtility.UrlEncode(ClientId) +
"&client_secret=" + HttpUtility.UrlEncode(ClientSecret));
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = await client.PostAsync(URL, content);
if (response.IsSuccessStatusCode)
{
JObject Result = JObject.Parse(await response.Content.ReadAsStringAsync());
string BearerToken = Result["access_token"].ToString();
string URL2 = "https://api.businesscentral.dynamics.com/v2.0/36393c6b.../Production/ODataV4/Company('CRONUS%20MX')/VistaClientes";
HttpClient testclient = new HttpClient();
testclient.DefaultRequestHeaders.Add("Authorization", "Bearer " + BearerToken);
var result = await testclient.GetAsync(URL2);
if (result.IsSuccessStatusCode)
{
MessageBox.Show(await result.Content.ReadAsStringAsync());
List<Record> records = new List<Record>();
List<string> rows = File.ReadAllLines(ruta).ToList();
foreach (var row in rows)
{
string[] entries = row.Split(',');
//I consider entering the code here to send the values to the exposed page of Business Central
}
}
else
{
MessageBox.Show(result.StatusCode.ToString());
}
}
else
{
MessageBox.Show(response.StatusCode.ToString());
}
}
}
}
I've tried this
var newClient = "{\"Name\": " + entries[0] + ",\"Name_2\": " + entries[1] + ",\"Location_Code\": " + entries[2] + ",\"Post_Code\": " + entries[3] + ",\"Country_Region_Code\": " + entries[4] + ",\"Phone_Code\": " + entries[5] + "}";
HttpContent dataHttpContent = new StringContent(newClient, Encoding.UTF8, "application/json");
var dataResponse = await testclient.PostAsync(URL2, dataHttpContent);
MessageBox.Show(await dataResponse.Content.ReadAsStringAsync());
I get this error
Post request error
Hello I am using this code to connect vpn with c# my code can connect and disconnect and create vpn and it working fine but i want use it in xamarin android i do search google but No result
private static string FolderPath => string.Concat(Directory.GetCurrentDirectory(),
"\\VPN");
private void btnConnect_Click(object sender, EventArgs e)
{
if (!Directory.Exists(FolderPath))
Directory.CreateDirectory(FolderPath);
var sb = new StringBuilder();
sb.AppendLine("[VPN]");
sb.AppendLine("MEDIA=rastapi");
sb.AppendLine("Port=VPN2-0");
sb.AppendLine("Device=WAN Miniport (IKEv2)");
sb.AppendLine("DEVICE=vpn");
sb.AppendLine("PhoneNumber=" + txtHost.Text);
File.WriteAllText(FolderPath + "\\VpnConnection.pbk", sb.ToString());
sb = new StringBuilder();
sb.AppendLine("rasdial \"VPN\" " + txtUsrname.Text + " " + txtPassword.Text + " /phonebook:\"" + FolderPath +
"\\VpnConnection.pbk\"");
File.WriteAllText(FolderPath + "\\VpnConnection.bat", sb.ToString());
var newProcess = new Process
{
StartInfo =
{
FileName = FolderPath + "\\VpnConnection.bat",
WindowStyle = ProcessWindowStyle.Normal
}
};
newProcess.Start();
newProcess.WaitForExit();
btnConnect.Enabled = false;
btnDisconnect.Enabled = true;
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
File.WriteAllText(FolderPath + "\\VpnDisconnect.bat", "rasdial /d");
var newProcess = new Process
{
StartInfo =
{
FileName = FolderPath + "\\VpnDisconnect.bat",
WindowStyle = ProcessWindowStyle.Normal
}
};
newProcess.Start();
newProcess.WaitForExit();
btnConnect.Enabled = true;
btnDisconnect.Enabled = false;
}
or I want convert it to xamarin android and
connect or disconnect sorry for my english
Halllo
I have made my first project and it works, well sort of, I can not get it to close serial port.
I am running 200hz in the Serialmonitor and the save funktion works perfect.
I suspect that it attempts to read data while I am trying to close the port.
It does not come up with an error but hanging in the debugger trying to close the port.
MY CODE IN VISUAL STUDIO 2015:
using System;
using System.Windows.Forms;
using System.IO.Ports;
namespace Arduino_Serial
{
public partial class Form1 : Form
{
private SerialPort myport;
private DateTime datetime;
private string in_data1;
private int runtime_sec = 0;
private float runtime_milis = 0;
public Form1()
{
InitializeComponent();
}
private void Start_Click_1(object sender, EventArgs e)
{
myport = new SerialPort();
myport.BaudRate = 115200;
myport.PortName = Port_name_tb.Text;
myport.Parity = Parity.None;
myport.DataBits = 8;
myport.StopBits = StopBits.One;
myport.DataReceived += Myport_DataReceived;
try
{
myport.Open();
timer2.Enabled = true;
timer1.Enabled = true;
Data_tb.Text = "\"Arduino\"" + "\n";
Data_tb.AppendText("Time" + "\t" + "Raw_data" + "\t" + "MAP" + "\n");
Data_tb.AppendText("Sec " + "\t" + "Raw_data" + "\t" + "KPA" + "\n");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
void Myport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
in_data1 = myport.ReadLine();
Invoke(new EventHandler(displaydata_event));
}
private void displaydata_event(object sender, EventArgs e)
{
datetime = DateTime.Now;
string time = datetime.Hour + ":" + datetime.Minute + ":" + datetime.Second;
Data_tb.AppendText(("\n")+ (runtime_milis) + ("\t")+ in_data1 );
}
private void Stop_bt_Click(object sender, EventArgs e)
{
try
{
myport.ReadTimeout = 1000000000;
myport.Close();
timer2.Enabled = false;
timer1.Enabled = false;
runtime_milis = 0;
runtime_sec = 0;
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message, "Error");
}
}
private void Save_bt_Click(object sender, EventArgs e)
{
try
{
datetime = DateTime.Now;
String time = datetime.Year + "-"+ datetime.Month + "-"+ datetime.Day + "_" + datetime.Hour + "." + datetime.Minute + "." + datetime.Second;
string pathfile = #"C:\DATA\";
string filename = "Arduino_" + time + ".msl";
System.IO.File.WriteAllText(pathfile + filename, Data_tb.Text);
MessageBox.Show("Data has been saved");
Close();
}
catch (Exception ex3)
{
MessageBox.Show(ex3.Message, "Error");
}
}
private void timer1_Tick(object sender, EventArgs e)
{
runtime_sec++;
}
private void timer2_Tick(object sender, EventArgs e)
{
runtime_milis++;
}
}
}
I have a DotNetZip code for zipping the folder. It doesnt zip the file for the first time after cleaning the solution. After that it works fine. Can anybody know the issue why its happening??
Button Click Event Code
private void button3_Click(object sender, EventArgs e)
{
try
{
copy_stuff(textBox1.Text, textBox2.Text, textBox3.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Method that gets called from Button Click
private void copy_stuff(string srcFolder, string destFolder, string Backup)
{
using (ZipFile zip = new ZipFile())
{
zip.AddProgress += AddProgressHandler;
zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Default;
zip.SaveProgress += SaveProgress;
zip.StatusMessageTextWriter = System.Console.Out;
zip.AddDirectory(destFolder);
zip.Save(Backup + "\\VibrantBackup" + DateTime.Now.ToString("yyyyMMdd hh.mm.ss") + ".zip");
label1.Text = "Compression completed.";
}
}
Add & Save Handlers for Progress
int _numEntriesToAdd = 0;
int _numEntriesAdded = 0;
void AddProgressHandler(object sender, AddProgressEventArgs e)
{
switch (e.EventType)
{
case ZipProgressEventType.Adding_Started:
_numEntriesToAdd = 0;
_numEntriesAdded = 0;
label1.Text = "Adding files to the zip...";
label1.Update();
Application.DoEvents();
break;
case ZipProgressEventType.Adding_AfterAddEntry:
_numEntriesAdded++;
label1.Text = String.Format("Adding file: {0} :: {2}",
_numEntriesAdded, _numEntriesToAdd, e.CurrentEntry.FileName);
label1.Update();
Application.DoEvents();
break;
case ZipProgressEventType.Adding_Completed:
label1.Text = "Added all files";
label1.Update();
Application.DoEvents();
break;
}
}
public void SaveProgress(object sender, SaveProgressEventArgs e)
{
if (e.EventType == ZipProgressEventType.Saving_Started)
{
label1.Text = "Begin Saving: " + e.ArchiveName;
label1.Update();
Application.DoEvents();
}
else if (e.EventType == ZipProgressEventType.Saving_BeforeWriteEntry)
{
label1.Text = "Processing : " + e.CurrentEntry.FileName;
label1.Update();
label3.Text = "Files Processed: (" + (e.EntriesSaved + 1) + "/" + e.EntriesTotal + ")";
label3.Update();
Application.DoEvents();
progressBar3.Maximum = e.EntriesTotal;
progressBar3.Value = e.EntriesSaved + 1;
}
else if (e.EventType == ZipProgressEventType.Saving_EntryBytesRead)
{
//progressBar2.Value = (int)((e.BytesTransferred * 100) / e.TotalBytesToTransfer);
//label3.Text = "Writing: " + e.CurrentEntry.FileName + " (" + (e.EntriesSaved + 1) + "/" + e.EntriesTotal + ")";
label1.Update();
Application.DoEvents();
}
}
I wrote a program that compiles my .cs files using csc.exe:
namespace myCompiler
{
public partial class Form1 : Form
{
string compilerFolder;
string outputFolder;
string projectFile;
string output = #" /out:";
public Form1()
{
InitializeComponent();
}
private void startCompile_Click(object sender, EventArgs e)
{
Compile();
}
public void findCompile_Click(object sender, EventArgs e)
{
DialogResult result1 = folderBrowserDialog1.ShowDialog();
compilerFolder = folderBrowserDialog1.SelectedPath;
MessageBox.Show(compilerFolder);
cscLabel.Text = compilerFolder;
}
private void outputCompile_Click(object sender, EventArgs e)
{
DialogResult result2 = folderBrowserDialog2.ShowDialog();
outputFolder = folderBrowserDialog2.SelectedPath;
outputLabel.Text = (outputFolder);
MessageBox.Show(outputFolder);
}
private void findProject_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
projectFile = openFileDialog1.FileName;
projectLabel.Text = (projectFile);
MessageBox.Show(projectFile);
}
}
public void Compile()
{
try
{
Process compile = new Process();
string outputExe = fileName.Text;
string compiler = compilerFolder + #"\csc.exe";
string arGs = output + outputFolder + #"\" + outputExe + " " + projectFile;
compile.StartInfo.FileName = (compiler);
compile.StartInfo.Arguments = (arGs);
compile.StartInfo.RedirectStandardOutput = true;
compile.StartInfo.UseShellExecute = false;
compile.Start();
string stdOutput = "";
while (!compile.HasExited)
{
stdOutput += compile.StandardOutput.ReadToEnd();
MessageBox.Show(stdOutput);
}
}
catch (Exception errorMsg)
{
MessageBox.Show(errorMsg.Message);
}
}
private void testButton_Click(object sender, EventArgs e)
{
MessageBox.Show(projectFile);
MessageBox.Show(compilerFolder);
}
}
}
The compile instruction runs but produces no results, just a quick flash of a black console screen.
Basically what seems to be happening, is when all the strings are parsed in the commandline as arguments for the process, the .cs project source directory is broken up by each white space ie c:\users\%username%\Documents\Visual Studio 2010\ is broken up as c:\users\%username%\Documents\Visual then Studio then 2010\Projects\Myproject\myproj.cs
and subsequently the compilation fails.
You need double quotes around a filepath with spaces in it.
See my edit to your code below.
public void Compile()
{
try
{
Process compile = new Process();
string outputExe = fileName.Text;
string compiler = compilerFolder + "\csc.exe";
// add double quotes around path with spaces in it.
string arGs = output + "\"" + outputFolder + "\"" + #"\" + outputExe + " " + projectFile;
compile.StartInfo.FileName = compiler;
compile.StartInfo.Arguments = arGs;
compile.StartInfo.RedirectStandardOutput = true;
compile.StartInfo.UseShellExecute = false;
compile.Start();
string stdOutput = "";
while (!compile.HasExited)
{
stdOutput += compile.StandardOutput.ReadToEnd();
MessageBox.Show(stdOutput);
}
}
catch (Exception errorMsg)
{
MessageBox.Show(errorMsg.Message);
}
}