Amazon Ad

Thursday, 1 February 2018

How to read soap envelope in c#

Hi guys,

I was given a task to read soap envelope and do some operations on it. Here is how I achieved it      

        [HttpPost]
        [ActionName("CDDService")]
        [Route("api/test/CDDService")]
        public void CDDService()
        {
            var b = RequestBody(HttpContext.Current.Request.InputStream);

            XmlDocument soapEnvelop = new XmlDocument();
            soapEnvelop.LoadXml(b);

            XmlNamespaceManager nsmgr = new XmlNamespaceManager(soapEnvelop.NameTable);
            nsmgr.AddNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
            nsmgr.AddNamespace("sch", "http://ws.test.com/rti/cdd/schema");
            nsmgr.AddNamespace("wsse", "http://dtest.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            nsmgr.AddNamespace("wsu", "http://dtest.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");

            string Username = soapEnvelop.DocumentElement.SelectSingleNode("//wsse:Username",nsmgr).InnerText;
            string password = soapEnvelop.DocumentElement.SelectSingleNode("//wsse:Password",nsmgr).InnerText;

            var cddRequest = soapEnvelop.DocumentElement.SelectSingleNode("//sch:cddRequest",nsmgr);

            string clientCandidateID = cddRequest.Attributes["clientCandidateID"].Value;
            string clientID = cddRequest.Attributes["clientID"].Value;

            string firstname = cddRequest.SelectSingleNode("candidateName/firstName").InnerText;
            string lastname = cddRequest.SelectSingleNode("candidateName/lastName").InnerText;

            string email = cddRequest.SelectSingleNode("webAccountInfo/email").InnerText;

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "text/xml;charset=utf-8";
            HttpContext.Current.Response.Write(@"<pingResponse><status>Success</status></pingResponse>");
            HttpContext.Current.Response.End();
        }

        private static string RequestBody(Stream InputStream)
        {
            var bodyStream = new StreamReader(InputStream);
            bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
            var bodyText = bodyStream.ReadToEnd();
            return bodyText;
        }

Hope it helps!

Thanks
Ritesh Tandon

Saturday, 27 January 2018

How to solve net::ERR_CONTENT_DECODING_FAILED in ASP.NET

Guys,

It took me three days to solve one simple problem which was caused due to ajax post form posting data to .asmx service webmethod. This error usually happens when there is an implementation of dynamic/stati compression in the project for ex. gzip or deflate compression. The code which worked is given below:

$.ajax({
                    url: 'test.asmx',
                    dataType:"json",
                    contentType: false,
                    processData: false,
                    type: 'POST',
                    data: formData,
                    success: function (data) {
                        console.log(data);
                        data = data.d;
                        console.log('inside success response Text is '+this.responseText);
                        console.log(data);
                        console.log('Success');
                        checkData(this.responseText);
                    },
                    error: function (a, b, c) { console.log('Error');checkData(a.responseText); console.log(a); console.log(b); console.log(c); }
                });

Wednesday, 13 December 2017

Upload multiple files using progressbars in HTML5 Javscript with webservices


Hi Guys,

Today I will tell you how to upload multiple files using progressbars and  webserivces. Below is the code I have used.


<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Courses</title>
    <script src="js/jquery-1.11.3.js"></script>
    <link href="css/bootstrap.css" rel="stylesheet" />
    <style>
        .pt10 {
            padding-top: 10px;
        }

        .pb10 {
            padding-bottom: 10px;
        }

        .fileinput-button input {
            position: absolute;
            top: 0;
            right: 0;
            margin: 0;
            opacity: 0;
            -ms-filter: 'alpha(opacity=0)';
            direction: ltr;
            width: 150px;
            cursor: pointer;
        }

        .fileinput-button {
            position: relative;
        }

        progress::-moz-progress-bar {
            background: green;
        }

        progress::-webkit-progress-value {
            background: green;
        }

        progress {
            color: green;
        }
    </style>
    <script src="js/jquery-1.11.3.js"></script>
</head>
<body>
    <div class="container">
        <div>
            <h4>Course Code : <span id="coursecode"></span></h4>
            <h4>TotalMarks : <span id="totalmarks"></span></h4>
            <h4>Term : <span id="term"></span></h4>
            <hr />
        </div>
        <div class="col-md-12 col-sd-12 col-xs-12">
            <div id="testimg" class="col-md-6 col-sd-6 col-sm-12 col-xs-12">
            </div>
            <div id="submitform" class="col-md-6 col-sd-6 col-sm-12 col-xs-12">
                <div class="pt10">
                    <input type="hidden" id="assignmentid" />
                    <input type="hidden" id="assignmentnumber" />
                    <input type="hidden" id="regnumber" />
                    <input type="hidden" id="code" />
                    <!--<div class="btn btn-success fileinput-button">
                    <i class="glyphicon glyphicon-plus"></i>
                    <input type="file" name="images" id="images" multiple>
                    <span>Add files...</span>
                </div>-->
                    <div class="btn btn-success fileinput-button pt10">
                        <i class="glyphicon glyphicon-plus"></i>
                        <input type="file" name="images" id="images" accept=".jpg, .png, .jpeg, .gif, .bmp, .tif, .tiff|images/*" multiple />
                        <span>Select files...</span>
                    </div>
                    <div>
                        <h5>To select multiple files, hold down the CTRL or SHIFT key while selecting files.</h5>
                    </div>
                    <div class="files pt10">
                    </div>
                    <!--<button class="btn btn-info" onclick="submitform();">Submit</button>-->
                </div>
            </div>
        </div>
    </div>

    <script type="text/javascript">
        var spath = 'http://localhost:121231/testwebservice.svc';
        var s1path = 'http://localhost:64383/api/upload';
        var regno = '12X2323232';

        $(document).ready(function () {
            var coursecode = getParameterByName("code");
            loadassignment(coursecode);
        });

        function loadassignment(coursecode) {
            $.get(spath + '/GetOnlineAssignment/' + coursecode, function (data) {

                $("#assignmentid").val(data[0].ID);
                $("#assignmentnumber").val(data[0].AssignmentNumber);
                $("#regnumber").val(regno);
                $("#code").val(data[0].CourseCode);
                $("#coursecode").text(data[0].CourseCode);
                $("#totalmarks").text(data[0].TotalMarks);
                $("#term").text(data[0].TermId);
                def(data[0].ID);
            });

        }

        //load assignment picture
        function def(id) {
            var html = "";
            var Obj = new Object();
            Obj.Id = id;

            $.ajax({
                type: "Get",
                contentType: "application/json; charset=utf-8",
                url: s1path + "/GetAssignmentQuestion",
                dataType: "json",
                data: Obj,
                success: function (data1) {
                    console.log(data1);
                    if (data1.d == undefined) {
                    }
                    else {
                        data1 = data1.d;
                    }
                    if (data1.length > 0) {
                        if (data1[0].Message == "No Record Found") {
                        }
                        else {
                            html += "<img class='img-responsive' src='" + data1[0].File + "'>"
                        }
                        $("#testimg").html(html);
                    }
                    else {
                    }
                },
                error: function (result) {

                }
            });
        }

        function getParameterByName(name, url) {
            if (!url) url = window.location.href;
            name = name.replace(/[\[\]]/g, "\\$&");
            var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                results = regex.exec(url);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, " "));
        }

        $('#images').on('change', function () {
            var images = document.getElementById('images');
            var length = images.files.length;
            for (i = 0; i < length; i++) {
                //
                if (images.files[i].size < 2048000) {
                    send(i);
                } else {
                    //
                    alert('The file length exceeded 2MB size.');
                }
            }
        });

        var counter = 0, processed = false, pg = 0;
        function send(i) {

            var images = document.getElementById('images');
            var length = images.files.length;
            var image = images.files[i];

            var formData = new FormData();
            formData.append('QuestionId', '1');
            formData.append('AnswerNo', '1');
            formData.append('EntryBy', '2103242342');
            formData.append('coursecode', 'DEG101');
            formData.append('image', image);

            var h = '<div id="r' + (counter) + '"><progress id="progressBar' + (counter) + '" value="0" max="100" style="width: 300px"></progress><h5 id="status' + (counter) + '"></h5><p id="loaded_n_total' + (counter) + '"></p></div>';
            $(".files").append(h);
            counter++;

            var xhr = new window.XMLHttpRequest();
            xhr.open("POST", s1path + "/SaveAssignment");

            //Upload progress
            xhr.upload.addEventListener("progress", function (evt) {
                if (evt.lengthComputable) {

                    if (!processed) {
                        var prog = Math.ceil(evt.loaded / evt.total) * 100;
                        $("#loaded_n_total" + i).html("Uplodaed " + evt.loaded + " bytes of " + evt.total);
                        $("#progressBar" + i).val(Math.round(prog));
                        $("#status" + i).html(images.files[i].name + " <b>" + Math.round(prog) + "</b> % uploaded");

                        //Do something with upload progress
                        console.log(prog + ' % completed.');
                        console.log('loaded ' + evt.loaded + ' of ' + evt.total);

                    } else {
                        var prog = Math.ceil(evt.loaded / evt.total) * 100;
                        $("#loaded_n_total" + (pg)).html("Uplodaed " + evt.loaded + " bytes of " + evt.total);
                        $("#progressBar" + (pg)).val(Math.round(prog));
                        $("#status" + (pg)).html(images.files[i].name + " <b>" + Math.round(prog) + "</b> % uploaded");
                    }

                }
            }, false);

            //after complete make things ok
            xhr.upload.addEventListener("loadend", function () {
                $("#status" + pg).html("<strong class='text-success'>" + images.files[i].name + " <i class='glyphicon glyphicon-ok'></i></strong>");
                $("#loaded_n_total" + pg).html("Uplodaed Successfully");
                $("#progressBar" + (pg)).val(100);
                if ((i + 1) == length) {
                    processed = true;
                }
                pg++;
            }, false);
            xhr.send(formData);
            return xhr;
        }

    </script>
