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();
}
}
}

Wednesday, December 28, 2011

Fully open-source video streaming

post about red5 and xuggler

http://www.markturner.net/2011/01/31/fully-open-source-video-streaming/

Thursday, December 22, 2011

Flex for Free: Setting Up the Flex 4 SDK with Eclipse IDE

Here is a good article

http://www.seanhsmith.com/2010/03/29/flex-for-free-setting-up-the-flex-4-sdk-with-eclipse-ide/

Sunday, December 18, 2011

Send email Without SMTP Server (Copied post)




Usually, when we send an email, we need to have valid SMTP server along with access and deliver the email using that server. If we add the send email functionality to software, the user needs to configure an SMTP server address, the username, and the password. The SMTP server receive message and send it to another SMTP server or deliver it to local inbox. Why not send an email to the receiver's SMTP server directly? Why can’t we directly communicate to receiver SMTP server on port 25?

The problem is we don't know which SMTP server is responsible for receiving emails for a given email address. The secret is that this information can be obtained from Domain Name System (DNS) servers. This seems simple; however, it needs a lot work to implement the DNS protocol (RFC 1035) because the .NET framework doesn't support getting mail server info from DNS.

There are certain fundamental concepts defined for SMTP RFC 5321

SMTP servers which send message to another server are called MTAs. MTAs look for MX record (may find more than one MX records) for the domain (DNS look up for NS and MX record, in windows you can use dnsapi.dll, DnsQuery_W method suits to needs.). Once you have server IP you can connect to port 25 (generally those ports are Ephemeral) and exchange message (of course according to RFC 5321).

We can use Dnsapi.dll to query DNS server the code is....

/* **********************************************

* Developed by Dipak Bava

* Resolves MX records for domain name

* Date: 25 Feb 2009

* **********************************************/

Download it here http://www.joyinfotech.com  look for SendMail link

using System;

using System.Collections;

using System.ComponentModel;

using System.Runtime.InteropServices;

namespace SendSMTP

{

public class DnsLookUp

{

public DnsLookUp()

{

}

[DllImport("dnsapi", EntryPoint = "DnsQuery_W", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]

private static extern int DnsQuery([MarshalAs(UnmanagedType.VBByRefStr)]refstring pszName, QueryTypes wType, QueryOptions options, int aipServers, ref IntPtrppQueryResults, int pReserved);

[DllImport("dnsapi", CharSet = CharSet.Auto, SetLastError = true)]

private static extern void DnsRecordListFree(IntPtr pRecordList, intFreeType);

public static string[] GetMXRecords(string domain)

{

IntPtr ptr1 = IntPtr.Zero;

IntPtr ptr2 = IntPtr.Zero;

MXRecord recMx;

if (Environment.OSVersion.Platform != PlatformID.Win32NT)

{

throw new NotSupportedException();

}

ArrayList list1 = new ArrayList();

int num1 = DnsLookUp.DnsQuery(ref domain, QueryTypes.DNS_TYPE_MX,QueryOptions.DNS_QUERY_BYPASS_CACHE, 0, ref ptr1, 0);

if (num1 != 0)

{

throw new Win32Exception(num1);

}

for (ptr2 = ptr1; !ptr2.Equals(IntPtr.Zero); ptr2 = recMx.pNext)

{

recMx = (MXRecord)Marshal.PtrToStructure(ptr2, typeof(MXRecord));

if (recMx.wType == 15)

{

string text1 = Marshal.PtrToStringAuto(recMx.pNameExchange);

list1.Add(text1);

}

}

DnsLookUp.DnsRecordListFree(ptr1, 0);

return (string[])list1.ToArray(typeof(string));

}

private enum QueryOptions

{

DNS_QUERY_ACCEPT_TRUNCATED_RESPONSE = 1,

DNS_QUERY_BYPASS_CACHE = 8,

DNS_QUERY_DONT_RESET_TTL_VALUES = 0x100000,

DNS_QUERY_NO_HOSTS_FILE = 0x40,

DNS_QUERY_NO_LOCAL_NAME = 0x20,

DNS_QUERY_NO_NETBT = 0x80,

DNS_QUERY_NO_RECURSION = 4,

DNS_QUERY_NO_WIRE_QUERY = 0x10,

DNS_QUERY_RESERVED = -16777216,

DNS_QUERY_RETURN_MESSAGE = 0x200,

DNS_QUERY_STANDARD = 0,

DNS_QUERY_TREAT_AS_FQDN = 0x1000,

DNS_QUERY_USE_TCP_ONLY = 2,

DNS_QUERY_WIRE_ONLY = 0x100

}

private enum QueryTypes

{

DNS_TYPE_MX = 15

}

[StructLayout(LayoutKind.Sequential)]

private struct MXRecord

{

public IntPtr pNext;

public string pName;

public short wType;

public short wDataLength;

public int flags;

public int dwTtl;

public int dwReserved;

public IntPtr pNameExchange;

public short wPreference;

public short Pad;

}

}

}

Download it here  http://www.joyinfotech.com  look for SendMail link

Sounds good up to here but when you really try to connect MTAs to deliver message spamhaus comes in to picture. Most of the MTAs are now intelligent enough to fight against spammer and your ISP could be in the radar. So before you try, it’s wise to check you IP with http://www.spamhaus.org/query/bl?ip=xx.xx.xx.xx

Use the following code to deliver message if you do not want to study RFC 5321.

//Now prepare your message.

MailMessage mail = new MailMessage();

mail.To.Add("someone@somedomain.com");

mail.From = new MailAddress("tome@somedomain.com");

mail.Subject = "Send email without SMTP server";

mail.Body = "Yep, its workin!!!!";

//Send message

string domain = mail.To[0].Address.Substring(mail.To[0].Address.IndexOf('@') + 1);

//To Do :need to check for MX record existance before you send. Left intentionally for you.

string mxRecord = SendSMTP.DnsLookUp.GetMXRecords(domain)[0];

SmtpClient client = new SmtpClient(mxRecord);

client.Send(mail);

Best Luck

Dipak Goswami






 This code can be used in real solutions, if your IP has good reputations.

This post is copied from http://sites.google.com/site/dvgoswami/


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...