Amazon Ad

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!!
 

Wednesday, 23 December 2015

How to get printer serial number in c#

Dear All,

I was facing an issue to get Printer serial number, Here is how I was able to solve it using C#.

You can see the serial number of the model by going into "Device Manager" and then select the device and click on "Properties".
A dialog with name USB Printing Support Properties will appear, Click on the "Details" section and you will see lot of different properties of the device.
Look for the property "Device Instance Path" in case of printer. Here you will find a value like "USB\VID_XXXX&PID_XXXX\XXXXXXXXX" here "X" represents your device related numbers.

The problem was how to get these details from C#, I searched on google and found a link where I got an idea to create this utility.

Special Thanks to "Django Anonymous" for
http://stackoverflow.com/questions/20416888/to-get-provider-from-managementobjectsearcher-win32-pnpentity

The above link has a different question, But somehow I thought to use the details to build my own utility. However, I was not able to get the device name associated with the device serial number and my comboboxlist produces only serial number not the device name. I am working on it, Hopefully will give you a solution of the same.

Here is my own code in c#

    public class Device
    {
        public string DeviceName { get; set; }
        public string SerialNumber { get; set; }
    }

 public class ComboboxItem
    {
        public string Text { get; set; }
        public object Value { get; set; }

        public override string ToString()
        {
            return Text;
        }
    }

public List<Device> GetDeviceList()
{
    List<Device> devicelist = new List<Device>();
using (ManagementObjectSearcher searchernew = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEntity WHERE Caption Like '%print%'"))
                {
                    foreach (ManagementObject mgmt in searchernew.Get()){
                        foreach (PropertyData property in mgmt.Properties){
                            if (property.Name == "DeviceID" && property.Value.ToString().Contains("USB\\VID_")){
                                string val = property.Value.ToString();
                                if (val.IndexOf('\\') != -1){
                                    val = val.Substring(val.LastIndexOf('\\') + 1);
                                    devicelist.Add(new Device() { SerialNumber = val, DeviceName = val });
                                }
                            }
                        }
                    }
                }
return devicelist;
}

private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                List<Device> lst = GetDeviceList();
                foreach (Device a in lst)
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = a.DeviceName;
                    item.Value = a.SerialNumber;
                    cmbPrinter.Items.Add(item);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
}


Thanks

Friday, 18 September 2015

How to upload file from jquery ajax

Dear All,

Today I am going to tell you how to upload a file from jquery ajax. First of all you need is a jquery reference and a .cs file as I am doing it in ASP.net.

Step 1 : Create a form, Here I have created a form and included a file upload html <input type="file" id="fileUpload"> and simple button with name "btnUploadFile".

Step 2: Write the javascript code to upload the file

<script type="text/javascript">
            $(document).ready(function () {
                $('#btnUploadFile').on('click', function () {
                    var files = $("#fileUpload").get(0).files;

                    var data = new FormData();
                    data.append('data', files[0]);

                    // Make Ajax request with the contentType = false, and processData = false
                    var ajaxRequest = $.ajax({
                        type: "POST",
                        url: "SendFile.aspx/uploadfile",
                        contentType: false,
                        processData: false,
                        data: data,
                        success: function (data) {
                            alert('File uploaded Successfully');
                        },
                        error: function (xhr, ajaxoptions, thrownerror) {
                            alert(xhr.status);
                            alert(thrownerror);
                        },
                        asyn:false
                        //data: data
                    });
                   
                    ajaxRequest.done(function (xhr, textStatus) {
                        // Do other operation
                    });
                });
            });
</script>

Monday, 1 June 2015

Call SOAP Web Service From MS SQL

Hi Guys,

I was given a task to call a SOAP web service from MS SQL. There few steps which are required before writing the T-SQL for invoking web service.


Step 1:

Give rights to invoke OA(Object Access) for SOAP. Below is how to do it

sp_configure 'show advanced options', 1
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1
GO
RECONFIGURE;
GO
sp_configure 'show advanced options', 1
GO
RECONFIGURE;
GO

Step 2:

TSQL stored procedure which calls the web service. I Assume that you have a web service with WebMethod "GetProgram" with one Parameter "Code". I am also assuming that its a POST method. Below is the strored procedure:

-- ================================================
-- Template generated from Template Explorer using:
-- Create Procedure (New Menu).SQL
--
-- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--
-- This block of comments will not be included in
-- the definition of the procedure.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Ritesh Tandon>
-- Create date: <01-Jun-2015>
-- Description:    <Invoke Web Service From SQL Stored Procedure>
-- =============================================
Alter PROCEDURE pCallWebServiceGet
    -- Add the parameters for the stored procedure here
    @ServicePath varchar(500)='',
    @RequestBody varchar(1000)='<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
   <soapenv:Header/>
   <soapenv:Body>
      <GetProgram xmlns="http://tempuri.org/">
      <Code>1513100000</Code>
    </GetProgram>
   </soapenv:Body>
</soapenv:Envelope>'
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    Declare @Object as Int;
    Declare @ResponseText as Varchar(8000);
    Declare @RequestLength as int

    set @RequestLength=Len(@RequestBody)

    --Code Snippet
    Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
    Exec sp_OAMethod @Object, 'open', NULL, 'POST','http://www.yourwebsite.com/service.asmx?op=GetProgram','false'
    EXEC sp_OAMethod @Object, 'setRequestHeader', NULL, 'Content-Type', 'text/xml;charset=UTF-8'
    --EXEC sp_OAMethod @Object, 'setRequestHeader', NULL, 'SOAPAction', 'POST'
    --EXEC sp_OAMethod @Object, 'setRequestHeader', NULL, 'Content-Length', @RequestLength
    Exec sp_OAMethod @Object, 'send', NULL, @RequestBody
    Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT

Wednesday, 29 April 2015

Application_Error Not Invoked From Global.asax

Hi ,

If you have implemented Application_Error event in Global.asax and its not invoked, after all the hard work, You need to make sure to do the following

1. Sometimes in the web.config the CustomError property is set to Off. In this case set it to On.

2. Make sure your Global.asax's bin file (app_global.dll) exists and the modified date is same as your Global.asax file.

3. If you have implemented RadCompression, It will not invoke the Application_Error event until you add the following in your web.config file

<telerik.web.ui>  
    <radCompression>   
        <excludeHandlers>
            <add handlerPath="Global.asax" matchExact="true"/>
        </excludeHandlers>
    </radCompression>
</telerik.web.ui>

4. Still if you are not able to implement it, Use HttpModule to trap an error.

These are some of the common causes of not invoking the error event.

Thanks

Tuesday, 28 April 2015

405 Method not found in ASP.NET Web API and Angular.js

Hi,

I was facing a strange problem when implementing web api in asp.net with Angular.js. The web api method was absolutely fine and was working locally. But when it was published on the development server, It gave the error 405 method not found. I added the CORS in web.api, in web.config and in the controller by enabling cors (Adding the line [EnableCors("*", "*", "*")] before the controller class). But no use it was still giving me the same message with OPTIONS method not found.

Finally, I resolved it by adding the config section in my angular code where i was creating my module. Below is the code. After adding this it resolved all the issues i was facing.

Thursday, 16 April 2015

How make faster asp.net websites in ASP.NET 4.5 with EF 6

Hi Guys,

I was able to successfully create a responsive and very fast website with EF6 and ASP.NET 4.5. Here is how i was able to do it successfully.

1. Create a basepage which all the webforms inherits and add the following code in the constructor of the basepage

a. you need to install a nuget package

PM> Install-Package EFInteractiveViews

