Some important question on WCF


What is the service?
Services are a group of methods that share a common set of requirements and functional goals. They are called by other parts that need to execute its logic, depending on the outcome (such as data, results of calculations, and so on).

Service is the combination of Channel, Protocol, Message, Policy, Schema and Contract

What is SOA ?
SOA is service oriented architecture. It is style of programming, an architectural approach in software development, where the application is organized in functional units of code with a given behavior called services.

SOA is a way to build distributed systems where autonomous logic is called using loosely coupled messages via a well defined interface.

Four Tenets of SOA
1. Boundaries are explicit

Boundaries are explicit means client only needs to be aware of the existence of function in the service that can only be executed via the contract.

2. Services are autonomous

Services are autonomous means
• Services should not dependent on the behavior of the other service.
• Services should be deployed and versioning independently.
• Service shouldn’t be coupled to each other as classes are coupled.

3.Services share schema and contract, not class

Schema is the definition of service operation and describes the signature of function. I.e. the name of function, type of parameters, and the type of return values. Service should not share the code of class to other parties.

4.Service compatibility is based on policy

A policy is used to negotiate elements in communication, such as message format and security requirement

Message Exchange pattern in WCF ?

These are the message pattern in WCF
1. Request-Response
The most commonly used pattern. The client request message from service by sending a request message and expect the response message from service. This means the service has to be reachable and
the client waits for the answer for a defined time.

2. One way

Messages are sent from client to server in one direction. The client sends a message but doesn’t expect an answer back.

3. Duplex Messaging

In the duplex pattern, client and server exchange messages without a predefined pattern. The client sends an initial request to the service waiting for a response but allows the service that sends the response to call back to the client to ask for more information. The service can call back to the client dynamically and possibly multiple times before sending the response to the initial request.

4. Streaming
In the streaming pattern the client initiates a request to get a very large set of data. The service chunks up the data in smaller pieces and sends them to the client one by one. The data is so big that the service has to read this data from a file system or database in chunks. The data chunks are sent to the client in an ordered way as the receiver wants to consume them in that same ordered way. This would be the case in streaming video.

5. Pub-Sub

In the pub – sub pattern the publisher is typically unaware who the subscribers are and what they are doing with the received data. The publisher doesn’t even care whether there are subscribers.
The publisher just cares about sending data out of its system.

How to Create “watermark” Text on Image in asp.net?



Hi
If you want to protect your image being reuse by other person, then the best way to protect image by keeping watermark text on image.

Here is the few steps to do this task

Step1: Keep some image on Default page like this

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<img src="images/Koala.jpg" height="500px" width="600px" />
</div>
</form>
</body>
</html>

Step2: Create one Class i.e WaterMark in appcode folder and write the code like this

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mime;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

/// <summary>
/// Summary description for ImageHandler
/// </summary>
public class WaterMark : IHttpHandler
{

public string GetContentType(String path)
{
switch (Path.GetExtension(path))
{
case ".bmp": return "Image/bmp";
case ".gif": return "Image/gif";
case ".jpg": return "Image/jpeg";
case ".png": return "Image/png";
default: break;
}
return String.Empty;
}

public ImageFormat GetImageFormat(String path)
{
switch (Path.GetExtension(path).ToLower())
{
case ".bmp": return ImageFormat.Bmp;
case ".gif": return ImageFormat.Gif;
case ".jpg": return ImageFormat.Jpeg;
case ".png": return ImageFormat.Png;
default: return null;
}
}

protected byte[] WatermarkImage(HttpContext context)
{

byte[] imageBytes = null;
if (File.Exists(context.Request.PhysicalPath))
{
// Normally you’d put this in a config file somewhere.
string watermark = "https://chandradev819.wordpress.com/&quot;;

Image image = Image.FromFile(context.Request.PhysicalPath);

Graphics graphic;
if (image.PixelFormat != PixelFormat.Indexed && image.PixelFormat != PixelFormat.Format8bppIndexed && image.PixelFormat != PixelFormat.Format4bppIndexed && image.PixelFormat != PixelFormat.Format1bppIndexed)
{

graphic = Graphics.FromImage(image);
}
else
{

Bitmap indexedImage = new Bitmap(image);
graphic = Graphics.FromImage(indexedImage);

// Draw the contents of the original bitmap onto the new bitmap.
graphic.DrawImage(image, 0, 0, image.Width, image.Height);
image = indexedImage;
}
graphic.SmoothingMode = SmoothingMode.AntiAlias & SmoothingMode.HighQuality;

Font myFont = new Font("Arial", 20);
SolidBrush brush = new SolidBrush(Color.FromArgb(80, Color.White));

//This gets the size of the graphic

SizeF textSize = graphic.MeasureString(watermark, myFont);

// Code for writing text on the image.

PointF pointF = new PointF(430, 710);
graphic.DrawString(watermark, myFont, brush, pointF);

using (MemoryStream memoryStream = new MemoryStream())
{
image.Save(memoryStream, GetImageFormat(context.Request.PhysicalPath));
imageBytes = memoryStream.ToArray();
}

}
return imageBytes;
}

#region IHttpHandler Members

public bool IsReusable
{
get { return false; }
}

public void ProcessRequest(HttpContext context)
{
context.Response.Clear();
context.Response.ContentType = GetContentType(context.Request.PhysicalPath);
byte[] imageBytes = WatermarkImage(context);
if (imageBytes != null)
{
context.Response.OutputStream.Write(imageBytes, 0, imageBytes.Length);
}
else
{

context.Response.StatusCode = 404;
}
context.Response.End();
}

#endregion
}

