Categories
.NET C# Utility

Serialize and Deserialize POCO classes in XML

Serialize and Deserialize the Plain Old CLR Object (POCO) class is the theme of this post and I will be discussing regarding XML-based Serialization and Deserialization.

Note: This post is purely about Serialization and not regarding how to write Serializable POCO classes.

Image Illustration

Serialization Mechanism
Shows overall process of Serialization

POST Index

  1. Serialization
  2. Deserialization
  3. Uses
  4. Download Source code

 

For Serialization

DEFINITION

Serialization is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link) and reconstructed later in the same or another computer environment. Also known as deflating or marshalling.

Source: Wikipedia

Conversion

POCO class to String

Steps

  1. Input POCO class instance
  2. Declare Encoding such as ASCII, UTF-8, and BigEndianUnicode, or else
  3. Declare Stream for In-Memory Serialization
  4. Declare Serializer
  5. Execute Serialization method
  6. Fetch the serialized XML
  7. Output is String value ( XML value )

Source Code

public static string XmlSerialize(T sourceValue) where T : class
{
	// If source is empty, throw Exception
	if (sourceValue == null)
		throw new NullReferenceException("sourceValue is required");

	// Define encoding
	var encoding = Encoding.ASCII;

	// Declare the resultant variable
	string targetValue;

	// Using MemoryStream for In-Process conversion
	using (var memoryStream = new MemoryStream())
	{
		// Declare Stream with required Encoding
		using (var streamWriter = new StreamWriter(memoryStream, encoding))
		{
			// Declare Xml Serializer with source value Type (serializing type)
			var xmlSerializer = new XmlSerializer(sourceValue.GetType());

			// Perform Serialization of the source value and write to Stream
			xmlSerializer.Serialize(streamWriter, sourceValue);

			// Grab the serialized string
			targetValue = encoding.GetString(memoryStream.ToArray());
		}
	}

	// Return the resultant value;
	return targetValue;
}

 

FOR DESERIALIZATION

DEFINITION

The opposite operation of Serialization, i.e. extracting a data structure from a series of bytes, is deserialization. Also known as inflating or unmarshalling.

Source: Wikipedia

CONVERSION

String to POCO Class

STEPS

  1. Input String value ( XML value )
  2. Declare Encoding
  3. Declare Serializer
    • Same Serializer class is used for Serializing and Deserializing
  4. Declare Stream for In-Memory Deserialization
  5. Execute Deserialization method
  6. Type cast the return Object to POCO type
  7. Output is POCO class instance

Source CODE

public static T XmlDeserialize(string sourceValue) where T : class
{
	// If source is empty, throw Exception
	if (string.IsNullOrWhiteSpace(sourceValue))
		throw new NullReferenceException("sourceValue is required");

	// Define encoding
	var encoding = Encoding.ASCII;

	// Declare the resultant variable
	T targetValue;

	// Declare Xml Serializer with target value Type (serialized type)
	var xmlSerializer = new XmlSerializer(typeof(T));

	// Get the source value to bytes with required Encoding
	byte[] sourceBytes = encoding.GetBytes(sourceValue);

	// Using MemoryStream for In-Process conversion
	using (var memoryStream = new MemoryStream(sourceBytes))
	{
		// Read stream into XML-based reader
		using (var xmlTextReader = new XmlTextReader(memoryStream))
		{
			// Perform Deserialization from the stream and Convert to target type
			targetValue = xmlSerializer.Deserialize(xmlTextReader) as T;
		}
	}

	// Return the resultant value;
	return targetValue;
}

 

Uses

  1. For Deep Cloning the objects
  2. For integrating with RESTful API and Remoting Services
  3. For persisting the User Data for Offline apps which later uses various Synchronization methods
  4. In .NET apps, Serialization is used for saving and accessing settings from web.config or app.config
  5. Remote procedure calls ( RPC )
  6. In Distributed Memory Applications, such AppFabric for Windows Server which is used for Middle tier caching in Load balancing situation
  7. For Data Exchange in cross-platform applications such as .NET apps integration with Android apps or Windows Phone apps.

 

Download Source Code

 

Categories
.NET ASP.NET Sitecore Utility

Code Generation using Sitecore Rocks and Visual Studio

Index Points

  1. Introduction
  2. Assumptions
  3. Code Generation Steps using Sitecore Rocks
  4. Image Guided Steps for Code Generation using Sitecore Rocks
  5. Conclusion
  6. Reference Links

 

Introduction

This post will guide you on how to work with code generation using Sitecore Rocks.

Assumptions

Code Generation Steps using Sitecore Rocks

