Saturday, 27 June 2015

Bootstarp

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="boot1.aspx.cs" Inherits="boot1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="javascript/jquery.js"></script>
    <link href="Bootstrap/css/bootstrap.min.css" rel="stylesheet" />
    <link href="Bootstrap/css/bootstrap-theme.min.css" rel="stylesheet" />
</head>
<body>
    <nav class="navbar navbar-inverse navbar-fixed-top" id="my-navbar" >
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#asd">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                    </button>
                <a href="" class="navbar-brand" >wiredWiki</a>
           
            </div><!-- navbar header-->
            <div class="collapse navbar-collapse" id="asd" >
                   <a href="" class="btn btn-info navbar-btn navbar-right " >Download Now</a>

                <ul class="nav navbar-nav">
                    <li> <a href="#feedback">Feedback</a>
                    <li> <a href="#galary">GALARY</a>
                    <li> <a href="#faq">FAQ</a>
                    <li> <a href="#contact">CONTACT US</a>
                </ul>
            </div>
        </div>
    </nav>
    <div class="jumbotron" >
        <div class="container text-center" >
            <h1>Hello word!!!</h1>
            <p>hiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii</p>
            <div class="btn-group">
                <a href="" class="btn btn-lg btn-danger" >First</a>
                <a href="" class="btn btn-lg btn-default" >Secound</a>
                <a href="" class="btn btn-lg btn-warning" >Thrid</a>
            </div>
        </div>

    </div>
    <div class="container">
        <div class="page-header" id="feedback">
            <h1>Feedback</h1>
            <p>hellllllllllllllooooooooooooooooo!!!!!!!</p>
        </div>
    </div><!--container close-->
    <div class="row">
        <div class="col-lg-4 text-center">
            <blockquote>
                <p>hdsdhajshdkjashjkdj
                    habdjhgwdjgwajsdhhsaghdsgf;uea
                    yriufyiweuryfusdgjsdgfkjdsfkgsdjkfs
                    djkfhfdiougioreufosdlihdjfdsjf</p>
                <footer>joe smith</footer>
            </blockquote>
        </div>
        <div class="col-lg-4 text-center">
            <blockquote>
                <p>hdsdhajshdkjashj
                    kdjhabdjhgwdjgwajsdhhsaghdsgf;u
                    eayriufyiweuryfusdgjsdgfkjdsfkgsdjkf
                    sdjkfhfdiougioreufosdlihdjfdsjf</p>
                <footer>joe smith</footer>
            </blockquote>
        </div>
        <div class="col-lg-4 text-center">
            <blockquote>
                <p>hdsdhajshdkjashjkdjhab
                    djhgwdjgwajsdhhsaghdsgf;ueayriufyiweuryfus
                    dgjsdgfkjdsfkgsdjkfsdjkf
                    hfdiougioreufosdlihdjfdsjf</p>
                <footer>joe smith</footer>
            </blockquote>
        </div>
    </div><!-- close row div-->
    <div class="well">
        <div class="container text-center">
            <p>Substription for more stuff</p>
            <form action="" class="form-inline">
                <div class="form-group">
                <input id="Text1" type="text" class="form-control"  /><input id="Button1" type="button" value="click me!!!" class="btn btn-info" />
                    </div>
            </form>
        </div>
    </div><!--close well div-->

    <!-- galaryyyy-->
    <div class="container">
        <div class="page-header" id="galary">
        <h2>Galary!!!</h2>
        </div>
        <div class="carousel slide" id="screenshot" data-ride="carousel">
            <ol class="carousel-indicators">
                <li data-target="#screenshot" data-slide-to="0" class="active"></li>
                <li data-target="#screenshot" data-slide-to="1"></li>
                <li data-target="#screenshot" data-slide-to="2"></li>
                <li data-target="#screenshot" data-slide-to="3"></li>
            </ol>
            <div class="carousel-inner">
                <div class="item active">
                   <img src="img/slide1.jpg" />
                </div>
                 <div class="item">
                     <img src="img/415518.jpg" />
                </div>
                 <div class="item">
                     <img src="img/551030_459715544042762_253466538_n.jpg" />
                </div>
                 <div class="item">
                     <img src="img/408469.jpg" />
                </div>

            </div><!--close carousel inner-->

            <a href="#screenshot" class="left carousel-control" data-slide="prev">
                <span class="glyphicon-chevron-left" ></span>
            </a>
            <a href="#screenshot" class="right carousel-control" data-slide="next">
                <span class="glyphicon-chevron-right" ></span>
            </a>
        </div><!--close carousel slider-->
    </div><!--close container-->

    <div class="container" id="faq">
        <div class="page-header" id="header">
        <h2>FAQ</h2>  
        </div>
            <div class="panel-group" id="accordion">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <div class="panel-title">
                            <a href="#reply1" data-toggle="collapse" data-parent="#accordion">
                                QUESTION1
                            </a>
                        </div>
                        <div id="reply1" class="panel-collapse collapse" >
                            <div class="panel-body">
                                hhhhhhhhhhhhhhhhhhh!!!!!!!!!!!!!!!!!!!
                            </div>
                        </div>
                    </div>
                </div><!-- close panel group-->
           

        </div>
         <div class="panel-group" id="accordion2">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <div class="panel-title">
                            <a href="#reply2" data-toggle="collapse" data-parent="#accordion2">
                                QUESTION2
                            </a>
                        </div>
                        <div id="reply2" class="panel-collapse collapse" >
                            <div class="panel-body">
                                hhhhhhhhhhhhhhhhhhh!!!!!!!!!!!!!!!!!!!
                            </div>
                        </div>
                    </div>
                </div><!-- close panel group-->
           

        </div>
         <div class="panel-group" id="accordion3">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <div class="panel-title">
                            <a href="#reply3" data-toggle="collapse" data-parent="#accordion3">
                                QUESTION 3
                            </a>
                        </div>
                        <div id="reply3" class="panel-collapse collapse" >
                            <div class="panel-body">
                                hhhhhhhhhhhhhhhhhhh!!!!!!!!!!!!!!!!!!!
                            </div>
                        </div>
                    </div>
                </div><!-- close panel group-->
        </div>
    </div><!--CLOSE FEATURE DIV-->

    <div class="container" id="contact">
        <div class="page-header">
            <h2>CONTACT US<small> for more details!!!</small></h2>
        </div>
        <div class="row">
            <div class="col-lg-6">
                <p><strong>Mayur vihar phase 3</strong><br />
                    new delhi - 110096<br />
                    India<br />
                    Mobile no. 9999999999<br />
                </p>
            </div><!--close col lg  -->
            <div class="col-lg-6">
                <form action="" class="form-horizontal">
                <div class="form-group">
                    <label for="user-name" class="col-lg-2 control-label">Name</label>
                    <div class="col-lg-10">
                        <input id="Text2" type="text" class="form-control" />
                    </div>
                </div>
                    <div class="form-group">
                    <label for="user-email" class="col-lg-2 control-label">Email</label>
                    <div class="col-lg-10">
                        <input id="Text3" type="text" class="form-control" />
                    </div>
                </div>
                    <div class="form-group">
                    <label for="user-mobile" class="col-lg-2 control-label">Mobile No.</label>
                    <div class="col-lg-10">
                        <input id="Text4" type="text" class="form-control" />
                    </div>
                </div>
                    <div class="form-group">
                    <label for="user-message" class="col-lg-2 control-label">Comment</label>
                    <div class="col-lg-10">
                        <textarea id="TextArea1" cols="20" rows="4" class="form-control"></textarea>
                    </div>
                </div>
                    <div class="form-group">
                    <div class="col-lg-4 col-lg-offset-8">
                        <input id="Button2" type="button" value="button" class="btn btn-info form-control" />
                    </div>
                </div>
                    </form>
            </div>
        </div><!--close row-->
    </div>

     <script src="Bootstrap/js/bootstrap.min.js"></script>
    <script src="Bootstrap/html5shiv.min.js"></script>
    <script src="Bootstrap/respond.min.js"></script>
