Thursday, December 27, 2012

Upload file using JSP

I found a good article to upload a file using jsp here . I just modified it little so that it can upload file to the root directory of the webapp.

fileindex.jsp

<%@ page language="java" %>
<HTml>
<HEAD><TITLE>Display file upload form to the user</TITLE></HEAD>
<% // for uploading the file we used Encrypt type of multipart/form-data and input of file type to browse and submit the file %>
<BODY> <FORM ENCTYPE="multipart/form-data" ACTION="single_upload_page.jsp" METHOD=POST>
<br><br><br>
<center><table border="2" >
<tr><center><td colspan="2"><p align="center"><B>PROGRAM FOR UPLOADING THE FILE</B><center></td></tr>
<tr><td><b>Choose the file To Upload:</b></td>
<td><INPUT NAME="F1" TYPE="file"></td></tr>
<tr><td colspan="2"><p align="right"><INPUT TYPE="submit" VALUE="Send File" ></p></td></tr>
<table>
</center>
</FORM>
</BODY>
</HTML>

Tuesday, December 25, 2012

jsp with beans example

Here is an example :

index.jsp
---------------------

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="us" scope="request" class="msgbean.User"></jsp:useBean>
<%
if (request.getParameter("Name") != null) {
//out.write(request.getParameter("Name"));
us.setName(request.getParameter("Name"));
us.setEmail(request.getParameter("Email"));
}
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form method="post">
<table>
<tr><td>Name:</td><td><input type="text" name="Name"/></td></tr>
<tr><td>Email:</td><td><input type="text" name="Email"/></td></tr>
<tr><td><input type="submit" value="Submit"/></td></tr>
</table>
</form>

You entered:<br />

Name: <%= us.getName()%></br>
Email: <%= us.getEmail()%></br>
</body>
</html>
----------------------------------

Sunday, November 25, 2012

Get number of element of specific name in a xml file

XmlDocument xdoc = new XmlDocument();
xdoc.Load(Server.MapPath("~/pp1.xml"));
string PersonCount = xdoc.DocumentElement.SelectNodes("//persons/person").Count.ToString();
Response.Write(PersonCount);

Tuesday, October 16, 2012

ওয়ালটন প্রিমো (অ্যান্ড্রয়েড) রিভিউ

আমি নিজে অনেকদিন থেকেই সনি এরিকসন এক্সপেরিয়া এক্স এইট চালাই। এক বন্ধুর জন্য গত শনিবার গেলাম এন্ড্রয়েড ফোন কিনতে। প্রথমে ভেবেছিলাম যে সিম্ফোনি w5 নিবো কিন্তু পরে নেট ঘেটে দেখলাম যে দাম এবং কনফিগারেশনের দিক থেকে ওয়ালটন প্রিমো এগিয়ে। কিনলাম ওয়ালটন এর বিজয় সরনী এর শো রুম থেকে। কেনার পর একদিন ব্যবহার করার সুযোগ পেলাম। তাতে যা দেখলাম টাকার হিসেবে অসাধারন জিনিস (আমার মতে)।

Monday, September 24, 2012

Make your windows 7 laptop into wifi hotspot

Make sure you have installed Microsoft Virtual Wifi miniport adapter

 

Then make command as follows:
C:\Windows\system32>netsh wlan set hostednetwork mode=allow ssid=MyWifi key=password keyUsage=persistent

To start your network
C:\Windows\system32>netsh wlan start hostednetwork

To Stop your network
C:\>netsh wlan show hostednetwork

Share your internet connection by going to network sharing center





Monday, June 11, 2012

Create a colorful flashlight in android

Create an android project in eclipse and pasted the following code in the main activity class:

package com.rayhan.nothing;

import java.util.Random;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class AndruTestActivity extends Activity {
/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);

super.onCreate(savedInstanceState);
setContentView(R.layout.main);

View v=findViewById(R.id.mainlayout);

v.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
Random rnd=new Random();

v.setBackgroundColor(rnd.nextInt());

}
});

}
}

//------------------------------------------------

And here is the xml file for the layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainlayout"
android:background="@color/white"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

</LinearLayout>

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