Thursday, October 1, 2009

Ajax Style File Upload

Hello Friends,
I need to implement file upload functionality using ajax. So after doing some RND on it then I will come with solutions.

Here I post live sample of ajax style file upload.

ASPX File:-uploadtest.aspx


   1:  <%@ Page Language="C#" AutoEventWireup="true" CodeFile="uploadtest.aspx.cs" Inherits="uploadtest" %>

   2:   

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

   4:  <html xmlns="http://www.w3.org/1999/xhtml">

   5:  <head runat="server">

   6:      <title></title>

   7:   

   8:      <script language="javascript" type="text/javascript">

   9:         

  10:          function onerror(args, context) {

  11:              document.getElementById("<%=message.ClientID %>").innerHTML = "Upload Failed";

  12:          }

  13:          function results(args, context) {

  14:              document.getElementById("<%=message.ClientID %>").innerHTML = "File has been uploaded successfully";

  15:          }

  16:          function Button1_onclick() {        

  17:              arguments = document.getElementById("path").value + "/" + document.getElementById("File1").value;            

  18:              <%= cbref %>

  19:          }

  20:      </script>

  21:  </head>

  22:  <body>

  23:      <form id="form1" runat="server">

  24:      <div>

  25:          <input type="text" id="path" value="" />

  26:          <input id="File1" type="file" />

  27:          <input id="Button1" type="button" value="upload" onclick="return Button1_onclick()" />

  28:      </div>

  29:      <span id="message" runat="server"></span>

  30:      <script language="javascript" type="text/javascript">

  31:          document.getElementById("<%=message.ClientID %>").innerHTML = "";

  32:      </script>

  33:      </form>

  34:  </body>

  35:  </html>



CS File:-uploadtest.aspx.cs


   1:  using System;

   2:  using System.Collections.Generic;

   3:  using System.Linq;

   4:  using System.Web;

   5:  using System.Web.UI;

   6:  using System.Web.UI.WebControls;

   7:  using System.Web.UI.HtmlControls;

   8:  using System.Net;

   9:   

  10:  public partial class uploadtest : System.Web.UI.Page, ICallbackEventHandler

  11:  {

  12:      protected string cbref = string.Empty;

  13:      protected void Page_Load(object sender, EventArgs e)

  14:      {

  15:   

  16:          ClientScriptManager csm = Page.ClientScript;

  17:          cbref = csm.GetCallbackEventReference(this, "arguments", "results", null, "onerror", true);

  18:      }

  19:   

  20:   

  21:      #region ICallbackEventHandler Members

  22:   

  23:      public string GetCallbackResult()

  24:      {

  25:          return cbref;

  26:      }

  27:   

  28:      public void RaiseCallbackEvent(string eventArgument)

  29:      {

  30:          System.Net.WebClient wc = new System.Net.WebClient();

  31:          wc.UploadFile("http://localhost:2830/Amadeus/uploadfile.aspx", "POST", eventArgument);

  32:      }

  33:   

  34:      #endregion

  35:  }



Now here is an uploadfile.aspx.cs where file upload start.


   1:  using System;

   2:  using System.Collections.Generic;

   3:  using System.Linq;

   4:  using System.Web;

   5:  using System.Web.UI;

   6:  using System.Web.UI.WebControls;

   7:  using System.Web.UI.HtmlControls;

   8:   

   9:  public partial class uploadfile : System.Web.UI.Page

  10:  {

  11:      protected void Page_Load(object sender, EventArgs e)

  12:      {

  13:          HttpPostedFile myfile = Request.Files[0];

  14:          string path = Server.MapPath("~/upload");

  15:          if (!System.IO.Directory.Exists(path))

  16:          {

  17:              System.IO.Directory.CreateDirectory(path);

  18:          }

  19:          string filename = myfile.FileName;

  20:          string fullpath = System.IO.Path.Combine(path, filename);

  21:          myfile.SaveAs(fullpath);

  22:      }

  23:  }



I hopes this will help you :)
Happy Programming...!

Reference : - http://www.dotnetfunda.com/articles/article484-ajax-style-fileupload.aspx

Regards,
Kinjal Shah

Wednesday, September 23, 2009

Create Custom control

Hello frnds,
I think most of people who need to make textbox value as a mandatory then they are use required field validator in each page. But at my point of view this is not good and so that I came with proper solution. I have create on class file in which I inherited textbox web server control and made that textbox control value with mandatory.

