Monday, January 30, 2012

Is Razor or XSLT better for my project?

I've read an very good article about XSLT and RAZOR. Some people think XSLT is better when you are using Multiple templates.

I don't agree with that. For me, Xslt is good for only static html pages. (no server codes). When you need to use server code, it's a lot difficult to control with XSLT.

XSLT or Razor would help to provide a separation of concerns where the original XML or response represents your model, the XSLT or 'Razor view' represents your view. I'll leave the controller out for this example. The initial design proposal recommends XSLT, however I suggested the use of Razor instead as a more friendly view engine.

These are the reasons I suggested for Razor (C#):

  • Easier to work with and build more complicated pages.
  • Can easily produce non-*ML output, eg csv, txt, fdf
  • Less verbose templates
  • The view model is strongly typed, where XSLT would need to rely on convention, eg boolean or date values
  • Markup is more approachable, eg nbsp, newline normalization, attibute value normalization, whitespace rules
  • Built in HTML helper can generate JS validation code based on DTO attributes
  • Built in HTML helper can generate links to actions

And the arguments for XSLT over razor were:

  • XSLT is a standard and will still exist many years into the future.
  • It is hard to accidentally move logic into the view
  • Easer for non programmers (which I don't agree with).
  • It's been successful in some of our past projects.
  • Data values are HTML-encoded by default
  • Always well formed

So I'm looking for aguments on either side, recommendations or any experience making a similar choice?

Sunday, November 6, 2011

Facebook comment:


Google will index comments from sites using Facebook's comments plug-in
Move should see lively discussion sites benefit
Google also tweaking search so 'trending' results 'work faster'



Read more: http://www.dailymail.co.uk/sciencetech/article-2057640/Now-Googles-spiders-read-Facebook-comments.html#ixzz1cyVwuMMU





https://developers.facebook.com/docs/reference/plugins/comments/

Sunday, October 30, 2011

MVC 3 Razor C# View Engine adding

As a OOD web developer, I like to group usercontrols, pages to related folders.
In MVC 3, Default Search view engine works like the following:

If user controls, the View engine finds under View folder OR Shared folder only.

Here is a problem:

If I created a folder under shared folder and your user control having in that folder, MVC ViewEngine couldn't find the correct user control via embedded usercontrol's page.

.Net throws this error.




But in MVC, every class that integreated in MVC you can extend as your custom requried.

Here is an example that I've found in internet that somebody shared in this website
(Waynehaffenden.com


RazorCSharpViewEngine.cs
view source

01 using System.Web.Mvc;
02 public class RazorCSharpViewEngine : RazorViewEngine
03 {
04 public RazorCSharpViewEngine()
05 {
06 AreaViewLocationFormats = new[]
07 {
08 "~/Areas/{2}/Views/{1}/{0}.cshtml",
09 "~/Areas/{2}/Views/Shared/{0}.cshtml"
10 };
11 AreaMasterLocationFormats = new[]
12 {
13 "~/Areas/{2}/Views/{1}/{0}.cshtml",
14 "~/Areas/{2}/Views/Shared/{0}.cshtml"
15 };
16 AreaPartialViewLocationFormats = new[]
17 {
18 "~/Areas/{2}/Views/{1}/{0}.cshtml",
19 "~/Areas/{2}/Views/Shared/{0}.cshtml"
20 };
21 ViewLocationFormats = new[]
22 {
23 "~/Views/{1}/{0}.cshtml",
24 "~/Views/Shared/{0}.cshtml"
25 };
26 MasterLocationFormats = new[]
27 {
28 "~/Views/{1}/{0}.cshtml",
29 "~/Views/Shared/{0}.cshtml"
30 };
31 PartialViewLocationFormats = new[]
32 {
33 "~/Views/{1}/{0}.cshtml",
34 "~/Views/Shared/{0}.cshtml"
35 };
36 }
37 }


Your Global.ascs's Application start() method should be as following.

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();

RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);

ViewEngines.Engines.Add(new RazorCustomViewEngine());
}

Friday, October 7, 2011

OOD Project?

Today, one of my colleague ( as Senior developer), he told me his project is OOD programming project. I didn't say anything back to him. Just laughed myself.
Please look up following code whether it's OOD porject or not.

It's about binding Portfolio data from portfolio database.



I tired to add a new simple functionality to his code. And also he's always saying his code the best one.

Friday, June 24, 2011

Invalid operation. The connection is closed. ASP.NET MVC

Invalid operation. The connection is closed. ASP.NET MVC



In Entity framework 4.0.. datacontext shouldn't be static. so then, in every controller, you need to do a new instance of datacontext.

Otherwise, static datacontext can occur that two different request hitting will break the site.

Globalization .net


foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.
NeutralCultures))
{
DropDownListLang.Items.Add(new ListItem(ci.NativeName, ci.Name));
}


