ĐÀO TẠO DOANH NGHIỆP : SỞ KHOA HỌC CÔNG NGHỆ TỈNH ĐỒNG NAI

ENTERPRISE TRAINING: DONG NAI DEPARTMENT OF SCIENCE AND TECHNOLOGY.

HÌNH ẢNH TẬP HUẤN LỚP SHAREPOINT WORKFLOW VÀ KIẾN TRÚC SHAREPOINT

PHOTOS OF SHAREPOINT WORKFLOW AND ARCHITECTURE CLASS.

HÌNH ẢNH TẬP HUẤN LỚP SHAREPOINT WORKFLOW VÀ KIẾN TRÚC SHAREPOINT

PHOTOS OF SHAREPOINT WORKFLOW AND ARCHITECTURE CLASS.

Friday, November 6, 2015

Sharepoint PowerShell List of all site collections in Web Application

$xl=New-Object -ComObject "Excel.Application"
$xl.Visible=$True
$xl.Workbooks.Add()
$ws=$xl.ActiveWorkbook.ActiveSheet
$cells=$ws.Cells
$i = 1
$sites = Get-SPSite -Limit All -WebApplication http://pc362/
foreach ($site in $sites)
{
 $cells.item($i,1)= invoke-command { $site.URL }
 $cells.item($i,2)= invoke-command { $site.Owner.UserLogin }
 $cells.item($i,3)= invoke-command { $site.SecondaryContact.UserLogin }
 $cells.item($i,4)= invoke-command { $site.WebApplication.DisplayName }
 $cells.item($i,5)= invoke-command { $site.Usage.Storage/1MB }
 $cells.item($i,6)= invoke-command { $site.ContentDatabase.Name }
 $cells.item($i,7)= invoke-command { $site.Quota.Storagemaximumlevel }
 $cells.item($i,8)= invoke-command { $site.RootWeb.SiteUsers.Count }
 $cells.item($i,9)= invoke-command { $site.Usage.Hits }
 $cells.item($i,10)= invoke-command { $site.Usage.Bandwidth }
 $i++
}

Or

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
#Configure the location for the output file
$Output="C:\Output.csv";
"Site URL"+","+"Owner Login"+","+"SecondaryContact Login"+","+"WebApplication DisplayName"+","+"Quota Limit (MB)"+","+"Total Storage Used (MB)"+","+"Site Quota Percentage Used"+","+"ContentDatabase"+","+"SiteUsers"+","+"UsageHits"+","+"UsageBandwidth" | Out-File -Encoding Default -FilePath $Output;
#Specify the root site collection within the Web app
$Siteurl="https://your web application";
$Rootweb=New-Object Microsoft.Sharepoint.Spsite($Siteurl);
$Webapp=$Rootweb.Webapplication;
#Loops through each site collection within the Web app, if the owner has an e-mail address this is written to the output file
Foreach ($Site in $Webapp.Sites)
{if ($Site.Quota.Storagemaximumlevel -gt 0) {[int]$MaxStorage=$Site.Quota.StorageMaximumLevel /1MB} else {$MaxStorage="0"};
if ($Site.Usage.Storage -gt 0) {[int]$StorageUsed=$Site.Usage.Storage /1MB};
if ($Storageused-gt 0 -and $Maxstorage-gt 0){[int]$SiteQuotaUsed=$Storageused/$Maxstorage* 100} else {$SiteQuotaUsed="0"};
$Web=$Site.Rootweb; $Site.Url + "," + $Site.Owner.UserLogin + "," + $Site.SecondaryContact.UserLogin + "," +$Site.WebApplication.DisplayName + "," +$MaxStorage+","+$StorageUsed + "," + $SiteQuotaUsed+ "," + $Site.ContentDatabase.Name+ "," + $Site.RootWeb.SiteUsers.Count+ "," + $Site.Usage.Hits+ "," + $Site.Usage.Bandwidth | Out-File -Encoding Default -Append -FilePath $Output;$Site.Dispose()};

Monday, November 2, 2015

Sharepoint designer workflow update current item from lookup list based on current lookup field

Sharepoint designer workflow update current item from lookup list based on current lookup field

1. Create new custom list "Provinces". Rename Title to ProvinceID. Create new field ProvinceName (single line of text)