Here I post sample example of it and I hopes it will help you also.

Class File : TextControl.CS
Whenever you add any class file then it will prompt you to add app_code folder. So for that click on no.


   1:  using System;

   2:  using System.Collections.Generic;

   3:  using System.Linq;

   4:  using System.Web;

   5:  using System.Web.UI.WebControls;

   6:  /// <summary>

   7:  /// Summary description for TextControl

   8:  /// </summary>

   9:  /// 

  10:   

  11:   

  12:  namespace ControlValidator

  13:  {

  14:      

  15:      public class TextControl:TextBox 

  16:      {

  17:          public bool Required { get; set; }

  18:          public string ErrorMessage { get; set; }

  19:          

  20:          private RequiredFieldValidator RequiredFieldValidator;

  21:          protected override void OnInit(EventArgs e)

  22:          {

  23:              if (this.Required)

  24:              {                

  25:                  RequiredFieldValidator = new RequiredFieldValidator();

  26:                  RequiredFieldValidator.ControlToValidate = this.ID;

  27:                  RequiredFieldValidator.ErrorMessage = this.ErrorMessage;

  28:                  Controls.Add(RequiredFieldValidator);

  29:              }

  30:          }

  31:   

  32:          protected override void Render(System.Web.UI.HtmlTextWriter writer)

  33:          {

  34:              base.Render(writer);

  35:              if (this.Required)

  36:              {

  37:                  RequiredFieldValidator.RenderControl(writer);

  38:              }

  39:          }

  40:      }

  41:      

  42:      

  43:  }






After that u need to create dll file for this class file using following command.
I hopes you current prompt is you working webapp path.

C:\Documents and Settings\kinjal.SOLUTIONS.000\My Documents\Downloads\MyCustomControls\MyCustomControls>
csc /out:bin\ControlValidator.dll /target:library /r:system.dll TextControl.cs

After that you add default.aspx file
File Name : Default.aspx


   1:  <%@ Register Namespace="ControlValidator" Assembly="ControlValidator" TagPrefix="Control" %>

   2:   

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

   4:   

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

   6:  <html xmlns="http://www.w3.org/1999/xhtml">

   7:  <head runat="server">

   8:      <title></title>

   9:  </head>

  10:  <body>

  11:      <form id="form1" runat="server">

  12:      <div>

  13:          <Control:TextControl runat="server" ID="txtName" Required="true" ErrorMessage="Name Is Required"></Control:TextControl>

  14:          <br />

  15:          <asp:Button ID="btnOk" runat="server" Text="Click me" />

  16:      </div>

  17:      </form>

  18:  </body>

  19:  </html>





Happy Programming and coding...!

Sunday, September 13, 2009

Date Calculation

Please ignore this post due to not proper format and proper instruction.


using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
public partial class _Default : System.Web.UI.Page
{
List<string> ListDay = new List<string>();
List<string> ListMonth = new List<string>();


List<ShowDate> ListDate = new List<ShowDate>();

string[] dayArr = { "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" };
string[] monthArr = { "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december" };

Hashtable HTWeekDay = new Hashtable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DateTime DT = DateTime.Now;
DT = GetFirstDateOfWeek(DT);

System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;


object index = DateTime.Now;
string r = String.Format("ww", index);
int res = getPreviousWeekNumber(index);

//0 First day of year
res = System.Globalization.CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
Convert.ToDateTime(index), System.Globalization.CalendarWeekRule.FirstDay, System.Globalization.DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek);

res = System.Globalization.CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
Convert.ToDateTime(index), System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
DateTime curMonth = Convert.ToDateTime(DateTime.Today.Year.ToString() + "-09-07");
//Calendar1.VisibleDate = curMonth;
Response.Write(getISOWeek(curMonth).ToString());

int week = ci.Calendar.GetWeekOfYear(DateTime.Now , ci.DateTimeFormat.CalendarWeekRule, ci.DateTimeFormat.FirstDayOfWeek);

//Convert.ToDateTime(index), System.Globalization.CalendarWeekRule.FirstDay, System.Globalization.DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek);

HTWeekDay.Add("FirstWeekDay", "1");
HTWeekDay.Add("SecondWeekDay", "2");
HTWeekDay.Add("ThirdWeekDay", "3");
HTWeekDay.Add("FourthWeekDay", "4");
foreach (string day in dayArr)
{
ListDay.Add(day);
}