</body>
</html>

Thanks
Ritesh

Tuesday, 28 November 2017

Regex to find all catch blocks in Visual Studio



Find all catch blocks

catch\s*\(\w*\s*(.*\w)*\)\s*\b*\n*\{

Replace with
$&\n\t\t\tlogerror($1);


Here logerror(); is the method which captures the logs. The method errorlog can be called.

Wednesday, 15 November 2017

Create custom error logs in your ASP.NET application including try/catch errors

Dear All,


Guys I finally managed to catch all the errors coming in the try/catch or outside this block using global.asax file. Below is the code to be done


Create a class named UErrorLog

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace test
{
    public class UException
    {
        public string UserId { get; set; }
        public string ProjectName { get; set; }
        public string PageName { get; set; }
        public string LineNumber { get; set; }
        public string ErrorMessage { get; set; }
        public string ErrorDescription { get; set; }
        public string IpAddress { get; set; }
        public string LogDateTime { get; set; }
        public int? MenuId { get; set; }
    }
    public class ContextInfo
    {
        public Exception ex { get; set; }
        public List<string> Session { get; set; }

    }
   
    public class UErrorLog : Exception
    {
        public UErrorLog()
        {

        }

        public UErrorLog(Exception ex)
        {
            logerror(ex);
        }

        int line = 0;
        string filename = "";

        public void logerror(Exception ex)
        {
            //System.Exception ex = System.Web.HttpContext.Current.Server.GetLastError();
            if (ex != null)
            {
                //This is included in try/catch to handle the case when the database goes down.
                try
                {
                    var stack = new System.Diagnostics.StackTrace(true);
                    //Get the details
                    //System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(ex, true);
                    System.Diagnostics.StackFrame frame =new System.Diagnostics.StackFrame();

                    foreach (System.Diagnostics.StackFrame f in stack.GetFrames())
                    {
                        if (f.GetFileName() != null && f.GetFileLineNumber() > 0)
                        {
                            frame = f;
                        }
                    }

                    if (frame != null)
                    {
                        //if (line != frame.GetFileLineNumber() && filename != frame.GetFileName().Substring(frame.GetFileName().LastIndexOf("\\") + 1))
                        //{
                            line = frame.GetFileLineNumber();
                            filename = frame.GetFileName().Substring(frame.GetFileName().LastIndexOf("\\") + 1);

                            if (!filename.Contains("Global.asax"))
                            {

                                UException err = new UException();
                                //Log this error in your database
                                if (System.Web.HttpContext.Current.Session["LoginName"] != null)
                                {
                                    err.UserId = System.Web.HttpContext.Current.Session["LoginName"].ToString();
                                }
                                else
                                {
                                    err.UserId = "";//Session["LoginName"].ToString();
                                }
                                err.ProjectName = "YourProjectName";
                                //err.PageName = this.GetType().BaseType.Name;

                                //Get the page name and line number
                                err.PageName = filename;
                                err.LineNumber = line.ToString();

                                //Error Messages
                                err.ErrorMessage = ex.Message;
                                if (ex.InnerException != null)
                                    err.ErrorDescription = ex.InnerException.ToString() != "" ? ex.InnerException.ToString() : "";
                                else
                                    err.ErrorDescription = "";

                                //Get IP Address
                                string ip = "";
                                ip = GetIPAddress();
                                if (ip == "" || ip == "::1")
                                {
                                    ip = LocalIPAddress();
                                }
                                err.IpAddress = ip;

                                err.LogDateTime = DateTime.Now.ToString("dd MMM yyyy hh:mm tt");

                                string str = "pInsertErrorLog";
                                SqlConnection con = new SqlConnection("data source=.;user id=sa;password=123;database=test");
                                if (con.State == System.Data.ConnectionState.Closed)
                                    con.Open();

                                SqlCommand cmd = new SqlCommand(str, con);
                                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                                cmd.Parameters.AddWithValue("@UserId", err.UserId);
                                cmd.Parameters.AddWithValue("@ProjectName", err.ProjectName);
                                cmd.Parameters.AddWithValue("@PageName", err.PageName);
                                cmd.Parameters.AddWithValue("@LineNumber", err.LineNumber);
                                cmd.Parameters.AddWithValue("@ErrorMessage", err.ErrorMessage);
                                cmd.Parameters.AddWithValue("@ErrorDescription", err.ErrorDescription);
                                cmd.Parameters.AddWithValue("@IpAddress", err.IpAddress);
                                cmd.Parameters.AddWithValue("@LogDateTime", err.LogDateTime);
                                cmd.Parameters.AddWithValue("@MenuId", err.MenuId);
                                cmd.ExecuteNonQuery();
                            }

                        //}//if (line != frame.GetFileLineNumber() && filename != frame.GetFileName().Substring(frame.GetFileName().LastIndexOf("\\") + 1))

                    }//if (frame != null)

                }
                catch (Exception e)
                {

                }
            }
        }

        //For ISP (Internet Service Provider) IP Address
        public static string GetIPAddress()
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            string sIPAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(sIPAddress))
            {
                return context.Request.ServerVariables["REMOTE_ADDR"];
            }
            else
            {
                string[] ipArray = sIPAddress.Split(new Char[] { ',' });
                return ipArray[0];
            }
        }


        //For LAN (Local Area Network) IP Address
        public string LocalIPAddress()
        {
            IPHostEntry host;
            string localIP = "";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                    break;
                }
            }
            return localIP;
        }

    }
}

