Amazon Ad

Tuesday, 15 November 2016

How to create dynamic menus in MVC partial view?

Hi,

I was wonder how to create dynamic views in MVC partial view.

1. Create your table with name Menu

MenuId int
MenuName varchar(150)
MenuLink varchar(250)
ParentId int

Create a procedure

-- =============================================
-- Author:        <Ritesh Tandon>
-- Create date: <Create Date,,>
-- Description:    <Description,,>
-- =============================================

Create PROCEDURE [dbo].[pGetUserMenus]
    -- Add the parameters for the stored procedure here
    @RoleId int=3
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    WITH Tree_CTE(MenuId, MenuName,MenuLink, ParentId,ParentName,IsActive,EntryBy,level)
AS
(
    SELECT MenuId,MenuName,MenuLink,ParentId,
    (select MenuName from MenuMaster where MenuId=MenuMaster.ParentId) as ParentName
    ,IsActive,EntryBy,rank() over (partition by ParentId order by MenuId)+1 as level
    FROM MenuMaster WHERE ParentID is null
    UNION ALL
    SELECT ChildNode.MenuId,ChildNode.MenuName,ChildNode.MenuLink,ChildNode.ParentId,
    (select MenuName from MenuMaster where MenuId=ChildNode.ParentId) as ParentName
    ,ChildNode.IsActive,ChildNode.EntryBy,Tree_CTE.level
    FROM MenuMaster AS ChildNode
    INNER JOIN Tree_CTE
    ON ChildNode.ParentID = Tree_CTE.MenuId
)
SELECT MenuId,MenuName,MenuLink,ParentId,ParentName,IsActive,EntryBy,level
FROM Tree_CTE
where MenuId in (select MenuId from RolesMenu where RoleId=@RoleId)
    and Isactive=1
order by level,ParentId


END
2. In your controller

public ActionResult _MainMenu()
        {
            return PartialView("_Menu", db.pGetUserMenus(0));
        }


3. In your partial view

@model IEnumerable<Menu>
<div class="hor-menu  ">
    <ul class="nav navbar-nav">
        @{
        int temp_pid=-1;   
               
        foreach (var item in Model)
        {
                if(item.ParentId == 0)
                {
                    @((item.ParentId==0)?Html.Raw("</li>"):Html.Raw(""))
                    @((item.ParentId==0 && temp_pid>0)?Html.Raw("</ul>"):Html.Raw(""))
           
                    @((item.ParentId==0)?Html.Raw("<li class='menu-dropdown classic-menu-dropdown '>"):Html.Raw(""))
                    <a href="javascript:;">
                        <i class="icon-note"></i>@item.MenuName
                    </a>
                }

                if (item.ParentId != 0)
                {
                   
                    @((temp_pid!=0 && temp_pid!=-1 && item.ParentId==0)?Html.Raw("</ul>"):Html.Raw(""))
                    @((temp_pid==0 && temp_pid!=-1 && item.ParentId!=0)?Html.Raw("<ul class='dropdown-menu pull-left'>"):Html.Raw(""))
                   
                        <li class=" ">
                            <a href="@item.MenuLink" class="nav-link">@item.MenuName</a>
                        </li>
                }
               
                temp_pid = item.ParentId;
        }
        }
    </ul>

Enjoy!!

Tuesday, 5 July 2016

How to add questions in between youtube videos

I was given a task to embed questions in between youtube videos. The questions should appear after a particular timeframe i.e like after 10 seconds and after 30 seconds. I found a javascript file which takes care of the same. Create a div tag in your html page, the id attribute of the div tag should be "player". There is also a div which has a popup with id "myModal" which is used to invoke the popup. You can use any jquery or javascript popup for the same. In this case I have used inbu

Here is the complete code of the file

<script src="https://www.youtube.com/iframe_api"></script>
<script>
      var player,videoid;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          height: '415px',
          width: '780px',
          videoId: 'YOUR_YOUTUBE_VIDEO_ID',
      playerVars: { 'autoplay': 0, 'controls': 1,'autohide':1,'wmode':'opaque' },
          events: {
            'onStateChange': onPlayerStateChange
          }
        });
      }

      var done = false,isQ1displayed=false,isQ2displayed=false;
      function onPlayerStateChange(event) {
          setInterval(function () {
              var current_time = player.getCurrentTime();
              console.log(current_time);
              if(Math.floor(current_time)==10 && isQ1displayed==false)
              {
          $("#myModalLabel").html("Q. Question 1?");   
          pauseVideo();
          isQ1displayed=true;
          done=true;
              }
          else if(Math.floor(current_time)==30 && isQ2displayed==false)
              {
          $("#myModalLabel").html("Q. Question 2?");
          pauseVideo();
          isQ2displayed=true;
          done=true;
              }
          }, 1);
      }
     
      function hidePopup(){
    $('#myModal').modal('hide');
    done=false;
    playVideo();
      }
     
      function showPopup(){
    $('input[type=radio]').each(function() { this.checked = false; });
    $('#myModal').modal({
    backdrop:'static',
    keyboard:false
    });
      }
     
      function pauseVideo() {
          player.pauseVideo();
      showPopup();
      }

      function playVideo() {
          player.playVideo();
      }

      function stopVideo() {
        player.stopVideo();
      }