Step3: In web confi file add this line between tag like this

<httpHandlers>

<add verb="*" path="*.jpg,*.gif" type="WaterMark" />
</httpHandlers>

How to protect images in asp.net Website?


Hi

if we have to protect our images from being download or reusing by some other person on other website, we can protect our images using so many ways like

1.Disable right click using Javascript or Jquery
2.Keeping “WaterMark Text” on Image

How to disable right click using Javascript ?

This method is very easy to use, but if the user will disable the javascript then he can download the image.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Image_Protection_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head runat="server">
<title></title>

<script language="javascript">

function right(e) {
var msg = "Sorry, you don’t have permission to download Image";

if (navigator.appName == ‘Netscape’ && e.which == 3) {
alert(msg);
return false;
}
if (navigator.appName == ‘Microsoft Internet Explorer’ && event.button==2) {
alert(msg);
return false;
}
else return true;
}

function trap()
{
if(document.images)
{
for(i=0;i<document.images.length;i++)
{
document.images[i].onmousedown = right;
document.images[i].onmouseup = right;
}
}
}

</script>

</head>
<body onLoad="trap()">
<form id="form1" runat="server">
<div>
<img src="../Img/Penguins.jpg" alt="" height="300px" height="200px" />
</div>
</form>
</body>
</html>

How to disable right click using Jquery ?

Here is the complete syntax

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Image_Protection_Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&gt;
</script>
<script type="text/javascript" language="javascript">
$(function() {
$(this).bind("contextmenu", function(e) {
e.preventDefault();
var msg = "Sorry, you don’t have permission to download Image";
alert(msg);
});
});

</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<img src="../Img/Penguins.jpg" height="200Px" width="200px" alt="" />

</div>
</form>
</body>
</html>

For keeping watermar text on image read this article WaterMark Text on Image

How to do insert/Update/Delete using Entity Framework in asp.net ? Part #3


Hi
I hope that you are knowing the database mapping concept of EF. If not then please see my previous post How to fill gridview using EF?

For doing CRUD operation using EF, we have to do like this
srep1: Take gridview,Lable,Hidden field asp.net control and design the page like above

<div>

<asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False" AllowPaging="true"
CellPadding="4" ForeColor="#333333" GridLines="None" Width="417px"
onpageindexchanging="Gridview1_PageIndexChanging"
onrowcommand="Gridview1_RowCommand"
onrowdeleting="Gridview1_RowDeleting" onrowediting="Gridview1_RowEditing">
<RowStyle BackColor="#E3EAEB" />
<Columns>
<asp:TemplateField HeaderText="SI.No">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="EmpName" DataField="EmpName" />
<asp:BoundField HeaderText="EmpSal" DataField="EmpSal" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CausesValidation="false" CommandName="Edit" CommandArgument='<%# Eval("Id") %>’ OnClientClick="return confirm(‘Are you sure?’)" />
<asp:LinkButton ID="LinkDelete" runat="server" Text="Delete" CausesValidation="false" CommandName="Delete" CommandArgument='<%# Eval("Id") %>’ OnClientClick="return confirm(‘Are you sure?’)" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#7C6F57" />
<AlternatingRowStyle BackColor="White" />

