-->

Sunday, April 5, 2015

Writing Javascript into HTML

JavaScript syntax is embedded into HTML file. A Browser reads HTML files and interprets HTML tags. Since all JavaScripts need to be included as an integral part of an HTML document when required, the browser needs to be informed that specific sections of HTML code is JavaScript. The Browser will then use its built-in JavaScript engine to interpret this code.
The Browser is given this information using HTML tags <SCRIPT>....</SCRIPT>.  The <SCRIPT> tag marks the beginning of a snippet of scripting code. The paired </SCRIPT> marks the end of a snippet of script code.
The <SCRIPT> tag takes an optional attribute, as listed below:

Attributes
Description
Language
Indicates the scripting language used for writing the snippet scripting code. It can take following values:
        1JavaScript
     2. VBScript

Syntax:

<script language="javascript">
<!-- JavaScript statements 
// -->
</script>

For example

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
<script type ="text/javascript" >
    document.write("Hello World!");

</script>
</body>
</html>

The code above will produce this output on an HTML page: 


Writing Javascript into HTML

To insert a JavaScript into an HTML page, we use the <script> tag. Inside the <script> tag we use the type attribute to define scripting language.
So, the <script type="text/javascript"> and </script> tells where a JavaScript starts and ends.
The word document.write is a standard JavaScript command for writing output to a page. 
By entering the document.write command between the <script> and </script> tags. the browser will recognize it as a JavaScript command and execute the code line. In this case the browser will write Hello World! to the page.

World clock app for window phone 8 c#

Introduction

If you want to know time at any location in the world, use this app in windows phone. This app offers numbers of features, including an interactive time zone list. Select any time zone, which is given in the list and check it. No advertisements are shown in this app. Basically This app is designed for beginners, who want to know about windows phone app development.

How to Install it in windows phone

  1. Download the mentioned package
  2. Use .xap file for running it.

Learn How to design it

To create a new app in windows phone 8, the steps are listed below:
To create a new app in windows phone 8
  1. Create a new project by going through File | New Project | Windows Phone Application - Visual C#. Give a desired project name( World Clock is my app name).
  2. From Solution Explorer, open MainPage.xaml file. (If Solution Explorer  is currently not opened then open it via View>>Other Windows>> Solution Explorer).

  3. Change name of your header text, which is in TextBlock(Inside stack panel).
  4. Add a listbox control in the grid panel control. Also bind from ItemSource property.
  5. Add a class in the project, which name is "timezone.cs". Add two public property inside in it. Now, code look like
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace WorldClock
    {
     class timezone
     {
     public String timename { get; set; }
     public string ImagePath { get; set; }
     }
    }
    
    
6.  Now add some utc time in the list collection with flag images. Also bind this with ListBox using DataContext
  List chemists = new List();
            chemists.Add(new timezone() { timename = "UTC-12:00 Internatioanl Date Line West", ImagePath = "image/Internatioanl Date Line West.jpg" });
            chemists.Add(new timezone() { timename = "UTC-11:00 Coordinated Universal Time-11", ImagePath = "image/Internatioanl Date Line West.jpg" });
            chemists.Add(new timezone() { timename = "UTC-10:00 Hawaii", ImagePath = "image/hawaii.jpg" });
            chemists.Add(new timezone() { timename = "UTC-09:00 Alaska", ImagePath = "image/Alaska.gif" });
            chemists.Add(new timezone() { timename = "UTC-08:00 Baja California", ImagePath = "image/bajaflag.jpg" });
            chemists.Add(new timezone() { timename = "UTC-08:00 Pacific Time(US & Canada)", ImagePath = "image/uscan.jpg" });

  7. Now, use DispatcherTimer class for update the time with 1 sec.  Now, use this code for update the time
DispatcherTimer newTimer = new DispatcherTimer();
newTimer.Interval = TimeSpan.FromSeconds(1);
            newTimer.Tick += OnTimerTick;
            newTimer.Start();
void OnTimerTick(Object sender, EventArgs args)
        {
           
         
            clocklabel.Text = DateTime.Now.ToString();
           
         
        }
8 .Create the code for each index of ListBox also display the result on MessageBox.

