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.

ASP.NET Page Life Cycle Overview

Asp.net have 7 stages of page life cycle. They are:

Page request
The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.

Start

In the start stage, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. The page also sets the UICulture property.

Initialization

During page initialization, controls on the page are available and each control's UniqueID property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

Load
During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

Postback event handling

If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.

Rendering

Before rendering, view state is saved for the page and all controls. During the rendering stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page's Response property.

Unload

The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and cleanup is performed.

interface (C# Reference)

An interface contains only the signatures of methods, delegates or events.

code example of Interface

interface ISampleInterface
{
void SampleMethod();
}

class ImplementationClass : ISampleInterface
{
// Explicit interface member implementation:
void ISampleInterface.SampleMethod()
{
// Method implementation.
}

static void Main()
{
// Declare an interface instance.
ISampleInterface obj = new ImplementationClass();

// Call the member.
obj.SampleMethod();
}
}

System.Collection namespace in C#


.Net Collection class


The System.Collections namespace contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hash tables and dictionaries.


.Net Collection.Generic class



  • Use generic types to maximize code reuse, type safety, and performance.

  • The most common use of generics is to create collection classes.

  • The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible instead of classes such as ArrayList in the System.Collections namespace.

  • You can create your own generic interfaces, classes, methods, events and delegates.

  • Generic classes may be constrained to enable access to methods on particular data types.

  • Information on the types that are used in a generic data type may be obtained at run-time by using reflection.

Wednesday, January 19, 2011

Question

Here is the question i like to put. if you guys like to reply to this, I am more than welcome.

.net collection class

class and abstract

generic object

object and class

list and hash table

Report CSV download

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


namespace
{
public partial class CompetitionsList : System.Web.UI.Page
{
tCompetitionsTableAdapter taCompetition = new tCompetitionsTableAdapter();
tCompetitionEntriesTableAdapter adCompetitionEntries = new tCompetitionEntriesTableAdapter();
tCompetitionOpenEntriesTableAdapter adOpenCompetitionEntries = new tCompetitionOpenEntriesTableAdapter();

protected void Page_Load(object sender, EventArgs e)
{
Master.AppendCssClassToContainerDiv("page-competitionsManagement");
}

protected void rptCompetitions_ItemCommand(object source, RepeaterCommandEventArgs e)
{
switch (e.CommandName.ToLowerInvariant())
{
case "download":
StringBuilder sbCSV = new StringBuilder();
sbCSV.AppendLine("Title, First Name, Last Name, Baby First Name, Baby Age, Email Address, Postcode, Address, Address Ln2, Address Ln3, Town, County, Country");

CompetitionsEntity.tCompetitionsDataTable dtCompetition = taCompetition.GetData(int.Parse(e.CommandArgument.ToString()));

if (dtCompetition.Count > 0)
{
if (((CompetitionsEntity.tCompetitionsRow)dtCompetition.Rows[0]).IsBabyClub == true)
{
CompetitionsEntity.tCompetitionEntriesDataTable privateEntries = adCompetitionEntries.GetDataByCompetitionId(int.Parse(e.CommandArgument.ToString()));

foreach (CompetitionsEntity.tCompetitionEntriesRow trCompetitions in privateEntries.Rows)
{

sbCSV.Append(trCompetitions.IsTitleNull() ? "" : trCompetitions.Title);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsYourFirstNameNull() ? "" : trCompetitions.YourFirstName);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsYourLastNameNull() ? "" : trCompetitions.YourLastName);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsYourBabyFirstNameNull() ? "" : trCompetitions.YourBabyFirstName);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsYourBabyAgeNull() ? 0 : trCompetitions.YourBabyAge);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsEmailAddressNull() ? "" : trCompetitions.EmailAddress);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsPostcodeNull() ? "" : trCompetitions.Postcode);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsAddressNull() ? "" : trCompetitions.Address);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsAddress2Null() ? "" : trCompetitions.Address2);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsAddress3Null() ? "" : trCompetitions.Address3);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsTownNull() ? "" : trCompetitions.Town);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsCountyNull() ? "" : trCompetitions.County);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsCountryNull() ? "" : trCompetitions.Country);
sbCSV.AppendLine();
}
}
else if (((CompetitionsEntity.tCompetitionsRow)dtCompetition.Rows[0]).IsBabyClub == false)
{
CompetitionsEntity.tCompetitionOpenEntriesDataTable publicEntries = adOpenCompetitionEntries.GetDataByCompetitionId(int.Parse(e.CommandArgument.ToString()));

foreach (CompetitionsEntity.tCompetitionOpenEntriesRow trCompetitions in publicEntries.Rows)
{

sbCSV.Append(trCompetitions.IsTitleNull() ? "" : trCompetitions.Title);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsYourFirstNameNull() ? "" : trCompetitions.YourFirstName);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsYourLastNameNull() ? "" : trCompetitions.YourLastName);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsYourBabyFirstNameNull() ? "" : trCompetitions.YourBabyFirstName);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsYourBabyAgeNull() ? 0 : trCompetitions.YourBabyAge);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsEmailAddressNull() ? "" : trCompetitions.EmailAddress);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsPostcodeNull() ? "" : trCompetitions.Postcode);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsAddressNull() ? "" : trCompetitions.Address);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsAddress2Null() ? "" : trCompetitions.Address2);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsAddress3Null() ? "" : trCompetitions.Address3);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.Town);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsCountyNull() ? "" : trCompetitions.County);
sbCSV.Append(",");
sbCSV.Append(trCompetitions.IsCountryNull() ? "" : trCompetitions.Country);
sbCSV.AppendLine();
}
}

