Access RichtextBox from BusinessLayer and show text on it using c# - c#

I create three Project layer -Application layer, Business laer and DataAccess layer according to software architecture.Now I want to access Richtextbox from application layer to Business Logic layer.in business logic layer I implemented a WikipediaPerseCode to show the short text from Wikipedia page.I write the code. But I am not sure how to reference and show the text in application layer.I am trying, But as I am new in softawre architecture handling ,I do not know how to do it.
my Application layer is like-
namespace TouristPlace
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ShortText.txt1 = richTextBox1;
}
public string SetText1
{
get { return richTextBox1.Text; }
set { richTextBox1.Text = value; }
}
}
}
My Business Logic layer for short text is-
namespace WikiPerser
{
class ShortText
{
public static RichTextBox txt1 = new RichTextBox();
public static void shortText(string name)
{
using (WebClient wc = new WebClient())
{
var startPath = Application.StartupPath;
//var spath = Path.Combine(startPath,#"\ShortText\");
string folderName = Path.Combine(startPath, "Short Text");
System.IO.Directory.CreateDirectory(folderName);
string fileName = name + ".txt";
var path = Path.Combine(folderName, fileName);
var client = new WebClient();
var response = client.DownloadString("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=" + name + "&redirects=");
var responseJson = JsonConvert.DeserializeObject<RootObject>(response);
var firstKey = responseJson.query.pages.First().Key;
var extract = responseJson.query.pages[firstKey].extract;
try
{
Regex regex = new Regex(#".(?<=\()[^()]*(?=\)).(.)");
string.Format("Before:{0}", extract);
extract = regex.Replace(extract, string.Empty);
string result1 = String.Format(extract);
result1 = Regex.Replace(result1, #"\\n", " ");
//richTextBox1.Text = result;
txt1.Text = extract;
File.WriteAllText(path, txt1.Text);
}
catch (Exception)
{
txt1.Text = "Error";
}
}
}
}
}

I think you looking for something like that :
Implementation of the Form
Form consume services of the ShortTextService which is your WikiParser(as I understood so far)
public partial class Form1
: Form
{
private readonly ShortTextService _shortTextService;
public Form1()
{
_shortTextService = new ShortTextService();
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.Text = _shortTextService.GetShortText(NameTextBox.Text);//here NameTextBox is input for the name
}
}
ShortTextService is class which is responsible for request of the wiki data. This is what you mean with Business Logic, I guess.
ShortTextService implementation:
public class ShortTextService
{
private string _baseUrl =
"https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles={0}&redirects=";
public string GetShortText(string name)
{
string requestUrl = string.Format(_baseUrl, name);
string result;
using (WebClient client = new WebClient())
{
try
{
string response = client.DownloadString(requestUrl);
RootObject responseJson = JsonConvert.DeserializeObject<RootObject>(response);
var firstKey = responseJson.query.pages.First().Key;
var extract = responseJson.query.pages[firstKey].extract;
Regex regex = new Regex(#".(?<=\()[^()]*(?=\)).(.)");
extract = regex.Replace(extract, string.Empty);
result = Regex.Replace(extract, #"\\n", " ");
}
catch (Exception)
{
result = "Error";
//handle exception here. E.g Logging
}
}
return result;
}
}
I didn't have code for RequestObject so I left your code unchanged.
Additionally I removed code for file handling. I didn't get why you first put the data to the file and than read it from the file into the response of the service. If it really needed you can add it again into your implementation.
Meaning of the Layered Architecture is to separate areas of the responsibilities. So you could reuse your existing implementation or replace some parts without impact on other parts of the application.
Your application is quite simple to see the big benefit of this strategy.

Related

getter setter can't change textBox.Text control value in Winform c#

Why textBox3.text do not shows value _TextBoxRequestMsg. MessageBox opens and shows _TextBoxRequestMsg value OK, console prints too.
public partial class F_Main : Form
{
private string _TextBoxRequestMsg;
public string TextBoxRequestMsg
{
get { return textBox3.Text; }
set
{
_TextBoxRequestMsg = value;
MessageBox.Show(_TextBoxRequestMsg);
Console.WriteLine(_TextBoxRequestMsg);
textBox3.Text = _TextBoxRequestMsg;
}
}
public F_Main()
{
InitializeComponent();
}
}
public class CdataController : ApiController
{
F_Main mainForm = new F_Main();
public async Task<HttpResponseMessage> PostPayloadEventsOp(string SN, string table, string OpStamp)
{
using (var contentStream = await this.Request.Content.ReadAsStreamAsync())
{
contentStream.Seek(0, SeekOrigin.Begin);
using (var sr = new StreamReader(contentStream))
{
string results = sr.ReadToEnd();
mainForm.TextBoxRequestMsg = results;
}
}
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent("OK", System.Text.Encoding.UTF8);
response.Headers.CacheControl = new CacheControlHeaderValue()
{
MaxAge = TimeSpan.FromMinutes(2)
};
return response;
}
}
Your question states that your goal is to change textBox.Text control value in Winform and your code indicates that you want to do this by processing an HttpResponseMessage. Consider that the Form that owns the textBox3 control could await the response so that it can meaningfully process its content and assign the value to the text box.
For a minimal example, mock the API request:
public class MockCdataController : ApiController
{
public async Task<HttpResponseMessage> MockPostPayloadEventsOp(string SN, string table, string OpStamp)
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync("https://stackoverflow.com/q/75310027/5438626");
response.Content = new StringContent("OK", System.Text.Encoding.UTF8);
response.Headers.CacheControl = new CacheControlHeaderValue()
{
MaxAge = TimeSpan.FromMinutes(2)
};
return response;
}
}
}
The Form that is in possession of textBox3 could invoke something like this:
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
buttonPost.Click += onPost;
}
private async void onPost(object? sender, EventArgs e)
{
try
{
UseWaitCursor = true;
buttonPost.BackColor = Color.LightGreen;
var response = await _controller.MockPostPayloadEventsOp("38D6FF5-F89C", "records", "Asgard");
if((response.Headers != null) && (response.Headers.CacheControl != null))
{
textBox3.Text = $"{response.Headers.CacheControl.MaxAge}";
}
}
finally
{
UseWaitCursor = false;
Cursor.Position = new Point(Cursor.Position.X + 1, Cursor.Position.Y);
}
}
MockCdataController _controller = new MockCdataController();
}

