My company is currently looking into bringing a new piece of third party software in for online ordering. The software does not handle pricing so they are requesting the pricing information from a web service. Their software is passing an XML file as a parameter, and expecting an XML file as a response. I would think that returning an XML file would be pretty straight forward, but I cannot think of a way to receive an XML file as a parameter. Has anyone done this, or am I missing something really obvious?
Possibly obvious - an XML "file" can be represented by a String.
Edit to Answer Comment
The string is the XML file, so all you need to do is deserialize it into the classes created from the XSD:
Dim xmlString As String = GetStringFromVendor()
Dim xmlClass As New CoolXMLClass
Dim serializer As New Xml.Serialization.XmlSerializer(GetType(CoolXMLClass))
xmlClass = serializer.Deserialize(New StringReader(xmlString))
Related
I want to access to raw query parameters in ASP.NET Core 2.0
Currently HttpRequest.Query provides access to strings decoded from url encoded encoding, but it decodes it incorrectly.
How can I access to raw parameters instead of parsing full query string by hands?
Ok, it seems I overcome this issue.
So, how I did it?
I used QueryFeature class from asp.net core source and replaced call to QueryHelpers.ParseNullableQuery (you can find it here) with slightly changed implementation of this helper without call to Uri.UnescapeDataString to parameter value.
Then created middleware class that sets my custom QueryFeature for HttpContext:
context.Features.Set<IQueryFeature>(new MyQueryFeature(context.Features));
and used it during app configure.
Don't forget that after this all your parameters will stay url encoded if they were.
I have been asked to change a legacy .asmx web service and there are a few issues I would appreciate some guidance on.
The web methods are decorated like this:
[WebMethod(EnableSession = true), ScriptMethod(ResponseFormat = ResponseFormat.Json)]
In my particular method, I am returning data from a database, which I return as a list of to of objects using JSON.
I noticed that the JSON is still returned without the: ScriptMethod(ResponseFormat = ResponseFormat.Json part.
In that case:
can I safely remove this from here?
if it still works, does that mean it will be configured elsewhere in a base class or config file perhaps?
What is the purpose of the (EnableSession = true) and is it required if the service does not update the data and the read data is rarely changed?
Sorry for the basic rather vague questions but I've not worked with .asmx web services before. Can someone point me in the right direction please?
Thanks
EnableSession = true allows you to access the Session collection, which is part of the HttpContext.Current.Session. If the code in your web method does not use the Session collection, then yes it is safe to remove, but if it does use the Session collection, then removing this attribute will cause your web service logic to throw an exception, because it will not have access to the Session collection.
ScriptMethod(ResponseFormat = ResponseFormat.Json) is explicitly defining that this web method will return JSON, but since JSON is the default return type, then removing it does not matter. So the short answer is, yes it is fine to remove this, but it will not hurt to leave it there (in fact I would argue that is better to because it explicitly states this thing is returning JSON data).
AS #Karl already said if you need to access Session in webmethod, you've to decorate your method with the said attribute.
Now I've seen people complaining about webmethod not returning JSON response on SO and Asp.net official forum even though they have decorated their method with
ScriptMethod(ResponseFormat = ResponseFormat.Json)
because they might have missing configuration in web.config.
I would suggest you to go through Dave Ward's below articles that may help you to understand what needs to be done to return JSON response with ASMX:
ASMX and JSON – Common mistakes and misconceptions
ASMX ScriptService mistake: Installation and configuration
I have a mvc 3 project and I need to populate sql database with data from xml file. So I added the console app project to the solution and wrote the code that will display all needed data on the screen. Now I want to write data into the database. Here is the chunk of code: (fom the console app)
public static void Main()
{
IKernel ninjectKernel = new StandardKernel();
ninjectKernel.Bind<IItemsRepository>().To<ItemsRepository>();
ninjectKernel.Bind<IProductRepository>().To<ProductRepository>();
ninjectKernel.Bind<IShippingRepository>().To<ShippingRepository>();
var itemsRepository = ninjectKernel.Get<IItemsRepository>(); // redirection to datacontext file
var productRepository = ninjectKernel.Get<IProductRepository>();
var shippingRepository = ninjectKernel.Get<IShippingRepository>();
var doc = XDocument.Load(#"C:\div_kid.xml");
var offers = doc.Descendants("offer");
foreach (var offer in offers)
{ // here I use Linq to XML to get all needed data from xml file:
// name, description, price, category, shippingCost, shippingDetails
Product product = productRepository.CreateProduct(name, description, price, category, "Not Specified", "Not Specified");
Shipping shipping = shippingRepository.CreateShipping(shippingCost, shippingDetails);
// here I think I will just create "admin" user and assign its "UserId" to "userId"
Guid? userId = null;
Item item = itemsRepository.CreateItem(product.ProductId, shipping.ShippingId, (Guid) userId, DateTime.Now);
// Resharper highlights this line like unreachable. Why?
Console.WriteLine("name: {0}", offer.Element("name").Value);
}
}
First of all when I run the console app the NullReferenceException occures in MvcProjectName.Designer.cs file in the following line:
public WebStoreDataContext() :
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["WebStoreConnectionString"].ConnectionString, mappingSource)
NullReferenceException: The reference to the object is not pointing to the object instance.
So, I have lots of questions:
1) How to integrate console app code with mvc 3 app code in one solution?
2) I've also found this post on stackoverflow.
But can't I just add reference to MvcProject in references of ConsoleProject? And this way get access to the "mvc repositories" code?
3) Should I use ninject container in console app?
4) Is there any better implementation of loading data from xml file into slq database? I've never had two projects in one solution before, so mabby there are other ways to beautifully handle this situation?
Thanks for Your help in advance!
Edits:
I added app.config file with the connection string:
<add
name="WebStoreConnectionString" connectionString="Data Source=(LocalDB)\v11.0;
AttachDbFilename=|DataDirectory|\WebStore.mdf;Integrated Security=True;Connect Timeout=30"
providerName="System.Data.SqlClient"
/>
Now when I run console app I get the following SqlException when the Linq to SQL ".submitChanges()" method is called:
An attempt to attach an auto-named database for file C:\Users\Aleksey\repos\working_copy\WebStore\LoadDataTool\bin\Debug\WebStore.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
Also in the directory LoadDataTool\bin\Debug "WebStore" file with extension "Program Debug Database" appeared.
It's hard to make an accurate assumption on your solution architecture, but from what I'm reading, it doesn't sound like you've separated your Data Access Layer (DAL) from the presentation layer (MVC) - which seems to be why you're trying to referencing it in a console application.
With that assumption, here's how I would answer your questions.
I wouldn't... But if I was going to I was 1) make sure that I have all the required references, 2) validate that the app.config file is setup correctly pointing to the correct database and server.
I would separate your repositories in a different project and use a dependency resolver to inject them into your MVC Application. With that, the console application will only need to reference the DAL assembly - thus not needed all the references in your console app.
If your think that you're going to be pulling out the DAL in the future, then yes. (**See #2 suggestion).
Unless you can't run your solution without the XML file and database created, a better solution is to simply make an administration Controller and Action that allows you to upload your XML file and complete the tasks.
I hope that helps.
Update
For your issue
An attempt to attach an auto-named database for file
Change your connection string so that it looks something like;
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\WebStore.mdf;
A good source for connection strings is:
http://www.connectionstrings.com/
I guess that you need to define a connection string in the App.config file that is used by your console application (the same way you have it in your web.config):
<connectionStrings>
<add
name="WebStoreConnectionString"
connectionString="YOUR CONNECTION STRING COMES HERE"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
I have a Filetable containing many different document types (.doc;.pdf;.xls etc).
I am writing a small web (C# / .net 4) search app. Search works great using fulltext index with filetable to find content.
But I'm struggling to find a way in my app to have the search results as links which can launch the document in question? And just handle the different file types? (Assume client has Word/adobe/excel installed etc)
Grateful for any advice.
You will need to write a custom page handler to stream the bytes to the client with the proper HTTP headers. You will need to decide whether to support inline viewing (open in the browser - Content-Disposition: inline) versus external viewing using an attachment (e.g. Content-Disposition: attachment).
Response.AddHeader("Content-Disposition", "attachment; filename=example.pdf");
If you are using ASP.NET MVC - you can leverage the FileResult to streamline this process, but creating your own handler wouldn't be too much different.
public FileResult Download()
{
byte[] fileBytes = ...; // from FileTable
string fileName = "example.txt";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
The best approach to handling various MIME types (PDF, DOC, XLS) is to statically define the supported file types or dynamically read IIS and assign the appropriate Content-Type HTTP header.
Response.ContentType = "application/pdf";
I am trying to create a method in a class that accesses a WebMethod on a Web Service using WebClient, and am running into problems. Using VS2010 on Windows.
First of all, yes I know I could create a Web Reference to the web service in the class library, of course this is design time binding. However, I need to be able to get to the web service using information only available at run time. There's a business reason for this that I won't go into here, just go with it, please.
This appears to be possible using the WebClient class from the System.Net namespace. And in fact I am able to get to the service in question, but the data I am sending to it doesn't appear to be in a correct format, although for all I can tell it is a properly formatted SOAP message.
The WebException contains the following message: "The remote server returned an error: (415) Unsupported Media Type."
Here's the code:
public string DoingBusiness()
{
WebClient client = new WebClient();
string destUri = "http://localhost/Service/Service.asmx?op=CommunicationsCheck";
StreamReader reader = new StreamReader(#"CommCheck.xml");
string data = String.Format(reader.ReadToEnd(), "The End is Near!");
reader.Close();
string response = client.UploadString(destUri, data);
return response;
}
Leaving off the actual xmlns, which is sensitive, the data read by the StreamReader above looks like:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<CommunicationsCheck xmlns="http://.../">
<communication>{0}</communication>
</CommunicationsCheck>
</soap:Body>
</soap:Envelope>
This looks like a perfectly fine SOAP message. Of course the "{0}" gets filled in with the payload string. If the WebMethod "CommunicationsCheck(string communication) ran successfully it would return:
<?xml version="1.0" encoding="utf-8" ?>
<string xmlns="http://[service url]/">You sent 'The End is Near!'</string>
Which it does if I access the service through a browser, or through a design-time web reference.
So, the question is, what am I doing wrong here that I get the "(415) Unsupported Media Type"
Are there properties on the WebClient that need to be set? Do I perhaps need to provide a Header containing a UserAgent? Or something else?
Darn. I guess I should let someone else answer the question, but answering one's own question is acceptable, if one finds it oneself.
Anyway, some further research on the problem seemed to suggest that one surmise on my part, namely that there might be some Header property I needed to set, was a possible solution. And the research suggested that the property would be "content-type" needed to be set as "text/xml". So I added this line:
client.Headers.Add("content-type", "text/xml");
just before the UploadString method call.
BINGO!
The expected response occurred.
Has anyone ever noticed that answers to perplexing questions sometimes become self-evident once the question is posed, but not before? Interesting phenomenon.