Console not writing - c#

using System;
using System.Net;
static class Program {
public static void Main()
{
WebClient wc = new WebClient();
var proxies = wc.DownloadString(#"http://proxy-ip-list.com/download/free-proxy-list.txt");
Console.WriteLine("http://" + proxies.Split(';')[5]);
Console.ReadLine();
}
}
I'm very much baffled...
I tried printer Char-by-Char.
I tried assigning the string to a variable before writing.
I've tried everything, what's going on?
Console.WriteLine("http://" + "182.255.46.123:8080"); works...

It's because the string being returned contains a carriage-return character at the beginning:
proxies.Split(';')[5] = " \r182.255.46.123:8080"
You can remove it like this:
Console.WriteLine("http://" + proxies.Split(';')[5].Replace("\r", "").Trim());

Try this:
using System;
using System.Text.RegularExpressions;
using System.Net;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
WebClient wc = new WebClient();
var proxies = wc.DownloadString(#"http://proxy-ip-list.com/download/free-proxy-list.txt");
var regex = new Regex(#"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,5}");
var match = regex.Matches(proxies);
Console.WriteLine("http://" + match[3].Value);
Console.ReadLine();
}
}
}
Is most save in case of changes in content of the request result.

Updated answer as per your comment. You just need to Trim() to remove all white spaces from start and end.
using System;
using System.Net;
static class Program
{
public static void Main()
{
WebClient wc = new WebClient();
var proxies = wc.DownloadString(#"http://proxy-ip-list.com/download/free-proxy-list.txt");
Console.WriteLine("http://" + proxies.Split(';')[5].Trim());
Console.ReadLine();
}
}

Related

How to convert azure vision output in string Json to previous object?

I have converted the input image into OCRResults by using these codes.
https://learn.microsoft.com/en-us/azure/cognitive-services/computer-vision/quickstarts-sdk/client-library?tabs=visual-studio&pivots=programming-language-csharp
using System;
using System.Collections.Generic;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading;
using System.Linq;
namespace ComputerVisionQuickstart
{
class Program
{
// Add your Computer Vision subscription key and endpoint
static string subscriptionKey = "PASTE_YOUR_COMPUTER_VISION_SUBSCRIPTION_KEY_HERE";
static string endpoint = "PASTE_YOUR_COMPUTER_VISION_ENDPOINT_HERE";
private const string READ_TEXT_URL_IMAGE = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/printed_text.jpg";
static void Main(string[] args)
{
Console.WriteLine("Azure Cognitive Services Computer Vision - .NET quickstart example");
Console.WriteLine();
ComputerVisionClient client = Authenticate(endpoint, subscriptionKey);
// Extract text (OCR) from a URL image using the Read API
ReadFileUrl(client, READ_TEXT_URL_IMAGE).Wait();
}
public static ComputerVisionClient Authenticate(string endpoint, string key)
{
ComputerVisionClient client =
new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
{ Endpoint = endpoint };
return client;
}
public static async Task ReadFileUrl(ComputerVisionClient client, string urlFile)
{
Console.WriteLine("----------------------------------------------------------");
Console.WriteLine("READ FILE FROM URL");
Console.WriteLine();
// Read text from URL
var textHeaders = await client.ReadAsync(urlFile);
// After the request, get the operation location (operation ID)
string operationLocation = textHeaders.OperationLocation;
Thread.Sleep(2000);
// Retrieve the URI where the extracted text will be stored from the Operation-Location header.
// We only need the ID and not the full URL
const int numberOfCharsInOperationId = 36;
string operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);
// Extract the text
ReadOperationResult results;
Console.WriteLine($"Extracting text from URL file {Path.GetFileName(urlFile)}...");
Console.WriteLine();
do
{
results = await client.GetReadResultAsync(Guid.Parse(operationId));
}
while ((results.Status == OperationStatusCodes.Running ||
results.Status == OperationStatusCodes.NotStarted));
// Display the found text.
Console.WriteLine();
var textUrlFileResults = results.AnalyzeResult.ReadResults;
foreach (ReadResult page in textUrlFileResults)
{
foreach (Line line in page.Lines)
{
Console.WriteLine(line.Text);
}
}
Console.WriteLine();
}
}
}
If I converting the output from the azure vision into json.Is any possibilities convert the json to previous object?

How to generate a hash for my Android app?

I'm using this guide to implement an autocomplete funcionality in an app I'm working on, but when I try to test it in different computers it returns me a different hash https://www.c-sharpcorner.com/article/verify-otp-automatically-in-android-without-sms-read-permission-using-xamarin-fo/
The helper class used is the following:
using System.Text;
using Android.Content;
using Android.Content.PM;
using Android.Util;
using Java.Security;
using Java.Util;
namespace InteliMobile.App.Droid.Service
{
public class AppHashKeyHelper
{
private static string HASH_TYPE = "SHA-256";
private static int NUM_HASHED_BYTES = 9;
private static int NUM_BASE64_CHAR = 11;
private static string GetPackageSignature(Context context)
{
var packageManager = context.PackageManager;
var signatures = packageManager.GetPackageInfo(context.PackageName, PackageInfoFlags.Signatures).Signatures;
return signatures.First().ToCharsString();
}
public static string GetAppHashKey(Context context)
{
string keystoreHexSignature = GetPackageSignature(context);
string appInfo = context.PackageName + " " + keystoreHexSignature;
try
{
var messageDigest = MessageDigest.GetInstance(HASH_TYPE);
messageDigest.Update(Encoding.UTF8.GetBytes(appInfo));
byte[] hashSignature = messageDigest.Digest();
hashSignature = Arrays.CopyOfRange(hashSignature, 0, NUM_HASHED_BYTES);
string base64Hash = Android.Util.Base64.EncodeToString(hashSignature, Base64Flags.NoPadding | Base64Flags.NoWrap);
base64Hash = base64Hash.Substring(0, NUM_BASE64_CHAR);
return base64Hash;
}
catch (NoSuchAlgorithmException e)
{
return null;
}
}
}
}
How can I get the hash without using a bash script, since the server runs in a Windows machine? Is it safe to deploy the app to production with the helper class in it?
You don't compute the hash client side. It's sent from the server, and the instructions to do so are at https://developers.google.com/identity/sms-retriever/verify#computing_your_apps_hash_string
You don't do it in code at all, you do it via command line tools.

Nethereum C# how can I get balance in address?

I try to get balance in address.
It is my code:
`using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Nethereum.Web3;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Bananas().Wait();
}
static private async Task Bananas()
{
var publicKey = "0xC0b4ec83028307053Fbe8d00ba4372384fe4b52B";
var web3 = new Nethereum.Web3.Web3("https://ropsten.infura.io/myInfura");
//var txCount = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(publicKey);
var balance = await web3.Eth.GetBalance.SendRequestAsync(publicKey);
var etherAmount = Web3.Convert.FromWei(balance.Value);
Console.WriteLine(web3);
Console.WriteLine("Get txCount ", etherAmount);
Console.ReadLine();
}
}
}`
I installed Nethereum via PM console: Nethereum.
I use a normal link of infura.
Why don`t I get a next result without the balance in address?
I have just made a console application with your code and all the data is coming back fine from Nethereum.
Your issue is with your Console.WriteLine(... You are passing the etherAmount as a arg0 property into the Console.WriteLine which will not output correctly on the console when you run it.
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Nethereum.Web3;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Bananas().Wait();
}
static private async Task Bananas()
{
var publicKey = "0xC0b4ec83028307053Fbe8d00ba4372384fe4b52B";
var web3 = new Nethereum.Web3.Web3("https://ropsten.infura.io/myInfura");
//var txCount = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(publicKey);
var balance = await web3.Eth.GetBalance.SendRequestAsync(publicKey);
var etherAmount = Web3.Convert.FromWei(balance.Value);
Console.WriteLine(web3);
Console.WriteLine("Get txCount " + etherAmount);
Console.ReadLine();
}
}
}
ps nice 1110.337873197299357846 ETH ;) (i know it is only test ETH but we can dream)

Inputting values to a string as a website URL for the page to be downloaded

I'm messing around with the System.Net library in C# and I'm trying to simply have it set up such that you enter an url and it will take that as a string and put that into the parameter for the URl in the Client.DownloadString() field.
Here is my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace StringDownloadTest
{
class GetInformation
{
string EnterString;
public string InputString()
{
EnterString = Console.ReadLine();
return EnterString;
}
}
class DownloadString
{
static void Main(string[] args)
{
GetInformation R = new GetInformation();
R.InputString();
string downloadedString;
System.Net.WebClient client;
client = new System.Net.WebClient();
downloadedString = client.DownloadString(R.InputString());
Console.WriteLine("String: {0}", downloadedString);
}
}
}
Any help here, it will compile but the program crashes.
You're calling R.InputString twice and only entering input for the first time.
Try:
GetInformation R = new GetInformation();
Console.WriteLine("Please enter a valid url protocol://domain");
var input = R.InputString();
Uri uri;
if(!Uri.TryCreate(input, UriKind.Absolute, out uri))
{
Console.WriteLine("Url format could not be determined for {0}", input);
Environment.Exit(1);
}
var client = new System.Net.WebClient();
var downloadedString = client.DownloadString(uri);
Console.WriteLine("String: {0}", downloadedString);

How to connect to Mailman mailing list using .Net

I have to develop a .Net application in which i have to add or remove a user from Mailman mailing list.My Question is whether there is any .Net connector or Dll to connect to mailman mailing list using .Net.
Edit (9/21/14): I have just released a NuGet package for manipulating most aspects of a Mailman v2 list via HTTP calls. https://www.nuget.org/packages/MailmanSharp/
I'm not aware of any existing component to do this, but since the Mailman interface is all on the web, you can "control" it with HttpWebRequest; I recently wrote a small app which can retrieve the subscriber list, subscribe/unsubscribe people, and set individual flags like moderate/nomail/etc. It takes a little poking around in the source of the Mailman pages to see what variables need to be set in the POST, and some trial and error. I suggest setting up a temp Mailman list just to play with.
In order to do most of this, you'll need a persistent CookieContainer that you can hook up to your different HttpWebRequests; the first call is a POST to the admin page with the admin password to set the session cookie that gives you access to the other pages.
Some of the POSTs are regular application/x-www-form-urlencoded types, but some are also multipart/form-data. For the latter, I found some very helpful code at http://www.briangrinstead.com/blog/multipart-form-post-in-c I had to make a couple of changes so that I could pass in my CookieContainer
Here's some sample code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Data;
using System.Threading;
namespace UpdateListserv
{
class Program
{
static void Main(string[] args)
{
try
{
File.Delete(_logFilename);
Log(String.Format("Starting: {0}", DateTime.Now));
Login();
var roster = GetSubscribers();
Unsubscribe(roster);
string members = GetMemberEmails();
Subscribe(members);
Unmoderate("foo#example.com");
Log("Done");
}
catch(Exception e)
{
Log(e.Message);
}
}
private static void Unmoderate(string email)
{
Log("Unmoderating " + email);
email = email.Replace("#", "%40");
_vars.Clear();
_vars["user"] = email;
_vars[email + "_nomail"] = "off";
_vars[email + "_nodupes"] = "on";
_vars[email + "_plain"] = "on";
_vars[email + "_language"] = "en";
_vars["setmemberopts_btn"] = "Submit Your Changes";
FormUpload.MultipartFormDataPost(_adminUrl + _membersPage, "foobar", _vars, _cookies);
}
private static CookieContainer _cookies = new CookieContainer();
private static string _adminUrl = "http://mylist.com/admin.cgi/listname";
private static string _rosterUrl = "http://mylist.com/roster.cgi/listname";
private static string _pw = "myPassword";
private static string _adminEmail = "foo#example.com";
private static Dictionary<string, object> _vars = new Dictionary<string, object>();
private static string _addPage = "/members/add";
private static string _removePage = "/members/remove";
private static string _membersPage = "/members";
private static string _logFilename = "Update Listserv.log";
private static void Log(string message)
{
Console.WriteLine(message);
using (var log = File.AppendText(_logFilename))
log.WriteLine(message);
}
private static void Subscribe(string members)
{
// members is a list of email addresses separated by \n
Log("Subscribing everyone");
_vars.Clear();
_vars["subscribees"] = members;
_vars["subscribe_or_invite"] = 0;
_vars["send_welcome_msg_to_this_batch"] = 0;
_vars["send_notifications_to_list_owner"] = 0;
FormUpload.MultipartFormDataPost(_adminUrl + _addPage, "foobar", _vars, _cookies);
}
private static string GetMemberEmails()
{
// This method retrieves a list of emails to be
// subscribed from an external source
// and returns them as a string with \n in between.
}
private static void Unsubscribe(string roster)
{
// roster is a list of email addresses separated by \n
Log("Unsubscribing everybody");
_vars.Clear();
_vars["unsubscribees"] = roster;
_vars["send_unsub_ack_to_this_batch"] = 0;
_vars["send_unsub_notifications_to_list_owner"] = 0;
FormUpload.MultipartFormDataPost(_adminUrl + _removePage, "foobar", _vars, _cookies);
}
private static string GetSubscribers()
{
// returns a list of email addresses subscribed to the list,
// separated by \n
Log("Getting subscriber list");
var req = GetWebRequest(_rosterUrl);
req.Method = "post";
_vars.Clear();
_vars["roster-email"] = _adminEmail;
_vars["roster-pw"] = _pw;
var rosterLines = GetResponseString(req).Split('\n').Where(l => l.StartsWith("<li>"));
Log(String.Format("Got {0} subscribers", rosterLines.Count()));
var roster = new List<string>();
var regex = new Regex("<a.*>(.*)</a>");
foreach (var line in rosterLines)
{
roster.Add(regex.Match(line).Groups[1].Value.Replace(" at ", "#"));
}
return String.Join("\n", roster);
}
private static void Login()
{
Log("Logging in to list admin panel");
var req = GetWebRequest(_adminUrl);
req.Method = "post";
_vars["adminpw"] = _pw;
SetPostVars(req);
req.GetResponse();
}
private static HttpWebRequest GetWebRequest(string url)
{
var result = HttpWebRequest.Create(url) as HttpWebRequest;
result.AllowAutoRedirect = true;
result.CookieContainer = _cookies;
result.ContentType = "application/x-www-form-urlencoded";
return result;
}
private static string GetResponseString(HttpWebRequest req)
{
using (var res = req.GetResponse())
using (var stream = res.GetResponseStream())
using (var sr = new StreamReader(stream))
{
return sr.ReadToEnd();
}
}
private static void SetPostVars(HttpWebRequest req)
{
var list = _vars.Select(v => String.Format("{0}={1}", v.Key, v.Value));
using (var stream = req.GetRequestStream())
using (var writer = new StreamWriter(stream))
{
writer.Write(String.Join("&", list));
}
}
}
}

Categories