2. Create new custom list Employees. Rename Title to FullName. Create new field ProvinceID lookup to list Province and return ProvinceID.  Create new field ProvinceName (single line of text)

3. Create new workflow (list workflow)

4. Insert action Update item and configure like image below. Then configure workflow setting is "start workflow automatically when an item is created" and start workflow automatically when an item is changed. Then publish workflow.

5. Create new item and leave ProvinceName

6. Workflow auto update ProvinceName.

Done.

Thursday, October 22, 2015

PowerShell copy list item to another list with same structure

Insert item from source list

$web = Get-SPWeb http://yourURL
$lista =$web.Lists["Source List Name"]
$listb =$web.Lists["Target List Name"]
$items = $lista.items
foreach ($item in $items) {
write-host -foregroundcolor yellow $item["Title"]
$newitem= $listb.items.Add()
$newitem["Title"] = $item["Title"]
$newitem["MultiLine"] = $item["MultiLine"]
$newitem["Number"] = $item["Number"]
$newitem["HyperLink"] = $item["HyperLink"]
$newitem["Choice"] = $item["Choice"]
$newitem["Created"] = $item["Created"]
$newitem["Author"] = $item["Author"]
$newitem["Modified"] = $item["Modified"]
$newitem["Editor"] = $item["Editor"]
$newitem.update()
start-sleep 1
}
$web.dispose
start-sleep 10

Powershell sharepoint get item by id

$web = Get-SPWeb http://yourURL
$lista =$web.Lists["Source List Name"]
$listb =$web.Lists["Target List Name"]
$items = $lista.GetItemById(523)
foreach ($item in $items) {
write-host -foregroundcolor yellow $item["ID"]
write-host -foregroundcolor yellow $item["Title"]
start-sleep 1
}
$web.dispose
start-sleep 10

Update Item by ID

$web = Get-SPWeb http://yourURL
$lista =$web.Lists["Source List Name"]
$listb =$web.Lists["Target List Name"]
$items = $lista.GetItemById(523)
foreach ($item in $items) {
write-host -foregroundcolor yellow $item["Title"]
$newitem= $listb.GetItemById(524)
$newitem["Title"] = $item["Title"]
$newitem["MultiLine"] = $item["MultiLine"]
$newitem["Number"] = $item["Number"]
$newitem["HyperLink"] = $item["HyperLink"]
$newitem["Choice"] = $item["Choice"]
$newitem["Created"] = $item["Created"]
$newitem["Author"] = $item["Author"]
$newitem["Modified"] = $item["Modified"]
$newitem["Editor"] = $item["Editor"]
$newitem.update()
start-sleep 1
}
$web.dispose
start-sleep 10

Thanks.

Thursday, October 1, 2015

Listing All SharePoint Server Features of Web Application dynamic by power shell

Listing All SharePoint Server Features of Web Application dynamic by power shell
1. Writing the function to export all features of web application with parameter
function Get-SPFeatureActivated
{
[CmdletBinding()]
param(
    [parameter(Mandatory=$true)][string]$Url,#Input your URL of web application
    [parameter(Mandatory=$true)][string]$Path,#Input your file name which you want to export like (c:\features.csv)
    [Parameter(position = 1, valueFromPipeline=$true)]#Default para
    [Microsoft.SharePoint.PowerShell.SPFeatureDefinitionPipeBind]   
    $Identity
)#end param
    Begin
    {       
        $results = @()
       
        $params = @{}
    }
    Process
    {
        if([string]::IsNullOrEmpty($Identity) -eq $false)
        {
            $params = @{Identity = $Identity
                        ErrorAction = "SilentlyContinue"
            }
        }   

        # Get web application URL
    $webApplication = Get-SPWebApplication -Identity $Url
        foreach($webApp in $webApplication)
        {
            $results += (Get-SPFeature -WebApplication $webApp -Limit All @params |
                             % {Add-Member -InputObject $_ -MemberType noteproperty -Name Url -Value $webApp.Url -PassThru} |
                             Select-Object -Property Scope, DisplayName, Id, Url)

            # check site collection features in current web app
            foreach($site in ($webApp.Sites))
            {
                $results += (Get-SPFeature -Site $site -Limit All @params |
                                 % {Add-Member -InputObject $_ -MemberType noteproperty -Name Url -Value $site.Url -PassThru} |
                                 Select-Object -Property Scope, DisplayName, Id, Url)
                                
                $site.Dispose()

                # check site features in current site collection
                foreach($web in ($site.AllWebs))
                {
                    $results += (Get-SPFeature -Web $web -Limit All @params |
                                     % {Add-Member -InputObject $_ -MemberType noteproperty -Name Url -Value $web.Url -PassThru} |
                                     Select-Object -Property Scope, DisplayName, Id, Url)

                    $web.Dispose()
                }
            }
        }
    }
    End
    {
        $results > $Path
    }
}