That's cool. You will get all available .net culture into the drop down list.

Wednesday, June 1, 2011

return confirm('" & strMessage & "');")

Most of people know the following codes.

btn.Attributes.Add("onclick", "return confirm('single " & strMessage & " single ');")

what I want to mention is "return confirm('" & strMessage & "')
sometime in development, you may need to do string manipulation. the similar case could be happened any time.

For reference purpose, I've hosted this post. If someone can reference on this, I am worth to put this post.

Friday, May 20, 2011

How to: Move a Database Using Detach and Attach (Transact-SQL)

You can move a detached database to another location and re-attach it to the same or a different server instance.

Attach the moved database and, optionally, its log by executing the following Transact-SQL statements:

USE master;
GO
CREATE DATABASE MyAdventureWorks
ON (FILENAME = 'C:\MySQLServer\AdventureWorks2008R2_Data.mdf'),
(FILENAME = 'C:\MySQLServer\AdventureWorks2008R2_Log.ldf')
FOR ATTACH;
GO

For a production database, place the database and transaction log on separate disks.

Enjoy on this !

Monday, May 16, 2011

MVC validation on controller.

The following link has very useful information for validation of mvc .

Before in my knowledge, I do understand the validation of mvc has to be placed on the model layer. That gives some headache to me to find right entity in entities.

That a pieces of codes saves my headache. That's just brilliant. Thanks to who posted this post. http://www.asp.net/mvc/tutorials/creating-model-classes-with-the-entity-framework-cs



public ActionResult Add()
{
return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Add(FormCollection form)
{
var movieToAdd = new Movie();

// Deserialize (Include white list!)
TryUpdateModel(movieToAdd, new string[] { "Title", "Director" }, form.ToValueProvider());

// Validate
if (String.IsNullOrEmpty(movieToAdd.Title))
ModelState.AddModelError("Title", "Title is required!");
if (String.IsNullOrEmpty(movieToAdd.Director))
ModelState.AddModelError("Director", "Director is required!");

// If valid, save movie to database
if (ModelState.IsValid)
{
_db.AddToMovieSet(movieToAdd);
_db.SaveChanges();
return RedirectToAction("Index");
}

// Otherwise, reshow form
return View(movieToAdd);
}

Tuesday, May 10, 2011

Microsoft SQL Server 2008 - Saving changes is not permitted

Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.

I have the same problem above. If you reference this site, you will get the resolve the problem.

http://www.sqlcoffee.com/Troubleshooting074



Thursday, May 5, 2011

Google map api for searching lat and lng by postcode and country name

This is a big achivement for Today. I was strugling with Italy google map. the issue was italy postcode has same format with US postcode. so, google api gives returns us map instead of italy map.

I solved this issue with some codes which does reference to this site

http://www.storm-consultancy.com/blog/development/code-snippets/using-google-maps-api-to-get-latitude-longitude-co-ordinates-from-postcode-or-address/

very genius of that.
public LatLng GetLatLng(string addr)
33 {
34 var url = "http://maps.google.co.uk/maps/geo?output=csv&key=" +
35 this.API_KEY + "&q=" + HttpContext.Current.Server.UrlEncode(addr);
36
37 var request = WebRequest.Create(url);
38 var response = (HttpWebResponse)request.GetResponse();
39
40 if (response.StatusCode == HttpStatusCode.OK)
41 {
42
43 var ms = new MemoryStream();
44 var responseStream = response.GetResponseStream();
45
46 var buffer = new Byte[2048];
47 int count = responseStream.Read(buffer, 0, buffer.Length);
48
49 while (count > 0)
50 {
51 ms.Write(buffer, 0, count);
52 count = responseStream.Read(buffer, 0, buffer.Length);
53 }
54
55 responseStream.Close();
56 ms.Close();
57
58 var responseBytes = ms.ToArray();
59 var encoding = new System.Text.ASCIIEncoding();
60
61 var coords = encoding.GetString(responseBytes);
62 var parts = coords.Split(",");
63
64 return new LatLng(
65 Convert.ToDouble(parts[2]),
66 Convert.ToDouble(parts[3]));
67 }
68
69 return null;
70 }
71 }

