joomla visitors
Mithila Software Blog | Asp.Net

Getting the number of days in a selected month using Calender control

December 22, 2014 Posted by Himanshu
By Himanshu Jha Select month and calculate all days of this month To get the solution to this problem we will use Drag and drop one calender control and name it Calender1 and one Label control name it Label1 to display the result from the calender control. We attach and event handler in Page_Load event named   Calendar1.VisibleMonthChanged += Calendar1_VisibleMonthChanged; This is because we need to displays days in a month as soon the calender control's forward or backward button is pressed. The days in a month processing will be handled in this funtion void Calendar1_VisibleMonthChanged(object sender, MonthChangedEventArgs e) Now lets get on to the codebehind that we need to understand       Insert code here...protected void Page_Load(object sender, EventArgs e) { Calendar1.VisibleMonthChanged += Calendar1_VisibleMonthChanged; } void Calendar1_VisibleMonthChanged(object sender, MonthChangedEventArgs e) { int months = Calendar1.VisibleDate.Date.Month; int days = calaculatedaysinamonth(months); Label1.Text = string.Format("The selected month has {0} days",days.ToString()); } public int calaculatedaysinamonth(int m) { int tdays = 0; if (m == 1) { tdays = 31; return tdays; } else if (m == 2) { int curryear = Calendar1.VisibleDate.Year; bool varResult = DateTime.IsLeapYear(curryear); if (varResult.Equals(true)) { tdays = 29; return tdays; } else { tdays = 28; return tdays; } return tdays; } else if (m == 3) { tdays = 31; return tdays; } else if (m == 4) { tdays = 30; return tdays; } else if (m == 5) { tdays = 31; return tdays; } else if (m == 6) { tdays = 30; return tdays; } else if (m == 7) { tdays = 31; return tdays; } else if (m == 8) { tdays = 31; return tdays; } else if (m == 9) { tdays = 30; return tdays; } else if (m == 10) { tdays = 31; return tdays; } else if (m == 11) { tdays = 30; return tdays; } else if (m == 12) { tdays = 31; return tdays; } return tdays; }

How to download an image directly to the disk in asp.net

