Skip to main content

Posts

Showing posts from 2014

Knockout JS [Hello World]

Knockout is a standalone JavaScript implementation of the Model-View-ViewModel pattern with templates. The underlying principles are therefore: a clear separation between domain data, view components and data to be displayed.
What is Model?
Model is your business entity like User,Customer objects which contains property.
What is ViewModel:
Viewmodel looks like Model but it contains behavior
Let's create a simple hello world example using knockout.js.Create a html file named index.html and add following code
In the above code,first I have added refrence of knockout.js and then created two html controls input and span.Notice the markup on line 8 and 9 We are using a new attribute: data-bind.
data-bind is knockout syntax for binding viewmodel property to view.
On line 10 to 14 I have created a simple viewmodel which have one singal property message with default value "Hello World".
On line 15 I am attaching viewmodel to view 

Using the DropDownList Helper with ASP.NET MVC

This post will teach you the basics of working with the DropDownList helper helper in an ASP.NET MVC Web application.
The DropDownList helper used to create an HTML select list requires a IEnumerable , either explicitly or implicitly. That is, you can pass the IEnumerable explicitly to the DropDownList helper or you can add the IEnumerable to the ViewBag using the same name for the SelectListItem as the model property.
Let's suppose you want to show list of Animals as dropdownlist

publicstatic List<String> GetPets() { List<string> petList = new List<string>(); petList.Add("Dog"); petList.Add("Cat"); petList.Add("Hamster"); petList.Add("Parrot"); petList.Add("Gold fish"); petList.Add("Mountain lion"); petList.Add("Elephant"); return petList; }
Open your controller met…

How to create html helper in razor (.NET MVC)

Razor is an ASP.NET programming syntax used to create dynamic web pages with the C# or Visual Basic .NET programming languages.The Razor syntax is a template markup syntax, based on the C# programming language, that enables the programmer to use an HTML construction workflow[clarification needed]. Instead of using the ASP.NET .ASPX markup syntax with <%= %> symbols to indicate code blocks, Razor syntax starts code blocks with a @ character and does not require explicit closing of the code-block.

HTML Helper
Html helper are much like asp.net control that return html string.But HTML helpers are more lightweight. Unlike Web Form controls, an HTML helper does not have an event model and a view state.
In this post I will show you how to create Html helper in MVC.NET.There are two ways to create html helper in MVC.
Inline Helpers
These are create in the same view by using the Razor @helper tag. These helpers can be reused only on the same view.For example in following code snippet I ha…

How to check stream has Image or not

