How can I test WCF JSON services. I want to create something like unit tests for this services. Is there any tutorial for something like this? I would b most interested to write the JSON object myself like
{somedata:abc,foo:boo}
Here is a link that might get you started.
http://www.entechsolutions.com/wcf-web-service-for-soap-json-and-xml-with-unit-tests
"-create a dynamic class that matches JSON datastructure
-Serialize it to JSON
-Send json to web service
-Deserilize response to a dynamic object
-Make sure that response has value that I expected"
POST
[Test]
public void Add_WhenMethodPost_And_ValidApiKey_ReturnsSum()
{
var addRequest = new
{
Value1 = 5,
Value2 = 11,
ApiKey = Const.ValidApiKey
};
var url = string.Format("{0}/json/add", Const.WebServiceUrl);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
var jsSerializer = new JavaScriptSerializer();
var jsonAddRequest = jsSerializer.Serialize(addRequest);
var writer = new StreamWriter(request.GetRequestStream());
writer.Write(jsonAddRequest);
writer.Close();
var httpWebResponse = (HttpWebResponse)request.GetResponse();
string jsonString;
using (var sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
jsonString = sr.ReadToEnd();
}
var jsonAddResponse = jsSerializer.Deserialize<dynamic>(jsonString);
Assert.AreEqual(16, jsonAddResponse["Sum"]);
}
GET
[Test]
public void Add_WhenMethodGet_And_ValidApiKey_ReturnsSum()
{
var url = string.Format("{0}/json/add?value1={1}&value2={2}&apiKey={3}", Const.WebServiceUrl, 5, 11,
Const.ValidApiKey);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";
string jsonString;
var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
jsonString = sr.ReadToEnd();
}
var jsSerializer = new JavaScriptSerializer();
var jsonAddResponse = jsSerializer.Deserialize<dynamic>(jsonString);
Assert.AreEqual(16, jsonAddResponse["Sum"]);
}
Related
I've got this code that sends a simple email using SmtpClient, MailMessage, and MailAddress objects:
private void EmailMessage(string msg)
{
string TO_EMAIL = "cshannon#proactusa.com";
var windowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();
string userName = windowsIdentity.Name;
string subject = string.Format("Log msg from Report Runner app sent {0}; user was {1}", DateTime.Now.ToLongDateString(), userName);
string body = msg;
var SmtpServer = new SmtpClient(ReportRunnerConstsAndUtils.EMAIL_SERVER);
var SendMe = new MailMessage();
SendMe.To.Add(TO_EMAIL);
SendMe.Subject = subject;
SendMe.From = new MailAddress(ReportRunnerConstsAndUtils.FROM_EMAIL);
SendMe.Body = body;
try
{
SmtpServer.UseDefaultCredentials = true;
SmtpServer.Send(SendMe);
}
}
I also need, though, to attach a file to an email. I was doing it using Outlook like so:
Application app = new Application();
MailItem mailItem = app.CreateItem(OlItemType.olMailItem);
. . .
FileInfo[] rptsToEmail = GetLastReportsGenerated();
foreach (var file in rptsToEmail)
{
String fullFilename = String.Format("{0}\\{1}", uniqueFolder, file.Name);
if (!file.Name.Contains(PROCESSED_FILE_APPENDAGE))
{
mailItem.Attachments.Add(fullFilename);
}
}
mailItem.Importance = OlImportance.olImportanceNormal;
mailItem.Display(false);
...but I need to move away from using Outlook for this. Here the MailItem is a Microsoft.Office.Interop.Outlook.MailItem
How can I add attachments in the simple MailMessage I need to use now?
Setting the Importance is not too important, I don't think, but the Display is something I will need to set for the MailMessage, too.
Easy:
if (!file.Name.Contains(PROCESSED_FILE_APPENDAGE))
{
var attachment = new Attachment(fullFilename);
mailMsg.Attachments.Add(attachment);
}
mailMsg.Priority = MailPriority.Normal;
Is there a simpler way to do this? I am sincerely concerned that this LinqPad doodle might be too verbose:
var xml = #"
<root attr1=""attribute one"" attr2=""attribute two"">
<title>this is the root</title>
<xhtml>
<div id=""wrapper"">
<p style=""first""><em>hello</em> world!</p>
</div>
</xhtml>
</root>
";
var xDoc = XDocument.Parse(xml);
Func<XNode, string> getXhtml = node =>
{
var s = string.Empty;
StringWriter wr = null;
try
{
wr = new StringWriter();
using(var jsonWriter = new JsonTextWriter(wr))
{
jsonWriter.StringEscapeHandling = StringEscapeHandling.EscapeHtml;
new JsonSerializer().Serialize(jsonWriter, node.ToString());
}
s = wr.ToString();
}
finally
{
if(wr != null) wr.Dispose();
}
return s;
};
var escaped_xhtml = getXhtml(xDoc.Root.Element("xhtml").Element("div"));
escaped_xhtml.Dump("escaped xhtml");
var placeholder = "#rx-xhtml";
xDoc.Root.Element("xhtml").Value = placeholder;
var json = JsonConvert.SerializeXNode(xDoc.Root, Newtonsoft.Json.Formatting.Indented);
var json_final =json
.Replace(string.Format(#"""{0}""",placeholder), escaped_xhtml);
json_final.Dump("json with escaped xhtml");
var jDoc = JObject.Parse(json_final);
escaped_xhtml = (string)jDoc["root"]["xhtml"];
escaped_xhtml.Dump("decoded xhtml");
It may be reasonable to assume that JSON.NET already has, say, the equivalent of my getXhtml() routine. JSON.NET has so many great features I am concerned that I might be missing out.
Is this what you want? It produces the same result for json_final:
// Parse the XML
var xDoc = XDocument.Parse(xml);
// Extract the "div" element.
var div = xDoc.Root.Element("xhtml").Element("div");
div.Remove();
// Convert the remainder to a JObject.
var jDoc = JObject.FromObject(xDoc.Root, JsonSerializer.CreateDefault(new JsonSerializerSettings { Converters = new[] { new XmlNodeConverter() } }));
// Store the Div element as a string literal.
jDoc["root"]["xhtml"] = div.ToString();
// Stringify the JSON using StringEscapeHandling = StringEscapeHandling.EscapeHtml
var json_final = JsonConvert.SerializeObject(jDoc, new JsonSerializerSettings { Formatting = Formatting.Indented, StringEscapeHandling = StringEscapeHandling.EscapeHtml });
It eliminates the string replacement and the getXhtml delegate. Note that StringEscapeHandling applies during the final conversion to string, not to intermediate conversions to Joken (where string literals are not escaped).
Even simpler still, replace the <Div> element with a corresponding XML string literal before converting to JSON:
// Parse the XML
var xDoc = XDocument.Parse(xml);
// Replace the DIV element with its XML string literal value
var div = xDoc.Root.Element("xhtml").Element("div");
div.Remove();
xDoc.Root.Element("xhtml").Value = div.ToString();
// Convert to JSON using StringEscapeHandling = StringEscapeHandling.EscapeHtml
var json_final = JsonConvert.SerializeObject(xDoc, new JsonSerializerSettings { Converters = new[] { new XmlNodeConverter() }, Formatting = Formatting.Indented, StringEscapeHandling = StringEscapeHandling.EscapeHtml });
I am trying to add an element in existing isolated folder in xml
code:
public void writeToXML(List<AppTile> appList)
{
// Write to the Isolated Storage
XmlWriterSettings x_W_Settings = new XmlWriterSettings();
x_W_Settings.Indent = true;
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!ISF.FileExists("config.xml"))
{
using (IsolatedStorageFileStream stream = ISF.OpenFile("config.xml", FileMode.CreateNew))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<AppTile>));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, x_W_Settings))
{
serializer.Serialize(xmlWriter, appList);
}
stream.Close();
}
}
else
{
string tileName = null;
string url = null;
string key = null;
byte [] tilePic = null;
XDocument loadedData;
if (appList != null)
{
foreach (AppTile app in appList)
{
tileName = app.TileName;
url = app.Url;
key = app.Key;
tilePic = app.TilePic;
// tilePic = Encoding.UTF8.GetString(app.TilePic,0,app.TilePic.Length);
// tilePic = Encoding.Unicode.GetString(app.TilePic,0,app.TilePic.Length);
// var writer = new BinaryWriter(tilePic);
}
using (Stream stream = ISF.OpenFile("config.xml", FileMode.Open, FileAccess.ReadWrite))
{
loadedData = XDocument.Load(stream);
var RootNode = new XElement("AppTile");
RootNode.Add(new XElement("TileName", tileName));
RootNode.Add(new XElement("Key", key));
RootNode.Add(new XElement("Url", url));
RootNode.Add(new XElement("TilePic", tilePic));
// Find Root Element And Descedents and Append New Node After That
var root = loadedData.Element("ArrayOfAppTile");
var rows = root.Descendants("AppTile");
var lastRow = rows.Last();
lastRow.AddAfterSelf(RootNode);
}
// Save To ISOconfig.xml File
using (IsolatedStorageFileStream newStream = new IsolatedStorageFileStream("config.xml", FileMode.Create, ISF))
{
loadedData.Save(newStream);
newStream.Close();
}
}
}
}
}
while reading from xml i am using xmlWriter and deserialize it to get List
when ever i am trying to acces the tilePic of AppTile type i am getting error :The component cannot be found. with the following code::
Image img = new Image();
MemoryStream imgStream = new MemoryStream(NewApp.TilePic);//NewApp is AppTile type
BitmapImage imgSource = new BitmapImage();
imgSource.SetSource(imgStream);//here i get error
img.Source = imgSource;
Its most likely with the TilePic i am saving is not formatted correctly to be retrieved.
Please Help!!
Why don't you use the SaveJpeg extension methodoogy in creating the byte array?
This one might help you!
Windows Phone - byte array to BitmapImage converter throws exception
solved the issue:
while saving the byte array it is encoded to some format not recognizable while reading,So what i have done is saved it as a string.So the updated code is:
else
{
string tileName = null;
string url = null;
string key = null;
string tilePicString = null;
XDocument loadedData;
System.Windows.Media.Imaging.BitmapImage imgSource = new System.Windows.Media.Imaging.BitmapImage();
if (appList != null)
{
foreach (AppTile app in appList)
{
tileName = app.TileName;
url = app.Url;
key = app.Key;
//changed here
tilePicString = System.Convert.ToBase64String(app.TilePic);
}
//same code as above
I'm trying to upload file to box using v2. The only result i get is the error while uploading. I'm able to authenticate, get the auth token but not able to upload, I have given the code which i'm using. If i'm wrong anyway just correct me. Any help will be appreciated!!
public function upload(argFile:flash.filesystem.File):void{
argFile.addEventListener(Event.COMPLETE,
function onComplete(event:Event):void
{
trace("complete:"+event.toString());
}
);
argFile.addEventListener(IOErrorEvent.IO_ERROR,
function onIOError(event:IOErrorEvent):void
{
trace("Error:"+event.toString());
}
);
var url:String = "https://api.box.com/2.0/files/data";
// Setup the custom header
var customHeader:String = "BoxAuth api_key=" + api_key + "&auth_token=" + auth_token;
var headers:Array = [
new URLRequestHeader("Authorization", customHeader)
];
// create the url-vars
var urlVars:URLVariables = new URLVariables();
urlVars.filename1 = '#'+argFile.name;
urlVars.folder_id = "0";
// create the url-reqeust
var request:URLRequest = new URLRequest();
request.contentType = "application/octet-stream";
request.method = URLRequestMethod.POST;
// set ther url
request.url = url;
// set the header
request.requestHeaders = headers;
// set the vars
request.data = urlVars;
try {
argFile.upload(request);
} catch (e:Error)
{
trace(e.toString(), "Error (catch all)");
}
}
I've got a JSON string:
query = {"action":"do","password":"c","name":"s"}
When using HTTPService's send method:
_service = new HTTPService();
_service.url = "http://localhost:8080";
_service.method = "POST";
_service.contentType = "application/json";
_service.resultFormat = "text";
_service.useProxy = false;
_service.makeObjectsBindable = true;
_service.addEventListener(FaultEvent.FAULT,faultRX);
_service.addEventListener(ResultEvent.RESULT,resultRX);
_service.showBusyCursor = true;
var _request:Object = new Object();
_request.query = query;
_service.request = _request;
_service.send();
I don't know what I am doing wrong but on my HTTP server I get:
{["object","Object"]}
Any clues please?
Thanks
You are declaring an object of an object.
Try:
_service.request = query;
_service.send();
you get
{["object","Object"]}
because of this
var _request:Object = new Object();
_request.query = query;
_service.request = _request;
do this
var jsonOBJ:Object = {};
jsonOBJ.action = "do";
jsonOBJ.password = "c";
jsonOBJ.name = "s";
var _service:HTTPService = new HTTPService();
_service.url = "http://localhost:8080";
_service.method = "POST";
_service.contentType = "application/json";
_service.resultFormat = "text";
_service.useProxy = false;
_service.makeObjectsBindable = true;
_service.addEventListener(FaultEvent.FAULT,faultRX);
_service.addEventListener(ResultEvent.RESULT,resultRX);
_service.showBusyCursor = true;
_service.send( JSON.encode( jsonOBJ ) );// encode the json object with AS3Corelib
Don't forget top JSON decode the string on the server side.