b. Then add below code in your constructor of basepage class
public BasePage()
        {
            try
            {
                using (var ctx = new LPUOnlineEntities())
                {
                    InteractiveViews.SetViewCacheFactory(ctx, new SqlServerViewCacheFactory

(ctx.Database.Connection.ConnectionString));
                }
            }
            catch (Exception ex)
            {

            }
        }


2. Enable ViewState Compression

a. Create two methods in your basepage class
protected override object LoadPageStateFromPersistenceMedium()
        {
            string viewState = Request.Form["__VSTATE"];
            byte[] bytes = Convert.FromBase64String(viewState);
            bytes = Compressor.Decompress(bytes);
            LosFormatter formatter = new LosFormatter();
            return formatter.Deserialize(Convert.ToBase64String(bytes));
        }

        protected override void SavePageStateToPersistenceMedium(object viewState)
        {
            LosFormatter formatter = new LosFormatter();
            StringWriter writer = new StringWriter();
            formatter.Serialize(writer, viewState);
            string viewStateString = writer.ToString();
            byte[] bytes = Convert.FromBase64String(viewStateString);
            bytes = Compressor.Compress(bytes);
            //ClientScript.RegisterHiddenField("__VSTATE", Convert.ToBase64String(bytes));
            ScriptManager.RegisterHiddenField(this, "__VSTATE", Convert.ToBase64String(bytes));
        }

b. A class which compresses the data

using System.IO;
using System.IO.Compression;

public static class Compressor
{

    public static byte[] Compress(byte[] data)
    {
        MemoryStream output = new MemoryStream();
        GZipStream gzip = new GZipStream(output,
                          CompressionMode.Compress, true);
        gzip.Write(data, 0, data.Length);
        gzip.Close();
        return output.ToArray();
    }

    public static byte[] Decompress(byte[] data)
    {
        MemoryStream input = new MemoryStream();
        input.Write(data, 0, data.Length);
        input.Position = 0;
        GZipStream gzip = new GZipStream(input,
                          CompressionMode.Decompress, true);
        MemoryStream output = new MemoryStream();
        byte[] buff = new byte[64];
        int read = -1;
        read = gzip.Read(buff, 0, buff.Length);
        while (read > 0)
        {
            output.Write(buff, 0, read);
            read = gzip.Read(buff, 0, buff.Length);
        }
        gzip.Close();
        return output.ToArray();
    }
}

Monday, 16 February 2015

Saving object/array object in LocalStorage in ASP.NET Bootstrap

Hi Guys,

I was checking out a small code in Javascript which adds a javascript class object/JSON object in a

localstorage. The localstorage saves the array object and displays it in the bootstrap table/grid.

You need to have knowledge of JSON and object oriented programming in Javascript. However comments

have been added which can help you out.

Following is the HTML and Javascript content

<!DOCTYPE html>

<html lang="en">
  <head>
    <meta charset="utf-8">
   
    <title>Enter Exam Details</title>

    <!-- include Bootstrap CSS for layout -->
    <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-

combined.min.css" rel="stylesheet">
  </head>
 
  <body>
    <div class="container">
      <h1>Add your past exam details</h1>
     
      <form method="post" class="form-horizontal">
        <fieldset>
          <legend>Add Exams</legend> 
          <div class="control-group">
            <label class="control-label" for="type">Type of enquiry</label>
            <div class="controls">
              <select name="type" id="type">
                <option value="">Please select</option>
                <option value="general">General</option>
                <option value="sales">Sales</option>
                <option value="support">Support</option>
              </select>
            </div>
          </div>
     

Sunday, 15 February 2015

Entity Framework unable to retrieve metadata for

Hi Guys,

I was facing a problem while implementing a custom class in the Entity Framework. I faced the following error

"unable to retrieve metadata for XXXX.XXXX"

The error was coming due to the fact that EF context uses metadata for Generting EF tt models. Whereas a custom class is not using tt models and therefore it gave this error. However i couldn't find the solution but i managed to do it by creating a new connectionstring which was not having metadata.

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:...