Response.Clear();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=HCP_CompetitionData_" + DateTime.Now.ToString("yyyyMMddmmss") + ".csv");
Response.Write(sbCSV.ToString());
Response.End();
}

break;
}

rptCompetitions.DataBind();
}


}
}

Tuesday, January 11, 2011

1.5 Million Windows Phone 7 Devices Shipped!

that 1.5 million Windows Phone 7 devices were shipped by manufacturers within the first six weeks. We also learn that there are 18,000 developers actively developing applications and that the marketplace today has 4,000 applications with more coming each day.

I found some video adv on youtube.com about HTC HD7 window 7 phone. It is really cool.

Wednesday, January 5, 2011

Another T-SQL Update query with Inner Join

This is a T-SQL Update statement with Inner Join statement. That's really useful.
Datetime is comparison a bit tricky.

DECLARE @p_date DATETIME
DECLARE @L_date DATETIME
SET @p_date = CONVERT( DATETIME, '21 Dec 2010', 106)
SET @L_date = CONVERT( DATETIME, '5 Jan 2011', 106)

UPDATE [PrideAngel].[dbo].[tProfile]
SET [MessageCredits] = (tp.[MessageCredits] + '5' )
FROM [PrideAngel].[dbo].[tProfile] tp Inner join
[PrideAngel].[dbo].[aspnet_Membership] tm
ON tm.[UserId] = tp.UserId
Where tm.[LastLoginDate] >= @p_date and tm.[LastLoginDate] <= @L_date

SQL Date time compare in Where clause

DECLARE @p_date DATETIME
SET @p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )

SELECT *
FROM table1
WHERE column_datetime >= @p_date
AND column_datetime < DATEADD(d, 1, @p_date)

The advantage of this is that it will use any index on 'column_datetime' is it exists.

C# asp.net Repeater Paging

This is c# asp.net repeater paging. You can have two paging on one page. and including synchronizing each other.


Paging.aspx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ProjectInspiration.ascx.cs"
Inherits="UserControls_ProjectInspiration" %>





Show projects by product type


Find a project by product:





Dsiplaying <%= GetCurrentPageNumber() %> of <%= GetProjectListCount() %> projects











>Previous


><%# Container.DataItem %>




Next
















>Previous


><%# Container.DataItem %>




Next







Paging.aspx.cs

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CMS_Library.ProjectManagement;
using CMS_Library.PageManagment;
using System.Data;
using System.Reflection;
using System.ComponentModel;
using System.Collections;
using CMS_Library.ProductManagement;
using CMS_Library.ProjectManagement.ProjectProductTypeEntityTableAdapters;
using CMS_Library;
using System.Configuration;

public partial class UserControls_ProjectInspiration : System.Web.UI.UserControl
{
private Project CurrentProject = new Project();
private ProjectImage CurrentProjectImage = new ProjectImage();
private tProjectProductTypeTableAdapter TaProjectProductType = new tProjectProductTypeTableAdapter();
private int projectProductTypeId = 0;
private int pagingSize = CMS_Library.Helpers.ConfigHelper.PagingSize;
private int projectTableCount = 0;

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadData();
BindProductType();
}
}