Have fun with this !

Tuesday, May 3, 2011

How to postback on index change of ASP.net MVC dropdownlist?

How to postback on index change of ASP.net MVC dropdownlist?

I have found this on internet from this site

http://www.altafkhatri.com/Technical/ASP-NET-MVC-Dropdownlist/How-to-post-back/on-selectedIndexChanged

It is really helpful post. I put this on here future reference.

Steps to create the postback in ASP.Net MVC dropdownlist selectedindex change event:

Create a controller - Dropdownlist. Paste the code in the section below.
Create a view of the GetDD action binded to the strongly typed object(CoverObject). Paste the code in the section below.


Code in the controller

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Mvc.Ajax;



namespace MvcApplication1.Controllers

{

public class CoverObject

{

public IList iliSLI;

public string SelectedName { get; set; }

public string Name { get; set; }

public string Address { get; set; }



public string formAction { get; set; }



public CoverObject()

{

iliSLI = new List();

SelectListItem sli = new SelectListItem();

sli.Text = "Altaf";

sli.Value = "1";



iliSLI.Add(sli);



sli = new SelectListItem();

sli.Text = "Krish";

sli.Value = "22";

iliSLI.Add(sli);



sli = new SelectListItem();

sli.Text = "Sameer";

sli.Value = "3333";

iliSLI.Add(sli);



sli = new SelectListItem();

sli.Text = "Iqbal";

sli.Value = "44444";

iliSLI.Add(sli);



sli = new SelectListItem();

sli.Text = "Maimoona";

sli.Value = "5555";

iliSLI.Add(sli);



}

}

public class DropdownlistController : Controller

{

//

// GET: /Dropdownlist/

public ActionResult Index()

{

return View();

}



public ActionResult GetDD()

{

CoverObject co = new CoverObject();

co.formAction = "";

//ViewData["SecretQuestion"] = co.iliSLI;

return View(co);

}



[AcceptVerbs(HttpVerbs.Post)]

public ActionResult GetDD(CoverObject co)

{

CoverObject coNew = new CoverObject();

string indexChangedValue = co.SelectedName;





var item = from it in coNew.iliSLI

where it.Value == co.SelectedName

select it;

item.First().Selected = true;

coNew.Name = item.First().Text;

coNew.Address = co.Address;





if (!string.IsNullOrEmpty(co.formAction) && co.formAction.Equals("Submit Form By Clicking"))

{

// Based on the main submit of the form, it can process and redirect or stay on the same view.

ModelState.AddModelError("_FORM", "Form Submitted by clicking submit button");

}

else//Submitted by dropdownlist index change event

{

//DROPDOWNLIST on selectedIndexChangedEvent Handled hereModelState.AddModelError("_FORM", "Form Submitted by clicking submit button");

ModelState.AddModelError("iliSLI", "Form Submitted by selected Index Change event");

}

return View(coNew);

}

}

}



Code in the aspx file

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>











GetDD







<%= Html.ValidationSummary("Form submitted by what event notification:") %>



<% using (Html.BeginForm()) {%>





Fields







<%= Html.TextBox("co.Address", Model.Address)%>

<%= Html.ValidationMessage("Address", "*") %>









<%= Html.DropDownList("co.SelectedName", Model.iliSLI, new { onChange = "onSelectedIndexChanged()" })%>

<%= Html.ValidationMessage("iliSLI", "*") %>









<%= Html.TextBox("Name", Model.Name, new { disabled="true" })%>

<%= Html.ValidationMessage("Name", "*") %>















<% } %>








Friday, February 18, 2011

Insert query return SCOPE_IDENTITY()

This is a example of how to get [table]ID back when you inserted a record to table.

this is very useful when you needed to do more business logic after table inserting.


ALTER PROCEDURE [dbo].[uspNewsletterSubscriptions_Insert]

@TitleId int,
@Forename nvarchar(255),
@Surname nvarchar(255),
@EmailAddress nvarchar(255),
@Id int OUTPUT

AS
BEGIN

insert into tNewsletterSubscriptions(TitleId, Forename, Surname, EmailAddress)
values(@TitleId, @Forename, @Surname, @EmailAddress)


SET @Id = SCOPE_IDENTITY()

