StreamWriter MVVM C# writes variable address? - c#

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);
}

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();
}

Accessing a Json array as string array

I have this code which reads from my json file an array of words
public static string[] GetProfanity()
{
var json = string.Empty;
using (var fs = File.OpenRead("profanity.json"))
using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
json = sr.ReadToEnd();
var profanityJson = JsonConvert.DeserializeObject<ProfanityJson>(json);
return profanityJson.badwords;
}
This is the json
{
"badwords" : ["bad", "stupid"]
}
And i try to access this here
public static bool ProfanityCheck(string inputString)
{
string[] badWords = GetProfanity();
string checkString = inputString.ToLower();
if (badWords.Any(checkString.Contains))
return true;
return false;
}
As requested I access the ProfanityCheck method here
[Command("echo")]
[Description("says whatever the user gives")]
public async Task Echo(CommandContext ctx, [RemainingText] string echoText)
{
bool hasProfanity = ProfanityFilter.ProfanityCheck(echoText);
if(hasProfanity)
{
var errMsg = ProfanityFilter.ErrorMessage();
var errSent = await ctx.Channel.SendMessageAsync(embed: errMsg).ConfigureAwait(false);
Thread.Sleep(3000);
await ctx.Channel.DeleteMessageAsync(errSent).ConfigureAwait(false);
await ctx.Channel.DeleteMessageAsync(ctx.Message).ConfigureAwait(false);
return;
}
await ctx.Channel.SendMessageAsync(echoText).ConfigureAwait(false);
}
and the struct I Deserialize it as
public struct ProfanityJson
{
[JsonProperty("badwords")]
public string[] badwords { get; private set; }
}
but when i attempt to search for this any bad words in a string I pass, nothing happens, no errors in the console, no output otherwise. I have it set up so that it sends me an error message when profanity is found, but in its current state it does nothing when profanity is passed
Your code seems to be correct... I would write the GetProfanity() in another way (and I wouldn't surely reread it every time a word is passed to to ProfanityCheck) but this is tangential to your problem. I've written a minimum testable example:
public class ProfanityJson
{
public string[] badwords { get; set; }
}
public static class ProfanityChecker
{
public static string[] GetProfanity()
{
var json = string.Empty;
using (var fs = File.OpenRead("profanity.json"))
using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
json = sr.ReadToEnd();
var profanityJson = JsonConvert.DeserializeObject<ProfanityJson>(json);
return profanityJson.badwords;
}
public static string[] GetProfanity2()
{
using (var sr = new StreamReader("profanity.json"))
using (var jtr = new JsonTextReader(sr))
{
var ser = new JsonSerializer();
var profanityJson = ser.Deserialize<ProfanityJson>(jtr);
return profanityJson.badwords;
}
}
public static bool ProfanityCheck(string inputString)
{
string[] badWords = GetProfanity2();
Trace.WriteLine($"Loaded {badWords.Length} bad words");
string checkString = inputString.ToLower();
if (badWords.Any(checkString.Contains))
return true;
return false;
}
}
static void Main(string[] args)
{
Console.WriteLine(ProfanityChecker.ProfanityCheck("badder"));
}
So the only idea I have is that you are using a "stale" version of profanity.json. I've added a little loggin in the ProfanityCheck() method. It will go to the Output pane in Visual Studio.
(Would be a mess as a comment)
You could have your class like this:
public class ProfanityJson
{
[JsonProperty("badwords")]
public string[] Badwords { get; set; }
}
Is it like so? Json is case sensitive.

Access RichtextBox from BusinessLayer and show text on it using 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.

My list keeps appearing empty after using binary serialization, however is fine if deserialized

I am experiencing an issue where when I create a record and serialize it, accessing it immediately after, List _log; has a 0 count and no items. However, upon restart of my application (because the records are only loaded on startup) accessing the same record again does bring back the items that were contained in the list.
The List in question is being used by ItemsSource binding to a DataGrid if that will help any.
Record code below:
[Serializable]
public class Record
{
private List<LogEntry> _log;
private Account _account;
private string _callReason;
private string _customerName;
private DateTime _timeStamp;
public List<LogEntry> Log { get { return _log; } }
public Account Account { get { return _account; } }
public string CallReason { get { return _callReason; } }
public string CustomerName { get { return _customerName; } }
public DateTime TimeStamp { get { return _timeStamp; } }
/// <summary>
/// A record for interactions.
/// </summary>
/// <param name="account"></param>
/// <param name="customerName"></param>
/// <param name="callReason"></param>
/// <param name="log"></param>
public Record(Account account, string customerName, string callReason, List<LogEntry> log)
{
_account = account;
_customerName = customerName;
_callReason = callReason;
_log = log;
_timeStamp = DateTime.Now;
}
}
public class RecordKeeper
{
public List<Record> Records { get; protected set; }
public RecordKeeper()
{
Records = new List<Record>();
LoadUsers();
}
public void SaveUsers() // Save users data
{
try
{
var bf = new BinaryFormatter();
var file = new FileStream("Records.bin", FileMode.Create, FileAccess.Write);
bf.Serialize(file, Records.ToArray());
file.Close();
}
catch (Exception ex)
{
Log.Exception(ex, "Error while saving user data.");
}
}
private void LoadUsers() // Load users data
{
try
{
var bf = new BinaryFormatter();
var file = new FileStream("Records.bin", FileMode.Open, FileAccess.Read);
var infos = (Record[])bf.Deserialize(file);
file.Close();
Records = infos.ToList();
}
catch
{ }
}
Edit
I discovered where my issue occurs but I do not understand why this happens. I clear the listed being used by the DataGrid AFTER creating and serializing the record, however the value in the Record gets modified as well.
public MainWindow(RecordKeeper recordKeeper)
{
_recordKeeper = recordKeeper;
_logEntries = new List<LogEntry>();
InitializeComponent();
}
private List<LogEntry> _logEntries;
public List<LogEntry> LogEntries { get { return _logEntries; } }
private void Button_Click2(object sender, RoutedEventArgs e)
{
if (!DependencyObjectIsValid(this)) return;
var account = new Account(long.Parse(AccountNumberBox.Text));
List<LogEntry> recordLog = LogEntries; // count is 3
var record = new Record(account, CustomerName.Text, CallReason.Text, recordLog);
RecordKeeper.Records.Add(record);
RecordKeeper.SaveUsers(); // record.Log.Count is still 3
AccountNumberBox.Text = "";
CustomerName.Text = "";
CallReason.Text = "";
LogMessage.Text = "";
LogEntries.Clear(); // record.Log.Count is 0, shouldn't the instance be separate and immutable at this point in execution?
LogGrid.Items.Refresh();
RecordGrid.Items.Refresh();
}
Edit 2
Creating a new list in the record seemed to do the trick for me
replacing
`_log = log; `
with
`_log = new List<LogEntry>();
foreach (LogEntry entry in log)
{
_log.Add(entry);
}`
In Record's constructor. Not sure it's the best practice though to achieve this.
Thanks https://stackoverflow.com/users/17034/hans-passant
Edit 3
List<LogEntry> recordLog = new List<LogEntry>(LogEntries);

Memory Exception; NullReference; CA1001 implement IDisposable

I have small program that takes the links from a text file, pass those links to backend system at ImportIO, and save the results to a CSV. However I am seeing following errors after 15,20 min of run. I encounter two exception whichever comes first
1. System.OutOfMemoryException
OR
2. System.NUllReferenceException
Both of these are however I feel my fault somewhere in the code. I am not an expert but I tried to use timer, or closing the files, or even setting objects to null. None worked or even using ArgumentNullException.
I ran the code analysis and it suggested that I should Idispose by this error.
CA1001 Types that own disposable fields should be disposable Implement
IDisposable on 'ImportIO' because it creates members of the following
IDisposable types: 'BlockingCollection>'. Ostock Main.cs 232
My code is as followed, I am not including importIO class it is long. I think solution is easy but I am just not on right path. Could you guys please help?
namespace MinimalCometLibrary
{
class Program
{
private static CountdownEvent countdownLatch;
static void Main(string[] args)
{
string[] lines = File.ReadAllLines(#"C:\Users\James\Desktop\Exper\Input_Links\Stock_links.txt");
for (int i = 0; i < lines.Length; i++)
{
string[] line = lines[i].Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
for (int j = 0; j < line.Length; j++)
{
ImportIO io = new ImportIO("https://query.import.io", Guid.Parse("sdasd-asdasd-NoReal-3easdecb"), "NoReal=");
/* Time Starts
Stopwatch sw = new Stopwatch(); // sw cotructor
sw.Start(); // starts the stopwatch
for (int b = 0; ; b++)
{
if (b % 1000 == 0) // if in 100000th iteration (could be any other large number
// depending on how often you want the time to be checked)
{
sw.Stop(); // stop the time measurement
if (sw.ElapsedMilliseconds > 25) // check if desired period of time has elapsed
{
break; // if more than 5000 milliseconds have passed, stop looping and return
// to the existing code
}
else
{
sw.Start(); // if less than 5000 milliseconds have elapsed, continue looping
// and resume time measurement
}
}
}
//Time Ends
*/
io.Connect();
countdownLatch = new CountdownEvent(1);
// Query for tile SamsClub_Extractor, line[j]
Dictionary<String, Object> query1 = new Dictionary<string, object>();
query1.Add("input", new Dictionary<String, String>() { { "webpage/url", line[j] } });
query1.Add("connectorGuids", new List<String>() { "189f34f3-0f82-4abb-8fbc-f353f35a255a" });
io.DoQuery(query1, HandleQuery);
countdownLatch.Wait();
io.Disconnect();
}
}
Environment.Exit(0);
}
private static void HandleQuery(Query query, Dictionary<String, Object> message)
{
if (message["type"].Equals("MESSAGE"))
{
Console.WriteLine("Got data!");
string JSON = JsonConvert.SerializeObject(message["data"]);
//Deserialize to strongly typed class i.e., RootObject
RootObject obj = JsonConvert.DeserializeObject<RootObject>(JSON);
// handle null reference
if (obj == null) { throw new ArgumentNullException("PleaseKeepRunning"); }
//loop through the list and write to CSV file
foreach (Result resultsItem in obj.results)
{
Console.WriteLine(resultsItem.itemnbr + "-" + resultsItem.price +
"-" + resultsItem.product_name + "_" + obj.pageUrl);
string filePath = #"C:\Users\James\Desktop\Exper\Output_Files\StockPrice_NOW.txt";
//checking if file already exists, if not, create it:
if (!File.Exists(filePath))
{
FileStream fs = new FileStream(filePath, FileMode.CreateNew);
fs.Close();
}
//writing to a file (appending text):
using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write))
{
using (TextWriter tw = new StreamWriter(fs))
tw.WriteLine(resultsItem.itemnbr + "\t" + resultsItem.price + "\t" + resultsItem.product_name + "\t" + resultsItem.misc +
"\t" + resultsItem.qty + "\t" + obj.pageUrl);
fs.Close();
}
//Set object to null
obj = null;
obj.results = null;
}
}
if (query.isFinished) countdownLatch.Signal();
}
}
//root Object
public class Result
{
public double price { get; set; }
public string itemnbr { get; set; }
public string product_name { get; set; }
public string qty { get; set; }
public string misc { get; set; }
}
public class RootObject
{
public List<string> cookies { get; set; }
public List<Result> results { get; set; }
public string pageUrl { get; set; }
public string connectorGuid { get; set; }
public string connectorVersionGuid { get; set; }
public int offset { get; set; }
}
Please excuse my limited knowledge in .net. I am totally new to it. :)
Thanks
---- Edit
I used dispose and using as suggested but I am still facing the error. I am seeing error exception and debugger highlight this code of line in importIO.
new Thread(new ThreadStart(PollQueue)).Start();
I also observe that stock.vshost.exe *32 also keep increasing memory and throw out of memory exception at any time after 70MB or something. I am including the importIO class code
class ImportIO
{
private String host { get; set; }
private int port { get; set; }
private Guid userGuid;
private String apiKey;
private static String messagingChannel = "/messaging";
private String url;
private int msgId = 0;
private String clientId;
private Boolean isConnected;
CookieContainer cookieContainer = new CookieContainer();
Dictionary<Guid, Query> queries = new Dictionary<Guid, Query>();
private BlockingCollection<Dictionary<String, Object>> messageQueue = new BlockingCollection<Dictionary<string, object>>();
public ImportIO(String host = "http://query.import.io", Guid userGuid = default(Guid), String apiKey = null)
{
this.userGuid = userGuid;
this.apiKey = apiKey;
this.url = host + "/query/comet/";
clientId = null;
}
public void Login(String username, String password, String host = "http://api.import.io")
{
Console.WriteLine("Logging in");
String loginParams = "username=" + HttpUtility.UrlEncode(username) + "&password=" + HttpUtility.UrlEncode(password);
String searchUrl = host + "/auth/login";
HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create(searchUrl);
loginRequest.Method = "POST";
loginRequest.ContentType = "application/x-www-form-urlencoded";
loginRequest.ContentLength = loginParams.Length;
loginRequest.CookieContainer = cookieContainer;
using (Stream dataStream = loginRequest.GetRequestStream())
{
dataStream.Write(System.Text.UTF8Encoding.UTF8.GetBytes(loginParams), 0, loginParams.Length);
HttpWebResponse loginResponse = (HttpWebResponse)loginRequest.GetResponse();
if (loginResponse.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Could not log in, code:" + loginResponse.StatusCode);
}
else
{
foreach (Cookie cookie in loginResponse.Cookies)
{
if (cookie.Name.Equals("AUTH"))
{
// Login was successful
Console.WriteLine("Login Successful");
}
}
}
}
}
public List<Dictionary<String, Object>> Request(String channel, Dictionary<String, Object> data = null, String path = "", Boolean doThrow = true)
{
Dictionary<String, Object> dataPacket = new Dictionary<String, Object>();
dataPacket.Add("channel", channel);
dataPacket.Add("connectionType", "long-polling");
dataPacket.Add("id", (msgId++).ToString());
if (this.clientId != null)
dataPacket.Add("clientId", this.clientId);
if (data != null)
{
foreach (KeyValuePair<String, Object> entry in data)
{
dataPacket.Add(entry.Key, entry.Value);
}
}
String url = this.url + path;
if (apiKey != null)
{
url += "?_user=" + HttpUtility.UrlEncode(userGuid.ToString()) + "&_apikey=" + HttpUtility.UrlEncode(apiKey);
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-8";
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip");
String dataJson = JsonConvert.SerializeObject(new List<Object>() { dataPacket });
request.ContentLength = dataJson.Length;
request.CookieContainer = cookieContainer;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(System.Text.UTF8Encoding.UTF8.GetBytes(dataJson), 0, dataJson.Length);
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader responseStream = new StreamReader(response.GetResponseStream()))
{
String responseJson = responseStream.ReadToEnd();
List<Dictionary<String, Object>> responseList = JsonConvert.DeserializeObject<List<Dictionary<String, Object>>>(responseJson);
foreach (Dictionary<String, Object> responseDict in responseList)
{
if (responseDict.ContainsKey("successful") && (bool)responseDict["successful"] != true)
{
if (doThrow)
throw new Exception("Unsucessful request");
}
if (!responseDict["channel"].Equals(messagingChannel)) continue;
if (responseDict.ContainsKey("data"))
{
messageQueue.Add(((Newtonsoft.Json.Linq.JObject)responseDict["data"]).ToObject<Dictionary<String, Object>>());
}
}
return responseList;
}
}
catch (Exception e)
{
Console.WriteLine("Error occurred {0}", e.Message);
return new List<Dictionary<String, Object>>();
}
}
}
public void Handshake()
{
Dictionary<String, Object> handshakeData = new Dictionary<String, Object>();
handshakeData.Add("version", "1.0");
handshakeData.Add("minimumVersion", "0.9");
handshakeData.Add("supportedConnectionTypes", new List<String> { "long-polling" });
handshakeData.Add("advice", new Dictionary<String, int>() { { "timeout", 60000 }, { "interval", 0 } });
List<Dictionary<String, Object>> responseList = Request("/meta/handshake", handshakeData, "handshake");
clientId = (String)responseList[0]["clientId"];
}
public void Connect()
{
if (isConnected)
{
return;
}
Handshake();
Dictionary<String, Object> subscribeData = new Dictionary<string, object>();
subscribeData.Add("subscription", messagingChannel);
Request("/meta/subscribe", subscribeData);
isConnected = true;
new Thread(new ThreadStart(Poll)).Start();
new Thread(new ThreadStart(PollQueue)).Start();
}
public void Disconnect()
{
Request("/meta/disconnect", null, "", true);
isConnected = false;
}
private void Poll()
{
while (isConnected)
{
Request("/meta/connect", null, "connect", false);
}
}
private void PollQueue()
{
while (isConnected)
{
ProcessMessage(messageQueue.Take());
}
}
private void ProcessMessage(Dictionary<String, Object> data)
{
Guid requestId = Guid.Parse((String)data["requestId"]);
Query query = queries[requestId];
query.OnMessage(data);
if (query.isFinished)
{
queries.Remove(requestId);
}
}
public void DoQuery(Dictionary<String, Object> query, QueryHandler queryHandler)
{
Guid requestId = Guid.NewGuid();
queries.Add(requestId, new Query(query, queryHandler));
query.Add("requestId", requestId);
Request("/service/query", new Dictionary<String, Object>() { { "data", query } });
}
}
Try calling Dispose() method because as seen in your error message , it's a memory error because you keep opening files and reading them and then keeping the data there loaded on memory which causes the crash you see after some time
Try this :
if (!File.Exists(filePath))
{
FileStream fs = new FileStream(filePath, FileMode.CreateNew);
fs.Close();
fs.Dispose();
}
Also use the using() { } for the ImportIO class
using(ImportIO myIO = new ImportIO) { }
I can't say if your exceptions are related to it or not without seeing complete code, but the warning is about an issue "in" ImportIO, not in the code that's calling it (it's complaining that the ImportIO class does not implement IDisposable, not that you do something wrong with it)
Since you edited with the class : just implement IDisposable on your ImportIO class, here's a link on how to properly implement IDisposable : Implementing IDisposable correctly
Make sure to dispose of the BlockingCollection in the dispose of your ImportIO.
Then wrap your ImportIO in a using and the warning should go away. I'd be surprised if that alone caused those exceptions however but this is the way to fix your warning.

Categories

Resources