public int PageNumber
{
get
{
if (ViewState["PageNumber"] != null)
return Convert.ToInt32(ViewState["PageNumber"]);
else
return 0;
}
set
{
ViewState["PageNumber"] = value;
}
}

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
rptPages.ItemCommand += new RepeaterCommandEventHandler(rptPages_ItemCommand);
rptPagingTop.ItemCommand += new RepeaterCommandEventHandler(rptPagingTop_ItemCommand);
}

protected void rptPages_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandArgument != "")
{
PageNumber = Convert.ToInt32(e.CommandArgument) - 1;
LoadData();
}
}

protected void rptPagingTop_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandArgument != "")
{
PageNumber = Convert.ToInt32(e.CommandArgument) - 1;
LoadData();
}
}

public void rptPages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("btnPage");
if (lnkbtnPage.CommandArgument.ToString() == (PageNumber + 1).ToString())
{
lnkbtnPage.Enabled = false;
lnkbtnPage.Style.Add("font-size", "12px");
lnkbtnPage.Font.Bold = true;
}
}
}

public void rptPageingTop_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("btnPage");
if (lnkbtnPage.CommandArgument.ToString() == (PageNumber + 1).ToString())
{
lnkbtnPage.Enabled = false;
lnkbtnPage.Style.Add("font-size", "12px");
lnkbtnPage.Font.Bold = true;
}
}
}

public string GetProjectImageUrl(int projectId)
{
//Project image
CurrentProjectImage = ProjectImage.GetProjectImagesByProjectId(projectId);
string sProjectImageUrl = "";
if (CurrentProjectImage.ThumbURL != "" && CurrentProjectImage.ThumbURL != null)
{
sProjectImageUrl = CurrentProjectImage.ThumbURL;
}
return sProjectImageUrl;
}

public string GetVariantsByProjectId(int projectId)
{
// Project Products
CurrentProject.GetVariants(projectId);
string sProduct = "";
foreach (Variant var in CurrentProject.Variants)
{
var.GetProduct();
if (var.Product != null)
{
//if (sProduct != string.Empty) { sProduct += " /"; }
sProduct += " GA " + var.Code + "";
}
}
return sProduct;
}

private void LoadData()
{
// Access Base Page Class
PageManager _PageManeger = (PageManager)this.Page;
List projects = new List();

if (projectProductTypeId > 0)
{
projects = Project.GetPageProjects(_PageManeger._Page.PageId, projectProductTypeId, true);
}
else
{
projects = Project.GetPageProjects(_PageManeger._Page.PageId, true);
}


DataTable dt = ToDataTable(projects);
projectTableCount = dt.Rows.Count;

PagedDataSource pgItems = new PagedDataSource();
DataView dv = new DataView(dt);

pgItems.DataSource = dv;
pgItems.AllowPaging = true;
//pgItems.PageSize = 5;
pgItems.PageSize = pagingSize;
pgItems.CurrentPageIndex = PageNumber;

if (pgItems.PageCount > 1)
{
rptProjects.Visible = true;
ArrayList pages = new ArrayList();
for (int i = 0; i < pgItems.PageCount; i++)
{
pages.Add((i + 1).ToString());
rptPages.DataSource = pages;
rptPages.DataBind();

// Bind data to top paging.
rptPagingTop.DataSource = pages;
rptPagingTop.DataBind();
}

rptPages.Visible = true;
rptPagingTop.Visible = true;
}
else
{
rptPages.Visible = false;
rptPagingTop.Visible = false;
}
rptProjects.DataSource = pgItems;
rptProjects.DataBind();

}

protected void btnNext_Click(Object sender, EventArgs e)
{
if (PageNumber < rptPages.Items.Count - 1)
{
PageNumber++;
LoadData();
}
}

protected void btnPrevious_Click(Object sender, EventArgs e)
{
if (PageNumber > 0)
{
PageNumber--;
LoadData();
}
}

// Convert generic list to data table.
private static DataTable ToDataTable(IList data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));

DataTable dt = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
dt.Columns.Add(prop.Name, prop.PropertyType);
}

object[] values = new object[props.Count];
foreach (T _pro in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(_pro);
}
dt.Rows.Add(values);
}
return dt;
}

protected void btnSearch_Click(Object sender, EventArgs e)
{
projectProductTypeId = int.Parse(ddlProductType.SelectedValue);
LoadData();
}