</body>
</html>

Friday, 26 June 2015

CORS in Ajax jquery

<script type="text/javascript">
        $(document).ready(function () {
            var contentType = "application/x-www-form-urlencoded; charset=utf-8";
            if (window.XDomainRequest)
                contentType = "text/plain";

            $.ajax({
                url: "http://uatsolutions.mypacco.com/api/TrackOrder",
                type: "Post",
                datatype: "json",
                data: '{"AppId":"46b4e721-18bd-4fd6-8209-a805aea2da5b","Token":"1234","tdata": {"awb_no":"794640356942"}  }',
              //  data: '{"AppId":"46b4e721-18bd-4fd6-8209-a805aea2da5b","Token":"1234","tdata":[ {"awb_no":"794640356942"} ] }',
                contentType: contentType,
                success: function (data) {
                    alert('hii  ' + JSON.stringify(data));
                },
                error: function (response) { alert('error' + JSON.stringify(response)); }
            });
        });
    </script>

Monday, 22 June 2015

output parameter in stored procedure

Stored Procedure

CREATE PROCEDURE [dbo].[GetFruitName]
      @FruitId INT,
      @FruitName VARCHAR(30) OUTPUT
AS
BEGIN
      SET NOCOUNT ON;
     
      SELECT @FruitName = FruitName
      FROM Fruits
      WHERE FruitId = @FruitId