2. Call function then input the value via parameter in above function

3. The result is all features is exported to csv file 
 Thanks.

Thursday, September 24, 2015

export and import lists and libraries full version and permission

How to export and import lists and libraries full version and permission
Exporting

# specify the site URL to export

$web = Get-SPWeb "microsofttechnology.net/sites/sharepoint"

# specify output folder to store exported lists

$path = "D:\SharepointLists"

foreach($list in $web.lists)

{

"Exporting " + $list.RootFolder.URL

export-spweb $web.URL -ItemUrl $list.RootFolder.URL -IncludeUserSecurity -IncludeVersions All -path ($path + $list + ".cmp")

}

Importing

# specify target SharePoint site to import into

$site = "microsofttechnology.net/sites/sharepoint1"

# specify folder containing exported lists

$folder = "D:\SharepointLists"

$Files = Get-ChildItem $folder

foreach ($file in $files)
{

$name = $file.Name

"Importing: " + "$folder$name"

import-spweb $site -path ("$folder$name") -includeusersecurity –UpdateVersions Overwrite
}

Wednesday, September 2, 2015

Error SharePoint Designer does not support editing non-SharePoint sites


Error SharePoint Designer does not support editing non-SharePoint sites



Close SharePoint Designer and Reopen it. The issue will be solved.
Done!!!

Monday, August 24, 2015

What is a SharePoint Administrator?

The role of the SharePoint Administrator is often a topic that comes up when beginning to plan out a SharePoint implementation, as it should. The various roles and responsibilities should be clearly defined upfront, but I often receive the initial feedback from customers that we should be able to just tell them what those responsibilities are. The problem with that philosophy is that the organization, management, goals, and skill sets of every organization are not the same.
The role of a SharePoint Administrator will vary depending upon your organization. If you are looking for the SharePoint Administrator to be the "lone wolf" that can support everything you need to get started and that same person will be solely responsible for keeping the environment running, the list of roles and responsibilities will be different than that of a team approach. Differences will certainly occur based upon such things as your need to support environments around the clock or the view of how highly sensitive your data is or if you have a highly-audited environment. Some administrators will be license police, procurement clerks, infrastructure management, farm administration, back up, recovery support, and help desk. Some organizations have people and roles (part-time to full-time) that have specializations in each of these areas.
Because of the wide variety of organizations, a discussion of decent length should be undertaken to understand the responsibilities that you consider part of the role. Once you understand what those responsibilities entail, you can determine if this is just a part-time job duty or a full-time job in and of itself.
In a nutshell, the SharePoint Administrator should be responsible for the following (though not a standard):
  • Managing and checking the overall server health and functionality
  • Monitoring SharePoint disk space usage through the built-in SharePoint reports for each site collection
  • Managing SharePoint permissions
  • Analyzing and reporting upon SharePoint usage and activity
  • Moving/copying sites
  • Supporting network load balancing needs and ensuring its correct operation (NLB)
  • Regular review of the events and messages reported in Event Viewer and Performance Monitor
  • Regular review, clean-up, management and configuration of SharePoint accounts and sites. This portion of the role will work closely with an Active Directory administrator if they are separated.
  • Regularly analyzing SharePoint content and storage
  • Monitoring SharePoint trends (e.g. site usage and growth, disk space usage and growth)
  • Setting up alerts and enforcing policies
  • Regularly auditing your SharePoint environment
  • Identifying and reporting governance violations
  • Checking for operating system, SQL Server and SharePoint patches and cumulative updates.
