Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, August 20, 2012

HttpWebRequest Time Out HTTPS Call

I recently had some HttpWebRequest calls begin to timeout without any error code returned. Just a timeout. I had not changed my code so I suspected that the site I was calling had changed something.

I found that I could call other HTTPS sites just fine, but this one in particular just timed out. I also tried to bypass all the certificate errors using the code:

ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, ssl) => true;

That did not work. I had the break-through moment when I found that if I change the call from HTTPS to HTTP, it worked. Although that was not going to be a fix!

After much searching, I found this post, I submitted the fix to the company and it resolved the problem.

The company had migrated the webserver which was an Apache Server. This small configuration item made some mismatch with the SSL certificate which blocked the HttpWebRequest calls I was making to the HTTPS urls.

Basically, Apache httpd.conf needed to be modified. Here is info from the post:

It had the server name like this: ServerName www.secure.mydomain.com

The certificate was registered to secure.mydomain.com, and the URL I was calling was also https://secure.mydomain.com/xxxx.html.

So simply changing the conf file to the following and restarting Apache did the trick:

ServerName secure.mydomain.com

The following would have also worked, most likely:
ServerName www.secure.mydomain.com
ServerAlias secure.mydomain.com

Hope this saves someone a major headache!

Monday, October 10, 2011

ClientScript.RegisterStartupScript Not Working?

ClientScript.RegisterStartupScript is used to call javascript in the .net code-behind. Once you learn this nice little trick, you think it is great, until one day years later on another page/project you try it again, but it does not work.

First, please check if the control/page you are trying to update contains an UpdatePanel. If so, keep reading.

This WON'T work with an UpdatePanel (in my experience). You will need to use: ScriptManager.RegisterStartupScript

For example:
ScriptManager.RegisterStartupScript(this, this.GetType(), "saving", "doneSaving();", true);

Also, in VS, it did not seem to recognize ScriptManager, when I right-clicked to "Resolve" it gave me no options. I am not sure why but I had to add "using System.Web.UI;" to my using clauses manually. Maybe that was some quirk with my page though...

Thursday, September 16, 2010

Tips: FedEx WebService for Rate Quotes C#/Asp.Net

After a long run of using the UPS quotes for online orders, we moved to FedEx. So that meant, I needed to update the ecommerce app to reflect our new shipper.

This task wasn't *too* hard since I had already written the UPS one about 4 years ago, but the FedEx one uses a WebService, for the UPS rates, I sent an HttpWebRequest. I don't know why they don't have webservice, maybe they do now...

Anyhow, hopefully these tips will help get you started on your way.

1. Get the WSDL. To do this, I downloaded the WSDL file from FedEx, this file includes the RateService_v9.wsdl file. I unzipped this file to my local webserver, then to my production webserver.