END

Now Sql Code


string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constring))
    {
        using (SqlCommand cmd = new SqlCommand("GetFruitName", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@FruitId"int.Parse(txtFruitId.Text.Trim()));
            cmd.Parameters.Add("@FruitName"SqlDbType.VarChar, 30);
            cmd.Parameters["@FruitName"].Direction = ParameterDirection.Output;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            lblFruitName.Text = "Fruit Name: " + cmd.Parameters["@FruitName"].Value.ToString();
        }
    }

Wednesday, 17 June 2015

Web Config for WCF

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>

    <system.web>
      <compilation debug="true" targetFramework="4.0" />
    </system.web>
  <connectionStrings>
    <add name="connetDis2" connectionString="Data Source=MANI-PC\SQLEXPRESS;Initial Catalog=tesing;Integrated Security=True" />
  </connectionStrings>
 
    <system.serviceModel>

      <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>

      <services>
       
          <!--Add this line-->
        <service name="Service" behaviorConfiguration="ServiceBehavior">
          <endpoint address="http://localhost:4904/Service.svc" binding="webHttpBinding" contract="IService" behaviorConfiguration="EndPointBehavior"/>
        </service>
      <!--Add this line-->
     
      </services>
     
      <behaviors>
            <serviceBehaviors>
                <behavior name="ServiceBehavior">
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="false" />
                </behavior>
            </serviceBehaviors>
       
<!--Add this line-->
        <endpointBehaviors>
          <behavior name="EndPointBehavior">
            <enableWebScript/>
          </behavior>
        </endpointBehaviors>
        <!--Add this line-->
     
        </behaviors>
     
    </system.serviceModel>
</configuration>

Tuesday, 16 June 2015

Rank, Dense_Rank and Row_Number



RANK()

Returns the rank of each row in the result set of partitioned column.
select Name,Subject,Marks,
RANK() over(partition by name order by Marks desc)Rank
From ExamResult
order by name,subject

Rank() Example

DENSE_RANK()

This is same as RANK() function. Only difference is returns rank without gaps.
select  Name,Subject,Marks,
DENSE_RANK() over(partition by name order by Marks desc)Rank
From ExamResult
order by name

DENSE_RANK() Example
In RANK() result set screenshot, you can notice that there is gap in Rank(2) for the name Sam and same gap is removed in DENSE_RANK().

NTILE()

Distributes the rows in an ordered partition into a specified number of groups.
It divides the partitioned result set into specified number of groups in an order.

Example for NTILE(2)

select Name,Subject,Marks,
NTILE(2) over(partition by name order by Marks desc)Quartile
From ExamResult
order by name,subject

NTILE(2) Example

Example for NTILE(3)

select Name,Subject,Marks,
NTILE(3) over(partition by name order by Marks desc)Quartile
From ExamResult
order by name,subject

NTILE(3) Example

ROW_NUMBER()

Returns the serial number of the row order by specified column.
select Name,Subject,Marks,
ROW_NUMBER() over(order by Name) RowNumber
From ExamResult
order by name,subject
 ROW_NUMBER() Example

Friday, 12 June 2015

Web API in MVC

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using abc.Models;
using System.Data;
using System.Xml;
using System.Net.Http;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Threading.Tasks;  

 public  ActionResult LoginUser(Loginguser log)
        {
            if (ModelState.IsValid)
            {
                try
                {                                      
                       HttpClient webClient1 = new HttpClient();
                       string pass = log.password;

                       //Uri uri = new Uri("http://m.abc.com/service/userprofile.svc/logIn?loginId=" + log.username + "&pass=" + log.password);
                       Uri uri = new Uri("http://m.vinipost.com/service/userprofile.svc/logInUsrTyp?loginId=" + log.username + "&pass="+pass +"&usrTyp=1");
                       var response1 = webClient1.GetAsync(uri).Result;



                       var jsonString = response1.Content.ReadAsStringAsync().Result;

                        string[] x = jsonString.Split('[');
                        string[] y = x[1].Split(']');
                        string res = "[" + y[0] + "]";

                        var _Data = JsonConvert.DeserializeObject<List<JClass>>(res);
                        string msg = null;                    
                        string Name = null;

                        foreach (JClass Student in _Data)
                        {
                           msg = Student.msg;
                           Name = Student.Name;
                        }

                      if(msg!=null)
                      {
                          ViewBag.reg = msg;
                          return View();
                      }
                      Session["Username"] =Name;
                      if (Session["Reviewuser"] != null)
                              {
                                 string id = Session["Reviewuser"].ToString();
                                 if (globevar.cid == 1)
                                  {
                                     return RedirectToAction("CabShows", "CabService");
                                  }
                                  return RedirectToAction("Reviews", "Review", new { id1 = id });
                             }
                             else
                                 return RedirectToAction("Show", "User");


                     /* Connection obj = new Connection();
                      DataSet ds = new DataSet();
                      string pass = log.password.ToString();//globevar.Decryptdata(log.password.ToString());
                      string s = "select U_Type from User_Master where U_Name='" + log.username.ToString() + "' and U_Password='" + pass.ToString() + "'";
                      ds = obj.Getdata(s);
                      if (ds.Tables[0].Rows.Count > 0)
                      {
                          Session["Username"] = log.username.ToString();
                          if (Session["Reviewuser"] != null)
                          {
                              string id = Session["Reviewuser"].ToString();
                              if (globevar.cid == 1)
                              {
                                  return RedirectToAction("CabShows", "CabService");
                              }
                              return RedirectToAction("Reviews", "Review", new { id1 = id });
                          }
                          else
                              return RedirectToAction("Show", "User");
                      }
                      else
                      {
                          ViewBag.reg = "Invalid ID or Password";
                          return View();
                      }

                    */

                }
                catch (Exception)
                {
                    return View();
                }
            }
            else
                return View();
        }
     

Thursday, 11 June 2015

Bind dropdown MVC

<div class="form-group">
                                        <label for="exampleInputEmail1">User Name</label>
                                        <input list="stat" name="user_name" class="form-control" required />
                                        <datalist id="stat">
                                            @foreach (var cell in ViewBag.user)
                                            {
                                                <option>@cell</option>
                                            }
                                        </datalist>
                                    </div>


Controller


public ActionResult addHolidayPack()
        {
             if (Session["User_Name"] != null)
             {
            try
            {              
                string s = null;
                DataTable dt = new DataTable();
                string str = "select th_name from Theme_master";
                dt = con.GetdataTable(str);
                ArrayList lis = new ArrayList();
                int n = dt.Rows.Count;
                for (int j = 0; j < n; j++)
                {
                    s = dt.Rows[j]["th_name"].ToString();
                    lis.Add(s);
                }
                ViewBag.theme = lis;


                string s1 = null;
                DataTable dt1 = new DataTable();
                string str1 = "select PK_name from Pack_Type";
                dt1 = con.GetdataTable(str1);
                ArrayList lis1 = new ArrayList();
                int n1 = dt1.Rows.Count;
                for (int j = 0; j < n1; j++)
                {
                    s1 = dt1.Rows[j]["PK_name"].ToString();
                    lis1.Add(s1);
                }
                ViewBag.pack = lis1;

                string s3 = null;
                DataTable dt3 = new DataTable();
                string str3 = "select U_Name from User_Master where U_Type='V'";
                dt3 = con.GetdataTable(str3);
                ArrayList lis3 = new ArrayList();
                int n3 = dt3.Rows.Count;
                for (int j = 0; j < n3; j++)
                {
                    s3 = dt3.Rows[j]["U_Name"].ToString();
                    lis3.Add(s3);
                }
                ViewBag.user = lis3;

                return View();
            }
            catch
            {
                return View();
            }
            }
           else
            {
                return RedirectToAction("Login", "Cp");
            }
        }

Validation in Asp.net MVC

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

namespace Book_Package.Models
{
    public class SignUp
    {
        [Required(ErrorMessage = "Please Enter Valid Name")]
        [Display(Name = "firstname")]
        [MinLength(2)]
        public string firstname { get; set; }
        public string lastname { get; set; }
        [Display(Name = "mobile(Mobile)")]
        [StringLength(10, ErrorMessage = "The Mobile must contains 10 characters", MinimumLength = 10)]
        public string mobile { get; set; }
        [Required(ErrorMessage = "Please Enter Valid Email Address")]
        [Display(Name = "email(Email Address)")]
        [RegularExpression(".+@.+\\..+", ErrorMessage = "Please Enter Correct Email Address")]
        public string email { get; set; }
        [Required(ErrorMessage = "Please Enter Password")]
        [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "password")]
        public string password { get; set; }
        [Required(ErrorMessage = "Please Enter Confirm Password")]
         [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
         [DataType(DataType.Password)]
         [Display(Name = "confirmpassword")]
         [Compare("password", ErrorMessage = "The password and confirmation password do not match.")]
        public string confirmpassword { get; set; }
    }
}

Admin Controller

Admin Controller:-


using GsMentors.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using System.IO;

namespace GsMentors.Controllers
{
    public class AdminController : Controller
    {
        //
        // GET: /Admin/
        private gs_dbEntities con = new gs_dbEntities();
        public ActionResult Index()
        {
            if (Session["userid"] != null)
                return View();
            else
                return RedirectToAction("Login", "Admin");
        }
        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Login(LoginModel  call)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (!string.IsNullOrEmpty(call.UserName.ToString()) && !(string.IsNullOrEmpty(call.Password.ToString())))
                    {

                        var i = from o in con.User_Master where o.U_Name.Equals(call.UserName) && o.U_Password.Equals(call.Password) select o;
                        if (i.ToList().Count() > 0)
                        {
                            Session["userid"] = call.UserName.ToString();
                            return RedirectToAction("Index", "Admin");
                        }
                        else
                        {
                            ViewBag.err = "Invalid ID or Password!";
                            return View();
                        }
                    }
                    return View();
                }
                else
                    return View();
            }
            catch (Exception)
            {
                return View();
            }
        }

        public ActionResult Category()
        {
            var data = con.Category_Master.ToList();
            return View(data);
        }
      
        public ActionResult Comments()
        {
            return View();
        }
        
        public ActionResult addCat()
        {
            return View();
        }

        [HttpPost]
        public ActionResult addCat(Category_Master model)
        {
            if(ModelState.IsValid)
            {
                con.Category_Master.Add(model);
                con.SaveChanges();
                return RedirectToAction("Category");
            }           
            return View();
        }
        public ActionResult EditCat(int id=0)
        {
            Category_Master data = con.Category_Master.Find(id);
            if(data==null)
            {
                return HttpNotFound();
            }
            return View(data);
        }

        [HttpPost]
        public ActionResult EditCat(Category_Master model)
        {
            if(ModelState.IsValid)
            {
                con.Entry(model).State = EntityState.Modified;
                con.SaveChanges();
                return RedirectToAction("Category");
            }
            return View(model);
        }
        public ActionResult DeleteCat(int id=0)
        {
            Category_Master data = con.Category_Master.Find(id);
            if(data==null)
            {
                return HttpNotFound();
            }
            con.Category_Master.Remove(data);
            con.SaveChanges();
            return RedirectToAction("Category");
        }

        //Blogs goes here...
        public ActionResult Post()
        {
            var data = con.Blog_Master.Include(x => x.User_Master).Include(x => x.Category_Master);
            return View(data.ToList());
        }
        public ActionResult addPost()
        {
            ViewBag.User_ID = new SelectList(con.User_Master, "ID", "U_Name");
            ViewBag.Cat_ID = new SelectList(con.Category_Master, "ID", "Name");
            return View();
        }
        [HttpPost]
        public ActionResult addPost(Blog_Master data,IEnumerable<HttpPostedFileBase> image)
        {            
            if(ModelState.IsValid)
            {
                foreach (HttpPostedFileBase file in image)
                {
                    string cat_id = null;
                    if (file != null)
                    {
                        int max = 0;
                        int len = file.FileName.Length;
                        int startlen = len - 4;
                        string strlen = file.FileName.Substring(startlen);
                        var val=con.Blog_Master.FirstOrDefault(x=>x.ID.Equals(1));
                        if (val== null)
                        {
                            max = 0;
                        }
                        else
                        {

                            max = con.Blog_Master.Max(s => s.ID);
                        }
                                           
                        max++;
                        cat_id = "Blog" + "_" + max + strlen;
                        var path = Path.Combine(Server.MapPath("~/Image"), cat_id);
                        file.SaveAs(path);
                    }
                    Blog_Master obj = new Blog_Master();
                    obj.Cat_ID = data.Cat_ID;
                    obj.User_id = data.User_id;
                    obj.Title = data.Title;
                    obj.Tags = data.Tags;
                    obj.Pic = cat_id;
                    obj.Descr = data.Descr;
                    obj.Date = DateTime.Now.ToString();

                    con.Blog_Master.Add(obj);
                    con.SaveChanges();
                    return RedirectToAction("Post");
                }
            }
            ViewBag.User_ID = new SelectList(con.User_Master, "ID", "U_Name");
            ViewBag.Cat_ID = new SelectList(con.Category_Master, "ID", "Name");
            return View(data);
        }
        public ActionResult EditPost(int id=0)
        {
            Blog_Master data = con.Blog_Master.Find(id);
            if (data == null)
            {
                return HttpNotFound();
            }
            ViewBag.User_ID = new SelectList(con.User_Master, "ID", "U_Name");
            ViewBag.Cat_ID = new SelectList(con.Category_Master, "ID", "Name");
            return View(data);
        }
        [HttpPost]
        public ActionResult EditPost(Blog_Master data,IEnumerable<HttpPostedFileBase> image)
        {
            if (ModelState.IsValid)
            {
                foreach (HttpPostedFileBase file in image)
                {
                    string cat_id = null;
                    if (file != null)
                    {
                        int len = file.FileName.Length;
                        int startlen = len - 4;
                        string strlen = file.FileName.Substring(startlen);

                        cat_id = "Blog" + "_" + data.ID + strlen;
                        var path = Path.Combine(Server.MapPath("~/Image"), cat_id);
                        file.SaveAs(path);
                    }
                    Blog_Master obj = new Blog_Master();
                    obj.ID = data.ID;
                    obj.Cat_ID = data.Cat_ID;
                    obj.User_id = data.User_id;
                    obj.Title = data.Title;
                    obj.Tags = data.Tags;
                    obj.Pic = cat_id;
                    obj.Descr = data.Descr;
                    obj.Date = DateTime.Now.ToString();
                                     
                    con.Entry(obj).State = EntityState.Modified;
                    con.SaveChanges();
                    return RedirectToAction("Post");
                }
            }
            ViewBag.User_ID = new SelectList(con.User_Master, "ID", "U_Name");
            ViewBag.Cat_ID = new SelectList(con.Category_Master, "ID", "Name");
            return View(data);
        }
        public ActionResult DeletePost(int id=0)
        {
            Blog_Master data = con.Blog_Master.Find(id);
            if (data == null)
            {
                return HttpNotFound();
            }
            con.Blog_Master.Remove(data);
            con.SaveChanges();
            return RedirectToAction("Post");
        }
        public ActionResult Logout()
        {
            Session.Abandon();
            return RedirectToAction("Login", "Admin");
        }
    }
}