In many ways, the SharePoint Administrator has become a jack-of-all-trades. They are managing services and scheduled jobs within the SharePoint environment, they are creating new sites and lists, installing new web parts, doing backups, managing the Shared Services, educating users on how to use features like InfoPath, managing governance policies and permissions. The SharePoint Administrator effectively becomes:
  • Infrastructure engineer
  • Database administrator
  • Security administrator
  • End users licensing expert (Windows, Office, SQL Server, SharePoint, etc.)
  • Backup and recovery coordinator
  • Internal guru of all SharePoint capabilities
  • SharePoint interactive environment expert
  • Internal help desk
  • Graphic designer
  • SharePoint developer
Many of the specific duties must also consider the limitations that Microsoft imposes and should be followed to ensure that long-term support is still available from Microsoft. For example, the extent of database tuning that you are allowed to do without losing support would be in the allocation of databases to drives. If you change any of the database settings (indexes, stored procedures, etc.) then you will fall out of support. Similar considerations must also be made when looking at the database as a source of information for a data warehouse. If you write any access mechanism that accesses the database to pull data out the database, you are no longer under support. In general, a SharePoint Administrator is responsible for the general health and well-being of the entire SharePoint environment.
From a knowledge perspective, the Administrator must have an above-basic level of understanding of:
  • Windows operating system and hardware – Basic administration of a server including service packs and hot fixes.
  • General knowledge of networking – IP, DNS, Load Balancing as well as the concepts of Availability, Scalability, and Maintainability. This person should also understand firewalls, encryption and security zones.
  • Internet Information Server (IIS) and the basic operation of websites, Application Pools, IIS Administration, the IIS Metabase, Ports, SSL Certifications (security certificates and wildcard certificates)
  • Microsoft SQL Server - Basic operation, tuning, transaction log selection, backup and recovery, and maintenance planning. Since SharePoint is completely supported by a Microsoft SQL Server database, the SharePoint Administrator is expected to be knowledgeable at the database level.
  • SharePoint working knowledge of Central Administration, STSADM, and more so now, the PowerShell administration modules. SharePoint Event Log troubleshooting, search administration and troubleshooting, concepts of a farm and the planning and implementation of Service Packs and Cumulative Updates.
  • Debugging skills and techniques for each of these areas identified above – troubleshooting issues can occur within or across one-to-many of these areas.