SELECT [Id]
,[Created]
,[LastUpdated]
,[TitleId]
,[Forename]
,[Surname]
,[EmailAddress]

FROM tNewsletterSubscriptions
WHERE Id = SCOPE_IDENTITY()

END

Thursday, February 17, 2011

Email Templates with C# asp.net

From my expected, GlobalRescource .resx file is obviously handy to store email templates.

You write whatever you want that Html email template or text email template in eg(contorlsculture.resx) under App_GlobalResources.

And follows following codes -

private string FormatEmailBody(StringBuilder emailBody)
{
emailBody.Replace("{jobtitle}", HttpUtility.HtmlEncode(drVacancy.Title));
emailBody.Replace("{reference}", HttpUtility.HtmlEncode(drVacancy.Reference));
emailBody.Replace("{location}", HttpUtility.HtmlEncode(drVacancy.Location));
emailBody.Replace("{salary}", HttpUtility.HtmlEncode(drVacancy.Salary));

emailBody.Replace("{title}", HttpUtility.HtmlEncode(txtTitle.Text));
emailBody.Replace("{firstname}", HttpUtility.HtmlEncode(txtFirstName.Text));
emailBody.Replace("{surname}", HttpUtility.HtmlEncode(txtSurname.Text));
emailBody.Replace("{email}", HttpUtility.HtmlEncode(txtEmail.Text));
emailBody.Replace("{telephone}", HttpUtility.HtmlEncode(txtTelephone.Text));
emailBody.Replace("{message}", HttpUtility.HtmlEncode(txtMessage.Text));

return emailBody.ToString();
}

private void SendEmail()
{
// Sends Job application to recruiter
string strEmailBody = FormatEmailBody(new StringBuilder(Resources.ControlsCulture.JobApplicationTemplate));
EmailHelper.SendMail(drVacancy.Title + " Job - Application", strEmailBody, new string[] { ConfigHelper.RecruitmentEmail }, null, null,
ConfigHelper.NoReplyEmail.ToString(), fuApplicationForm.PostedFile, fuCV.PostedFile, fuOpsForm.PostedFile);


txtTitle.Text = txtFirstName.Text = txtSurname.Text = txtEmail.Text = txtConfirmEmail.Text =
txtTelephone.Text = txtMessage.Text = "";
phMessage.Visible = true;
}

protected void lkbSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
SendEmail();
}
}

That takes you get sucessful email sending process.


But on the other hand, some opposite idea programmer wants to use a physical files for email templates.

Then creates template files under App_data folder.
now a little bit needs to update the code of sending email. Basically, uses IO and stringbuilder class.

Something like that :

private string FormatEmailBody(StringBuilder emailBody)
{
emailBody.Replace("{contact}", HttpUtility.HtmlEncode("Administrator"));
emailBody.Replace("{name}", HttpUtility.HtmlEncode(txtTitle.Text + " " + txtFirstName.Text + " "
+ txtSurname.Text));
emailBody.Replace("{email}", HttpUtility.HtmlEncode(txtEmail.Text));
emailBody.Replace("{housename}", HttpUtility.HtmlEncode(txtHouseName.Text));

emailBody.Replace("{street}", HttpUtility.HtmlEncode(txtNumberStreet.Text));
emailBody.Replace("{area}", HttpUtility.HtmlEncode(txtLocation.Text));
emailBody.Replace("{town}", HttpUtility.HtmlEncode(txtCity.Text));
emailBody.Replace("{county}", HttpUtility.HtmlEncode(txtCounty.Text));
emailBody.Replace("{postcode}", HttpUtility.HtmlEncode(txtPostcode.Text));
emailBody.Replace("{telephone}", HttpUtility.HtmlEncode(txtTelephone.Text));
emailBody.Replace("{enquiry}", HttpUtility.HtmlEncode(txtEnquiry.Text));

return emailBody.ToString();
}

private void SendEmail()
{
string sFullTemplatePath = HttpContext.Current.Server.MapPath(drFormEmails.EmailTxtFileName);
StringBuilder sbTemplate = new StringBuilder();
using (StreamReader sr = new StreamReader(sFullTemplatePath))
{
sbTemplate = new StringBuilder(sr.ReadToEnd());
}

string strEmailBody = FormatEmailBody(sbTemplate);
EmailHelper.SendMail("Contact us", strEmailBody, new string[] { drFormEmails.MailTo }, null, null,
drFormEmails.MailFrom);
}

