Basic struction — create Database first ASP MVC Application(Models in three way)

Here in the internet have a lot tutorial introduction about create code first asp mvc application, but in the real life world the database always aready is exsiting. I am not mvc experter, I am fresher now. It took me a while to get the basic struction a while.So I like to write it down wish this could help some people like me struggling in the beginning.

OK, let me asume that we are going to create a online store ecormmerce website.

Way one: basic struction

Then you create a new MVC project through VS2013, first thing is add a connection string to your root web.config file.

It is like this:connectionStr

Modelsisnothingjustclassfile

Models is nothing just class file. You map your table to class file, then when you create a controller you could select strongly type.

finally is the Add one line to Global.asax to stop populater some seed data

GlobalNeedAddOneLine

See the null meaning don’t popular seed data.

Way two: basic struction(Models is another project)

I won’t talk about the controller or the views. But Models could anything, Web services, WCF and don’t sit in your project, the model is not neccessary sit in your project.So your project only have controller and Views, but the Models is independent. Here is a simple practise I did in my Demo struction is like this:

separateModelMvc

Way three: basic struction(Model is your entity Framework)

MvcEntityFrameworkStruction

Create marquee news in front page and the news is read from the database with expired data,also included management page to insert news

My boss just saw other company website has a marquee new on the front page, so she asked me if I could make one and arrow her to insert news and the news will dispear at the expired data.

For achieve that task, first I create a table in my database table, here is my table:

breadNewTable

then I write a store proceedure, a little tip for fresh guy, alway use store preceedure to insert data for security reasons.

breadNewStoreProceedure

Now, We could start the front end job. I create a user control:marquee.ascx(so you could put it in anyway you like), to display the new, here is my html code:

frontUCmarquee

here is the backcod, I used ado.net to open the database and qurery what I need, and bind it to my BulledtedList:

databasereadertomarquee

See the code this if(!IsPostBack) is not neccessary, but I use web froms so it wil inherit maintain state so I don’t need retrieve database everytime postback.

here I am also happy to share the css file for style this unorder list to display inline:

MarqueeCssStyle

A tip for fresh guy, put this in the page your use control will stand it.

Now, you just need drag the usercontrol to any page you want it with this css style in top of the header it. You coud see it.

Then We could start create a page to arrow my boss to insert the bread news, I used boostrap format so it save my time to write css. here is the front page look like:

addNews

here is the html code:

htmlCodeAddnews

The form use jQury Validate, the jquery-ui.js, is for my boss click then will pop up the jQuery calender to arrow her to put the expired date. So simple isn’t, I am love JQure very much, save a lot of time. It remind me when I first time write javascript over 10 years ago, for every simply function I need write a lot codes.

Finally I just need write a event could be fired by this button.

storeIntodatabase

Ok, That’s all. Have fun!

Using c# code to force bootstrap modal stay open after page postback

Recently I write a small function into my asp.net application.To enable the driver to input the time the submit the pick up client and drop off the client time.
My boss like the pick up time and drop off time should been populate by just click.so I write a code on the back of page to retrive the time every time the driver click the button.
But the dropoff button driver me to nuts,Because When the dropoff button click I pop out the bootstrap modal.But the problems came out this button need make page postback to retrive the current time and after postback my modal need stay open.
It take me a while to fix out this.
Here is my solution.
first, I need write javascript like this is for to open the modal: #dropoffModal is my hidden modal.

 function openModal() {
$('#dropoffModal').modal({ show: true });
}
 

Second I have the the button is like this(See the button click will fire a event named:”Button_DropOff_Click” behind it):

 button_click_event_fire_javascript

Finally, just write your event on the page behind file:


protected void Button_DropOff_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}

here just a solution. by the way, You could use ScriptManager.RegisterStartupScript() this command call another function in your frond page javascript.

How to create Picture Upload by using ASP MVC 4

This is a very simply example for how to using asp MVC. In this example doesn’t involved with your database. So start from create a model here is your code for your picture upload model. model is cs file, so save below code as PictureModel.cs


using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MvcDemo.Models
{
    public class PictureModel
    {
        [Required]
        public HttpPostedFileBase PictureFile { get; set; }
    }
}

