Unable to close a streamwriter and reopen to append data - c#

I created a little class in order to create logs.
This class use streamwriter functions in order to do this.
I write a log, and after closed the log, i would like to re-open after, in order to append some datas.
I tried severals tips, and...i always have an exception who tell me " The file is used by another process".
Nevertheless, i use the close(), but, i always had this exception.
Here is my class :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace TEST
{
public class CLog
{
private StreamWriter myWriter;
public string Name
{
set { Name = value; }
get
{
FileInfo myFile = new FileInfo(CompleteFileName);
return myFile.Name;
}
}
public string Directory
{
set { Directory = value; }
get
{
FileInfo myFile = new FileInfo(CompleteFileName);
return myFile.Directory.ToString();
}
}
public string CompleteFileName { set; get; }
public CLog(string _CompleteFileName)
{
CompleteFileName = _CompleteFileName;
}
public bool CreateLog()
{
try
{
myWriter = new StreamWriter(CompleteFileName);
return true;
}
catch (Exception ex )
{
return false;
}
}
public bool AppendTextToFile(string strText)
{
try
{
using (System.IO.StreamWriter sw = System.IO.File.AppendText(CompleteFileName))
{
sw.WriteLine(strText);
}
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool WriteLine(string strLine)
{
try
{
myWriter.WriteLine(strLine);
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool SaveFile()
{
try
{
myWriter.Close();
myWriter.Dispose();
return true;
}
catch (Exception ex)
{
return false;
}
}
}
}
Please look at the AppendTextToFile.
Here is the use :
monLog = new CLog("C:\\TEST.TXT");
if (monLog.CreateLog())
{
monLog.WriteLine("");
monLog.WriteLine("******");
monLog.WriteLine("Some data");
monLog.WriteLine("******");
monLog.SaveFile();
...
....
monLog.AppendTextToFile("** my AppendedData***);
monLog.SaveFile();
}
Anyone know why i have this exception and how solve it ?
Thanks a lot :)

Related

Issue with Xamarin.Google.Guava

I think I understand the error but I have no idea how to solve it :/
This is the error I'm getting:
"JAR library references with identical file names but different contents were found: __reference__guava.jar. Please remove any conflicting libraries from EmbeddedJar, InputJar and AndroidJavaLibrary. Food_Recipe_App.Android"
Reason to why I want Xamarin.Google.Guava is that someone said that it would fix an issue I had earlier;
"System.NullReferenceException
Message=Object reference not set to an instance of an object."
Which, honestly, I have no idea how to solve either.
I'm thankful for all help :)
Edit: It breaks after calling the Firestore.Read();
protected override async void OnAppearing()
{
base.OnAppearing();
//using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
//{
// conn.CreateTable<Recipe>();
// var recipes = conn.Table<Recipe>().ToList();
// //recipeListView.ItemsSource = recipes;
//};
var recipes = await Firestore.Read(); ***//this line breaks***
//assignRecipesToDays(recipes);
}
This is the Read method from my Firestore script:
public async Task<List<Recipe>> Read()
{
try
{
hasReadRecipes = false;
var collection = FirebaseFirestore.Instance.Collection("recipes");
var query = collection.WhereEqualTo("userId", FirebaseAuth.Instance.CurrentUser.Uid);
query.Get().AddOnCompleteListener(this);
for (int i = 0; i < 50; i++)
{
await System.Threading.Tasks.Task.Delay(100);
if (hasReadRecipes)
break;
}
return recipes;
}
catch (Exception ex)
{
return recipes;
}
}
And this is the whole Firestore Script if that helps solving it:
using Android.App;
using Android.Content;
using Android.Gms.Tasks;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Firebase.Auth;
using Firebase.Firestore;
using Food_Recipe_App.Assets.Classes;
using Food_Recipe_App.Helpers;
using Java.Interop;
using Java.Util;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xamarin.Forms;
[assembly: Dependency(typeof(Food_Recipe_App.Droid.Dependencies.Auth))]
namespace Food_Recipe_App.Droid.Dependencies
{
public class Firestore : Java.Lang.Object, IFirestore, IOnCompleteListener
{
List<Recipe> recipes;
bool hasReadRecipes = false;
public Firestore()
{
recipes = new List<Recipe>();
}
public async Task<bool> Delete(Recipe recipe)
{
try
{
var collection = FirebaseFirestore.Instance.Collection("recipes");
collection.Document(recipe.Id).Delete();
return true;
}
catch (Exception ex)
{
return false;
}
}
public async Task<bool> Insert(Recipe recipe)
{
try
{
var recipeDocument = new Dictionary<string, Java.Lang.Object>()
{
{ "title", recipe.title },
{ "description", recipe.description },
{ "creatorUserId", FirebaseAuth.Instance.CurrentUser.Uid }
};
var collection = Firebase.Firestore.FirebaseFirestore.Instance.Collection("recipes");
collection.Add(new HashMap(recipeDocument));
return true;
}
catch (Exception ex)
{
return false;
}
}
public void OnComplete(Android.Gms.Tasks.Task task)
{
if (task.IsSuccessful)
{
var documents = (QuerySnapshot)task.Result;
recipes.Clear();
foreach (var doc in documents.Documents)
{
Recipe newRecipe = new Recipe()
{
title = doc.Get("title").ToString(),
description = doc.Get("description").ToString(),
Id = doc.Id
};
recipes.Add(newRecipe);
}
}
else
{
recipes.Clear();
}
hasReadRecipes = true;
}
public async Task<List<Recipe>> Read()
{
try
{
hasReadRecipes = false;
var collection = FirebaseFirestore.Instance.Collection("recipes");
var query = collection.WhereEqualTo("userId", FirebaseAuth.Instance.CurrentUser.Uid);
query.Get().AddOnCompleteListener(this);
for (int i = 0; i < 50; i++)
{
await System.Threading.Tasks.Task.Delay(100);
if (hasReadRecipes)
break;
}
return recipes;
}
catch (Exception ex)
{
return recipes;
}
}
public async Task<bool> Update(Recipe recipe)
{
try
{
var recipeDocument = new Dictionary<string, Java.Lang.Object>()
{
{ "title", recipe.title },
{ "description", recipe.description },
{ "creatorUserId", FirebaseAuth.Instance.CurrentUser.Uid }
};
var collection = FirebaseFirestore.Instance.Collection("recipes");
collection.Document(recipe.Id).Update(recipeDocument);
return true;
}
catch (Exception ex)
{
return false;
}
}
}
}

: Error CS1729: 'SQLiteConnection' does not contain a constructor that takes 1 arguments (CS1729)

Does anyone have any idea of how to solve this error message
Error CS1729: 'SQLiteConnection' does not contain a constructor that takes 1 arguments (CS1729)
this is the files where it is happening
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using SQLite;
using Android.Util;
using SQLite.Net;
namespace CPDEP1
{
public class DataBase
{
string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
public bool createDataBase()
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Persons.db")));
{
connection.CreateTable<Person>();
return true;
}
}
catch(SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return false;
}
}
public bool insertIntoTablePerson(Person person)
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Persons.db")))
{
connection.Insert(person);
return true;
}
}
catch(SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return false;
}
}
public List<Person> selectTablePerson()
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Persons.db")))
{
return connection.Table<Person>().ToList();
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return null;
}
}
public bool updateTablePerson(Person person)
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Persons.db")))
{
connection.Query<Person>("UPDATE Person set Nom=?,Prenom=?,Telephone=?,Addresse=?,Courriel=?,Cin=? Where Id=?,",person.Nom,person.Prennom,person.Telephone,person.Addresse,person.Courriel,person.Cin,person.Id);
return true;
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return false;
}
}
public bool deleteTablePerson(Person person)
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Persons.db")))
{
connection.Delete(person);
return true;
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return false;
}
}
public bool selectQueryTablePerson(int Id)
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Persons.db")))
{
connection.Query<Person>("SELECT * FROM Person Where Id=?", Id);
return true;
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return false;
}
}
}
}
Thanks in advance for your help
I was following the instruction here: https://wolfprogrammer.com/2016/09/10/adding-a-sqlite-database-to-xamarin-forms/ and got the same error.
Then I referred to Microsoft instruction here (https://msdn.microsoft.com/en-us/magazine/mt736454.aspx) and noticed there are 2 very similar thing both written by Frank Krueger. Please check the image below, download the one that is highlighted in GREEN, not the RED one.

Contructor is inaccessible due to its protection level

my error is:
Error 1 'aCI.CheckTexture.CheckTexture()' is inaccessible due to its
protection level
and i use this code to check some files MD5/Hash :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace aCI
{
class CheckTexture
{
Thread Search;
protected CheckTexture()
{
Search = new Thread(Scan);
Search.Start();
}
protected void Scan()
{
if (GetMD5Hash("1.rar") != "9647997C556C5A37A63EFAFBCA4A40D0"
|| GetMD5Hash("2.rar") != "6626959A9099B4C6F5C755E0D2E57EF8"
|| GetMD5Hash("3.rar") != "4D6611A825F81024E0153E2753B8A27E")
{
System.Windows.Forms.MessageBox.Show(
"Sorry come back and restor your orginal files.",
"Error",
System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.Error);
return;
}
}
#region Hash Calculator
private static byte[] ConvertStringToByteArray(string data)
{
return (new System.Text.UnicodeEncoding()).GetBytes(data);
}
private static System.IO.FileStream GetFileStream(string pathName)
{
return (new System.IO.FileStream(pathName, System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite));
}
public static string GetSHA1Hash(string pathName)
{
string strResult = "";
string strHashData = "";
byte[] arrbytHashValue;
System.IO.FileStream oFileStream = null;
System.Security.Cryptography.SHA1CryptoServiceProvider oSHA1Hasher =
new System.Security.Cryptography.SHA1CryptoServiceProvider();
try
{
oFileStream = GetFileStream(pathName);
arrbytHashValue = oSHA1Hasher.ComputeHash(oFileStream);
oFileStream.Close();
strHashData = System.BitConverter.ToString(arrbytHashValue);
strHashData = strHashData.Replace("-", "");
strResult = strHashData;
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message, "Error!",
System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.Error,
System.Windows.Forms.MessageBoxDefaultButton.Button1);
}
return (strResult);
}
public static string GetMD5Hash(string pathName)
{
string strResult = "";
string strHashData = "";
byte[] arrbytHashValue;
System.IO.FileStream oFileStream = null;
System.Security.Cryptography.MD5CryptoServiceProvider oMD5Hasher =
new System.Security.Cryptography.MD5CryptoServiceProvider();
try
{
oFileStream = GetFileStream(pathName);
arrbytHashValue = oMD5Hasher.ComputeHash(oFileStream);
oFileStream.Close();
strHashData = System.BitConverter.ToString(arrbytHashValue);
strHashData = strHashData.Replace("-", "");
strResult = strHashData;
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message, "Error!",
System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.Error,
System.Windows.Forms.MessageBoxDefaultButton.Button1);
}
return (strResult);
}
#endregion
}
}
Then i try Using class CheckTexture from the above code in here:
private void BtnMpLanClick(object sender, RoutedEventArgs e)
{
if (!File.Exists("chrome.exe"))
{
MessageBox.Show("Cannot find chrome.exe");
return;
}
else
{
//Process.Start("chrome.exe");
this.StartTheProcess("chrome.exe", "");
Thread.Sleep(10);
try
{
// I have error on this line:
CheckTexture Scan = new CheckTexture();
}
catch (Exception)
{ }
}
}
but I have that error on this line:
CheckTexture Scan = new CheckTexture();
SO pleas if possible someone tel me what is my mistake.
Thank you for help
The class isn't public. Change it to:
public class CheckTexture
{
Thread Search;
public CheckTexture()
{
Search = new Thread(Scan);
Search.Start();
}
In C#, default access modifier of classes is internal.
So your CheckTexture class is internal. Change it to public like;
public class CheckTexture
{
...
}
From Access Modifiers (C# Programming Guide)
Classes and structs that are declared directly within a namespace (in
other words, that are not nested within other classes or structs) can
be either public or internal. Internal is the default if no access
modifier is specified.
But this doesn't enough. Because when you write;
CheckTexture Scan = new CheckTexture();
This calls parameterless constructor of CheckTexture class which its access modifier is protected. Make it public also.
public CheckTexture()
{
Search = new Thread(Scan);
Search.Start();
}
by default the class in C# is internal. Mark it public. Based on #Caramiriel comment, the constructor also needs to be marked public

IRibbonExtensibility->GetCustomUI calling from a class other than Connect.cs

I am using Vs2010 -> Extensibility->Shared Add-in
Connect.cs file
public class Connect : Object, Extensibility.IDTExtensibility2, IRibbonExtensibility
{
public string GetCustomUI(string RibbonID)
{
return MyResources.customUI;
}
}
The Ribbons gets created using this above code.
I have Class customRibbons.cs
public class Create_Custom_Ribbons : IRibbonExtensibility
{
Outlook.Application applicationObject;
public Create_Custom_Ribbons(Outlook.Application application)
{
try
{
applicationObject = application;
GetCustomUI("");
}
catch(Exception ex)
{
MessageBox.Show(""+ex.StackTrace);
}
}
public string GetCustomUI(string RibbonID)
{
return MyResource.customUI;
}
}
and on Connect.cs
public void OnStartupComplete(ref System.Array custom)
{
try
{
customRibbons.Create_Custom_Ribbons cu = new
customRibbons.Create_Custom_Ribbons(applicationObject);
}
catch (Exception ex)
{
MessageBox.Show("" + ex.StackTrace);
}
}
But the Ribbons is not getting created.Please can anyone tell me what am i doing wrong or any other way to achieve this.I am not able to understand y it is not getting created.
See my reply at the Office Dev group: http://social.msdn.microsoft.com/Forums/en-US/outlookdev/thread/394ac918-f32f-4c7b-9dee-a6d45f1bdf46

Token EndElement in state EndRootElement would result in an invalid XML document

I am developing an application for wp7.i am storing the state of my application in isolatedstoragefile using datacontractserializer.Now when i try to serialize the object
sometimes i face this exception.
Token EndElement in state EndRootElement would result in an invalid
XML document. Make sure that the ConformanceLevel setting is set to
ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to
write an XML fragment.
here is my class which i am serializing
[DataContract]
public class TcpSessionProperties
{
[DataMember]
public int NumberOfReceivedStanzas { get { return _numberOfReceivedStanzas; } set { _numberOfReceivedStanzas = value; } }
[DataMember]
public int NumberOfPacketsSent { get { return _numberOfPacketsSent; } set { _numberOfPacketsSent = value; } }
[DataMember]
public List<TcpPacket> PendingPacketsToSendQueue
{
get { return _pendinPacketsToSendQueue; }
set
{
LogUtility.Log(Thread.CurrentThread.GetHashCode());
_pendinPacketsToSendQueue = value;
}
}
}
cla
Here is my code where i am serializing and deserializing
public class AppCacheIsolatedFile
{
public static void Add(object val)
{
private static object _objectToSave;
lock (_storageLock)
{
/*
if (PhoneApplicationService.Current.State.ContainsKey(key))
PhoneApplicationService.Current.State[key] = val;
else
PhoneApplicationService.Current.State.Add(key, val);
*/
_objectToSave = val;
WriteObject(NameOfFile, val, typeof(StreamingSocketConnection.StreamingSocketConnection));
}
public static void WriteObject(string fileName,object val,Type type)
{
try
{
Console.WriteLine(
"Creating a Person object and serializing it.");
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileName, FileMode.Create, IsoStore))
{
DataContractSerializer dcs = new DataContractSerializer(type);
dcs.WriteObject(stream, val);
}
}
catch (Exception exception)
{
LogUtility.NotifyUserAndLog("Exception occured in isolatd storage file while writing "+exception.StackTrace);
}
}
}
That exception occurs at dcs.writeobject. I donnot why is this happening.

Categories

Resources