November 3, 2010 Leave a comment

You can use this code for hyperlinked button as well as underlined text . You  know there is no facilities for such option in none of iPhone SDK. So you can try this. It works for me.

in .h file

@interface UnderLineLabel : UIButton{
CGFloat stockWidth;

}

@property(nonatomic,assign)CGFloat stockWidth;

@end

in .m file

@implementation UnderLineLabel

@synthesize stockWidth;

- (id)initWithFrame:(CGRect)frame {

if (self = [super initWithFrame:frame]) {

// Initialization code

}

return self;

}

- (void)drawRect:(CGRect)rect {

[super drawRect:rect];

CGContextRef context = UIGraphicsGetCurrentContext();

CGFloat components[4] = {0.654901961, 0.662745098, 0.674509804, 1};

CGContextSetStrokeColor(context, components);

// Draw them with a 1.0 stroke width.

CGContextSetLineWidth(context, self.stockWidth);

// Draw a single line from left to right

CGContextMoveToPoint(context, 0, rect.size.height);

CGContextAddLineToPoint(context, rect.size.width, rect.size.height); 

CGContextStrokePath(context);

}

- (void)dealloc {

[super dealloc]; 

}

@end

Making a Call From Your Application

August 14, 2010 Leave a comment

As far i know in earlier version of iPhone (before iOS4), your application will terminate before making a call. Because it doesn’t support multitasking. But iOS4 support multitasking. So don’t afraid now. Just follow the code

-(void)callButtonClicked{
NSString *makBoneyphnNo = @"+8801717011014";
NSString *phoneStr = [[NSString alloc] initWithFormat:@"tel:%@",makBoneyphnNo];
NSURL *phoneURL = [[NSURL alloc] initWithString:phoneStr];
[[UIApplication sharedApplication] openURL:phoneURL];
[phoneURL release];
[phoneStr release];
}
Categories: iPhone, Objective-C Tags: , ,

Things Should Know First

August 12, 2010 2 comments

What do think after knowing these. What is yar choice…

Windows Mobile

C++ or .NET
free distribution, just like normal applications
Microsoft have market, too – here
Windows Phone 7
.NET and Silverlight
through Marketplace

Android

Java
through Android Market ($25 one-time fees) or like normal applications
The platform is completely open source

iPhone(my favorite)

Objective-C or Java (Developing iPhone Applications using Java)
through iPhone Market
pay some fees ($99/year)
The Incredible App Store Hype
You need Mac (Mac OS) for development (thx to ctacke)

Java

J2ME or JavaFX

Symbian

Is open source
Has by far the largest market share (45% or so) of smartphones
Runs on cheaper hardware than Android and iPhone (means volumes will go up significantly faster)
Runs Python, Ruby, Java and Web Runtime Widgets
From Symbian^4 will have a complete Qt stack.

According to me and fixEdd

Symbian’s dead; Windows Mobile will die, but take a long time; Android will become the standard in the next few years; iPhone will remain trendy in coming years, but NOT take be the biggest player; Pre/WebOS will maintain a niche market, but not be wildly sucessfull, Blackberry will decline, but still be around forever. I’d probably put my time/money into Android or iPhone at this point.

UIWebView in Action – iPhone Application Development

July 28, 2010 Leave a comment

Usually we use UIWebView to load web pages. But i faced some problems that was really scared for me. Visited couple of forums, talked to some guyz and they really helped me to stuck out of that problem.

Okay, let me share it.  If you need to show a hyperlink or have to show a large text with some captions (i mean something like headline) what will you do???Don’t panic couple of solutions are waiting for you.

UIWebView as hyperlink

First, you can use a custom label and a button to trgiger that action. You can also get help from the famous Threee20 project. But i found UIWebview very much useful. You have to place that UIWebView in the exact position and then use a transparent button to do something. Here is some  code snnipet

myWebView.frame = prefableFrame;  // any preferable frame

NSString *linkString = @"WWW.makboney.wordpress.com";

