Next step of programming

Just another WordPress.com weblog

Posts Tagged ‘ASP.NET

.Net RIA Service Part 1

without comments

What is a .Net RIA Service

It is set of libraries and tools given, to help develop the Rich internet application in much easier fashion. When we develop silverlight application we need to interact with the server for various reasons. Now .Net RIA Service will make that much easier and better.

In our normal silverlight application we used to interact with the server from the client code to move data in async fashion and managing it. But now .NET RIA Service will just hide it all from you and handles all those stuff. You can concentrate more on what to do with data rather than how to get the data.

It is link between the presentation layer and business logic layer. You can add various kind of validation also to be performed.

you can download these services from here

Now i am developing sample application of RIA Service with silverlight and will post it with complete working details of .net RIA Service

Written by A.Sethi

September 3, 2009 at 10:05 am

Posted in Silverlight

Tagged with ,

Event Calendar in MVC application Using jMonthCalendar(JQuery)

with 8 comments

A good Jquery plugin is available as Event Calendar which can be download from following location.

http://www.bytecyclist.com/projects/jmonthcalendar/
or
http://code.google.com/p/jmonthcalendar/

I used it in one sample project with MVC and loaded certain events from the controller. Which can in return load from the Model. But for the time being in this sample i returned from the controller it self.


public ActionResult Events(string date)
{
MyEvents event1 = new MyEvents            
{
EventID = 11 ,
StartDate = new DateTime(2009,04,01),
Title = "Meeting with Boss",
Description = "Meeting on product release",
CssClass = "Meeting",
URL= "/Home/EventDetails/11"            
};

MyEvents event2 = new MyEvents            
{
EventID = 12,
StartDate = new DateTime(2009, 04, 01),
Title = "Celebration",
Description = "Fathers birthday",
CssClass = "Birthday",
URL = "/Home/EventDetails/12"            
};

string[] stringlist = new string[2];
stringlist[0] = event1.GetJSONResult();
stringlist[1] = event2.GetJSONResult();

return Json(stringlist);
}


For calling the events it did getJson call from the index page where the jMonthCalendar is shown. It will call one of the function the Controller and in return will get the array of the events which will then be sent to the jMonthCalendar. It will load the events. We can add the URL also so that when user clicks the event he will get the complete detail once again with the help of the controller


<script type="text/javascript">
    $().ready(function() {
var options = {

height: 650,
width: 980,
navHeight: 25,
labelHeight: 25,

onMonthChanging: function(dateIn) {
$.getJSON("http://localhost:1511/Home/Events",
function(data) {

//Array of my events                    
var events = new Array();

//Loop and load all the events and load them into the array
                    $.each(data, function(i, item) {

var oResultData = eval('(' + item + ')');
var event = { "EventID": 5, "Date": oResultData.StartDate,
"Title": oResultData.Title, "URL": oResultData.URL,
"Description": oResultData.Description,
"CssClass": oResultData.CssClass
};

events.push(event);

});

//Load the events into the calendar
                    $.jMonthCalendar.ReplaceEventCollection(events);
$.jMonthCalendar.DrawCalendar(dateIn);
});
return true;
},
onEventBlockOver: function(event) {
return true;
},
onEventBlockOut: function(event) {
return true;
},
onDayLinkClick: function(date) {
return true;
},
onDayCellClick: function(date) {
return true;
}
};

var newevents = [];
$.jMonthCalendar.Initialize(options, newevents);
});</script>


Download the sample from following location

EventCalendar

Here are the screen shot of the application.

Event Calendar in MVC Application

Event Calendar in MVC Application

Detail of selected Event

Detail of selected Event

Written by A.Sethi

April 30, 2009 at 5:25 pm

Posted in ASP.NET

Tagged with , , , ,

File upload in ASP.NET MVC

with 7 comments

Here is a sample for handling upload of a file, In your MVC application. In this sample i used the Dialog box of JQuery, where user will select the file and will click upload


<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">    

<h2>Files uploaded to server</h2>    

<div id="dialog" title="Upload files">        
    <% using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {%><br />
        <p><input type="file" id="fileUpload" name="fileUpload" size="23"/> ;</p><br />
        <p><input type="submit" value="Upload file" /></p>        
    <% } %>    
</div>
<a href="#" onclick="jQuery('#dialog').dialog('open'); return false">Upload File</a>
</asp:content>


Then we have to handle this request in the respective controller which is specified in BeginForm of our above code (FileContoller) and action name (Upload). Following will be our code in the FileController Controller for the Upload action


public void Upload()
{
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase file = Request.Files[inputTagName];
if (file.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads")
, Path.GetFileName(file.FileName));
file.SaveAs(filePath);
}
}

RedirectToAction("Index", "File");
}


Download the sample code from here

File upload in MVC with JQuery Dialog

File upload in MVC with JQuery Dialog

Written by A.Sethi

April 17, 2009 at 10:55 am

Posted in ASP.NET

Tagged with , , ,

Crop Image in ASP.NET using JCrop, JQuery

with 12 comments

You might have seen various websites and web application giving features to Crop your image and save it. That can be done in DHTML or in Javascript. Lets see one example of doing it with the help of JCrop which can be download from here (JCrop)

How to start

1. First include the following file into your project

  • jquery.Jcrop.js
  • jquery.Jcrop.min.js
  • jquery.min.js

or you can directly drag and drop the JCrop folder in your project

JCrop files

JCrop files

2. We need to write code in our page. Include the JQuery function in the page and also add one event for crop control for updation of the cordinates in the variable on selection by users. Check the head section of the page given below

<head runat="server">    
<title></title>    

<script src="js/jquery.min.js"></script>

<script src="js/jquery.Jcrop.min.js"></script>
<script src="js/jquery.Jcrop.js"></script>

<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />

		<script language="Javascript">

		    jQuery(document).ready(function() {
		    jQuery('#cropbox').Jcrop({
		            onSelect: updateCoords
		        });
		    });

		    function updateCoords(c) {
		        jQuery('#X').val(c.x);
		        jQuery('#Y').val(c.y);
		        jQuery('#W').val(c.w);
		        jQuery('#H').val(c.h);
		    };

		</script>
</head>

3. In your body section add following form to your page

<div>        
<asp:Button ID="Submit" runat="server" Text="Crop Image" 
onclick="Submit_Click" />        
<br />        
<br />        
<asp:Image ID="cropedImage" runat="server" Visible="False" />        
<br />        
<br />        

<img src="Sunset.jpg" id="cropbox" />

<asp:HiddenField ID="X" runat="server" />        
<asp:HiddenField ID="Y" runat="server" />        
<asp:HiddenField ID="W" runat="server" />        
<asp:HiddenField ID="H" runat="server" />        

</div>

4. We need to handle the click event of crop button in our code and crop the image there

protected void Submit_Click(object sender, EventArgs e)
{
if (this.IsPostBack)
{
//Get the Cordinates                
int x = Convert.ToInt32(X.Value);
int y = Convert.ToInt32(Y.Value);
int w = Convert.ToInt32(W.Value);
int h = Convert.ToInt32(H.Value);

//Load the Image from the location
                System.Drawing.Image image = Bitmap.FromFile(
HttpContext.Current.Request.PhysicalApplicationPath + "Sunset.jpg");

//Create a new image from the specified location to                
//specified height and width                
Bitmap bmp = new Bitmap(w, h, image.PixelFormat);
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(image, new Rectangle(0, 0, w, h), 
new Rectangle(x, y, w, h), 
GraphicsUnit.Pixel);

//Save the file and reload to the control
                bmp.Save(HttpContext.Current.Request.PhysicalApplicationPath + "Sunset2.jpg", image.RawFormat);
cropedImage.Visible = true;
cropedImage.ImageUrl = ".\\Sunset2.jpg";
}
}

Download complete code from here

Selection by user for Croping

Selection by user for Croping

Cropped Image

Cropped Image

Written by A.Sethi

April 13, 2009 at 5:33 am

Posted in ASP.NET

Tagged with , ,

Using JQuery UI in ASP.NET MVC

with 17 comments

