Saturday, 24 May 2014

Bind Asp.net ListBox using LINQ to SQL


In this article you will learn the basic operations like Save, Edit, Update and Delete operations in asp.net using LINQ to SQL. Newly inserting record will get displayed in ListBox control and clicking on any record from ListBox will fetch the corresponding details from the database and fills up the appropriate fields on the form, so that we can edit or delete that record as shown in demo above.


Implementation
 Let's create an asp.net application using LINQ to see it in action.
  • First of all create a SQL SERVER Database and name it "jaya_db" and also create a table "EMP_TABLE" using the script below:

CREATE TABLE [dbo].[EMP_TABLE]
(
 [EMP_ID] [int] IDENTITY(1,1) NOT NULL,
 [EMP_NAME] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
 [AGE] [int] NULL,
 [DEPT] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
 [SALARY] [bigint] NULL
)

  • Now open visual studio ->File menu -> New -> Website. New Web site dialog box will open as shown in image below-> Select Visual C# from the left pane under Installed Templates and also select ASP.NET Empty Web Site ->Select the location to save the application e.g. D:\jaya\LinqDemo  and click Ok button.
·         Now from the Website menu -> Add New Item ->Select LINQ to SQL Classes-> rename it from the default name DataClasses.dbml to emp.dbml  as shown in image below and click on Add button.








  •  This window is called ORM (Object-relational mapping).This window has two parts. On the Left portion of this window we drag the table from the server explorer and drop here and on Right portion we drag the Function, procedures etc from the server explorer and drop here.
  • Now connect your database with the visual studio .In Server explorer right click on the Data Connections and select Add connection as shown in image below
  • Now from Server explorer expand your connected database and select and drag and drop the EMP_TABLE to the left portion of the ORM window as shown in image below.

  • It will automatically create the connection string in the web.config file
<connectionStrings>
    <add name="emp_dbConnectionString" connectionString="Data Source=LocalServer;Initial Catalog=emp_db;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>


ASPX page:
<div >
<pre class="brush:xml">
<fieldset style="width: 400px">
<legend>Save,Edit,Update,Delete,Bind Asp.net Listview</legend>
<table style="background-color:AppWorkspace">
<tr>
<td colspan="2">
<asp:HiddenField ID="hdEmpId" runat="server" />
</td>
<td rowspan="6" valign="top">
<asp:ListBox ID="lstEmp" runat="server" AutoPostBack="True" Height="131px"
Width="134px"
Style="margin-left: 0px; margin-bottom: 0px;" OnSelectedIndexChanged="lstEmp_SelectedIndexChanged"></asp:ListBox>
</td>
</tr>
<tr>
<td width="90px">Emp Name</td>
<td>
<asp:TextBox ID="txtEmpName" runat="server" Width="181px"></asp:TextBox>
</td>
</tr>
<tr>
<td>Age</td>
<td>
<asp:TextBox ID="txtAge" runat="server" Width="181px"></asp:TextBox>
</td>
</tr>
<tr>
<td>Department</td>
<td>
<asp:TextBox ID="txtDept" runat="server" Width="181px"></asp:TextBox>
</td>
</tr>
<tr>
<td>Salary</td>
<td>
<asp:TextBox ID="txtSal" runat="server" Width="181px"></asp:TextBox>
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td align="center">
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
<asp:Button ID="btnUpdate" runat="server" Text="Update"
OnClick="btnUpdate_Click" />
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" />
<br />
<asp:Button ID="btnDisplay" runat="server" Text="Display"
OnClick="btnDisplay_Click" />

<asp:Button ID="btnCancel" runat="server" Text="Cancel"
OnClick="btnCancel_Click" />
</td>
</tr>
</table>
</fieldset>
</pre>
</div>

Example.aspx.cs

public partial class ListboxwithLinq : System.Web.UI.Page
{
empDataContext obj = new empDataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DisplayEmpRecords();
}
btnUpdate.Enabled = false;
btnDelete.Enabled = false;
btnDisplay.Enabled = false;

}