linkString  =[@" "linkString];linkString =[linkString stringByAppendingString:@" "];

[myWebView  loadHTMLString:linkString baseURL:nil];

//hidden button to trigger actionhiddenButton = [UIButton buttonWithType:UIButtonTypeCustom];

hiddenButton.frame = myWebView.frame;

hiddenButton.backgroundColor = [UIColor clearColor];

[hiddenButton addTarget:self action:@selector(buttonPressed)                                forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:hiddenButton];

UIWebView to show html text or big text containing  caption , bullet marks or somthing like that

When you need to display large text into label with some caption,bullet marks and also managed couple of other issues. In that case  i suggest you to use  UIWebView. For this you need to do some preprocessing  of the big text such as including tags into proper place. And now its easy. Follow the  bellow code snippet.

NSString *htmlTextString;

htmlTextString  =[@"" stringByAppendingString:[appDelegate modifiedString: bigtext]];

[descLabel loadHTMLString:htmlTextString baseURL:nil];

Display Image From URL

June 26, 2010 Leave a comment

This is handy if you need to add an image as a subview, yet, the image is not part of your application bundle.

URL to Remote Image

We start by creating a URL to the remote resource:

NSURL *url = [NSURL URLWithString:
@"http://iphonedevelopertips.com/images/logo-iphone-dev-tips.png"];

Create UIImage from NSData

The next step is to build a UIImage using the data downloaded from the URL, which consists of an NSData object that holds the remote image contents:

UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];

Putting it Together

Here’s how to wrap it all together, adding the remote image as a subview to an existing view by creating a UIImageView from the above UIImage:

NSURL *url = [NSURL URLWithString:
@"http://iphonedevelopertips.com/images/logo-iphone-dev-tips.png"];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
[self.view addSubview:[[UIImageView alloc] initWithImage:image]];

Duration of Your Touch Event

June 26, 2010 Leave a comment

Start by creating a variable of type NSTimeInterval to hold the time the touch event began.

// Define this as an instance variable
NSTimeInterval touchStartTime;

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
{
// When the touch event was detected
touchStartTime = [event timestamp];
}

Inside the touchesBegan event, with some simple math, one can determine how long from the start event to the end.

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
{
// Calculate how long touch lasted
NSTimeInterval touchTimeDuration = [event timestamp] - touchStartTime;

NSLog(@"Touch duration: %3.2f seconds", touchTimeDuration);
}
Categories: iPhone, Objective-C

Get iPhone Device Information

June 26, 2010 Leave a comment

The iPhone SDK includes a singleton of class type UIDevice that you can use to retrieve device specific information (this works equally as well with the simulator).

Available Properties in UIDevice

uniqueIdentifier – identifier guaranteed to be unique for every device
name – arbitrary name found in General > About setting on device
systemName – name of the OS running on the device
systemVersion – current version of the OS
model- model, such as ”iPhone” or ”iPod touch”
localizedModel – same as above using a localized string

Stats for Simulator

This code will list all stats shown above:

NSLog(@”uniqueIdentifier: %@”, [[UIDevice currentDevice] uniqueIdentifier]);
NSLog(@”name: %@”, [[UIDevice currentDevice] name]);
NSLog(@”systemName: %@”, [[UIDevice currentDevice] systemName]);
NSLog(@”systemVersion: %@”, [[UIDevice currentDevice] systemVersion]);
NSLog(@”model: %@”, [[UIDevice currentDevice] model]);
NSLog(@”localizedModel: %@”, [[UIDevice currentDevice] localizedModel]);

Running the above on the simulator returns:

Stats for iPhone

The device stats when running on my iPhone:

iPhone Memory Management

June 19, 2010 3 comments

After long time i’m back to my web home. Passing some tough time. Well today i am going to write about iPhone  memory  management. Its not easy to write code without considering the memory that reserved for you. If you dont have a clear concept right now, surely you will face some problem in developing yar application. So lets have a discussion.

Memory Management

