Posts

Showing posts from January, 2014

MVC 4 - Dynamic Output

Image
The whole point of a Web application platform is to construct and display dynamic output. In MVC, it is the controller’s job to construct some data and pass it to the view, which is responsible for rendering it to HTML. One way to pass data from the controller to the view is by using the ViewBag object, which is a member of the Controller base class. ViewBag is a dynamic object to which you can assign arbitrary properties, making those values available in whatever view is subsequently rendered. Example below demonstrates passing some simple dynamic data in this way in the HomeController.cs file. HomeController.cs  public class HomeController : Controller     {         //         // GET: /Home/         public ViewResult Index()         {             int hour = DateTime.Now.Hour;             ViewBag.Greeting = hour < 12 ? "Good Morning" : "Good Afternoon";             return View();         }     } Index.cshtml @{ Layout = null; } <!DOCTYPE html> <html&g

MVC 4 - Rendering web Pages

Image
The output from the previous post wasn’t HTML—it was just the string " Hello World, This is my first MVC Application ". To produce an HTML response to a browser request, we need to create a view. Creating And Rendering a View Modify the Controller to render a View (please refer the previous post before you do this).         public ViewResult Index()         {             return View();         } Right click at word View() and choose Add View Leave the devault value and click Add button Congratulation, now you have successfully created new view which will be rendered as html when the root / or  /Home or /Home/Index url hit Note : The . cshtml file extension denotes a C# view that will be processed by Razor . Now copy this HTML code on the Index.cshtml file. @{     ViewBag.Title = "Index"; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head>

Creating Your First MVC 4 Application

Image
In this tutorial i will show the example on MVC 4. Follow this step to create new MVC Application on Microsoft Visual Studio 2010. Creating MVC 4 Project File >> New Project Choose ASP.NET MVC4 Web Application. (If you dont have MVC 4, Install it here ) On Project Template , choose Empty if you want to start from zero or choose Internet Application to start developement with default template. Choose View engine Razor. Click OK button Now you have create one project with MVC4 Solution  Adding First Controller Right click on the Controller folder under Solution Explorer Menu. Choose Add >> Controller Rename Controller Name to HomeController Since this is empty project, so under Scaffolding Options Template choose Empty MVC Controller Change The default ActionResult Index() like this         public string Index()         {             return "Hello World, This is my first MVC Application";         } Run the project, You should see the output on the browser lik

Decimal Manipulation in C#

This post will  show manipulation on the Data Type Decimal. //This is the hard code value for decimal   //without suffic m or M, the compiler thread the object as a double hence will cause error   decimal price = 10.1654M;   //Convert decimal to double   double priceInDouble = Convert.ToDouble(price); //output : 10.1654   priceInDouble = (double)price;//output : 10.1654   //convert to double with 2 decimal point,           priceInDouble = Math.Round((double)price, 2); // output : 10.17   //convert back to decimal   price = Convert.ToDecimal(priceInDouble);//output : 10.17   price = (decimal)priceInDouble;//output : 10.17   //convert decimal to currency. The currency format will depend on the region,   //like myself in malaysia compiler will automatically give "RM" as a currency format   string currency = String.Format("Order Total: {0:C}", price); //output :RM10.17   currency = String.Format("Order Total: {0:C2}", price); //output :RM10.17 ,2 decimal poi

How to send email in ASP.NET- C# example

Image
This is example how to send email from asp,net web application. Refer this post if you want to send email in java code . This example will use google smtp email server. The aspx Page <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">     <asp:Label ID="LErrorMessage" runat="server" ></asp:Label>     <asp:Button ID="Button1" runat="server" Text="Send Email" OnClick="Button1_Click" /> </asp:Content> The Code Behind  protected void Page_Load(object sender, EventArgs e)         {         }         protected void Button1_Click(object sender, EventArgs e)         {                        string emailContent = "This mail is created and send through the c# code,"                     + "\n\n if you are developers, visit http://www.developersnote.com!",                     subject = "Developersnote update - Mail Send Using AS

How to send email in java - example

Image
This is a example code to send email in java. This example will use 3rd party library JavaMail   . The Code Example import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; /**  *  * @author zulkamal  */ public class sendEmail {     public static void main(String[] args) {         final String username = "yourgmailaddress@gmail.com";         final String password = "your password gmail";         Properties props = new Properties();         props.put("mail.smtp.auth", "true");         props.put("mail.smtp.starttls.enable", "true");         props.put("mail.smtp.host", "smtp.gmail.com");         props.put("mail.smtp.port", "587");         Session session = Session.getInstance

How to create XML File In Java

This is a example of creating XML file in java application. The Main Class Code import java.io.File; import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; public class CreateXml {     public static void main(String[] args) throws TransformerException {         ArrayList<String> arrayOne = new ArrayList<String>();         ArrayList<String> arrayTwo = new ArrayList<String>();         ArrayList<String> arrayThree = new ArrayList<String>();                 for(int i = 0; i

Jquery - Basic function for beginner

This is a jQuery basic fucntion that developers need to know. Do something after page load successfully $(document).ready(function() {   //do something }); Select Element by id / class var element = $("#idOfElement"); var elementByClass = $(".className"); if have more than one element with same class name var elementByClass = $(".className")[0]; Get selected value (drop down) var selectedValue = $("#isDropdown").val(); //return selected value Or var selectedValue = $("#isDropdown option:selected").val(); //return selected value Get selected text(drop down) var selectedValue = $("#isDropdown").text(); //return selected text Or var selectedValue = $("#isDropdown option:selected").text(); //return selected text Get Textbox Value var valueTextBox = $("#idTextbox).val();   Show/hide element  $("#idElement).show(); or  $("#idElement).fadeIn(500);  $("#idElement).hide(); or  $("#idElement).fadeOut(5

[SOLVED] JQuery - AJAX 500 Internal Server Error - JSON - jQueryAjax

Image
The above error always occur if you work with jQuery + Ajax. The error above may have several reason why the error occur and one of the reason is you are using the different parameter name to post to the server. Let say the method getState in webservice require one parameter which will represent country name, you must use the exactly name parameter to request from webservice. The Other Reason Not using JSON.stringify to pass parameter value. If you not supply type in jQuery, it will use GET method which is not accept in your webservice configuration. Add  ( type : "POST ) in your jQuery code to use POST method. You are actually request data from different domain. Cross Domain Request (CORS)which is not allowed. Please read here Content type not supply or not correct. Use " application/json; charset=utf-8 " DataType not not supply or not correct. Use json or jsonp By Mohd Zulkamal NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Fa

How to add items list in dropdown list using jquery - Cascading drop down

If you want to create 2 dropdown lists in which the second dropdown value will depend on the selected value from the first dropdown, you need to Implement JSON + Webservice+ JQuery. In my solution, I will use Jquery Ajax to request data from web service and add value to the second dropdown. Scenario Let say the first dropdown will list all Country, and the second dropdown will list all state from the selected country. Solution Create JSON Webservice, you can refer to this link Create custom JQuery function to handle onChange event on dropdown list country. Use return value from web services to the second dropdown items list. Full Code Example Note: The web service will use from the post here <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>     <title></title>     <script type="text/javascript&quo

How to create JSON webservice in ASP.NET

This example will show how to create Webservice using asp.net and the result will return in format JSON ( JavaScript Object Notation ). Below is the step by step to create webservice: Open Visual studio. Create New Project Add New File in the solution and choose Web Service file( .asmx) Copy paste code below to create your own JSON webservice The Web Service Code /// <summary>     /// Summary description for KenticoJSONTest     /// </summary>     [WebService(Namespace = "http://tempuri.org/")]     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]     [System.ComponentModel.ToolboxItem(false)]     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.     [System.Web.Script.Services.ScriptService]     public class AjaxWebService : System.Web.Services.WebService     {         [WebMethod]         public string HelloWorld()         {             return "Hello World";         }         [WebMethod]

JQuery Height not correct

JQuery have method to get the window height : - $(window).height()  , and document height : - $(document).height() ; Problem window height and document height give the same result which is wrong. If you resize the browser , the window height  should give smaller or bigger than document height. The Full HTML Code <html> <head>   <script type='text/javascript' src='http://code.jquery.com/jquery-1.10.1.js'></script> <script type='text/javascript'>$(document).ready(function(){     $('#windowheight').text($(window).height());     $('#documentheight').text($(document).height()); }); </script> </head> <body>   <div id="result">     $(window).height() = <span id="windowheight"></span> <br/>     $(document).height() = <span id="documentheight"></span> </div> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.  Sed vulpu

Print GridView Header On Each Page While On Printing : ASP.NET

Image
This example will show how you can include Table header on each page when you print the html document. You need to have the css, and javascript to do this objective. Let see the full example. The ASPX Page <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">     <title></title>     <style type="text/css" media="print">         .hideOnPrint         {             display: none;         }     </style>     <style type="text/css">         @media print         {             th             {                 color: black;                 background-color: white;             }             THEAD             {                 display: table-header-group;                 border: solid 2px black;             }         }     </style>     <sty

Multiple select button in one gridview

Image
GridView Multiple Select Buttons this is the keyword when i used to searching in Mr. Google and end up with several link to solve this problem. This was my solution to have a multiple select button in one GridView Controller The ASPX Page   <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black" GridLines="Vertical" Font-Names="Arial" Font-Size="12px" OnRowCommand="ActionCommand"> <Columns> <asp:BoundField DataField="ID" HeaderText="NO." /> <asp:BoundField DataField="CustomerName" HeaderText="Customer Name" /> <asp:ButtonField CommandName="showName" Text="Show Name" /> <

C#: Check if an application is already running

This is the snippet code to check if application running or not in C# using System.Diagnostics; bool IsApplicationAlreadyRunning(string processName) { Process[] processes = Process.GetProcessesByName(processName); if (processes.Length >= 1) return true; else return false; } By Mohd Zulkamal NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

RegisterForEventValidation can only be called during Render()[SOLVED]

Today i do my routine by developing / testing / and debuggig and found error on my web page : RegisterForEventValidation can only be called during Render(); The code actually for get html code from server side inside panel ...  var sb = new StringBuilder();  Panel1.RenderControl(new HtmlTextWriter(new StringWriter(sb)));  string htmlToConvert = sb.ToString(); So i do some googling and found the causes of this error occur.. The Causes occurs when you try to render a control to Response. Generally some people got this when I exported GridView to Excel, Word, PDF or CSV formats. The ASP.Net compiler issues the above Exception since it feels the Event is invalid. Solution The solution is quite simple you need to notify ASP.Net that not to validate the event by setting the EnableEventValidation flag to FALSE You can set it in the Web.Config in the following way <pages enableEventValidation="false"></pages> This will apply to all the pages in your website. Else yo

C# coalesce operator : Question Mark In C# and Double Question Mark

A not so common, but very useful operator is the double question mark operator (??). This can be very useful while working with null able types. Lets say you have two nullable int: int? numOne = null; int? numTwo = 23; Note : int? (data type with question mark used to declare variable with null able type) Scenario: If numOne has a value, you want it, if not you want the value from numTwo , and if both are null you want the number ten (10). Old solution: if (numOne != null)     return numOne; if (numTwo != null)     return numTwo; return 10; Or another solution with a single question mark : return (numOne != null ? numOne : (numTwo != null ? numTwo : 10)); But with the double question mark operator we can do this: return ((numOne ?? numTwo) ?? 10); Output : return numOne if have value, else return numTwo else return 10; As you can see, the double question mark operator returns the first value that is not null. By Mohd Zulkamal NOTE : – If You have Found this post Helpful, I will a

Pinging in ASP.NET Example

Image
This tutorial will show you how to ping a hostname/ip using the .NET System.Net class, ASP.NET 2.0 and C#.NET. The .NET Framework offers a number of types that makes accessing resources on the network easy to use. To perform a simple ping, we will need to use the System.Net, System.Net.Network.Information, System.Text namespaces. using System.Net; using System.Net.NetworkInformation; using System.Text; ASPX Page  <asp:ScriptManager ID="ScriptManager1" runat="server">     </asp:ScriptManager>     <asp:UpdatePanel ID="UpdatePanel1" runat="server">         <ContentTemplate>             <table width="600" border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#cccccc">                 <tr>                     <td width="100" align="right" bgcolor="#eeeeee" class="header1">                         Ho

Dynamically Add/Remove rows in HTML table using JavaScript

Image
This is very often for web developer when we need to use dynamically generate HTML table using JavaScript. The example will spare the first row(cannot delete) and you can dynamically add new row by clicking the button Add Row or delete the row by clicking the button Delete Row . The Code <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>     <title>Add/Remove dynamic rows in HTML table </title>     <script language="javascript">            function addRow(tableID) {             var table = document.getElementById(tableID);             var rowCount = table.rows.length;             var row = table.insertRow(rowCount);             var cell1 = row.insertCell(0);             var element1 = document.createElement("input");             element1.type = "checkbox";             ce

Constants VS ReadOnly

Constants are similar to read-only fields. You can’t change a constant value once it’s assigned. The const keyword precedes the field to define it as a constant. Assigning value to a constant would give a compilation error. For example: const int num3 = 34; num3 = 54; // Compilation error: the left-hand side of an assignment must  // be a variable, property or indexer Although constant are similar to read-only fields, some differences exist. Constants are always static, even though you don’t use the static keyword explicitly, so they’re shared by all instances of the class. The readonly keyword differs from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Example Constant public class ConstTest {     class SampleClass     {         public int x;         public int y;         p

C#: Execute Two Dependant Processes

This example shows how to run 2 program in application and the second program need to run after the first program successfully start. The example will use 2 program which is Notepad and Paint . The Notepad need to run first and after Notepad successfully run, the Paint application will start to open program. Let see the code. Two Dependant Processes using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Threading; namespace TwoDependantProcesses {      class Program     {           static void Main(string[] args)          {                  Console.WriteLine("Press Enter to start Notepad (i.e. Process 1)");                  Console.ReadKey();                  Console.WriteLine("Starting Notepad...");                  Thread t1 = new Thread(new ThreadStart(StartProcess1));                   t1.Start();                   while (t1.IsAlive == true)                  {                       System.Threading.Thread.Sleep

fancybox on google map marker example

Image
FancyBox is a tool for displaying images, html content and multi-media in a Mac-style "lightbox" that floats overtop of web page.  This example will show how to use Google Map Marker With Fancybox. You can see my previous post about Creating Google Map API Zoom the marker This is the requirement for this example : Jquery Script - you can get it here fancybox script pack - you can get it here fancybox css - you can get it here html page and of course the Google Map Script Header on html page * The header should link with jquery and fancybox script. I will put Google Marker script at header also. <script type="text/javascript" src="jquery-latest.min.js"></script> <script type="text/javascript" src="jquery.fancybox.pack.js"></script> <link href="jquery.fancybox.css" type="text/css" rel="StyleSheet" /> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor