Wednesday, June 17, 2015

Modify LabelFor to display an * for required fields

We are going to create a html helper method in MVC to automatically show an * for required fields.


Create a class let say ReqLabel

using System;
using System.Linq;
using System.Web.Mvc;
using System.Linq.Expressions;
using System.ComponentModel;

namespace YourNameSpace.Models
{
public static class ReqLabel
{
    public static MvcHtmlString ReqLabelFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
    {
        var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);

        string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
        string labelText = metaData.DisplayName ?? metaData.PropertyName ?? htmlFieldName.Split('.').Last();

        if (metaData.IsRequired)
            labelText += "*";

        if (String.IsNullOrEmpty(labelText))
            return MvcHtmlString.Empty;

        var label = new TagBuilder("label");
        label.Attributes.Add("for", helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));

        foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(htmlAttributes))
        {
            label.MergeAttribute(prop.Name.Replace('_', '-'), prop.GetValue(htmlAttributes).ToString(), true);
        }

        label.InnerHtml = labelText;
        return MvcHtmlString.Create(label.ToString());
    }

}
}

don't forget at add name of your name space to your class


Now you can use this new helper method inside your views as follows

include the namespace in your view

@using YourNameSpace.Models



and use ReqLabelFor instead of LabelFor

@Html.ReqLabelFor(model => model.Category, new { @class = "control-label col-md-3" })




Friday, March 27, 2015

Table Variable vs Temp Table, which one to prefer and when

Yesterday I came accross a situation where one of the stored procedure written by my collegue started misbehaving all of a sudden, It was becomming non responsive to a point where we were inserting a record into a table variable from a CTE query.

On further analysis I found that everything was okay with the query untill the point it tries to insert records into the table variable. I replaced that table variable with a temp table and everything went smoothly. That's when I thought to make a writeup on this topic for which one to use, and when, cause both are have some pross and cons.


  • For larger datasets use temp table. If your number of records are going to be greater than 100 use temp table, micrsoft recommends
  • Indexes cannot be created explicitly on table variables and no statistics are kept on table variable, so use temp tables if want to improve performance by indexes and supported statistics
  • Since table variables are still a varibales they do not participate in transactions, you can use them at a place where you want to log progress of large SQL batch
  • Queries that modify table variables do not generate parallel query execution plans. Performance can be affected when very large table variables, or table variables in complex queries, are modified. In these situations, consider using temporary tables instead
  • On the other hand when using fewer number of records use table variable instead cause it create less overhead on the database, and may need less or no in case they are stored in memory, because of being smaller in size. 
  • If you are frequently adding and deleting records from it then use temporay tables cause they support truncate command which has better performance than delete
  • If the source for the data inserted to the table is from a potentially expensive SELECT statement then consider that using a table variable will block the possibility of this using a parallel plan.
  • When using a #temp table within a user transaction, locks are held longer than for table variables and also it can prevent truncation of the tempdb transaction log until the user transaction ends. So this might favour the use of table variables
  • A table varibale cannot be altered after creation, however you you can alter the structure of a temp table by using an alter table command    

Tuesday, March 24, 2015

What data type we should preferably use for storing flag values in sql server

This question came to my mind some time back, when I was working on a project with a database having billions of records, spanned accross 20 financial years. I saw that for most of the flag fields Int data type was used. I was curious to know that if size of field impacts the performace of database opeartions. I posted a question for the same on stackoverflow and finally I found the solution by the help of a link provided by a stack overflow member.

What I found as answer is that we should consider using smallest data type sufficient enough to store flag values required. This is with respect to the performance of database as storage size is not a big concern these days.

Have a look on this link for more insights.

Rows and index entries are stored in 8k pages. So a million rows at 3 bytes per row isn't 3 MB on disk: it affects the number of rows per page ("page density").


The same applies to nvarchar to varchar, smalldatetime to datetime, int to tinyint etc

This article describes how the dataype and rowsize matters for DML operations in a database.


Wednesday, March 4, 2015

WCF Training

A Good article published by Microsoft.







Problem of SQL Server Ignoring seconds and milisecons at the time of implicit conversion

Hi Guys,

SQL server has the feature of implicit conversion of data types at the time of inserting records into a table.

I want to take your attention here on a specific issue related to varchar to datetime data type conversion.
When we insert data into a DATETIME or SMALLDATETIME column, SQL Server automatically attempts to convert the data if it is of a different type. 

