C# Reading/Splitting Text Files and Reversing Sentences Exercise - c#

Locked. There are disputes about this question’s content being resolved at this time. It is not currently accepting new answers or interactions.
I am trying to do this book exercise for quite a while now in C# using visual studio and windows forms, however, I am having trouble with the last few steps and the book has no solution manual that I can look to for help.
Here is what the exercise says:
Read in the file
Split the file line-by-line
Push each line on to a stack
Pop each line out to a results Window
Save the reversed file (the sentences should be reversed).
Here is a picture of what the windows form should look like:
What the windows form should look like
Here is the sample .txt file named SocialJustice-SampleText.txt:
The idea of social justice is innately a subjective concept. A socially created reality critical to the enactment of social institutions, ‘justice’ exists within the minds of all individuals as we each have varying ideas of what is just or unjust, fair or unfair, right or wrong (Tyler, 1997). In turn, what emerges from this socially created reality is considered the “first virtue” in the enactment of social institutions (Rawls, 1971), and the first form of criteria that emerges when political, legal, and other managerial authorities come under judgment (Kelman and Hamilton, 1989). From the perspective of the academician, social justice bears fruit in areas such as moral philosophy, theology, political science, law, social psychology, and many others. From the perspective of the citizen, social justice is at the heart of modern discourse on topics related to equal distributions of wealth (Piketty, 2014), equal distributions of healthy food (Alkon and Agyeman, 2011), and the general precept of human rights as the virtue of being able to achieve equal outcomes given equal effort (Cergy-Pontoise, 2005; Wilkinson and Pickett, 2010). Thus, social justice is instrumentalist an Pragmatist by its very nature (Fraser, 1998) as the psychology of social justice is predicated on the consequences and meanings of an action or an event in a social situation, and such meaning cannot be given in advance of experience (Denzin, 2012) in seeking a Pragmatism that addresses social justice issues (Denzin, 2012; West, 1995). To research social justice is to adopt an inherently moral aim (Denzin, 2012; West, 1995) where the outputs inherently carry political consequences. In turn, our ideas of social justice are not conceived not from a universalistic ontology, but from a psychologically-driven understanding of actions (Tyler, 1997). However, much of the research on social justice is predicated on organizational work from the industrial revolution (cite), and far less with regard to understanding social justice in the information age (Eubanks, 2011). As we transpose our understanding of the psychology of social justice to the information age, and offer new vistas for IS research, we conceptualize areas of research at the confluence of information, technology, societal systems, and praxis that emanates as just actions and lies beyond the organizational container (Winter et al., 2014). In this section, we draw on the psychology of social justice (Tyler, 1997; cite; cite), which has, in turn, drawn from the etymological, theological, and philosophical roots of organizational justice to elucidate four areas: relative deprivation, distributive justice, procedural justice, and retributive justice, that can be elucidated as platforms for Pragmatic social justice research in IS.
So far I have created the form with the two rich textboxes and also created the two buttons "Open File" and "Split File." I also have read the .txt file in when I click the "Open File" button.
Here is what my form looks like based off of what I have done so far:
My windows form
Here is my full 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;
namespace FileExercise
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void OpenFileButton_Click(object sender, EventArgs e)
{
StreamReader objstream = new StreamReader("C:\\Users\\Omie\\Desktop\\SocialJustice-SampleText.txt");
richTextBox1.Text = objstream.ReadLine();
}
private void SplitFileButton_Click(object sender, EventArgs e)
{
}
}
}
So I am having trouble with steps 2-5 and was wondering if anyone could provide me an example of how to go about doing it based on what I have worked on already.
Thank you.
EDIT: Updated 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.Text.RegularExpressions;
namespace FileExercise
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void OpenFileButton_Click(object sender, EventArgs e)
{
string TextFile = File.ReadAllText("C:\\Users\\Omie\\Desktop\\SocialJustice-SampleText.txt", Encoding.UTF8);
richTextBox1.Text = TextFile;
}
private void SplitFileButton_Click(object sender, EventArgs e)
{
string SplitFile = File.ReadAllText("C:\\Users\\Omie\\Desktop\\SocialJustice-SampleText.txt", Encoding.UTF8);
string[] SplitFileBySentence = Regex.Split(SplitFile, ".");
foreach (string Period in SplitFileBySentence)
{
richTextBox2.Text = Period;
}
}
}
}