First of all Objective-C don’t have garbage collection like some other language. But i have to say the memory management is not 100% manual neither 100% automatic. Confused!!! Wait keep reading, hope you will find the answer.

Retain Count

The first technique that can help to mange your memory is retain count.

So what is retain count???

Retain Count: How many other objects have a reference of a particular object. That is how many other objects holding the reference  of your declared objects. Hope you know that when you declared an object it consumed some space in your main memory and if don’t make free that space that will be a nightmare for you later. So every time you declared an object some memory occupied by your program and if you don’t dealloc it application will be crashed. So easy way to count down to find it is retain count.

In Objective C every class is derived from base class NSObject which has an property retainCount. So you can make an inquiry of your declared object with this property. Whenever you declare an object or hold the reference of an object the retainCount increased by  1 and when you release the reference, the retainCount is decreased by 1. And finally when the retainCount gets down to 0, Objective-C deletes memory for that object. So here is the summery

–[anObject retain] –> increment count by 1

–[anObject release]–> decrement count by 1

When count ==0 –>Obj C deletes memory for that object

You must release those objects which belongs to you(forget the else).

•Ownership of an object

–alloc

–new

–copy

–Retain message

You owned an object when you declare it by alloc/new, copt actually mutableCopy and by the retain message. So its yar duty to maintain retainCount. Thats the manual thing i talking about.

•Reference counting (example)

NSNumber  *myInt 1=  [NSNumber numberWithInteger:100]  ;

//count incresed by 1

NSNumber  *myInt 2;

NSMutable Array *myArray = [NSMutableArray array];

[myInt1 retainCount]; //just print to see what goin on result =1

[myArray addObject:myInt1]; //increment by 1

[myInt1 retainCount]; // result 2

myInt2 = myInt1;  //holding the reference

[myInt1 retain]; //doing that b coz of earlier statement

[myArray removeObject:myInt1]; // decresed by 1

[myInt1 release]; //// decresed by 1

Read more…

Categories: Uncategorized Tags: , , ,

Introduction to Objective-C

April 13, 2010 2 comments

Lets find the history of Objective-C in a a very short circumstances.

1972:  we have C one of the most popular programming languages

1983:  a reflective, object-oriented programming language which adds Smalltalk-style messaging to the C programming language.

1988: NeXT licences Objective-C for NeXT step C.

1996 : Apple buys NeXT.

2002: OS X

2007: iphone Objective C