In other words, a good SharePoint Administrator is a self-contained IT Department. Imagine the job!
Now that I've pleaded the case that the SharePoint Administrator must be a key and important player within your IT department, let me layout some regular or recurring duties that this person would, or should perform. This may help you in planning how much time this person would spend performing these tasks.
One-time / First-time Farm Activities
1. Determine general patch approach for applying patches 
2. Windows O/S (Windows Update)
3. SQL Server (Service Packs
4. Document the overall system architecture
5. Document the disaster recovery plan for data center, server, or document recovery
6. Determine search architecture (What is indexed?, how often?, etc.)
7. Determine design continuity (What templates are used for each area)
8. Determine best practices for creation of Sites, Site Collections, and content databases
9. Determine strategy for business intelligence in SharePoint (upon dashboards, where is 
the data stored?, how is it presented?, etc.)
10. Create SharePoint Service Level Agreement
11. Create best practices document for taxonomies
12. Create best practices document on security configuration
13. Create SharePoint roles document
14. Determine who can access the site (internal only? customers?)
15. Determine how partners and users will navigate the sit
16. Determine the process to request a site
17. Determine the process to request access to sites
18. Create best practices document to explain how and when to publish a document to a 
global audience (should they be PDFs?)
19. Create feedback and/or suggestion mechanism for site enhancements
20. Determine naming conventions
21. Develop process for FAQ (users and help desk)
22. Develop training process
Daily Activities
1. Review Windows Event Logs for high-priority issues 
2. Review the SharePoint Logs for high-priority issues
Weekly Activities
1. Review Search Usage reports 
2. Attempt searches upon typical end-user searches – verify they work properly 
3. Verify Alerts are functioning properly 
4. Enhance search through audit of Search patterns (implementation of noise words, best bets, 
keywords, thesaurus entry, etc.)
5. Review and maintain current BI cubes and web parts (if applicable) 
6. Audit server utilization (disk IO, disk space, CPU, etc.) and update baseline 
7. Review past week questions and issues and update FAQ 
8. Ensure off-site backup procedure working properly
Monthly Activities
1. Review overall server architecture based on current use 
2. Audit individual server design (each server) 
3. Review released patch list for Windows Operating System, SQL Server and SharePoint 
4. Apply patches per the pre-defined patch approach
5. Review patches or maintenance to third party controls (web parts, iFilters, etc.)
4. Review overall server architecture diagrams and documentation for updates and revisions 
5. Review search architecture for new areas to index, crawl or exclude 
6. Report on SharePoint uptime and SLA compliance 
7. Review security hierarchy 
8. Review new functions or sites deployed. Determine if training needs to be updated
9. Verify backups are valid and contain data
Quarterly Activities
1. Review company disaster recovery plan
Annual Activities
1. Exercise a company disaster recovery plan
There are books on the market and plenty of opinions (like mine) on the web. Read a few and get the correct description of the SharePoint Administrator that best fits your organization. As I was reading a few of these, I found this link useful in helping to break out specific duties and responsibilities for the various SharePoint roles.
- See more at: http://www.skylinetechnologies.com/Insights/Skyline-Blog/February-2012/What-is-a-SharePoint-Administrator#sthash.2DNaMGv4.dpuf

Link to reference: http://www.skylinetechnologies.com/Insights/Skyline-Blog/February-2012/What-is-a-SharePoint-Administrator

Thursday, August 20, 2015

Bulk Insert/Update/Delete Items from SharePoint List/Library

Bulk Insert/Update/Delete Items from SharePoint List/Library 
 We have the sharepoint list like as below

Create console project to run the code
 
 Code here
 Before run => remember change Target framework to 3.5 (i using visual 2010 and sharepoint 2010)
 Run application
 The result here but have problem with "Throttling" the next topic i will guide to you how to disable it in special list
Done !!!

How to update only one field using Entity Framework


 How to update only one field using Entity Framework
 
var tableEmployee = new T_Employees() { EmployeeID = item.EmployeeID , IsDisplayRequired = item.IsDisRequired };
                using (var db = new DBEntitiesContext())
                {
                    db.Configuration.ValidateOnSaveEnabled = false;
                    db.T_Employees.Attach(tableEmployee);
                    db.Entry(tableEmployee).Property(x => x.IsDisplayRequired).IsModified = true;
                    db.SaveChanges();
                    db.Configuration.ValidateOnSaveEnabled = true;
                }

MVC 5 Insert Update Delete CRUD Functionality using EF

MVC 5 Insert Update Delete CRUD Functionality using EF

Download project at here: http://www.mediafire.com/download/2s4mwu2vcunlx9d/MVC5.7z
1. Continue with previous article at link: http://www.microsofttechnology.net/2015/08/insert-update-and-delete-data-in-mvc5.html. 
Create new class in Models folder call is EmployeesModel at image below

2. Writing code like below

3. Create new controller (Empty)

4. Name is EmployeesController

5. The result as below

6. Create View (empty model)

7. Writing code to inherit from model (EmployeesModel)

8. Insert more code as below using WebGrid

9. Writing new code to display all of employees from database using entity framework

10. Run index view and see the result here

11. Continue create View Create

12. Insert  code "@model MVC5.Models.EmployeesModel" in top as below

13. Insert code like this to insert. we use control is TextBoxFor

14. Go to EmployeesController insert this code to insert data

15. Run view Create and input data then click Save button

16. Continue create View Edit

17. Insert  code "@model MVC5.Models.EmployeesModel" in top as below

18. Insert code like this to insert. we use control is TextBoxFor.
      Note: Hidden field with ID is Id use to pass to controller and get ID for update

19. Go to EmployeesController insert this code to update data.
      Note: you will get error when display form edit because you get the query string with name is employeeID from view Index can not find, so you back to view Index at step 8 and change it to
grid.Column("", null, format: @<text>@{<a href="/Employees/Edit/?employeeID=@item.Id">Edit</a>}</text>),

similar to delete
grid.Column("", null, format: @<text>@{<a href="/Employees/Delete/?employeeID=@item.Id">Delete</a>}</text>)


20. Run Index View then click edit link

21.Updating some value then click update button

22. Continue create View Create

23. Insert  code "@model MVC5.Models.EmployeesModel" in top as below

24. Insert code like this to insert. we use control is TextBoxFor
      Note: Hidden field with ID is EmployeeIdToDelete use to pass to controller and get ID for delete

25.Go to EmployeesController insert this code to insert data


26. Run Index View then click delete link
It will be deleted

Done!!!All Code:
EmployeesModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVC5.Models
{
    public class EmployeesModel
    {
        public List<EmployeesList> EmployeeListCollection { get; set; }
        public EmployeesList EmployeeListDetail { get; set; }
    }
    public class EmployeesList
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string City { get; set; }
        public string EmailID { get; set; }
    }
}
Index.cshtml
 @model MVC5.Models.EmployeesModel
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<style>
    table, td, th {
        border: 1px solid green;
        border-collapse: collapse;
        width: 50%;
    }

    th {
        border: 1px solid black;
        background-color: green;
        color: white;
    }
