Friday, November 9, 2012

String replace: case insensitive issue

I one of my product i build a file renaming system. User has many options to rename file. Among those we have some string replace cases.

At first we tried String.Replace Method (System) to replace texts. Below code snipped is given how things look, the code is simple and may seems different as it taken from different context.

public string ApplyRule(FileRenamePreview preview)
{
if (string.IsNullOrEmpty(SearchText))
return preview.NewFile;

if (IsFirstOnly == false)
{
var changedFileName = preview.NewFileName.Replace(SearchText, ReplaceText);
preview.NewFileName = changedFileName;
}
else
{
var regex = new Regex(SearchText);
preview.NewFileName = regex.Replace(preview.NewFileName, ReplaceText, 1);
}

return preview.NewFile;
}

Now the client wanted the replacement as such so that the search string should be case insensitive. Trick is simple we have to use regex in place of normal string replace, but with Regex option set to ignore case. Below code segment is given to show how it is done.


public string ApplyRule(FileRenamePreview preview)
{
if (string.IsNullOrEmpty(SearchText))
return preview.NewFile;

if (IsFirstOnly == false)
{
var changedFileName = Regex.Replace(preview.NewFileName, SearchText, ReplaceText,RegexOptions.IgnoreCase);
preview.NewFileName = changedFileName;
}
else
{
var regex = new Regex(SearchText,RegexOptions.IgnoreCase);
preview.NewFileName = regex.Replace(preview.NewFileName, ReplaceText, 1);
}

return preview.NewFile;
}

Last trick, while searching for text for first index, there is option to state ignoring case we have to use it.


int iIndexOfBegin = strSource.IndexOf(strBegin,StringComparison.InvariantCultureIgnoreCase);

Until next time.

Friday, November 2, 2012

Create custom project file using c# object serialization. Its easy! only few step and works perfectly.

Introduction

Recently I did couple of projects where I needed to save objects in a file and then load back to the system for some processing. I thought of couple of solutions but at last stick to a simpler solution. In one of our project we did something like the bellow solutions.

Step 1: Serialize the related class in separate files.

Step 2: Use Open source zip technology to zip the files in a single file.

Step 3: Rename the zip file with custom extension for instance “filename.xte”

Serialize a collection of class objects

In this post I have some classes to show In case of a simple serialization context. Below I have my data class named “Bond” with only 5 properties. Below the code snippet is given how the class looks like.

using System;

namespace PrizeBonds.Objects
{
[Serializable]
public class Bond
{
public long Id { get; set; }
public long Serial { get; set; }
public string Owner { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
}
}


Next I have a class which will be serialized and saved in a file. In this class I have a List of Bond class, and of course it  implements the ISerializable interface. Below a code snippet is given to show the the code looks like.


using System.Runtime.Serialization;

namespace PrizeBonds.Objects
{
[Serializable()]
public class ObjectToSerialize:ISerializable
{
private List<Bond> _bonds;

public List<Bond> Bonds
{
get { return _bonds; }
set { _bonds = value; }
}

public ObjectToSerialize()
{
}

public ObjectToSerialize(SerializationInfo info, StreamingContext ctxt)
{
_bonds = (List<Bond>)info.GetValue("Bonds", typeof(List<Bond>));
}

public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
info.AddValue("Bonds", _bonds);
}
}
}


The final piece of work that to the all kind of lifting is the serialize, below the code snippet to is given to demonstrate the idea. The responsibility of the below code is to serialize and de-serialize the objects.



using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace PrizeBonds.Objects
{
public class Serializer
{
public void SerializeObject(string filename, ObjectToSerialize objectToSerialize)
{
Stream stream = File.Open(filename, FileMode.Create);
var bFormatter = new BinaryFormatter();
bFormatter.Serialize(stream, objectToSerialize);
stream.Close();
}

public ObjectToSerialize DeSerializeObject(string filename)
{
Stream stream = File.Open(filename, FileMode.Open);
var bFormatter = new BinaryFormatter();
var objectToSerialize = (ObjectToSerialize)bFormatter.Deserialize(stream);
stream.Close();
return objectToSerialize;
}
}
}



In first method of above code  we pass the file name and the object that need to serialize, it serialize the object with binary formatter and save in the file that is provided. In second method we provide a file name where the serialized file is it desterilize the file and build the wrapped object.


using System.Windows.Forms;

namespace PrizeBonds.Objects
{
public class BackUpManager
{
public void LoadRule()
{

// Configure open file dialog box
var dlg = new OpenFileDialog { FileName = "Prize Bond Manager",
DefaultExt = ".pbm", Filter = @"Prize Bond Manager Files (.pbm)|*.pbm" };

// Show open file dialog box
var result = dlg.ShowDialog();

// Process open file dialog box results
if (result == DialogResult.OK)
{
// Open document
var filename = dlg.FileName;
var serializer = new Serializer();
var deSerializeObject = serializer.DeSerializeObject(filename);
var bonds = deSerializeObject.Bonds;
var dal = new DAL();
foreach (var bond in bonds)
{
dal.AddBond(bond);
}
}
}

public void SaveRule()
{
var dal = new DAL();
var bonds = dal.GetList();
if (bonds.Count == 0)
{
const string message = @"You do not have any bonds to Save, thus I am unable "
+ @" to save any bonds. Please add some bonds before Saving";
MessageBox.Show(message);
return;
}

var dlg = new SaveFileDialog { FileName = "Prize Bond Manager",
DefaultExt = ".pbm", Filter = @"Prize Bond Manager Files (.pbm)|*.pbm" };

// Show save file dialog box
var result = dlg.ShowDialog();

// Process save file dialog box results
if (result == DialogResult.OK)
{
// Save document
string filename = dlg.FileName;
var serializer = new Serializer();
var objectToSerialize = new ObjectToSerialize { Bonds = bonds };
serializer.SerializeObject(filename, objectToSerialize);
}
}
}
}


 


In above code I have a class named “BackUpManager” where we have two method, in first method using file open dialog and using Serializer class we saved the file. And in second method using Serializer class we saved a file, and in both case we have our own extension.


Conclusion


In the above short article we have seen a simple serialization scenario. And I explained why we need it. And also shown some classes to demonstrate the idea.


Reference



  1. http://tech.pro/tutorial/618/csharp-tutorial-serialize-objects-to-a-file

  2. http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx