Problem with to read a file with SharpSVN - c#

I am having an issue with the SharpSVN api. When I try to use SvnClient.Write() or SvnClient.Export(), the following error occurs:
Malformed URL for repository
My code is the following
using(SvnClient client = new SvnClient())
{
MemoryStream ms = new MemoryStream();
client.Authenticator.DefaultCredentials = new NetworkCredential("master","master");
SvnTarget t1 = new SvnUriTarget(new Uri("http://ETAB-APP:81/repositorio/"));
SvnTarget t2 = new SvnUriTarget(new Uri("http://ETAB-APP:81/repositorio/Registro e Controle Acadêmico/Administração/0000/Dossiê do Aluno - ADEMIR JOSPE SANGALLI - (2001193) - Curso (000)/DOC ADICIONAL(264839).pdf"));
client.Write(t2, ms);
client.Export(t2, "C:\\chups");
}
It's driving me insane because if I try to execute this method using t1 as SvnTarget, everything works fine. But the problem is that I can't export all the repository everytime I want to get an especific file.
I tried to put an "#" before the name of URL i.e.
http://#ETAB-APP:81/repositorio/Registro e Controle Acadêmico/Administração/0000/Dossiê do Aluno - ADEMIR JOSPE SANGALLI - (2001193) - Curso (000)/DOC ADICIONAL(264839).pdf
but nothing happens.
What am I doing wrong?
PS: Sorry if I did any mistake, I am brazilian and my english is not very good

What I have found is that if you simply pass an arbitrary URL to the Uri object constructor, it will create an invalid Uri that SVN does not understand. This can be due to foreign characters or escaping of certain characters that does not need to be escaped by the default Uri object constructor.
Break up the Uri into its parts by using the UriBuilder object and then pass the resulting Uri to SVN.
// Build Uri by explicitly specifying the constituent parts.
UriBuilder uriBuilder = new UriBuilder("http", "ETAB-APP", 81, "/repositorio/Registro e Controle Acadêmico/Administração/0000/Dossiê do Aluno - ADEMIR JOSPE SANGALLI - (2001193) - Curso (000)/DOC ADICIONAL(264839).pdf");
using(SvnClient client = new SvnClient())
{
MemoryStream ms = new MemoryStream();
client.Authenticator.DefaultCredentials = new NetworkCredential("master","master");
SvnTarget t2 = new SvnUriTarget(uriBuilder.Uri);
client.Write(t2, ms);
client.Export(t2, "C:\\chups");
}

when I call sharpsvn to get svn info by url (that contains '&',and end of '/').sharp svn throw an exception.
thanks sbrogers :
Do you need to escape the url? The SVN Api may do it for you, but it
might be worth trying running it through
msdn.microsoft.com/en-us/library/… – sbrogers Dec 29 '10 at 14:05
I use this code
SvnUriTarget repos = new SvnUriTarget(myUrlString.TrimEnd(new char[] { '/' }));
my problem is resolved.

Related

How to convert image path to http url in asp.net web api?

My Main domain is http://172.27.88.111. I have a relative path to a image file like Media/myimg.jpg
I need to convert this path into a full URL with the help of REST API in asp.net.
I want the output for the image path in POSTMAN something like
http://172.17.88.111/Media/myimg.jpg
Using a LINQPad script as an example, here are 3 examples - but the use of the 'Uri' class is generally the best way to advocate:
void Main()
{
var baseUrlStr = #"http://172.27.88.111";
var relUrlStr = #"/Media/myimg.jpg";
// # 1
var baseUri = new Uri(baseUrlStr);
var relUri = new Uri(relUrlStr, UriKind.Relative);
var absUri = new Uri(baseUri, relUri);
Console.WriteLine(absUri);
// # 2
Console.WriteLine($"{baseUrlStr}{relUrlStr}");
// # 3
Console.WriteLine(baseUrlStr + relUrlStr);
}
This should give the following output:
http://172.27.88.111/Media/myimg.jpg
http://172.27.88.111/Media/myimg.jpg
http://172.27.88.111/Media/myimg.jpg

Bug? System.UriFormatException: Invalid URI: The URI scheme is not valid