Reading Text from text file ant separating to variables

I'm trying to set value to different variables from messy text.
Main Dishes
name;group;price;TAX;number;Id;;Fullname;Description;
Bigger modifiers
Name;group;price;TAX;number;Id;/some/additional/stuff
Smaller modifiers
Name;;price;TAX;number;Id;/some/additional/stuff
Text
Omlet;Second Dishes;40,0000;;00027;326ef70c-8d29-4c63-94ce-0580f26f84ab;Omlet with chicken and mushroom sauce;;;;;
Onions;Vegetables;4,1000;21;00021;fe5bab77-72cf-474e-acbc-1562c2f6aa37;0/1/1/1/6;;;;
Tomatoes;Vegetables;4,2000;21;00022;180fa908-9428-444e-a1df-5b74a40def64;0/1/1/1/7;;;;
Day Soup;Soup;123,4560;9;10108;19674f89-a44a-423d-ae79-0fc020be8d72;;;;;;
Roast pork with sauce;Second Dishes;0,0500;21;1167;a929bf86-2b89-4af6-baf9-f37317e0d75f;;;;;;
Cucumbers;;0,5500;21;222;8e370b64-b1f8-4665-95ae-88327d877394;-/-/1/0/3;;;;;
Tomatoes with garlic;Vegetables;0,1100;21;00024;52d08882-41c2-4dc3-8c4b-998109b6aedc;-/-/1/0/3;;;;;
Salt;;0,3300;21;00025;39332fab-99e0-4663-a59a-fff0deab958d;-/-/1/0/3;;;;;
I have created a class
class Food
{
public string Name;
public string Group;
public string Price;
public string TaxPercent;
public string Number;
public string ID;
public string Type;
public string FullName;
public string Description;
}
Can someone explain me how i suppose to seperate part to smaller modifiers and bigger ones? Should I create new class or it is possible to work with one?
How should IF statement look like?
What i tried to so far
private void button1_Click(object sender, EventArgs e)
{
List<Food> List= new List<Food>();
using (StreamReader sr = new StreamReader(#"TEST.txt"))
{
while (!sr.EndOfStream)
{
string str;
string[] stringArray;
str = sr.ReadLine();
strArray = str.Split(';');
Food Dish = new Food();
Dish.Name = stringArray[0];
Dish.Group = stringArray[1];
Dish.Price = stringArray[2];
Dish.TaxPercent = stringArray[3];
List.Add(Dish);
textBox1.Text =displayMembers(List);
}
string displayMembers(List<Food> vegetables)
{
foreach (Food s in vegetables)
{
return s.ToString();
}
return null;
Out put
TESTREADER.FOOD //TESTREADER IS A FOLDER WHERE TEST FILE IS.
You can do something like this:
public List<Food> getFoods()
{
List<Food> foods = new List<Food>();
using (var fileReader = new StreamReader(#"file.txt"))
{
var line = fileReader.ReadLine();
while (line != null)
{
string[] data = s.Split(';');
line = fileReader.ReadLine();
Food food = new Food
{
Name = data[0];
Group = data[1];
(...)
}
line = fileReader.ReadLine();
}
return foods;
}

StreamWriter MVVM C# writes variable address?

im studying C# and wanted to create a simple registration and loginform in order to practice. Im trying to use MVVM pattern. As it seemed to be easier just to store login data into text file and afterwards read from it for authentification. But a problem occured StreamWriter writes sth like that : System.Collections.ObjectModel.ObservableCollection`1[LoginForm.Andmed.LoginData]
If anyone can tell whats the issues or how to fix i would be very thankful.
the view model:
class LoginVM
{
public string path = #"C:\Users\Dell\Desktop\data.txt";
private ObservableCollection<LoginData> andmed; // creating ObservableCollection of LoginData data.
public ObservableCollection<LoginData> Andmed
{
get { return andmed; }
set { andmed = value; }
}
public LoginVM()
{
this.andmed = new ObservableCollection<LoginData>();
}
public void lisaAndmed(string user, string pass)//adds data to ObservableCollection
{
this.andmed.Add(new LoginData(user, pass));
}
public void salvestaAndmed()//
{
StreamWriter SW = new StreamWriter(path, true); // using streamwriter to save data from the Collection to the path defined
SW.WriteLine(this.andmed);
SW.Close();
}
public string autendi() // method for later purpose for authentification in login form.
{
StreamReader SR = new StreamReader(path);
path = SR.ReadToEnd();
SR.Close();
return path;
}
properties :
namespace LoginForm.Andmed
{
public class LoginData
{
private string username;
private string password;
public string Username
{
get { return username; }
set { username = value; }
}
public string Password
{
get { return password; }
set { password = value; }
}
public LoginData(string _username, string _password)
{
this.password = _password;
this.username = _username;
}
}
}
Model view class:
public partial class MainWindow : Window
{
LoginVM mudel;
public MainWindow()
{
InitializeComponent();
mudel = new LoginVM();
this.DataContext = mudel;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (user.Text.Length > 0 && pass1.Password == pass2.Password)
{
success.Text = "Successfuly registered!" + user.Text;
error.Text = "";
mudel.lisaAndmed(user.Text, pass1.Password); // calling the method to add data into obsercablecooll
mudel.salvestaAndmed(); // now trying to save the data from obsservablecall
}
else if (pass1.Password != pass2.Password)
{
error.Text = "Passwords arent the same";
}
else
{
error.Text = "Username incorrect!";
}
Logimine logimine = new Logimine();
logimine.ShowDialog();
}
}
This:
SW.WriteLine(this.andmed);
writes a result of ObservableCollection<T>.ToString() method call, which is a type name by default, since ObservableCollection<T> doesn't override Object.ToString().
You have to use any serializer to save and load ObservableCollection<LoginData> contents. For example, it could be XmlSerializer:
var serializer = new XmlSerializer(typeof(ObservableCollection<LoginData>));
var collection = new ObservableCollection<LoginData>
{
new LoginData { Username = "admin", Password = "123" },
new LoginData { Username = "johndoe", Password = "456" }
};
var sb = new StringBuilder();
// serialize
using (var writer = new StringWriter(sb))
{
serializer.Serialize(writer, collection);
}
// deserialize
using (var reader = new StringReader(sb.ToString()))
{
var collectionClone = serializer.Deserialize(reader);
}

HtmlAgilityPack - loading multiple pages

I've been playing around with the HtmlAgilityPack for a while, but I've run into a problem regarding the creation of a new HtmlDocument. I have a simple program that gets the data of films on a particular list. Some of the information is retrieved on the list page itself, and the rest is retrieved on the linking page for each item.
The problem i'm having is that for every time I wish to retrieve information from the linked page, i'm creating a new HtmlDocument. When I try to retrieve the complete list of films, the program just hangs on the console window. Here is my code:
namespace ConsoleApplication5
{
public class Scraper
{
private string _baseUrl = #"http://www.imdb.com";
private string _startingUrl = #"http://www.imdb.com/chart/top";
private HtmlWeb _webGet = new HtmlWeb();
public string StartingUrl
{
get { return _startingUrl; }
}
public string BaseUrl
{
get { return _baseUrl; }
}
public HtmlWeb WebGet
{
get { return _webGet; }
}
public List<Film> GetFilmData()
{
var allFilmData = new List<Film>();
var doc = WebGet.Load(StartingUrl);
var allFilmsInTable = doc.DocumentNode.SelectNodes("//div[#id='main']/table/tr");
foreach (var line in allFilmsInTable)
{
if (line.PreviousSibling != null)
{
var film = new Film();
film.Title = line.SelectSingleNode(".//td/font/a").InnerHtml;
film.Url = BaseUrl + line.SelectSingleNode(".//td/font/a").Attributes["href"].Value;
film.Rating = Convert.ToDecimal(line.SelectSingleNode(".//td[#align='center']/font").InnerText);
film.RankInTop250 = Convert.ToInt32(line.SelectSingleNode(".//td[#align='right']/font/b").InnerText.Replace(".",string.Empty));
allFilmData.Add(SingleFilmInformation(film));
}
}
return allFilmData;
}
public Film SingleFilmInformation(Film film)
{
var singleDoc = WebGet.Load(film.Url);
film.ReleaseYear = Convert.ToInt32(singleDoc.DocumentNode.SelectSingleNode("//h1[#class='header']/span/a").InnerText);
film.Director = singleDoc.DocumentNode.SelectSingleNode("//div[#itemprop='director']/a/span").InnerText;
foreach (var genre in singleDoc.DocumentNode.SelectNodes("//div[#class='infobar']/a/span[#itemprop='genre']"))
{
film.Genres.Add(genre.InnerText);
}
return film;
}
}
Any help would be greatly appreciated.

Send post-tags to wordpress within XML-RPC

I use XML-RPC.net 3 and joeblog dll in C#. Everything is OK, but I cant create and send post-tags to WordPress.
I can create posts with categories, title, excerpt, content, cutomfields but no success to create post-tags.
Its my code:
public void createPost(newPost np)
{
loginformobject = new LoginForm();
string postid;
icp = (IcreatePost)XmlRpcProxyGen.Create(typeof(IcreatePost));
clientProtocol = (XmlRpcClientProtocol)icp;
clientProtocol.Url = url.Text;
try
{
postid = icp.NewPost(1, User.Text, Pass.Text, np, 1);
}
catch (Exception ex)
{
MessageBox.Show("createPost ERROR ->" + ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
customField newCustomField2 = default(customField);
newCustomField2.key = "Testttttttttttt";
newCustomField2.value = "testttvalye";
newPost newBlogPost = default(newPost);
newBlogPost.title = "Some Title<AliReza Test>";
newBlogPost.description = "Some description Test Test Test Test<AliReza Test>";
newBlogPost.custom_fields = new customField[] { newCustomField2 };
newBlogPost.categories = new string[] { "Test" };
newBlogPost.mt_excerpt = "Tozihate Kotah";
newBlogPost.mt_taxonomy = new string[] { "test","test2" };
createPost(newBlogPost);
}
How can send post with tags within XML-RPC in C#?
Is there any library or code to create post-tags?
Thanks for any help.
fix to this
public string[] categories;
public string title;
public string description;
public string mt_excerpt;
public customField[] custom_fields;
public string[] mt_keywords;
and
newBlogPost.mt_keywords = new string []{ "t1","t2"};

Categories

Resources