Then create a action event to your Controller. Controller also just cs file, so save below to one of the Controllers file


//by default, this will be called by get 
public ActionResult PictureUpload()
        {
            return View();
        }

here is the view file code. view is the PictureUpload.cshtml


@model MvcDemo.Models.PictureModel
@{
    ViewBag.Title = "Picture Upload";
}


Picture Upload

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = “multipart/form-data” })) { @Html.AntiForgeryToken() @Html.ValidationSummary(true)

PictureModel 

@Html.LabelFor(model => model.PictureFile)

 

@Html.TextBoxFor(model => model.PictureFile, new { type = “file” }) @Html.ValidationMessageFor(model => model.PictureFile)

} @section Scripts { @Scripts.Render(“~/bundles/jqueryval”) }

After submit, it will call the post, below is the action event for post


[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult PictureUpload(PictureModel model)
        {
            if (model.PictureFile.ContentLength > 0)
            {
                var fileName = Path.GetFileName(model.PictureFile.FileName);
                var filePath = Server.MapPath("~/Content/Uploads");
                string savedFileName = Path.Combine(filePath, fileName);
                model.PictureFile.SaveAs(savedFileName);                
            }
            return View(model);
        }

A store procedure to insert values into multitable without duplicate records

The previous store procedure have records repeated and here is the improve one.

the table like this:

tables

 


  
CREATE PROCEDURE [dbo].[spStoreLMStatusRecording]       
@parameterJobID varchar(30),  
@parameterLMStatus nvarchar(10),  
@parameterEntry_datetime datetime   
   
AS  
BEGIN  
declare   
 @username varchar(500),  
 @Job_Acceptance bit   
    SET @Job_Acceptance = '1'  
   
   
 IF NOT EXISTS(SELECT * FROM tblJob where JobID = @parameterJobID)    
 begin   
  insert into tblJob values(@parameterJobID,@Job_Acceptance);  
  select @username = username from tblUserAuthentication    
  insert into tblLMStatus values(@parameterLMStatus,@parameterEntry_datetime,@parameterJobID,@username)  
 end  
 else  
 begin  
  select @username = username from tblUserAuthentication    
  insert into tblLMStatus values(@parameterLMStatus,@parameterEntry_datetime,@parameterJobID,@username)  
 end  
   
END  

Cookies in ASP.NET

Cookies is a small piece of information stored on the client machine. This file is located on client machines “C:\Document and Settings\Currently_Login user\Cookie” path.  Its is used to store user preference information like Username, Password,City and PhoneNo etc on client machines. We need to import namespace called  Systen.Web.HttpCookie before we use cookie.
 
Type of Cookies?

  1. Persist Cookie – A cookie has not have expired time Which is called as Persist Cookie

  2. Non-Persist Cookie – A cookie has expired time Which is called as Non-Persist Cookie

How to create a cookie?
 
Its really easy to create a cookie in the Asp.Net with help of Response object or HttpCookie
 
Example 1:
 
        HttpCookie userInfo = new HttpCookie(“userInfo”);
        userInfo["UserName"] = “Annathurai”;
        userInfo["UserColor"] = “Black”;
        userInfo.Expires.Add(new TimeSpan(0, 1, 0));
        Response.Cookies.Add(userInfo);

Example 2:
 
        Response.Cookies["userName"].Value = “Annathurai”;
        Response.Cookies["userColor"].Value = “Black”;
                       
How to retrieve from cookie?

Its easy way to retrieve cookie value form cookes by help of Request object.
 
Example 1:
 
        string User_Name = string.Empty;
        string User_Color = string.Empty;
        User_Name = Request.Cookies["userName"].Value;
        User_Color = Request.Cookies["userColor"].Value;

Example 2:
 
        string User_name = string.Empty;
        string User_color = string.Empty;
        HttpCookie reqCookies = Request.Cookies["userInfo"];
        if (reqCookies != null)
        {
            User_name = reqCookies["UserName"].ToString();
            User_color = reqCookies["UserColor"].ToString();
        }
 
When we make request from client to web server, the web server process the request and give the lot of information with big pockets  which will have Header information, Metadata, cookies etc., Then repose object can do all the things with browser.

Cookie’s common property:

  1. Domain => Which is used to associate cookies to domain.

  2. Secure  => We can enable secure cookie to set true(HTTPs).

  3. Value    => We can manipulate individual cookie.

  4. Values  => We can manipulate cookies with key/value pair.

  5. Expires => Which is used to set expire date for the cookies.

Advantages of Cookie:

  1. Its clear text so user can able to read it.

  2. We can store user preference information on the client machine.

  3. Its easy way to maintain.

  4. Fast accessing.

Disadvantages of Cookie

  1. If user clear cookie information we can’t get it back.

  2. No security.

  3. Each request will have cookie information with page.

How to clear the cookie information?

 

  • we can clear cookie information from client machine on cookie folder

 

  1. To set expires to cookie object
    userInfo.Expires = DateTime.Now.AddHours(1);
    It will clear the cookie with one hour duration.

 

This article  is copy from http://www.c-sharpcorner.com/uploadfile/annathurai/cookies-in-Asp-Net/ some article is very useful, I past it here, so I could use it  when I need it.

How to create or customize drupal theme

I thought that I am programmer, but recently I also did a lot of front end job. This post will help the guys want to find out how to customize drupal theme.

For customize or create a new drupal theme, you don’t need to understand the php just need some knowledge about the HTML and CSS then will make you successfully create or customize drupla theme.

First, you need understand the construction of the drupal page. See below the picture, that is the most common useful template.

drupal_template1

Second, here is your theme direction should look like

drupal_theme2

third, those three need have the same name

drupal_theme3

Now we could start now. go to find this file

drupal_theme4

here is the header

drupal_theme6

drupal_theme7

Here is your page.tpl.php

drupal_theme9

the rest of just css and javascript:

drupal_theme10

drupal_theme11

 

 

 

 

 

 

Bootrap Jumbotron into WordPress Theme

In this post I will use a bootstrap Jumbotron template,here is the link http://getbootstrap.com/examples/jumbotron/  I will  customize it into wordpress theme

You need download bootstrap into” yourtheme “folder, whatever theme name you like to call it.

bootstrap_to_wordpress2

 

Those fold should inside your theme folder, don’t worry what are inside it except everything from bootstrap, the other file is empty now.

1) for wordpress could read you theme you need put those on top of your style.css:

/*
Theme Name: Bootstrap to WordPress
Theme URI: http://sandywebdesigner.com
Author: Sandy Zhang
Author URI: http://sandywebdesigner.com
Description: Example theme for  how to convert static Bootstrap site into dynamic WordPress theme
Version: 1.0
License:
License URI:
Text Domain: bootstrap-to-wp

This theme, like WordPress, is licensed under the GPL.
Use it to make something cool, have fun, and share what you’ve learned with others.
*/

/* Move down content because we have a fixed navbar that is 50px tall */
body {
padding-top: 50px;
padding-bottom: 20px;
}
.admin-bar .navbar-fixed-top {
margin-top: 30px;
}
/* Below is the style for navigation in functions.php add a class to sub-menu to the navigation so I just write a simple style to it,you could customize it by yourself */
@media (min-width:768px) {
.sub-menu {
display: none;
position: absolute;
background: #222;
padding: 10px 15px;
width: 150px;
}

li:hover .sub-menu {
display: block;
}

}

.sub-menu li {
margin-bottom: 10px;
list-style: none;
}

.sub-menu li:last-child {
margin-bottom: 0;
}

.sub-menu a  {
color: #999;
text-decoration: none;
}

.sub-menu a:hover  {
color: #fff;
}

.current-menu-item > a, .current-menu-parent > a {
background: #000;
}
.current-menu-parent li a {
background: inherit;
}
.current-menu-parent .current-menu-item a {
color: #fff;
font-weight: bold;
}

.sidebar{
margin-top:40px;
color:#444;
}
.sidebar h3{
color:#888;
}
.widget{
margin:10px 0 30px;
}
article .post{
margin:20px 0;
}

.featured-image img,
.portfolio-piece img,
.portfolio-image img {
max-width:100%;
}

.prev-next{
font-size:24px;
margin-top:30px;
text-align:right;
}

@media (max-width:540px) {
.portfolio-piece h4{
font-size:.8em;
}
.prev-next{
font-size:15px;
margin-top:15px;
text-align:right;
}

}

