I have written a news web application. I think code is right but it return false when the function Add news is called
/*my form
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using WindowsFormsApp1.Models;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
byte[] picture = null;
WebClient ObjWebClient = null;
List<CategoriesGET>ListCategories = null;
public Form1()
{
InitializeComponent();
//---------------------------------
ObjWebClient = new WebClient();
ObjWebClient.Headers[HttpRequestHeader.ContentType]= "application/json ; charset=utf-8";
string url = "http://localhost:3712/api/CategoriesApi/GetCategories";
string JsonResponse = ObjWebClient.DownloadString(url);
ListCategories = JsonConvert.DeserializeObject<List<CategoriesGET>>(JsonResponse);
cmb_NewsCategories.DataSource = ListCategories.Select(q=>q.CategoryTitle).ToList();
}
private void RefreshForms()
{
Txt_NewsTitle.Text = string.Empty;
Txt_NewsDescription.Text = string.Empty;
Txt_NewsDescription.Text = "لطفا دسته خبر را انتخاب کنید";
NewsImage.Image = Properties.Resources._2;
}
private void button3_Click(object sender, EventArgs e)
{
string url = "http://localhost:3712/api/NewsApi/AddNews/?NewsJson=";
ObjWebClient = new WebClient();
ObjWebClient.Headers[HttpRequestHeader.ContentType] = "application/json ; charset=utf-8";
ObjWebClient.Encoding = UTF8Encoding.UTF8;
//-------------------------------
PostNewsModel ObjPost = new PostNewsModel();
ObjPost.NewsTitle = Txt_NewsTitle.Text;
ObjPost.NewsDescription = Txt_NewsDescription.Text;
ObjPost.FK_CategoryID = ListCategories[cmb_NewsCategories.SelectedIndex].CategoryID;
ObjPost.NewsPicture = picture;
//-------------------------------------------------
string JsonData = JsonConvert.SerializeObject(ObjPost);
string Response = ObjWebClient.UploadString(url, JsonData);
MessageBox.Show(Response);
}
private void button4_Click(object sender, EventArgs e)
{
OpenFileDialog OFD = null;
string ImgPath = null;
OFD = new OpenFileDialog();
OFD.Title = "انتخاب عکس";
OFD.Filter = "JpegFiles|*.jpg";
if (OFD.ShowDialog() == DialogResult.OK)
{
if(OFD.FileName != null)
{
ImgPath = OFD.FileName;
NewsImage.Image = System.Drawing.Image.FromFile(ImgPath);
picture = AppClasses.Utility.ConvertImageToByte(NewsImage.Image, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
private void Txt_NewsTitle_TextChanged(object sender, EventArgs e)
{
}
}
}
//Add news function
public bool AddNews([FromBody]TB_News_Post NewsJson)
{
bool Succesfull =false;
try
{
string ImageLabel = GeneratePicName();
string Picture = ByteToImage(NewsJson.NewsPicture, ImageLabel);
TB_News Tbl_News = new TB_News();
Tbl_News.FK_CategoryID = NewsJson.FK_CategoryID;
Tbl_News.NewsDescription = NewsJson.NewsDescription;
Tbl_News.NewsPicture = Picture;
Tbl_News.NewsTitle = NewsJson.NewsTitle;
Tbl_News.NewsDate = DateTime.Now;
DbContext.TB_News.Add(Tbl_News);
DbContext.SaveChanges();
Succesfull = true;
}
catch (Exception)
{
Succesfull = false;
}
return Succesfull;
please help and feel free to ask the whole project thnx a lot
Related
I'll try to add as much information as needed, please tell me if you need any extra info that I haven't added and I'll do my best to provide it.
The basics of my problem is that whenenver I press a button, it will grab the file I select and save it to a text file. This works fine and I can save as many files as needed. The problem lies in the listbox of my listbox. My app is a soundboard, and I want filenames with their hotkeys to be displayed on the listbox which almost works fine. On loading the application the listbox will take all saved files and display them accordingly once and on adding a file, the file will be added to the listbox and it will be saved. As I said this almost works because for some reason unknown to me, you have to click the listbox for it to add the content. My code is as follows:
public partial class Form1 : Form
{
public int getNumberOfSongs()
{
using (Stream stream = File.Open(#"Sounds.txt", FileMode.Open))
{
using (StreamReader reader = new StreamReader(stream))
{
string line = null;
for (int i = 0; i < 1; ++i)
{
line = reader.ReadLine();
int ine = Int32.Parse(line);
ine = ine + 1;
return ine;
}
}
}
return 8;
//This is only here so it doesn't give me an error, it is never used
}
public void fineChanger(string newText, string fileName, int line_to_edit)
{
string[] arrLine = File.ReadAllLines(fileName);
arrLine[line_to_edit] = newText;
File.WriteAllLines(fileName, arrLine);
}
public void addFile()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "WAV files (*.wav)|*.wav";
openFileDialog.DefaultExt = ".wav";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
string filePath = openFileDialog.FileName;
songToAdd = filePath;
string control = filePath + "§modifier§hotkey";
string savePath = #"Sounds.txt";
int bruh = getNumberOfSongs();
fineChanger(control, savePath, bruh);
string bru = bruh.ToString();
fineChanger(bru, savePath, 0);
add = true;
}
}
public bool add = false;
public string songToAdd;
public bool load = true;
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
addFile();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (load == true)
{
listBox1.DataSource = File.ReadAllLines(#"Sounds.txt");
load = false;
}
if(add == true)
{
listBox1.Items.Add(songToAdd);
add = false;
}
}
}
P.S. I'm still a novice at windows forms and this app is still nowhere near done.
Instead of adding the items in SelectedIndexChanged I added them in outside. I load the saved songs in Form1_Load and I open/save the loaded files in the addFile() function.
Edited 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.IO;
using System.Media;
using System.Security.Cryptography.X509Certificates;
using System.Runtime;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic;
using System.Diagnostics;
namespace SoundBoard
{
public partial class Form1 : Form
{
public int getNumberOfSongs()
{
using (Stream stream = File.Open(#"Sounds.txt", FileMode.Open))
{
using (StreamReader reader = new StreamReader(stream))
{
string line = null;
for (int i = 0; i < 1; ++i)
{
line = reader.ReadLine();
int ine = Int32.Parse(line);
ine = ine + 1;
return ine;
}
}
}
return 8;
//This is only here so it doesn't give me an error, it is never used
}
public bool load = true;
public void fineChanger(string newText, string fileName, int line_to_edit)
{
string[] arrLine = File.ReadAllLines(fileName);
arrLine[line_to_edit] = newText;
File.WriteAllLines(fileName, arrLine);
}
public void addFile()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "WAV files (*.wav)|*.wav";
openFileDialog.DefaultExt = ".wav";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
string filePath = openFileDialog.FileName;
string control = filePath + "§modifier§hotkey";
string savePath = #"Sounds.txt";
int bruh = getNumberOfSongs();
fineChanger(control, savePath, bruh);
string bru = bruh.ToString();
fineChanger(bru, savePath, 0);
listBox1.Items.Add(filePath);
}
}
public bool loada = true;
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
addFile();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
if (loada == true)
{
listBox1.Items.Add(File.ReadAllLines(#"Sounds.txt"));
loada = false;
}
}
}
}
Every time when I click the button only one row will be displayed. But it should show multiple rows. I declare the list after the constructor invoke. I tried with gridview.update() and gridview.refresh() but they didn't work. I could not findout the issue.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using JournalEntryApp.Model;
namespace JournalEntryApp
{
public partial class NewDocument : Form
{
public NewDocument()
{
InitializeComponent();
}
List<JEFrom> JEFromsList = new List<JEFrom>();
List<JETo> JETosList = new List<JETo>();
JEFrom _jef = null;
private void NewDocument_Load(object sender, EventArgs e)
{
label4.Text = DateTime.Now.ToString("dd-MMM-yyyy");
using (var db =new JournalContext())
{
unitComboBox.DataSource = db.Units.ToList();
unitComboBox.ValueMember = "Id";
unitComboBox.DisplayMember = "UnitName";
}
}
private void addToListButton_Click(object sender, EventArgs e)
{
if (string.Empty== fromAccountTextBox.Text)
{
MessageBox.Show("From Account can not be empty!!!");
}
else if (string.Empty == toAccountTextBox.Text)
{
MessageBox.Show("To Account can not be empty!!!");
}
else
{
_jef = new JEFrom{ FromEntryName= fromAccountTextBox.Text , FromEntryDate= DateTime.Now };
JEFromsList.Add(_jef);
temporaryDataGridView.DataSource = JEFromsList;
fromAccountTextBox.Text = string.Empty;
toAccountTextBox.Text = string.Empty;
}
}
}
}
The temporaryDataGridView cannot detect that you have changed the DataSource. It will only refresh when Datasource has changed.
temporaryDataGridView.DataSource = null;
temporaryDataGridView.DataSource = JEFromsList;
so change the Datasource null first.
Or you can use bindingSource
private void NewDocument_Load(object sender, EventArgs e)
{
this.bindingSource1.DataSource = JEFromsList;
temporaryDataGridView.DataSource = this.bindingSource1;
label4.Text = DateTime.Now.ToString("dd-MMM-yyyy");
using (var db =new JournalContext())
{
unitComboBox.DataSource = db.Units.ToList();
unitComboBox.ValueMember = "Id";
unitComboBox.DisplayMember = "UnitName";
}
}
in button_click
JEFromsList.Add(_jef);
bindingSource1.ResetBindings(true);
I believe the creating the file finished. I am having issues with saving to a file. What I am supposed to do is create the file initially then fill out the form and have it save to that file and separate them by commas in the file so that in my next assignment I can create a form to read the file and have that fill in the form and split by those commas and fill into text boxes.
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;
namespace FileExercise
{
public partial class frmscout : Form
{
private StreamWriter fileWriter;
public frmscout()
{
InitializeComponent();
btnsave.Enabled = false;
}
private void clickclear(object sender, EventArgs e)
{
tb40.Clear();
tbheight.Clear();
tbname.Clear();
tbposition.Clear();
tbreps.Clear();
tbverticle.Clear();
}
private void clickexit(object sender, EventArgs e)
{
Application.Exit();
}
private void clickselect(object sender, EventArgs e)
{
DialogResult result;
string fileName;
using (SaveFileDialog fileChooser = new SaveFileDialog())
{
fileChooser.CheckFileExists = false;
result = fileChooser.ShowDialog();
fileName = fileChooser.FileName;
}
if (result == DialogResult.OK)
{
if (fileName == string.Empty)
{
MessageBox.Show("Invalid File Name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
try
{
FileStream flstrm = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
fileWriter = new StreamWriter( flstrm );
btnsave.Enabled = true;
btnopen.Enabled = false;
}
catch( IOException )
{enter code here
MessageBox.Show("Error opening file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
//FileStream outfile = new FileStream(fileName, FileMode.Append, FileAccess.Write);
}
private void clicksave(object sender, EventArgs e)
{
string[] values = new string[6];
values[0] = tbname.Text;
values[1] = tbheight.Text;
values[2] = tb40.Text;
values[3] = tbposition.Text;
values[4] = tbreps.Text;
values[5] = tbverticle.Text;
//}
}
}
}
you can do as below
private void clicksave(object sender, EventArgs e)
{
string[] values = new string[6];
values[0] = tbname.Text;
values[1] = tbheight.Text;
values[2] = tb40.Text;
values[3] = tbposition.Text;
values[4] = tbreps.Text;
values[5] = tbverticle.Text;
// you can get file name from `ShowDialog`,
//assume that file name is "filename.txt" then
System.IO.File.WriteAllLines("filename.txt",values);
}
You're creating a new instance of StreamWriter, and gathering your data onClick of the Save button, but nowhere are you calling StreamWriter.Write() or StreamWriter.WriteLine(). You need to insert at least one of those, as appropriate into your code, most likely in the clicksave function.
EDIT:
For example:
private void clicksave(object sender, EventArgs e)
{
string[] values = new string[6];
values[0] = tbname.Text;
values[1] = tbheight.Text;
values[2] = tb40.Text;
values[3] = tbposition.Text;
values[4] = tbreps.Text;
values[5] = tbverticle.Text;
fileWriter.WriteLine(String.Join(",",values));
fileWriter.Flush();
fileWriter.Close();
//}
}
Private void clicksave(object sender, EventArgs e)
{
string[] values = new string[6];
values[0] = tbname.Text;
values[1] = tbheight.Text;
values[2] = tb40.Text;
values[3] = tbposition.Text;
values[4] = tbreps.Text;
values[5] = tbverticle.Text;
fileWriter.WriteLine(String.Join(",",values));
fileWriter.Flush();
fileWriter.Close();
}
for joining of the string you can refer to the below link....as this is reference from Adrian Code..
http://www.dotnetperls.com/string-join
I'm trying to build an application that goes to a certain website (from a textbox) x number of times (also from a textbox) through a proxy. What I'm having trouble with is getting the proxy list into the program and using it in the webBrowser control. Here's what I have so far. Any help is appreciated. Thanks.
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.Security.Permissions;
using Microsoft.Win32;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System.Net;
namespace LetsBot
{
public partial class TrafficBot : Form
{
public TrafficBot()
{
InitializeComponent();
}
private void btnClear_Click(object sender, EventArgs e)
{
this.txtURL.Clear();
this.txtProxy.Clear();
this.txtURL.Focus();
}
private void btnStart_Click(object sender, EventArgs e)
{
this.lblBrowsing.Show();
this.btnStart.Enabled = false;
int n = Convert.ToInt32(this.txtNumVisits.Text);
for (int i = 0; i < n; i++)
{
string url = this.txtURL.Text;
this.webBotBrowser.Navigate(url);
while (webBotBrowser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
string PageText = this.webBotBrowser.DocumentText.ToString();
Thread.Sleep(5000);
}
}
private void btnStop_Click(object sender, EventArgs e)
{
this.btnStart.Enabled = true;
this.webBotBrowser.Stop();
this.txtURL.Focus();
}
private void btnExit_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Exit Traffic Bot?", "Don't Let Me Go!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
Application.Exit();
}
else if (dialogResult == DialogResult.No)
{
}
}
private void webBotBrowser_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
{
if (e.CurrentProgress > 0)
{
ProgressBar.Value = (int)(e.CurrentProgress / e.MaximumProgress * 100);
}
}
private List<string> getProxyListFromText(string input)
{
List<string> list = new List<string>();
StreamReader reader = new StreamReader(input);
string item = "";
while (item != null)
{
item = reader.ReadLine();
if (item != null)
{
list.Add(item);
}
}
reader.Close();
return list;
for (int i = 0; i < listBox1.Items.Count; i++)
{
object url;
WebClient wc;
url = this.txtURL.Text;
wc = new WebClient();
//This should come from the proxy list
foreach (string prox in getProxyListFromText("Proxies.txt"))
{
wc.Proxy = new WebProxy(prox);
var page = wc.DownloadString(url.ToString());
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(page);
var pplname = doc.DocumentNode.SelectNodes("/html/body/div[3]/div/div[2]/div[2]/div/div[4]/p");
}
}
}
}
}
I am having this strange error/conflict. I have two forms in my application. Both have same namespaces, and when I try to create an object of the next form it doesn't shows up. This is my code in Form1
Form2 form2 = new Form2();
form2.Show();
this.Hide();
And when I add another form in the project (like form3.cs) it shows up. Why is this "form2" missing? Although it is available in the project.
Form 1 code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
using UHF_Demo;
namespace UHF_Demo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void submit_Click(object sender, EventArgs e)
{
{
string query = "Select * from login_info where username = '" + username_tb.Text + "' and password = '" + password_tb.Text + "'";
SqlCeConnection conn = new SqlCeConnection();
conn.ConnectionString = #"Data Source =\Program Files\valcan\employeedb.sdf";
SqlCeCommand cmd = new SqlCeCommand(query, conn);
conn.Open();
SqlCeDataReader dr = cmd.ExecuteReader();
int counter = 0;
while (dr.Read())
{
counter = counter + 1;
}
if (counter > 0)
{
Form2 form2 = new Form2();
form2.Show();
this.Hide();
}
else
{
MessageBox.Show("Invalid Login name or Password. Please try again ....");
}
conn.Close();
dr.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'locationds.login_info' table. You can move, or remove it, as needed.
this.login_infoTableAdapter.Fill(this.locationds.login_info);
}
}
}
}}
Form2 code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
using System.Globalization;
using System.IO;
namespace UHF_Demo
{
public partial class MR6651_DEMO : Form
{
public bool BeingId = false;
byte[,] TagBuf = new byte[100, 14];
byte TagCnt = 0;
ComPort Port0 = new ComPort();
private CultureInfo culinfo = CultureInfo.CurrentCulture;
public MR6651_DEMO()
{
InitializeComponent();
double CostomiseFQ = 900.000;
for (int i = 0; i < 60; i++)
{
comboBox1.Items.Add(CostomiseFQ.ToString("#0.000")+"M");
comboBox2.Items.Add(CostomiseFQ.ToString("#0.000") + "M");
CostomiseFQ +=0.5;
}
MEMBANK.SelectedIndex = 1;
WORDPTR.SelectedIndex = 0;
WORDCNT.SelectedIndex = 0;
cmbFreqType.SelectedIndex = 2;
VALUE.Text = "";
//tabPage3.Parent = null;
if (culinfo.ToString() == "zh-CN")
{
this.Text = "UHF¶ÁдÑÝʾ";
TabPage page1 = tabControl1.TabPages[0];
page1.Text = "»¶Ó";
TabPage page2 = tabControl1.TabPages[1];
page2.Text = "EPC²âÊÔ";
//TabPage page3 = tabControl1.TabPages[2];
//page3.Text = "6B²âÊÔ";
label5.Text = "¹¦ÂÊ";
label8.Text = "ƵÂÊ";
labStatusBar.Text = "×¼±¸¾ÍÐ÷";
btnQueryPower.Text = "²éѯ";
btnSetPower.Text = "ÉèÖÃ";
EXIT.Text = "Í˳ö";
chkAutoClr.Text = "¹ýÂËÖظ´±êÇ©";
ID.Text = "ʶ±ð";
btnEPClist.Text = "Áбí";
button1.Text = "EPC¿é²Ù×÷";
CLEAR.Text = "Çå¿Õ";
label2.Text = "×ÖµØÖ·";
label3.Text = "×Ö³¤¶È";
label4.Text = "Êý¾Ý";
READ.Text = "¶ÁÈ¡";
WRITE.Text = "дÈë";
INIT.Text = "³õʼ»¯";
label10.Text = "×Ö½ÚµØÖ·";
label7.Text = "×Ö½Ú³¤¶È";
label9.Text = "Êý¾Ý";
btn6BID.Text = "ʶ±ð";
btn6BRead.Text = "¶ÁÈ¡";
btn6BWrite.Text = "дÈë";
btn6BLock.Text = "Ëø¶¨";
chkClear6B.Text = "¹ýÂËÖظ´±êÇ©";
btn6BClear.Text = "Çå¿Õ";
btnSaveFile.Text = "±£´æÎļþ";
label1.Text = "Êý¾Ý¿é";
cmbFreqType.Items.Clear();
cmbFreqType.Items.Add("Öйú");
cmbFreqType.Items.Add("±±ÃÀ");
cmbFreqType.Items.Add("Å·ÖÞ");
cmbFreqType.Items.Add("×Ô¶¨Òå");
cmbFreqType.SelectedIndex = 2;
listViewEPC.Columns[0].Text = "EPCÂë";
listViewEPC.Columns[1].Text = "񅧏";
label11.Text = "ÆðʼƵµã";
label12.Text = "ÖÕֹƵµã";
btn_locktid.Text = "ËøTID";
btn_seelocktid.Text = "²é¿´TIDËø";
}
}
private void EPC_DEMO_Load(object sender, EventArgs e)
{
if (Port0.Open() == 0)
{
if (culinfo.ToString() == "zh-CN")
{
labStatusBar.Text = "ͨѶ¶Ë¿Ú´ò¿ª³É¹¦!";
}
else
{
labStatusBar.Text = "Start conmunicate commport success!";
}
//aStatus = Port0.SetRf(10, 2);
Thread.Sleep(500);
btnQueryPower_Click(sender, e);
Sound.PlayWAV(#"\Application Data\Rfid\wav\shutter.wav");
for (int i = 0; i < 223; i++)
ADDR6B.Items.Add(i.ToString());
ADDR6B.SelectedIndex = 0;
ByteCnt6B.SelectedIndex = 0;
}
}
You have no Form2 class. You've got a MR6651_DEMO class. Try creating an instance of that instead. Your compiler should be telling you exactly what's wrong.
The name of a file doesn't have to have anything to do with the class contained within - that they often match is a matter of hygiene and sanity. =)
In your Form 2 Code there is no Class Definition for a Class named Form2. I guess thats the cause why it can't be found.