For Code generation using Sitecore Rocks the steps are:

  1. Setup the Sitecore site using .exe installer or Siteroot zip – available from Sitecore SDN.
  2. Setup Sitecore site in Visual studio solution – Creating .sln file.
  3. Install Sitecore Rocks (if not already installed).
  4. Connect the Visual studio solution with Sitecore site using Hard Rock web service exposed by Sitecore.
  5. Create new StronglyTypedItems file in Sitecore visual studio solution, extension will be .scx, with appropriate name – for example “CodeGenerationFile.scx”.
  6. Right-click on created file “CodeGenerationFile.scx” and execute the command ‘Run Custom Tool’ for code generation.

Note: Check YouTube video series linked in assumption section for information on how to install and setup Sitecore Rocks and Sitecore Visual studio solution.

Image Guided Steps for Code Generation using Sitecore Rocks

The visual steps for Sitecore Rocks code generation are as below:

sitecore codegen - create strongly typed items file
Create new file for Code generation
Right click on project > Add > New Item > Visual C# > Sitecore > Code Generation > select Strongly Typed Items > click Add
sitecore codegen - run custom tool
Run custom tool command to execute and generate code files
sitecore codegen - code generated in designer file
Verify the Code generated in CodeGenerationFile.Designer.cs file (File name may differ as per added file)

Conclusion

Code generation with Sitecore Rocks is very easy to follow. After generating code using Sitecore Rocks, developers may move the classes to relatively named class files by themselves or using command ‘Move class to file’ using ReSharper tool.

Reference Links

Do comment if you like this post or have any opinions.

Categories
.NET Personal Productivity Setup Utility

How to install .NET Framework 2.0 and 3.5 on Windows 8 in Offline Mode

I have installed Windows 8 few days back. And during some initial programs setup I noticed that Windows 8 does not include .NET 3.5 (include .NET 2.0 and 3.0) by default. However it did contained the setup in the OS disc.

So question is, How to install the .NET framework 3.5 including .NET 2.0 and 3.0 ?

Solution is answered as below.

I had found my solution on Microsoft support ? here.

This an Re-post of the same with corrections.

Steps below shows how we can install /enable the .NET Framework 3.5 (include .NET 2.0 and 3.0) feature in offline mode i.e. without using internet:

Step 1: Insert Windows 8 DVD or mount ISO image. The source of this feature can be found in folder E:\sources\sxs (In this case E: drive letter will be on which Windows 8 Media is located).

Windows 8 Media folder view
Windows 8 Media folder view

Step 2: Open cmd.exe (Command Prompt) with Administrative Privileges.

Step 3: Run the following command

dism.exe /online /enable-feature /featurename:NetFx3 /All /Source:"E:\sources\sxs" /LimitAccess

and then hit Enter.

Command Prompt showing installation of the feature.
Command Prompt shows installation of the feature completed.

 

Finish: After completing the installation of .NET Framework 3.5 you can see that the feature is enabled as shown in the screenshot below.

Windows features showing installed .NET 3.5
Windows features displays .NET 3.5 installed.

 

Categories
Interview Questions SQL Utility

MSSQL – Change default database by sql query

Microsoft SQL Server Management Studio showing...
Microsoft SQL Server Management Studio showing a query, the results of the query, and the Object Explorer pane while connected to a SQL Server database engine instance. (Photo credit: Wikipedia)

Dear reader,

Recently I noticed in my daily work that every time I logged in MS SQL I was required to select the database which I had to work on and this was regularly in use by me and this lead me to find the solution to change the default database selection after I log on to MS SQL using SSMS to reduce the hassle and also so that I don’t execute queries on different databases by mistake.

There is an inbuilt stored procedure name sp_defaultdb which can be used as below

Exec sp_defaultdb @loginame='Domain/UserName', @defdb='MyDefaultDatabaseName'

Here value of parameter @loginname is User Name such as ‘sa’ and it can change depending on the MSSQL login configurations such as Sql Authentication or Windows Authentication. Example shown here is for Windows Authentication. Then value of parameter @defdb is the database name such as ‘master’ or ‘AdventureWorks’ and it will change as per the need to set the default database for the particular login specified.

But this stored procedure seems soon to be obsolete as mentioned in MSDN link here. There is newer option available for this purpose – ALTER LOGIN which has many other usability apart from setting the default database but I would stick to the topic and show its usage.

ALTER LOGIN [Domain\UserName] WITH DEFAULT_DATABASE = [MyDefaultDatabaseName]

I hope you found this helpful and learnt something new from this.

Reference links: StackOverflow – How can I change my default database in SQL Server without using MS SQL Server Management Studio?

Keep your comments flowing for what you prefer. 🙂