2)header.php

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset=”<?php bloginfo( ‘charset’ ); ?>”>
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<link rel=”shortcut icon” href=”<?php bloginfo(‘template_directory’);?>/images/favicon.ico”>

<title>
<?php wp_title(‘|’,true,’right’);?>
<?php bloginfo(‘name’)?>

</title>

<?php wp_head(); ?>
</head>

<body <?php body_class(); ?>>

<div class=”navbar navbar-inverse navbar-fixed-top” role=”navigation”>
<div class=”container”>
<div class=”navbar-header”>
<button type=”button” class=”navbar-toggle” data-toggle=”collapse” data-target=”.navbar-collapse”>
<span class=”sr-only”>Toggle navigation</span>
<span class=”icon-bar”></span>
<span class=”icon-bar”></span>
<span class=”icon-bar”></span>
</button>
<a class=”navbar-brand” href=”<?php bloginfo(‘url’); ?>”><?php bloginfo(‘name’); ?></a>
</div>
<div class=”navbar-collapse collapse”>
<?php
$args = array(
‘menu’ => ‘mainmenu’,
‘menu_class’ => ‘nav navbar-nav’,
‘container’ => ‘false’
);
wp_nav_menu($args);
?>
</div><!–/.navbar-collapse –>
</div>
</div>

3)footer.php

<hr>

<footer>
<p>&copy; <?php bloginfo(‘name’);?> <?php echo date(‘Y’); ?></p>
</footer>
</div> <!– /container –>
<?php wp_footer(); ?>
</body>
</html>

3)index.php

<?php get_header(); ?>

<div class=”container”>

<div class=”row”>
<div class=”col-md-9″>
<?php if(have_posts()):while(have_posts()):the_post();?>
<div class=”Page-header”>
<h1><?php the_title(); ?></h1>
</div>
<?php the_content();?>
<?php endwhile; else:?>

<div class=”Page-header”>
<h1>Oh no!</h1>
</div>
<p>No content is appearing for this page!</p>
<?php the_content();?>

<?php endif;?>

</div>
<?php get_sidebar(); ?>

</div>

<?php get_footer(); ?>

4)functions.php

<?php
function theme_styles(){
wp_enqueue_style( ‘bootstrap_css’, get_template_directory_uri() . ‘/css/bootstrap.min.css’ );
wp_enqueue_style( ‘main_css’, get_template_directory_uri() . ‘/style.css’ );
}
add_action( ‘wp_enqueue_scripts’, ‘theme_styles’ );

function theme_js(){
global $wp_scripts;
wp_register_script( ‘html5_shiv’, ‘https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js&#8217;, ”, ”, false );

wp_register_script( ‘respond_js’, ‘https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js&#8217;, ”, ”, false );

$wp_scripts->add_data( ‘html5_shiv’, ‘conditional’, ‘lt IE 9′ );
$wp_scripts->add_data( ‘respond_js’, ‘conditional’, ‘lt IE 9′ );
wp_enqueue_script( ‘bootstrap_js’, get_template_directory_uri() . ‘/js/bootstrap.min.js’, array(‘jquery’), ”, true );
wp_enqueue_script( ‘theme_js’, get_template_directory_uri() . ‘/js/theme.js’, array(‘jquery’,’bootstrap_js’), ”, true );

}

add_action( ‘wp_enqueue_scripts’, ‘theme_js’ );

add_theme_support(‘menus’);
add_theme_support(‘post-thumbnails’);

function register_theme_menus() {
register_nav_menus(
array(
‘header-menu’    => __( ‘mainmenu’ )
)
);
}
add_action( ‘init’, ‘register_theme_menus’ );

function create_widget( $name, $id, $description ) {

register_sidebar(array(
‘name’ => __( $name ),
‘id’ => $id,
‘description’ => __( $description ),
‘before_widget’ => ‘<div class=”widget”>’,
‘after_widget’ => ‘</div>’,
‘before_title’ => ‘<h2>’,
‘after_title’ => ‘</h2>’
));
}

create_widget( ‘Front Page Left’, ‘front-left’, ‘Displays on the left of the homepage’ );
create_widget( ‘Front Page Center’, ‘front-center’, ‘Displays in the center of the homepage’ );
create_widget( ‘Front Page Right’, ‘front-right’, ‘Displays on the right of the homepage’ );
?>

See how simple it is, index.php you completed, then use this index.php to create other template like page.php. single.php, etc. Have fun!

 

 

 

 

 

 

How to customize your own WordPress Theme

Once you could write HTML and CSS website template, then you will be able to customize it to

WordPress Theme.

For to do that, there is some basic thing you need know:

1)Need understand WordPress Template Hierarchy, if you don’t knwo before, don’t scare.
Here is few template you must have in your theme folder.

Index.php //  main Theme templateindex.php
page.php //this is the static page template in wordpress
single.php //this is post page template
home.php // blog template
front-page.php//shown On front
archive.php// for archive page template
search.php// if you don’t have wordpree will use index.php

For more detail could go to http://codex.wordpress.org/Template_Hierarchy

2) WordPress cut page into pieces, so onece you have the html and css page, then slide it into
header.php, footer.php, sidebar.php(if you design have sidebar)