So we know that most of the modern languages (like C++, Java ,C# and etc) are from C. all of these are C Based languages. For say if want to write the program “Hello world”

In C++

#include<iostram.h>

int main()

{

std::cout<<”Hello World:!\n” ;

return 0;

}

In java

public class Hello{

public static void main(String[] args)

{

System.out.println(“Hello World:!”) ;

}

}

In C#

public class Hello

{

public static void Main(0

{

System.Console.WriteLine(“Hello World:!”);

}

}

See all of them inheritaed from C . All of these languages took C as their mother languages and implements and enhanced  from C. While Objective-C not enhanced from C.  Its actually expressing the language in a very different way. The same program written in Objective-c

import<Foundation/Foundation.h>

public int main(int argc, const char *argv)

{

NSLog(@”Hello World:!”);

return 0;

}

Objective-C has thousands of build in classes like NSString,NSStream,NSThread,NStask and many more. And these classes belongs to the common framework named Foundation Framework. Similarly we have thousands of classes for managing  Core Audio,Core graphics ,Map Kit,Game kit  for user interface and those classes are organized under the Framework UIKit. And finally combining both the Foundation Framework and UIKit Framework we have the Cocoa Touch Framework.

Cocoa uses the Model-View-Controller (MVC) design pattern throughout. Models encapsulate application data, Views display and edit that data, and Controllers mediate the logic between the two. By separating responsibilities in this manner, you end up with an application that is easier to design, implement, and maintain.

The MVC pattern means that Interface Builder requires no code to be written or generated while you focus exclusively on the View of your application. Cocoa bindings on the Mac eliminate most of the glue code, making the connection between Controllers coded in Xcode and the Views designed within Interface Builder a simple matter of graphically “wiring” the two together. Interface Builder works with Cocoa to make localizing your application easy so you can quickly enter entirely new

Hello iPhone

April 12, 2010 Leave a comment

Its enough if you have a little knowledge in C/C++ or C# or in Java to build your first iPhone application. Okay,  as usual we are going to develop the famous HelloWorld Application.

We use Visual studio for developing C# or asp.net application, Eclipse for java and Dreamweaver  for PHP. You know all of  these are IDE. Like those, in developing  iPhone application we use IDE XCode which is very interactive. Here, in this example  we dont need to code on Objective-C because its very simple.

First create a new project named HelloWorld. Soon you will see a figure like the bellow one.

Okay, here i have to mention that we can use XCode for developing Mac applications as well as iPhone applications. We go for iPhone application. You will  see some templets on the right hand side. Among them we choose View Based Application.

Now you will see that your project files are organized into different folders. XCode manage it because you can pick your file easily andd work on that but in your disk they are in the same place.

Now go to the class folder and double-click the HelloWorldViewController.xib file which is actually the design file. These will run another program called Interface Builder and you will seesome windows like the figure bellow…

The View window gives you the flavour of how your application will look like. While Libary window contains the interface’s elements and the Controller window is very important one to mange different action and view of your application. Here  drag a label and write “Hello world” by double clicking the label. Now close the Interface Builder. Build and Run your application. Hope you will see like…

Categories: iPhone Tags: ,

Test-Driven Devlopment (TDD)

April 12, 2010 Leave a comment

Please don’t think that Test-Driven development(TDD) is relevent to Testing. Because the name suggest you to think like that. It’s absolutely far away from testing. Okay, keep reading and you will have an idea on TDD. Here i just describing it on the basis of some documents got from BASIS OOP training programs. i am lucky because i completed that course. Now i am going to explain

what is Test-Driven Development :

Is a Test-First approach (Write the test-code first and then write the dev-code)
It leads to think about ‘How to use a component’ first and then about ‘How to implement’.
As much about design technique as testing TDD technique.
As much about (executable) documentation as testing

so, that’s the summary of TDD. TDD is about writing the development code through test code. At the very beginning we there are some story(User Story) and depending on those story we  will implement. So from the story we should find out the components and then implement the application on those components. please don’t write any code by thinking  what will happen in future? Then you are not in TDD. Because TDD insists to write exactly what we need not what we will need.Thsee are almost the principle of TDD.

Principles of TDD

Kent Beck defines:

• Never write a single line of code unless youhave a failing automated test.
• Eliminate duplication.

Red (Automated test fail)

Green (Automated test pass because dev code has been written)

Refactor (Eliminate duplication, Clean the code)

well  those are the principles of TDD. Think, you are yet confused. Trying to make it clear.

Actually  Red/Green/Refactor defines the process for implementing each test in the test list. The goal of this process is to work in small, verifiable steps that provide immediate feedback. William Wake, in his book Extreme Programming Explored (Addison-Wesley, 2001), details the programming tasks as follows: Read more…

Categories: Software Crafting Tags: , ,

10 simple Google search tricks

April 12, 2010 Leave a comment

Here are excerpts from an article on 10 little tricks you can use to get more out of a simple Google search:

· Use the “site:” operator to limit searches to a particular site. I use this one all the time, and it’s particularly handy because many site’s built-in search tools don’t return the results you’re looking for (and some sites don’t even have a search feature). If I’m looking for WWD posts about GTD, for example, I could try this search: GTD site:webworkerdaily.com.

· Use Google as a spelling aid. As Rob Hacker — the WWD reader I profiled last week — pointed out, entering a word into Google is a quick way to see if you have the right spelling. If it’s incorrect, Google will suggest the correct spelling instead. Additionally, if you want to get a definition of a word, you can use the “define:” operator to return definitions from various dictionaries (for example, define: parasympathetic).

· Use Google as a calculator. Google has a built-in calculator — try entering a calculation like 110 * (654/8 + 3). Yes, your computer also has a calculator, but if you spend most of your day inside a browser, typing your calculation into the browser’s search box is quicker than firing up your calculator app.

· Find out what time it is anywhere in the world. This one’s really handy if you want to make sure that you’re not phoning someone in the middle of the night. Just search for “time” and then the name of the city. For example, try: time San Francisco

· Get quick currency conversions. Google can also do currency conversion, for example: 100 pounds in dollars. It only has the more mainstream currencies, though — if you’re trying to see how many Peruvian nuevos soles your dollars might buy, you’ll be out of luck.

· Use the OR operator. This can be useful if you’re looking at researching a topic but you’re not sure which keywords will return the information you need. It can be particularly handy in conjunction with the “site:” operator. For example, you could try this search: GTD or “getting things done” site:webworkerdaily.com

· Exclude specific terms with the – operator. You can narrow your searches using this operator. For example, if you’re looking for information about American Idol but don’t want anything about Simon Cowell, you could try: “american idol” -cowell

· Search for specific document types. Google can search the web for specific types of files using the “filetype:” operator. If you’re looking for PowerPoint files about GTD, for example, you could try: GTD filetype:ppt

· Search within numerical ranges using the .. operator. Say, for example, you want to look for information about Olympic events that took place in the 1950’s, you could use this search: Olympics 1950..1960

· Area code lookup. Need to know where a phone number is located? Google will let you know where it is, and show you a map of the area, too. For example: 415

Categories: Uncategorized

The Four Pillars of iPhone

April 12, 2010 Leave a comment

There are many developers who can’t give you a specific idea in developing your iPhone application. So it would be little tough for you to adopt the new enviroment, you may confuzed about the right approach like me when i was new. So after having some documents and vedio tutorials i can tell you that you should follow the four pillars of iPhone. These four pillar will help you in developing your iPhone applications.

So the pillars of iPhone are :

The four pillars of iPhone

Read more…

Categories: iPhone Tags: , ,

Data Type Conversions

March 28, 2010 Leave a comment

Sometimes we have to change the data that we are using. Sometimes this change may change the value of the data or sometimes it just changes the memory space allocated by that data. This change is called data type conversion.

Data type is converted in 2 ways. They are:

  1. Implicit conversion
  2. Explicit conversion

They are described below.

Implicit conversion:

An implicit conversion converts data automatically without losing any data. Normally, data types can implicitly converted into the data types those contain more memory space.

Example:

short firstNumber = 65;

long secondNumber = firstNumber;

Explicit conversion:

An explicit conversion convert data that are automatically can’t be converted. It may converts data from bigger size to smaller size or converts data from one type into totally different type.

Example:

short firstNumber = 65;

long secondNumber = firstNumber; //Implicit conversion

short thirdNumber = (short)secondNumber; //Explicit  conversion

Console.WriteLine(thirdNumber); //outputs 65

char a = (char)firstNumber; //Explicit conversion

Console.WriteLine(a); //outputs A

We can use some built in functions those are provided with C#.

a. Convert class:

A convert class contains numerous method those can change one data type into another type. It is another implementation of explicit conversion.

Example:

int number = 65;

char character = Convert.ToChar(number); //Conversion using System’s Class

Console.WriteLine(character);   //Output: A

b. ToString() method:

A ToString() method converts any kind of data type into String type. It doesn’t change the internal value of that data.

Example:

char character = Convert.ToChar(65); //Conversion using System’s Class

string numberString = (65).ToString();

Console.WriteLine(character); //Output: A

Console.WriteLine(numberString); //Output(value is in String form): 65

Categories: ASP.NET, OOP Concept

Verbatim Characters

March 28, 2010 Leave a comment

A verbatim string is a string that is interpreted by the compiler exactly as it is written, which means that even if the string spans multiple lines or includes escape characters, these are not interpreted by the compiler and they are included with the output. The only exception is the quotation mark character, which must be escaped so that the compiler can recognize where the string ends.

string address = @”C:\Software\Books\Beginning”;

As you can see, verbatim is indicated with an ‘@’ sign at the beginning of a string.

If you want to use a quotation mark inside a verbatim string, you must escape it by using another set of quotation marks.

Example:

string greetings = @”"”Hello everyone”".said the trainer.”;

Categories: ASP.NET, OOP Concept Tags: ,

Naming Convention

March 26, 2010 Leave a comment

.NET Naming Convention

Casing Example Remarks
Button camelCase saveButton
Form PascalCase EmployeeInformationEntryUI “UI” or “Form” word should be appened at last part
TextBox camelCase firstNameTextBox “TextBox” should be appended at last part
ComboBox camelCase employeeListComboBox
ListView camelCase emploueeListListView
Class PascalCase Calculator, Employee should be noun
Object camelCase myCalculator,employeeObj
Method PascalCase GetFullName(), Add(), Encrypt() should be verb
Variable camelCase firstName, basicSalary
Property PascalCase FirstName, BasicSalary
Interface PascalCase IPrintable, ICloneable should be started with ‘”I”
Enum PascalCase EmployeeType
Categories: ASP.NET

Dynamic Ajax Content

March 25, 2010 Leave a comment

This script uses Ajax to enable you to load external pages into a DIV without having to reload the browser or use IFRAMES. If your external pages reference any external .css or .js files for styling, this script can also load and apply them to the page on demand.

Step 1: Insert the below script into the JabvaScrip tag of the HEAD section of your page:

(here i created an test.html)

var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)

var loadedobjects=”"

var rootdomain=”http://”+window.location.hostname

var bustcacheparameter=”"

function ajaxpage(url, containerid){

var page_request = false

if (window.XMLHttpRequest) // if Mozilla, Safari etc

page_request = new XMLHttpRequest()

else if (window.ActiveXObject){ // if IE

try {

page_request = new ActiveXObject(“Msxml2.XMLHTTP”)

}

catch (e){

try{

page_request = new ActiveXObject(“Microsoft.XMLHTTP”)

}

catch (e){}

}

}

else

return false

page_request.onreadystatechange=function(){

loadpage(page_request, containerid)

}

if (bustcachevar) //if bust caching of external page

bustcacheparameter=(url.indexOf(“?”)!=-1)? “&”+new Date().getTime() : “?”+new Date().getTime()

page_request.open(‘GET’, url+bustcacheparameter, true)

page_request.send(null)

}

function loadpage(page_request, containerid){

if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf(“http”)==-1))

