Wednesday, 30 April 2014

Find references table from specified table.

Find references table from specified table.


SELECT
   OBJECT_NAME(f.parent_object_id) TableName,
   COL_NAME(fc.parent_object_id,fc.parent_column_id) ColName
FROM
   sys.foreign_keys AS f
INNER JOIN
   sys.foreign_key_columns AS fc
      ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN
   sys.tables t
      ON t.OBJECT_ID = fc.referenced_object_id
WHERE
   OBJECT_NAME (f.referenced_object_id) = 'Customer'

Monday, 31 March 2014

Enable/Disable datepicker using jquery in mvc.

$("#txtcurrentdate").datepicker("enable");
$("#txtcurrentdate").datepicker("disable");
This disables the entire textbox. So may be you can use datepicker.destroy() instead:

$(document).ready(function() {
    $("#ddlsearch").change(function() {
        if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date") {
            $("#txtcurrentdate").datepicker();
        }
        else {
            $("#txtcurrentdate").datepicker("destroy");
        }
    }).change();
});

Monday, 10 March 2014

Find first element of second td of second tr.

<table>
<tr>
<td>
<input type="text" value="Test" name="txttest" maxlength="200" id="txttestfrom_1" class="inputSmall left valid" onchange="return GetValue(this);">
</td>
<td>
<input type="text" value="Test" name="txttest" maxlength="200" id="txttestto_1" class="inputSmall left
valid" onchange="return GetValue(this);">
<input type="text" value="Test" name="txttest" maxlength="200" id="txttestMax_1" class="inputSmall left valid" onchange="return GetValue(this);">
</td>
<td>
<input type="text" value="Test" name="txttest" maxlength="200" id="txttestdata_1" class="inputSmall left valid" onchange="return GetValue(this);">
</td>
</tr>
<tr>
<td>
<input type="text" value="Test" name="txttest" maxlength="200" id="txttestfrom_2" class="inputSmall left valid" onchange="return GetValue(this);">
</td>
<td>
<input type="text" value="Test" name="txttest" maxlength="200" id="txttestto_2" class="inputSmall left valid">
<input type="text" value="Test" name="txttest" maxlength="200" id="txttestMax_2" class="inputSmall left valid" onchange="return GetValue(this);">
</td>
<td>
<input type="text" value="Test" name="txttest" maxlength="200" id="txttestdata_2" class="inputSmall left valid" onchange="return GetValue(this);">
</td>
</tr>
</table>

<script>
function GetValue(obj)
{

alert($(obj).closest('tr').next('tr').find('td:nth-child(2) > input:nth-child(1)').attr("id"));
}

</script>



OutPut:

txttestto_2

Wednesday, 12 February 2014

Kendo UI Grid / Popup editing with selected droup down list field Using ASP.NET MVC.




Kendo UI Grid / Popup editing with selected droup down list field.


In order to get start with coding, please create a new ASP.NET MVC 4 Project using Visual Studio and choose Telerik Mvc web application . When the new project is created successfully, you can easily find "Model", "View" and "Controller" folders inside it.


     First of all, we will be creating a new domain model class inside the model folder say "ProductList.cs" as:   

 public class ProductList
    {

        public int ProductId { get; set; }


        public string Name { get; set; }


        public string Picture { get; set; }


        public decimal Price { get; set; }


        public string  CategoryName { get; set; }


        public int CategoryId { get; set; }


        public bool IsActive { get; set; }


        public bool Deleted { get; set; }


        public DateTime CreatedOnUtc { get; set; }


        public DateTime UpdatedOnUtc { get; set; }


    }


Now, its time to add controller class to your project. In controller folder, you will find two controller classes by default i.e. HomeController.cs and ValuesController.cs. Add a new controller "ProductController.cs" under "Controller" folder. Following will be the code for it.

 public class ProductController : Controller
    {

        #region - Action Method -

        //
        // GET: /Admin/Product/

        /// <summary>

        /// Get all product list
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            ViewBag.Categories = Categories(0);
            return View();
        }

        /// <summary>

        /// Get all active product list from database.
        /// </summary>
        /// <param name="Request">Data source read request </param>
        /// <returns> return all the active product.</returns>
        public ActionResult Read([DataSourceRequest]DataSourceRequest Request)
        {

            var Result = new M2CommerceDataContext();




            return Json(Result.Products.Where(x => x.IsActive == true && x.Deleted == false).Select(product => new ProductList

            {
                ProductId = product.ProductId,
                Name = product.Name,
                CategoryName = product.Category.Name,
                CategoryId = product.CategoryId,
                Price = product.Price.Value,
                Picture = product.Picture,
                CreatedOnUtc = product.CreatedOnUtc,
                UpdatedOnUtc = product.UpdatedOnUtc,
                IsActive = product.IsActive,
                Deleted = product.Deleted,

            }).OrderByDescending(x => x.ProductId).ToDataSourceResult(Request));


        }


        /// <summary>

        /// Get all the active category from database. 
        /// </summary>
        /// <param name="id">CategoryId</param>
        /// <returns>return all the active category.</returns>
        public List<CategoryList> Categories(int? id)
        {
            var Result = new M2CommerceDataContext();


            return Result.Categories.Where(x => x.IsActive == true && x.Deleted == false).Select(x => new CategoryList

            {
                Name = x.Name,
                CategoryId = x.CategoryId,


            }).ToList();




        }



        public ActionResult Update([DataSourceRequest]DataSourceRequest Request, ProductList model, HttpPostedFileBase Picture)

        {

            if (ModelState.IsValid)

            {
                using (var dbcontext = new M2CommerceDataContext())
                {

                    var existingdata = dbcontext.Products.Single(x => x.ProductId == model.ProductId);


                    existingdata.Name = model.Name;

                    existingdata.IsActive = model.IsActive;
                    existingdata.Deleted = model.Deleted;
                    existingdata.CategoryId = model.CategoryId;
                    existingdata.UpdatedOnUtc = DateTime.UtcNow;
                    dbcontext.SubmitChanges();
                }
            }

            return Json(new[] { model }.ToDataSourceResult(Request, ModelState));

        }
        #endregion

        #region - Pricate Method -


        public ActionResult RenderPhoto(int id)

        {
            var Result = new M2CommerceDataContext();

            string imageData = Result.Products.Single(x => x.ProductId == id).Picture;


            if (imageData != null)

            {
                return File("~/Uploads/" + imageData.ToString(), "image");
            }
            return null;


        }


        #endregion


    }

Now its time to create Popup view to your project. Add new view under the EditorTemplates forlder inside shared folder with the name as _Product.cshtml. Following will be the code for it.


@model M2Commerce.Models.ProductList
@{
    ViewBag.Title = "_Product";
   
}
@using Kendo.Mvc.UI;
<div class="editor-label">
    @(Html.LabelFor(model => model.Name))
</div>
<div class="editor-field">
    @(Html.TextBoxFor(model => model.Name, new { @class = "k-textbox" }))
    @Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
    @(Html.LabelFor(model => model.CategoryId))
</div>
<div class="editor-field">
    @Html.Kendo().DropDownListFor(x => x.CategoryId).BindTo(new SelectList(ViewBag.Categories, "CategoryId", "Name"))
    @(Html.HiddenFor(model => model.CategoryId, new { @id = "hdnCategory" }))
</div>
<div class="editor-label">
    @(Html.LabelFor(model => model.Price))
</div>
<div class="editor-field">
    @(Html.TextBoxFor(model => model.Price, new { @class = "k-textbox" }))
    @Html.ValidationMessageFor(model => model.Price)
</div>
<div class="editor-label">
    @(Html.LabelFor(model => model.Picture))
</div>
<div class="editor-field">
    <img src='@Url.Action("RenderPhoto", "Product", new { @id = "${ProductId}" }, @Request.Url.Scheme)' height="100" width="100" />
    @(Html.Kendo().Upload().ShowFileList(true).Name("Picture"))
    @Html.ValidationMessageFor(model => model.Picture)
</div>

Now create main view inside Product folder in view part as Index.cshtml.Following will be the code for it.
@{
    ViewBag.Title = "Index";
    Layout = "~/Areas/Admin/Views/Shared/_AdminLayout.cshtml";
}
@using Kendo.Mvc.UI;
@using Kendo.Mvc.Extensions;
@using M2Commerce.Models;

<script type="text/javascript"> 

    var options = @(Html.Raw(Json.Encode(ViewData["Categories"])))

</script>

<div id="example">
    <section class="well">
                <h3 class="ra-well-title">Product List</h3>
                
                  @(Html.ActionLink("Create", "Create", "Product"))
    <div id="UserList">
    
   @(Html.Kendo().Grid<M2Commerce.Models.ProductList>()
    .Name("ProductGrid")
    .Columns(column =>
    {

        column.Bound(x => x.Name).Width(100);

        column.Bound(x => x.UpdatedOnUtc).Format("{0:d}").Width(100);
        column.Bound(x => x.Price).Width(100);
        column.Bound(x => x.CategoryName).Width(100);
        
        column.Command(command =>
        {
            command.Edit();
            command.Destroy();
        }).Title("Action")
        .Width(100);
    })
    .ToolBar(toolbar =>
    {

        toolbar.Create();

    })
    .Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("_Product"))
         .Scrollable()
        .Groupable()
        .Sortable()
                
        .Pageable(pageable => pageable
            .Refresh(true)
            .PageSizes(true)
            .ButtonCount(5))
        .DataSource(dataSource => dataSource
            .Ajax()
                    .Model(model =>
                    {
                        model.Id(usr => usr.ProductId);
                        model.Field(usr => usr.ProductId).Editable(false);
                       
                      
                    }).PageSize(5)
                   .Read(read => read.Action("Read", "Product"))
                           .Update(update => update.Action("Update", "Product"))
                   .Create(create => create.Action("Create", "Product"))
                           .Destroy(delete => delete.Action("Delete", "Product"))
    ))
    </div></section>

</div>

Thursday, 18 July 2013

Direct Print with Report Viewer 2012

// Set report datasource to local report

 LocalReport report = new LocalReport();
            report.Refresh();
            report.ReportPath="ReportOrderReceipt.rdlc";//set your report path
            ReportParameter[] parms = new ReportParameter[5];
            report.DataSources.Add(new ReportDataSource("dsorder", dtitem));
            parms[0] = new ReportParameter("TrnsDisc", Convert.ToString(transactionvalue), false);
            parms[1] = new ReportParameter("TrnsPercentDis", Convert.ToString(transactionDisc), false);
            parms[2] = new ReportParameter("Total", Convert.ToString(total), false);
            parms[3] = new ReportParameter("TransactionId", Convert.ToString(TransactionId), false);
            parms[4] = new ReportParameter("customername", txtcustomername, false);
            report.SetParameters(parms);



// Export the given report as an EMF (Enhanced Metafile) file.

 private void Export(LocalReport report)
        {
            string deviceInfo =
              @"<DeviceInfo>
                <OutputFormat>EMF</OutputFormat>
                <PageWidth>3.25in</PageWidth>
                <PageHeight>11in</PageHeight>
                <MarginTop>0.20in</MarginTop>
                <MarginLeft>0.20in</MarginLeft>
                <MarginRight>0in</MarginRight>
                <MarginBottom>0in</MarginBottom>
            </DeviceInfo>";
            Warning[] warnings;
            m_streams = new List<Stream>();
            report.Render("Image", deviceInfo, CreateStream,
               out warnings);
            foreach (Stream stream in m_streams)
                stream.Position = 0;
        }


 // Handler for PrintPageEvents
        private void PrintPage(object sender, PrintPageEventArgs ev)
        {
            Metafile pageImage = new
               Metafile(m_streams[m_currentPageIndex]);

           // Adjust rectangular area with printer margins.
            Rectangle adjustedRect = new Rectangle(
                ev.PageBounds.Left - (int)ev.PageSettings.HardMarginX,
                ev.PageBounds.Top - (int)ev.PageSettings.HardMarginY,
                ev.PageBounds.Width,
                ev.PageBounds.Height);

            // Draw a white background for the report
            ev.Graphics.FillRectangle(Brushes.White, adjustedRect);

            // Draw the report content
            ev.Graphics.DrawImage(pageImage, adjustedRect);

            // Prepare for the next page. Make sure we haven't                  hit the end.
            m_currentPageIndex++;
            ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
        }

        private void Print()
        {
            if (m_streams == null || m_streams.Count == 0)
                throw new Exception("Error: no stream to print.");
            PrintDocument printDoc = new PrintDocument();
            if (!printDoc.PrinterSettings.IsValid)
            {
                throw new Exception("Error: cannot find the default printer.");
            }
            else
            {
                printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
                m_currentPageIndex = 0;
                printDoc.Print();
            }
        }


// Create a local report for Report.rdlc, load the data,
//    export the report to an .emf file, and print it.


        public void Dispose()
        {
            if (m_streams != null)
            {
                foreach (Stream stream in m_streams)
                    stream.Close();
                m_streams = null;
            }
        }

Wednesday, 17 July 2013

Retrieve Random Record/Row from DataBase Table Using LINQ 2 SQL

var qry = from row in ctx.Customers
          where row.IsActive
          Order by row.Name 
          select row;
int count = qry.Count(); // 1st round-trip
int index = new Random().Next(count);

Customer cust = qry.Skip(index).FirstOrDefault(); // 2nd round-trip

Saturday, 20 April 2013

N level category display in tree structure using stored procedure

 N level category display in tree structure using stored procedure


CREATE PROCEDURE ASD_SP_GetCategoryId   
    (   
      @CultureId INT = 1 ,   
      @CategoryID INT = NULL   
    )   
AS    
 WITH    CTE ( CategoryID, CategoryName, ParentCategoryID, level, ParentName, IsActive ) 
          AS ( SELECT   CategoryID , 
                        CategoryName , 
                        ParentCategoryID , 
                        0 , 
                        CASE WHEN ParentCategoryID = 0 
                             THEN CAST(CategoryName AS VARCHAR(MAX)) 
                             ELSE CAST(CategoryName AS VARCHAR(MAX)) 
                        END , 
                        IsActive 
               FROM     Asd_vw_CategoryMAster 
               WHERE    ParentCategoryID = 0 
                        AND CategoryID <> ISNULL(@CategoryID, -1) 
                        AND IsDeleted = 0 
                        AND cultureId = @CultureId 
               UNION ALL 
               SELECT   C.CategoryID , 
                        C.CategoryName , 
                        C.ParentCategoryID , 
                        level + 1 , 
                        CAST (CT.ParentName + ' >> ' + C.CategoryName AS VARCHAR(MAX)) , 
                        C.IsActive 
               FROM     Asd_vw_CategoryMAster C 
                        INNER JOIN CTE CT ON CT.CategoryID = C.ParentCategoryID 
               WHERE    c.cultureId = @CultureId 
                        AND C.IsDeleted = 0 
                        AND C.CategoryID <> ISNULL(@CategoryID, -1) 
             ) 
    SELECT  CategoryID , 
            ParentName AS CategoryName , 
            ParentCategoryID , 
            IsActive 
    FROM    CTE 
    ORDER BY ParentName