i am very confident, smart, and caring too. i belives in Truth. Friendship is the Main element of my nature, i need a Very Good Friend as my Life Patner. i want to live every moment of my life, i want to keep my family members happy. i like to watch listen Musics (soft). my friends always use to ask every Decision about them, they think that i am brainy.
Thursday, June 07, 2007
Close your eyes and make a wish…. Angels will b there to blow u a kiss… They’ll guide u and make all your dreams come true … Just like they did for me when I asked for a "SWEETHEART" like u...
You’re the air, babe, that I breathe You’re the strength that I always need You’re the light in my eyes My shining star, yeah, hea
You guide my way You have to promise me that you will stay Always and forever Just you and I
Angel You’re my angel Oh, whoa (Yeah, hea) You’re my angel (You’re my angel, baby) Alright
Angel [My angel] You’re my angel Whoa, whoa You’re my angel (You’re my angel, baby)
Girl, you know that, trust me I’ll be right here and you can count on me With a hand to hold And with open arms (Oh, whoa)
Every day, every night I will always be your guidin’ light Always and forever Just you and me (My angel)
Angel You’re my angel Oh, whoa (Oh, oh) You’re my angel (Yes, you are, yes, you are)
Angel [My angel] You’re my angel Whoa, whoa You’re my angel (Yes, you are, yes, you are)
You’ll be the one Ooh, the one that I need, oh And you are my angel, my guiding light
Oh, whoa Oh, whoa Oh, whoa
Angel [My angel] You’re my angel Oh, whoa (Oh, whoa) You’re my angel (Yes, you are, yes, you are)
Angel [My angel] You’re my angel Whoa, whoa (Oh) You’re my angel (My angel)
Angel My angel You’re my angel My shining star Oh, whoa I promise you You’re my angel Forever and ever
Angel My angel You’re my angel The air that I breathe Oh, whoa My only love You’re my angel You’re my angel forever.
YOU CAME INTO MY LIFE LIKE AN ANGEL - LOOKING FOR SOMETHING NEW YOU SAID HELLO AND THEN SOMETHING HAPPENED - A WHOLE DIFFERENT AVENUE I TOOK YOU IN MY ARMS AND IT FELT GOOD JUST SUPERNATURAL
LETS GUESS WHAT LOVE IS ALL ABOUT OH BABE JUST COME DOWN OFF YOUR CLOUD AND MAYBE I WILL REALIZE THAT YOURE A DEVIL IN DISGUISE
SO LET ME FEEL THAT HEAVENS ALL THAT REAL AND MAKE ME BREAK THE SEAL JUST BE THAT ANGEL IN MY BED BABY SPREAD YOUR WINGS LETS DO SOME SPECIAL THINGS YOURE ALL IVE NEVER HAD YOURE THAT ANGEL IN MY BED BABY
THE WAY YOURE KISSING ME MAKES ME WONDER IF ITS REALITY THE WAY YOU CHANGE MY DREAMS MAKES ME HOPE THAT YOULL STAY FOREVER
LETS GUESS WHAT LOVE IS ALL ABOUT OH BABE JUST COME DOWN OFF YOUR CLOUD AND MAYBE I WILL REALIZE THAT YOURE A DEVIL IN DISGUISE
SO LET ME FEEL THAT HEAVENS ALL THAT REAL AND MAKE ME BREAK THE SEAL JUST BE THAT ANGEL IN MY BED BABY SPREAD YOUR WINGS LETS DO SOME SPECIAL THINGS YOURE ALL IVE NEVER HAD YOURE THAT ANGEL IN MY BED BABY
I KNOW YOULL FLY AWAY NO CHANCE TO STOP YOU COS ANGELS NEVER STAY THEY LEAVE YOU WHEN YOU FALL IN LOVE
OH LET ME FEEL THAT HEAVENS ALL THAT REAL AND MAKE ME BREAK THE SEAL JUST BE THAT ANGEL IN MY BED BABY SPREAD YOUR WINGS LETS DO SOME SPECIAL THINGS YOURE ALL IVE NEVER HAD YOURE THAT ANGEL IN MY BED BABY
=================================== You're my angel in the night you're everything i think of everything i dream of. Yours is the voice i hear when The moon steals the day.
Yours is the voice i hear when the sun sneaks in to warm me. When my heart aches with lifes pains, you are my angel.
I never expected someone like you. Someone kind and loving as you. You snuck into my life like a true angel in the night. Loving you is the only thing that brought me this far.
Cuz' your my angel in the night.
=========================================== If I should stay.. Well I would only be in your way... And so I'll go and yet I know.. That I'll think of you Each step of my way...
And I will always love you.. I will always love you..
Bittersweet memories.. That's all I have and All I'm taking with me.. So goodbye, please don't cry.. Cause we both know that I'm not what you need...
But I will always love you.. I will always love you..
And I hope life will treat you kind.. And I hope that you have All you ever dreamed of.. Oh, I do wish you joy.. And I wish you happiness.. But above all this, I wish you love.. I love you.. I will always love you...
I, I will always, always love you.. I will always love you.. I will always love you... I will always....
This happens to be my all time favorite song and it is dedicated to everyone I have loved as well as to everyone I will love in the future.
But most of all, it is dedicated to my “ANGEL”. I like her because she LOVES me A LOT.
I love you with all of my being, my “ANGEL”! ===========================================
================================== My sweet beautiful angel. Sent to me from above. I am so grateful to have found you, and I give you all my love.
You must have come from heaven, because you have pretty little angel eyes. When you gaze at me with them, my heart begins to fly.
Your sweet angelic voice, continuously rings in my ears. With you by my side, there is nothing I fear.
Whenever we are together, You shine with a heavenly glow. Your beautiful angel face, raises me up from feeling low.
Yes, heaven is missing an angel, because you are here with me. You're my sweet, beautiful angel, and I'll love you for eternity! ==================================== As I slowly drift off, deep into my dreams. I sleep with a smile, surely must do it seems, For I meet an angel one as white as snow, My one true love, that I adore worship so. In sleep we both let ourselves ever be taken, Away from the morning before we & primal awaken. We cherish these endless times that we share, In dreams we can travel to almost anywhere. A romantic beach or maybe a beautiful shore, We travel eternity it seems and much more. We even take flight on Angel & prime’s very wings, Cherishing and nurturing joys that we bring. We can go anywhere, to all places unknown, Taking pleasure, time, as loves seeds are sown. But gradually slipping from each others sight, Our eyes slowly open, to the dawn of daylight. Kisses cuddles not wishing to let one another go The sweetest feeling only true loved one ’s know The awakening brings us back down, to reality, But our hearts know that later, together we’ll be.
It's so hard to say How a love could end this way The one that used to care for you Just turns and walks away And it's so hard to find To leave the pain behind When all the things you're looking for Your heart can't seem to find
-chorus- I'll be the air that you breathe I'll give the strength that you need I'll be the light in your eyes When hope becomes hard to see I'll be your shining star To guide you wherever you are And I promise that I'll be by your side Always you and I
No, you're not alone Without a love to call your own 'Cause I'll always be right there for you To help you carry on A heart that's always true Girl, I'm giving mine to you And everything you'll ever need I promise I will do
Girl, you know I'll stay beside?- I will be right there for you With a hand to hold A heart to see you through 'Cause each and every night I will make you right When life feels so wrong 'Cause in my arms is where you belong
Thoughts of you run through my head Every minute, every hour, of everyday At night I wake with such a fright Dreaming of you not being there What would I do if you were gone
You are thought of in every emotion
When I smile it is because you have brightened my day When I cry it is because you are not there When I frown it is because you are sad When I laugh I am laughing with you When I am happy it is because I know you are there
Please know you are my reason for living
You are in the deepest part of my heart Just remember and always know, You are the love of my life No one else means more to me than you!
Love is the tenderness in your loving touch. Love is not needing the last word in an argument. Love is looking at your own faults instead of mine. Love is sacrificing instead of demanding.
Love is being there during the bad times too. Love is caring when I'm sick. Love is being faithful to our union. Love is the honesty and respect you show me.
Love is giving instead of taking. Love is making me laugh when I'm depressed. Love is giving me comfort when I'm sad. Love is sharing important decisions.
Love is forgiveness when I need it. Love is being committed to our relationship. Love is accepting me as is instead of trying to change me. Love is holding me and crying with me.
You have blessed my heart and our love with all of these. My prayer is to return the same precious love to thee.
What Is Stress? Stress is the emotional and physical strain caused by our response to pressure from the outside world. Common stress reactions include tension, irritability, inability to concentrate, and a variety of physical symptoms that include headache and a fast heartbeat. It's almost impossible to live without some stress. And most of us wouldn't want to, because it gives life some spice and excitement. But if stress gets out of control, it may harm your health, your relationships, and your enjoyment of life. Examples of "overload" situations are common in today's world: You and your spouse both work full time while you are raising your family. At the same time, your parents are retired, in ill health, and are dependent on your help with shopping and running errands. You are a single person living alone, and your salary isn't rising as fast as the rate of inflation. It's getting harder each month to pay the bills. You are a divorced parent and share the custody of your children with your former spouse. But the friction between the two of you on matters concerning the children is becoming more bitter and more frequent. The expectations and competition at your workplace is becoming fierce. You find yourself coming in early, staying late, and taking on more work than you can handle. Managing stress involves learning about: How stress affects the mind and body How to identify the warning signs of stress How to develop good stress-management techniques When to seek professional help What Are The Signs Of Stress? Stress can cause both mental and physical symptoms. The effects of stress are different for different people. The mental symptoms of stress include: Tension Irritability Inability to concentrate Feeling excessively tired Trouble sleeping The physical symptoms of stress include: Dry mouth A pounding heart Difficulty breathing Stomach upset Frequent urination Sweating palms Tight muscles that may cause pain and trembling Nice To Know: Many addictions are linked to a stressful lifestyle, such as overeating, smoking, drinking, and drug abuse. These are used as an escape or a temporary way of "switching off" - but they do not address the underlying problem.
What Causes Stress? We may think of stressful events as unpleasant ones, such as losing a job or having difficulties at home or at school. But changes for the better can also cause stress, like a new baby, a wedding, and a new house. In an ideal world, maybe we could get away from stressful situations, or change them. Too often we can't do that - but we can learn to control our response to those situations. And we can develop techniques that will reduce the effects of stress on our mental and physical health. What's Stressful For You? What's stressful for you may be quite different from what's stressful to your best friend, your spouse, or the person next door. For example: Some people enjoy speaking in public; others are terrified. Some people are more productive under deadline pressure; others are miserably tense. Some people are eager to help family and friends through difficult times; others find it very stressful. Some people feel comfortable complaining about bad service in a restaurant; others find it so difficult to complain that they prefer to suffer in silence. Some people may feel that changes at work represent a welcome opportunity; others worry about whether they'll be able to cope. Nice To Know: Q: Are some people more vulnerable to stress than others? A: Yes. Personality type plays a role in reaction to stress. For example, people who drive themselves hard and are impatient (sometimes called Type A personalities) may be more at risk for stress-related physical problems. Certain occupations, such as law enforcement or air traffic control, are clearly more stressful than others. In addition, people with a personal or family history of mental illness may be affected more by stress.
What Are Your Personal Signs Of Stress? People react to stress in different ways. Once you identify your own signs of stress, they can serve as your personal early warning system. Think of yourself as a car that's equipped with lights and gauges to warn you if any problems are developing. If you keep an eye on the gauges and catch the trouble early, the problem may be easy to fix. If you ignore the warning signs, you may be in for a major repair job. You should assess yourself for four types of stress signs: Changes in body functions and physical health Changes in emotions and feelings Changes in behavior Changes in thoughts Use these checklists to identify your own signs of stress. There is space on the checklists for a second opinion, because people close to us may notice changes that we are not aware of. Changes in body functions and physical health Do you get more: Are you having this sign of stress? Has some one else noticed you have this sign? Backache Muscle tension Nervous stomach Breathing problems Frequent urination Fatigue Dizziness
Changes in emotions and feelings Do you feel more: Are you having this sign of stress? Has some one else noticed you have this sign? Irritable Sad Worried Tense Angry
Changes in behavior Are there changes in how much you: Are you having this sign of stress? Has some one else noticed you have this sign? Sleep Eat (too much or too little) Want sex (less or more than before) Drink alcohol Use drugs
Changes in how you think Are you finding it harder to: Are you having this sign of stress? Has some one else noticed you have this sign? Remember things Concentrate Look on the bright side Do you find yourself feeling: Helpless Hopeless
Now go over the lists, and pick out the signs of stress that you consider the most important - the ones that are really interfering with the way you function and enjoy life. Then mark on the next chart whether they are related to your body, your feelings, your behavior, or your thoughts.
How Does Stress Affect The Body? To understand what stress does to us, imagine you lived tens of thousands of years ago, at a time when humans were threatened by hungry animals such as saber-toothed tigers and wolves. Our caveman ancestors had to be able to react instantly, either by fighting the beasts or running away. So humans evolved the ability to respond to a stressful situation instantly, by preparing the body for "fight or flight." Under sudden stress, you will get a burst of exceptional strength and endurance, as your body pumps out stress hormones: Your heart speeds up Blood flow to your brain and muscles increases up to 400 percent Your digestion stops (so it doesn't use up energy that's needed elsewhere) Your muscle tension increases You breathe faster, to bring more oxygen to your muscles Sometimes we can still benefit from this "fight or flight" response - like the case of a mother whose child was pinned under a concrete slab during a tornado. Under stress, she found the strength to lift the huge slab with her bare hands, even though it later took three men to move it. But much of the time in modern life, the "fight or flight" response won't help. Yet those stress hormones still flood your system, preparing you for physical action. And if you are under stress frequently, it can harm your physical health.
How Stress Can Hurt Us It has been estimated that two-thirds of all visits to physicians are for stress-related problems. Recent evidence indicates that the physical changes associated with stress may contribute to the leading causes of death - heart disease and cancer. The effects of stress include the following: Stress can cause chronic fatigue, digestive upsets, headaches, and back pain. Stress can affect the blood cells that help you fight off infection, so you are more likely to get colds and other diseases. Constant stress can increase blood pressure and can increase the risk for stroke. Stress can increase the danger of heart attacks, particularly if you are often angry and mistrustful. Stress can make an asthma attack worse. Stress triggers behaviors that contribute to death and disability, such as smoking, alcoholism, drug abuse, and overeating. Stress can lead to diminished sexual desire and an inability to achieve orgasm. Stress makes it harder to take other steps to improve health, such as giving up smoking or making changes in diet. Dealing With Stress One method of stress management is called the TARP method, and it has been proven effective for many. A tarp is a protective cover thrown over something - a car or boat, for example - to protect it from the elements. Likewise, the TARP method offers a form of protection, too - protection against the distressing and sometimes harmful effects of stress. The TARP method teaches simple techniques that can be used any time, anywhere, to control your response to stressful situations. It consists of four steps: T is for "Tune in" - Get into the habit of noticing early signs of stress. A is for "Analyze" - Think about the source or causes of your stress. R is for "Respond" - Deal with the cause of your stress, and its effects on you. P is for "Prevent" - Develop good stress-reduction habits for a healthier lifestyle. In addition to the TARP method, other activities and methods also can help manage stress. "Tune in" Tuning in is important, because if you don't tackle your stress early, it can interfere with your sense of well being and your health almost before you know it. And the effects of stress often get worse as time goes on. Whenever you notice yourself feeling the beginnings of stress - for example, when you feel irritable, tense, distracted, or fatigued - scan yourself for signs of stress. How-To Information: Follow these four steps to scan yourself for signs of stress: 1. Scan yourself for physical signs of stress, starting with your head and working down. For example: Do you have muscle tension? Do you have sweaty palms? Do you have rapid breathing or rapid pulse? 2. Scan your behavior for signs of stress. For example: Are you pacing or fidgeting? Is your voice too tense, too loud or too quiet? 3. Scan your emotions, remembering some feelings that may be in the background. For example: Do you feel nervous, moody, depressed? Do you feel frustrated? Do you feel lonely? 4. Scan your thoughts and thinking patterns. For example: Are your thoughts always turning to your worries? Are you having trouble with concentration or memory?
Learning to spot signs of stress instantly can take practice. But if you make a point of scanning your body, behavior, feelings, and thoughts regularly, it will get easier. Nice To Know: Some people may find that a single sign will always tip them off that they are under stress. For example, they may notice that they always start to sweat, or tap a foot, or talk fast. Other people may have a "menu" of warning signs, any one of which could alert them to the beginning of stress.
"Analyze" Once you know how to "tune in" to your signs of stress, you will be better able to analyze the situations that are stressful to you. These "stressors," as they are called, could be either external or internal. External stressors are things and events outside your body that can make you feel threatened or out of control. For example: Physical irritants like noise, pollution, heat, or humidity Work demands or conditions Frightening events, like narrowly escaping a traffic accident Social or family demands, changes, or problems Internal stressors result from one's own attitudes and thinking patterns. For example: Do you always talk to yourself with words like "should, must, and ought?" Do you feel like a failure if you are late, or if things don't go as planned? Do you have "me last" syndrome, feeling you have to look after everyone else's needs before you think of your own? Do you feel worthless unless everyone likes you all the time? Are you guilty of "awful-izing," which means always expecting the worst? For example, if family members are late, do you often imagine they are injured or dead? Need To Know: Sometimes, your body itself can cause stress. For example, it is stressful to have to live with constant backache or other nagging sources of pain. Or, if you are not sleeping well (perhaps because of stress), you may be more stressed than ever the next day because you are so tired.
How-To Information: A stress diary can be helpful in the analyzing stage. For one week, write down all the stressors you can identify. Don't leave anything out. Here's an example:
"Respond" "Responding" in the days of early man meant fighting the source of stress or running away from it. Your body will still produce a physical "alarm response" that pumps stress hormones through your body, tensing your muscles and speeding up your heart. This "alarm response" in most cases doesn't do us any good - and it can be harmful. You can learn to turn off the alarm response and regain control. You can learn to respond calmly, and deal actively and positively with your stress, whether it is caused by outside or internal factors. Four useful techniques for responding calmly are: 1. Time out. A brief time out is the simplest possible approach to stress: Stop the activity (or the conversation) that was causing you stress. If you can move away, go to another room, or go for a short walk. If you can't move away, count to 10 silently before you speak again. 2. Breathing. You can often tell if people are under stress because of the way they are breathing. For example, customs officers have noticed that smugglers are the people taking fast, shallow breaths. If you learn to control your breathing, it will help you regain control over the effects of stress. Watch babies breathing; their abdomens expand when they breathe in. Watch a tense adult breathing; there may be no movement of the abdomen. All the work is being done by the chest. Abdominal breathing can be very soothing, because it slows you down. It is also efficient, bringing a good supply of oxygen to your brain. Prepare for stressful times by practicing your breathing now: Check your breathing pattern by putting one hand on your chest and one hand on your stomach. If your lower hand moves and your top hand does not, you are doing abdominal breathing. But if your top hand moves and your bottom one does not, you are doing chest breathing. To do abdominal breathing, get your stomach relax. Breathe in deeply, then breathe all the air out. Let your lungs fill with air again naturally, while your stomach expands. Practice this "belly breathing" whenever you have spare time (for example, while you are driving). Whenever you are stressed, worried, or tense, use your breathing to help calm yourself down. Take a deep breath and quietly let it go out completely, then let your abdomen expand as the air comes back into your lungs. Keep noticing your abdominal breathing for another few breaths. For a variation on this breathing technique, try "10-to-one countdown" breathing: Start with abdominal breathing, letting all the breath out and then allowing your abdomen to expand as your lungs fill up again. When you breathe out again, say "10," letting go of tension as if it is being carried out of your body with the air. Next time you breathe out, say "nine," and so on, all the way down to "one." When you get to "one," start again. Each time you breathe out, tell yourself you are letting go of tension. Many people repeat this sequence slowly for a period of 15 to 20 minutes. They find that with each new countdown, they reach a deeper level of relaxation. When we are under stress, we often feel things are happening too fast. Another technique, called slow-down breathing, can help you get settled down and in control. It starts with abdominal breathing, and uses cue words to help you focus and clear your mind. Examples of cue words are: As you breathe in, silently say "calm" As you breathe out, silently say "smiling" As you breathe in, say "present" As you breathe out, say "now" Practice breathing techniques for five or 10 minutes until you get the feel of it, then again several times a day for a few moments. Then it will be instantly ready to use as a "mini-tranquilizer" whenever you notice yourself starting to feel tense or out of control. 3. Progressive muscle relaxation. This technique will help you get rid of the muscle tension that is a major sign of uncontrolled stress, and which can lead to headaches, back pain, and muscle pulls. It is based on the principle that muscles go to a deeper level of relaxation after they have been tensed. Lie on the floor or on a firm bed, or sit in a chair that has good head support. Close your eyes and breathe deeply two or three times. Next, tighten up the muscles of different parts of your body in turn; keep them tight while you count silently to five; then let go and imagine the tension going out as you relax and smooth the muscles. Start with your face. Squint your eyes, tighten your teeth and jaw, and wrinkle your forehead. Feel the tension while you count silently to five, and then let go of it. Feel the warmth of relaxation coming to your face. Next, pull your shoulders up until they nearly touch your ears. Feel the tension while you count silently to five. Then let go. Now progress through the rest of your body, tightening muscles while you count slowly to five, then letting the tension go. Start with your stomach and chest muscles, then your lower abdomen, buttocks, and thighs. Finish with your lower legs, curling up your toes and tightening calf muscles to feel the tension in your foot, ankle, calves, and knee. When you have finished, notice the tension and release in all your muscles. Breathe deeply a few times, and feel relaxed, refreshed, and comfortable. 4. Thought-stopping. This is a good technique for dealing with stress that comes from your own negative feelings. When you notice negative thoughts, just say "stop!" to yourself. It may sound too simple to be effective - but it works, even though you may have to repeat the word several times until the negative thoughts are interrupted. Sometimes, using mental images can help you stop the negative thoughts: Imagine that the negative thoughts are coming from a tape recorder, and that you can push the "stop" button or turn down the volume to zero. Imagine sticky paper that catches your negative thoughts as they fly about. Imagine a "stop" sign that blocks your negative thoughts. Imagine a box that your negative thoughts get trapped in. Imagine you are driving through a car wash that washes the thoughts away. Need To Know: And the secret is... The secret to making these four "respond" techniques work is to practice them several times a week, until you feel comfortable. Then use them. And don't give up on them too soon. All too often, people will only try something a couple of times and give up after a few days. It may take a while before you are getting the full benefit of these techniques.
"Prevent" There are simple things you can do to help your body and mind withstand stress. These will help you improve your immune system, your energy level, your self-esteem, and your sense of well-being. 1. Relaxation. Relaxing regularly will help prevent stress. Set aside just 15 minutes every day, whether you are feeling stressed or not. Go through whatever relaxation procedures work best for you. Techniques such as yoga and stretching can be effective, as can progressive muscle relaxation . 2. Regular exercise. If you know people who run, swim, or bicycle regularly, you may notice that they have less stress than others. When your body is in first-class condition, your mind and emotions will also benefit. Regular exercise is one excellent way to "stress-proof" yourself, or at reduce the bad effects of stress. Exercise can make you look better, sleep better, concentrate better, and withstand disease better. It will also improve your mood and make you feel better about yourself. The best exercise for stress-proofing is aerobic activity, which uses your whole body. This includes jogging, bicycling, brisk walking, cross-country skiing, aerobic dancing, swimming, rowing, skating, and stair-stepping. If you are not used to exercise, start with walking. Walk briskly for about 20 minutes, three times a week. As you get in shape, take longer walks, or switch to a more vigorous form of activity. If you don't have access to a lake, mountain, or country road to row, ski, or bike on, substitute on machines at home or in a gym. But whenever you can, get out into nature. The quietness and change of scene will help your stress levels.
Need To Know: Some exercise safety tips: If you are over age 35 and not used to vigorous exercise, check with a doctor before you start, or stick to walking. Begin every exercise session slowly (including walks), and don't speed up until your muscles are warm. Don't race. Take the talk test. If you don't have enough spare breath to hold a conversation, slow down. At the end of your exercise session, walk around slowly for a while to cool down.
3. Eating right. You will be much better able to withstand stress if your body feels good, and it can't feel good if you don't feed it properly. Make sure you have three good meals a day, with plenty of fruit, vegetables, and filling food like bread, rice, or noodles. If you get hungry between meals, plan for a nutritious snack like fruit, yogurt, or a bagel. If you take a snack to work with you, you won't be tempted by junk food. Eating well will give you a sense of control that can help to reduce your stress levels, as well as making you feel good physically. 4. Chemicals: alcohol and drugs. People may be tempted to take a drink or drugs to deal with stress. It doesn't help. Alcohol may seem to calm you down, but it only masks the symptoms of stress for a while. Excessive alcohol (and drugs) will give you a rebound; you are likely to feel more stressed than ever when the effects wear off. One or two drinks a day, such as a glass of wine or beer with dinner, usually won't harm you. If you are regularly drinking much more than that, cut down - and if that is hard to do, get some help. 5. Tobacco. People often say that a cigarette "calms their nerves," but tobacco is really a stimulant. If you are afraid that quitting would cause you too much stress, talk to your doctor about prescribing a nicotine patch or gum to help ease the difficulty of withdrawal. Patches or gum work best if you also join a quit-smoking group or use a good self-help program that helps you learn to be a nonsmoker. In the long run, you will become a calmer person if you stop smoking.
6. Caffeine. People have different reactions to caffeine, and most people can take two or three cups of coffee or tea a day without trouble. But you might try cutting down your caffeine intake, to see if you are less jumpy. (If you get a headache for a few days, don't worry; that's a normal withdrawal symptom, and it will go away within a week.)
Other Ways To Manage Stress In addition to the relaxation practices described in the "TARP" method, there are many activities and methods that can help manage stress. These include: Humor Hobbies Meditation Biofeedback Massage therapy Humor Many stress-management experts recommend keeping a sense of humor during difficult situations. Laughing releases muscle tension and helps a person maintain perspective. Activities as simple as watching a funny movie, listening to a tape of a comedian's routine, or sharing time with a humorous friend can provide a psychological lift and relieve stress. Hobbies Regular leisure activities are important in reducing stress. Many people benefit from making time for positive leisure pursuits rather than, for example, spending time watching television in the evening (although that, too, can be relaxing to some degree). Relaxing hobbies include gardening, painting, bicycling, photography, carpentry, collecting, and many others. In order to obtain the most relaxation and enjoyment, the satisfaction should come in doing the hobby, not in the results. An individual who pursues gardening for relaxation may not grow prize-winning vegetables, but they can be eaten. An amateur photographer may not sell photographs, but they can be admired by friends and family. Meditation Used for many years in Eastern cultures, meditation is becoming more widely accepted in the U.S. as a relaxation technique. Meditation reduces heart rate, blood pressure, adrenaline levels, and skin temperature. There are a variety of meditation techniques that share a common goal: to achieve relaxation by clearing the mind of stressful outside interferences. Meditation involves achieving a state of consciousness in which the individual focuses on a single thing, such as a key word, sound, or image. Meditation techniques rely on quiet surroundings, sitting still, and a repetitive mental pattern. Various techniques are taught in instruction books and through religious and nonreligious organizations. Biofeedback Biofeedback provides a way for people to learn to control activities over which they normally have no awareness, such as heart rate and muscle tension. It is considered by many health professionals to be a valuable therapeutic tool for reducing stress. Biofeedback involves no discomfort and no risk. Biofeedback relies on sensitive electronic equipment. Sensors are placed on the body at various locations to measure skin temperature and muscle activity. The sensors are attached to a monitor that detects fluctuations when a person is anxious and displays signals in the form of beeps or light flashes. By watching the monitor, a person learns to control these stressful responses. Massage Therapy Massage is the gentle practice of manipulating the body's tissues in order to soothe and heal. It is one of the most ancient of the healing arts, and more people today are relying on it for natural, drug-free relief from the effects of busy, overstressed lives. Massage can relax the entire body and provide new energy that lingers long after the massage is over. A number of research studies have shown that massage reduces heart rate, lowers blood pressure, increases blood circulation and lymph flow, relaxes muscles, improves range of motion, and increases the production of endorphins, which are the body's own natural painkillers. There are a number of massage therapy techniques, including Swedish massage and Shiatsu. Massages can be for the full body or particular areas of the body, such as the back and shoulders. Some people choose to wear some clothing during a massage; others prefer to undress or use a dressing gown. During a massage, the person is warmly covered, and only the part of the body on which the therapist is working is uncovered. Need To Know: A word about medication Medication can be useful for dealing with short periods of acute stress, where the anxiety is severe and disabling, to help people regain control and begin coping. It can relieve symptoms temporarily, but it does not address the underlying problem.
When To Get Extra Help Self-help techniques for stress management have tremendous potential. They are easy to use, they're economical, and they are good for your general health. However, there may be times when you need other help in dealing with stress. To help you decide if you need additional help, here are some questions to ask yourself: Is stress really the problem? Sometimes, people may be too quick to blame stress if they are tired, or their backaches, or they are having trouble eating or sleeping. Check with your doctor to rule out physical reasons for these symptoms before you conclude that they are caused by stress. Is it more than stress? You may have psychological problems that are more complicated than stress. If you are frequently depressed, often feel panic, or think you may have a phobia (an abnormal fear of an object, experience, or place), consult a doctor or psychologist. Do you need technical help? Technical help can come in the form of books, videos, consultations with experts or the leader of a stress-management group. Here are some suggestions. Consultation With An Expert You may want the guidance that comes from individual consultation with a professional. An expert in stress management can do an assessment to identify which techniques would best suit your skills, temperament, and needs. Professional that help individuals cope with stress include: Psychologist Psychotherapist Nurse Physician Exercise instructor Dietitian
A boy was born to a couple after eleven years of marriage. They were a loving couple and the boy was the gem of their eyes. When the boy was around two years old, one morning the husband saw a medicine bottle open. He was late for office so he asked his wife to cap the bottle and keep it in the cupboard. His wife, preoccupied in the kitchen totally forgot the matter.
The boy saw the bottle and playfully went to the bottle fascinated by its color and drank it all. It happened to be a poisonous medicine meant for adults in small dosages. When the child collapsed the mother hurried him to the hospital, where he died. The mother was stunned. She was terrified how to face her husband.
When the distraught father came to the hospital and saw the dead child, he looked at his wife and uttered just five words.
QUESTIONS : 1. What were the five words ? 2. What is the implication of this story? Let's be understanding scroll down to read.... * * * * * * * * * ANSWER :
The husband just said "I am with you Darling"
The husband's totally unexpected reaction is a proactive behavior. The child is dead. He can never be brought back to life. There is no point in finding fault with the mother. Besides, if only he had taken time to keep the bottle away, this would not have happened. No one is to be blamed. She had also lost her only child. What she needed at that moment was consolation and sympathy from the husband. That is what he gave her.
If everyone can look at life with this kind of perspective, there would be much fewer problems in the world. " A journey of a thousand miles begins with a single step. Take off all your envies, jealousies,unforgiv eness, selfishness, and fears. And you will find things are actually not as difficult as you think.
MORAL OF THE STORY This story is really worth reading. ..... Sometimes we spend time in asking who is responsible or whom to blame, whether in a relationship, in a job or with the people we know. By this way we miss out something
प्रिये तुझ्याविना नाही आयुष्याला अर्थ काही ग सजणे तुझ्याविना, नाही शक्य ग माझे जगणे आता प्रिये तुझ्याविना.
माझे सारे काव्य वाटु लागते सुनेसुने तुझ्या गोड आठवणींविना, नाही सरत दिवस माझा तुझा आवाज ऐकल्याविना.
कशी होतील ग सखे स्वप्ने माझी तुझ्याविना कोण देणार ग साथ माझी सुखः दुःखात फक्त तुझ्याविना
विचार माझे थांबतात मन माझे भरुन येते, वरुन जरी शांत दिसलो तरी मनात दडलेले एक वादळ असते, आठवणी मनात दाटुन आल्या की प्रेम डोळ्यांतुन अश्रु बनुन वाहु लागते,
आणी मग,
वेडे मन माझं त्या वेड्या आठवणींवर काव्य बनवु लागते................................
1. TODAY I WILL NOT STRIKE BACK: If someone is rude, if someone is impatient, if someone is unkind... I will not respond in a like manner.
2. TODAY I WILL ASK GOD TO BLESS MY "ENEMY": If I come across someone who treats me harshly or unfairly, I will quietly ask God to bless that individual. I understand the "enemy" could be a family member, neighbor, co-worker, or a stranger.
3. TODAY I WILL BE CAREFUL ABOUT WHAT I SAY: I will carefully choose and guard my words being certain that I do not spread gossip.
4. TODAY I WILL GO THE EXTRA MILE: I will find ways to help share the burden of another person.
5. TODAY I WILL FORGIVE: I will forgive any hurts or injuries that come my way.
6. TODAY I WILL DO SOMETHING NICE FOR SOMEONE, BUT I WILL NOT DO IT SECRETLY: I will reach out anonymously and bless the life of another.
7. TODAY I WILL TREAT OTHERS THE WAY I WISH TO BE TREATED: I will practice the golden rule - "Do unto others as I would have them do unto me" - with everyone I encounter.
8. TODAY I WILL RAISE THE SPIRITS OF SOMEONE I DISCOURAGED: My smile, my words, my expression of support, can make the difference to someone who is wrestling life.
9. TODAY I WILL NUTURE MY BODY: I will eat less; I will eat only healthy foods. I will thank God for my body.
10. TODAY I WILL GROW SPIRITUALLUY: I will spend a little more time in prayer today: I will begin reading something spiritual or inspirational today; I will find a quiet place (at some point during the day)!
So far, so good, right? Now, we’ll add some ASP.NET code that will create the dynamic elements of the page, starting with the time.
2If you do use Notepad, be aware that to need to put quotes around any filename that doesn’t end with .txt in the Save As dialog. Most ASP.NET file names end with .aspx; if you forget to put quotes around them when saving, you’ll end up with files called filename.aspx.txt! Order the print version of this book to get all 700+ pages! 24 Chapter 1: Introduction to .NET and ASP.NET My First ASP.NET Page
Hello there!
The time is now:
We’ve added an tag to the document. This is a special tag that lets us insert dynamic content into the page. The asp: part of the tag name identifies it as a built-in ASP.NET tag. ASP.NET comes with numerous built-in tags; is arguably the simplest. The runat="server" attribute identifies the tag as something that needs to be handled on the server. In other words, the Web browser will never see the tag; ASP.NET sees it and converts it to regular HTML tags before the page is sent to the browser. It’s up to us to write the code that will tell ASP.NET to replace this particular tag with the current time. To do this, we must add some script to our page. Like ASP before it, ASP.NET gives you the choice of a number of different languages to use in your scripts. The two most common languages are Visual Basic.NET (VB.NET) and C# (pronounced “C sharp”). Let’s take a look at examples using both. Here’s a version of the page in VB.NET: VB.NET File: FirstPage.aspx
My First ASP.NET Page
Hello there!
The time is now:
Here’s the same page written in C#: 25 Order the print version of this book to get all 700+ pages! Your First ASP.NET Page C# File: FirstPage.aspx
My First ASP.NET Page
Hello there!
The time is now:
Both versions of the page achieve exactly the same thing. If you’ve never done any server-side programming before, this may be starting to look a little scary. Let’s break down the new elements of this page: File: FirstPage.aspx (excerpt)
27 Order the print version of this book to get all 700+ pages! Your First ASP.NET Page C# File: FirstPage.aspx (excerpt) }
The closing (End Sub) and (}) mark the end of the script to be run when the page is loaded, and the tag marks the end of the script block. Create a new subdirectory of C:\Inetpub\wwwroot on your Web server, and save your file there under the name FirstPage.aspx. Now, open your browser and point type this URL in the address bar: http://localhost/test/FirstPage.aspx Replace test with the name that you gave to the directory in which you saved the file. You should see a page similar to the one we saw in Figure 1.9. If the time isn’t displayed, chances are that you opened the file directly in your browser instead of loading it through your Web server. Because ASP.NET is a server-side language, your Web server needs to access the file before it’s sent to your browser for display. If it doesn’t get access to the file, the ASP.NET code is never converted into HTML that your browser can understand, so make sure you load the page by typing an actual URL (e.g. http://localhost/test/index.aspx), not just a path and filename. With the page displayed in your browser, use the View Source feature (View, Source in Internet Explorer) to view the HTML code for the page. Here’s what you’ll see:
My First ASP.NET Page
Hello there!
The time is now: 10/13/2003 1:55:09 PM
Notice that all the ASP.NET code has gone! Even the script block has been completely removed, and the tag has been replaced by a tag (with the same id attribute as the tag that we used) containing the date and time string. Order the print version of this book to get all 700+ pages! 28 Chapter 1: Introduction to .NET and ASP.NET That’s how ASP.NET works. From the Web browser’s point of view, there is nothing special about an ASP.NET page; it’s just plain HTML like any other. All the ASP.NET code is run by your Web server and converted to plain HTML that’s sent to the browser. So far, so good: the example above was fairly simple. The next chapter will get a bit more challenging as we begin to introduce you to some valuable programming concepts. The ASP.NET Support Site The official Microsoft ASP.NET support Website can be found at http://www.asp.net/. As you develop ASP.NET Web applications, you will undoubtedly have questions and problems that need to be answered. The ASP.NET support Website was developed by Microsoft as a portal for the ASP.NET community to answer the questions and solve the problems that developers have while using ASP.NET. The support Website provides useful information, such as news, downloads, articles, and discussion forums. You can also ask questions of the experienced community members in the SitePoint Forums[20]. Summary In this chapter, you learned about .NET. You also learned of the benefits of ASP.NET and that it’s a part of the .NET Framework. First, you learned about the constructs of ASP.NET and how to locate and install the .NET Framework. Then, we explored the software that’s required not only for this book, but also in order for you or your company to progress with ASP.NET. You’ve gained a solid foundation in the world of ASP.NET! The next chapter will build on this knowledge and begin to introduce you to ASP.NET in more detail, including page structure, languages to use, programming concepts, and form processing. [20] http://www.sitepoint.com/forums/ 29 Order the print version of this book to get all 700+ pages! The ASP.NET Support Site 30 ASP.NET Basics 2 So far, you’ve learned what ASP.NET is, and what it can do—you even know how to create a simple ASP.NET page. Don’t worry if it seems a little bewildering right now, because, as this book progresses, you’ll learn how to use ASP.NET at more advanced levels. So far, you’ve installed the necessary software to get going and have been introduced to some very simple form processing techniques. As the next few chapters unfold, we’ll introduce more advanced topics, including controls, programming techniques, and more. Before we can begin developing applications with ASP.NET, however, you’ll need to understand the inner workings of a typical ASP.NET page. This will help you identify the various parts of the ASP.NET page referenced by the many examples within the book. In this chapter, we’ll talk about some key mechanisms of an ASP.NET page, specifically: Page structure View state Namespaces Directives We’ll also cover two of the "built-in" languages supported by the .NET Framework: VB.NET and C#. As this section begins to unfold, we’ll explore the differences, similarities, and power that the two languages provide in terms of creating ASP.NET applications. So, what exactly makes up an ASP.NET page? The next few sections will give you an in-depth understanding of the constructs of a typical ASP.NET page. ASP.NET Page Structure ASP.NET pages are simply text files with the .aspx file name extension that can be placed on an IIS server equipped with ASP.NET. When a browser requests an ASP.NET page, the ASP.NET runtime (as a component of the .NET Framework’s Common Language Runtime, or CLR) parses and compiles the target file into a .NET Framework class. The application logic now contained within the new class is used in conjunction with the presentational HTML elements of the ASP.NET page to display dynamic content to the user. Sounds simple, right? An ASP.NET page consists of the following elements: Directives Code declaration blocks Code render blocks ASP.NET server controls Server-side comments Server-side include directives Literal text and HTML tags It’s important to remember that ASP.NET pages are just text files with an .aspx extension that are processed by the runtime to create standard HTML, based on their contents. Presentational elements within the page are contained within the tag, while application logic or code can be placed inside Here, the tags enclose some VB.NET code, but it could just as easily be C# if our page language were set thus: C#
Order the print version of this book to get all 700+ pages! 34 Chapter 2: ASP.NET Basics Comments in VB.NET and C# Code Both of these code snippets contain comments—explanatory text that will be ignored by ASP.NET, but which serves to describe how the code works. In VB.NET code, a single quote or apostrophe (') indicates that the remainder of the line is to be ignored as a comment. In C# code, two slashes (//) does the same. C# code also lets you span a comment over multiple lines by beginning it with /* and ending it with */. Before .NET emerged, ASP also supported such script tags using a runat="server" attribute, although they could only ever contain VBScript, and, for a variety of reasons, they failed to find favor among developers. Code declaration blocks are generally placed inside the tag of your ASP.NET page. The sample ASP.NET page shown in Figure 2.1, for instance, contained the following code declaration block: VB.NET
Perhaps you can work out what the equivalent C# code would be: C#
The
As you can see in the bold code, literal text and HTML tags provide the structure for presenting our dynamic data. Without them, there would be no format to the page, and the browser would be unable to understand it. Now you should understand what the structure of an ASP.NET page looks like. As you work through the examples in this book, you’ll begin to realize that in many cases you won’t need to use all these elements. For the most part, all of your development will be modularized within code declaration blocks. All of the dynamic portions of your pages will be contained within code render blocks or controls located inside a
If you save this example in the WebDocs subdirectory of wwwroot that you created in Chapter 1, you can open it in your browser by typing http://localhost/WebDocs/sample.asp, to see that view state is not automatically preserved. When the user submits the form, the information that was previously typed into the text box is cleared, although it is still available in Request. Form("txtName"). The equivalent page in ASP.NET, ViewState.aspx, demonstrates data persistence using view state: VB.NET File: ViewState.aspx
Sample Page using VB.NET
41 Order the print version of this book to get all 700+ pages! View State
C# File: ViewState.aspx
Sample Page using C#
In this case, the code uses ASP.NET controls with the runat="server" attribute. As you can see in Figure 2.2, the text from the box appears on the page when the button is clicked, but also notice that the data remains in the text box! The data in this example is preserved because of view state: Figure 2.2. ASP.NET supports view state. When a page is submitted, the information within the controls is preserved. Order the print version of this book to get all 700+ pages! 42 Chapter 2: ASP.NET Basics You can see the benefits of view state already. But where is all that information stored? ASP.NET pages maintain view state by encrypting the data within a hidden form field. View the source of the page after you’ve submitted the form, and look for the following code:
This is a standard HTML hidden form field with the value set to the encrypted data from the form element. As soon as you submit the form for processing, all information relevant to the view state of the page is stored within this hidden form field. View state is enabled for every page by default. If you do not intend to use view state, you can turn it off, which will result in a slight performance gain in your pages. To do this, set the EnableViewState property of the Page directive to false: <%@ Page EnableViewState="False" %> Speaking of directives, it’s time we took a closer look at these curious beasts! Working With Directives For the most part, ASP.NET pages resemble traditional HTML pages, with a few additions. In essence, just using an extension like .aspx on an HTML file will make the .NET Framework process the page. However, before you can work with certain, more advanced features, you will need to know how to use directives. We’ve already talked a little about directives and what they can do earlier in this chapter. You learned that directives control how a page is created, specify settings when navigating between pages, aid in finding errors, and allow you to import advanced functionality to use within your code. Three of the most commonly used directives are: Page Defines page-specific attributes for the ASP.NET page, such as the language used. Import Makes functionality defined elsewhere available in a page through the use of namespaces. You will become very familiar with this directive as you progress through this book. 43 Order the print version of this book to get all 700+ pages! Working With Directives Register Asyou will see in Chapter 16, you would use this directive to link a user control to the ASP.NET page. You will become very familiar with these three directives, as they’re the ones that we’ll be using the most in this book. You’ve already seen the Page directive in use. The Import directive imports extra functionality for use within your application logic. The following example, for instance, imports the Mail class, which you could use to send email from a page: <%@ Import Namespace="System.Web.Mail" %> The Register directive allows you to register a user control for use on your page. We’ll cover these in Chapter 16, but the directive looks something like this: <%@ Register TagPrefix="uc" TagName="footer" Src="footer.ascx" %> ASP.NET Languages As we saw in the previous chapter, .NET currently supports many different languages and there is no limit to the number of languages that could be made available. If you’re used to writing ASP, you may think the choice of VBScript would be obvious. With ASP.NET however, Microsoft has done away with VBScript and replaced it with a more robust and feature-rich alternative: VB.NET. ASP.NET’s support for C# is likely to find favor with developers from other backgrounds. This section will introduce you to both these new languages, which are used throughout the remainder of the book. By the end of this section, you will, I hope, agree that the similarities between the two are astonishing—any differences are minor and, in most cases, easy to figure out. Traditional server technologies are much more constrained in the choice of development language they offer. For instance, old-style CGI scripts were typically written with Perl or C/C++, JSP uses Java, Coldfusion uses CFML, and PHP is a language in and of itself. .NET’s support for many different languages lets developers choose based on what they’re familiar with, and start from there. To keep things simple, in this book we’ll consider the two most popular, VB.NET and C#, giving you a chance to choose which feels more comfortable to you, or stick with your current favorite if you have one. VB.NET Visual Basic.NET or VB.NET is the result of a dramatic overhaul of Microsoft’s hugely popular Visual Basic language. With the inception of Rapid Application Order the print version of this book to get all 700+ pages! 44 Chapter 2: ASP.NET Basics Development (RAD) in the nineties, Visual Basic became extremely popular, allowing inhouse teams and software development shops to bang out applications two-to-the-dozen. VB.NET has many new features over older versions of VB, most notably that it has now become a fully object-oriented language. At last, it can call itself a true programming language on a par with the likes of Java and C++. Despite the changes, VB.NET generally stays close to the structured, legible syntax that has always made it so easy to read, use, and maintain. C# The official line is that Microsoft created C# in an attempt to produce a programming language that coupled the simplicity of Visual Basic with the power and flexibility of C++. However, there’s little doubt that its development was at least hurried along. Following legal disputes with Sun about Microsoft’s treatment (some would say abuse) of Java, Microsoft was forced to stop developing its own version of Java, and instead developed C# and another language, which it calls J#. We’re not going to worry about J# here, as C# is preferable. It’s easy to read, use, and maintain, because it does away with much of the confusing syntax for which C++ became infamous. Summary In this chapter, we started out by introducing key aspects of an ASP.NET page including directives, code declaration blocks, code render blocks, includes, comments, and controls. As the chapter progressed, you were introduced to the two most popular languages that ASP.NET supports, which we’ll use throughout the book. In the next chapter, we’ll create more ASP.NET pages to demonstrate some form processing techniques and programming basics, before we finally dive in and look at object oriented programming for the Web. 45 Order the print version of this book to get all 700+ pages! C# 46 VB.NET and C# Programming Basics 3 As you learned at the end of the last chapter, one of the great things about ASP.NET is that we can pick and choose which of the various .NET languages we like. In this chapter, we’ll look at some key programming principles using our two chosen languages, VB.NET and C#. We’ll start off with a run-down of some basic programming concepts as they relate to ASP.NET using both languages. We’ll introduce programming fundamentals such as control and page events, variables, arrays, functions, operators, conditionals, and loops. Next, we’ll dive into namespaces and address the topic of classes—how they’re exposed through namespaces, and which you’ll use most often. The final sections of the chapter cover some of the ideas underlying modern, effective ASP.NET design, starting with that of code-behind and the value it provides by helping us separate code from presentation. We finish with an examination of how object-oriented programming techniques impact the ASP.NET developer. Programming Basics One of the building blocks of an ASP.NET page is the application logic: the actual programming code that allows the page to function. To get anywhere with this, you need to grasp the concept of events. All ASP.NET pages will contain controls, such as text boxes, check boxes, lists, and more, each of these controls allowing the user to interact with it in some way. Check boxes can be checked, lists can be scrolled, items on them selected, and so on. Now, whenever one of these actions is performed, the control will raise an event. It is by handling these events with code that we get our ASP.NET pages to do what we want. For instance, say a user clicks a button on an ASP.NET page. That button (or, strictly, the ASP.NET Button control) raises an event (in this case it will be the Click event). When the ASP.NET runtime registers this event, it calls any code we have written to handle it. We would use this code to perform whatever action that button was supposed to perform, for instance, to save form data to a file, or retrieve requested information from a database. Events really are key to ASP.NET programming, which is why we’ll start by taking a closer look at them. Then, there’s the messy business of writing the actual handler code, which means we need to check out some common programming techniques in the next sections. Specifically, we’re going to cover the following areas: Control events and handlers Page events Variables and variable declaration Arrays Functions Operators Conditionals Loops It wouldn’t be practical, or even necessary, to cover all aspects of VB.NET and C# in this book, so we’re going to cover enough to get you started, completing the projects and samples using both languages. Moreover, I’d say that the programming concepts you’ll learn here will be more than adequate to complete the great majority of day-to-day Web development tasks using ASP.NET. Control Events and Subroutines As I just mentioned, an event (sometimes more than one) is raised, and handler code is called, in response to a specific action on a particular control. For instance, Order the print version of this book to get all 700+ pages! 48 Chapter 3: VB.NET and C# Programming Basics the code below creates a server-side button and label. Note the use of the OnClick attribute on the Button control: File: ClickEvent.aspx (excerpt)
When the button is clicked, it raises the Click event, and ASP.NET checks the OnClick attribute to find the name of the handler subroutine for that event. Here, we tell ASP.NET to call the btn1_Click() routine. So now we have to write this subroutine, which we would normally place within a code declaration block inside the tag, like this: VB.NET File: ClickEvent.aspx (excerpt)
C# File: ClickEvent.aspx (excerpt)
This code simply sets a message to display on the label that we also declared with the button. So, when this page is run and users click the button, they’ll see the message "Hello World" appear next to it. I hope you can now start to come to grips with the idea of control events and how they’re used to call particular subroutines. In fact, there are many events that your controls can use, some of which are only found on certain controls—not others. Here’s the complete set of attributes the Button control supports for handling events: 49 Order the print version of this book to get all 700+ pages! Control Events and Subroutines OnClick As we’ve seen, the subroutine indicated by this attribute is called for the Click event, which occurs when the user clicks the button. OnCommand As with OnClick, the subroutine indicated by this attribute is called when the button is clicked. OnLoad The subroutine indicated by this attribute is called when the button is loaded for the first time—generally when the page first loads. OnInit When the button is initialized, any subroutine given in this attribute will be called. OnPreRender We can run code just before the button is rendered, using this attribute. OnUnload This subroutine will run when the control is unloaded from memory—basically, when the user goes to a different page or closes the browser entirely. OnDisposed This occurs when the button is released from memory. OnDataBinding This fires when the button is bound to a data source. Don’t worry too much about the intricacies of all these events and when they happen; I just want you to understand that a single control can produce a number of different events. In the case of the Button control, you’ll almost always be interested in the Click event, as the others are only useful in rather obscure circumstances. When a control raises an event, the specified subroutine (if there is one) is executed. Let’s now take a look at the structure of a typical subroutine that interacts with a Web control: VB.NET Public Sub mySubName(s As Object, e As EventArgs) ' Write your code here End Sub C# public void mySubName(Object s, EventArgs e) { // Write your code here } Order the print version of this book to get all 700+ pages! 50 Chapter 3: VB.NET and C# Programming Basics Let’s break down all the components that make up a typical subroutine: Public Defines the scope of the subroutine. There are a few different options to choose from, the most frequently public used being Public (for a global subroutine that can be used anywhere within the entire page) and Private (for subroutines that are available for the specific class only). If you don’t yet understand the difference, your best bet is to stick with Public for now. Sub Defines the chunk of code as a subroutine. A subroutine is a named block of code that doesn’t return void a result; thus, in C#, we use the void keyword, which means exactly that. We don’t need this in VB.NET, because the Sub keyword already implies that no value is returned. mySubName(…) This part gives the name we’ve chosen for the subroutine. s As Object When we write a subroutine that will function as an event handler, it must accept two parameters. The Object s first is the control that generated the event, which is an Object. Here, we are putting that Object in a variable named s (more on variables later in this chapter). We can then access features and settings of the specific control from our subroutine using the variable. e As EventArgs The second parameter contains certain information specific to the event that was raised. Note that, in EventArgs e many cases, you won’t need to use either of these two parameters, so you don’t need to worry about them too much at this stage. As this chapter progresses, you’ll see how subroutines associated with particular events by the appropriate attributes on controls can revolutionize the way your user interacts with your application. 51 Order the print version of this book to get all 700+ pages! Control Events and Subroutines Page Events Until now, we’ve considered only events that are raised by controls. However, there is another type of event—the page event. The idea is the same as for control events1, except that here, it is the page as a whole that generates the events. You’ve already used one of these events: the Page_Load event. This event is fired when the page loads for the first time. Note that we don’t need to associate handlers for page events the way we did for control events; instead, we just place our handler code inside a subroutine with a preset name. The following list outlines the page event subroutines that are available: Page_Init Called when the page is about to be initialized with its basic settings Page_Load Called once the browser request has been processed, and all of the controls in the page have their updated values. Page_PreRender Called once all objects have reacted to the browser request and any resulting events, but before any response has been sent to the browser. Page_UnLoad Called when the page is no longer needed by the server, and is ready to be discarded. The order in which the events are listed above is also the order in which they’re executed. In other words, the Page_Init event is the first event raised by the page, followed by Page_Load, Page_PreRender, and finally Page_UnLoad. The best way to illustrate the Page_Load event is through an example: VB.NET File: PageEvents.aspx (excerpt)
C# File: PageEvents.aspx (excerpt)
You can see that the control on the page does not specify any event handlers. There’s no need, because we’re using the special Page_Load subroutine, which will be called when the page loads. As the page loads, it will call the Page_Load routine, to display “Hello World” in the Label control, as shown in Figure 3.1. 53 Order the print version of this book to get all 700+ pages! Page Events Figure 3.1. The Page_Load event is raised, the subroutine is called, and the code within the subroutine is executed. Variables and Variable Declaration Variables are fundamental to programming, and you’ve almost certainly come across the term before. Basically, they let you give a name, or identifier, to a piece of data; we can then use that identifier to store, modify, and retrieve the data. However, there are, of course, many different kinds of data, such as strings, integers (whole numbers), and floating point numbers (fractions or decimals). Before you can use a variable in VB.NET or C#, you must specify what type of data it can contain, using keywords such as String, Integer, Decimal, and so on, like this: VB.NET Dim strName As String Dim intAge As Integer Order the print version of this book to get all 700+ pages! 54 Chapter 3: VB.NET and C# Programming Basics C# string strName; int intAge; These lines declare what type of data we want our variables to store, and are therefore known as variable declarations. In VB.NET, we use the keyword Dim, which stands for “dimension”, while in C#, we simply precede the variable name with the appropriate data type. Sometimes, we want to set an initial value for variables that we declare; we can do this using a process known as initialization: VB.NET Dim strCarType As String = "BMW" C# string strCarType = "BMW"; We can also declare and/or initialize a group of variables of the same type all at once: VB.NET Dim strCarType As String, strCarColor = "blue", strCarModel C# string strCarType, strCarColor = "blue", strCarModel; Table 3.1 below lists the most useful data types available in VB.NET and C#. 55 Order the print version of this book to get all 700+ pages! Variables and Variable Declaration Table 3.1. A List of the Commonly Used Data Types Description C# VB.NET Whole numbers in the range -2,147,483,648 to 2,147,483,647. int Integer Up to 28 decimal places. You’ll use decimal most often when dealing with costs of items. decimal Decimal Any text value. string String A single character (letter, number, or symbol). char Char True or false. bool Boolean In .NET, all types are ultimately a type of object, and so variables of this type can hold just about any kind of data. Object Object There are many more data types that you may encounter as you progress, but this list provides an idea of the ones you’ll use most often. So, to sum up, once you’ve declared a variable as a given type, it can only hold data of that type. You can’t put a string into an integer variable, for instance. However, there are frequently times when you’ll need to convert one data type to another. Have a look at this code: VB.NET Dim intX As Integer Dim strY As String = "35" intX = strY + 6 C# int intX; String strY = "35"; intX = strY + 6; Now, while you or I might think that this could make sense—after all, the string strY does contain a number, so we may well wish to add it to another number—the computer will not be happy, and we’ll get an error. What we have to do is explicitly convert, or cast, the string into an integer first: VB.NET Dim intX As Integer Dim strY As String = "35" intX = Int32.Parse(strY) + 6 Order the print version of this book to get all 700+ pages! 56 Chapter 3: VB.NET and C# Programming Basics C# int intX; String strY = "35"; intX = Convert.ToInt32(strY) + 6; Now, the computer will be happy, as we’ve told it that we want to turn the string into an integer before it’s used as one. This same principle holds true when mixing other types in a single expression. Arrays Arrays are a special variety of variable tailored for storing related items of the same data type. Any one item in an array can be accessed using the array’s name, followed by that item’s position in the array (its offset). Let’s create a sample page to show what I mean: VB.NET File: Arrays.aspx
57 Order the print version of this book to get all 700+ pages! Arrays C# File: Arrays.aspx
There are some important points to pick up from this code. First, notice how we declare an array. In VB.NET, it looks like a regular declaration for a string, except that the number of items we want the array to contain is given in brackets after the name: VB.NET File: Arrays.aspx (excerpt) Dim drinkList(4) As String In C#, it’s a little different. First, we declare that drinkList is an array by following the datatype with two empty square brackets. We must then specify that this is an array of four items, using the new keyword: C# File: Arrays.aspx (excerpt) String[] drinkList = new String[4]; A crucial point to realize here is that the arrays in both C# and VB.NET are what are known as zero-based arrays. This means that the first item actually has Order the print version of this book to get all 700+ pages! 58 Chapter 3: VB.NET and C# Programming Basics position 0, the second has position 1, and so on, through to the last item, which will have a position that’s one less than the size of the array (3, in this case). So, we specify each item in our array like this: VB.NET File: Arrays.aspx (excerpt) drinkList(0) = "Water" drinkList(1) = "Juice" drinkList(2) = "Soda" drinkList(3) = "Milk" C# File: Arrays.aspx (excerpt) drinkList[0] = "Water"; drinkList[1] = "Juice"; drinkList[2] = "Soda"; drinkList[3] = "Milk"; Notice that C# uses square brackets for arrays, while VB.NET uses standard parentheses. We have to remember that arrays are zero-based when we set the label text to the second item, as shown here: VB.NET File: Arrays.aspx (excerpt) lblArrayList.Text = drinkList(1) C# File: Arrays.aspx (excerpt) lblArrayList.Text = drinkList[1]; To help this sink in, you might like to try changing this code to show the third item in the list instead of the second. Can you work out what change you’d need to make? That’s right—you only need to change the number given in the brackets to match the position of the new item (don’t forget to start at zero). In fact, it’s this ability to select one item from a list using only its numerical location that makes arrays so useful in programming, as we’ll see as we get further into the book. Functions Functions are exactly the same as subroutines, but for one key difference: they return a value. In VB.NET, we declare a function using the Function keyword in place of Sub, while, in C#, we simply have to specify the return type in place of using void. The following code shows a simple example: 59 Order the print version of this book to get all 700+ pages! Functions VB.NET File: Functions.aspx
C# File: Functions.aspx
Order the print version of this book to get all 700+ pages! 60 Chapter 3: VB.NET and C# Programming Basics
Figure 3.2 shows the result in the browser. Figure 3.2. The Page_Load event is raised, the function is called, and the code within the function is executed. Here’s what’s happening: the line in our Page_Load subroutine calls our function, which returns a simple string that we can then assign to our label. I hope this illustrates what functions are about and how you can use them. In this simple example, we’re merely returning a fixed string (my name), but the function could just as well retrieve the name from a database—or somewhere else. The point is that, regardless of how the function gets its data, we use it (that is, call it) in just the same way. 61 Order the print version of this book to get all 700+ pages! Functions When we’re declaring our function, we must remember to specify the correct return type. Take a look at the following code: VB.NET ' Here's our function Function addUp(x As Integer, y As Integer) As Integer Return x + y End Function ' And now we use it in Page_Load Sub Page_Load(s As Object, e As EventArgs) lblMessage.Text = addUp(5, 5).ToString() End Sub C# // Here's our function int addUp(int x, int y) { return x + y; } // And now we use it in Page_Load void Page_Load() { lblMessage.Text = Convert.ToString(addUp(5, 5)); } You can easily adapt the previous example to use this new code and see the results in your browser. Have a look at this code, and see if you can spot what’s different and why. The first thing you might notice is that our function now accepts parameters. Any function or subroutine can take any number of parameters, each of any type (there’s no need for parameter types to match the return type—that’s just coincidental in this example). We can then readily use the parameters inside the function or subroutine just by using the names we gave them in the function declaration (here, we’ve chosen x and y, but we could have chosen different names). The other difference between this and the function declaration we had before is that we now declare our function with a return type of Integer or int, rather than String, because we want it to return a whole number. When we now call the new function, we simply have to specify the required number of parameters, and remember that the function will return a value with Order the print version of this book to get all 700+ pages! 62 Chapter 3: VB.NET and C# Programming Basics the type we specified. In this case, that means we have to convert the integer value it returns to a string, so we can assign it to the label. In VB.NET, we tack .ToString() onto the end of the function call, while in C# we use the Convert.ToString(…). Note the differences in how these two methods are used—converting numbers to strings is a very common task in ASP.NET, so it’s good to get a handle on it early. Don’t be too concerned if you’re a little confused by how these conversions work, though—the syntax will become clear once we discuss the object oriented concepts involved later in this chapter. Again, a complete discussion of functions could take up an entire chapter, but I hope the brief examples here are enough to prepare you for what we’re going to cover in future chapters. Don’t worry too much if you’re still a bit unsure what functions and subroutines are all about right now—they’ll become second nature very quickly. Operators Throwing around values with variables and functions isn’t much use unless you can use them in some meaningful way, and to do this we use operators. An operator is a symbol that has a certain meaning when applied to values. Don’t worry—they’re nowhere near as scary as they sound! In fact, in the last example, when our function added two numbers, we were using an operator—the addition operator, +. Most of the other available operators are just as well known, although there are one or two that will probably be new to you. Table 3.2 outlines the operators that you’ll use most often. 63 Order the print version of this book to get all 700+ pages! Operators Table 3.2. ASP.NET Operators Description C# VB.NET greater than > > greater than or equal to >= >= less than < < less than or equal to <= <= not equal to != <> equals == = assigns a value to a variable = = or Or and && And concatenate strings + & create object or array New New multiply * * divide / / add + + subtract - - The following code uses some of these operators: VB.NET If (user = "Zak" And itemsBought <> 0) Then lblMessage.Text = "Hello Zak! Do you want to proceed to " & _ "checkout?" End If C# if (user == "Zak" && itemsBought != 0) { lblMessage.Text = "Hello Zak! Do you want to proceed to " + "checkout?"; } Here, we use the equality, inequality (not equals to) and logical ‘and’ operators in an If statement to print a message only for a given user, and only when he or she has bought something. Of particular note is C#’s equality operator, ==, which is used when comparing two values to see if they are equal. Don’t use a single Order the print version of this book to get all 700+ pages! 64 Chapter 3: VB.NET and C# Programming Basics equals sign in C# unless you are assigning a value to a variable, or your code will have a very different meaning than you expect! Breaking Long Lines of Code Since the message string in the above example was too long to fit on one line in this book, I also used the string concatenation operator to combine two shorter strings on separate lines to form the complete message. In VB.NET, I also had to break one line of code into two using the line continuation symbol (_, an underscore at the end of the line to be continued). Since C# marks the end of each command with a semicolon (;), I can split a single command over two lines without having to do anything special. I’ll use these techniques throughout this book to show long lines of code within a limited page width. Feel free to recombine the lines in your own code if you like—there is no actual length limit on lines of code in VB.NET and C#. Conditional Logic As you develop ASP.NET applications, there will be many instances in which you’ll need to perform an action only if a certain condition is met, for instance, if the user has checked a certain checkbox, selected a certain item from a DropDownList control, or typed a certain string into a TextBox control. We check for such things using conditionals, the simplest of which is probably the If statement. This statement is often used in conjunction with an Else statement, which specifies what should happen if the condition is not met. So, for instance, we may wish to check if the name entered in a text box is "Zak," redirecting to one page if it is, or else redirecting to an error page: VB.NET If (txtUsername.Text = "Zak") Then Response.Redirect("ZaksPage.aspx") Else Response.Redirect("errorPage.aspx") End If C# if (txtUsername.Text == "Zak") { Response.Redirect("ZaksPage.aspx"); } else { Response.Redirect("errorPage.aspx"); } 65 Order the print version of this book to get all 700+ pages! Conditional Logic Often, we want to check for one of many possibilities, and perform a particular action in each case. In that event, we can use the Switch Case (VB.NET) or switch (C#) construct: VB.NET Dim strName As String = txtUsername.Text Select Case strName Case "Zak" Response.Redirect("ZaksPage.aspx") Case "Mark" Response.Redirect("MarksPage.aspx") Case "Fred" Response.Redirect("FredsPage.aspx") Case Else Response.Redirect("errorPage.aspx") End Select C# string strName = txtUsername.Text; switch (strName) { case "Zak": Response.Redirect("ZaksPage.aspx"); break; case "Mark": Response.Redirect("MarksPage.aspx"); break; case "Fred": Response.Redirect("FredsPage.aspx"); break; default: Response.Redirect("errorPage.aspx"); break; } Loops As you’ve just seen, an If statement causes a code block to execute once if the value of its test expression is true. Loops, on the other hand, cause a code block to execute repeatedly for as long as the test expression remains true. There are two basic kinds of loop: While loops, also called Do loops, which sounds like something Betty Boop might say! Order the print version of this book to get all 700+ pages! 66 Chapter 3: VB.NET and C# Programming Basics For loops, including For Next and For Each A While loop is the simplest form of loop; it makes a block of code repeat for as long as a particular condition is true. Here’s an example: VB.NET Dim Counter As Integer = 0 Do While Counter <= 10 ' Convert out Integer to a String lblMessage.Text = Counter.ToString() ' Below we use the += operator to increase our variable by 1 Counter += 1 Loop C# int counter = 0; while (counter <= 10) { // Below we use a sneaky way to convert our int to a string lblMessage.Text = counter + ""; // C# has the operator ++ to increase a variable by 1 counter++; } You can try out this code—enter it inside a Page_Load subroutine of one of the pages you’ve already created. The page illustrating Page_Load at the start of this chapter would be ideal. Make sure you remove any other code in the subroutine, and that there is an ASP.NET Label control in the HTML of the page with the ID lblMessage. When you open the page, the label will be set to show the number 0, then 1, then 2, all the way to 10. Of course, since all this happens in Page_Load (i.e. before any output is sent to the browser), you’ll only see the last value assigned, 10. This demonstrates that the loop repeats until the condition is no longer met. Try changing the code so that the counter variable is initialized to 20 instead of 10. When you open the page now, you won’t see anything on screen, because the loop condition was never met. 67 Order the print version of this book to get all 700+ pages! Loops There is another form of the While loop, called a Do While loop, which checks if the condition has been met at the end of the code block, rather than at the beginning: VB.NET Dim Counter As Integer = 0 Do ' Convert our Integer to a String lblMessage.Text = Counter.toString() ' Below we use the += operator to increase our variable by 1 Counter += 1 Loop While Counter <= 10 C# int counter = 0; do { // Below we use a sneaky way to convert our int to a string lblMessage.Text = counter + ""; // C# has the operator ++ to increase a variable by 1 counter++; } while (counter <= 10); If you run this code, you’ll see it provides the exact same output we saw when we tested the condition before the code block. However, we can see the crucial difference if we again change it so the counter variable is initialized to 20. In this case, we will, in fact, see 20 on screen, because the loop code is executed once before the condition is even checked! There are some instances when this is just what we want, so being able to place the condition at the end of the loop can be very handy. A For loop is similar to a While loop, but is typically used when the number of times we need it to execute is known beforehand. The following example displays the count of items within a DropDownList control called ddlProducts: VB.NET Dim i As Integer For i = 1 To ddlProducts.Items.Count lblMessage.Text = i.toString() Next Order the print version of this book to get all 700+ pages! 68 Chapter 3: VB.NET and C# Programming Basics C# int i; for (i = 1; i <= ddlProducts.Items.Count; i++) { lblMessage.Text = Convert.ToString(i); } In VB.NET, the loop syntax specifies the starting and ending values for our counter variable in the For statement itself. In C#, we assign a starting value (i = 1), a condition to be tested each time through the loop, just like a While loop (i <= ddlProducts.Items.Count), and how the counter variable should be incremented after each loop (i++). While this allows for some powerful variations on the theme in C#, it can be confusing at first. In VB.NET, the syntax is considerably simpler, but can be a bit limiting in exceptional cases. The other type of For loop is For Each, which loops through every item within a collection. The following example loops through an array called arrayName: VB.NET For Each item In arrayName lblMessage.Text = item Next C# foreach (string item in arrayName) { lblMessage.Text = item; } You may also come across instances in which you need to exit a loop prematurely. In this case, you would use Exit (VB.NET) or break (C#) to terminate the loop: VB.NET Dim i As Integer For i = 0 To 10 If (i = 5) Then Response.Write("Oh no! Not the number 5!!") Exit For End If Next C# int i; for (i = 0; i <= 10; i++) { if (i == 5) { Response.Write("Oh no! Not the number 5!!"); break; 69 Order the print version of this book to get all 700+ pages! Loops } } In this case, as soon as our For loop hits 5, it displays a warning message, using the Response.Write() method that will be familiar to those with past ASP experience, and exits the loop so that no further passes through the loop will be made. Although we have only scratched the surface, VB.NET and C# provide a great deal of power and flexibility to the Web developer, and time spent learning the basics now will more than pay off in the future. Understanding Namespaces Because ASP.NET is part of the .NET Framework, we have access to all the goodies that are built into it in the form of the .NET Framework Class Library. This library represents a huge resource of tools and features in the form of classes, all organized in a hierarchy of namespaces. When we want to use certain features that .NET provides, we have only to find the namespace that contains that functionality, and import that namespace into our ASP.NET page. Once we’ve done that, we can make use of the .NET classes in that namespace to achieve our own ends. For instance, if we wanted to access a database from a page, we would import the namespace that contains classes for this purpose, which happens to be the System.Data.OleDb namespace. The dots (.) here indicate different levels of the hierarchy I mentioned—in other words, the System.Data.OleDb namespace is grouped within the System.Data namespace, which in turn is contained in the System namespace. To import a particular namespace into an ASP.NET page, we use the Import directive. Consider the following excerpt from an ASP.NET page; it imports the System.Data.OleDb namespace, which contains classes called OleDbConnection, OleDbCommand, and OleDbDataReader. Importing the namespace lets us use these classes in a subroutine to display records from an Access database: VB.NET <%@ Import Namespace="System.Data.OleDb" %>
C# <%@ Import Namespace="System.Data.OleDb" %>
Don’t worry too much about the code right now (we cover this in detail in Chapter 6). Suffice it to say that, as we’ve imported that namespace, we have access to all the classes that it contains, and we can use them to get information from an Access database for display on our page. 71 Order the print version of this book to get all 700+ pages! Understanding Namespaces Specifically, the classes from System.Data.OleDb that are used in the above code are: OleDbConnection Used for connecting to the database OleDbCommand Used for creating a statement of contents to read from the database. OleDbConnection Used for connecting to the database OleDbCommand Used for creating a statement of contents to read from the database OleDbDataReader Used for actually reading contents from database Object Oriented Programming Concepts VB.NET and C# are great programming languages because they offer a structured way of programming. By structured, I mean that code is separated into modules, where each module defines classes that can be imported and used in other modules. Both languages are relatively simple to get started with, yet offer features sophisticated enough for complex, large-scale enterprise applications. The languages’ ability to support more complex applications—their scalability— stems from the fact that both are object oriented programming (OOP) languages. But ask a seasoned developer what OOP really is, and they’ll start throwing out buzzwords and catch phrases that are sure to confuse you—terms like polymorphism, inheritance, and encapsulation. In this section, I aim to explain the fundamentals of OOP and how good OOP style can help you develop better, more versatile Web applications down the road. This section will provide a basic OOP foundation angled towards the Web developer. In particular, we’ll cover the following concepts: Objects Properties Methods Classes Scope Order the print version of this book to get all 700+ pages! 72 Chapter 3: VB.NET and C# Programming Basics Events Inheritance Objects In OOP, one thinks of programming problems in terms of objects, properties, and methods. The best way to get a handle on these terms is to consider a real world object and show how it might be represented in an OOP program. Many books use the example of a car to introduce OOP. I’ll try to avoid that analogy and use something friendlier: my dog, an Australian Shepherd named Rayne. Rayne is your average great, big, friendly, loving, playful mutt. You might describe him in terms of his physical properties: he’s gray, white, brown, and black, stands roughly one and a half feet high, and is about three feet long. You might also describe some methods to make him do things: he sits when he hears the command "Sit", lies down when he hears the command "Lie down", and comes when his name is called. So, if we were to represent Rayne in an OOP program, we’d probably start by creating a class called Dog. A class describes how certain types of objects look from a programming point of view. When we define a class, we must define the following two things: Properties Properties hold specific information relevant to that class of object. You can think of properties as characteristics of the objects that they represent. Our Dog class might have properties such as Color, Height, and Length. Methods Methods are actions that objects of the class can be told to perform. Methods are subroutines (if they don’t return a value) or functions (if they do) that are specific to a given class. So the Dog class could have methods such as sit(), and lie_down(). Once we’ve defined a class, we can write code that creates objects of that class, using the class a little like a template. This means that objects of a particular class expose (or make available) the methods and properties defined by that class. So, we might create an instance of our Dog class called Rayne, set its properties accordingly, and use the methods defined by the class to interact with Rayne, as shown in Figure 3.3. 73 Order the print version of this book to get all 700+ pages! Objects Figure 3.3. The methods defined by the class interact with the object. This is just a simple example to help you visualize what OOP is all about. In the next few sections, we’ll cover properties and methods in greater detail, talk about classes and class instances, scope, events, and even inheritance. Properties As we’ve seen, properties are characteristics shared by all objects of a particular class. In the case of our example, the following properties might be used to describe any given dog: Color Height Length In the same way, the more useful ASP.NET Button class exposes properties including: Order the print version of this book to get all 700+ pages! 74 Chapter 3: VB.NET and C# Programming Basics Width Height ID Text ForeColor BackColor Unfortunately for me, if I get sick of Rayne’s color, I can’t change it. ASP.NET objects, on the other hand, let us change their properties very easily in the same way that we set variables. For instance, we’ve already used properties when setting text for the Label control, which is actually an object of class Label in the namespace System.Web.UI.WebControls: VB.NET lblMyText.Text = "Hello World" C# lblMyText.Text = "Hello World"; In this example, we’re using a Label control called lblMyText. Remember, ASP.NET is all about controls, and, as it’s built on OOP, all control types are represented as classes. In fact, as you’ll learn in Chapter 4, all interaction with ASP.NET pages is handled via controls. When we place a control on a page, we give it a name through its id attribute, and this ID then serves as the name of the control. Rayne is an object. His name, or ID, is Rayne. Rayne has a height of eighteen inches. The same holds true for the Label control. The Label control’s name or ID in the previous example is lblMyText. Next, we use the dot operator (.) to access the property Text that the object exposes and set it to the string "Hello World." Methods With our dog example, we can make a particular dog do things by calling commands. If I want Rayne to sit, I tell him to sit. If I want Rayne to lie down, I tell him to lie down. In object oriented terms, I tell him what I want him to do by calling a predefined command or method, and a resulting action is performed. In VB.NET or C#, we would write this as rayne.Sit(), or rayne.LieDown(). 75 Order the print version of this book to get all 700+ pages! Methods As Web developers, we frequently call methods when a given event occurs. For instance, the example earlier in this chapter that took information from an Access database created an object called objConn to represent the connection to the database. We then opened the connection by calling the Open() method on that object as follows: VB.NET Dim objConn As As New OleDbConnection( "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=C:\Database\books.mdb") … objConn.Open() We say that the Open() method is exposed by the connection object, and that we’re calling the Open() method on the OleDbConnection object stored in objConn. We don’t need to know what dark secrets the method uses to do its magic; all we need to know is its name and what we use it for. Classes You can think of a class as a template for building as many objects as you like of a particular type. When you create an instance of a class, you are creating an object of that class, and the new object has all the characteristics and behaviors (properties and methods) defined by the class. In our dog example, Rayne was an instance of the Dog class as shown in Figure 3.4. Order the print version of this book to get all 700+ pages! 76 Chapter 3: VB.NET and C# Programming Basics Figure 3.4. A class serves as the blueprint for an object. We see that Rayne is an object of class Dog. In our code, we could create a new instance of the Dog class, call it rayne, and use all the properties and methods exposed by the object. In OOP, when we create new instances of a class, we say we’re instantiating that class. For instance (no pun intended!), if we need to programmatically create a new instance of the Button control class, we could write the following code: VB.NET Dim myButton As New Button() C# Button myButton = new Button(); As you can see, we’ve essentially created a new object called myButton from the Button class. We can then access the properties and methods that the Button exposes through our new instance: VB.NET myButton.Text = "Click Me!" C# myButton.Text = "Click Me!"; 77 Order the print version of this book to get all 700+ pages! Classes Scope You should now have a concept of programming objects as entities that exist in a program and are manipulated through the methods and properties they expose. However, in some cases, we want to create methods to use inside our class, which are not available when that class is used in code. Let’s return to the Dog class to illustrate. Imagine we’re writing the Sit() method inside this class, and we realize that before the dog can sit, it has to shuffle its back paws forward a little (Just bear with me on this one…)! We could create a method called ShufflePaws(), then call that method from inside the Sit() method. However, we don’t want code in an ASP.NET page or in some other class to call this method—it’d just be silly. We can prevent this by controlling the scope of that method. The two types of scope available in VB.NET and C# that you should know about are: Public Defining a property or method of a class as public allows that property or method to be called from outside the class itself. In other words, if an instance of this class is created inside another object (remember, too, that ASP.NET pages themselves are objects), public methods and properties are freely available to the code that created it. This is the default scope in VB.NET and C# classes. Private If a property or method of a class is private, it cannot be used from outside the class itself. If an instance of this class is created inside an object of a different class, the creating object has no access to private methods or properties of the created object. Events We’ve covered events fairly well already. To sum up, events occur when a control object sends a message in response to some change that has happened to it. Generally, these changes occur as the result of user interaction with the control in the browser. For instance, when a button is clicked, a Click event is raised, and we can handle that event to perform some action. The object that triggers the event is referred to as the event sender, while the object that receives the event is referred to as the event receiver. You’ll learn more about these terms in Chapter 4. Order the print version of this book to get all 700+ pages! 78 Chapter 3: VB.NET and C# Programming Basics Understanding Inheritance The term inheritance refers to the ability for one class to use properties and methods exposed by another class. In our dog example, we first created a class called Dog, then created instances of that class to represent individual dogs such as Rayne. However, dogs are types of animals, and many characteristics of dogs are shared by all (or most) animals. For instance, Rayne has four legs, two ears, one nose, two eyes, etc. It might be better, then, for us to create a base class called Animal. When we then define the Dog class, it would inherit from the Animal class, and all public properties and methods of Animal would be available to instances of the Dog class. Similarly, we could create a new class based on the Dog class. In programming circles, this is called deriving a subclass from Dog. For instance, we might create a class for Australian Shepherd and one for my other dog Amigo, called Chihuahua, both of which would inherit the properties and methods of the Dog base class, and define new ones specific to each breed. Don’t worry too much if this is still a little unclear. The best way to appreciate inheritance is to see it used in a real program. The most obvious use of inheritance in ASP.NET comes with the technique of code-behind. Separating Code From Content With Code-Behind Most companies that employ development teams usually split projects into two groups, visual design and functional development, because software engineers are usually poor designers, and designers are often poor engineers. Until now, our ASP.NET pages have contained code render blocks that place VB.NET or C# code directly within the ASP.NET page. The problem with this approach is that there is no separation between the presentational elements of the page and the application logic. Traditional ASP was infamous for creating “spaghetti” code, which was scattered and intertwined throughout the presentation elements. This made it very tricky to manage the code between development teams, as you’ll know if you’ve ever tried to pick apart someone else’s ASP code. In response to these problems, ASP.NET introduces a new way of developing pages that allows code developers to work separately from the presentational designers who lay out individual pages. 79 Order the print version of this book to get all 700+ pages! Understanding Inheritance This new method, called code-behind, keeps all of your presentational elements (controls) inside the .aspx file, but moves all your code to a separate class in a .vb or .cs code-behind file. Consider the following ASP.NET page, which displays a simple button and label: VB.NET
Sample Page using VB.NET
C#
Sample Page using C#
Order the print version of this book to get all 700+ pages! 80 Chapter 3: VB.NET and C# Programming Basics Let’s see how this example could be separated into the following two distinct files: sample.aspx layout, presentation, and static content sample.vb code-behind files containing a custom page class sample.cs First, we take all the code and place it in the code-behind file (sample.vb or sample.cs). This file is a pure code file, and contains no HTML or other markup tags. What it does contain is a class definition. Nevertheless, we can still access presentation elements from this file, using their IDs, such as lblMessage: VB.NET File: sample.vb ' First off we import some useful namespaces Imports System Imports System.Web.UI Imports System.Web.UI.WebControls ' All code-behind classes generally inherit from Page Public Class Sample Inherits Page ' Declare the presentation elements on the ASPX page Protected WithEvents lblMessage As Label Protected WithEvents btnSubmit As Button ' Here's the Click handler just as it appeared before Sub Click(s As Object, e As EventArgs) lblMessage.Text = "Hello World" End Sub End Class C# File: sample.cs // First off we import some useful namespaces using System; using System.Web.UI; using System.Web.UI.WebControls; // All code-behind classes generally inherit from Page public class Sample : Page { // Declare the presentation elements on the ASPX page protected Label lblMessage; protected Button btnSubmit; 81 Order the print version of this book to get all 700+ pages! Separating Code From Content With Code-Behind // Here's the Click handler just as it appeared before public void Click(Object s, EventArgs e) { lblMessage.Text = "Hello World"; } } Without code, the main ASP.NET page becomes much simpler: VB.NET File: sample.aspx <%@ Page Inherits="Sample" Src="Sample.vb" %>
As you can see, the only line that’s different between the .aspx pages is the Page directive: Order the print version of this book to get all 700+ pages! 82 Chapter 3: VB.NET and C# Programming Basics VB.NET File: sample.aspx (excerpt) <%@ Page Inherits="Sample" Src="Sample.vb" %> C# File: sample.aspx (excerpt) <%@ Page Inherits="Sample" Src="Sample.cs" %> The only real change between the VB.NET and C# versions of the page is the source filename extension. In both cases, the page inherits from the class Sample. The code-behind file is written differently from what you’re used to seeing so far. While we no longer need C#
In this case, when the user clicks the button, the ServerClick event is raised, the Click() subroutine is called to handle it, and the ID of the HtmlButton control is written onto the screen with Response.Write() (the Write() method of the Response object). HtmlForm The HtmlForm control creates a server-side HtmlImage The HtmlImage control creates a server-side tag. The following code shows how we might place an HtmlImage control on a page, along with an HtmlButton:
The user could change this image dynamically by pressing the button if we add code as follows: VB.NET
C#
What will happen if these controls are placed on a page along with the script block? First of all, the image arrow.gif will appear. When the HtmlButton control is clicked, it changes to welcome.gif. Behind the scenes, the ServerClick event is raised when the button is clicked, thus the Click() subroutine is called, and the Src property of the HtmlImage control is changed from arrow.gif to welcome.gif. HtmlGenericControl The HtmlGenericControl creates a server-side control for HTML tags that do not have an HTML control associated with them. Perfect examples of this are the and
tags. The following example illustrates how you can 89 Order the print version of this book to get all 700+ pages! HtmlImage modify text within a tag to change the content from I like ASP.NET to Why would anyone need PHP? dynamically. I like ASP.NET
We simply add the following code to respond to the ServerClick event and change the text: VB.NET
C#
HtmlInputButton The HtmlInputButton control creates a server-side , , or HTML tag.
As with HtmlButton, you can assign a server-side event handler to controls of this type with the OnServerClick attribute. HtmlInputCheckBox The HtmlInputCheckBox control creates a server-side HTML tag. Order the print version of this book to get all 700+ pages! 90 Chapter 4: Web Forms and Web Controls />ASP.NET
/>PHP
/>JSP
/>CGI
/>Coldfusion
The HtmlInputCheckBox control is the perfect choice when you want to allow your users to select multiple items from a list. HtmlInputFile The HtmlInputFile control creates a server-side tag in the HTML. This displays a text box and Browse button to allow users to upload files from ASP.NET pages. There is no Web control equivalent for this tag, so it’s typically required when working with file uploads—even with Web Forms (which we’ll discuss shortly).
HtmlInputHidden The HtmlInputHidden control creates a server-side tag.
Try viewing the source of any one of your ASP.NET pages from your browser, and you’re likely to find this tag being used to store view state information. HtmlInputImage The HtmlInputImage control creates a server-side tag. src="ButtonImage.jpg" /> This tag provides an alternative to the HtmlInputButton control. They both function in the same way; the difference is that the HtmlInputImage control uses a custom image rather than the beveled gray Windows-style button. The mouse 91 Order the print version of this book to get all 700+ pages! HtmlInputFile coordinates are also sent along with the form submission when the user clicks a control of this type. HtmlInputRadioButton The HtmlInputRadioButton control creates a server-side radio button. The following code, for instance, offers a choice of Male or Female: Gender?
Male
Female Similar to the HtmlInputCheckBox control, the HtmlInputRadioButton control creates a list of items for users to choose from. The difference, however, is that the user is only able to select one item at a time. HtmlInputText The HtmlInputText control creates a server-side or type="password"> tag. Please Login
Username:
Password:
The preceding code creates a typical login screen layout. HtmlSelect The HtmlSelect control creates a server-side version of the