foreach (string month in monthArr)
{
ListMonth.Add(month);
}

// foreach (string weekday in weekArr)
// {
// ListWeekDay.Add(weekday);
// }
drpDay.DataSource = ListDay;
drpDay.DataBind();
drpDay.Items.Insert(0, new ListItem("ALL", "0"));
drpMonth.DataSource = ListMonth;
drpMonth.DataBind();
drpMonth.Items.Insert(0, new ListItem("ALL", "0"));
drpDay.SelectedValue = "0";
drpMonth.SelectedValue = "0";

drpWeekDay.DataSource = HTWeekDay;
drpWeekDay.DataTextField = "key";
drpWeekDay.DataValueField = "value";
drpWeekDay.DataBind();
drpWeekDay.Items.Insert(0, new ListItem("ALL", "0"));
drpWeekDay.SelectedValue = "0";

}
}
protected void btnClick_Click(object sender, EventArgs e)
{
DateTime FromDt = CalFromDt.SelectedDate;
//Response.Write((CalToDt.SelectedDate-FromDt).Days);
string day = string.Empty;
string month = string.Empty;
while ((CalToDt.SelectedDate - FromDt).Days >= 0)
{
day = FromDt.DayOfWeek.ToString().ToLower();
month = FromDt.ToString("MMMM").ToLower();
if (!drpDay.SelectedValue.Equals("0"))
{
if (!drpMonth.SelectedValue.Equals("0"))
{
if (month.Equals(drpMonth.SelectedValue) && day.Equals(drpDay.SelectedValue))
{
ShowDateBasedonsingleCriteria(FromDt);
}
}
else if (day.Equals(drpDay.SelectedValue))
{
ShowDateBasedonsingleCriteria(FromDt);
}
}
else if (!drpMonth.SelectedValue.Equals("0"))
{
if (month.Equals(drpMonth.SelectedValue))
{
ShowDateBasedonsingleCriteria(FromDt);
}
}
else if (!drpWeekDay.SelectedValue.Equals("0"))
{
int weekday = System.Globalization.CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(FromDt, CalendarWeekRule.FirstDay, System.Globalization.DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek);
if (weekday == 0) { weekday = 5; }
Math.DivRem(weekday, 5, out weekday);
if (weekday.ToString().Equals(drpWeekDay.SelectedValue))
{
ShowDateBasedonsingleCriteria(FromDt);
}
}
else
{
ShowDateBasedonsingleCriteria(FromDt);
}

FromDt = FromDt.AddDays(1);
}
gv.DataSource = ListDate;
gv.DataBind();
//lblDiff.Text = (CalToDt.SelectedDate - CalFromDt.SelectedDate).ToString();

}

private void ShowDateBasedonsingleCriteria(DateTime FromDt)
{
ShowDate objshowdate = new ShowDate();
objshowdate.rownumber = 1;
objshowdate.date = FromDt.ToString("dd/MM/yyyy");
ListDate.Add(objshowdate);
}

private int getPreviousWeekNumber(Object Date)
{
DateTime dtSend;
try
{
dtSend = Convert.ToDateTime(Date);
}
catch (Exception)
{
throw new Exception("Please give Valid Date");
}
object dtLastWeek = dtSend.AddDays(-7); // Am adding -7 Days because it exactly a 7 Days back from to Day

return System.Globalization.CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
Convert.ToDateTime(dtLastWeek), System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Sunday);
}




public class ShowDate
{
public int rownumber { get; set; }
public string date { get; set; }
}

public static DateTime GetFirstDateOfWeek(DateTime dayInWeek)
{

CultureInfo defaultCultureInfo = CultureInfo.CurrentCulture;

return GetFirstDateOfWeek(dayInWeek, defaultCultureInfo);

}

public static DateTime GetFirstDateOfWeek(DateTime dayInWeek, CultureInfo cultureInfo)
{

DayOfWeek firstDay = cultureInfo.DateTimeFormat.FirstDayOfWeek;

DateTime firstDateInWeek = dayInWeek.Date;

while (firstDateInWeek.DayOfWeek != firstDay)

firstDateInWeek = firstDateInWeek.AddDays(-1);

return firstDateInWeek;

}

public int getISOWeek(DateTime day)
{
return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(day, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}

}