protected void lbSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
SendEmail();
Response.Redirect("/Contact-us-confirmation");
}
}


Any better suggestion, please comment it. I will reply you.

Thursday, February 10, 2011

how to display a value to textbox whos textmode is set to 'password' in c#

The code given below is to check the username n display the password via cookie. It works perfectly allright. since i want the value displayed in the password.text to be masked, i changed the textmode of the password.text to 'password'. as a result value isnt passed to the textbox.

Question: String cookiename = TextBox1.Text;

//grab cookie
HttpCookie cookie = Request.Cookies[cookiename];

//exists?
if (null == cookie)
{
Label1.Text = "cookie not found";
}
else
{
password.Text=cookie.Value.ToString();

}

Answer:

HttpCookie myCookie = new HttpCookie("MyTestCookie");
myCookie = Request.Cookies["MyTestCookie"];

TextBox2.Attributes.Add("value", cookie.Value.ToString());


The answer is just one line. but it saves a lot of time.

Monday, February 7, 2011

publicity event fire c#

publicity event fire



In Usercontrol


Declare this:

public event EventHandler FileUploaded;


In some of click event of usercontrol

// Fire public event.
FileUploaded(this.FileResourceId, e);




On .aspx page


On the page load

writes instance to know usercontrol first:

WRVS.Website.V1.WebApplication.Admin.inc.usercontrols.FileUploader uFileUploader =
(WRVS.Website.V1.WebApplication.Admin.inc.usercontrols.FileUploader)
fvContentPage.FindControl("uFileUploader");


if (uFileUploader != null)
{
uFileUploader.FileUploaded += new EventHandler(FileUploaded);
}



Then create event:

private void FileUploaded(object sender, EventArgs e)
{

// logic for page update.
}

Friday, January 28, 2011

session timeout on IIS

Microsoft Windows 2000

1. Start Microsoft Internet Information Services (IIS) Manager.
2. In the Internet Information Services window, expand the ServerName node, where ServerName is the name of the server.
3. Right-click Default Web Site, and then click Properties.
4. In the Default Web Site Properties dialog box, on the Home Directory tab, click Configuration.
5. In the Application Configuration dialog box, on the Options tab, the session timeout box displays the Session.Timeout value.

Back to the top
Microsoft Windows Server 2003

1. Start Internet Information Services Manager, or open the IIS snap-in.
2. In the Internet Information Services window, expand the ServerName node, where ServerName is the name of the server.
3. Expand the Web Sites node.
4. Right-click Default Web Site, and then click Properties.
5. In the Default Web Site Properties dialog box, on the Home Directory tab, click Configuration.
6. In the Application Configuration dialog box, on the Options tab, the session timeout box displays the Session.Timeout value.


To configure session timeout

You can perform this procedure by using the user interface (UI), by running Appcmd.exe commands in a command-line window, by editing configuration files directly, or by writing WMI scripts.
User Interface
To Use the UI

1.

Open IIS Manager and navigate to the level you want to manage. For information about opening IIS Manager, see Open IIS Manager (IIS 7). For information about navigating to locations in the UI, see Navigation in IIS Manager (IIS 7).
2.

In Features View, double-click ASP.
3.

On the ASP page, under Services, expand Session Properties.
4.

In the Time-out field, enter a time-out value in the format hh:mm:ss. For example, enter 00:15:00 for 15 minutes.
5.

In the Actions pane, click Apply.

Wednesday, January 26, 2011

Google language tool in website.

The is the google language tool for the website. All you need to do is just add this code to your site.



Monday, January 24, 2011

Different betwwen public, private, protected

What is the different between public, private, protected....


public
The type or member can be accessed by any other code in the same assembly or another assembly that references it.

private
The type or member can only be accessed by code in the same class or struct.

protected
The type or member can only be accessed by code in the same class or struct, or in a derived class.

internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal
The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.

Static
The static modifier on a class means that the class cannot be instantiated, and that all of its members are static. A static member has one version regardless of how many instances of its enclosing type are created.

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself.

Thursday, January 20, 2011

Abstract class (c#)

When you gone a interview, most of interviewer interest to ask different between abstract and class.

The answer is simple.

The abstract modifier can be used with classes, methods, properties, indexers, and events.
* An abstract class cannot be instantiated.
* An abstract class may contain abstract methods and accessors.
* It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited.
* A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.