Monday, March 3, 2008

Post and receive XML to a URL

Here is a quick example of how to post and receive XML using HttpWebRequest:

//Some libraries that will be needed:
System.Net;
System.IO;
System.Xml;
System.Text;

public XmlDocument Send(string url, XmlDocument reqdoc)
{
//Setting up and posting request
  HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
  httpReq.Method = @"POST";
  httpReq.ContentType = @"text/xml";
  httpReq.Timeout = 600000; // 10 minutes (in milliseconds)
  httpReq.KeepAlive = false;

  Stream strm = httpReq.GetRequestStream();
  XmlDocument doc = new XmlDocument();
  doc.LoadXml("); //load xml
  doc.Save(strm); //strm will be the data to be sent
  strm.Close();

//Receiving result
  HttpWebResponse resp = (HttpWebResponse)httpReq.GetResponse();
  StreamReader srdr = new StreamReader(resp.GetResponseStream(),Encoding.GetEncoding("UTF-8"));
  string xmlstr = srdr.ReadToEnd();

  resp.Close();
  XmlDocument respdoc = new XmlDocument();
  try
  {
    StringBuilder sb = new StringBuilder(xmlstr);
    for(int c=0; c<sb.Length; c++)
    {
      if (sb[c]<'\x20')
      {
        sb[c]='\x20';
      }
    }

    respdoc.LoadXml(sb.ToString());
    string respXmlStr = respdoc.OuterXml;
  }
  catch(Exception e)
  {
    string msg = "Invalid XML response returned: " + e.Message;
    throw new Exception(msg,e);
  }

return respdoc;
}

Friday, January 11, 2008

C# @ string meaning.

And now for a little string manipulation:

string initXML = @"<?xml version=""1.0"" ?><request company=""gnc"" auth=""{0}"" unit=""{1}"" code=""{2}"" />";

initXML = String.Format(initXML, authCode, location, passCode);

The difference between a regular and verbatim string expression:
























Regular literal

Verbatim literal

Result

"Unplug1dot6"

@"Unplug1dot6"

Unplug1dot6

"Backslash: \\"

@"Backslash: \"

Backslash: \

"Quote: \""

@"Quote: """

Quote: "

"CRLF:\r\nPost CRLF"

@"CRLF:
Post CRLF"

CRLF:
Post CRLF

Monday, January 7, 2008

Use BCP within ASP.NET, C#

The Bulk Copy Program (BCP) is a command-line utility that ships with SQL Server. You can import / export large amounts of data in / out of SQL.

The BCP utility is accessed from the command prompt. Syntax below:
bcp {dbtable | query} {in | out | queryout | format} datafile
[-n native type] [-c character type]
[-S server name] [-U username]
[-P password] [-T trusted connection]

Remember: When using BCP, the terms are case-sensitive.
-n term specifies native SQL Server format.
-S term enables you to add the server/instance name.
-U term allows you to add the name of the login used to connect to SQL Server.
-P term lets you add the password of the -U switch.
-T term is for establishing a trusted connection to your SQL Server
-c term performs the operation using a character data type. This option does not prompt for each field; it uses char as the storage type, without prefixes and with \t (tab character) as the field separator and \r\n (newline character) as the row terminator
-t field_term specifies the field terminator. The default is \t (tab character). Use this parameter to override the default field terminator.
-r row_term specifies the row terminator. The default is \n (newline character). Use this parameter to override the default row terminator.

Example - C# in .cs file
Process bcp = new Process();
bcp.StartInfo.WorkingDirectory = WorkPath;
bcp.StartInfo.FileName = "bcp";
bcp.StartInfo.Arguments = "datatableName..storedprocedureToRun"
  + " in " //out
  + file.Name
  + @" -c -t ~ -r \n -DATABASE_NAME -Ucredential -Pcredential";
bcp.Start();
bcp.WaitForExit();

Wednesday, January 2, 2008

Verify a condition is true before posting asp:checkbox

If you want to verify a condition before the AutoPostBack event is fired for an asp:checkbox.

Set up the javascript function of what you want to verify:
<script language="javascript">
  function Reviewed_Click(o, e)
  {
    var oResponse = document.getElementById("Response");
    if (oResponse != null)
    {
      var reg = /\s+/g;
      var value = oResponse.innerText.toLowerCase().replace(reg, "");
      if (value == "yes"
      && !confirm("A question to ask?\nIf \"Yes\" click OK, otherwise click CANCEL."))
      {
        event.returnValue = false;
        return false;
      }
    }
  return true;
}
</script>

--------------------------------------------------------------
Now add the asp:checkbox...

<asp:checkbox id="Reviewed" Runat="server" AutoPostBack="True" Text="Information Reviewed" onclick="if (!Reviewed_Click(this, event)) return false;"></asp:checkbox>

Tuesday, November 13, 2007

network problem?

Some DOS commands that can help determine network problems:
ping, tracert, nslookup, netstat

C:\Documents and Settings\unplug1.6>ping tttx-inst1.com

Pinging tttx-inst1.com [182.11.110.111] with 32 bytes of data:

Request timed out.
Request timed out.
Request timed out.
Request timed out.

Ping statistics for 182.11.110.111:
Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),


C:\Documents and Settings\unplug1.6>tracert minn

Tracing route to minn.xx.com [182.11.110.111]
over a maximum of 30 hops:

1 1 ms <1 ms <1 ms 182.11.110.111
2 * * * Request timed out.
3 25 ms 23 ms 24 ms 192.168.16.160
4 24 ms 23 ms 25 ms minn.xx.com [182.11.110.111]

If there were a problem with an ip, you can specify which ip to use in tracert:
tracert -j 180.16.116.116 oh-01.xx.com

Tracing route to oh-01.xx.com [180.16.116.116]
over a maximum of 30 hops:

1 * * * Request timed out.
2 * * * Request timed out.

Trace complete.

C:\Documents and Settings\unplug1.6>nslookup 192.168.16.160
Server: oh-01.xx.com
Address: 182.16.160.16

*** oh-01.xx.com can't find 192.168.16.160: Non-existent domain

Friday, November 9, 2007

C# threading example

This is a simple, but handy multi-thread example. The two "foreach" sections at the end is where the hip happens. All process' will start at the same time and "Main" will not exit until all threads have been joined.

static void Main(string[] args)
{
  ArrayList threads = new ArrayList();

  try
  {
    if(args.Length > 0)
  {

  switch(args[0].ToUpper())
  {
    case "case1" :
    {
      case1Export case1 = new case1Export();
      Thread t1 = new Thread(new ThreadStart(case1.Start));
      threads.Add(t1);
      break;
    }
    case "case2" :
    {
      case2Export case2 = new case2Export();
      Thread t2 = new Thread(new ThreadStart(case2.Start));
      threads.Add(t2);
      break;
    }
    case "case3" :
    {
      case3Export case3 = new case3Export();
      Thread t3 = new Thread(new ThreadStart(case3.Start));
      threads.Add(t3);
      break;
    }
    default :
      break;
    }
  }

  foreach(Thread thread in threads)
  {
    thread.Start();
  }

  foreach(Thread joinThread in threads)
  {
    joinThread.Join();
  }
}

Thursday, October 11, 2007

Print page with simple script

It is simple to add print capabilities to a page. This would be useful if you are opening a page without menu options.

function printpage()
{
  window.print();
}


<input type="button" id="PrintBtn" name="PrintBtn" value="Print" class="Btn" onclick="printpage();">