The Namespace X already contains a definition for XX? - c#

I don't understand this error I am getting. I have tried to clean and build my project several times. Can anyone help me?
Program.cs
using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.IO;
using System.Threading.Tasks;
namespace HTTPrequestApp
{
class Program
{
static void Main(string[] args)
{
var lstWebSites = new List<string>
{
"www.mearstransportation.com",
"www.amazon.com",
"www.ebay.com",
"www.att.com",
"www.verizon.com",
"www.sprint.com",
"www.centurylink.com",
"www.yahoo.com"
};
string filename = #"RequestLog.txt";
{
using (var writer = new StreamWriter(filename, true))
{
foreach (string website in lstWebSites)
{
for (var i = 0; i < 4; i++)
{
MyWebRequest request = new MyWebRequest();
request.Request(website);
}
}
}
}
}
}
}
MyWebRequest.cs - the problem is here: public class MyWebRequest
Error is: "The namespace HttpRequestApp already contains a definition for MyWebRequest"
using HTTPrequestApp.MyWebRequest;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace HTTPrequestApp
{
public class MyWebRequest : IWebRequest
{
public void Request(string strWebSite)
{
List<string> lstWebSites = Program.GetList(strWebSite);
using (var client2 = new TcpClient(strWebSite, 80))
{
using (NetworkStream stream = client2.GetStream())
using (StreamWriter writer = new StreamWriter(stream))
using (StreamReader reader2 = new StreamReader(stream))
{
//writer.AutoFlush = true;
writer.WriteLine("GET / HTTP/1.1");
writer.WriteLine("HOST: {0}:80", lstWebSites[1]);
writer.WriteLine("Connection: Close");
writer.WriteLine();
writer.WriteLine();
string theresponse = reader2.ReadToEnd();
Console.WriteLine(theresponse);
}
}
}
}
}
IWebRequest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using System.IO;
using System.Threading.Tasks;
//using MyWebRequest.Lib;
namespace HTTPrequestApp.MyWebRequest
{
public interface IWebRequest
{
Task<List<strWebSite>> GetList();
void Request();
}
}
To give an over view of what I am trying to accomplish here is: Send HTTP request to get the initial page. Get back the HTTP response and check that it is a 200 response code. And time how long it took to retrieve the response.
This is a console app but I need to not have it depend on the console, it needs to be an independent application so I can use it somewhere else.
If anyone has any suggestions on how I can simplify my code please let me know.
thanks.

You have a HTTPrequestApp.MyWebRequest namespace and a HTTPrequestApp.MyWebRequest class name: c# compiler get confused (and human too...)
Consider renaming the namespace in something such HTTPrequestApp.MyWebRequestNameSpace if you really want a different namespace.

Related

Uploading large blobs to azure using azure-sdk-for-net is timing out

I am attempting to use c# and the Azure.Storage.Blobs.Specialized.BlockBlobClient to upload large files. I am encountering time-outs. I need a sample that shows how to upload large files (approx 300MB). I have not been able to find a good example.
using Azure.Storage.Blobs.Specialized;
...
using (var fs = fileInfo.Open(FileMode.Open,FileAccess.Read))
{
var blockBlobClient = new BlockBlobClient(
connectionString,
"ore",
fileInfo.Name);
await blockBlobClient.UploadAsync(fs);
}
I had to adjust the network timeout.
var uploadManager = new UploadManager();
await uploadManager.UploadBlob(connectionString, container, fileInfo);
This class handles large uploads, increases the network timeout and provides a Progress output.
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs.Specialized;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Uploader
{
public class UploadManager
{
System.Collections.Concurrent.ConcurrentBag<long> progressBag = null;
Progress<long> progressHandler = null;
public UploadManager()
{
progressBag = new System.Collections.Concurrent.ConcurrentBag<long>();
progressHandler = new Progress<long>(progress => progressBag.Add(progress));
progressHandler.ProgressChanged += ProgressHandler_ProgressChanged;
}
public async Task UploadBlob(string connectionString, string container, FileInfo fileInfo)
{
using (var fs = fileInfo.Open(FileMode.Open, FileAccess.Read))
{
var clientOptions = new BlobClientOptions();
clientOptions.Retry.NetworkTimeout = new TimeSpan(0, 0, 600);
var blockBlobClient = new BlockBlobClient(connectionString, container, fileInfo.Name, clientOptions);
var uploadOptions = new BlobUploadOptions();
uploadOptions.ProgressHandler = progressHandler;
await blockBlobClient.UploadAsync(fs, uploadOptions);
}
}
private static void ProgressHandler_ProgressChanged(object sender, long e)
{
Debug.WriteLine($"Progress:{(e / 1000).ToString()} MB");
}
}
}

Nethereum EthECKey not working. Scripts are not compiled

If i add this line to my code then it refuses to compile!(This happens with All scripts in unity, even empty ones)
string publicKey = Nethereum.Signer.EthECKey.GetPublicAddress(privatekey);
Code:
using System.Collections;
using System;
using System.Collections.Generic;
using Nethereum.Util;
using UnityEngine;
using System.Threading.Tasks;
using Nethereum.Hex.HexConvertors.Extensions;
using Org.BouncyCastle.Crypto.Digests;
using System.Linq;
using System.Text;
using Nethereum.Util.Keccak;
using System.Numerics;
using System.Runtime.CompilerServices;
using Nethereum.RLP;
using Nethereum.Signer.Crypto;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Agreement;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
public class MianScript : MonoBehaviour
{
string chain = "ethereum";
string network = "rinkeby";
[SerializeField]
public string password;
public void OnClickBTN()
{
string privatekey = CreateAccount();
string publicKey = Nethereum.Signer.EthECKey.GetPublicAddress(privatekey);
Debug.Log("\nPrivate: " + privatekey + "\nPublicKey: " + publicKey);
}
public byte[] CalculateHash(byte[] value)
{
var digest = new KeccakDigest(256);
var output = new byte[digest.GetDigestSize()];
digest.BlockUpdate(value, 0, value.Length);
digest.DoFinal(output, 0);
return output;
}
public async Task<String> GetBalance(string chain1, string network1, string address1)
{
string balance = await EVM.BalanceOf(chain1, network1, address1);
return balance;
}
public static string CreateAccount()
{
System.Random random = new System.Random();
var bytes = new Byte[32];
random.NextBytes(bytes);
var hexArray = Array.ConvertAll(bytes, x => x.ToString("X2"));
var hexStr = String.Concat(hexArray);
return Convert.ToString(hexStr.ToLower());
}
}
Help pls!
I'm not using unity, C# either but it seems that GetPublicAddress() is not a static function but a class method.
So I think you need to do something like that:
// Creating an EthECKey instance
var key = new Nethereum.Signer.EthECKey(privateKey.HexToByteArray(), true);
// Getting the public Address
string publicKey = key.GetPublicAddress();
I simply checked examples from here.

how to print each line of text file using below Rx.Net code?

Problem Statement - I have a file continuously written by a process line by line. I would like a C# solution which will print line by line as soon as it is written by the process.
Solution - I would like to use Reactive extension C#, where I will subscribe the stream.
I tried below code, but how to print each line,
stream.Subscribe(e => Console.WriteLine(e.//how to print each line));
Here is full code,
using System;
using System.Collections.Generic;
using System.IO;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
using (FileStream fs = new FileStream(#"C:\Files\test_Copy.txt", FileMode.Open))
{
var stream = ObserveLines(fs);
stream.Subscribe(e => Console.WriteLine(e.//how to print each line));
}
}
public static IObservable<string> ObserveLines(Stream inputStream)
{
return ReadLines(inputStream).ToObservable(Scheduler.ThreadPool);
}
public static IEnumerable<string> ReadLines(Stream stream)
{
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
yield return reader.ReadLine();
}
}
}
}

Modify a printTicket

I'm trying to modify a print ticket since many days. :(
Here is the code :
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Printing;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Drawing.Printing;
using System.Drawing;
using System.Xml;
// ....
// Get the ticket
var printQueue = new PrintServer("\\\\NetworkNameHere").GetPrintQueue("PrinterNameHere");
PrintTicket userPrintTicket = printQueue.UserPrintTicket;
// Modify the ticket to print in landscape (or any other option)
var xmlDoc = new XmlDocument();
xmlDoc.Load(userPrintTicket.GetXmlStream());
var manager = new XmlNamespaceManager(xmlDoc.NameTable);
manager.AddNamespace(xmlDoc.DocumentElement.Prefix, xmlDoc.DocumentElement.NamespaceURI);
string xpath = string.Format("//psf:Feature[#name='{0}']/psf:Option", "psk:PageOrientation");
XmlNode node = xmlDoc.SelectSingleNode(xpath, manager);
node.Attributes["name"].Value = "psk:Landscape";
PrintTicket modifiedPrintTicket = null;
using (var stream = new MemoryStream())
{
xmlDoc.Save(stream);
stream.Position = 0;
modifiedPrintTicket = new PrintTicket(stream);
}
System.Printing.ValidationResult result = printQueue.MergeAndValidatePrintTicket(printQueue.UserPrintTicket, modifiedPrintTicket);
printQueue.UserPrintTicket = result.ValidatedPrintTicket;
MessageBox.Show(result.ValidatedPrintTicket.PageOrientation.Value.ToString());
printQueue.Commit();
Byte[] myByteBuffer = UnicodeEncoding.Unicode.GetBytes("This is a test string for the print job stream.");
using (var job = printQueue.AddJob())
using (var stream = job.JobStream)
{
stream.Write(myByteBuffer, 0, myByteBuffer.Length);
stream.Close();
}
The problem :
Look like the ticket is correctly modified, but for some reasons it never use the information specified in the ticket for any option. HELP!!!!
Note that I'm using .Net 4.0 but I get the same result with the new PrintTicket parameter in addJob (4.5) : printQueue.AddJob("xx", result.ValidatedPrintTicket)
Thanks!

Trouble getting groups out of Regex

The following code only returns "Good job!" How can I get the actual URLs out of it? I followed the tutorial on the site given, and I'm still having a bit trouble wrapping my head around it. Also, I imagine that this isn't the best way to go about regex (mixing regex with html). Is there a simple way to capture text based on it's CSS class?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
namespace Scraper
{
class Program
{
static void Main(string[] args)
{
string target = #"http://www.omegacoder.com/?p=58";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(target);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Regex URL = new Regex("(?:href=)(?<link>.*?)");
string line;
using (Stream responseStream = response.GetResponseStream())
using (StreamReader htmlStream = new StreamReader(responseStream))
while ((line = htmlStream.ReadLine()) != null){
Match m = URL.Match(line);
if (m.Success) {
Console.WriteLine("Good job! " + URL.Match(line) + m.Groups[0].Value + m.Groups[1].Value + m.Groups["link"]);
Console.ReadLine();
} else {
}
}
/* if (Regex.IsMatch(line, "XXXXX"))
Console.WriteLine(line);
} */
Console.ReadLine();
}
}
}
You should use (?:href=)(?<link>\S*)
\S matches a character that is not space

Categories

Resources