Convert cookie string to a Cookie object in C# or Java - authentication

I need to automatically access a website that requires authentication. I found cookie string of this website's http host (using fiddler). Is there a way to convert this string to a cookie object and pass it to a Webclient to pass the authentication?

Convert the Sting to a cookie object. For this you need to parse the String to get name, value, path, domain, etc.
You have to do something like this -
String[] cArray = cookieValueIs.split(";");
for (String s : cArray) {
s = s.trim();
int i1 = s.indexOf('=');
if (i1 != -1) {
String k = s.substring(0, i1).trim();
String v = s.substring(i1 + 1).trim();
if (k.equalsIgnoreCase(VERSION)) {
version = v;
} else if (k.equalsIgnoreCase(COMMENT)) {
comment = v;
} else if (k.equalsIgnoreCase(DOMAIN)) {
domain = v;
} else if (k.equalsIgnoreCase(PATH)) {
path = v;
} else if (k.equalsIgnoreCase(MAX_AGE)) {
maxAge = v;
} else if(k.equalsIgnoreCase(EXPIRES)){
continue;
}
else {
key = k;
value = v;
}
} else {
if (s.equalsIgnoreCase(SECURE)) {
secure = true;
} else if (s.equalsIgnoreCase(HTTPONLY)) {
httpOnly = true;
}
}
Once you are done with this create a cookie object-
Cookie cookie = new Cookie(key,value);
if(comment != null){
cookie.setComment(comment);
}
if(domain != null){
cookie.setDomain(domain);
}
if(path != null){
cookie.setPath(path);
}
if(version != null){
cookie.setVersion(Integer.parseInt(version));
}
if(secure){
cookie.setSecure(true);
Now your string is converted to the Cookie object --> cookie

This worked for me in c#.
public static Cookie ToCookie(this string #this)
{
String[] array = #this.Split(';');
var cookie = new Cookie();
foreach (var ss in array)
{
string key;
object value;
var s = ss.Trim();
int indexOf = s.IndexOf('=');
if (indexOf != -1) {
key = s.Substring(0, indexOf).Trim();
value = s.Substring(indexOf + 1).Trim();
} else
{
key = s.ToTitleCase();
value = true;
}
var prop = cookie.GetType().GetProperty(key.ToTitleCase());
if (prop != null)
{
var converted = Convert.ChangeType(value, prop.PropertyType);
prop.SetValue(cookie, converted, null);
}else
{
cookie.Name = key;
cookie.Value = value.ToString();
}
}
return cookie;
}

Related

How to create url with complex query

I use dart and flutter for mobile app. I use my api to get data from server. But I found a problem, maybe its dart core problem.
I need to add complex queryParams to my URL like
Map<String, Map<String, List<String>>>{"a": {"b": ["c","d"]}, "e": {}}
I use Uri.parse(url).replace(queryParams: myQueryParams).toString()
But Uri.replace() accepts only Map<String, Iterable<String>> and throws an error
Unhandled Exception: type '_InternalLinkedHashMap<String, List<String>>' is not a subtype of type 'Iterable<dynamic>'
I found method which throws this error
static String _makeQuery(String query, int start, int end,
Map<String, dynamic /*String|Iterable<String>*/ > queryParameters) {
if (query != null) {
if (queryParameters != null) {
throw ArgumentError('Both query and queryParameters specified');
}
return _normalizeOrSubstring(query, start, end, _queryCharTable,
escapeDelimiters: true);
}
if (queryParameters == null) return null;
var result = StringBuffer();
var separator = "";
void writeParameter(String key, String value) {
result.write(separator);
separator = "&";
result.write(Uri.encodeQueryComponent(key));
if (value != null && value.isNotEmpty) {
result.write("=");
result.write(Uri.encodeQueryComponent(value));
}
}
queryParameters.forEach((key, value) {
if (value == null || value is String) {
writeParameter(key, value);
} else {
Iterable values = value;
for (String value in values) {
writeParameter(key, value);
}
}
});
return result.toString();
}
So my question is there is some method in dart to add my queryParams to url or I need to create it by my own?
I have modified original method and now its work.
class UrlCreator {
static String addQueryParams(String url, Map<String, dynamic> queryParams) {
var result = StringBuffer();
var separator = "";
void writeParameter(String key, String value) {
result.write(separator);
separator = "&";
result.write(Uri.encodeQueryComponent(key));
if (value != null && value.isNotEmpty) {
result.write("=");
result.write(Uri.encodeQueryComponent(value));
}
}
void buildQuery(Map queryParams, {parentKey}){
queryParams.forEach((key, value){
print("parentKey = $parentKey Key = $key value = $value");
if (value == null || value is String) {
var newKey = parentKey != null ? "$parentKey[$key]" : key;
writeParameter(newKey, value);
} else if (value is Map) {
buildQuery(value, parentKey: key);
} else {
Iterable values = value;
var newKey = parentKey != null ? "$parentKey[$key][]" : "$key[]";
for (String value in values) {
writeParameter(newKey, value);
}
}
});
}
buildQuery(queryParams);
return url + "?" + result.toString();
}
}

Throwing an Exception In an Xss Attack

This is a Web API which Json payloads (so, no Razor).
I'm using ASP.NET Core 2.1
1st up I should mention that I am sanitizing the relevant inputs with HtmlEncoder. However, that is just in case any gets past my validator, which I want to ask about here.
I want to write a validator which will return an error code where a user tries to include an html string in an input (using a mobile app, which would be a property in the json payload).
I've seen some naive implementation suggestion here on SO - usually just checking to see of the string contains '<' or '>' (and maybe one or 2 other chars).
I guess I would like to know if that is sufficient for the task at hand. There's no reason for a user to post any kind of html/xml in this domain.
A lot of the libraries around will sanitize input. But none of them seem to have a method which tells you if a string contains potentially harmful input.
As I said, I'm already sanitizing (as a last line of defence). But ideally I would return an error code before it gets to that.
Use this class from Microsoft ASP.NET Core 1
// <copyright file="CrossSiteScriptingValidation.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
public static class CrossSiteScriptingValidation
{
private static readonly char[] StartingChars = { '<', '&' };
#region Public methods
// Only accepts http: and https: protocols, and protocolless urls.
// Used by web parts to validate import and editor input on Url properties.
// Review: is there a way to escape colon that will still be recognized by IE?
// %3a does not work with IE.
public static bool IsDangerousUrl(string s)
{
if (string.IsNullOrEmpty(s))
{
return false;
}
// Trim the string inside this method, since a Url starting with whitespace
// is not necessarily dangerous. This saves the caller from having to pre-trim
// the argument as well.
s = s.Trim();
var len = s.Length;
if ((len > 4) &&
((s[0] == 'h') || (s[0] == 'H')) &&
((s[1] == 't') || (s[1] == 'T')) &&
((s[2] == 't') || (s[2] == 'T')) &&
((s[3] == 'p') || (s[3] == 'P')))
{
if ((s[4] == ':') || ((len > 5) && ((s[4] == 's') || (s[4] == 'S')) && (s[5] == ':')))
{
return false;
}
}
var colonPosition = s.IndexOf(':');
return colonPosition != -1;
}
public static bool IsValidJavascriptId(string id)
{
return (string.IsNullOrEmpty(id) || System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(id));
}
public static bool IsDangerousString(string s, out int matchIndex)
{
//bool inComment = false;
matchIndex = 0;
for (var i = 0; ;)
{
// Look for the start of one of our patterns
var n = s.IndexOfAny(StartingChars, i);
// If not found, the string is safe
if (n < 0) return false;
// If it's the last char, it's safe
if (n == s.Length - 1) return false;
matchIndex = n;
switch (s[n])
{
case '<':
// If the < is followed by a letter or '!', it's unsafe (looks like a tag or HTML comment)
if (IsAtoZ(s[n + 1]) || s[n + 1] == '!' || s[n + 1] == '/' || s[n + 1] == '?') return true;
break;
case '&':
// If the & is followed by a #, it's unsafe (e.g. S)
if (s[n + 1] == '#') return true;
break;
}
// Continue searching
i = n + 1;
}
}
#endregion
#region Private methods
private static bool IsAtoZ(char c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
#endregion
}
Then use this middleware to control URL,Query Parameteres and Content:
public class XssMiddleware
{
private readonly RequestDelegate _next;
public XssMiddleware(RequestDelegate next)
{
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
_next = next;
}
public async Task Invoke(HttpContext context)
{
// Check XSS in URL
if (!string.IsNullOrWhiteSpace(context.Request.Path.Value))
{
var url = context.Request.Path.Value;
int matchIndex;
if (CrossSiteScriptingValidation.IsDangerousString(url, out matchIndex))
{
throw new CrossSiteScriptingException("YOUR_ERROR_MESSAGE");
}
}
// Check XSS in query string
if (!string.IsNullOrWhiteSpace(context.Request.QueryString.Value))
{
var queryString = WebUtility.UrlDecode(context.Request.QueryString.Value);
int matchIndex;
if (CrossSiteScriptingValidation.IsDangerousString(queryString, out matchIndex))
{
throw new CrossSiteScriptingException("YOUR_ERROR_MESSAGE");
}
}
// Check XSS in request content
var originalBody = context.Request.Body;
try
{
var content = await ReadRequestBody(context);
int matchIndex;
if (CrossSiteScriptingValidation.IsDangerousString(content, out matchIndex))
{
throw new CrossSiteScriptingException("YOUR_ERROR_MESSAGE");
}
await _next(context);
}
finally
{
context.Request.Body = originalBody;
}
}
private static async Task<string> ReadRequestBody(HttpContext context)
{
var buffer = new MemoryStream();
await context.Request.Body.CopyToAsync(buffer);
context.Request.Body = buffer;
buffer.Position = 0;
var encoding = Encoding.UTF8;
var contentType = context.Request.GetTypedHeaders().ContentType;
if (contentType?.Charset != null) encoding = Encoding.GetEncoding(contentType.Charset);
var requestContent = await new StreamReader(buffer, encoding).ReadToEndAsync();
context.Request.Body.Position = 0;
return requestContent;
}
}

Error: Only primitive types or enumeration types are supported in this context

[HttpPost]
public ActionResult Dep_Save_Attachments(int in_queue_id, HttpPostedFileBase httpfile, string authorized_by, string authorized_to, string confirmed_by, string approved_by)
{
if (httpfile != null)
{
var folder = Server.MapPath("~/Attachments/Laptops/" + in_queue_id + "/");
var prev_fa = db.File_Attachments.Where(x => x.inventory_table_id == in_queue_id).Where(x => x.is_active == true).ToList();
var prev_hfa = db.HW_Authorization_Forms.Where(x => x.file_attachments_id == prev_fa.FirstOrDefault().file_attachments_id).Where(x => x.is_active == true).ToList();
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
if (prev_fa.Count != 0)
{
foreach (var pf in prev_fa)
{
pf.is_active = false;
db.Entry(pf).State = EntityState.Modified;
db.SaveChanges(); ;
}
}
if (prev_hfa.Count != 0)
{
foreach (var hpf in prev_hfa)
{
hpf.is_active = false;
db.Entry(hpf).State = EntityState.Modified;
db.SaveChanges(); ;
}
}
try
{
string path = System.Web.HttpContext.Current.Server.MapPath("~/Attachments/Laptops/" + in_queue_id + "/") + System.IO.Path.GetFileName(httpfile.FileName);
httpfile.SaveAs(path);
File_Attachments fa = new File_Attachments();
fa.file_attachments_id = 1;
fa.inventory_table_name = "Laptops_Transactions";
fa.inventory_table_id = in_queue_id;
fa.file_name = System.IO.Path.GetFileName(httpfile.FileName);
fa.file_path = "http://" + Request.Url.Host + ":" + Request.Url.Port + "/Attachments/Laptops/" + httpfile.FileName;
fa.created_by = #User.Identity.Name.Remove(0, 9).ToLower();
fa.created_date = System.DateTime.Now;
fa.is_active = true;
db.File_Attachments.Add(fa);
db.SaveChanges();
Laptops_Transactions laptops_trans = db.Laptops_Transactions.Find(in_queue_id);
laptops_trans.lp_trans_type = "deployed";
laptops_trans.lp_date_returned = System.DateTime.Now;
db.Entry(laptops_trans).State = EntityState.Modified;
db.SaveChanges();
HW_Authorization_Forms hwf = new HW_Authorization_Forms();
hwf.hw_authorization_forms_id = 1;
hwf.file_attachments_id = fa.file_attachments_id;
hwf.hw_authorized_by = authorized_by;
hwf.hw_authorized_to = authorized_to;
hwf.hw_confirmed_by = confirmed_by;
hwf.hw_approved_by = approved_by;
hwf.hw_approved_date = fa.created_date;
hwf.created_by = fa.created_by;
hwf.created_date = fa.created_date;
hwf.hw_authorized_date = fa.created_date;
hwf.hw_confirmed_date = fa.created_date;
hwf.is_active = true;
db.HW_Authorization_Forms.Add(hwf);
db.SaveChanges();
}
catch
{
}
}
else
{
return Content("<script language='javascript' type='text/javascript'>alert('Please Attach the Deployment Authorization Form! Kindly go back to previous page');</script>");
}
return RedirectToAction("Index");
}
The error is on this line:
var prev_hfa = db.HW_Authorization_Forms.Where(x => x.file_attachments_id == prev_fa.FirstOrDefault().file_attachments_id).Where(x => x.is_active == true).ToList();
This is my code in the controller, actually this is working already but it suddenly have a error. I really don't have an idea why i have this kind of error where before it works perfectly.
Please help me with this. Need some advice. Thanks in advance.
The error is because of Datatype issue i guess, you need to confirm you are doing with correct datatype, file_attachments_id of database and from your comparing value must be same.
Also, is_active must be of datatype Boolean. Correcting this may solve your error.

Getting all the Term Stores in Sharepoint 2010 (web services or client-side object model)?

Is it possible with Sharepoint 2010 (not 2013!) to get a list of all the Term Stores on the site using either the web services or the client-side object model?
I know 2013 has added a library for it, but that will not help me on 2010.
If not the whole list, how do I get the Term Store ID, if I know a Term (that might or might not be in the TaxonomyHiddenList)?
Someone mentioned checking out the TaxonomyFieldType fields, so I hacked together these 2 methods. I do not know if these will work under all circumstances.
First function just returns the Term Store ID which is stored in the info of the first TaxonomyFieldType* we come over.
public static string GetDefaultTermStore(string site) {
var context = new ClientContext(site);
var fields = context.Web.Fields;
context.Load(fields, fs => fs.Include(f => f.SchemaXml, f => f.TypeAsString));
context.ExecuteQuery();
foreach (var field in fields) {
if (field.TypeAsString.StartsWith("TaxonomyFieldType")) {
var doc = XDocument.Parse(field.SchemaXml);
var node = doc.XPathSelectElement("//Name[text()='SspId']/../Value");
if (node != null && !string.IsNullOrEmpty(node.Value)) {
return node.Value;
}
}
}
throw new Exception("Term Store ID not found!");
}
The second function goes through all the fields and gets all the possible Term Store IDs and returns them in a list.
public static List<string> GetTermStores(string site) {
var context = new ClientContext(site);
var fields = context.Web.Fields;
context.Load(fields, fs => fs.Include(f => f.SchemaXml, f => f.TypeAsString));
context.ExecuteQuery();
var hashlist = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
foreach (var field in fields) {
if (field.TypeAsString.StartsWith("TaxonomyFieldType")) {
var doc = XDocument.Parse(field.SchemaXml);
var node = doc.XPathSelectElement("//Name[text()='SspId']/../Value");
if (node != null && !string.IsNullOrEmpty(node.Value)) {
if (!hashlist.Contains(node.Value)) {
hashlist.Add(node.Value);
}
}
}
}
if (hashlist.Count == 0) throw new Exception("No Term Store IDs not found!");
return hashlist.ToList();
}
Is this a correct answer to my question do anyone have a more sure way to get the IDs?
Does not seem like anyone else has a good answer for this question.
I have added the utility class I made from this below. Big block of uncommented code below for those who might need:
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Services.Protocols;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Xml.XPath;
namespace VitaminTilKanbanPusher.Sharepoint {
public class SharepointTaxonomyAgent {
//URLS:
//http://www.novolocus.com/2012/02/06/working-with-the-taxonomyclientservice-part-1-what-fields-are-there/
//
public static void Test() {
var site = ConfigurationManager.AppSettings["VitaminSite"];
//var list = ConfigurationManager.AppSettings["VitaminList"];
//var id = GetDefaultTermStore(site);
//var ids = GetTermStores(site);
var rs = GetAllTermSetNames(site);
var ts = GetTermSetTerms(site, "Some Name");
//var ts = GetTermSetTerms(site, "Some other name");
//var term = GetTermInfo(site, "Priority");
//var term2 = GetTermInfo(site, "My term");
//var termset = GetTermSetInfo(site, "My term");
//var termsets = GetTermSets(site, "My term");
}
public static string GetDefaultTermStore(string site) {
var context = new ClientContext(site);
context.ExecutingWebRequest += ctx_MixedAuthRequest;
var fields = context.Web.Fields;
context.Load(fields, fs => fs.Include(f => f.InternalName, f => f.SchemaXml, f => f.TypeAsString));
context.ExecuteQuery();
foreach (var field in fields) {
//field.InternalName== "TaxKeyword" -> possibly default?
if (field.TypeAsString.StartsWith("TaxonomyFieldType")) {
var doc = XDocument.Parse(field.SchemaXml);
var node = doc.XPathSelectElement("//Name[text()='SspId']/../Value");
if (node != null && !string.IsNullOrEmpty(node.Value)) {
return node.Value;
}
}
}
throw new Exception("Term Store ID not found!");
}
public static List<string> GetTermStores(string site) {
var context = new ClientContext(site);
context.ExecutingWebRequest += ctx_MixedAuthRequest;
var fields = context.Web.Fields;
context.Load(fields, fs => fs.Include(f => f.SchemaXml, f => f.TypeAsString));
context.ExecuteQuery();
var hashlist = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
foreach (var field in fields) {
if (field.TypeAsString.StartsWith("TaxonomyFieldType")) {
var doc = XDocument.Parse(field.SchemaXml);
var node = doc.XPathSelectElement("//Name[text()='SspId']/../Value");
if (node != null && !string.IsNullOrEmpty(node.Value)) {
if (!hashlist.Contains(node.Value)) {
hashlist.Add(node.Value);
}
}
}
}
if (hashlist.Count == 0) throw new Exception("No Term Store IDs not found!");
return hashlist.ToList();
}
private static List<TermSet> _termSets;
public static List<TermSet> GetAllTermSetNames(string site, string onlySpecificTermSetName = null) {
if (_termSets != null) {
if (onlySpecificTermSetName == null) return _termSets;
foreach (var ts in _termSets) {
if (ts.Name.Equals(onlySpecificTermSetName, StringComparison.InvariantCultureIgnoreCase)) {
return new List<TermSet>() { ts };
}
}
return new List<TermSet>();
}
var context = new ClientContext(site);
context.ExecutingWebRequest += ctx_MixedAuthRequest;
var fields = context.Web.Fields;
context.Load(fields, fs => fs.Include(f => f.SchemaXml, f => f.TypeAsString));
context.ExecuteQuery();
var hashlist = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
var termSets = new List<TermSet>();
TermSet theChosenTermSet = null;
foreach (var field in fields) {
if (field.TypeAsString.StartsWith("TaxonomyFieldType")) {
var ts = new TermSet();
var doc = XDocument.Parse(field.SchemaXml);
var fn = doc.Element("Field");
if (fn == null) continue;
if (fn.Attribute("DisplayName") == null) continue;
if (fn.Attribute("ID") == null) continue;
ts.Name = fn.Attribute("DisplayName").Value;
//Only 1 set?
if (onlySpecificTermSetName != null) {
if (!ts.Name.Equals(onlySpecificTermSetName, StringComparison.InvariantCultureIgnoreCase)) {
theChosenTermSet = ts;
}
}
if (fn.Attribute("Description") != null) {
ts.Description = fn.Attribute("Description").Value;
}
var node = doc.XPathSelectElement("//Name[text()='SspId']/../Value");
if (node != null && !string.IsNullOrEmpty(node.Value)) {
ts.TermStoreId = node.Value;
}
var node2 = doc.XPathSelectElement("//Name[text()='TermSetId']/../Value");
if (node2 != null && !string.IsNullOrEmpty(node2.Value)) {
ts.Id = node2.Value;
}
else {
continue; //No ID found
}
//Unique hites
if (!hashlist.Contains(ts.Id)) {
hashlist.Add(ts.Id);
termSets.Add(ts);
}
}
}
_termSets = termSets;
if (onlySpecificTermSetName != null) return (theChosenTermSet == null ? new List<TermSet>() : new List<TermSet>() { theChosenTermSet });
return termSets;
}
public static TermSet GetTermSetTerms(string site, string termName) {
var ts = GetAllTermSetNames(site, termName);
if (ts.Count == 0) throw new Exception("Could not find termset: " + termName);
var theTermSet = ts[0];
var proxy = new SharepointTaxWS.Taxonomywebservice();
proxy.UseDefaultCredentials = true;
proxy.PreAuthenticate = true;
proxy.Url = Path.Combine(site, "_vti_bin/taxonomyclientservice.asmx");
GetAuthCookie(proxy, site);
var lciden = 1033; //var lcidno = 1044; // System.Globalization.CultureInfo.CurrentCulture.LCID
var clientTime = DateTime.Now.AddYears(-2).ToUniversalTime().Ticks.ToString();
var termStoreId = new Guid(theTermSet.TermStoreId);// Guid.Parse(theTermSet.TermStoreId);
var termSetId = new Guid(theTermSet.Id);
string clientTimestamps = string.Format("<timeStamp>{0}</timeStamp>", clientTime);
string clientVersion = "<version>1</version>";
string termStoreIds = string.Format("<termStoreId>{0}</termStoreId>", termStoreId.ToString("D"));
string termSetIds = string.Format("<termSetId>{0}</termSetId>", termSetId.ToString("D"));
string serverTermSetTimestampXml;
string result = proxy.GetTermSets(termStoreIds, termSetIds, 1033, clientTimestamps, clientVersion, out serverTermSetTimestampXml);
var term = ParseTermSetInfo(result);
term.Description = theTermSet.Description;
term.Id = theTermSet.Id;
term.Name = theTermSet.Name;
return term;
}
//public static Term GetTermSetInfo(string site, string termName) {
// var proxy = new SharepointTaxWS.Taxonomywebservice();
// proxy.UseDefaultCredentials = true;
// proxy.PreAuthenticate = true;
// proxy.Url = Path.Combine(site, "_vti_bin/taxonomyclientservice.asmx");
// GetAuthCookie(proxy, site);
// var lciden = 1033; //var lcidno = 1044; // System.Globalization.CultureInfo.CurrentCulture.LCID
// var sets = proxy.GetChildTermsInTermSet(Guid.Parse(""), lciden, Guid.Parse("termsetguid"));
// var term = ParseTermInfo(sets);
// return term;
//}
public static Term GetTermInfo(string site, string termName) {
var proxy = new SharepointTaxWS.Taxonomywebservice();
proxy.UseDefaultCredentials = true;
proxy.PreAuthenticate = true;
proxy.Url = Path.Combine(site, "_vti_bin/taxonomyclientservice.asmx");
GetAuthCookie(proxy, site);
var lciden = 1033; //var lcidno = 1044; // System.Globalization.CultureInfo.CurrentCulture.LCID
var sets = proxy.GetTermsByLabel(termName, lciden, SharepointTaxWS.StringMatchOption.StartsWith, 100, null, false);
var term = ParseTermInfo(sets);
return term;
}
private static TermSet ParseTermSetInfo(string xml) {
//Not done
var info = XDocument.Parse(xml);
var ts = new TermSet();
ts.Terms = new List<Term>();
var n1 = info.XPathSelectElements("//T");
if (n1 != null) {
foreach (var item in n1) {
var t = new Term();
t.Id = item.Attribute("a9").Value;
t.Name = item.XPathSelectElement("LS/TL").Attribute("a32").Value;
t.TermSet = ts;
ts.Terms.Add(t);
}
}
return ts;
}
private static Term ParseTermInfo(string xml) {
var info = XDocument.Parse(xml);
var t = new Term();
var ts = new TermSet();
var n1 = info.XPathSelectElement("TermStore/T");
var n2 = info.XPathSelectElement("TermStore/T/LS/TL");
var n3 = info.XPathSelectElement("TermStore/T/TMS/TM");
if (n1 != null && n1.Attribute("a9") != null) {
t.Id = n1.Attribute("a9").Value;
}
if (n2 != null && n2.Attribute("a32") != null) {
t.Name = n2.Attribute("a32").Value;
}
if (n3 != null && n3.Attribute("a24") != null) {
ts.Id = n3.Attribute("a24").Value;
}
if (n3 != null && n3.Attribute("a12") != null) {
ts.Name = n3.Attribute("a12").Value;
}
t.TermSet = ts;
return t;
}
private static CookieCollection _theAuth;
private static bool _bNoClaims;
static void GetAuthCookie(SoapHttpClientProtocol proxy, string site) {
return;
//if (_bNoClaims) {
// return; //Ingen claims.
//}
//// get the cookie collection - authentication workaround
//CookieCollection cook = null;
//try {
// if (_theAuth == null) {
// cook = ClaimClientContext.GetAuthenticatedCookies(site, 925, 525);
// }
// else {
// cook = _theAuth;
// }
// _theAuth = cook;
// _bNoClaims = false;
//}
//catch (ApplicationException ex) {
// if (ex.Message.Contains("claim")) _bNoClaims = true;
// Console.Write("Auth feilet: " + ex.Message + " - ");
// //IGNORE
//}
//if (_theAuth != null) {
// proxy.CookieContainer = new CookieContainer();
// proxy.CookieContainer.Add(_theAuth);
//}
}
static void ctx_MixedAuthRequest(object sender, WebRequestEventArgs e) {
//add the header that tells SharePoint to use Windows Auth
e.WebRequestExecutor.RequestHeaders.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
}
}
public class TermSet {
public string Id { get; set; }
public string Name { get; set; }
public List<Term> Terms { get; set; }
public string TermStoreId { get; set; }
public string Description { get; set; }
public override string ToString() {
int tc = 0;
if (Terms != null) tc = Terms.Count;
return Name + "|" + Id + " (" + tc + "terms)";
}
}
public class Term {
public string Id { get; set; }
public string Name { get; set; }
public TermSet TermSet { get; set; }
public override string ToString() {
return Name + "|" + Id;
}
}
}

Rewriting from MonoTouch Application to MonoDroid

I'm going to rewrite the application from Monotouh to Monodroid application for android. Correct me if I'm wrong. The logic remains the same as in MonoTouch or change anything? If something changes, please tell me, what?
As far as I understand, only GIU changes. Thanks in advance!
So, this is my code where i call data from my server:
namespace Mobile{
public static class SiteHelper
{
public static string DbPath = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), "Sql_1.4.sqlite");
public const string TempDbPath = "./Sql.sqlite";
public static UIView View { get; set; }
public static BaseController Controller { get; set; }
private static event NIHandler _noInternetHandler;
private static bool _noInternetShoved = false;
public static string SiteDomain = "http://mysite.com"; //files which connecting to the DB on server (.asx files)
private delegate void NIHandler ();
public static XDocument DoRequest (string Request)
{
if (_noInternetHandler != null) {
foreach (var del in _noInternetHandler.GetInvocationList()) {
_noInternetHandler -= del as NIHandler;
}
}
if (Controller != null)
_noInternetHandler += new NIHandler (Controller.PushThenNoInternet);
string CryptoString = "";
string Language = "ru";
using (MD5 md5Hash = MD5.Create()) {
string hashKey = Guid.NewGuid ().ToString ().Substring (0, 4);
CryptoString = Request + (Request.Contains ("?") ? "&" : "?") + "hash=" + GetMd5Hash (
md5Hash,
"myprogMobhash_" + hashKey
) + "&hashKey=" + hashKey + "&language=" + Language;
UIActivityIndicatorView _preloader = null;
if (Controller != null) {
Controller.InvokeOnMainThread (delegate() {
_preloader = new UIActivityIndicatorView (UIActivityIndicatorViewStyle.Gray);
if (View != null && Request.IndexOf ("login.ashx") == -1
&& Request.IndexOf ("yandex") == -1
&& Request.IndexOf ("GetDialogMessages") == -1) {
lock (_preloader) {
if (_preloader != null && !_preloader.IsAnimating)
_preloader.HidesWhenStopped = true;
_preloader.Frame = new RectangleF (150, 170, 30, 30);
_preloader.Transform = MonoTouch.CoreGraphics.CGAffineTransform.MakeScale ((float)1.3, (float)1.3);
_preloader.StartAnimating ();
View.Add (_preloader);
}
}
});
}
/*ctx.GetText(Resource.String.SiteAddress)*/
Stream Stream = null;
try {
HttpWebRequest request = new HttpWebRequest (new Uri (SiteDomain + "/FolderWithFiles/" + CryptoString));
request.Timeout = 8000;
Stream = request.GetResponse ().GetResponseStream ();
_noInternetShoved = false;
if (_noInternetHandler != null)
_noInternetHandler -= new NIHandler (Controller.PushThenNoInternet);
} catch (WebException) {
if (_noInternetHandler != null)
_noInternetHandler.Invoke ();
var resp = new XDocument (new XElement ("Response",
new XElement ("status", "error"),
new XElement ("error", "Отсутствует интернет"))
);
return resp;
}
StreamReader Sr = new StreamReader (Stream);
string Resp = Sr.ReadToEnd ();
XDocument Response = XDocument.Parse (Resp.Substring (0, Resp.IndexOf ("<html>") == -1 ? Resp.Length : Resp.IndexOf ("<!DOCTYPE html>")));
string Hash = Response.Descendants ().Where (x => x.Name == "hash")
.FirstOrDefault ().Value;
string HashKey = Response.Descendants ().Where (x => x.Name == "hashKey")
.FirstOrDefault ().Value;
Sr.Close ();
Stream.Close ();
if (Controller != null && _preloader != null) {
Controller.InvokeOnMainThread (delegate() {
lock (_preloader) {
_preloader.StopAnimating ();
_preloader.RemoveFromSuperview ();
}
});
}
if (VerifyMd5Hash (
md5Hash,
"mobileSitehash_" + HashKey,
Hash
))
return Response;
else
throw new Exception ();
}
}
public static XDocument DoWriteFileRequest (string Request, byte[] file)
{
string CryptoString = "";
string Language = "ru";
using (MD5 md5Hash = MD5.Create()) {
string hashKey = Guid.NewGuid ().ToString ().Substring (0, 4);
CryptoString = Request + (Request.Contains ("?") ? "&" : "?") + "hash=" + GetMd5Hash (
md5Hash,
"mobileMobhash_" + hashKey
) + "&hashKey=" + hashKey + "&language=" + Language;
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create (SiteDomain + "/misc/mobile/" + CryptoString);
Req.Method = "POST";
Stream requestStream = Req.GetRequestStream ();
requestStream.Write (file, 0, file.Length);
requestStream.Close ();
Stream Stream = Req.GetResponse ().GetResponseStream ();
StreamReader Sr = new StreamReader (Stream);
string Resp = Sr.ReadToEnd ();
XDocument Response = XDocument.Parse (Resp);
string Hash = Response.Descendants ().Where (x => x.Name == "hash")
.FirstOrDefault ().Value;
string HashKey = Response.Descendants ().Where (x => x.Name == "hashKey")
.FirstOrDefault ().Value;
Sr.Close ();
Stream.Close ();
if (VerifyMd5Hash (
md5Hash,
"mobileSitehash_" + HashKey,
Hash
))
return Response;
else
throw new Exception ();
}
}
public static string GetMd5Hash (MD5 md5Hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash (Encoding.UTF8.GetBytes (input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder ();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++) {
sBuilder.Append (data [i].ToString ("x2"));
}
// Return the hexadecimal string.2
return sBuilder.ToString ();
}
//Geting the info for my app
public static List<PackageListModel> GetUserPackages (int UserID)
{
List<PackageListModel> Events = new List<PackageListModel> ();
string Req = "SomeFile.ashx?UserID=" + UserID;
XDocument XmlAnswer = DoRequest (Req);
if (XmlAnswer.Descendants ("status").First ().Value == "ok") {
foreach (var el in XmlAnswer.Descendants ("Response").First ().Descendants().Where(x=>x.Name == "Event")) {
PackageListModel Event = null;
Event = new PackageListModel ()
{
ID = int.Parse(el.Attribute("ID").Value),
Title = el.Element("Title").Value,
Date = el.Element("Date").Value,
Price = el.Element("Price").Value,
ImageUrl = el.Element("ImageUrl").Value,
Location = el.Element("Location").Value
};
Events.Add (Event);
}
}
return Events;
}
//Получить пользовательские поездки
public static List<TransporterListModel> GetUserTransporters (int UserID)
{
List<TransporterListModel> Events = new List<TransporterListModel> ();
string Req = "SomeFile.ashx?UserID=" + UserID;
XDocument XmlAnswer = DoRequest (Req);
if (XmlAnswer.Descendants ("status").First ().Value == "ok") {
foreach (var el in XmlAnswer.Descendants ("Response").First ().Descendants().Where(x=>x.Name == "Event")) {
TransporterListModel Event = null;
Event = new TransporterListModel ()
{
ID = int.Parse(el.Attribute("ID").Value),
Date = el.Element("Date").Value,
Price = el.Element("Price").Value,
TransportsStr = el.Element("Transports").Value,
Location = el.Element("Location").Value
};
Events.Add (Event);
}
}
return Events;
}
}
}
}
I think you should read this.
In brief - you can reuse application logic that not depends on platform-specific parts, so working with database/server can be shared between MonoTouch and Mono for Android.