Friday, March 30, 2012

Serialize and DeSerialize an object to a file in C#

Here is the code for serialization:

/// <summary>
/// Function to save object to external file
/// </summary>
/// <param name="_Object">object to save</param>
/// <param name="_FileName">File name to save object</param>
/// <returns>Return true if object save successfully, if not return false</returns>
public bool ObjectToFile(object _Object, string _FileName)
{
try
{
// create new memory stream
System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream();

// create new BinaryFormatter
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter
= new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

// Serializes an object, or graph of connected objects, to the given stream.
_BinaryFormatter.Serialize(_MemoryStream, _Object);

// convert stream to byte array
byte[] _ByteArray = _MemoryStream.ToArray();

// Open file for writing
System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);

// Writes a block of bytes to this stream using data from a byte array.
_FileStream.Write(_ByteArray, 0, _ByteArray.Length);

// close file stream
_FileStream.Close();

// cleanup
_MemoryStream.Close();
_MemoryStream.Dispose();
_MemoryStream = null;
_ByteArray = null;

return true;
}
catch (Exception _Exception)
{
// Error
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
}

// Error occured, return null
return false;
}

 

 

 

Here is the code for deserialize the object:

 

public object FileToObj(string _fileName)
{
FileStream fs = new FileStream(_fileName, FileMode.Open);


// create new BinaryFormatter
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter
= new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

// Serializes an object, or graph of connected objects, to the given stream.
return _BinaryFormatter.Deserialize(fs);
}

Wednesday, March 7, 2012

Checking availibility of WCF service

I've got one method from the book "Programming WCF Services" by Juval Lowy (page 71).
Code Snippet:




   MetadataExchangeClient mexClient =

bool isServiceUp = true;
try
{
string address = "http://localhost/MyService.svc?wsdl";new MetadataExchangeClient(newUri(address), MetadataExchangeClientMode.HttpGet);
MetadataSet metadata = mexClient.GetMetadata();
// if service down I get the exception
}
   catch (Exception ex)
{
isServiceUp =
false;
}

I catch the Exception like {"Metadata contains a reference that cannot be resolved: "http://localhost/MyService.svc?wsdl"} System.Exception {System.InvalidOperationException}

Thursday, March 1, 2012

Get or Set Session in ashx handler

If you need to share session in ashx handler just use System.Web.SessionState.IRequiresSessionState this Interface

 

Like

public class login : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
......

}

Sunday, February 26, 2012

Post and redirect from code behind of aspx page

Here is a code that I found searching in google but can't remember from where :( . It is  very useful.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Collections.Specialized;
using System.Text;

/// <summary>
/// Summary description for PostHelper
/// </summary>
public class PostHelper
{
public PostHelper()
{
//
// TODO: Add constructor logic here
//
}
/// <summary>
/// POST data and Redirect to the specified url using the specified page.
/// </summary>
/// <param name="page">The page which will be the referrer page.</param>
/// <param name="destinationUrl">The destination Url to which
/// the post and redirection is occuring.</param>
/// <param name="data">The data should be posted.</param>
/// <Author>Samer Abu Rabie</Author>

public static void RedirectAndPOST(Page page, string destinationUrl,
NameValueCollection data)
{
//Prepare the Posting form
string strForm = PreparePOSTForm(destinationUrl, data);
//Add a literal control the specified page holding
//the Post Form, this is to submit the Posting form with the request.
page.Controls.Add(new LiteralControl(strForm));
}

/// <summary>
/// This method prepares an Html form which holds all data
/// in hidden field in the addetion to form submitting script.
/// </summary>
/// <param name="url">The destination Url to which the post and redirection
/// will occur, the Url can be in the same App or ouside the App.</param>
/// <param name="data">A collection of data that
/// will be posted to the destination Url.</param>
/// <returns>Returns a string representation of the Posting form.</returns>
/// <Author>Samer Abu Rabie</Author>

private static String PreparePOSTForm(string url, NameValueCollection data)
{
//Set a name for the form
string formID = "PostForm";
//Build the form using the specified data to be posted.
StringBuilder strForm = new StringBuilder();
strForm.Append("<form id=\"" + formID + "\" name=\"" +
formID + "\" action=\"" + url +
"\" method=\"POST\">");

foreach (string key in data)
{
strForm.Append("<input type=\"hidden\" name=\"" + key +
"\" value=\"" + data[key] + "\">");
}

strForm.Append("</form>");
//Build the JavaScript which will do the Posting operation.
StringBuilder strScript = new StringBuilder();
strScript.Append("<script language='javascript'>");
strScript.Append("var v" + formID + " = document." +
formID + ";");
strScript.Append("v" + formID + ".submit();");
strScript.Append("</script>");
//Return the form and the script concatenated.
//(The order is important, Form then JavaScript)
return strForm.ToString() + strScript.ToString();
}
}