document.getElementById(containerid).innerHTML=page_request.responseText

}

function loadobjs(){

if (!document.getElementById)

return

for (i=0; i

var file=arguments[i]

var fileref=”"

if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding

if (file.indexOf(“.js”)!=-1){ //If object is a js file

fileref=document.createElement(‘script’)

fileref.setAttribute(“type”,”text/javascript”);

fileref.setAttribute(“src”, file);

}

else if (file.indexOf(“.css”)!=-1){ //If object is a css file

fileref=document.createElement(“link”)

fileref.setAttribute(“rel”, “stylesheet”);

fileref.setAttribute(“type”, “text/css”);

fileref.setAttribute(“href”, file);

}

}

if (fileref!=”"){

document.getElementsByTagName(“head”).item(0).appendChild(fileref)

loadedobjects+=file+” ” //Remember this object as being already added to page

}

}

}


Step 2: Once that’s done, simply create links that will load an external page into the desired DIV or container using one of the below syntax:

href=”javascript:ajaxpage(‘test.htm’, ‘contentarea’);”

Categories: Freaky But Tricky Tags:

ASP.NET Web Site Types

March 25, 2010 Leave a comment

As a Beginner i was little bite confused when created a Project. Asked many one but no one give me a clear answer about what does it mean by those Local Host,FTP and Remote Site. So here i am now and going to tell the beginners that they are types of  ASP.NET websites. Now i am going give you a brief discussion on them:

Local IIS sites:

Local IIS sites run on your computer, handled by Internet Information Services. They are a good way to test a web site in an IIS environment, or for example, in the case of intranet sites.

In order to use local IIS sites, you must meet the following prerequisites:

  • IIS 5.0 or later installed.
  • .NET framework 2.0 or later.
  • ASP.NET enabled on local IIS.
  • Administrative privileges on local computer.

Creating local IIS sites:

Visual Studio handles the task for you, when you create a local IIS site.

Running local IIS websites:

By default, simply enter: http://localhost/YourSiteName/APage.aspx

File-System based sites:

With this project type, a website is stored on the file system. It is handy, when IIS is not installed, or when multiple developers must access the same files, in classroom settings, etc.

For testing file system sites, a Web server (included in Visual Studio) must be used.

FTP sites:

In this case, the sites are stored on a remote FTP server, and you can communicate with it using Visual Studio. You open the project, and then modify it, and VS takes care of synchronization, etc.

Active and Passive FTP mode:

  • Active FTP is for server admins, the client initializes a port for the command, and passes the address of it for the server, which attempts to initialize a port on the client for the data. This will likely fail, if the client has a firewall configured.
  • Passive FTP is for the clients. Both ports will be initialized by the client, thus avoiding the interruption by the firewall.