</style>
@using (@Html.BeginForm("Index", "Employees"))
{
    var grid = new WebGrid(Model.EmployeeListCollection);

    <div>
        @grid.GetHtml(columns:
            grid.Columns
            (
                 grid.Column("FirstName", "FirstName"),
                 grid.Column("LastName", "LastName"),
                 grid.Column("City", "City"),
                 grid.Column("EmailID", "EmailID"),
                 grid.Column("", null, format: @<text>@{<a href="/Employees/Edit/?employeeID=@item.Id">Edit</a>}</text>),
                 grid.Column("", null, format: @<text>@{<a href="/Employees/Delete/?employeeID=@item.Id">Delete</a>}</text>)
                 ), mode: WebGridPagerModes.Numeric)
    </div>
    <div>
        <a href="/Employees/Create/">Add New Record</a>
    </div>
}

Create.cshtml
 @model MVC5.Models.EmployeesModel
@{
    ViewBag.Title = "Create";
}
<style>
    .container {
        width: 100%;
        text-align: center;
    }

    .left {
        float: left;
        width: 150px;
    }
</style>

@using (Html.BeginForm("Create", "Employees", FormMethod.Post))
{
    <div>
        <table width="20%" cellpadding="5" cellspacing="5" border="1" style="border: 1 solid black;
            border-collapse: collapse; margin-top:20px;">
            <tr>
                <td align="right">
                    FirstName:
                </td>
                <td align="left">
                    @Html.TextBoxFor(m => m.EmployeeListDetail.FirstName)
            </td>
        </tr>
        <tr>
            <td align="right">
                LastName:
            </td>
            <td align="left">
                @Html.TextBoxFor(m => m.EmployeeListDetail.LastName)
        </td>
    </tr>
    <tr>
        <td align="right">
            City:
        </td>
        <td align="left">
            @Html.TextBoxFor(m => m.EmployeeListDetail.City)
    </td>
</tr>
<tr>
    <td align="right">
        EmailID:
    </td>
    <td align="left">
        @Html.TextBoxFor(m => m.EmployeeListDetail.EmailID)
</td>
</tr>
<tr>
    <td colspan="2" align="center">
        <input type="submit" value="Save" />&nbsp;&nbsp;
        <a href="/Home/index/">Back</a>

        <div style="color: Red">@ViewBag.Message</div>
    </td>
</tr>
</table>
</div>
}

Edit.cshtml
 @model MVC5.Models.EmployeesModel