</asp:GridView>
<asp:HiddenField ID="HiddenField1" runat="server" />

</div>

Step2: Write the code in code behind page like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
fillGrid();
}

//This code is used for fetch data from database
protected void fillGrid()
{
using (TestModel.TestEntities TE = new TestModel.TestEntities())
{
var query = from m in TE.tblEmp
orderby m.Id descending
select m;
Gridview1.DataSource = query;
Gridview1.DataBind();
}
}

protected void BtnSubmit_Click(object sender, EventArgs e)
{
if (BtnSubmit.Text == "Submit")
{
SaveEmpData();

fillGrid();
}
else if (BtnSubmit.Text == "Update")
{
UpdateEmpRecord();
fillGrid();

}

}

//This code is used for Update functionality
private void UpdateEmpRecord()
{
using (TestModel.TestEntities TE = new TestModel.TestEntities())
{
int Id1=Convert.ToInt32(HiddenField1.Value);
var query = (from m in TE.tblEmp
where m.Id==Id1
select m).First();

query.EmpName = txtEmpName.Text;
query.EmpSal = txtEmpSal.Text;
TE.SaveChanges();
lblmsg.Text = "Data has been updated Sucessfully";
BtnSubmit.Text = "Submit";
txtEmpName.Text = "";
txtEmpSal.Text = "";
}

}

// This code is used for save functionality
private void SaveEmpData()
{
using (TestModel.TestEntities TE = new TestModel.TestEntities())
{

TestModel.tblEmp objEmp = new TestModel.tblEmp();
objEmp.EmpName = txtEmpName.Text;
objEmp.EmpSal = txtEmpSal.Text;
TE.AddTotblEmp(objEmp);
TE.SaveChanges();
lblmsg.Text = "Data has been inserted sucessfully";
txtEmpName.Text = "";
txtEmpSal.Text = "";
}

}

protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
// This code is used for Delete functionality

if (e.CommandName == "Delete")
{
using(TestModel.TestEntities TE=new TestModel.TestEntities())
{
int id1 = Convert.ToInt32(e.CommandArgument);
var user = TE.tblEmp.First(m => m.Id == id1);
TE.DeleteObject(user);
TE.SaveChanges();
fillGrid();
lblmsg.Text = "";
txtEmpName.Text = "";
txtEmpSal.Text = "";

}

}

//This code is used for fetching particular row of gridview and dispaly on
// respective textbox field

else if (e.CommandName == "Edit")
{
using (TestModel.TestEntities TE = new TestModel.TestEntities())
{
int id1 = Convert.ToInt32(e.CommandArgument);
var Empinfo = GetEmpInfo(id1);
txtEmpName.Text= Empinfo[0].EmpName.ToString();
txtEmpSal.Text = Empinfo[0].EmpSal.ToString();
HiddenField1.Value= Empinfo[0].Id.ToString();
BtnSubmit.Text = "Update";
}
}

}
protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{

}
protected void Gridview1_RowEditing(object sender, GridViewEditEventArgs e)
{

}
//This code is used for paging
protected void Gridview1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
Gridview1.PageIndex = e.NewPageIndex;
fillGrid();

}

private List<TestModel.tblEmp> GetEmpInfo(int Id)
{
using (TestModel.TestEntities TE = new TestModel.TestEntities())
{
return (from m in TE.tblEmp
where m.Id == Id
select m).ToList();
}
}

}

How to fill Gridview using Entity Framework in asp.net ?Part #2



Hi
Here is some few steps to do this task

Note: I have tested this code with asp.net 3.5 sp1, In asp.net 4.0 also process is same.

Step1: Go to solution Explore, then right click then add new item like this

Step2: Click on next like this

Step3: Select the Exact database and click on next like this

Step4: Select your table name like this

Step5: Then you will get Model.edmx file like this

Step6:Take one gridview asp.net control in default page and write the code in code behind page like this

protected void Page_Load(object sender, EventArgs e)
{
fillGrid();
}

//This code is used for fetch data from database
protected void fillGrid()
{
using (TestModel.TestEntities TE = new TestModel.TestEntities())
{
var query = from m in TE.tblEmp
orderby m.Id descending
select m;
Gridview1.DataSource = query;
Gridview1.DataBind();
}
}