Amazon Ad

Tuesday, 24 October 2017

Calling a webservice from ESP900 using AT Commands

Hi Guys,
I was given a task to get data from a web API in Arduino, I struggled a lot as there is no specific documentation on it. Finally I achieved it, below is the code for the same.
#include <SoftwareSerial.h>

const byte rxPin = 2; // Wire this to Tx Pin of SIM900
const byte txPin = 3; // Wire this to Rx Pin of SIM900

SoftwareSerial SIM900(rxPin, txPin);
float temp;
int tempPin = 0;
void setup()
{
 SIM900.begin(9600);  
 Serial.begin(115200);  
 delay(1000);

SIM900.println("AT+CIPSHUT");
 delay(1000);
 printSerialData();

 SIM900.println("AT+CIPMUX=0");
 delay(2000);
 printSerialData();
 SIM900.println("AT+CGATT=1");
 delay(1000);
 printSerialData();
 //here my sim is of Airtel hence i have mentioned airtelgprs.com
 SIM900.println("AT+CSTT=\"airtelgprs.com\",\"\",\"\"");//setting the APN,2nd parameter empty works for all networks 
 delay(5000);
 printSerialData();
 SIM900.println();
 SIM900.println("AT+CIICR");
 delay(6000);
 printSerialData();
 SIM900.println("AT+CIFSR"); //init the HTTP request
 delay(2000); 
 printSerialData();
 SIM900.println("AT+CIPSTART=\"TCP\",\"echo.jsontest.com\",\"80\"");
 //SIM900.println("AT+CIPSTART=\"TCP\",\"test.in\",\"80\"");
 delay(2000);
 printSerialData();
 //String cmd="GET /test.php HTTP/1.1\r\nHost: test.in\r\nUser-Agent: SIM900_HTTP_CLIENT\r\nCache-Control: no-cache\r\nConnection: keep-alive\r\n\r\n";
 String cmd="GET /title/ipsum/content/blah HTTP/1.1\r\nHost: echo.jsontest.com\r\nUser-Agent: SIM900_HTTP_CLIENT\r\nCache-Control: no-cache\r\nConnection: keep-alive\r\n\r\n";
 delay(6000);
 SIM900.println("AT+CIPSEND="+String(cmd.length()));
 if(SIM900.find(">")){
  Serial.println("Sending Request..");
  SIM900.print(cmd);
  String c;
  while(SIM900.available()>0){
    c=SIM900.readString();
     Serial.println(c);
    };
    delay(10000);
   while(SIM900.available()>0){
     c=SIM900.readString();
     Serial.println(c);
   }
   delay(10000);
   while(SIM900.available()>0){
     c=SIM900.readString();
     Serial.println(c);
   }
   
  
 }

 delay(1000);
 SIM900.write(0x1A);
 delay(2000);
 printSerialData();
//sendtemp();
SIM900.println("AT+CIPCLOSE");
printSerialData();

SIM900.println("AT+CIPSHUT");
delay(1000);
printSerialData();
}

void loop()
{
}


void printSerialData()
{
 while(SIM900.available()!=0)
 Serial.write(SIM900.read());
}

void sendtemp()
{
  temp = analogRead(tempPin);
  temp = temp * 0.48828125;
  Serial.print("TEMPERATURE = ");
  Serial.print(temp);
  Serial.print("*C");
  Serial.println();
  delay(5000);
 SIM900.println(temp);
 delay(3000);
 printSerialData();
 delay(3000);
   printSerialData();
}
Thanks
Ritesh

Thursday, 31 August 2017

How to maintain session in asp.net

Dear All,

I faced a strange problem of maintaining session. We all know that we can maintain session and its timeout explicitly. Although we have this facility, but sometimes due to network disturbance the session gets expired and user has to come on the login or "yellow screen" again. Today, I am going to tell you how we can tackle this problem.

Step 1: I am taking one page which is dependent upon session. This page has a simple jquery code which calls a page through "HeartBeat" function. This function calls the page and sends the session in encrypted format which is again restored on the page. Thus it allows creation of session incase of any network fault or disturbance. Below is the code for the same.

in aspx html is

//your html code

//javascript code
<script src="Scripts/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
        var sess = '<%=EncryptSession(Session["LoginName"].ToString())%>';
        function HeartBeat() {
            $.post("SessionPage.aspx", { 'sess': sess }, function (data) {
            });
        }
        setInterval(HeartBeat, 5000);
    </script>

in .cs file

protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Session["SessionName"] = "testsession";
            }
            else
            {
                string sessionval = Session["SessionName"].ToString();
            }
        }

        public static string passwordEncrypt(string inText, string key)
        {
            byte[] bytesBuff = Encoding.Unicode.GetBytes(inText);
            using (Aes aes = Aes.Create())
            {
                Rfc2898DeriveBytes crypto = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                aes.Key = crypto.GetBytes(32);
                aes.IV = crypto.GetBytes(16);
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cStream.Write(bytesBuff, 0, bytesBuff.Length);
                        cStream.Close();
                    }
                    inText = Convert.ToBase64String(mStream.ToArray());
                }
            }
            return inText;
        }

      
        public static string EncryptSession(String s)
        {
            string enc = passwordEncrypt(s,"secretkeyword");
            return enc;
        }

Step 2: In another page named SessionPage.aspx, I have

In .cs file
 public partial class SessionPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String sess = Request.Params["sess"].ToString();
    //This line restores the breaked session again
            Session["SessionName"] = passwordDecrypt(sess,"secretkeyword");
            Response.Write("Any message if you want to be returned");
            Response.End();
        }

        public static string passwordDecrypt(string cryptTxt, string key)
        {
            cryptTxt = cryptTxt.Replace(" ", "+");
            byte[] bytesBuff = Convert.FromBase64String(cryptTxt);
            using (Aes aes = Aes.Create())
            {
                Rfc2898DeriveBytes crypto = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                aes.Key = crypto.GetBytes(32);
                aes.IV = crypto.GetBytes(16);
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cStream.Write(bytesBuff, 0, bytesBuff.Length);
                        cStream.Close();
                    }
                    cryptTxt = Encoding.Unicode.GetString(mStream.ToArray());
                }
            }
            return cryptTxt;
        }
    }

Thanks


Tuesday, 13 June 2017

How to read any json from API in C# Dictionary class object?

Hi Guys,

I was working on a project and I found a really difficult thing to read values of any json object.

Below is the code for the same, this code can extract any json object

Dictionary<string, string> jdata = new Dictionary<string, string>();
            JsonTextReader reader = new JsonTextReader(new StringReader(response.Content));
            string p = "", v = "";
            while (reader.Read())
            {
               //Here this 2 represents the nested level of your json.
              //ex. {"validated":{"token":"xxxxxx","level":"x"}}
                if (reader.Depth == 2)
                {
                    if (reader.TokenType == JsonToken.PropertyName)
                    {
                        p = reader.Value.ToString();
                    }
                    if (reader.TokenType == JsonToken.String)
                    {
                        v = reader.Value.ToString();
                    }
                    if (p!="" && v != "")
                    {
                        jdata.Add(p, v);
                        p = "";
                        v = "";
                    }
                }

            }

Hope it help you guys

Tuesday, 2 May 2017

How to upload a file with parameters to an external API

Hi Guys,

Today I am going to tell you how to upload a file with parameters to an external API. It is quite useful to send information like profile details of a user to an API. To achieve

this there are two ways which I found to implement the same. The first way is using "RestSharp" which is a library used in C# to call API. This is really simple and allows async

calls which is quite prevalant these days. The second way is to create a utility class and then call the post method to send the details with file stream.

  Below are the ways

1. Using RestClient

//First Way Using Nuget Package https://www.nuget.org/packages/RestSharp
//RestRequest for adding parameters
RestRequest request = new RestRequest("http://www.test.com/profiledata.aspx", Method.POST);
request.AddParameter("details", msgTextBox.Text);
request.AddFile("profilepic", Server.MapPath("Myfiles/")+"test.jpg");

//calling server with restClient
RestClient restClient = new RestClient();
restClient.ExecuteAsync(request, (response) =>
{
     if (response.StatusCode == HttpStatusCode.OK)
     {
          //POST successful
  
     }
     else
     {
          //error ocured during POST
     }
});


2. Using Utility Class

