Skip to main content

Posts

Showing posts from July, 2014

ASP.NET MVC 5 Example

This is for cshtml code @model Models.LoginViewModel @{ Layout = null; } @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { @Html. AntiForgeryToken () Welcome to PCX Not a member? @Html.ActionLink("Sign up now »", "SignUpForGuestUser", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" }) Or Login with your account @Html.ValidationSummary(true, String.Empty, new { @class =

MVC 5 Web API 2 Token Based Authentication

MVC 5 Preventing Cross-Site Request Forgery(CSRF) Attacks Table of Contents 1. In the 1st step add the function GetTokenHeader() to get token header. 2. In second step add the script code for post the ajax request with token header for API controller. 3. Add the ValidateAntiForgeryToken attribute for validate the antiforgery token on controller actions. 4. validate the all request using RequestVerificationToken and HttpRequestMessage. The below video show the steps where put the codes For more details seen the below example. //Step 1 //Put the code in cshtml page @{ Models.UserSession userSession = (Models.UserSession)Session["userSession"]; @functions{ public string GetTokenHeader() { string cookieToken, formToken; AntiForgery.GetTokens(null, out cookieToken, out formToken); return cookieToken + ":" + formToken; } } } //Step 2 //Th

if not null condition in sql server

I am going to share the example code for IF NOT NULL and the used condition for if not null in Sql Server as given below. DECLARE @PRICINGID INT SET @PRICINGID = NULL IF @PRICINGID IS NULL         SELECT @PRICINGID ELSE         SELECT 'NOT NULL'

drop table if exists in SQL Server

This is basically used for drop table using if exists in sql server . The example as given below. IF OBJECT_ID('TEMPDB..#SPLETEDTEMPTABLE') IS NOT NULL DROP TABLE #SPLETEDTEMPTABLE CREATE TABLE #SPLETEDTEMPTABLE(ID INT, SERVICES VARCHAR(300)) INSERT INTO #SPLETEDTEMPTABLE EXEC GET_SPLITED_TABLE 'Anil Singh India', '-'

How to check column table dependencies sql server?

I am going to share the code sample for how to   checkdependencies of table in Sql server . The example as give below. Method 1 :   using sp_depends to get table dependencies SQL Server SP_DEPENDS 'DBO.USAGE' Method 2 :   using information_schema . routines to get table dependencies SQL  Server SELECT *     FROM INFORMATION_SCHEMA . ROUTINES IS_RO     WHERE CHARINDEX ( 'DBO.USAGE' , IS_RO . ROUTINE_NAME ) > 0 Method 3   : using SYSCOMMENTS SELECT NAME FROM SYSCOMMENTS SYST     JOIN SYSOBJECTS SYSTOBJ ON SYST . ID = SYSTOBJ . ID     WHERE TEXT LIKE '%CALLTYPEID%'

prevent partial view in mvc 5 c#

We can prevent the partial view in MVC 5 using   ChieldActionOnly attribute on Partial-view action method in the  controller . The below example might help you. [ChildActionOnly] public PartialViewResult Partial(string id) { return PartialView(); }

Redirect from a view to another view using MVC 5

We can redirect a view to another view in mvc 5. The below code sample might help you for redirection using  Response.Redirect ( "~/Account/Login" ); @{ Models.UserSession userSession = (Models.UserSession)Session["userSession"]; if (userSession == null) { Response.Redirect("~/Account/Login"); } }

How to clear session in mvc 5 global.asax

We can clear the session on global level in mvc 5 using   Session_End () in global.asax. The below example might help you for clear the session and abandon session in the global levels. 1.  Session.Clear(); // for clear sessions. 2.  Session.Abandon(); // for a bandon  sessions. //End the application sessions. private void Session_End(object sender, EventArgs e) { Session.Clear(); Session.Abandon(); }

MVC 5 Redirect from the global.asax to controller action

We can redirect to controller actions from Global.asax in ASP.Net MVC 5 using the method - RedirectToControllers .  The  RedirectToControllers () method provided by MVC 2 + versions.  Example , it might help you to understand more about the same. /// <summary> /// gets the authentication cookie /// if the cookie is null then redirect to controller action /// </summary> protected void Application_AuthenticateRequest(Object sender, EventArgs e) {     // Get the authentication cookie.     string cookieName = FormsAuthentication.FormsCookieName;     HttpCookie authCookie = Context.Request.Cookies[cookieName];     // If the cookie is null then redirect to the controller action.     if (authCookie == null )     {         RedirectToControllers( "Account" , "Login" );     } }   ///<summary> /// Clear the response. /// Clear the server errors. /// Create the route using RouteData (controller/acti

download excel file using c# mvc 5 jquery

We can download files using the below mvc 5 code or jQuery code both code are woking. C# code work in server side but jQuery on client only. Download Excel File using C# MVC 5 .Net public ActionResult DownloadExcelFile(string Orgfile = "DownloadSampleFile.xlsx") { string filePath = Server.MapPath("~/UploadedExcelFolder/DownloadSampleFile.xlsx"); System.IO.FileInfo file = new System.IO.FileInfo(filePath); if (file.Exists) { Response.Clear(); Response.AddHeader("Content-Disposition", "attachment; filename=" + Orgfile); Response.AddHeader("Content-Length", file.Length.ToString()); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.WriteFile(file.FullName); } return RedirectToAction("Success"); } OR    Download Excel File using jQuery $('#btnDownloadExcel').click(fun

how to add a drop down in excel sheet

We can add the drop-down  list in excel files. The given below steps and video might help you. Table of Contents Step1 . Open excel sheet . Step2 . Type items for display in drop-down. Step3 . Select area where u want to display drop-down. Step4 . Go to the data tab. Step5 . Select the data validation tab and click on it. Step6 . Select the setting tab in data validation. Step7 . Allow the list validation criteria. Step8 . Add the source of typed items Step1.

How to execute stored procedure and set temp table in sql server 2008?

We can set the temp table by execute procedure results. The below example might help you. Table of Contents 1. Drop Temp table 2. Create Temp table 3. Insert into Temp Table form Store procedure 4. Select inserted data from Temp table. execute stored procedure and set temp table in sql server 2008 DROP TABLE #TempTable CREATE TABLE #TempTable(Id INT, Services VARCHAR(300)) INSERT INTO #TempTable EXEC GET_SPLITED_TABLE 'ANIL-KUMAR-SINGH', '-' SELECT * FROM #TempTable http://www.code-sample.com/2014/07/execute-stored-procedure-and-set-temp.html

How to split a string in sql server 2008 using stored procedure and insert the data to table

We can split the strings in SQL Server using split identifies( _, -, |, ' ', .... ). The below code-sample might help you. Table of Contents 1. Create Function for Split Strings Using Identifier . 2. Create Procedure and call split function within procedure . Create Function for Split Strings Using Identifier CREATE FUNCTION dbo.Split ( @ListItems NVARCHAR(2000), @Identifier NVARCHAR(5) ) RETURNS @RtnValue TABLE ( Id INT IDENTITY(1,1), Value NVARCHAR(100) ) AS BEGIN WHILE (CHARINDEX(@Identifier,@ListItems)>0) BEGIN INSERT INTO @RtnValue (value) SELECT Value = LTRIM(RTRIM(SUBSTRING(@ListItems,1,CHARINDEX(@Identifier,@ListItems)-1))) IF(@Identifier = ' ') SET @ListItems = SUBSTRING(@ListItems,CHARINDEX(@Identifier,@ListItems)+1,LEN(@ListItems)) ELSE SET @ListItems = SUBSTRING(@ListItems,CHARINDEX(@Identifier,@ListItems)+

how to use isnull function in sql server 2008

We can use the  ISNULL ()  function in SQL Server. The given below code-sample might help you. SELECT SUSR.ID ,SUSR.EmailID ,SUSR.MobileNo ,ISNULL(SUSR.NickName, SUSR.FirstName +' '+ SUSR.LastName) as SubrName ,SUSR.StatusID FROM [SubscriberUser] SUSR order by SUSR.ID desc

case in sql server 2008 r2

We can use  CASE  in single line query in SQL Server. The given below example might help you. DECLARE @NET VARCHAR(10) SET @NET ='3G' SELECT (CASE @NET WHEN '4G' THEN 1 WHEN '3G' THEN 2 WHEN '2G' THEN 3 END) AS NETWORKID Result : NETWORKID is 2

How to insert a data table into SQL Server database table

Table of Contents 1. Create a User-Defined TableType in your db. 2. Create Stored Procedure and define the parameters. 3. using c# .net, send the DataTable data to sql server . Create a User-Defined TableType in your db. /****** Object:  UserDefinedTableType [dbo].[MapExcelTableType]    Script Date: 07/22/2014 14:57:05 ******/ CREATE TYPE [dbo] . [MapExcelTableType] AS TABLE (       [ID] [int] NULL,       [CostCenter] [varchar] ( 150 ) NULL,       [MobileNo] [varchar] ( 150 ) NULL,       [EmailID] [varchar] ( 150 ) NULL,       [FirstName] [varchar] ( 150 ) NULL,       [LastName] [varchar] ( 150 ) NULL,       [Services] [varchar] ( 150 ) NULL,       [UsageType] [varchar] ( 150 ) NULL,       [Network] [varchar] ( 150 ) NULL,       [UsageIncluded] [int] NULL,       [Unit] [varchar] ( 150 ) NULL ) GO Create Stored Procedure and define the parameters. ALTER PROCEDURE [dbo] . [SubscriberServiceMappingByExcel]       @Ta

c# mvc 5 convert datatable to xml data string

We can convert data-table to XML data string using MVC 5 C# .Net. The given below code-sample is might help you to converting the same. Table of  Contents 1. Create string builder object. 2. Set the table name. 3. Append row data and table name. //Convert data table in to XML data string method public string ConvertDataTableToXMLDataString ( DataTable dataTbl) {        StringBuilder XMLString = new StringBuilder ();           if ( string .IsNullOrEmpty(dataTbl.TableName))                 dataTbl.TableName = "DataTable" ;             XMLString.AppendFormat( "<{0}>" , dataTbl.TableName);             DataColumnCollection tableColumns = dataTbl.Columns;             foreach ( DataRow row in dataTbl.Rows)             {                 XMLString.AppendFormat( "<RowData>" );                 foreach ( DataColumn column in tableColumns)                 {                     XMLString.AppendFormat( "