ViewData in MVC

View:-


@model IEnumerable<GsMentors.Models.Blog_Master>

@{
    Layout = "~/Views/Shared/_masterLayouth.cshtml";
}
@{

    IEnumerable<GsMentors.Models.Blog_Master> recent = ViewData["recent"] as IEnumerable<GsMentors.Models.Blog_Master>;
    IEnumerable<GsMentors.Models.Category_Master> cat = ViewData["cat"] as IEnumerable<GsMentors.Models.Category_Master>;
}

@*@section sl_image
{
    <img src="../../image1/header.jpg" />
}*@

<div class="container">
    <div class="row" style="float:left">




        @foreach (var item in Model)
        {
            <div class="col-md-1 date">
                <p><strong>@Html.DisplayFor(x => item.Date)</strong></p>
            </div>
            <div class="col-md-6">
                <h3>
                    <a href="/Blogs/Index/@item.ID" style="text-decoration:none;">
                        @Html.DisplayFor(x => item.Title)
                    </a>
                </h3>
                <p>
                    <a href="#"><span class="glyphicon glyphicon-user"></span>@Html.DisplayFor(x => item.User_Master.U_FirstName)@Html.DisplayFor(x => item.User_Master.U_LastName)</a>
                    <a href="#"><span class="glyphicon glyphicon-lock"></span>@Html.DisplayFor(x => item.Category_Master.Name)</a>&nbsp;
                    <a href="#"><span class="glyphicon glyphicon-tag"></span>@Html.DisplayFor(x => item.Tags)</a>&nbsp;
                    <a href="#"><span class="glyphicon glyphicon-cloud"></span>Leave a comment</a>
                </p>
                <p>
                    @Html.DisplayFor(x => item.Descr)
                </p>

            </div>
            <br />
        }

    </div>

    <div class="col-md-3 side" style="float: right;   margin-top: -191px;margin-right: 123px;">
        <h4><a href="#">Like our Facebook Page<a></h4>
        <hr>

        <h4>Recent Posts</h4>
        <hr>
        <ul>
            @foreach (GsMentors.Models.Blog_Master i in recent)
            {
                <li><a href="/Blogs/index/@i.ID">@i.Title</a></li>
            }
        </ul>
        <h4>Archives</h4>
        <hr>
        <ul>
            <li><a href="#">August 2011</a></li>
            <li><a href="#">July 2011</a></li>
        </ul>
        <h4>E-mail Subscription</h4>
        <p>Enter your email address to subscribe to this blog and receive notifications of new posts by email.</p>
        <p>Join 1 other follower</p>
        <input type="text" class="form-control" placeholder="Enter Your email address">
        <br>
        <a href="#" class="btn btn-primary">Sign me up!</a>
        <h4>Categories</h4>
        <ul>
            @foreach (GsMentors.Models.Category_Master i in cat)
            {
                <li><a href="/Blogs/Category/@i.ID">@i.Name</a></li>
            }
        </ul>
    </div>