In the global.asax file add the following code

protected void Application_Start(object sender, EventArgs e)
        {
            bool _insideFirstChanceExceptionHandler = false;
            AppDomain.CurrentDomain.FirstChanceException += (object source, FirstChanceExceptionEventArgs e1) =>
            {
                if (_insideFirstChanceExceptionHandler)
                {
                    // Prevent recursion if an exception is thrown inside this method
                    return;
                }
                try
                {
                    _insideFirstChanceExceptionHandler = true;
                    new UErrorLog().logerror(e1.Exception);
                    //throw new UErrorLog(e1.Exception);
                }
                catch
                {
                    // You have to catch all exceptions inside this method
                    _insideFirstChanceExceptionHandler = true;
                }
                finally
                {
                    _insideFirstChanceExceptionHandler = false;
                }
                //new UErrorLog().logerror(e1.Exception);
            };

        }


Table is


CREATE TABLE [dbo].[ErrorLog](
    [LogId] [int] IDENTITY(1,1) NOT NULL,
    [UserId] [varchar](50) NULL,
    [ProjectName] [varchar](150) NULL,
    [PageName] [varchar](150) NULL,
    [ErrorMessage] [varchar](max) NULL,
    [ErrorDescription] [varchar](max) NULL,
    [IpAddress] [varchar](20) NULL,
    [LogDateTime] [datetime] NULL,
    [MenuId] [int] NULL,
 CONSTRAINT [PK_ErrorLog] PRIMARY KEY CLUSTERED
(
    [LogId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO


-- =============================================
-- Author:        <Ritesh Tandon>
-- Create date: <Create Date,,>
-- Description:    <Record Error Log>
-- =============================================
CREATE PROCEDURE [dbo].[pInsertErrorLog]
    -- Add the parameters for the stored procedure here
    @UserId varchar(50),
    @ProjectName varchar(100),
    @PageName varchar(100),
    @ErrorMessage varchar(max),
    @ErrorDescription varchar(max),
    @IpAddress varchar(20),
    @LogDateTime varchar(150),
    @MenuId int=null
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    INSERT INTO ErrorLog(UserId,ProjectName,PageName,ErrorMessage,ErrorDescription,IpAddress,LogDateTime,MenuId)
    VALUES(@UserId,@ProjectName,@PageName,@ErrorMessage,@ErrorDescription,@IpAddress,@LogDateTime,@MenuId)
END

GO

Another method is to find and replace all catch block with your method name. See the below regular expression which can be easily used in visual studio find and replace with regex option.

Find all catch blocks

catch\s*\(\w*\s*(.*\w)*\)\s*\b*\n*\{

Replace with
$&\n\t\t\tlogerror($1);


Here logerror(); is the method which captures the logs. The method errorlog can be called.

And friends that it, you will get your own logs.

Monday, 6 November 2017

Validate that user has logged in once at a time

Dear All,

I was given a task to validate that the user has logged in once at a time, i.e the user once logged in cannot login from same or other place until logs out.

Below is the code for the events on my Login Page:

//create object of global.asax class
Global obj = new Global();
 protected void Login_Click(object sender, EventArgs e)
        {  
            bool result=obj.GenerateSession(TextBox1.Text,true);
            if(result){
                Label1.Text = "Logged in Sucessfully";
            }
            else
            {
                Label1.Text = "You are already logged in";
            }
        }

        protected void Logout_Click(object sender, EventArgs e)
        {
            bool result=obj.DeleteValue(TextBox1.Text);
            if (result)
            {
                Label1.Text = "Logged Out Sucessfully";
            }
            else
            {
                Label1.Text = "You are already logged Out";
            }
        }


Below is the code of Global.asax file:

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

How to read soap envelope in c#

Hi guys, I was given a task to read soap envelope and do some operations on it. Here is how I achieved it               [HttpPost]    ...