</script>

Thanks
Ritesh Tandon

Saturday, 30 April 2016

How to generate dynamic URL from javascript.

Dear all,

I was given a task to generate dynamic url using javascript, After going through all the aspects I decided to work with history object available in javascript. Almost every modern browser today supports modern techniques used in html5. There are basically two methods, Apart from external plugins for url rewriting we can use these inbuilt javascript functions.

1. PushState as the name suggests pushes the history object in the history, just like stack push. It adds the object in the history object which is taken automatically by the browser. The first object is taken as the current object. For Instance,

window.history.pushState(null, response.pageTitle, '/developer/consturction/House');

Here, the statObj is an object which is the object taking the object value. Next parameter is page title and last parameter is urlPath is path which is displayed on the browser.
This is used in most of the cases when the url is to be created dynamically based on user action on the browser without page post back or reload. In the above example, When executed the URL of the browser will become, http(s)://yourdomain/developer/construction/House.

2 ReplaceState as the name suggests, it replaces the exising object with a new object. For example,

window.history.replaceState(stateObj,response.pageTitle,urlPath);

Here the parameters are the same except for the functionality.

Thanks
Ritesh

Friday, 8 April 2016

Authorize your WEB API to send data only to your website only

Hi,

I was wondering how we could implement security in web API, I wanted to send JSON data only to my desired website(s). Therefore, I decided to  create a custom Authorize Attribute in C# which will authorize any request and will help in implementing security for WEB API.

First we will create a class like below

public class ApiAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
    {
        private string _responseReason = "";
        public bool ByPassAuthorization { get; set; }

        List<string> allowedWebsites = new List<string>();

        public ApiAuthorizeAttribute()
        {
            //List of authorized websites
            allowedWebsites.Add("localhost");
            allowedWebsites.Add("dev.test.com");
            allowedWebsites.Add("staging.test.com");          
            allowedWebsites.Add("new-test.test.com");
            allowedWebsites.Add("test.com");
        }

        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
            if (!string.IsNullOrEmpty(_responseReason))
                actionContext.Response.ReasonPhrase = _responseReason;
        }

        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
           
            //checking against our custom table goes here
            if (!this.IsValidRequest(actionContext))
            {
                this.HandleUnauthorizedRequest(actionContext);
                _responseReason = "Access Denied";
                return false;
            }

            return true;
            //return base.IsAuthorized(actionContext);
        }

        public override void OnAuthorization(HttpActionContext actionContext)
        {
            //logic that will run before even authorizing the customer / user. if this logic fails
            // then the user checking against our custom database table will not processed.
            // you can skip this if you don't have such requirements and directly call
            base.OnAuthorization(actionContext);
          
        }

        public bool IsValidRequest(HttpActionContext actionContext)
        {

            //Check if a valid api page is requested
            /*var apiAttributes = GetApiAuthorizeAttributes(actionContext.ActionDescriptor);
            if (apiAttributes != null && apiAttributes.Any())
                return true;
            return false;*/
            string url = HttpContext.Current.Request.UrlReferrer.Host;
            bool isAllowed=allowedWebsites.Contains(url);
            return isAllowed;
        }
    }

Secondly, We have to implement it see how its done below
 
        [HttpGet]
        [ApiAuthorizeAttribute]
        [ActionName("GetData")]
        public List<DataMaster> GetData()
        {
             //your code goes here..
        }

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

In case of webforms we have to use global.asax file to achieve the same result. Create a function in global.asax for ex.

protected bool CheckRequest()
        {
            List<string> allowedWebsites = new List<string>();
            allowedWebsites.Add("test");
            allowedWebsites.Add("localhost");

            if (Request.Url != null)
            {
                string requestfrom = Request.Url.GetLeftPart(UriPartial.Authority);
                requestfrom = requestfrom.Substring(requestfrom.IndexOf('/') + 2);
                requestfrom = requestfrom.Substring(0,requestfrom.IndexOf(':'));

                bool isAllowed = allowedWebsites.Contains(requestfrom);
                return isAllowed;
            }
            else
            {
                return true;
            }
        }

Then in  Application_BeginRequest event in global .asax do this:

 protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            if (!CheckRequest())
            {
                Response.Write("<center><h1>A suspicious activity has been detected, Your IP has been recorded for further investigation.</h1></center>");
                Response.End();
            }
       }

Thats it!!
 

How to implement Captcha v3 in ASP.NET

 I was facing an issue of dom parsing in my website. I finally resolved it by using Google Captcha V3. Step 1: Get your keys from https:...