protected void btnSave_Click(object sender, EventArgs e)
{
EMP_TABLE db = new EMP_TABLE
{
EMP_NAME = txtEmpName.Text,
AGE = Convert.ToInt32(txtAge.Text),
DEPT = txtDept.Text,
SALARY = Convert.ToInt64(txtSal.Text)
};
obj.EMP_TABLEs.InsertOnSubmit(db);
obj.SubmitChanges();
DisplayEmpRecords();
ClearControls();

}

protected void btnUpdate_Click(object sender, EventArgs e)
{
EMP_TABLE db = obj.EMP_TABLEs.First(k => k.EMP_ID == Convert.ToInt32(hdEmpId.Value));
db.EMP_NAME = txtEmpName.Text;
db.AGE = Convert.ToInt32(txtAge.Text);
db.DEPT = txtDept.Text;
db.SALARY = Convert.ToInt64(txtSal.Text);
obj.SubmitChanges();
DisplayEmpRecords();
ClearControls();
btnSave.Enabled = true;

}

protected void btnDelete_Click(object sender, EventArgs e)
{
EMP_TABLE db = obj.EMP_TABLEs.First(k => k.EMP_ID == Convert.ToInt32(hdEmpId.Value));
obj.EMP_TABLEs.DeleteOnSubmit(db);
obj.SubmitChanges();
DisplayEmpRecords();
ClearControls();
btnSave.Enabled = true;

}

protected void btnDisplay_Click(object sender, EventArgs e)
{
DisplayEmpRecords();
btnDisplay.Enabled = true;

}
private void DisplayEmpRecords()
{
var q = from p in obj.EMP_TABLEs
select new { p1 = p.EMP_ID, p2 = p.EMP_NAME };
lstEmp.DataTextField = "p2";
lstEmp.DataValueField = "p1";
lstEmp.DataSource = q;
lstEmp.DataBind();
}
private void ClearControls()
{
txtEmpName.Text = string.Empty;
txtAge.Text = string.Empty;
txtDept.Text = string.Empty;
txtSal.Text = string.Empty;
hdEmpId.Value = string.Empty;
txtEmpName.Focus();
}
       
protected void btnCancel_Click(object sender, EventArgs e)
{
ClearControls();
lstEmp.Items.Clear();
btnDisplay.Enabled = true;
btnSave.Enabled = true;

}

protected void lstEmp_SelectedIndexChanged(object sender, EventArgs e)
{
var q = (from p in obj.EMP_TABLEs
where p.EMP_ID == Convert.ToInt32(lstEmp.SelectedValue)
select p).SingleOrDefault();

if (q != null)
{
hdEmpId.Value = q.EMP_ID.ToString();
txtEmpName.Text = q.EMP_NAME;
txtAge.Text = q.AGE.ToString();
txtDept.Text = q.DEPT;
txtSal.Text = q.SALARY.ToString();
btnUpdate.Enabled = true;
btnDelete.Enabled = true;
btnSave.Enabled = false;
}       
}
}
}



Monday, 28 April 2014

Hide the Content Type Column in SharePoint 2013

There are many good reasons to use Content Types… if you can get people to use them, and then leave them alone.   :-)

When creating a new list item based on a Content Type the user needs to select the Content Type from the New dropdown. Once selected, the Content Type should generally not be changed. Changing it is too easy as the user is offered the choice every time they edit the item.

Preventing this is pretty easy as all we need to do is hide the first row of the edit form's HTML table. The following JavaScript will do this for us and will work in both SharePoint 2007, SharePoint 2010 and SharePoint Online / Office 365:

<script>

var ttnTables = document.getElementsByTagName("TABLE")
for (var i=0;i<ttnTables.length;i++)
{
  if (ttnTables[i].className=="ms-formtable")
  {
    ttnTables[i].rows[0].style.display="none";
  }
}
</script>


Now the Content Type is hidden on the edit form.