private void lstCountries_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            switch (list1.SelectedIndex)
            {
                case 0: MessageBox.Show(dt.AddMinutes(-720).ToString() + TimeZoneInfo.Utc.DaylightName);
                    break;
                case 1: MessageBox.Show(dt.AddMinutes(-660).ToString() + TimeZoneInfo.Utc.DaylightName);
                    break;
                case 2: MessageBox.Show(dt.AddMinutes(-600).ToString() + TimeZoneInfo.Utc.DaylightName);
                    break;
                case 3: MessageBox.Show(dt.AddMinutes(-540).ToString() + TimeZoneInfo.Utc.DaylightName);
                    break;
                case 4: MessageBox.Show(dt.AddMinutes(-480).ToString() + TimeZoneInfo.Utc.DaylightName);
                    break;
                case 5: MessageBox.Show(dt.AddMinutes(-480).ToString() + TimeZoneInfo.Utc.DaylightName);
                    break;

            }

        }
9. Run this app in Emulator WVGA 512mb, now code will generate the output.

Run this app in Emulator WVGA 512mb



When you select any item from the given list then phone emulator display the time according to the time zone. Basically this system designed on UTC time.

Saturday, April 4, 2015

SignIn after registration in ASP.NET

In my previous article, we have already learned  that how to create registration page in asp.net 4.5. Today we talk about signin after registration.  Simple API provided by the microsoft  that is Microsoft.AspNet.Identity, various methods and classes given init by the microsoft, such as UserManager class etc . After successfully registration you can  check, whether the registration is success or not using IdentityResult class. If IdentityResult class return true then you will signin into the account using static method of SignIn, which is available in IdentityHelper class. Now, code of your application is

IdentityResult result = manager.Create(user, Password.Text);

if (result.Succeeded)
{

IdentityHelper.SignIn(manager, user, isPersistent: false);

IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);

}

The Simple static SignIn method of IdentityHelper class is

public static void SignIn(UserManager manager, ApplicationUser user, bool isPersistent)
{
IAuthenticationManager authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}

After signin you can redirect to other page. A very simple method provided by the microsoft that is RedirectToReturnUrl (static), which is also available in IdentityHelper class that is


public static void RedirectToReturnUrl(string returnUrl, HttpResponse response)
{
if (!String.IsNullOrEmpty(returnUrl) && IsLocalUrl(returnUrl))
{
response.Redirect(returnUrl);
}
else
{
response.Redirect("~/");
}
}

Business Objects as model in MVC

We have to already implement mvc project to retrive data with the help of model folder. Today, we will discuss about business objects as model in MVC. First to implement the business logic in the separate project. Add a new class library project in the solution, also Add two class in it. First class that is, department.cs. Copy this code and paste into your department.cs file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BusinessModel
{
public class department
{
public int Id { get; set; }
public string Name { get; set; }
}
}

Code define the department table properties that is Id and Name. Second class that is, BusinessLayermodel.cs.

Copy this code and paste into your BusinessLayermodel.cs file

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace BusinessModel
{
public class BusinessLayermodel
{
public IEnumerable<department> departments
{
get
{
List<department> dept = new List<department>();

SqlConnection con = new SqlConnection();
con.ConnectionString= ConfigurationManager.ConnectionStrings ["EmployeeConnection"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from [Department]";
cmd.Connection = con;

SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
department dt = new department();
dt.Id=Convert.ToInt32(rd[0].ToString());
dt.Name = rd[1].ToString();
dept.Add(dt);

}
return dept;
}
}
}
}
In this code, we have a public class BusinessLayermodel with single public property that is departments. This class work as context class, through this, we can access data from the database table by the public property of departments . Comparison between business layer model v/s MVC
model
 
business layer model v/s MVC   model


     Add a reference of the class library project into the MVC project. Add a department controller  in the controller folder. Through which, we will retrieve list of data. Copy this code and paste into your DepartmentController class.
using BusinessModel;

namespace WebApplication11.Controllers
{
public class DepartmentController : Controller
{
//
// GET: /Department/
public ActionResult Index()
{
BusinessLayermodel blt = new BusinessLayermodel();
List<department> dept = blt.departments.ToList();

return View(dept);
}
}
}
Build the project before adding the view in the MVC project. Right click on your controller class, Add new view by the snap shot.

Build the project before adding the view in the MVC project


   Note :  Select List as a Template, also select department as model class which is inside in Library class project. After adding the view in the MVC project.

 the view in the MVC project.
 
  Now run your application, without any changes in the View. Now, Your code generate the following output
 
Now run your application, without any changes in the View.
   

Fix Application is currently offline

Application is currently offline error occurs in the browser. Offen, when we work with the SQL-Sserver then that's types of problem occurs. When, today i  was develop a new project with the help of SQl. i face this error during demonstration. I want to say that when we retrieve data from database table through Sql DataSource control. I was run my application in browser, error becomes in the browser. Actually its not a error, you can say its a exception, which is detect by the browser. I think, this is overloading exception,  after some time buffer is full so dotnet framework create a page for this types of exception.

