So, i'm calling the method to update the primary "sendAs" object of a google account, without results. The documentation from google at users.settings.sendAs/update indicates all i need and did:
i've set the domain wide account and scopes
i'm generating a token and accessing it no problem
i'm calling the "list" method first (with that token) as shown in users.settings.sendAs/list documentation, and finding the one that is the primary (the "isPrimary" attribute is true)
After that, changing the "signature" value to "Its a Test Signature", and sending the PUT request with it doesn't do anything.
The JSON sent to the update API (via PUT method) is the exact one i collected from the list (the primary one), but with the signature changed.
There is no error at all, and i receive an "sendAs" object back as a response (as the documentation says i should in case of sucess), but the signature is unchanged.
What can i be?
EDIT (adding the code section for the call, again - no errors)
public bool Update()
{
string json = null;
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/json";
wc.Headers["Authorization"] = "Bearer " + GenerateServerToServerToken(this.OwnerMail, this.scope);
json = wc.DownloadString("https://gmail.googleapis.com/gmail/v1/users/" + this.OwnerMail + "/settings/sendAs");
JSon.Query response = JSon.Parse(ref json);
json = null;
response = response["sendAs"];
List<JSon.Query> mailAs = null;
if (response.TryParseList(out mailAs))
{
JSon.Query main = null;
bool prim = false;
foreach (JSon.Query q in mailAs)
{
if (q["isPrimary"].TryParseBoolean(out prim) && prim)
{
if (q["sendAsEmail"].TryParseString(out json)) { main = q; }
break;
} else { json = null; }
}
if (main != null)
{
JSon.ObjectValue mainO = (JSon.ObjectValue)main.Value;
if (mainO.ContainsKey("signature"))
{
((JSon.StringValue)mainO["signature"]).Data = this.HtmlSignature.Replace("<", ("\\" + "u003c")).Replace(">", ("\\" + "u003e"));
mainO["verificationStatus"] = new MdIO.JSon.StringValue("accepted");
json = wc.UploadString("https://gmail.googleapis.com/gmail/v1/users/" + this.OwnerMail + "/settings/sendAs/" + json, "PUT", main.Value.ToJSON());
response = JSon.Parse(ref json);
if (response["sendAsEmail"].TryParseString(out json) && !string.IsNullOrEmpty(json)) { return true; }
}
}
}
}
return false;
}
I am developing one application in web api and angularjs. I have file upload part. I am able to upload files and i am not storing files in webroot(i created folder called Uploads). My problem is i am not using any good naming convention to maintain uniqueness of files so there are chances of overriding files. I am new to angularjs so i refered below link. http://instinctcoder.com/angularjs-upload-multiple-files-to-asp-net-web-api/
This is my controller level code.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var uploadPath = HttpContext.Current.Server.MapPath("~/Uploads");
var multipartFormDataStreamProvider = new CustomUploadMultipartFormProvider(uploadPath);
await Request.Content.ReadAsMultipartAsync(multipartFormDataStreamProvider);
var fileName = "";
DateTime dt = DateTime.Now;
foreach (var key in multipartFormDataStreamProvider.Contents)
{
var a = key.Headers;
fileName = a.ContentDisposition.FileName;
break;
}
foreach (var key in multipartFormDataStreamProvider.FormData.AllKeys)
{
foreach (var val in multipartFormDataStreamProvider.FormData.GetValues(key))
{
Console.WriteLine(string.Format("{0}: {1}", key, val));
}
}
In the above code I am trying to add date part to beginning of file name as below
string filenameNew = "App1" + DateTime.Now.ToString("yyyyMMddHHmmss");
fileName = filenameNew + a.ContentDisposition.FileName;
public CustomUploadMultipartFormProvider(string path) : base(path) { }
public override string GetLocalFileName(HttpContentHeaders headers)
{
string startwith = "Nor" + DateTime.Now.ToString("yyyyMMddHHmmss");
if (headers != null && headers.ContentDisposition != null)
{
return headers
.ContentDisposition
.FileName.TrimEnd('"').TrimStart('"').StartsWith("startwith").ToString();
}
return base.GetLocalFileName(headers);
}
This i tried but whatever the original file name that only comes. May I get some idea where can i append datepart to file while saving? Any help would be appreciated. Thank you.
I'm not sure what you're trying to do inside of the GetLocalFileName, this is pretty messed up.
First off, StartsWith returns a boolean (true or false) that indicates if the string starts with whatever you put in the parenthesis.
string str = "SIMPLE";
bool t = str.StartsWith("SIM"); // true
bool f = str.StartsWith("ZIM"); // false
The fact you're turning this bool back into a string and also passing the string "startsWith" into the method, means it will always return the string "false" (a bool value converted into a string) unless the real filename starts with "startsWith".
I think this is what you're looking for:
public override string GetLocalFileName(HttpContentHeaders headers)
{
string prefix = "Nor" + DateTime.Now.ToString("yyyyMMddHHmmss");
if (headers != null && headers.ContentDisposition != null)
{
var filename = headers.ContentDisposition.FileName.Trim('"');
return prefix + filename;
}
return base.GetLocalFileName(headers);
}
My suggestion for you is to learn the basics of C# and .Net a bit more, maybe read a C# book or something.
I am Scraping HTML DOM elements using HtmlAgilityPack in ASP.NET. currently my code is loading all the href links which means that sublinks of sublinks also . But I need only the depending URL of my domain URL. I don't know how to write code for it. Can any one help me to do this?
Here is my code:
public void GetURL(string strGetURL)
{
var getHtmlSource = new HtmlWeb();
var document = new HtmlDocument();
try
{
document = getHtmlSource.Load(strGetURL);
var aTags = document.DocumentNode.SelectNodes("//a");
if (aTags != null)
{
outputurl.Text = string.Empty;
int _count = 0;
foreach (var aTag in aTags)
{
string strURLTmp;
strURLTmp = aTag.Attributes["href"].Value;
if (_count != 0)
{
if (!CheckDuplicate(strURLTmp))
{
lstResults.Add(strURLTmp);
outputurl.Text += strURLTmp + "\n";
counter++;
GetURL(strURLTmp);
}
}
_count++;
}
}
}
If you meant to get URL that contains specific domain, you can change the XPath to be :
//a[contains(#href, 'your domain here')]
Or if you prefer LINQ than XPath :
var aTags = document.DocumentNode.SelectNodes("//a");
if (aTags != null)
{
....
var relevantLinks = aTags.Where(o => o.GetAttributeValue("href", "")
.Contains("your domain here")
);
....
}
GetAttributeValue() is a better way to get value of an attribute using HAP. Instead of returning null which may cause exception, this method returns the 2nd parameter when the attribute is not found in the context node.
I don't like to post such a general question, but I am not seeing a lot on the topic, so I was wondering if anyone has done something like this, and whether or not this is a good implementation to go with.
EDIT Added whole method
Here is the code
protected void gridViewAttachments_HtmlDataCellPrepared(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewTableDataCellEventArgs e)
{
//if (e.DataColumn.FieldName == "AttachmentName" && e.CellValue.ToString().ToLower().Contains("://"))
// attachmentUrl = e.CellValue.ToString();
//if (e.DataColumn.FieldName == "AttachmentName" && !e.CellValue.ToString().ToLower().Contains("://"))
// attachmentUrl = "http://" + e.CellValue;
Uri targetUri;
if (Uri.TryCreate("http://" + e.CellValue, UriKind.RelativeOrAbsolute, out targetUri))
{
attachmentUrl = new Uri("http://" + e.CellValue);
}
if (e.DataColumn is DevExpress.Web.ASPxGridView.GridViewDataHyperLinkColumn)
{
if (attachmentUrl.ToString() == "")
{
DevExpress.Web.ASPxEditors.Internal.HyperLinkDisplayControl hyperlink =
(e.Cell.Controls[0] as DevExpress.Web.ASPxEditors.Internal.HyperLinkDisplayControl);
hyperlink.Target = "_blank";
hyperlink.NavigateUrl = ApplicationUrl + "/Attachment.ashx?key=" + hyperlink.Text;
hyperlink.Text = GetWords("GENERAL.VIEW_ATTACHMENT");
}
else
{
DevExpress.Web.ASPxEditors.Internal.HyperLinkDisplayControl hyperlink = (e.Cell.Controls[0] as DevExpress.Web.ASPxEditors.Internal.HyperLinkDisplayControl);
hyperlink.Target = "_blank";
hyperlink.NavigateUrl = attachmentUrl.ToString();
hyperlink.Text = "Go to URL";
}
}
}
Pretty basic, and it works. My question is this: Is checking if the string contains :// enough to check whether or not it is a url? The reason I have to check is it is pulling the data from table and some of the fields in the table are filenames (mydoc.docx) in which case I will do something else with them. Is there another more robust check I can do in C#?
You could use Uri.TryCreate instead to see if creation of the URL is successful:
Uri targetUri;
if (Uri.TryCreate("http://" + e.CellValue, UriKind.RelativeOrAbsolute, out targetUri))
{
//success
attachmentUrl = "http://" + e.CellValue;
}
I have a URL that also might have a query string part, the query string might be empty or have multiple items.
I want to replace one of the items in the query string or add it if the item doesn't already exists.
I have an URI object with the complete URL.
My first idea was to use regex and some string magic, that should do it.
But it seems a bit shaky, perhaps the framework has some query string builder class?
I found this was a more elegant solution
var qs = HttpUtility.ParseQueryString(Request.QueryString.ToString());
qs.Set("item", newItemValue);
Console.WriteLine(qs.ToString());
Lets have this url:
https://localhost/video?param1=value1
At first update specific query string param to new value:
var uri = new Uri("https://localhost/video?param1=value1");
var qs = HttpUtility.ParseQueryString(uri.Query);
qs.Set("param1", "newValue2");
Next create UriBuilder and update Query property to produce new uri with changed param value.
var uriBuilder = new UriBuilder(uri);
uriBuilder.Query = qs.ToString();
var newUri = uriBuilder.Uri;
Now you have in newUri this value:
https://localhost/video?param1=newValue2
Maybe you could use the System.UriBuilder class. It has a Query property.
I use following method:
public static string replaceQueryString(System.Web.HttpRequest request, string key, string value)
{
System.Collections.Specialized.NameValueCollection t = HttpUtility.ParseQueryString(request.Url.Query);
t.Set(key, value);
return t.ToString();
}
string link = page.Request.Url.ToString();
if(page.Request.Url.Query == "")
link += "?pageIndex=" + pageIndex;
else if (page.Request.QueryString["pageIndex"] != "")
{
var idx = page.Request.QueryString["pageIndex"];
link = link.Replace("pageIndex=" + idx, "pageIndex=" + pageIndex);
}
else
link += "&pageIndex=" + pageIndex;
This seems to work really well.
No, the framework doesn't have any existing QueryStringBuilder class, but usually the querystring information in a HTTP request is available as an iterable and searchable NameValueCollection via the Request.Querystring property.
Since you are starting off with a Uri object, however, you will need to obtain the querystring portion using the Query property of the Uri object. This will yield a string of the form:
Uri myURI = new Uri("http://www.mywebsite.com/page.aspx?Val1=A&Val2=B&Val3=C");
string querystring = myURI.Query;
// Outputs: "?Val1=A&Val2=B&Val3=C". Note the ? prefix!
Console.WriteLine(querystring);
You can then split this string on the ampersand character to differentiate it into different querystring parameters-value pairs. Then again split each parameter on the "=" character to differentiate it into a key and value.
Since your final goal is to search for a particular querystring key and if necessary create it, you should try to (re)create a collection (preferably, a generic one) that allows you easily search in the collection, similar to the facility provided by the NameValueCollection class.
I used the following code to append/replace the value of a parameter in the current request URL:
public static string CurrentUrlWithParam(this UrlHelper helper, string paramName, string paramValue)
{
var url = helper.RequestContext.HttpContext.Request.Url;
var sb = new StringBuilder();
sb.AppendFormat("{0}://{1}{2}{3}",
url.Scheme,
url.Host,
url.IsDefaultPort ? "" : ":" + url.Port,
url.LocalPath);
var isFirst = true;
if (!String.IsNullOrWhiteSpace(url.Query))
{
var queryStrings = url.Query.Split(new[] { '?', ';' });
foreach (var queryString in queryStrings)
{
if (!String.IsNullOrWhiteSpace(queryString) && !queryString.StartsWith(paramName + "="))
{
sb.AppendFormat("{0}{1}", isFirst ? "?" : ";", queryString);
isFirst = false;
}
}
}
sb.AppendFormat("{0}{1}={2}", isFirst ? "?" : ";", paramName, paramValue);
return sb.ToString();
}
Maybe this helps others when finding this topic.
Update:
Just saw the hint about UriBuilder and did a second version using UriBuilder, StringBuilder and Linq:
public static string CurrentUrlWithParam(this UrlHelper helper, string paramName, string paramValue)
{
var url = helper.RequestContext.HttpContext.Request.Url;
var ub = new UriBuilder(url.Scheme, url.Host, url.Port, url.LocalPath);
// Query string
var sb = new StringBuilder();
var isFirst = true;
if (!String.IsNullOrWhiteSpace(url.Query))
{
var queryStrings = url.Query.Split(new[] { '?', ';' });
foreach (var queryString in queryStrings.Where(queryString => !String.IsNullOrWhiteSpace(queryString) && !queryString.StartsWith(paramName + "=")))
{
sb.AppendFormat("{0}{1}", isFirst ? "" : ";", queryString);
isFirst = false;
}
}
sb.AppendFormat("{0}{1}={2}", isFirst ? "" : ";", paramName, paramValue);
ub.Query = sb.ToString();
return ub.ToString();
}
I agree with Cerebrus. Sticking to the KISS principle, you have the querystring,
string querystring = myURI.Query;
you know what you are looking for and what you want to replace it with.
So use something like this:-
if (querystring == "")
myURI.Query += "?" + replacestring;
else
querystring.replace (searchstring, replacestring); // not too sure of syntax !!
I answered a similar question a while ago. Basically, the best way would be to use the class HttpValueCollection, which the QueryString property actually is, unfortunately it is internal in the .NET framework.
You could use Reflector to grab it (and place it into your Utils class). This way you could manipulate the query string like a NameValueCollection, but with all the url encoding/decoding issues taken care for you.
HttpValueCollection extends NameValueCollection, and has a constructor that takes an encoded query string (ampersands and question marks included), and it overrides a ToString() method to later rebuild the query string from the underlying collection.
public class QueryParams : Dictionary<string,string>
{
private Uri originolUrl;
private Uri ammendedUrl;
private string schemeName;
private string hostname;
private string path;
public QueryParams(Uri url)
{
this.originolUrl = url;
schemeName = url.Scheme;
hostname = url.Host;
path = url.AbsolutePath;
//check uri to see if it has a query
if (url.Query.Count() > 1)
{
//we grab the query and strip of the question mark as we do not want it attached
string query = url.Query.TrimStart("?".ToArray());
//we grab each query and place them into an array
string[] parms = query.Split("&".ToArray());
foreach (string str in parms)
{
// we split each query into two strings(key) and (value) and place into array
string[] param = str.Split("=".ToArray());
//we add the strings to this dictionary
this.Add(param[0], param[1]);
}
}
}
public QueryParams Set(string paramName, string value)
{
if(this.ContainsKey(paramName))
{
//if key exists change value
this[paramName] = value;
return (this);
}
else
{
this.Add(paramName, value);
return this;
}
}
public QueryParams Set(string paramName, int value)
{
if (this.ContainsKey(paramName))
{
//if key exists change value
this[paramName] = value.ToString();
return (this);
}
else
{
this.Add(paramName, value);
return this;
}
}
public void Add(string key, int value)
{
//overload, adds a new keypair
string strValue = value.ToString();
this.Add(key, strValue);
}
public override string ToString()
{
StringBuilder queryString = new StringBuilder();
foreach (KeyValuePair<string, string> pair in this)
{
//we recreate the query from each keypair
queryString.Append(pair.Key + "=" + pair.Value + "&");
}
//trim the end of the query
string modifiedQuery = queryString.ToString().TrimEnd("&".ToArray());
if (this.Count() > 0)
{
UriBuilder uriBuild = new UriBuilder(schemeName, hostname);
uriBuild.Path = path;
uriBuild.Query = modifiedQuery;
ammendedUrl = uriBuild.Uri;
return ammendedUrl.AbsoluteUri;
}
else
{
return originolUrl.ToString();
}
}
public Uri ToUri()
{
this.ToString();
return ammendedUrl;
}
}
}