@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm("Edit", "Employees", FormMethod.Post))
{
    <div>
        <table width="20%" cellpadding="5" cellspacing="5" border="1" style="border: 1 solid black; border-collapse: collapse; margin-top: 20px;">
            <tr>
                <td align="right">
                    FirstName:
                </td>
                <td align="left">
                    @Html.TextBoxFor(m => m.EmployeeListDetail.FirstName)
                @Html.Hidden("Id", Model.EmployeeListDetail.ID)
            </td>
        </tr>
        <tr>
            <td align="right">
                LastName:
            </td>
            <td align="left">
                @Html.TextBoxFor(m => m.EmployeeListDetail.LastName)
        </td>
    </tr>
    <tr>
        <td align="right">
            City:
        </td>
        <td align="left">
            @Html.TextBoxFor(m => m.EmployeeListDetail.City)
    </td>
</tr>
<tr>
    <td align="right">
        EmailID:
    </td>
    <td align="left">
        @Html.TextBoxFor(m => m.EmployeeListDetail.EmailID)
</td>
</tr>
<tr>
    <td colspan="2" align="center">
        <input type="submit" value="Update" />
        <div style="color: Red">@ViewBag.Message</div>
    </td>
</tr>
</table>
</div>
}
Delete.cshtml
@model MVC5.Models.EmployeesModel
@{
    ViewBag.Title = "Delete";
}

<h2>Delete</h2>