You can use
string[] readText = File.ReadAllLines("C:\\Users\\Omie\\Desktop\\SocialJustice-SampleText.txt")
to read all lines into string array.
Then, process the each line in the loop. I hope you can write the code to reverse the line.

Related

How to write selected combobox and textbox text to specific line in text file

Trying to save selected comboBox and textBox text to text file.
however there are multiple values being saved.
To avoid confusion systematically saving them on a specific line of the text file will help identify the values.
tried using the following, but application hangs.
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 WindowsFormsApp1
{
public partial class Setups : Form
{
public Setups()
{
InitializeComponent();
//this.TopMost = true;
//this.FormBorderStyle = FormBorderStyle.None;
//this.WindowState = FormWindowState.Maximized;
}
private void textBox8_TextChanged(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
static void lineChanger(string newText, string fileName, int line_to_edit)
{
string[] arrLine = File.ReadAllLines(fileName);
arrLine[line_to_edit - 1] = newText;
File.WriteAllLines(fileName, arrLine);
}
public void button5_Click(object sender, EventArgs e)
{
lineChanger(string.Format("{0} | {1}", comboBox1.Text, textBox8.Text), "sample.txt", 30); //
// Succesfully wrote to file on first line
//StreamWriter sw = new StreamWriter("Test.txt");
//sw.WriteLine($"{comboBox1.Text}.{textBox8.Text}");
//sw.Close();
}
A better solution would be to create a class that has all the settings and then serialize/deserialize it using JSON.
Use nuget to add the JSON package to your app. Example code to serialize: https://www.newtonsoft.com/json/help/html/SerializingJSON.htm
An application that hang and an out-of-range exception are 2 different things. Be precise in your question if you want help.
Also, your lineChanger function would obviously fails if the file you read does not already contains at least 30 lines when you click on button 5.
Hard coded number like that is always a bad idea in production code. If at some point, the file content is modified, it would be very hard to ensure that everything is properly fixed in the code.
If you really want to use such text file, then at the very least:
use an enumeration or constants define a single place for the purpose of each line.
use a class to manage your configuration so that only that class knows the structure of the file.
But as mentioned in another answer, it would be preferable to use another format like JSON. Almost every other format except binary data would be preferable to a text file (assuming that the content is settings for your application).
Having said that, if you really want lineChanger, then you should add a test like that:
if (line_to_edit >= arrLine.Length)
{
List<string> list(arrLine);
while (List.Length < line_to_edit) { list.Add(string.Empty); }
list.Add(newText);
arrLine = list.ToArray();
}
else { … old code from question… }
However, if you read other lines from the file or often read lines, it might become very slow to open/read/update/write/close the file each time a line is modified. Another reason why it would be a good idea to have a class to manage settings so that you load them once when opening the dialog and once when closing the dialog (assuming that the dialog is displayed a relatively short period of time and it is not critical to save changes immediately).
I think your question is too broad and needs more details.
You need to think of separating your form from your data. Create a data class to hold the values you want to be stored or read and have the UI interact with this class using data binding. Then your data class will always contain the most up-to-data information.
When needed, you can serialize your data file with TextStream, BinaryFormatter, XmlSerializer or JSON, depending on if the data needs to be accessed by other programs or locations. You can even use the built-in Settings to save the data before the application exits and to be read back in when it starts up again.
So please edit the question to clarify what you want to do with this data and add an example of what it looks like as a whole (all the lines in your text file now). Then we can answer more specifically.

need guidance for speech recognition engine with custom keywords c#

I have an windows form app. I need to add speech recognition into it in order to shorten the processing time for product entry. we need this speech recognition in Turkish. if it was in english, because of wrong pronunciation it would give a lot of false results. So we need in Turkish. But windows offline speech recognition engine doesnt support Turkish.
Actually We need max 100 keywords in order to succeed this. we don't need whole language in process. So if I can create a language by adding a word and train the engine for that with a kind of training as speech training in windows, it would be great.
So I need guidance to start or move forward for this task. I have looked at the cmusphnfix but it doesnt have turkish language also. But I dont know if I can create a custom language for 100 words with correct pronunciation. if so how can ı do it in c#.
note: we dont want to use google and microsoft online services. we are looking other options.
Thanks in advance.
Windows desktop versions have built in APIs for speech recognition. These include grammar support for identifying the words or meaning of what was spoken. I don't know if Turkish is supported.
Perhaps https://stackoverflow.com/a/5473407/90236 or https://learn.microsoft.com/en-us/previous-versions/office/developer/speech-technologies/hh361633(v%3doffice.14) can help you get started
https://www.sestek.com has good Turkish speech recognition. As for 100 keywords, on that scale it is easier to recognize whole speech and just look for keywords in transcription. That will give you better accuracy because speech recognition uses more context. When you just look for keywords you do not have context so the recognition is actually less accurate.
this is script for C# console app
if you want this in windows forms, just copy static void recognize and all in this and paste it in class Form : Form1, or where you want. write recognize(); in button1_click, or where you want. in windows forms do not copy anything else!
write this:
using System;
using System.Runtime.CompilerServices;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO;
using System.Linq.Expressions;
namespace speechrecognition
{
class Program
{
static string a { get; set; }
static void Main(string[] args)
{
recognize();
}
static void recognize()
{
SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine();
Choices colorChoice = new Choices(new string[] { "gugl", "noutpad" });
GrammarBuilder colorElement = new GrammarBuilder(colorChoice);
Choices bothChoices = new Choices(new GrammarBuilder[] { colorElement });
Grammar grammar = new Grammar((GrammarBuilder)bothChoices);
recognizer.LoadGrammar(grammar);
try
{
recognizer.SetInputToDefaultAudioDevice();
RecognitionResult result = recognizer.Recognize();
try
{
if (result.Text != null)
{
switch (result.Text.ToString())
{
// Here you add keywords like other two
// and write the into choices color choice too
case "noutpad":
Process.Start(#"notepad.exe");
Console.WriteLine("Notepad opened!");
recognize();
break;
case "gugl":
Process.Start(#"chrome.exe");
Console.WriteLine("Google opened!");
recognize();
break;
}
}
else
{
Console.WriteLine("I dont hear you!");
recognize();
}
}
catch (System.NullReferenceException)
{
recognize();
}
}
catch (InvalidOperationException exception)
{
Console.WriteLine("I dont hear you!");
Console.ReadLine();
recognize();
}
finally
{
recognizer.UnloadAllGrammars();
recognize();
}
}
}
}

Microsoft.DirectX.AudioVideoPlayback program not working

I'm trying to write a simple program that I'm going to be using inside another program for playing back audio and video files using the Microsoft.DirectX.AudioVideoPlayback.dll file. I've got the code listed below since it doesn't have to be incredibly complex. The problem that I am having is that... well, the program does nothing. Not even the main window shows up and I don't know why. I'm using .Net 4.0 and the DirectX DLL version says it's 1.0.2902.0. I tried moving the initialization for the audio and video files to different places (The load event and the button press event specifically). When in the button press event, the form loads, but as soon as I press a button, the program hangs. No errors or anything. Anyone know what is going on here? If someone has a better idea for playing audio and video files, I'm willing to consider that too.
using Microsoft.DirectX.AudioVideoPlayback;
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;
namespace MediaPlayer
{
public partial class Player : Form
{
Audio derp;
Video herp;
public Player()
{
InitializeComponent();
this.derp = new Audio("<Audio File Name>");
this.herp = new Video("<Video File Name>");
this.herp.Owner = this.panel1;
}
private void btnPlayPauseStop_Click(object sender, EventArgs e){
switch(((Button)sender).Text){
case "Play":
if (!herp.Playing)
herp.Play();
break;
case "Pause":
if (!herp.Paused)
herp.Pause();
break;
case "Stop":
if (!herp.Stopped)
herp.Stop();
break;
}
}
private void Player_Load(object sender, EventArgs e)
{
}
}
}
I have been using this for making my very own "Media Player Classic" clone
Be sure to debug this in 32 bit mode:
Project Menu --> {project} Properties ... --> Build --> Platform Target = x86
For video, I do not load Audio (it gets done automatically). So instead of using both, use only the one needed (video or audio)
The next thing is to ensure that the panel is visible and big enough to see (check the size after "new Video(...)")

'Random_Number_File_Writer.Form1' does not contain a definition for 'saveFileDialog1_FileOk'

'Random_Number_File_Writer.Form1' does not contain a definition for 'saveFileDialog1_FileOk' and no extension method 'saveFileDialog1)_FileOk' accepting a first argument of type 'Random_Number_File_Writer.Form1' could be found (are you missing a using directive or an assembly reference?)
That, is the error message that I am getting. I tried going to my college's lab for assistance, but the person is not familiar with C# and it took us around an hour just to get my line numbers showing (just for reference...) And then I went to my professor and he said he was going to be busy for a while.. So I thought I'd try here as an alternate source of help.
I looked at the questions already on here regarding similar errors, but it still leaves me puzzled as how to correct this one in particular, and as I referenced the code in my textbook as closely as possible, I'm not sure I understand why I'm even getting this error.
Here's the code, and I'm sorry if it's difficult to read. Oh, and I know that this is the part generating the error, because I had it running yesterday, WITHOUT this part. But part of the assignment is having the save as dialog.
try
{
//Initial opening point for save file dialogue
saveFileDialog1.InitialDirectory = #"C:\Users\Heather\Documents\Visual Studio 2010\Projects\Random Number File Writer";
//Save As popup - Opening the file for writing usage once it's created.
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
randomNumberFile = File.CreateText(openFileDialog1.FileName);
}
else // Popup informing user that the data will not save to a file because they didn't save.
{
MessageBox.Show("You elected not to save your data.");
}
here's the using stuff that didn't format:
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.IO; // Added to be able to use StreamWriter variable type
And here is the code snippet it gives when I double click and it takes me to the Form1.Designer.CS window.
this.saveFileDialog1.FileOk += new System.ComponentModel.CancelEventHandler(this.saveFileDialog1_FileOk);
saveFileDialog1_FileOk Looks like it's supposed to be an event handler( a method) so make sure that you have a method like
public void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
in your Form1 class

C# DirectX input problem

So i have simple application, just a few lines:
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 Microsoft.DirectX.DirectInput;
namespace asdasd
{
public partial class Form1 : Form
{
public Device joystick;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (
DeviceInstance di in
Manager.GetDevices(
DeviceClass.GameControl,
EnumDevicesFlags.AttachedOnly))
{
joystick = new Device(di.InstanceGuid);
break;
}
if (joystick == null)
{
throw new Exception("No joystick found.");
}
}
}
}
and i try to get the active joystick on my computer, but i get error:
i have the assembly Microsoft.DirectX.DirectInput and i have directX SDK 2010 installed.
Can someone tell me where is the problem?
Try adding this to the config file:
http://devonenote.com/2010/08/mixed-mode-assembly-error-after-upgrading-to-dotnet-4-0/
(if configuration already exists, just merge these in)
And, maybe it's not the right place, but just take a look at XNA... Things are usually much easier with that.
I couldn't paste the XML directly here, it doesn't show up.
The DirectX assemblies are built against .NET v1.1 Microsoft stopped actively developing them before .NET v2.0 was released.
They cannot be used in projects targeting other than .NET v1.1. XNA is the "blessed" path forward for managed access to Direct X features. I don't know all if it's features, but SlimDX appears to give a more Direct X feeling API for C# than XNA, though I have not used it, I've heard a lot about it.
You might find better responses for chosing an upgrade path over at gamedev.stackexchange.com though.

Categories