I am working on different approaches of cloning of an objects in c# but currently I stuck with the simple one. I have a static class with static variables & I want to make an exact copy of one of my static variable.I have sketched my code structure below:
public static class RULE_SET
{
public static bool IsdataValid;
public static GCBRequest GCBData;
public static T Clone<T>(this T source)
{
try
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", "source");
}
if (Object.ReferenceEquals(source, null))
{
return default(T);
}
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
catch (Exception ee) { return default(T); }
}
}
[XmlRoot(ElementName = "GCBRequest")]
public class GCBRequest
{
[XmlElement(ElementName = "PID")]
public string PID { get; set; }
[XmlElement(ElementName = "AID")]
public string AID { get; set; }
[XmlElement(ElementName = "CID")]
public string CID { get; set; }
}
//code to load the RULE_SET
string strJsonRuleset = "{\r\n \"GCdBINRequest\": {\r\n\"PID\": \"(?s).*#M#20\",\r\n\"AID\": \"(?s).*#O#10\",\r\n\"CID\": \"(?s).*#O#25\"\r\n }\r\n}";
public class RULE_SET_LOCAL
{
public static GCBRequest GCBData;
}
//from other method
RULE_SET_LOCAL objParentRuleSet = new RULE_SET_LOCAL();
objParentRuleSet = JsonConvert.DeserializeObject<RULE_SET_LOCAL>(strJsonRuleset);
RULE_SET.GCBData = objParentRuleSet.GCBData;
//Main Method from which I have to create a clone object
Object objRuleset;
objRuleset = RULE_SET.GCBData.Clone();
if(objRuleset == null)
{
** stuck here**
I don't know why Everytime I got the null object ?
}
// but I have use
objRuleset = RULE_SET.GCBData;
if(objRuleset != null)
{
** Successfully reached **
//But I can't do any operation on this object as it will effect the original one.
}
Guys, Do you have any solution/Suggestion ?
Please help me to understand this , any help will be appreciated.
Thanks.
After searching a lot I got this method :
public static T Clone<T>(this T source)
{
var serialized = JsonConvert.SerializeObject(source);
return JsonConvert.DeserializeObject<T>(serialized);
}
& now I am able to get the clone by calling
object objRuleset = RULE_SET.Clone<GCBRequest>(RULE_SET.GCBData);
Related
I'm trying to get at the individual 32bit samples using CScore. What I have so far is
public MainWindow()
{
InitializeComponent();
var wasapiCapture = new WasapiCapture();
wasapiCapture.Initialize();
wasapiCapture.Start();
var wasapiCaptureSource = new SoundInSource(wasapiCapture);
var stereoSource = wasapiCaptureSource.ToStereo();
var ieeeFloatToSample = new IeeeFloatToSample(stereoSource);
var sampleProvider = new SampleProvider(ieeeFloatToSample);
var wavesource = sampleProvider.ToWaveSource();
var wasapiOut = new WasapiOut();
wasapiOut.Initialize(wavesource);
wasapiOut.Play();
}
And a class
class SampleProvider : ISampleSource
{
private ISampleSource _source;
public SampleProvider(ISampleSource source)
{
this._source = source;
}
public int Read(float[] buffer, int offset, int count)
{
var sampleRead = _source.Read(buffer, 0, count);
return sampleRead;
}
public void Dispose()
{
throw new NotImplementedException();
}
public WaveFormat WaveFormat { get; private set; }
public long Position { get; set; }
public long Length { get; private set; }
}
Which I thought would pass the audio through unchanged but I am getting an error on the sampleProvider.ToWaveSource(); saying "Object reference not set to an instance of an object"
Any ideas? Thanks.
If you poke around through the CSCore source you'll find that ToWaveSource ends up cloning the WaveFormat of your SampleProvider - which you've left undefined. You can probably just return the WaveFormat from the upstream source:
public WaveFormat WaveFormat { get { return _source.WaveFormat; } }
I have this base class structure:
Base:
public abstract class BackgroundTask
{
protected readonly Logger Logger = LogManager.GetCurrentClassLogger();
protected virtual void Initialize()
{
// initialize database access
}
public void Run()
{
Initialize();
try
{
Execute();
// insert to database or whatever
}
catch (Exception ex)
{
Logger.ErrorException(string.Format("Error proccesing task: {0}\r\n", ToString()), ex);
Exceptions.Add(ex);
}
finally
{
TaskExecuter.Discard();
}
}
protected abstract void Execute();
public abstract override string ToString();
public IList<Exception> Exceptions = new List<Exception>();
}
Task executor:
public static class TaskExecuter
{
private static readonly ThreadLocal<IList<BackgroundTask>> TasksToExecute
= new ThreadLocal<IList<BackgroundTask>>(() => new List<BackgroundTask>());
public static void ExecuteLater(BackgroundTask task)
{
TasksToExecute.Value.Add(task);
}
public static void StartExecuting()
{
foreach (var backgroundTask in TasksToExecute.Value)
{
Task.Factory.StartNew(backgroundTask.Run);
}
}
public static void Discard()
{
TasksToExecute.Value.Clear();
TasksToExecute.Dispose();
}
}
FileTask:
public class FileTask : BackgroundTask
{
protected static string BaseFolder = #"C:\ASCII\";
private static readonly ReaderWriterLockSlim Lock = new ReaderWriterLockSlim();
private readonly string _folder;
private IHistoryRepository _historyRepository;
public string Folder
{
get { return _folder; }
}
public FileTask(string folder)
{
_folder = string.Format("{0}{1}", BaseFolder, folder);
}
protected override void Initialize()
{
_historyRepository = new HistoryRepository();
}
protected override void Execute()
{
// todo: Get institute that are active,
var institute = MockInstitute(); // todo: uncomment _historyRepository.FindInstituteByFolderName(Folder);
// todo: Update institute, lastupdate - [date] | [files amount] | [phonenumbers amount]
if (institute == null)
{
Logger.Warn("Not found data", Folder);
return;
}
// todo: read file get encoding | type and parse it
Task.Factory.StartNew(ReadFile);
}
private void ReadFile()
{
var list = GetFilesByFolder();
StreamReader sr = null;
try
{
Lock.EnterReadLock();
foreach (var fi in list)
{
var fileName = fi.FullName;
Logger.Info("Line: {0}:=> Content: {1}", fileName, Thread.CurrentThread.ManagedThreadId);
sr = new StreamReader(fileName, DetectEncoding(fileName));
string currentLine;
while ((currentLine = sr.ReadLine()).ReturnSuccess())
{
if (string.IsNullOrEmpty(currentLine)) continue;
Logger.Info("Line: {0}:=> Content: {1}", fileName, currentLine);
}
}
Lock.ExitReadLock();
}
finally
{
if (sr != null) sr.Dispose();
Logger.Info("Finished working" + Folder);
}
}
protected IEnumerable<FileInfo> GetFilesByFolder()
{
return Directory.GetFiles(Folder).Select(fileName => new FileInfo(fileName));
}
protected Encoding DetectEncoding(string file)
{
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
var cdet = new Ude.CharsetDetector();
cdet.Feed(fs);
cdet.DataEnd();
return cdet.With(x => x.Charset)
.Return(x => Encoding.GetEncoding(cdet.Charset),
Encoding.GetEncoding("windows-1255"));
}
}
private Institute MockInstitute()
{
return new Institute
{
FromFolderLocation = string.Format("{0}{1}", BaseFolder, Folder)
};
}
public override string ToString()
{
return string.Format("Folder: {0}", Folder);
}
}
When don't read the file every thing ok, the Log is populated and every thing runs smooth,
but when i attach the Task.Factory.StartNew(ReadFile); method i have an exception.
Exception:
Cannot access a disposed object.
Object name: 'The ThreadLocal object has been disposed.'.
How do i solve that issue? might i need to change the LocalThread logic, or what - i have been trying to handle that issue, for almost a day.
BTW: It's an MVC4 project, and C# 5.0 and i'm trying to TDD it all.
You shouldn't be calling TasksToExecute.Dispose();
there.
I mae a WCF service that contain this method :
public List<LocationDB> GetLocation()
{
List<LocationDB> locations = null;
using (SqlConnection connection = new SqlConnection(conn))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = string.Format("Select L_ID ,L_Name from Location");
connection.Open();
//code to fill the locations list..
my problem is when i want to bind the result from this method in my code i do the following.
void MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
client.GetLocationCompleted += new EventHandler<GetLocationCompletedEventArgs>(client_GetLocationCompleted);
client.GetLocationAsync();
}
}
and :
void client_GetLocationCompleted(object sender, GetLocationCompletedEventArgs e)
{
LocationCombo.ItemsSource = e.Result;
LocationCombo.SelectedValuePath =
LocationCombo.DisplayMemberPath =
}
and finally my LocationDB Class that is located in the App_code folder in the asp web site:
[DataContract]
public class LocationDB
{
[DataMember]
public int Lid { get; set; }
[DataMember]
public int SmId { get; set; }
[DataMember]
public string Lname { get; set; }
how can i bind the SelectedValePath and the DisplayMemberPath in code behind not in XAML.
Thanks
From what I can tell you already have everything you need although some of it needs to be in a different order.
void client_GetLocationCompleted(object sender, GetLocationCompletedEventArgs e)
{
LocationCombo.SelectedValuePath = "Lid";
LocationCombo.DisplayMemberPath = "Lname";
LocationCombo.ItemsSource = e.Result;
}
You should be able to set each of them to a string which represents the property (on the bject you're binding to) to use as the SelectedValuePath and DisplayMemberPath respectively:
LocationCombo.SelectedValuePath = "Lid";
LocationCombo.DisplayMemberPath ="Lname";
LocationCombo.ItemsSource = e.Result.ToList();
I have this code:
[Serializable]
[XmlRoot("ISO_CCY_CODES")]
public class IsoCurrencyCodes
{
public IsoCurrencyCodes()
{
IsoCodes = new List<IsoCurrencyCode>();
}
public IsoCurrencyCodes(List<IsoCurrencyCode> isoCodes)
{
IsoCodes = isoCodes;
}
[XmlArrayItem("ISO_CURRENCY")]
public List<IsoCurrencyCode> IsoCodes { get; set; }
public static IEnumerable<IsoCurrencyCode> Get()
{
var doc = XDocument.Parse(XmlStringIsoCodes.XmlSource.Replace("\r\n", ""));
var res = doc.Deserialize<IsoCurrencyCodes>();
return res.IsoCodes;
}
}
[Serializable]
[XmlRoot("ISO_CURRENCY")]
public class IsoCurrencyCode
{
public IsoCurrencyCode()
{
}
[XmlElement(ElementName = "ENTITY")]
public string Entity { get; set; }
[XmlElement(ElementName = "CURRENCY")]
public string Currency { get; set; }
[XmlElement(ElementName = "ALPHABETIC_CODE")]
public string Alpha_Code3 { get; set; }
[XmlElement(ElementName = "NUMERIC_CODE")]
public int NumCode { get; set; }
[XmlElement(ElementName = "MINOR_UNIT")]
public string MinorUnit { get; set; }
}
And this code, for deserialization:
public static XDocument Serialize<T>(this T source)
{
var ser = new XmlSerializer(source.GetType());
var sb = new StringBuilder();
using (var writer = new StringWriter(sb))
{
ser.Serialize(writer, source);
}
return XDocument.Parse(sb.ToString());
}
public static T Deserialize<T>(this XDocument xmlDocument)
{
var xmlSerializer = new XmlSerializer(typeof (T));
using (var reader = xmlDocument.CreateReader())
return (T) xmlSerializer.Deserialize(reader);
}
This is the XML source
But deserialization doesn't work. Please help.
Thanks!
I believe you only want to use XMLArray if you have a collection element for all of the items to sit underneath. For example here it could be ISO_CURRENCIES. I'm assuming you can't change the source in this case, so just use this instead:
[XmlElement("ISO_CURRENCY")]
public List<IsoCurrencyCode> IsoCodes { get; set; }
You should find that works.
Additionally, if you find you have further problems in getting the deserialization classes right, you can have them autogenerated for you from the XML and then you can take a look at the code that is created:
xsd source.xml
xsd source.xsd /c
This will create source.cs which you can then use in your project or adapt for your own uses.
As a further note, you'll find you can't use int for Minor_Unit as it's nullable (look at ANTARCTICA). You can't deserialize straight to an int?, so you'll either have to make it a string or go via another property, look at this question for more information.
Im creating an application, wich will conect to several sql database and get some details form the database,
In this application i have to encrypt the database connection details such as user name passwords. yes its pritty straight forward and simple just write a metod to decrypt the credentials.
but in my case i have to rely on third party encription mechanisam to decrypt the credentials. more over i have to connect to several sql servers which will again used some other encryption methods. hence im cording my application to load a encryption assembly dynamically and call the encryption method.
but when i load the assembly form Assembly.LoadFile("Path") i cannot unload the loaded assembly. i think i have load this assembly in separate app domain and call the relavant methods and unload that appdomain. im needing some help on this part. due to my lack of knoladge i cannot call the required method. my code as follows. please help me on this.
class ApplicationSettings
{
private static ApplicationSettings m_ApplicationSettings;
public String m_ServerName { get; private set; }
public String m_DatabaseName { get; private set; }
public String m_UserID { get; private set; }
public String m_Password { get; private set; }
public String m_EncryptionDLLPath{ get; private set; }
public String m_NameSpace { get; private set; }
public String m_ClassName { get; private set; }
public String m_EncryptionMethodName { get; private set; }
public String m_DecryptionMethodName { get; private set; }
private ApplicationSettings()
{
m_ApplicationSettings = this;
}
public static ApplicationSettings CurrentValues
{
get
{
return m_ApplicationSettings;
}
private set
{
m_ApplicationSettings = value;
}
}
internal static void Initialize()
{
CommonFunctions.DataEncryption _enc = new CommonFunctions.DataEncryption();
ApplicationSettings.CurrentValues = new ApplicationSettings();
ApplicationSettings.CurrentValues.m_EncryptionDLLPath = #"C:\Users\Administrator\Documents\Visual Studio 2010\Projects\TestApp\TestApp\bin\Debug\AppSec.dll";
ApplicationSettings.CurrentValues.m_NameSpace = "AppSec";
ApplicationSettings.CurrentValues.m_ClassName = "AppSecEncDec";
ApplicationSettings.CurrentValues.m_EncryptionMethodName = "Encrypt";
ApplicationSettings.CurrentValues.m_DecryptionMethodName = "Decrypt";
ApplicationSettings.CurrentValues.m_Password = _enc.Decrypt("pzBS3EJDoGM=");
ApplicationSettings.CurrentValues.m_UserID = "sa";
}
}
class DataEncryption
{
AppDomain DomainName;
//Call the Encryption Method
public String Encrypt(Object _DataToEncrypt)
{
}
//Call the Decryption Method
public String Decrypt(Object _DataToDecrypt)
{
String _Decrypt = "";
String assemblyFileName = ApplicationSettings.CurrentValues.m_EncryptionDLLPath;
String assemblyName = ApplicationSettings.CurrentValues.m_NameSpace;
//Setup the evidence
Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence);
AppDomain TestDomain = AppDomain.CreateDomain(
"TestDomain", //The friendly name of the domain.
evidence, //Evidence mapped through the security policy to establish a top-of-stack permission set.
AppDomain.CurrentDomain.BaseDirectory, // The base directory that the assembly resolver uses to probe for assemblies.
System.IO.Path.GetFullPath(assemblyFileName), // The path relative to the base directory where the assembly resolver should probe for private assemblies.
true // If true, a shadow copy of an assembly is loaded into this application domain.
);
string s = TestDomain.Load(assemblyName).FullName;
string[] myparam = new String[1];
myparam[0] = "test";
TestDomain.CreateInstance(TestDomain.Load(assemblyName).GetName().ToString(), ApplicationSettings.CurrentValues.m_NameSpace + "." + ApplicationSettings.CurrentValues.m_ClassName).CreateObjRef(GetType());
//her i need to execute the Encrypt method which will load form the third party encryption mechanisam
//method name will be returnd on this parameter in application settings Classes.ApplicationSettings.CurrentValues.m_EncryptionMethodName ;
UloadAssembly();
return _Decrypt;
}
public void UloadAssembly()
{
//Unload the loaded appdomain
AppDomain.Unload(DomainName);
GC.Collect();
}
}
Thanks in advance.
I have figured out how to do this and hope fully it will be successful please find the below code which if used to over come the situation
public String Encrypt(Object _DataToEncrypt)
{
try
{
String _Encrypt = "";
LoadAssembly();
ShowLoadedAssemblies();
if (ClassInstance != null)
{
MethodInfo EncryptionMethod = ClassInstance.GetType().GetMethod(Classes.ApplicationSettings.CurrentValues.m_EncryptionMethodName); ;
if (EncryptionMethod != null)
{
object[] myparam = new object[1];
myparam[0] = _DataToEncrypt;
_Encrypt = (string)EncryptionMethod.Invoke(null, myparam);
}
}
UloadAssembly();
ShowLoadedAssemblies();
return _Encrypt;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
//Call the Decryption Method
public String Decrypt(Object _DataToDecrypt)
{
String _Decrypt = "";
LoadAssembly();
ShowLoadedAssemblies();
if (ClassInstance != null)
{
MethodInfo DecryptionMethod = ClassInstance.GetType().GetMethod(Classes.ApplicationSettings.CurrentValues.m_DecryptionMethodName);;
if (DecryptionMethod != null)
{
object[] myparam = new object[1];
myparam[0] = _DataToDecrypt;
_Decrypt = (string)DecryptionMethod.Invoke(null, myparam);
}
}
UloadAssembly();
ShowLoadedAssemblies();
return _Decrypt;
}
//Loading the Assembly
public void LoadAssembly()
{
Evidence evi = new Evidence(AppDomain.CurrentDomain.Evidence);
DomainName = AppDomain.CreateDomain(Classes.ApplicationSettings.CurrentValues.m_NameSpace
, evi
, AppDomain.CurrentDomain.BaseDirectory
, Classes.ApplicationSettings.CurrentValues.m_EncryptionDLLPath
, true
);
String LoadingAssemblyName = AssemblyName.GetAssemblyName(Classes.ApplicationSettings.CurrentValues.m_EncryptionDLLPath).FullName;
ClassInstance = DomainName.CreateInstanceAndUnwrap(LoadingAssemblyName
, Classes.ApplicationSettings.CurrentValues.m_NameSpace
+ "."
+ Classes.ApplicationSettings.CurrentValues.m_ClassName
);
}
public void UloadAssembly()
{
//Unload the loaded appdomain
AppDomain.Unload(DomainName);
GC.Collect();
}