@using (Html.BeginForm("Delete", "Employees", FormMethod.Post))
{
    <div>
        <table width="20%" cellpadding="5" cellspacing="5" border="1" style="border: 1 solid black;
          border-collapse: collapse;; margin-top: 20px;">
            <tr>
                <td align="right">
                    FirstName:
                </td>
                <td align="left">
                    @Html.DisplayFor(m => m.EmployeeListDetail.FirstName)
                @Html.Hidden("EmployeeIdToDelete", Model.EmployeeListDetail.ID)
            </td>
        </tr>
        <tr>
            <td align="right">
                LastName:
            </td>
            <td align="left">
                @Html.DisplayFor(m => m.EmployeeListDetail.LastName)
        </td>
    </tr>
    <tr>
        <td align="right">
            City:
        </td>
        <td align="left">
            @Html.DisplayFor(m => m.EmployeeListDetail.City)
    </td>
</tr>
<tr>
    <td align="right">
        EmailID:
    </td>
    <td align="left">
        @Html.DisplayFor(m => m.EmployeeListDetail.EmailID)
</td>
</tr>
<tr>
    <td colspan="2" align="center">
        <input type="submit" value="Delete" />
        <div style="color: Red">@ViewBag.Message</div>
    </td>
</tr>
</table>
</div>
}
EmployeesController.cs
using MVC5.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVC5.Controllers
{
    public class EmployeesController : Controller
    {
        //
        // GET: /Employees/
        /// For getting detail list of student
        ///
        public ActionResult Index()
        {
            EmployeesModel employeesModel = new EmployeesModel();
            employeesModel.EmployeeListCollection = new List<EmployeesList>();
            employeesModel.EmployeeListCollection = GetEmployeesList();
            return View(employeesModel);
        }
        ///


        /// Get student record
        ///
        public List<EmployeesList> GetEmployeesList()
        {
            List<EmployeesList> objEmployee = new List<EmployeesList>();
            /*Create instance of entity model*/
            DEMODBEntities demoDBEntities = new DEMODBEntities();
            /*Getting data from database for user validation*/
            var _objuserdetail = (from data in demoDBEntities.Samples
                                  select data);
            foreach (var item in _objuserdetail)
            {
                objEmployee.Add(new EmployeesList { ID = item.ID, FirstName = item.FirstName,
                    LastName = item.LastName, City = item.City, EmailID = item.EmailID });
            }
            return objEmployee;
        }
        public ActionResult Create()
        {
            EmployeesModel employeesModel = new EmployeesModel();
            return View(employeesModel);
        }
        [HttpPost]
        public ActionResult Create(EmployeesModel employeesModel)
        {
            try
            {
                /*HERE WILL BE YOUR CODE TO SAVE THE FILE DETAIL IN DATA BASE*/
                Sample employeeSample = new Sample();
                employeeSample.ID = 1;
                employeeSample.FirstName = employeesModel.EmployeeListDetail.FirstName;
                employeeSample.LastName = employeesModel.EmployeeListDetail.LastName;
                employeeSample.City = employeesModel.EmployeeListDetail.City;
                employeeSample.EmailID = employeesModel.EmployeeListDetail.EmailID;

                DEMODBEntities demoDBEntities = new DEMODBEntities();

                demoDBEntities.Samples.Add(employeeSample);
                demoDBEntities.SaveChanges();
                ViewBag.Message = "Data saved successfully.";
            }
            catch
            {
                ViewBag.Message = "Error while saving data.";
            }
            return View(employeesModel);
        }

        /// This method display record for edit
        ///
        public ActionResult Edit()
        {
            int employeeID =Convert.ToInt32(Request.QueryString["employeeID"]);
            DEMODBEntities objentity = new DEMODBEntities();
            Sample objEmployeedetail = new Sample();
            objEmployeedetail = (from data in objentity.Samples
                                where data.ID == employeeID
                                select data).FirstOrDefault();
            EmployeesList _objEmployeelist = new EmployeesList();
            _objEmployeelist.ID = employeeID;
            _objEmployeelist.FirstName = objEmployeedetail.FirstName;
            _objEmployeelist.LastName = objEmployeedetail.LastName;
            _objEmployeelist.City = objEmployeedetail.City;
            _objEmployeelist.EmailID = objEmployeedetail.EmailID;
            EmployeesModel objEmployeeListModel = new EmployeesModel();
            objEmployeeListModel.EmployeeListDetail = _objEmployeelist;
            return View(objEmployeeListModel);
        }
        ///


        /// This method edit function
        ///
        [HttpPost]
        public ActionResult Edit(EmployeesModel employeesModel, int Id = 0)
        {
            DEMODBEntities objentity = new DEMODBEntities();
            Sample objdstudent = objentity.Samples.First(m => m.ID == Id);
            objdstudent.FirstName = employeesModel.EmployeeListDetail.FirstName;
            objdstudent.LastName = employeesModel.EmployeeListDetail.LastName;
            objdstudent.City = employeesModel.EmployeeListDetail.City;
            objdstudent.EmailID = employeesModel.EmployeeListDetail.EmailID;
            /*Save data to database*/
            objentity.SaveChanges();
            ViewBag.Message = "Data updated successfully.";
            return View(employeesModel);
        }

        public ActionResult Delete()
        {
            int employeeID = Convert.ToInt32(Request.QueryString["employeeID"]);
            DEMODBEntities objentity = new DEMODBEntities();
            Sample objEmployeedetail = new Sample();
            objEmployeedetail = (from data in objentity.Samples
                                 where data.ID == employeeID
                                 select data).FirstOrDefault();
            EmployeesList _objEmployeelist = new EmployeesList();
            _objEmployeelist.ID = employeeID;
            _objEmployeelist.FirstName = objEmployeedetail.FirstName;
            _objEmployeelist.LastName = objEmployeedetail.LastName;
            _objEmployeelist.City = objEmployeedetail.City;
            _objEmployeelist.EmailID = objEmployeedetail.EmailID;
            EmployeesModel objEmployeeListModel = new EmployeesModel();
            objEmployeeListModel.EmployeeListDetail = _objEmployeelist;
            return View(objEmployeeListModel);
        }
        ///

        /// This method delete function
        ///
        [HttpPost]
        public ActionResult Delete(int EmployeeIdToDelete = 0)
        {
            DEMODBEntities objentity = new DEMODBEntities();
            Sample objEmployeeDetail = new Sample();
            objEmployeeDetail.ID = EmployeeIdToDelete;
            objentity.Samples.Attach(objEmployeeDetail);
            objentity.Samples.Remove(objEmployeeDetail);
            /*Save data to database*/
            objentity.SaveChanges();
            return RedirectToAction("/Index/");
        }      
    }
}


Tuesday, August 18, 2015

Insert, Update and Delete Data in MVC5 Using Entity Framework

Insert, Update and Delete Data in MVC5 Using Entity Framework


Create new database and table like below


Continue with article: http://www.microsofttechnology.net/2015/08/how-to-create-mvc-5.html, open that project - right click to models folder >> Add new item >> from left panel choose Data >> Ado.NET Entity Data Model


Click new connection ... button >> choose data source is Microsoft SQL Server >> Continue


Server name: input . or (local) >> select existing database


Choose Entity Framework 5.0 >> Next


Choose your table


After create Model then create Controller >> Right click to controller folder >> Add >> Controller >> choose MVC 5 ... like image below


Choose model class and Data context. 


Here is default view


Try to run project F5, here is list of item


Here is Create View


Here is Edit view


Here is detail view


Done.
This is way we implement action base on default. we can implement it by custom. i will create it at the next time.