For example, if you insert a varchar value into a DATETIME column, SQL Server will convert the data – if the value is in an  acceptable format.
Sometimes you will notice that this implicit conversion has ignored the values of seconds and milisecons, and inserted zero instead.To cope up with this situation you need to explicitly convert the field value using Convert or Cast function.

Friday, November 16, 2012

How to permanently delete a file from Team Foundation server

tf destroy $/proj/proj/proj/projEntities.Designer.cs /login:admin,abc@123 /collection:http://server:8080/tfs/proj

Friday, February 3, 2012

Deploying a .Net crystal report website on a shared server

Hi Guys,

Deploying a crystal report website on a shared server has really been a very difficult task. I have been using rdlc reports upto now for my web applications, but due to the limitations they have I had to use crystal report to one of my web applications, that's when I had to learn this thing, and also realised that many of the guys are struggling with this issue and some of them are not able to sort this thing out for months/years. Though there so many deployment issues which is not possible for me to list out, but here I am writting steps to deploy a crystal report site, which you can use as a primary guideline for deploying a crystal report website.

1. Put the following DLLs to your BIN directory at your shared server.

CrystalDecisions.CrystalReports.Engine
CrystalDecisions.Shared
CrystalDecisions.ReportSource

2. Install the appropriate crystal report redistributable(the redistributable applicable for the version you are using) at server.

3. Give the IIS user account and asp.net worker process account full control for the reports folder.

4. Make sure to give 'everyone' full control to the temp directory of windows.

5. for more information and support log on to http://forums.sdn.sap.com/index.jspa.

wish you all the best for your deployment.

Monday, January 30, 2012

tsql function to convert a column value to csv

Option 1:

alter function udf_get_csv_faults (@unit varchar(4),@jobno int)
returns varchar(500)
as
begin
declare @csv varchar(2048)
SELECT @csv= SUBSTRING(
(SELECT ',' + s.detail
FROM vw_job_sheet_fault s
where s.js_unitcode=@unit and s.js_jobno=@jobno
FOR XML PATH('')),2,500)
return @csv
end
GO


Option 2:

create FUNCTION udf_get_csv(@unit varchar(4),@jobno int)
RETURNS varchar(500)
AS
BEGIN
declare @csv varchar(500)
Select @csv = null
SELECT @csv = Coalesce(@csv + ', ', '') +
s.detail
FROM vw_job_sheet_fault s
where s.js_unitcode=@unit and s.js_jobno=@jobno
RETURN @csv

END

Friday, January 20, 2012

code for crystal report

Visual Studio 2005 and Crystal Report XI.

1. Create a Crystal Report as usual in Visual studio 2005 .net
using ODBC connection. In this example "CrystalReport.rpt"

2. Create a aspx web form to display the report. This form will
be a place holder for crystal report.

3. In design mode, drag and drop Crystal Report viewer control and
don't configure anything.

4. Open code behind .aspx.vb

'Declare public variable

Private myReportDocument As ReportDocument

'Note: This is Page Init event not Page Load event

Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
Dim myConnectionInfo As ConnectionInfo = New ConnectionInfo()

' Note: This is your local ODBC Name NOT SQL SERVER NAME

myConnectionInfo.ServerName = "PUBSODBCNAME"

' If your ODBC connection defaulted to your application database,
' you can remove the following line.

myConnectionInfo.DatabaseName = "Pubs"
myConnectionInfo.UserID = "userid"
myConnectionInfo.Password = "password"

myReportDocument = New ReportDocument()
'If your crystal report is in some other folder, give proper path
' In this example, .rpt file in the same folder as .aspx file
Dim reportPath As String = Server.MapPath("CrystalReport.rpt")
myReportDocument.Load(reportPath)
SetDBLogonForReport(myConnectionInfo, myReportDocument)
CrystalReportViewer1.ReportSource = myReportDocument
' You can customize the Crystal Reports toolbar.
' like the following. I have disabled the business object logo
' in the tool bar.

CrystalReportViewer1.HasCrystalLogo = False

End Sub

'This Sub is necessary for Crystal report database connection

Private Sub SetDBLogonForReport(ByVal myConnectionInfo As ConnectionInfo, ByVal myReportDocument As ReportDocument)
Dim myTables As Tables = myReportDocument.Database.Tables
For Each myTable As CrystalDecisions.CrystalReports.Engine.Table In myTables
Dim myTableLogonInfo As TableLogOnInfo = myTable.LogOnInfo
myTableLogonInfo.ConnectionInfo = myConnectionInfo
myTable.ApplyLogOnInfo(myTableLogonInfo)
Next
5. Now run the .aspx page. You will see the report or the crystal report parameter
form. It will not ask you DB login information.

