Wednesday, 31 July 2013

Finding Last Record in SQL table


SELECT TOP 1 * FROM CareerPathChildItems ORDER BY CPCID DESC

Finding Top record in SQL table


SELECT TOP 1 * FROM CareerPathChildItems ORDER BY CPCID ASC

Finding the 10th record in sql table


WITH NthRowCTE AS
(
    SELECT
        ROW_NUMBER() OVER (ORDER BY primarykeyfield) AS RNum
        , *
    FROM tablename
)
SELECT * FROM NthRowCTE WHERE RNum = 10
GO

-----------------------------------------------


select

* from
(
SELECT ROW_NUMBER() OVER (ORDER BY Primaryfieldcolumn) AS tablefield1, tablefield2, tablefield3
FROM Tablename
) T1

where T1.RowNumber=10

Stored Procedure for Listing Active Directory Users


USE [DatabaseName]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:                     <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[ADUsersList]
            -- Add the parameters for the stored procedure here
           
AS
BEGIN
            -- SET NOCOUNT ON added to prevent extra result sets from
            -- interfering with SELECT statements.
            SET NOCOUNT ON;

    -- Insert statements for procedure here
            SELECT  sAMAccountName,givenName, sn, userAccountControl,mail FROM OpenQuery(ADSI, '<LDAP://DOMAINNAME.LOCAL/DC=DOMAINNAME,DC=LOCAL>;(&(objectClass=User)(|(sAMAccountName=A*)(sAMAccountName=B*)(sAMAccountName=C*)(sAMAccountName=D*)) );sAMAccountName,givenName, sn, mail,userAccountControl;subtree')
UNION ALL
SELECT  sAMAccountName,givenName, sn, userAccountControl,mail FROM OpenQuery(ADSI, '<LDAP://DOMAINNAME.LOCAL/DC=DOMAINNAME,DC=LOCAL>;(&(objectClass=User)(|(sAMAccountName=E*)(sAMAccountName=F*)(sAMAccountName=G*)(sAMAccountName=H*)) );sAMAccountName,givenName, sn, mail,userAccountControl;subtree')
UNION ALL
SELECT  sAMAccountName,givenName, sn, userAccountControl,mail FROM OpenQuery(ADSI, '<LDAP://DOMAINNAME.LOCAL/DC=DOMAINNAME,DC=LOCAL>;(&(objectClass=User)(|(sAMAccountName=I*)(sAMAccountName=J*)(sAMAccountName=K*)(sAMAccountName=L*)) );sAMAccountName,givenName, sn, mail,userAccountControl;subtree')
UNION ALL
SELECT  sAMAccountName,givenName, sn, userAccountControl,mail FROM OpenQuery(ADSI, '<LDAP://DOMAINNAME.LOCAL/DC=DOMAINNAME,DC=LOCAL>;(&(objectClass=User)(|(sAMAccountName=M*)(sAMAccountName=N*)(sAMAccountName=O*)(sAMAccountName=P*)) );sAMAccountName,givenName, sn, mail,userAccountControl;subtree')
UNION ALL
SELECT  sAMAccountName,givenName, sn, userAccountControl,mail FROM OpenQuery(ADSI, '<LDAP://DOMAINNAME.LOCAL/DC=DOMAINNAME,DC=LOCAL>;(&(objectClass=User)(|(sAMAccountName=Q*)(sAMAccountName=R*)(sAMAccountName=S*)(sAMAccountName=T*)) );sAMAccountName,givenName, sn, mail,userAccountControl;subtree')
UNION ALL
SELECT  sAMAccountName,givenName, sn, userAccountControl,mail FROM OpenQuery(ADSI, '<LDAP://DOMAINNAME.LOCAL/DC=DOMAINNAME,DC=LOCAL>;(&(objectClass=User)(|(sAMAccountName=U*)(sAMAccountName=V*)(sAMAccountName=W*)(sAMAccountName=X*)) );sAMAccountName,givenName, sn, mail,userAccountControl;subtree')
UNION ALL
SELECT  sAMAccountName,givenName, sn, userAccountControl,mail FROM OpenQuery(ADSI, '<LDAP://DOMAINNAME.LOCAL/DC=DOMAINNAME,DC=LOCAL>;(&(objectClass=User)(|(sAMAccountName=Y*)(sAMAccountName=Z*)) );sAMAccountName,givenName, sn, mail,userAccountControl;subtree')

ORDER BY sn
END

Code for downloading large amount of data file >5MB


protected void Download(object sender, EventArgs e)
    {
        string filename = Convert.ToString(((LinkButton)sender).CommandArgument);
        string filepath = "../Content/Files/";
        filepath = filepath + "" + filename;
        string extension = System.IO.Path.GetExtension(filename).ToString();

        if (filename != "")
        {
            if (extension == ".doc" || extension == ".docx")
            {
                if (File.Exists(Server.MapPath(filepath)))
                {
                    if (extension == ".docx")
                    {
                        Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                    }
                    else
                    {
                        Response.ContentType = "application/msword";
                    }
                    Response.AddHeader("content-disposition", "attachment;filename=" + filename);
                    Response.WriteFile(filepath);
                    Response.End();
                    Response.Flush();
                }
            }
            else
            {
                if (File.Exists(Server.MapPath(filepath)))
                {
                    Response.ClearContent();
                    Response.ClearHeaders();
                    Response.ContentType = "application/pdf";
                    Response.AddHeader("Content-Disposition", "attachment; filename=" +
                    filename);
                    Response.WriteFile(filepath);
                    Response.End();
                }
            }
        }
    }