Exception snapshot

 

How to fix it

  1. Remove the app offline page (HTML page) from the project folder
  2. Empty your Recycle Bin

How to Hide web application code from users in ASP.NET

If we talk about web application projects then we simply says that each presentation page attach with code behind page(where you can design your business logic code). If you are a developer and you want to sell your project without code then you will hide its business logic code behind the ".DLL" (dynamic link library) file.
There are available some steps to do this task.
These are
  1. Create a web application project (file--new project--Visual C# --Web -- ASP.NET web Form application)
  2. Write project name, which you want, In this article we take "hide code" as a project name.
new web project in asp.net

3. Delete all directories from the solution explorer. Because i want to design only business logic code, after coding we will create DLL file for this. For this you should attach a class file in this project. Take a look after deleted all files from solution explorer.

deleted all files from solution explorer.

4.  Now, we learn how to attach a class file in the project. Select "add new item" from context menu by right clicking on project name.
Select "add new item"

Now, here appear a new window. In this window select code in left panel and also select class in the right panel.
 select code in left panel and also select class in the right panel.

5.  Write the business logic code for display message on the screen, so we raise a button handler code in displayResult class.
You can design your code for multiple classes through this approach we will create a business logic model. Suppose i want to create a small application for employee, in which i want to display data of employee also display employee salary. Application hold two function first for employee data and second for employee salary. Similarly through this code i want to display "Hello World!" message on the browser. Now your code look like
business logic model

In the above mentioned snap displayResult class inherits from page class, page class contains some object like response,request etc. if you want to use page objects then created class must be inherits from Page class. Also mentioned two namespace, first is System.Web.UI and other is System.Web.UI.WebControls.
6.  Build the solution by selecting "Build HideCode" from Build Tab.
Build the solution by selecting "Build HideCode"

Now your .DLL file has made in Bin folder of the project. File contains single namespace(HideCode) , class(displayResult) and single method(displayresult( )).
7. Now add new project in the solution by right clicking on solution name. Select ASP.NET Web form application project in appeared window also write name of the project, i keep presentation part as a project name. Now your solution explorer contains two project, see below
solution explorer contains two project

8.  Now add new web form in the project also change the name of it, i keep  "presentationpage.aspx" as a project name. This page is basically used for designing purpose. Through this page we can call method of other projects, but will do some changes in the page . Before doing this, first of all add above mentioned project reference in the current project. Learn how to add reference in the project.
Note : Remove all attached file from this page.
 Remove all attached file from this page

(a) Add Reference by right click on References link. select Solution from the appeared window also select .dll checkbox which is appeared in right panel of it.
select .dll checkbox which is appeared in right panel

9. Remove "CodeBehind" attribute from presentation page also add inherits attribute in the page directive. Assign namespace , which is created in earlier project  with class name. Look like
 Remove "CodeBehind" attribute

10. Add button in the page also raise onclick event on it. Call displayresult( ) method, which is created in business logic code. now your code look like
<%@ Page Language="C#" AutoEventWireup="true" Inherits="HideCode.displayResult" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="hide coding" OnClick ="displayresult" />
</div>
</form>
</body>
</html>

Now your code generate the following output

How to Hide web application code from users in ASP.NET

First code of line define the page directive. In this line,you must to add namespace with class name in inherits attribute. After that you can access methods and properties of that class. In this code i also access method of displayResult class using Button click event.

Tuesday, March 31, 2015

Can we take multiple web.config files in single asp.net application

Yes,  we can take multiple web.config files in the single asp.net application. If we have a single directory then we can add multiple config file with different name. If you want to access xml tag from config file then you can access only web.config file elements. Lets take an simple example of the file.


web.config file

<configuration>
  <appSettings>
    <add key="first" value="My first web.config file"/>   
    
  </appSettings>
</configuration>

Default.aspx file

    <asp:Label ID="Label1" runat="server" Text="<%$appSettings:first%>"></asp:Label> 

Its working fine, but when we take another config file in the application then get the error like file not found error. So, i have a solution of this problem. Follow the mentioned steps to overcome this problem:
Step-1 : Add a new directory in the solution(application)
Step-2 : Add new web.config file in the newly created directory.
Step-3 : Also add a web form in the directory.
Step-4 : Now, you can easily access web.config file which is available in the newly created directory.
© Copyright 2013 Computer Programming | All Right Reserved