I was developing one application in ASP.NET MVC, where i was in need of displaying Date Picker to the user. But if you generate View with the help of MVC extension then it will display text box for your date field. In order to show the datepicker i used jquery datepicker.
You can download it from JQuery UI here

Step 1

  • Include these files in your project. in the script folder
  • jquery-1.3.2.js
    ui.core.js
    ui.datepicker.js

    Also include the theme folder in project to apply the themes for the respective controls

  • Add the Script reference in your webpage, for that include the following code
  • <script type="text/javascript" src="/../../Scripts/jquery-1.3.2.js"></script>
    <script type="text/javascript" src="/../../Scripts/ui.core.js"></script>
    <script type="text/javascript" src="/../../Scripts/ui.datepicker.js"></script>
    
  • Include the following script in your view page(where you want to show the date picker) giving it a ID. On that ID we will use it as a input. ID should be unique
  • <script type="text/javascript">
     $(document).ready(function(){
    $("#FromDate").datepicker();
    });
    </script>
    

Step 2

  • We need to create a Extension for HtmlHelper Class.
  • using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace System.Web.Mvc.Html
    {
    public static class DatePickerExtension
    {
    public static string DatePicker(this HtmlHelper htmlHelper, string name)
    {
    return "<input type=\"text\" id=\"" + name + 
    "\" name=\"" + name + "\" value=\"\"/>";
    }
    }
    }
  • In your view page you have to add the following code to have that control
  •  <label for="fromDate">From date:</label>             
    <%= Html.DatePicker("FromDate")%>

Output :

JQuery UI DatePicker

JQuery UI DatePicker

Written by A.Sethi

April 10, 2009 at 8:45 am

Posted in ASP.NET

Tagged with , , , , ,