When session gets expired it should redirect to the index page for that declare:

<machineKey validationKey="3AE041467624C0947FE562E2DBE6122B532FBC4AA9845AE3D82EC6AC473104EA40A27F8E89BADDAEE44B1F7582FC47299B674ED1FD2DDE1368710504EB2C54C1" decryptionKey="2FC79A393A5A463F82D38828F43ED7D030C418B448C9E76C" validation="SHA1"/>

Maximum request length exceeded


For big file uploads declare:

 <httpRuntime maxRequestLength="32768"/>

A potentially dangerous Request.QueryString Value was detected from the client (=”<script>”).

Solution:

Web.config file:

<pages validateRequest="false" />

Or disable it at the page level:

<%@ Page Language="C#" ValidateRequest="false" %>

Saturday, 27 July 2013

Video Play on Page Load using SWF player

<h2>Video Play on Page Load</h2>
<script src="@Url.Content("~/Content/video/jwplayer.js")"></script>
<script src="@Url.Content("~/Content/video/jquery-latest.js")"></script>
<script type="text/javascript">
    $(document).ready(function () {
        var videoPath = "@Url.Content("~/Content/Video/")";
        jwplayer("video_player").setup({
            flashplayer: videoPath + "player.swf",
            autostart: true,
            file: videoPath + "welcome.mp4",
            height: 344,
            width: 495
        });

        jwplayer().onComplete(function () {
            _gaq.push(['_trackEvent', 'Clicks', 'Video Player', 'Watched video till end']);

        });

        jwplayer().onPlay(function () {
            _gaq.push(['_trackEvent', 'Clicks', 'Video Player', 'Video Played']);

        });

        jwplayer().onPause(function () {
            _gaq.push(['_trackEvent', 'Clicks', 'Video Player', 'Video Paused']);

        });
    });
</script>

<div id="video_player">Loading the player ...</div>
Include Jquery latest file: http://www.4shared.com/document/rXvQEdmV/jquery-latest.htm ,
swf player and 
jwplayer js file: http://www.2shared.com/complete/ZT7n-cEV/jwplayer.html

Different ways of MVC Dropdown binding


1. Static

   @Html.DropDownListFor(model => model.Gender, new SelectList(new[] { "Male", "Female" }), "--Select--")

2. Using View Data

View

  @Html.DropDownListFor(model => model.Country, new SelectList(((System.Collections.IEnumerable)ViewData["CList"]), "Value", "Text"), "—Select”)

Controller

     List<DTO> lstadto = Getlist();
  ViewData["CList"] = lstadto;

3. Using Model List

View

    @(Html.DropDownListFor(model => model.Country, new SelectList(Model.CountryList, "Value", "Text"), new { @class = "txtbox", id = "ddlcid" }))

Controller

Model dto=new model();
Dto.CountryList=getlist();
Return View(dto);

4. Using script jsonresult

Script

var URL = '@Url.Action("GetCountry")';
            $.getJSON(URL, function (data) {
                $('.ddlcountry').html(data);
            });

View

  @(Html.DropDownListFor(model => model.Country, new SelectList(Model.CountryList, "CID", "CName"), new { @class = "txtbox", id = "ddlcountry" }))

Controller

public JsonResult GetCountry()
        {
           string code = string.Empty;
            StringBuilder sb = new StringBuilder();
            List<DTO> lstadto = FillCountries();       
            foreach (var data in lstadto)
            {
                sb.Append("<option value='" + data.CID + "' >" + data.CName + " </option> ");
            }
            return Json(sb.ToString(), JsonRequestBehavior.AllowGet);
        }

5. Using script add options

Script

$('.ddlcountry').html(null);
            $('.ddlcountry').append($('<option/>', {
                value: 0,
                text: "-- Select --"
            }));

View

  @(Html.DropDownListFor(model => model.Country, new SelectList(Model.Countrylst, "CID", "CName"), new { @class = "txtbox", id = "ddlcountry" }))

6. Using script

Script

var url = '@Url.Content("../Clinic/Getdoc")';
  $.getJSON(url, { dep: 1 }, function (data) {
                $(ddltarget).empty();
                $("#doc").append("<option  value=''>Select </option>");
                $.each(data, function (index, Data) {
                    $("#doc").append("<option value='" + Data.UID + "'>" + Data.FName + "</option>");
                });

View

@Html.DropDownList("doc", Enumerable.Empty<SelectListItem>(),
    new { @style = "width: 175px;" })

Controller

public JsonResult Getdoc(int dep)
        {
            JsonResult result = new JsonResult();
            var dt = _icserv.DocList(dep);
            result.Data = dt;
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;
        }