</div>


Controller:-


    public ActionResult Index()
        {
            var data = db.Blog_Master.ToList();


            ViewData["recent"] = (from s in db.Blog_Master orderby s.Date select s).Take(5);
            ViewData["cat"] = (from s in db.Category_Master orderby s.Name select s);
            return View(data);
        }
            


Model:-


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

namespace GsMentors.Models
{
    public class Query
    {

        [Required(ErrorMessage = "Please Enter Valid Username")]
        [Display(Name = "Name")]
        [MinLength(2)]
        public string Name { get; set; }
        [Required]
        [DataType(DataType.EmailAddress)]
        [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                           @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                           @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
                           ErrorMessage = "Email is not valid")]
        public string Email { get; set; }
        [Required]
        [DataType(DataType.PhoneNumber)]
        public int Mobile { get; set; }
        [Required]
       
        public int Website { get; set; }
        [Required]
        public string quary { get; set; }
    }
}

Thursday, 4 June 2015

Linq Query


The SELECT Operation
private void GetCourses()
{
      
//create DataContext object      OperationDataContext OdContext = new OperationDataContext();
      var courseTable = from course in OdContext.GetTable<COURSE>() select course;
      
//grdCourse is gridview id      grdCourse.DataSource = courseTable;
      grdCourse.DataBind();
}