Captcha Control Sample (C#, ASP.NET, Server Control)

with 6 comments

In various websites, Captcha control is used for validating the user input and protect web application from the program. Here is one of the sample control for Captcha. It is basic one which can be enhanced further by including more to the image generation and even including the timeout. Or you can add much more to it

This application has two parts

1. CaptchaControl
2. CaptchaControl Sample Project

Captcha control has three files.

1. CaptchaControl (Which is the main control)
2. CaptchaImage (Which generates the Captcha image)
3. CaptchaImageHandler (which will provide the image to browser from the cache).

You can download it from (Captcha Control Sample)

Captcha Sample Control

Captcha Sample Control

Written by A.Sethi

February 26, 2009 at 4:17 am

Posted in ASP.NET, Controls

Tagged with , , , ,

Search your website (Microsoft Indexing Service, C#, ASP.NET)

with one comment

You might have seen various website providing search capabilities to search content within their website. Implementing this in our web application is also easy and for that we have to just use the indexing service to create indexes of our pages. Microsoft is providing indexing service which we can utilise for this purpose.

To understand what is indexing service click this link

Now you might wonder how to get this service in your system. For that follow the steps

1. Goto Control Panel > Add Remove Programs
2. Click “add remove windows component”
3. from the screen select “Indexing service” and install

Installing Indexing Service

Installing Indexing Service

Now you have indexing service in your system. From computer management you can see the indexing service and can manage it. We need to create new catalog which will contain the indexes. To that catalog we will add the directories which are to be indexed.

Indexing Service Management

Indexing Service Management

There are other settings too like Indexing Service usage and etc. For that right click your indexing service node and select All Task > Tune Performance

Tune Performance (Updating Indexes)

Tune Performance (Updating Indexes)

We can now implement this in our web application to search the web pages. Below sample code is written for seaching and displaying the content in the ASP.Net Page

 string connectionString ="Provider=MSIDXS;Data Source=MISSample;";
OleDbConnection connection = new OleDbConnection(connectionString);
connection.Open();

string query = @"SELECT Path, FileName, size, write, attrib, Characterization,
DocTitle FROM SCOPE() " +
"WHERE FREETEXT(Contents, '*" +  txtQuery.Text + "*')";
OleDbCommand command = new OleDbCommand(query, connection);
OleDbDataAdapter adapter = new OleDbDataAdapter(command);

DataSet dataSet = new DataSet();
adapter.Fill(dataSet);

GridView1.DataSource = dataSet.Tables[0];
GridView1.DataBind();
connection.Close();

Sample Output

Sample Application

Sample Application

Written by A.Sethi

February 11, 2009 at 9:51 am

Posted in ASP.NET

Tagged with , , , ,

Sample weather forecast WCF application.

without comments

Here is one WCF webservice sample developed for weather forecasting. Two projects are include one is web application another one is wcf application. Download and check out

Weather Forecast WCF Sample

Weather Forecast WCF Sample

Written by A.Sethi

February 10, 2009 at 8:17 am

Google Contact Detail Listing (C# , Google API, ASP.NET)

with 5 comments

Check out the following ASP.NET example for listing contact of a gmail account and adding a new contact to it. First download the Google Data API from the specified link and install it

http://code.google.com/p/google-gdata/

Then create a new project and include following references in it

Google.GData.Client.dll
Google.GData.Contacts.dll
Google.GData.Extensions.dll

Then i created the following class


using System;
using System.Collections.Generic;
using Google.GData.Contacts;
using Google.GData.Extensions;

/// 
/// Summary description for GoogleContactService
/// 
public class GoogleContactService
{
public static ContactsService GContactService = null;

public static void InitializeService(string username, 
string password)
{
GContactService = new ContactsService("Contact Infomation");
GContactService.setUserCredentials(username, password);
}

public static List<ContactDetail> GetAllContact()
{
List<ContactDetail> contactDetails = new List<ContactDetail>();
ContactsQuery query = new ContactsQuery(ContactsQuery.
CreateContactsUri("default"));

ContactsFeed feed = GContactService.Query(query);
foreach (ContactEntry entry in feed.Entries)
{
ContactDetail contact = new 
ContactDetail{Name = entry.Title.Text,
EmailAddress1 = entry.Emails.Count >= 1 ? entry.Emails[0].Address : "",
EmailAddress2 = entry.Emails.Count >= 2 ? entry.Emails[1].Address : "",
Phone = entry.Phonenumbers.Count >= 1 ? entry.Phonenumbers[0].Value : "",
Address =  entry.PostalAddresses.Count >= 1 ? entry.PostalAddresses[0].Value : "",
Details = entry.Content.Content};

contactDetails.Add(contact);
}

return contactDetails;
}

public static void AddContact(ContactDetail contact)
{
ContactEntry newEntry = new ContactEntry();
newEntry.Title.Text = contact.Name;

EMail primaryEmail = new EMail(contact.EmailAddress1);
primaryEmail.Primary = true;
primaryEmail.Rel = ContactsRelationships.IsWork;
newEntry.Emails.Add(primaryEmail);

EMail secondaryEmail = new EMail(contact.EmailAddress2);
secondaryEmail.Rel = ContactsRelationships.IsHome;
newEntry.Emails.Add(secondaryEmail);

PhoneNumber phoneNumber = new PhoneNumber(contact.Phone);
phoneNumber.Primary = true;
phoneNumber.Rel = ContactsRelationships.IsMobile;
newEntry.Phonenumbers.Add(phoneNumber);

PostalAddress postalAddress = new PostalAddress();
postalAddress.Value = contact.Address;
postalAddress.Primary = true;
postalAddress.Rel = ContactsRelationships.IsHome;
newEntry.PostalAddresses.Add(postalAddress);

newEntry.Content.Content = contact.Details;

Uri feedUri = new Uri(ContactsQuery.CreateContactsUri("default"));

ContactEntry createdEntry = (ContactEntry)GContactService.Insert(feedUri, newEntry);
}
}

public class ContactDetail
{
public string Name { get; set; }
public string EmailAddress1 { get; set; }
public string EmailAddress2 { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public string Details { get; set; }
}

After that i create one webpage to list and create new contacts details in my gmail account. You can download the complete project from this location Download Here


Login to Gmail Account

Login to Gmail Account

Add Contacts to google and list them

Add Contacts to google and list them

Written by A.Sethi

February 6, 2009 at 10:50 am