FTP credentials:

In most cases, when you attempt to connect to an FTP site, you must specify valid credentials. Be aware, that these credentials are passed to the server in clear text format, thus be likely the target of interception.

FTP files are cached by VS when editing them. This can cause versioning conflicts when two or more developers edit the same FTP site.

Remote sites:

Alternatively to an FTP server, you can also use a remote IIS server to publish your application on it. Although it’s a requirement for the server that FrontPage Server Extensions must be installed on it. Also, the same prerequisites exist as at the local IIS site, namely: IIS 5.0 or later, .NET 2.0 or later must be installed, and ASP.NET pages must be enabled on the server.

The creation of this type is simply as any other, Visual Studio transparently does the heavy setup work, and you can concentrate on the development.

All of them have some pros & cons:

  • Local IIS site:
    • Benefits: testability in IIS environment, site is accessible from other computers
    • Disadvantages:  demands administrative rights, can be debugged only by one user
  • File-system based site:
    • Benefits: security, no IIS needed, no administrative rights needed, multiple users can debug it at the same time
    • Disadvantages: cannot be tested in IIS environment
  • FTP site:
    • Pros: site can be tested on the server where it will be used
    • Cons: site exists only in the server; this project type cannot be created, only opened.
  • Remote site:
    • Pros: testability, access for multiple developers
    • Cons: debugging issues.
Categories: ASP.NET

Configure Projects

March 25, 2010 Leave a comment

There are four project types for creating a web application in Visual Studio, which you should be familiar with for this exam. Namely: ASP.NET Web Site, Empty Web Site, ASP.NET Web Service, and ASP.NET Web Application. I will cover ASP.NET Web Site, and ASP.NET Web Application.

ASP.NET Web Site:

This project type is file-based, and there is no project file included. So every file- whatever its extension would be- in a given folder is the part of your project. This is the default web site project type in Visual Studio (simply click on the New Web Site button on the menu (represented as an Earth globe).

This template generates a web.config file with some initial entries, and a Default.aspx page with the given code-behind file for you. Also an App_Data folder will be included to help you begin your work. The above mentioned Empty Web Site project is exactly the same as this project type, the difference is that you won’t get any content generated at startup.

ASP.NET Web Application:

You can understand the Web Site project type deeper in contrast with an ASP.NET Web Application project. If you’ve ever programmed a Windows Forms Application, you’ll find this project type very familiar. You can set references on assemblies, control the assembly information of your project with the AssemblyInfo.cs file. This type also generates .designer files for your web forms.

This project type includes a project file for your application, and only the files referenced in it will be the part of your web application, whatever else may reside in your project directory.

The compilation of a Web Application project is called classic compilation. All the files, which represent your UI (.aspx and etc) are published without compilation, thus compiled dynamically when the first user requests the page. The code files will be compiled to a single assembly, so you won’t be able to change them later.

Adding References

There are two different scenarios of adding references to assemblies, depending on which project type you use. In the case of a Web Application, simply right click the references folder, and select add reference. Because Visual Studio is responsible for compiling this type, it simply includes your reference in the project file.

When you use a Web Site project type, adding a reference is also very easy, just click on the project name in solution explorer, and select add reference. Because this type of project is compiled by ASP.NET (and not Visual Studio), the web.config file will be modified to include your reference, in the following way:

<compilation>
<assemblies>
<add assembly=”MyAssembly” …./>
</assemblies>
</compilation>

Of course, you can do this manually.

Be aware of that when you add a reference to an assembly, which isn’t included in the Global Asembly Cache, Visual Studio will generate a Bin folder in your project, and place the referenced assembly there, regardless of the project type you use. If you’ve added custom assemblies to your GAC, and reference them in your project, then you should include that assembly into your applications Bin folder, and set a reference to that copy. In this manner, you can use the XCOPY or the Copy Web Site tool to deploy your application.

Categories: ASP.NET

ASP.NET Tracing

March 25, 2010 Leave a comment

With tracing, you can access data from a running application, with the help of a browser. In ASP.NET, you can access to the following information:

  • The details of the request
  • Trace information: performance information of the Web page’s life cycle events
  • Control tree: size information about controls.
  • Session state: displays session variables and values
  • Application state: displays application variables and their values
  • Request cookie collection: list of cookies passed to the server as part of the request
  • Response cookie collections: list of cookies passed to the browser as part of the response
  • Headers collection: the list of HTTP headers sent with the request
  • Form collection: postback values.
  • QueryString collection: the variables of the query string.
  • Server variables: all server variables.

To enable tracing, you have two options: enable tracing for single pages, or for the whole application. To enable page tracing, you should set the Trace property to true in the @Page directive. Also, you can set it in code-behind, with the Page.Trace.IsEnabled = true; syntax. At page level, you can also include a TraceMode property, which sets the sort order of trace information, by time, or by category. When you set tracing at the page level, the trace output will be added to your page, so never implement this behavior in production applications.

To enable tracing for the whole application, you should modify the web.config as follows:

<system.web>
<trace ebabled=”true” requestLimit=”100” pageOutput=”false” ceMode=”sortByCategory”  localOnly=”true” mostRecent=”false” />
</system.web>

Attributes of Trace
Enabled Enable or disable tracing on the application level. This behavior can be overridden by independent pages, using the @Page directive. To enable tracing on specific pages, when application-level tracing is disabled, set the pageOutput attribute accordingly.
traceMode The possible values are SortByTime, which sorts the tracing information by time, or SortByCategory.
localOnly Decides whether tracing information should be provided just for local clients, or everyone else. Always set to true when publishing your application.
pageOutput Determines whether the tracing information should be included for pages or not. When set to false, you can view trace data in the Trace.axd site on the root level.
requestLimit Specifies the number of HTTP requests to be traced. Maximum us 10.000. Works only when application level tracing is enabled.
mostRecent Determines whether the most recent number of HTTP request should be stored in the trace information, or only the first requsetLimit number of requests.
writeToDiagnosticsTrace If set to true, tracing information will be forwarded to any trace listeners signed up to your application.

When enabled, application-level trace information can be viewed by requesting Trace.axd in the root of the application.

You can add your own tracing messages to the output, simply calling Trace.Write(string Category, string Message) or Trace.Warn(string Category, string Message). The only difference between the two is that Trace.Warn shows your message written with red letters.

Categories: ASP.NET Tags: ,
Follow

Get every new post delivered to your Inbox.