The strings are identical but when passed as a variable it is not valid?
What the hell is going on? Is it a language bug? I'm running this in C# .Net Core
var postUrl = "​http://www.contoso.com";
var postUri = new Uri("http://www.contoso.com"); // works
var uri = new Uri(postUrl); // does not work
If you pulling your hair, then it because there is space after first opening quote in postUrl. Please remove that space & your bug will be begone.
Worked around the problem by using.
var postUrl = "​http://www.contoso.com";
var uriBuilder = new UriBuilder(postUrl);
var uri = uriBuilder.Uri
Still wondering wtf?
Just the daily wtf of a programmer doing his job.

How to create new AutoML DataSet for simple classification (C#)

As part of ML automation process I want to dynamically create new AutoML model. I'm using C# (.net framework) and Google.Cloud.AutoML.V1.
After trying to run CreateDataSet code:
var autoMlClient = AutoMlClient.Create();
var parent = LocationName.FromProjectLocation(_projectId, _locationId);
var dataset = new Google.Cloud.AutoML.V1.Dataset();
dataset.DisplayName = "NewDataSet";
var response = autoMlClient.CreateDataset(parent, dataset);
I get the following error:
Field: dataset.dataset_metadata; Message: Required field not set
According to this user manual I should set Dataset Metadata Type, but the list contains only specific types of classifications (Translation/ImageClassifications etc.), I can't find a simple classification type.
How do I create a simple classification data set with the API ? in the AutoML UI its just with a simple button click ("NEW DATASET") - and have to provide only name & region - no classification type.
I also tried to set:
dataset.TextClassificationDatasetMetadata =
new TextClassificationDatasetMetadata() { ClassificationType = ClassificationType.Multiclass };
But I was unable to import data to it (got too many errors of invalid inputs from the input CSV file), I guess its related to the reason that the input format is not suitable for Text Classification.
UPDATE
I've just notice that the Nuget works with AutoML v1 but v1 beta does contains TablesDatasetMetadata Dataset Metadata Type for normal classifications. I'm speechless.
I also experienced this scenario today while creating a dataset using the NodeJS client. Since the Google AutoML table service is in the beta level you need to use the beta version of the AutoML client. In the Google cloud documentation they have used the beta client to create a dataset.
In NodeJS importing the beta version require('#google-cloud/automl').v1beta1.AutoMlClient instead of importing the normal version (v1) require('#google-cloud/automl').v1 worked for me to successfully execute the create dataset functionality.
In C# you can achieve the same through a POST request. Hope this helps :)
After #RajithaWarusavitarana comment, and my last question update , below is the code that did the trick. The token is being generated by GoogleClientAPI nuget and AutoML is handled by REST.
string GcpGlobalEndPointUrl = "https://automl.googleapis.com";
string GcpGlobalLocation = "us-central1"; // api "parent" parameter
public string GetToken(string jsonFilePath)
{
var serviceAccountCredentialFileContents = System.IO.File.ReadAllText(jsonFilePath);
var credentialParameters = NewtonsoftJsonSerializer.Instance.Deserialize<JsonCredentialParameters>(serviceAccountCredentialFileContents);
var initializer = new ServiceAccountCredential.Initializer(credentialParameters.ClientEmail)
{
Scopes = new List<string> { "https://www.googleapis.com/auth/cloud-platform" }
};
var cred = new ServiceAccountCredential(initializer.FromPrivateKey(credentialParameters.PrivateKey));
string accessToken = cred.GetAccessTokenForRequestAsync("https://oauth2.googleapis.com/token").Result;
return accessToken;
}
public void GetDataSetList(string projectId, string token)
{
var restClient = new RestClient(GcpGlobalEndPointUrl);
var createDataSetReqUrl = $"v1beta1/projects/{projectId}/locations/{GcpGlobalLocation}/datasets";
var createDataSetReq = new RestRequest(createDataSetReqUrl, Method.GET);
createDataSetReq.AddHeader("Authorization", $"Bearer {token}");
var createDatasetResponse = restClient.Execute(createDataSetReq);
createDatasetResponse.Dump();
}
I took the token generation code from google-api-dotnet-client Test File

Sitecore 7 Lucene.Net.Contrib highlight search results

I am trying to do highlighting on the search results. Here is the relevant part of my code.
QueryScorer scorer = new QueryScorer(q);
Lucene.Net.Search.Highlight.IFormatter formatter = new SimpleHTMLFormatter("<b>", "</b>");
Lucene.Net.Search.Highlight.Highlighter highlighter = new Highlighter(formatter, scorer);
highlighter.TextFragmenter = new SimpleFragmenter(800);
Lucene.Net.Util.Version vers = new Lucene.Net.Util.Version();
vers = Lucene.Net.Util.Version.LUCENE_30;
TokenStream stream = new StandardAnalyzer(vers).TokenStream(string.Empty, new StringReader(text));
string s = string.Empty;
try
{
s = highlighter.GetBestFragments(stream, text, 10, "...");
}
Here, GetBestFragments method throws a System.MissingMethodException.
I have tried to replace the original Lucene.net dll with Lucene.Net.Contrib but this time, I dont know what I should write instead of TokenStream. It doesnt exist in Lucene.Net.Contrib.* dlls.
I am working on existing code and I need to find out how I can rewrite TokenStream class and GetBestFragments method.
Thanx
The problem was something about deployment, that the new compatible Lucene.dll was replaced by the incompatible Sitecore7 dll.
So, if both lucene.net and lucene.net.contrib dll are referenced, it should work.
Not directly the solution to my question, but this source is worth mentioning again. (About lucene.dll versions) : http://laubplusco.net/sitecore-7-lucen-3-0-highlighted-results/

URL sometimes not being properly encoded - threading issue?

I am working on a Windows Form application in C# and have a method like the following which is being accessed by multiple threads (precisely, by multiple background workers):
public Uri signURL(OAuthToken token, string url)
{
UriBuilder builder = new UriBuilder(addOAuthParameters(url));
NameValueCollection query = HttpUtility.ParseQueryString(builder.Query);
query.Set("oauth_consumer_key", consumerKey);
/*
* & sometimes not replaced by %26
*/
query.Set("oauth_signature", consumerSecret + "&" + token.Secret);
query.Set("oauth_token", token.Token);
builder.Query = query.ToString();
return builder.Uri;
}
I use this method to sign an arbitrary URL with some required OAuth parameters and afterwards do an HttpWebRequest to retrieve the content.
Edit 1: Here is the content of the addOAuthParameter method:
private Uri addOAuthParameters(string uri)
{
UriBuilder builder = new UriBuilder(uri);
NameValueCollection query = HttpUtility.ParseQueryString(builder.Query);
query.Set("oauth_signature_method", "PLAINTEXT");
query.Set("oauth_timestamp", "" + (int)(DateTime.UtcNow -
new DateTime(1970, 1, 1)).TotalSeconds);
query.Set("oauth_nonce", "" + getNonce());
query.Set("oauth_version", "1.0");
builder.Query = query.ToString();
return builder.Uri;
}
Sometimes, the oauth_signature parameter contains an ampersand although this should be properly encoded with %26 by the NameValueCollection object, and, as result, I get a "401 Unauthorized". I have the feeling this happens when the method is being accessed by multiple background workers (multiple threads?). Is that possible?
Edit 2: Okay, it seems that I've narrowed down the issue. If I do a Debug.Assert(builder.Uri.ToString().Contain("%26") && builder.Uri.PathAndQuery.Contains("%26")); it turns out that builder.Uri.ToString() does not contain the %26 while builder.Uri.PathAndQuery does. Now, why's that?
Debugging the issue turned out to be very hard. Does anyone have any suggestions?
Uri.ToString is for display only the docs state that it returns an un-escaped string.
You want to use Uri.AbsoluteUri, Uri.OriginalString or Uri.GetComponents.
var uri = new Uri("http://example.com/some?query=testing%26other");
Console.WriteLine(uri.ToString());
Console.WriteLine(uri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped));
http://example.com/some?query=testing&other
/some?query=testing%26other
GetComponents has the advantage that the escaping is explicitly specified so there's no ambiguity.
Some simple advice (originally from Keith Brown's blog post, Beware Uri.ToString).
Use Uri.AbsoluteUri to get the value of a URI when you know it’s absolute.
Use Uri.OriginalString to get the value of a URI when it could be either absolute or relative (this method does not throw an InvalidOperationException for a relative URI).
Use Uri.ToString to get the value of a URI only when you really want it to be unescaped (e.g. when you want to display it nicely for a human).
When viewing a URI in the debugger, remember the debugger uses Uri.ToString so what you see may not match exactly what the URI contains.

Categories