Let's suppose you have a page on which user upload there image and you want to validate that user is uploading image file only not other file format.The one easy solution is use regex and validate the extension of the file but if user rename the extension of the file and upload some executable code.Following is the simple c# code snippet that check the file type by the header value.
privatebool IsImage() { bool isImage = false; FileStream stream = new FileStream(Server.MapPath(@"Images\a.txt"), FileMode.Open, FileAccess.Read); StreamReader reader = new StreamReader(stream); // Read the first 25 characters, we will be checking for a GIF or JPG signature.char[] strBuffer = newchar[25]; reader.ReadBlock(strBuffer, 0, 25); string stringBuffer = newstring(strBuffer); // Is this an image?if (stringBuffer.IndexOf("GIF8") &gt; -1 || stringBuffer.IndexOf("JFIF") &gt; -1) { i…

How To Change your ASP.Net controls at runtime

Lets say you are working in a fairly large asp.net application. Now because of situation (or clients request) you want to change all the textbox or button control to some server control or user control. This can be very very tedious JOB if you are using Asp.net 1.X. But if you are using Asp.net 2.0 , there is a very easy way to get this done using tagMapping
it’s a way to turn all instances of a type into another type at compile time. In human language it means that it can turn all e.g. System.Web.UI.WebControls.Textbox (in our example ) instances in the entire website into another control.That is so cool that I had to do a little example. I’ve created a very simple control that inherits from a TextBox and overrides the Text property so that it HTML encodes the text. I placed it in the App_Code folder and called it SafeTextBox.

using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; …

How to change some text before it is sent to the client.

In this post,I will show you how to modify the response before it is sent to the client.The trick here is to override the Render method of the Page class and modify the response.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="InterceptHtml.aspx.cs" Inherits="InterceptHtml" %> <!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>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> Hello World! <br /> Hi </div> </form> </body> </html>
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using Syst…

How to return data from ajax call

In this post,I will show you how to return data from ajax request.As you know that you can not return data from ajax request but if you want to perform some action on return data of ajax.The better approach is to organize your code properly around callbacks. In the example,you can make GetUsers accept a callback and use it as success callback.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ReturnAjax.aspx.cs" Inherits="ReturnAjax" %><!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"><headrunat="server"><scripttype="text/javascript"src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <title></title> <script type="text/javascript"> $(document).ready(function () { …

How To Convert HTML to Text, Easily

Whether you want to convert an HTML page into pure text so you can parse out that special piece of information, or you simply want to load a page from the Net into your own word processing package, this mini function could come in handy. It’s called StripTags and accepts an HTML string. Using a regular expression, it identifies all <tags>, removes them, and returns the modified string. Here’s the code:<%@ Page Language="C#" ValidateRequest="False" AutoEventWireup="true" CodeFile="StripTag.aspx.cs" Inherits="StripTag" %><!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"><headrunat="server"><title>Untitled Page</title></head><body><formid="form1"runat="server"><div><asp:TextBoxID="TextBox1&quo…

How to change default binding in wcf 4.0

In this post I will share a very handy tips for wcf 4.0.As we all know that default binding is a new feature introduced in wcf 4.0.With WCF 4, this is no longer the case because the runtime automatically adds one or more "default endpoints" for you, thereby making the service usable without any configuration.
<protocolMapping><addbinding="wsHttpBinding"scheme="http"/></protocolMapping>

How to create a simple http server in node.js

Node.js is an open source, cross-platform runtime environment for server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, Linux and FreeBSD.

Node.js provides an event-driven architecture and a non-blocking I/O API that optimizes an application's throughput and scalability. These technologies are commonly used for real-time applications.

Node.js uses the Google V8 JavaScript engine to execute code, and a large percentage of the basic modules are written in JavaScript. Node.js contains a built-in library to allow applications to act as a Web server without software such as Apache HTTP Server or IIS.


Start by creating a new file named “app.js”. Insert the following code into the file and save it.

var http = require("http"); var app = http.createServer(function(request, response) {   response.writeHead(200, { "Content-Type": "text/html" });…

How to stream large file using node.js

Node.js is an open source, cross-platform runtime environment for server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, Linux and FreeBSD.

Node.js provides an event-driven architecture and a non-blocking I/O API that optimizes an application's throughput and scalability. These technologies are commonly used for real-time applications.

Node.js uses the Google V8 JavaScript engine to execute code, and a large percentage of the basic modules are written in JavaScript. Node.js contains a built-in library to allow applications to act as a Web server without software such as Apache HTTP Server or IIS.




var http = require('http'); var fs = require('fs'); http.createServer(function(req, res) { var newFile = fs.createWriteStream("x.wmv"); var fileBytes = req.headers['content-length']; var uploadedBytes = 0; req.pipe(newFile); req.on(&#…

Understand WebMessage Format

In this post I will show how how to use WebMessageBodyStyle parameter attribute in REST Service.WebMessageBodyStyle is an enumeration that specifies whether to wrap parameter and return values.WebMessageBodyStyle contains four member.

I have listed down all the members and there discription in following table.

using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; namespace RestLoginService { [ServiceContract] publicinterface ILoginService { [OperationContract] [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] AuthResult Login(User user); } }

using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using …

Decorator Design Pattern

Intent:
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub classing for extending functionality (also known as Wrapper)





using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DecoratorPattern { publicclass UpperStream : Stream { private Stream _stream; public UpperStream(Stream stream) { this._stream = stream; } publicoverridelong Length { get { return _stream.Length; } } publicoverrideint Read(byte[] buffer, int offset, int count) { var numberOfBytesRead = _stream.Read(buffer, offset, count); for (int i = 0; i < numberOfBytesRead; i++) { buffer[i] = (byte)char.ToUpper((char)((int)buffer[i])); } return numberOfBytesRead; } publicoverrideboo…

Strategy Design Pattern

Strategy Design Pattern
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Problem:
Client wants to decide at run-time what serialization it should use to serialize a type. Many different serialization algorithms are already available.
Solution:
Encapsulate the different serialization algorithms using the Strategy pattern!
C# Code
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StrategyPattern { publicinterface ISerializer { void Serialize(); } publicclass XmlSerializer : ISerializer { publicvoid Serialize() { Console.WriteLine("Xml serilizer Invoked"); } } publicclass JsonSerializer : ISerializer { publicvoid Serialize() { Console.WriteLine("Json serializer Invoked"); } } …

Adapter Design Pattern

Adapter Pattern: The Adapter pattern converts the interface of a class into another interface that clients expect.The client makes a request on the adapter by invoking a method from the target interface on it and then adapter translates that request into one or more calls on the adaptee using the adaptee interface. The client receives the results of the call and never knows there is an adapter doing the translation

Pre-Condition: You are maintaining an existing system that makes use of a third-party class library from vendor A
Stimulus: Vendor A goes belly up and corporate policy does not allow you to make use of an unsupported class library.
Response: Vendor B provides a similar class library but its interface is completely different from the interface provided by vendor A
Assumptions: You don’t want to change your code, and you can’t change vendor B’s code
Solution?: Write new code that adapts vendor B’s interface to the interface expected by your original code

C# Example




using System;
usi…