3)Here is the basic function you need it.
The path of style.css is: <?php bloginfo( ‘stylesheet_url’ ); ?>
The path of the theme folder: <?php bloginfo(‘template_directory’); ?>
<?php get_header();?> //this is for you get your header
<?php get_footer();?> // this is for you get your footer
<?php get_sidebar();?> //this is for you get your sidebar, if you have sidebar in your design

<?php if(have_posts()):while(have_posts()):the_post();?>
<?php endwhile; else:?>//this loop is very important,will be use for a lot of times when you

create a wordpress theme

In next post I will use a bootstrap Jumbotron template,here is the link http://getbootstrap.com/examples/jumbotron/  I will  customize it into wordpress theme

Chapter 8: Web Development

1. Html elementary
Create a web page accessible at the URL http://localhost/~student/text.html and within this page insert five headings from largest to smallest heading types. Insert also at least two paragraphs of text, and make some of the text in this page “bold” and some of it “emphasized”.

vim filename.html
<html>
<bold> </bold>
<em> </em>
<h1> </h1> x 5
</html>

 
2. Html hyperlink
Create an HTML web page accessible at the URL http://localhost/~student/extlink.html with exactly one anchor tag linking to http://www.google.com

vim extlink.html
<html>
< a href = “
http://www.google.com”>

 
3. Html preformat
Create a web page accessible at the URL http://localhost/~student/preformat.html and within this page insert two elements: one paragraph, and one block of preformatted text.

vim preformat.html
<p></p>
<pre></pre>

 
4. Html list
Create a web page accessible at the URL http://localhost/~student/list.html. Create within this file only one ordered list with 4 list items. The items may contain any text or html. (You can check your answer by browsing to http://localhost/~student/list.html)

vim list.html
<html>
<ol>
<li> coffee </li>
<li> milk </li>
<li> hot chocolate </li>
<li> tea </li>
</ol>
</html>

 
5. Html table
Create a web page accessible at the URL http://localhost/~student/table.html containing a table with 2 rows and 4 columns, each cell containing a small amount of text.

vim table.html
<tr> </tr> x 2
<td> </td> x 4

 
6. Html picture
Copy the image file /usr/local/linuxgym-data/public_html/fish.jpg into your public_html directory. It should be viewable by following the link http://localhost/~student/fish.jpg Create an HTML web page accessible at the URL http://localhost/~student/picture.html displaying the fish.jpg image, together with some explanatory text.

cp /usr/local/linuxgym-data/public_html/fish.jpg   fish.jpg
vim picture.html
<html>
<img src = “fish.jpg” alt = “Big Fish”>
</html>

 
7. Html index
An index.html file is automatically accessed by the browser without specifying the filename. The goal of this exercise is to create an HTML web page accessible at the URL http://localhost/~student/ As the “front page” of this chapter, give the index.html page links to several other pages in your public_html directory without using “http” in the address. This is called a “relative link”. (A link using “http” in the address is called “absolute”.)

vim index.html
<html>
<a href = “picture.html”>
<a href = “table.html”>
etc
</html>

Best Web Design, web developer, php developer,designers,freelance

Follow

Get every new post delivered to your Inbox.

Join 90 other followers