But Site Owner Can Change it?
The only problem with this solution is that it also prevents the site owner from changing the Content Types. We need to only run the above code for non site owners. To do this we will use the SPSecurityTrimmedControl and set the PermissionString to a suitable value, such as ManageWeb.
<!-- default value -->
<script type="text/javascript">
  var canChangeContentType = false;
</script>

<Sharepoint:SPSecurityTrimmedControl runat="server" PermissionsString="ManageWeb">
  <!--text for users who have the ManageWeb permission -->
  <script type="text/javascript">
    canChangeContentType = true;
  </script>
</SharePoint:SPSecurityTrimmedControl>

<script type="text/javascript">
if (canChangeContentType == false)
{
  var ttnTables = document.getElementsByTagName("TABLE")
  for (var i=0;i<ttnTables.length;i++)
  {
    if (ttnTables[i].className=="ms-formtable")
    {
      ttnTables[i].rows[0].style.display="none";
    }
  }
}
</script>

There is Work around
A user with permissions to create private views can create a DataSheet view with the Content Type column displayed and then edit the Content Type.

Where to Add this Code
SharePoint 2013
1.             Open SharePoint Designer and open the site with the list that uses Content Types
2.             In the Folder List pane expand Lists and your list
3.             Double-click EditForm.aspx
4.             If the HTML is not displayed, click the Code button at the bottom of the page
5.             Search for "PlaceHolderMain"
6.             Select the entire line, right-click the line and select Find Matching Tag (this should find </asp:Content>)
7.             Add the JavaScript from above just before the </asp:Content> line
8.             Save and test (remember, as a Site Owner you will always be able to see the Content Type)
SharePoint 2010
1.             Open SharePoint Designer and open the site with the list that uses Content Types
2.             In the Navigation Pane click Lists and Libraries
3.             Click the name of the list that uses Content Types
4.             In the Forms area click EditForm.aspx
5.             If the window is split into Design and Code views, click the Split button at the bottom of the window
6.             Click in the area just below the existing web part
7.             You should see something similar to the following in the Code view:
8.             Paste the JavaScript from above between the DIV tags
9.             Save and test (remember, as a Site Owner you will always be able to see the Content Type)

Saturday, 12 April 2014

Install\Deploying .wsp file in SharePoint2013 Central administration.


   1)    Run the below command on SharePoint 2010 Management Shell.

   Add-SPSolution -LiteralPath "path to wsp file\EventReceiverProject.wsp"
   Example: Add-SPSolution -LiteralPath "C:\EventReceiverProject.wsp"

    2)      On the Central Administration Home page, click System Settings.

    3)      In the Farm Management section, click Manage farm solutions.

    4)      On the Solution Management page, click the solution that you want to deploy. 

    5)      On the Solution Properties page, click Deploy Solution

    6)      On the Deploy Solution page, in the Deploy When section, select one of the following:

           a)      Now

           b)      At a specified time. If you select this option, specify a time by using the date and time boxes we recommend that you select a time when the load on the destination servers is low.

    7)      In the Deploy To? Section, in the A specific web application list, click either All web applications or select a specific Web application.

    8)      Click OK.

    9)      Now open your site, go to site settings ->Site features

   10)      Activate the feature if it is not active.

Here’s a quick overview of what we’ve learned with a few more commands you’ll probably need along the way:
·         Add Solution
Add-SPSolution c:<path><solution filename>.wsp
·         Deploy/Install Solution
Install-SPSolution –Identity <solution file>.wsp –WebApplication http://<url> -GACDeployment
·         Update Solution
Update-SPSolution –Identity <solution file>.wsp –LiteralPath c:<path><solution file>.wsp –GACDeployment
·         Uninstall Solution
Uninstall-SPSolution –Identity <solution file>.wsp –WebApplication http://<url>
·         Remove Solution
Remove-SPSolution –Identity <solution file>.wsp


SharePoint tenant opt-out for modern lists is retiring in 2019

We're making some changes to how environments can opt out of modern lists in SharePoint. Starting April 1, 2019, we're going to be...