April 01, 2013 Posted by Mithila Software
With just a couple line of codes you can download an image from internet onto your pc with the asp.net code below. if(Directory.Exists(@"c:\localpath")) { localFilename = @"c:\localpath\tofile.jpg"; } else { Directory.CreateDirectory(@"c:\localpath"); localFilename = @"c:\localpath\tofile.jpg"; } using (WebClient client = new WebClient()) { client.DownloadFile(http://cs316628.userapi.com/v316628767/56f7/FqFPYSd-0fg.jpg, localFilename); } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; white-space: normal; } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } The above code requires two references System.IO and System.Net

Tags:

Asp.Net

Calculating age in years and months in asp.net c#

January 08, 2013 Posted by Mithila Software
There may be many occasions when you need to output the current age of a user in your database with respect to the current date and time especially in profile of user in content management system or for any other purpose.You can use the c# method below to carry out this error prone task with accuracy and ease. Take a look at how this works. This is the method - public string agecalculate(string date) { DateTime today = DateTime.Today; DateTime bdate = Convert.ToDateTime(date);   System.Collections.ArrayList arr = new System.Collections.ArrayList(); arr = span(today, bdate);   return arr[0].ToString() + " years " + arr[1].ToString() + " months";   } public string ageyears(string date) { DateTime today = DateTime.Today; DateTime bdate = Convert.ToDateTime(date);   System.Collections.ArrayList arr = new System.Collections.ArrayList(); arr = span(today, bdate);   return arr[0].ToString();   }   public System.Collections.ArrayList span(DateTime f, DateTime l) { int days; int months; int years;   int fird = f.Day; int lasd = l.Day;   int firm = f.Month; int lasm = l.Month;   if (fird >= lasd) { days = fird - lasd; if (firm >= lasm) { months = firm - lasm; years = f.Year - l.Year; } else { months = (firm + 12) - lasm; years = f.AddYears(-1).Year - l.Year; } } else { days = (fird + 30) - lasd; if ((firm - 1) >= lasm) { months = (firm - 1) - lasm; years = f.Year - l.Year; } else { months = (firm - 1 + 12) - lasm; years = f.AddYears(-1).Year - l.Year; } }   if (days < 0) { days = 0 - days; } if (months < 0) { months = 0 - months; } System.Collections.ArrayList ar = new System.Collections.ArrayList(); ar.Add(years.ToString()); ar.Add(months.ToString()); ar.Add(days.ToString()); return ar; } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   How to call this method - Response.Write(agecalculate("10/10/1986")); .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   Easy ! Isn’t it ?

Tags:

Asp.Net

Creating unique Image Names for uploaded files in asp.net

November 27, 2012 Posted by Mithila Software
While programming a multiuser application in asp.net , for example a social sharing site like - video sharing , photo sharing , social network or so..There is a provision where members can upload their images. Let us explore popular approaches to prevent images name clash or preventing images from over writing when two members of your site upload image bearing same name and type.   Approach # 1 Saving Image names with GUID value 1.Images are saved with GUID name that is - people upload their images from their end having a name xx.jpg , and your program saves it as <generated guid>.jpg The code for unique image name is generated like below string uploaded_image_unique_name = string.Concat(Guid.NewGuid().ToString(),".jpg");   The benefit of this approach is that every time a 100% pure unique name is generated Ex - 7f94c135-931c-49a1-b19b-f68fad85d586.jpg   However , the downside is that when we open the image folder when we are storing all these images we come across images files of the site members bearing this cryptic name.And we have no clue whose image it is until we open it. Apart from that consider our images below again - 1.7f94c135-931c-49a1-b19b-f68fad85d586.jpg (Our Image) 2.HSJ_in_friends_party.jpg  (User's Originally uploaded image ) Clearly you can see that image at #2 is more meaningful and so when search engines are ranking the images especially Google Images  they place you better in rank for Image No 2 .   Approach # 2 Saving Image with original Image name but appended with GUID Programmers Place uploaded images inside user's own directory coz username is unique.So it goes like this 1.HSJ creates an account on x.com with unique username HSJ 2.The website creates a folder for HSJ. 3.When HSJ uploads an image file to his profile for say hsj.jpg the program saves it as hsj-<GUID>.jpg to HSJ folder. This approach is also good but it can create thousands of directories on server if site becomes very popular.   Approach # 3 Saving Image after checking for duplicate one   In this approach we loop through the upload directory for any duplicate record and if found we append the loop no to that file.Check the example below -   const string ImageDirectory = "~/Uploads/"; string ImagePath = ImageDirectory + FileUpload1.FileName; string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(FileUpload1.FileName); int count = 1; while (System.IO.File.Exists(Server.MapPath(ImagePath))) { ImagePath = string.Concat(ImageDirectory , fileNameWithoutExtension, "-", iteration, ".jpg"); count++; } FileUpload1.SaveAs(Server.MapPath(ImagePath));     1 First of all we declared the base directory where we are going to store images 2 We combine the path with our uploaded file name and also store our uploaded file name without file extension. 3 Now we loop through the directory for the existence of any already existing same name image file and if we found one we append our ImagePath to our uploaded file name with loop count where we saw the duplicate value. 4Finally we save this new unique image file on server.

Tags:

Asp.Net

Using FCKeditor built-in upload file function in asp.net

November 27, 2012 Posted by Mithila Software
This video explains how you can use and upload feature in asp.net. This fckeditor in the video has been tweaked for enabling upload for asp.net.- Download fckeditor package file

Tags:

Asp.Net

Free swf server control for asp.net developers

November 27, 2012 Posted by Mithila Software
Many a times , asp.net developers , need to use flash (now adobe flash !) as a part of their web projects.The handling of those junk looking flash embed codes becomes awkward so we decided to package those codes in to our very own -  server controls. Its extremely easy to use this swf server controls for asp.net so you may give it a try... Step 1 . Download the asp.net Swf Server control for displaying flash file from here   Download Asp.net swf server control   Step 2. Drop this dll in your Bin folder of the asp.net application.   Step 3. On your asp.net Page below   <%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="myfolders.aspx.cs" Inherits="myfolders" %> // my asp.net swf control declaration <%@ Register Assembly="JCodesSwfControl" Namespace="JCodesSwfControl" TagPrefix="cc1" %> step4) Now drop this piece of tags where you need to display a flash file <cc1:JcodesSWFControl ID="JcodesSWFControl1" runat="server" SWFPath="~/joke.swf" />    The Good thing with this server control is that you can select and change the properties from properties box for Height , Width , SWFPath (dialog box support for file choosing) If you have tried it let us know about the bugs or difficulty..

Tags:

Asp.Net

Creating a Random Alphanumeric String in asp.net

November 27, 2012 Posted by Mithila Software
There are sometimes when we need to create an alphanumeric string in asp.net.The small routine below can help you achieve this. Copy and paste this asp random generator method in your application   public string GetRandomString(int length)     {         Random rnd = new Random();         string charPool         = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";         System.Text.StringBuilder rs = new System.Text.StringBuilder();         while (length-- > 0)             rs.Append(charPool[(int)(rnd.NextDouble() * charPool.Length)]);         return rs.ToString();     } Calling this method from your application. Simple ! Place it anywhere in your codebehind events... Response.Write(GetRandomString(20)); SAMPLE OUTPUT :: IJMG8VQNZ4U7EMBNA0IL Download Demo Random Alphanumeric Generator

Tags:

Asp.Net

Dealing with Validation of viewstate MAC failed error in asp.net

November 27, 2012 Posted by Mithila Software
If you are testing an asp.net application on your newly created sub-domains or subdomains-in-folders then sometimes , you run into a very nasty problem that shows this error description : "Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster." Most of the time the error is solved by this trick Steps : 1. Go to http://aspnetcafe.com/tools/machineKey.aspx and generate a machine key (ASP.NET 2.0 machineKey in our case) 2.Add the machine key generated at the website in your testing web applications web.config's file under <system.web> i.e.   <system.web> <----Generated machine key from the website here---> </system.web> Hope that solves your valuable hours to programming...

Tags:

Asp.Net

Trying out a swiss knife like asp.net email function in asp.net

July 05, 2012 Posted by Mithila Software
Whether you are a seasoned web developer or a newbie you might agree to the point that writing email sending code for clients is one of the most frequently used actions in your life.There may be many applications of the email code , ranging from that very simple contact/query page to the fancy scheduler enabled e-mailers programs.In addition , you may have found email codes interacting with database for record keeping and maintenance.   The purpose of this post is to find a way so that we can design an asp.net email sending code which can handle gmail email accounts as well with minimum coding or such that we can put some credentials and we are able to send an email.   First Step Defining email sending credentials in asp.net constants. say -   public const string _SMTP_Server = "xx.domain.com"; // Our SMTP server provided by the host public const string _SMTP_User = xx@domain.com; public const string _SMTP_Pass = "<pass>"; public const string _Message_Receiving_Email = xx@domain.com; // The address which will receive our email     Constructing Our Generic Email Sending Function   public bool SendMail (string from, string name, string subject, string body, bool IsGmail) { System.Net.Mail.MailMessage msgMail = new System.Net.Mail.MailMessage(); //for gmail servers change mail@domain.com with your-gmail-id@gmail.com System.Net.Mail.MailAddress From = new System.Net.Mail.MailAddress(_SMTP_User, name); msgMail.From = From; //person to send mail msgMail.To.Add(_Message_Receiving_Email); msgMail.Subject = subject; msgMail.Body = body; msgMail.IsBodyHtml = true; msgMail.Priority = System.Net.Mail.MailPriority.Normal; //for gmail replace mail@domain.com with gmailID@gmail.com and gmail password System.Net.NetworkCredential logininfo = new System.Net.NetworkCredential(_SMTP_User, _SMTP_Pass); System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(); if (IsGmail) { client.Host = "smtp.gmail.com"; client.Port = 587; client.EnableSsl = true; } else { //if not using gmail input your smtp host name here client.Host = _SMTP_Server; } client.UseDefaultCredentials = false; client.Credentials = logininfo; //client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory try { client.Send(msgMail); return true; } catch (Exception ep) { Response.Write(ep.Message + ep.Data + ep.InnerException); return false; } }     Invoking our Function   bool deliveryReport = false; deliveryReport = SendMail (“userXX@some_email.com”, “Sample User Name”, “User Enquiry Subject”, “Body of the Email”, false) ;if(deliveryReport){Response.Write("Email Sent Successfully"); }else{Response.Write("failed");}

Tags:

Asp.Net

Sending SMS using SMPP sample code

July 04, 2012 Posted by Mithila Software
There are many sms paid service providers which you can use in your applications either for user verfication or information update push to the end user.When you buy bulk sms pack from your provider they should provide   Host IP or Name ="xx.xx.xxx.xx" / xxx.com ; Port = "xxxx"; User = ""; Password = ""; From = "";   The sample code provided by the providers are mostly in php or classic asp.An implementation of sms sending code in asp.net is expected to be like this   public void sendSMS (string strHost, string strPort,string strUser,string strPassword ,string strRecip,string strMsgText,string strFrom) { Uri objURI =new Uri("http://" + strHost + ":" + strPort+ "/?User=" + HttpUtility.UrlEncode(strUser) + "&Password=" + HttpUtility.UrlEncode(strPassword) + "&PhoneNumber=" + HttpUtility.UrlEncode(strRecip) + "&Text=" + HttpUtility.UrlEncode(strMsgText) // The actual message that you send must be <=140 characters+"&Sender=" + HttpUtility.UrlEncode(strFrom)); WebRequest objWebRequest= WebRequest.Create(objURI); WebResponse objWebResponse = objWebRequest.GetResponse(); }   Now the above code is like fire and forget principle.In reality we may need the outcome of our send message.For that purpose we can modify the above code to return the outcome of our sent sms.   public string sendSMS (string strHost, string strPort,string strUser,string strPassword ,string strRecip,string strMsgText,string strFrom) { Uri objURI =new Uri("http://" + strHost + ":" + strPort+ "/?User=" + HttpUtility.UrlEncode(strUser) + "&Password=" + HttpUtility.UrlEncode(strPassword) + "&PhoneNumber=" + HttpUtility.UrlEncode(strRecip) + "&Text=" + HttpUtility.UrlEncode(strMsgText) + "&Sender=" + HttpUtility.UrlEncode(strFrom)); WebRequest objWebRequest= WebRequest.Create(objURI); WebResponse objWebResponse = objWebRequest.GetResponse(); Stream objStream= objWebResponse.GetResponseStream(); StreamReader objStreamReader = new StreamReader(objStream); String strHTML = objStreamReader.ReadToEnd();return strHTML; }   So , the above code is supposed to return a string result of our send sms.

Tags:

Asp.Net


Category Posts

Address ::
Mithila Software Solutions,
Green House , 3 GM Road ,
Near Radio Station , Darbhanga
PIN:: 846004
Phone :: # 099-397-49350