2. Create a reference to the WebService in Visual Studio. In my project, I right-clicked then selected Add Web Reference. Then I pointed the reference to my localhost (http://localhost/fedex/RateService_v9.wsdl) and gave it a name.

3. Requested a Test Key from FedEx that I plugged into the values Account Number, Meter Number, Key and Password.

4. Downloaded the FedEx example for getting Rate Service Quotes. Modified it to my liking. Here's a snippet:

RateRequest request = new RateRequest();

RateService service = new RateService(); // Initialize the service

request.WebAuthenticationDetail = new WebAuthenticationDetail();
request.WebAuthenticationDetail.UserCredential = new WebAuthenticationCredential();
request.WebAuthenticationDetail.UserCredential.Key = this._key; // Replace "XXX" with the Key
request.WebAuthenticationDetail.UserCredential.Password = this._password; // Replace "XXX" with the Password
//
request.ClientDetail = new ClientDetail();
request.ClientDetail.AccountNumber = this._accountNumber; // account number
request.ClientDetail.MeterNumber = this._meter; // meter number
//
request.TransactionDetail = new TransactionDetail();
request.TransactionDetail.CustomerTransactionId = "MY-RATE-REQUEST";
//
request.Version = new VersionId(); // automatically set from wsdl


if (packages != null && packages.Count > 0)
{
SetShipmentDetails(request, packages.Count);

int i = 0;
decimal totalWeight = 0.0M;

foreach (Package package in packages){
RequestedPackageLineItem rpli = new RequestedPackageLineItem();
Weight packageWeight = new Weight();
packageWeight.Value = (decimal)package.Weight;
packageWeight.Units = WeightUnits.LB;
rpli.Weight = packageWeight;

totalWeight += (decimal)package.Weight;

request.RequestedShipment.RequestedPackageLineItems[i] = rpli;
i++;
}

Weight weight = new Weight();
weight.Value = totalWeight;
weight.Units = WeightUnits.LB;
request.RequestedShipment.TotalWeight = weight;

}
.....

5. Once I was satisfied with the results, I requested a Production Key from FedEx then plugged in those values. I kept receiving a "Meter Number is missing or invalid".

This where I got tripped up. I had to change the URL being called in the app.config (that seems to have been created for me with properties in it). There is a url value that is referenced by the WebService.

However, even though I kept changing this value, it would continue to use the old value which was the test site, and of course, give me the same error - since my meter number was a production one not a test one.

Finally, I thought to open up the Properties - Settings.settings file. Right when I double-clicked the file to open it, the proprety inside there was updated with the new value I had in the app.config file.

I assume it was some sort of Visual Studio 2010 thing. It seems like it was supposed to auto-update but it didn't. Later, to be sure, I just updated it manually.

After that everything worked like a charm.

FYI:
(for SOAP Requests)
The test url is: https://wsbeta.fedex.com:443/web-services/rate
The production url is: https://gateway.fedex.com:443/web-services

Wednesday, February 24, 2010

Linq to Entity - Workaround Subquery?

For quite sometime, I been trying to figure out how to run a subquery in a Linq to Entity format. I’m kinda old school on querying, I really like to write straight SQL, not linq stuff. And to be honest, I'm not really sure what the right terminology is for some of it....so this post may not be the best in the world.

I’m not really even sure if this is a 'linq subquery' or not, but it is a way of getting nested data. It works for me so that is good.

To give the background on the data being retrieved, I'm getting a User that may have many User_Roster rows tied to it, each User_Roster row has a Book row tied to it, each Book row may have a User_Test row tied to it. So in this example, I need to get down to a certain a User_Test...oh my, hope that makes sense.

//method that uses linq/entity to get data from the database
public static User Get(int userId)
{
   using (FakeEntities eContext = new FakeEntities ())
    {
     User user = eContext.User
     .Include("User_Roster.Book.User_Test")
      .Where(i => .ID.Equals(userId))
      .FirstOrDefault();
    return user;
   }
}

//sample method that would be a consumer of the previous linq query
public string GetUser(string request)
{

//setup some hard coded values for examples sake
  int bookId = 1234;


  //call the method that used linq to query the database
  User item = Get(userId);

  //subquery the list to the exact roster i need
  //on the second line: m is for User_Roster, any variable name works
  User_Roster ur = item.User_Roster
    .Where(m => m.Book.ID.Equals(bookId))
    .FirstOrDefault();

  //if i found the roster i need, get the data i'm looking for
  if (ur != null)
   {
    User_Test test = ur.Book.User_Test .FirstOrDefault();
     if (test != null)
        ....
     }
}

i know there is probably a much smarter way of doing this, but I've not come across any good examples on the internet. so if this post helps you, let me know!! i'm curious.

Friday, February 5, 2010

Active Reports - Single report with multiple subreport

I have created a single Active Report with a single subreport before. Not too difficult. Mine looked like this in the code view:

//create an xml datasource for the subreport
DataDynamics.ActiveReports.DataSources.XMLDataSource xmlDS = new DataDynamics.ActiveReports.DataSources.XMLDataSource();

//load data
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(booksXml.ToString());
xmlDS.FileURL = null;
xmlDS.RecordsetPattern = "//book";
xmlDS.LoadXML(xDoc.InnerXml);

//set report datasource
BookDetail ed = new BookDetail();
this.subReport1.Report = ed;
this.subReport1.Report.DataSource = xmlDS;

Okay, so I thought when I added a second subreport with different data, I could just do the same, but I added an if statement that skipped doing anything with the subreport if the object was null.

And, THAT was a problem, it seems. When I would run the report, nothing showed up in the second subreport, even though it should have. Even when I put a breakpoint in the subreport, the Fetch method wasn't being hit - that was a clue.

Well, I guess, even if you have null data you still gotta do something with the subsequent subreport. So, I found an example on the AR support site that explained this to me - setting up a dummy object.

//create an xml datasource for the subreport
DataDynamics.ActiveReports.DataSources.XMLDataSource finalDS = new DataDynamics.ActiveReports.DataSources.XMLDataSource();

XElement BookXml = new XElement("Books");
BookXml.Add(Book.ToXml());

//load data
XmlDocument doc = new XmlDocument();
doc.LoadXml(booksXml.ToString());
finalDS.FileURL = null;
finalDS.RecordsetPattern = "//book";
finalDS.LoadXML(doc.InnerXml);


User_Book book = Book.GetItem(b.ID, m.ID);

if book != null)
{
//set subreport datasource
BookDetail fed = new BookDetail();
this.subReport2.Report = fed;
this.subReport2.Report.DataSource = finalDS;
}
else
{
BookDetail fed = new BookDetail();
fed.DetailData = false;
this.subReport2.Report = fed;
}

Hope this helps someone!