The INSERT Operation
private void AddNewCourse()
{
      
//Data maping object to our database      OperationDataContext OdContext = new OperationDataContext();
      COURSE objCourse = new COURSE();
      objCourse.course_name = "B.Tech";
      objCourse.course_desc = "Bachelor Of Technology";
      objCourse.modified_date = DateTime.Now;
      
//Adds an entity in a pending insert state to this System.Data.Linq.Table<TEntity>and parameter is the entity which to be added      OdContext.COURSEs.InsertOnSubmit(objCourse);
      
// executes the appropriate commands to implement the changes to the database      OdContext.SubmitChanges();
}

The Update Operation
private void UpdateCourse()
{
      OperationDataContext OdContext = new OperationDataContext();
      
//Get Single course which need to update      COURSE objCourse = OdContext.COURSEs.Single(course => course.course_name == "B.Tech");
      
//Field which will be update      objCourse.course_desc = "Bachelor of Technology";
      
// executes the appropriate commands to implement the changes to the database      OdContext.SubmitChanges();
 }


The DELETE Operation
private void DeleteCourse()
{
      OperationDataContext OdContext = new OperationDataContext();
      
//Get Single course which need to Delete      COURSE objCourse = OdContext.COURSEs.Single(course => course.course_name == "B.Tech");
      
//Puts an entity from this table into a pending delete state and parameter is the entity which to be deleted.      OdContext.COURSEs.DeleteOnSubmit(objCourse);
      
// executes the appropriate commands to implement the changes to the database      OdContext.SubmitChanges();
}


Conculsion
To perform select, insert, update and delete operations we create a table and create a data context class; in other words a dbml file. In this file designer view we drag and drop the COURSE table from the Server Explorer. This data context class is an Object and table mapping and we perform the operation on the object and database updated according to the action using the submitChanges() method.