6. dont forget to Imports dll

Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports CrystalDecisions.ReportSource

Friday, October 7, 2011

Using Stored Procedures in the Entity Framework with Scalar Return Values

This Link explains well on how to deal with stored procs returning scalar values using EF. Further it also explains how to handle if the proc returns null. If you have any doubt or need more examples, you can discuss with me here.

Friday, September 16, 2011

upload a file in asp.net MVC along with other components in your view

Hi,

I am here going to describe how to upload a file in asp.net MVC along with other components in your view. The view is a content page.

let us take an example of an item object I will write here some portions of viewmodel, view page and controller function.

ViewModel:


[Required(ErrorMessage = "Item Code Required")]
[StringLength(50, ErrorMessage = "Must be less than 51 characters")]
public string i_code
{
get;
set;
}

[Required(ErrorMessage = "Item Name Required")]
[StringLength(50, ErrorMessage = "Must be less than 51 characters")]
public string i_name
{
get;
set;
}

public HttpPostedFileBase Image
{
get;
set;
}





View:

'

<% using (Html.BeginForm("Create","items",FormMethod.Post, new {enctype = "multipart/form-data"}))
{%>

<% =ViewData["Result"] %>
<%: Html.ValidationSummary(true)%>



<%: Html.LabelFor(model => model.i_code) %>
<%: Html.TextBoxFor(model => model.i_code) %>
<%: Html.ValidationMessageFor(model => model.i_code) %>

<%: Html.LabelFor(model => model.i_name) %>
<%: Html.TextBoxFor(model => model.i_name) %>
<%: Html.ValidationMessageFor(model => model.i_name) %>

<%: Html.LabelFor(model => model.FileUpload) %>
input type="file" id="Image" name="Image"

input type="submit" value="Create"


<% } %>'




Controller Function:

[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create( itemviewmodel ToCreate)
{

if (ToCreate.Image.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../bin/Uploads"),
Path.GetFileName(ToCreate.Image.FileName.Replace(' ','_')));
ToCreate.Image.SaveAs(filePath);
ToCreate.i_imgpath = filePath;
}

_entities.AddToitems(m);
_entities.SaveChanges();

}


The things to be more careful are

1). Using a correct version of Html.BeginForm function(see above) and
2). Input type file should have "id" and "name" same value as the name of your viewmodel property field for file upload.
3). Make sure you have given sufficient permissions to the Network service or IUser Account for the folders where images will be stored, this is a common problem after deployment to many developers.

Further one more thing to be kept in mind is that your master page also has a
tag which will cause the
tag of the content page to be bypassed, to overcome this problem, remove
tag from the master page.


hope you will find this post helpful.
wish you good luck with file uploading.

Friday, March 25, 2011

calling a Stored Procedure using Entity Framework

Any stored procedure can be called through EF. Create a SP and add it to your model. Further go to the model browser, right click the sp, and click add function import, here select your SP, and select what type it returns, if it returns nothing then select 'None'. If it returns a sclar type then select the type, and if its returning a recordset then select complex. Click on get column information, it will show you the colums returning. click on create new complex type. and click ok. If its returning one of you entities then click on option entity and select the entity type from the list box.

now you call call it in your code.

if its returning a complex type use code:

MyEntities _entities = new MyEntities();
var p = from d in _entities.GetOrderInfo() select d;


if its returning nothing then use code:

MyEntities _entities = new MyEntities();
_entities.Cancel_Sale(ucode, oid);

Friday, February 25, 2011

simple application using mvccontrib grid

download the mvccontrib.dll, and add the reference of this dll to your application.


write a controller function:

public ActionResult salesreport()
{
handsetviewmodel vm = new handsetviewmodel();
return View(vm);

}



view code:

include the following namespace:

<%@ Import Namespace="MvcContrib.UI.Grid" %>
<%@ Import Namespace="MvcContrib.UI.Grid.ActionSyntax" %>


write the following code to display the grid

<%: Html.Grid(Model.handsetstock()).Columns(column => {

column.For(c=>c.itemcode);
column.For(c => c.imeicsv);


})%>

Tuesday, October 5, 2010

WCF Data Services.

The Data Services framework facilitates the creation of flexible data
services that are naturally integrated with the web. WCF Data Services
use URIs to point to pieces of data and use simple, well-known formats
to represent that data in the form of client libraries for consumers(
viz .NET, Silverlight, AJAX, PHP and Java).