a. Create  a utility class as below
    public static class Upload
    {
        private const string FileFieldNameDefault = "fileContent";

        public static WebResponse PostFile
            (Uri requestUri, NameValueCollection postData, Stream fileData, string fileName,
             string fileContentType, string fileFieldName, CookieContainer cookies,
             NameValueCollection headers)
        {
            ServicePointManager.Expect100Continue = false;

            if (requestUri.Scheme == "https")
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

                ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, err) => true;
            }

            var webRequest = (HttpWebRequest)WebRequest.Create(requestUri);

            webRequest.Method = "POST";

            string boundary = "----------" + DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture);

            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

            string ctype;

            if (string.IsNullOrEmpty(fileContentType))
                fileContentType = TryGetContentType(fileName, out ctype)
                                    ? ctype
                                    : "application/octet-stream";

            fileFieldName = string.IsNullOrEmpty(fileFieldName) ? FileFieldNameDefault : fileFieldName;

            if (headers != null)
                foreach (string key in headers.AllKeys)
                {
                    var values = headers.GetValues(key);
                    if (values != null)
                        foreach (var value in values)
                            webRequest.Headers.Add(key, value);
                }

            if (cookies != null)
                webRequest.CookieContainer = cookies;

            var sbHeader = new StringBuilder();

            if (fileData != null)
            {
                var fileNameValue = string.Empty;

                if (string.IsNullOrEmpty(fileName) == false)
                    fileNameValue = string.Format(CultureInfo.InvariantCulture, "filename=\"{0}\"", Path.GetFileName(fileName));

                sbHeader
                    .AppendFormat("--{0}", boundary)
                    .AppendLine()
                    .AppendFormat("Content-Disposition: form-data; name=\"{0}\"; {1}", fileFieldName, fileNameValue)
                    .AppendLine()
                    .AppendFormat("Content-Type: {0}", fileContentType)
                    .AppendLine()
                    .AppendLine();
            }

            var sbFooter = new StringBuilder();
            sbFooter.AppendLine();

            if (postData != null)
                foreach (var key in postData.AllKeys)
                {
                    var values = postData.GetValues(key);
                    if (values != null)
                        foreach (var value in values)
                            sbFooter
                                .AppendFormat("--{0}", boundary)
                                .AppendLine()
                                .AppendFormat("Content-Disposition: form-data; name=\"{0}\"", key)
                                .AppendLine()
                                .AppendLine()
                                .Append(value)
                                .AppendLine();
                }

            sbFooter.AppendFormat("--{0}--\r\n", boundary);

            byte[] header = Encoding.UTF8.GetBytes(sbHeader.ToString());
            byte[] footer = Encoding.UTF8.GetBytes(sbFooter.ToString());
            long contentLength = header.Length + (fileData != null ? fileData.Length : 0) + footer.Length;

            webRequest.ContentLength = contentLength;

            using (var requestStream = webRequest.GetRequestStream())
            {
                requestStream.Write(header, 0, header.Length);

                if (fileData != null)
                {
                    var buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = fileData.Read(buffer, 0, buffer.Length)) != 0)
                        requestStream.Write(buffer, 0, bytesRead);
                }

                requestStream.Write(footer, 0, footer.Length);

                return webRequest.GetResponse();
            }
        }

        public static WebResponse PostFile
            (Uri requestUri, NameValueCollection postData, string fileName,
             string fileContentType, string fileFieldName, CookieContainer cookies,
             NameValueCollection headers)
        {
            using (var fileData = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                return PostFile(requestUri, postData, fileData,
                                fileName, fileContentType, fileFieldName, cookies,
                                headers);
        }

        private static bool TryGetContentType(string fileName, out string contentType)
        {
            try
            {
                RegistryKey key = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type");

                if (key != null)
                {
                    foreach (string keyName in from keyName in key.GetSubKeyNames()
                                               let subKey = key.OpenSubKey(keyName)
                                               where subKey != null
                                               let subKeyValue = (string)subKey.GetValue("Extension")
                                               where string.IsNullOrEmpty(subKeyValue) == false
                                               where string.Compare(Path.GetExtension(fileName), subKeyValue, StringComparison.OrdinalIgnoreCase) == 0
                                               select keyName)
                    {
                        contentType = keyName;
                        return true;
                    }
                }
            }
            catch
            {
                // fail silently
                // TODO: rethrow registry access denied errors
            }
            contentType = string.Empty;
            return false;
        }
    }

b. call the api using this example

//Thanks to http://stackoverflow.com/questions/7382786/uploading-a-file-using-application-x-www-form-urlencoded

            //Get the file name and save it in a stream
            string filename = Server.MapPath("~/ProfileFile/sampleCSV.csv");
            FileStream fileData = new FileStream(filename, FileMode.Open, FileAccess.Read);

            //Add the form values in the collection
            NameValueCollection frmValues = new NameValueCollection();
            frmValues.Add("method", "myUpload");
            frmValues.Add("userid", "xxxxxxxxx");
            frmValues.Add("password", "xxxxxxxx");
            frmValues.Add("xlsFile", filename);

            //Get the path of the target url
            Uri u=new Uri("http://www.test.com/GatewayAPI/rest");

            //Get the name value collection of headers
            //NameValueCollection headers = base.Request.Headers;
            NameValueCollection headers = null;

            //Post the data
            Upload.PostFile(u, frmValues, fileData, filename, "text/csv", "xlsFile", null, headers);


Thanks and Enjoy!!

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

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>

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