// Bind Project product type to dropdownlist
private void BindProductType()
{
ProjectProductTypeEntity.tProjectProductTypeDataTable dt =
TaProjectProductType.GetData();

if (dt.Rows.Count > 0)
{
ddlProductType.DataSource = dt;
ddlProductType.DataValueField = "ProjectProductTypeId";
ddlProductType.DataTextField = "Name";
ddlProductType.DataBind();

ddlProductType.Items.Insert(0, new ListItem ("Choose product type", "0"));
}
}

// Get current page number
public string GetCurrentPageNumber()
{
string strCurrentPageNumber = "";

if (PageNumber > 0)
{
strCurrentPageNumber = ((PageNumber * pagingSize) + 1) + "-" + ((PageNumber + 1) * pagingSize);
}
else
{
strCurrentPageNumber = (PageNumber + 1) + "-" + ((PageNumber + 1) * pagingSize);
}

return strCurrentPageNumber;

}

public string GetProjectListCount()
{
string strProjectListCount = "";

strProjectListCount = projectTableCount.ToString();

return strProjectListCount;
}

}





Date time how to get last month or previous month.

This is good example of datetime how to get last month.




DateTime LastMonthDate=DateTime.Now.AddMonths(-1);
Response.Write(LastMonthDate.ToString("MM/dd/yyyy"));

DateTime.Now.AddMonths(-1).ToString("MM/dd/yyyy")

Monday, January 3, 2011

Fckeditor Toolbar definition

Toolbar definition

A toolbar definition is a JavaScript array that contains the elements to be displayed in all "toolbar rows" available in the editor. There are two ways to set the desired toolbar definition in the editor. It can be set directly into the "toolbar" setting, or it can instead be set to a configuration named "toolbar_", where "" is a name that can be used to identify the toolbar in the "toolbar" setting. The following is the default setting we have in the editor.

config.toolbar = 'Full';

config.toolbar_Full =
[
['Source','-','Save','NewPage','Preview','-','Templates'],
['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'],
['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'],
['BidiLtr', 'BidiRtl'],
'/',
['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','CreateDiv'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
['Link','Unlink','Anchor'],
['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
'/',
['Styles','Format','Font','FontSize'],
['TextColor','BGColor'],
['Maximize', 'ShowBlocks','-','About']
];

config.toolbar_Basic =
[
['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink','-','About']
];

Note that two toolbar definitions have been defined, one named "Full" and the other "Basic". The "Full" definition has been set to be used in the toolbar setting.
Toolbar Bands

Every toolbar definition is composed of a series of "toolbar bands" that are grouped in the final toolbar layout. The bands items move together on new rows when resizing the editor.

As you can see in the above definitions, every toolbar band is defined as a separated JavaScript array of strings. Every string indicates toolbar item to be used. Toolbar items are defined by plugins.

You can also include a separator in the toolbar band by including the dash ("-") character on it.
Forcing Row Break

Looking at the "Full" definition you will note some slash ("/") characters between toolbar bands. This slash can be used to force a break at that point, having the next band to be rendered in a new row and not following the previous one.
Customizing the toolbar

A simple way to configure all editors toolbar is by simply adding a custom toolbar definition inside the config.js file, or even better in a separated configuration file (see "Setting Configurations"). The easiest way for that is by simply copying the above "Full" toolbar definition, and strip it down to your needs. For example, the following is a good recommended toolbar definition to have in the config.js file:

CKEDITOR.editorConfig = function( config )
{
config.toolbar = 'MyToolbar';

config.toolbar_MyToolbar =
[
['NewPage','Preview'],
['Cut','Copy','Paste','PasteText','PasteFromWord','-','Scayt'],
['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
'/',
['Styles','Format'],
['Bold','Italic','Strike'],
['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
['Link','Unlink','Anchor'],
['Maximize','-','About']
];
};

You can create as many toolbar definitions as you want inside the configuration file. Later, based on some criteria, you can decide the toolbar to use for each editor instance. For example, with the following code, two editors are created in the page, each one using a different toolbar:

CKEDITOR.replace( 'editor1',
{
toolbar : 'MyToolbar'
});

CKEDITOR.replace( 'editor2',
{
toolbar : 'Basic'
});

It's also possible to set the toolbar definition in-page, when creating the editor instance directly. In that case, just assign it to the toolbar setting directly, for example:

CKEDITOR.replace( 'editor1',
{
toolbar :
[
['Styles', 'Format'],
['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', '-', 'About']
]
});

Sunday, January 2, 2011

Login failed for user IIS APPPOOL\DefaultAppPool

For default on IIS 7.5, ApplicationPoolIdentity at process model identity.

If you change it as following image, all the problems will be fixed.