Monday, February 13, 2012

Simple ajax with asp.net

Here is a simple example of ajax using asp.net.

Create a asp.net web project named AjaxTest. In defaut.aspx page add the following code:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="AjaxTest._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<script type="text/javascript">
var xmlhttp = null;
function ShowSuggestions(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "Search.aspx?q=" + str;
xmlhttp.open("GET", url, false);
xmlhttp.send(null);
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
</script>
<h2>
Welcome to ASP.NET AJAX!
</h2>
<input type="text" id="txt1″" onkeyup="ShowSuggestions(this.value)" />
<p>
Suggestions: <span id="txtHint"></span>
</p>
</asp:Content>
--------------------------------------------

Add a page named Search.aspx

Add the following code in the code behind page

protected void Page_Load(object sender, EventArgs e)
{
var sugtext = new List<string>();
sugtext.Add("Rayhan");
sugtext.Add("Tonmoy");
string suggestion = (from sgText in sugtext
where sgText.StartsWith(Request.QueryString["q"])
select sgText).FirstOrDefault();
//string suggestion="Hello";
if (string.IsNullOrEmpty(suggestion))
Response.Write("No Suggestion Found");
else
Response.Write(suggestion);
Response.End();
}

 

 

Build and see the action.

Wednesday, February 8, 2012

Parse an XML document in C#

here is the code

XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/out.xml"));
XmlNodeList nodes = doc.GetElementsByTagName("BankcheckEnhanced");
for (int i = 0; i < nodes.Count; i++)
{
XmlElement Element = (XmlElement)nodes[i];
try
{
BEResult = GetInnerValue(Element,"Result");
BEScore = GetInnerValue(Element, "Score");
BEAccountIssuer = GetInnerValue(Element, "AccountIssuer");
BEOtherAccountsFoundForIssuer = GetInnerValue(Element, "OtherAccountsFoundForIssuer");
}
catch (Exception ex)
{


}
}

 

 

 

another method is required

private static string GetInnerValue(XmlElement Element, string tagName)
{
return Element.GetElementsByTagName(tagName)[0].InnerText;
}

Tuesday, January 31, 2012

Asp.net MVC and Entity Framework CRUD

public class MyController : Controller
{
//
// GET: /My/
MyDBEntities db = new MyDBEntities();
public ActionResult Index()
{
return View(db.Information.ToList());
}

//
// GET: /My/Details/5

public ActionResult Details(int id)
{
return View();
}

//
// GET: /My/Create

public ActionResult Create()
{

return View();
}

//
// POST: /My/Create

[HttpPost]
public ActionResult Create([Bind(Exclude = "Id")]Information info)
{
try
{
// TODO: Add insert logic here

db.AddToInformation(info);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}

//
// GET: /My/Edit/5

public ActionResult Edit(int id)
{


// var cc = db.Information.Select(x => x.Id == id).FirstOrDefault();

var cc = (from info in db.Information where info.Id == id select info).FirstOrDefault();


return View(cc);
}

//
// POST: /My/Edit/5

[HttpPost]
public ActionResult Edit( Information info)
{
try
{
// TODO: Add update logic here

db.Information.AddObject(info);
db.ObjectStateManager.ChangeObjectState(info, System.Data.EntityState.Modified);
// db.AcceptAllChanges();
db.SaveChanges();
return RedirectToAction("Index");
}
catch(Exception ex)
{
return View();
}
}

//
// GET: /My/Delete/5

public ActionResult Delete(int id)
{
var cc = (from info in db.Information where info.Id == id select info).FirstOrDefault();
return View(cc);
}

//
// POST: /My/Delete/5

[HttpPost]
public ActionResult Delete(Information info)
{
try
{
db.Information.AddObject(info);
db.ObjectStateManager.ChangeObjectState(info, System.Data.EntityState.Deleted);
// db.AcceptAllChanges();
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}

What is DaemonSet in Kubernetes

 A DaemonSet is a type of controller object that ensures that a specific pod runs on each node in the cluster. DaemonSets are useful for dep...