Amazon Ad

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