Have a .Net Backend service on Azure and I'd like to make my REST urls kind of 'nicer'...
Currently as:
Want it to be:
The 'api.domain.com' is achieved through DNS, now how to get rid of the 'api' part?
Have a .Net Backend service on Azure and I'd like to make my REST urls kind of 'nicer'...
Currently as:
Want it to be:
The 'api.domain.com' is achieved through DNS, now how to get rid of the 'api' part?
We have a scenario in our client project where the client application saves and tries to fetch files from a shared folder location , which is a virtual shared folder. But we have been facing issues with a specific application user id losing access to that shared folder. So we need help in pre advance checking if the access is present for that user id on that shared folder location . So thinking of an application to be developed in C# or vb.net to check for that user access.
I asked a question yesterday and, unfortunately, even with the answers provided, I'm still hitting up on stumbling blocks about how to do things correctly... My issue is that my code actually works, but I'm a complete novice at concurrency programming and it feels like I'm not programming the correct way and, most importantly, I'm afraid of developing bad habits.
To make up a simplistic example to elaborate on yesterday's question, suppose I had the following methods:
static Task<IEnumerable<MyClass>> Task1(CancellationToken ct)
static Task<IEnumerable<int>> Task2(CancellationToken ct, List<string> StringList)
static Task<IEnumerable<String>> Task3(CancellationToken ct)
static Task<IEnumerable<Double>> Task4(CancellationToken ct)
static Task Task5(CancellationToken ct, IEnumerable<int> Task2Info, IEnumerable<string> Task3Info, IEnumerable<double> Task4Info)
static Task Task6(CancellationToken ct, IEnumerable<int> Task2Info, IEnumerable<MyClass> Task1Info)
And the code I've written that utilizes them looks as follows:
static Task execute(CancellationToken ct)
{
IEnumerable<MyClass> Task1Info = null;
List<string> StringList = null;
IEnumerable<int> Task2Info = null;
IEnumerable<string> Task3Info = null;
IEnumerable<double> Task4Info = null;
var TaskN = Task.Run(() =>
{
Task1Info = Task1(ct).Result;
}
, ct)
.ContinueWith(res =>
{
StringList = Task1Info.Select(k=> k.StringVal).ToList();
Task2Info = Task2(ct, StringList).Result;
}
, ct);
return Task.Run(() =>
{
return Task.WhenAll
(
TaskN,
Task.Run(() => { Task3Info = Task3(ct).Result; }, ct),
Task.Run(() => { Task4Info = Task4(ct).Result; }, ct)
)
.ContinueWith(res =>
{
Task5(ct, Task2Info, Task3Info, Task4Info).Wait();
}
, ct)
.ContinueWith(res =>
{
Task6(ct, Task2Info, Task1Info).Wait();
}
, ct);
});
}
In other words:
Task1 to calculate StringList and to run Task2Task2, Task3 and Task4 can all run concurrentlyTask5Task5 is run, I use all the results in running Task6As a simple explanation, imagine the first portion is data gathering, the second is data cleansing and the third data reporting
Like I said, my challenge is that this actually runs, but I simply feel that it's more of a "hack" that the right way to program - Concurrency programming is very new to me and I definitely want to learn the best ways this should be done...
I have a console job for generting pdfs(to generate 10000 pdfs)
Can any one suggest what may be the issue while running through task scheduler.
Suggest me any software to find any memory leaks, GC Collect, Windows Handles utilized.
When I compile and run the code to my application, the buttons and text from that window doesn't appear in the same location on the running application as in the designer tab. All other windows appear correctly when run. Any ideals? Here are a few pictures of the problem.
Picture of the designer: http://ift.tt/1DXAfSK
Picture of the program when running: http://ift.tt/1JC5fhx
I read on Scott Hanselman's Blog, "I'm using Visual Studio 2015 to edit even .NET 2.0 apps so I'm not using older versions of VS," .
I also support old .Net solutions that open in previous versions of Visual Studio (2005, 2008, 2010, 2013). Is it possible with VS2015 to open these old solutions with out upgrading them?
I don't mind if they don't target the latest framework, it would just be handy to use a single version of Visual Studio rather than have 5 versions installed side by side.
I am noob in security sorry for that. I have an xml file which include,
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<ID_VG_Response>
<Result>
<SubjectDN>CN="XX", SERIALNUMBER=XX/XX, C=IN</SubjectDN>
<UserIDN>XX</UserIDN>
<CardNumber>XX</CardNumber>
<TransactionType>XX</TransactionType>
<Status>Success</Status>
</Result>
<Validity>180</Validity>
<SignatureTime>
<date>20150726</date>
<time>15:01:51:927</time>
</SignatureTime>
<Signature xmlns="http://ift.tt/uq6naF">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://ift.tt/1roZfRO" />
<SignatureMethod Algorithm="http://ift.tt/18jbiFB" />
<Reference URI="">
<Transforms>
<Transform Algorithm="http://ift.tt/A1C4L2" />
</Transforms>
<DigestMethod Algorithm="http://ift.tt/1jbsD3O" />
<DigestValue>XXX</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>XXXXXXXXXX</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>XXXX</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>
</ID_VG_Response>
and some cer files. Now I need to verify the SignatureValue using the cer files in C#. Can anyone help me please? One of colleague sent me a java file to validate this but I need to do this in C#? Here is java code,
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PublicKey;
import java.security.SignatureException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import javax.security.cert.CertificateException;
import javax.security.cert.X509Certificate;
import javax.xml.crypto.AlgorithmMethod;
import javax.xml.crypto.KeySelector;
import javax.xml.crypto.KeySelectorException;
import javax.xml.crypto.KeySelectorResult;
import javax.xml.crypto.XMLCryptoContext;
import javax.xml.crypto.XMLStructure;
import javax.xml.crypto.dsig.SignatureMethod;
import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.crypto.dsig.dom.DOMValidateContext;
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import javax.xml.crypto.dsig.keyinfo.X509Data;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import sun.misc.BASE64Decoder;
import sun.security.x509.X509CertImpl;
public class XMLSignatureValidator {
private String userIDN;
public static void main(String[] args) throws Exception {
XMLSignatureValidator validator = new XMLSignatureValidator();
//boolean verified = validator.verifyVGResponse(new FileInputStream(
// "C:/ID_VG_Response.xml"), "CA");
FileInputStream fis = new FileInputStream("C:/ID_VG_Response.xml");
byte[] data = new byte[fis.available()];
fis.read(data);
fis.close();
boolean verified = validator.verifyVGResponse(new String(data),
"E:/EIDA Toolkit/VG Related/ADSIC_Prod/VG Response Cert");
System.out.println(verified);
}
public boolean verifyVGResponse(final String vgResponse,
final String cAFolderPath) throws Exception {
byte[] xml = new BASE64Decoder().decodeBuffer(vgResponse);
return verifyVGResponse(new ByteArrayInputStream(xml), cAFolderPath);
}
public boolean verifyVGResponse(final InputStream vgResponse,
final String cAFolderPath) throws Exception {
X509Certificate[] certificates = getCertificates(cAFolderPath);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse(vgResponse);
NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS,
"Signature");
if (nl.getLength() == 0) {
throw new Exception("Cannot find Signature element");
}
final X509KeySelector keySelector = new X509KeySelector();
DOMValidateContext valContext = new DOMValidateContext(keySelector,
nl.item(0));
XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM",
new org.jcp.xml.dsig.internal.dom.XMLDSigRI());
final XMLSignature signature = factory
.unmarshalXMLSignature(valContext);
// Verify signature.
boolean coreValidity = signature.validate(valContext);
if (coreValidity) {
// Verify the complete certificate chain.
final X509CertImpl signerCertImpl = (X509CertImpl) keySelector
.getSignerCertificate();
final X509Certificate signerCert = javax.security.cert.X509Certificate
.getInstance(signerCertImpl.getEncoded());
boolean verified = verifyCertificate(signerCert, certificates);
if (verified) {
NodeList nl2 = doc.getElementsByTagName("Status");
if (!nl2.item(0).getFirstChild().getNodeValue()
.equalsIgnoreCase("Success")) {
throw new Exception("Status element not set to success");
}
long signerTime = new SimpleDateFormat("yyyyMMdd HH:mm:ss:SSS")
.parse(doc.getElementsByTagName("date").item(0)
.getFirstChild().getNodeValue()
+ " "
+ doc.getElementsByTagName("time").item(0)
.getFirstChild().getNodeValue())
.getTime();
int validitySec = Integer.parseInt(doc
.getElementsByTagName("Validity").item(0)
.getFirstChild().getNodeValue());
System.out.println("signer time: " + signerTime);
System.out.println("signer time date: " + new Date(signerTime));
System.out.println("validitySec: " + validitySec);
System.out.println("validitySec * 1000: " + validitySec * 1000);
Date d = new Date();
System.out.println("Date on the server is: " + d);
System.out.println("Date on server in milliseconds: " + d.getTime());
System.out.println(d.getTime() > signerTime + validitySec * 1000);
if (d.getTime() > signerTime + validitySec * 1000) {
throw new Exception("VG response expired");
}
userIDN = doc.getElementsByTagName("UserIDN").item(0)
.getFirstChild().getNodeValue();
return true;
} else {
throw new Exception("Certificate Not Valid");
}
}
throw new Exception("Signature Not Valid");
}
// CHECKSTYLE_IGNORE_START
private final boolean verifyCertificate(final X509Certificate signerCert,
final X509Certificate[] certificates) throws InvalidKeyException,
NoSuchAlgorithmException, NoSuchProviderException,
SignatureException, CertificateException {
// CHECKSTYLE_IGNORE_END
signerCert.checkValidity();
X509Certificate issuerCert = null;
String issuerDN = signerCert.getIssuerDN().getName();
for (int i = 0; i < certificates.length; i++) {
if (certificates[i].getSubjectDN().getName().equals(issuerDN)) {
issuerCert = certificates[i];
break;
}
}
if (issuerCert == null) {
return false;
}
signerCert.verify(issuerCert.getPublicKey());
for (int i = 0; i < certificates.length; i++) {
if (signerCert.getSerialNumber().equals(
certificates[i].getSerialNumber())) {
return true;
}
}
return false;
}
// CHECKSTYLE_IGNORE_START
private class SimpleKeySelectorResult implements KeySelectorResult {
Key pk = null;
SimpleKeySelectorResult(Key _pk) {
pk = _pk;
}
// @Override
public Key getKey() {
return pk;
}
}
// CHECKSTYLE_IGNORE_END
public class X509KeySelector extends KeySelector {
private X509CertImpl cert;
@SuppressWarnings("rawtypes")
public KeySelectorResult select(KeyInfo keyInfo,
KeySelector.Purpose purpose, AlgorithmMethod method,
XMLCryptoContext context) throws KeySelectorException {
Iterator ki = keyInfo.getContent().iterator();
while (ki.hasNext()) {
XMLStructure info = (XMLStructure) ki.next();
if (!(info instanceof X509Data)) {
continue;
}
X509Data x509Data = (X509Data) info;
Iterator xi = x509Data.getContent().iterator();
while (xi.hasNext()) {
Object o = xi.next();
if (o instanceof X509Certificate) {
// Currently not used, the object returned is
// X509CertImpl
PublicKey key = ((X509Certificate) o).getPublicKey();
// Make sure the algorithm is compatible
// with the method.
if (algEquals(method.getAlgorithm(), key.getAlgorithm())) {
return new SimpleKeySelectorResult(key);
}
}
if (o instanceof X509CertImpl) {
cert = ((X509CertImpl) o);
PublicKey key = ((X509CertImpl) o).getPublicKey();
// Make sure the algorithm is compatible
// with the method.
if (algEquals(method.getAlgorithm(), key.getAlgorithm())) {
return new SimpleKeySelectorResult(key);
}
}
}
}
throw new KeySelectorException("No key found!");
}
public X509CertImpl getSignerCertificate() {
return cert;
}
// CHECKSTYLE_IGNORE_START
boolean algEquals(String algURI, String algName) {
if (algName.equalsIgnoreCase("DSA")
&& algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) {
return true;
} else if (algName.equalsIgnoreCase("RSA")
&& algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)) {
return true;
} else if (algName.equalsIgnoreCase("RSA")
&& algURI
.equalsIgnoreCase("http://ift.tt/18jbiFB")) {
return true;
} else {
return false;
}
}
// CHECKSTYLE_IGNORE_END
}
private static X509Certificate[] getCertificates(String cAFolderPath)
throws FileNotFoundException, CertificateException {
ArrayList<X509Certificate> certificates = new ArrayList<X509Certificate>();
File f = new File(cAFolderPath);
if (f.isDirectory()) {
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++) {
X509Certificate cert = X509Certificate
.getInstance(new FileInputStream(files[i]));
certificates.add(cert);
}
X509Certificate[] certs = new X509Certificate[certificates.size()];
if (certificates.size() != 0) {
for (int i = 0; i < certs.length; i++) {
certs[i] = certificates.get(i);
}
return certs;
}
}
return null;
}
public String getUserIDN() {
return userIDN;
}
public void setUserIDN(String userIDN) {
this.userIDN = userIDN;
}
}
Why does the following code gives IndexOutOfRangeException in Java:
Dim intNum() As Integer = {1, 2, 3, 4, 5}
Dim tot As Integer
For Each n As Integer In intNum
tot = tot + intNum(n)
Next
MsgBox(tot)
Please tell me how to update list data from Application to exists large records in SQL server (more then 800million records).
This mean : i will foreach my List data --> then [select record by id from table in SQL] then if exist record i will update record from Application to SQL server. Because the database very large then 1 record want to be updated will find more than 800million records in SQL--> 1*800million--> so i want to update 100 record then --> 100*800million.
Please help me the best solution to solve this prolem. Thank you so much!
I have an interesting study case for you :)
I have a problema with a wrapper integration. I made a Dll in write in C++. CLR Windows. This Dll is called form a C# application (for a the), till here all rigth.
The C# aplications is form a thrid part and I Cannot modify this source code.
When I call some C++ function since a button for example. The applications si bloqued an I can't doing any more until the C++ function return. I need that when I wating for a C++ function the different the formulary controlls has enabled again so on, I need some additional process.
I try to do it with async methods and treads but I can't figure out the way to deploy it.
C++ function
__declspec(dllexport) HANDLE openport(char *ComPort, int BR);
C# function:
[DllImport("mydll.dll")] public static extern IntPtr openport(string ComPort, int BR);
Thanks in advance for your help.
Regards.
I have an interesting study case for you :)
I have a problema with a wrapper integration. I made a Dll in write in C++. CLR Windows. This Dll is called form a C# application (for a the), till here all rigth.
The C# aplications is form a thrid part and I Cannot modify this source code.
When I call some C++ function since a button for example. The applications si bloqued an I can't doing any more until the C++ function return. I need that when I wating for a C++ function the different the formulary controlls has enabled again so on, I need some additional process.
I try to do it with async methods and treads but I can't figure out the way to deploy it.
C++ function
__declspec(dllexport) HANDLE openport(char *ComPort, int BR);
C# function:
[DllImport("mydll.dll")] public static extern IntPtr openport(string ComPort, int BR);
Thanks in advance for your help.
Regards.
I am a good C# programmer, but recently i had a work involving a lot of pinvoking so i thought it would be a good idea to learn C++ through C++/CLI as it is an intermediate language between both Native/Managed worlds, also i like the fact that in C++ i have access to the well detailed .Net Framework. HOWEVER from the results of the search i done C++/CLI seems to be a neglected language with no much support so i thought what should be a good decision for me now regarding that i am a former C# programmer who want to dive a little bit into the Native world.
Edit: i know that this question is partially asked times in the past, but i want to get a more 2015-ish answer.
I have a ConfigurationProperty that is annotated with a RegexStringValidator that looks like this:
public class Test : ConfigurationElement
{
[ConfigurationProperty("field", IsKey = true)]
[RegexStringValidator("issuer|subject")]
public string Field
{
get { return (string)base["field"]; }
}
}
It always throws an exception saying that the RegexStringValidator failed. I can achieve success if I change the regex value to either of these:
"[a-zA-Z]*"".*"The actual "field" value being validated is the simple string "issuer". I can see no reason why there should be a problem. In fact, the source code for RegexStringValidator does nothing fancy; it simply uses a Regex and checks for success.
So I tried to do the regex directly as a test, the same way that it is done inside RegexStringValidator:
Regex reg = new Regex(@"issuer|subject", RegexOptions.Compiled);
bool match = reg.Match("issuer").Success;
The above works as expected; it returns Success==true. I even used Telerik's "Just Decompile" to verify the System.Configuration source code indeed matches what is published online.
Again, I can see no reason why my "issuer|subject" RegexStringValidator regex constantly fails.
Any ideas?
The only clue I've turned up is when I tried the regex "[a-zA-Z]". Strangely, this failed because it did not have the trailing asterisk. So perhaps the regex must be written to match the full-length of the input. To test that theory, I changed my regex to "^issuer$|^subject$", but that still didn't work when applied to the RegexStringValidator. It does, however, work with my explicitly written regex test.
What makes the above anomaly interesting is that the source code for RegexStringValidator gives no reason of why "[a-zA-Z]" would fail. Does this imply that the code I'm reflecting and seeing online does not match what is actually executing on my machine? That doesn't seem plausible. So this is weird indeed...
I'm using a .net 4.0 build, on a machine that has .net 4.5 installed.
I have an existing Windows Service application, based on .NET Framework 4.5 and want to add an user interface for configuration and diagnostics.
In Windows Forms or WPF the service would send it's data via TCP connection (.NET Remoting or WCF) to the client, but that would require additional configuration, either on client or on server side and also requires service and client to be on the same compatibility level, which in worst case means multiple clients for multiple services.
I have an idea of melting service and user interface together in one application using new ASP.NET5 Web Application. When the Windows service starts, first I would like to start the web server and then start the rest of the service. So it would be possible for the user to interact with the service without installing any additional software. The Web Application and Windows Service should run in the same AppDomain, so that I can change an object in user interface and the service can use it immediately.
So far, I have played a bit with new Console Application (dnx451) and hosting via WebHostBuilder and got a working page, but I don't think that that's the solution I'm looking for. I get the project output and a cmd-file to start the server.
So my first question is: Is there an equivalent implementation of WebHostBuilder for .NET 4.5, to run a web site in tradional Visual Studio projects?
My second thought would be to completely run the service inside IIS, so I'd have a WebPage hosting the existing service functionality. But I'm not aware of any differences between applications in IIS and as Windows service. And what's about ASP.NET 4.6 in this case? Because I think I will have to convert my existing libraries into new ASP.NET5 class library (Packages).
The last possibility I could think of would be to publish web application to IIS and service as Windows service and communicate via WCF NamedPipes, like I would do with WPF or Windows Forms application.
To sum up, Is there anything planned to support my first idea or do I have to choose one of the others? And which option would probably be the best?
I have a function in my code to open various reports in SSRS, which may or may not need to accept a parameter(s). I'm passing the URL and parameters as follows:
var reportUrl = ConfigurationManager.AppSettings["ReportServerUrl"];
var reportPathComponents = ConfigurationManager.AppSettings["ReportPath"].Split(';');
var reportPath = string.Join("&", reportPathComponents);
return reportUrl + string.Format(reportPath, start.ToShortDateString(), end.ToShortDateString());
Possible inputs are:
reportUrl = "http://ssrs14devreports..." ReportPath = "Report;rs:Command=Render;start={0};end={1}"
This works just fine in IE 11 but in the latest Chrome and FireFox browsers it encodes the "&" as "&".
Certain .NET Types like List are implemented in the mscorlib instead of the BCL repo (corefx repo).
What is the primary benefit of doing this? TIA
I'm adding lightweight logging functionality to some enterprise software, and I'm trying to do so without adding much of a memory footprint, as memory consumption is a major problem with the software. Therefore, my goal is to not add any references to the current projects. The problem is, there are only 3 projects that have the reference I need to make the call to log information. The problem is, these places aren't shared across the code, and so no one can really call them. In order to get around this, I created a logging event in a static, shared place. I then, from my logging class, hook it up to that event. Then, whenever that event is called from the shared place, the logging gets called. Now, I have to instantiate the logging class at the beginning of my app in order to hook into the event in the shared class. This obviously then lives throughout the lifecycle of the app. Does this add a lot of memory overhead?
I'm sorry if this is vague, but it's the best I could do to try to explain my situation.
I am creating a web service that will be hosted in IIS using the WebApi V2 framework. The web service exposes a local service provided locally by a .dll. The interface of the local service is very simple. I am following RESTful architectural constraints, and we don't have a need to store data on a database or persist the data. The response from the local service is a string that I will simply filter and parse into a JSON object before returning it back to the client. Is this cool?
I've been searching since yesterday about my question but I found nothing related to it so far. By the way, I am quite new to classes so please be kind.
I declared a System::String variable within a class, I created a method to update that variable and another one that returns it's value. However, updating the said variable throws an exception. What is the correct way of declaring a System::String within a class and how do you update and return it's value from a class?
The exception:
A first chance exception of type 'System.NullReferenceException' occurred in XXX.exe
Here is the simplified version of the class I made:
ref class clTimeStamp {
public:
clTimeStamp()
{
strDatestamp = gcnew System::String("");
}
private:
System::String ^strDatestamp;
public:
void SetDateStamp(System::String ^a)
{
strDatestamp = a->Substring( 6, 4 ); // yyyy
strDatestamp = strDatestamp + "-" + a->Substring( 3, 2 );
strDatestamp = strDatestamp + "-" + a->Substring( 0, 2 ) + "T";
}
System::String ^GetDateTimeStamp()
{
return strDatestamp;
}
};
And this is how I used it in the main program:
strBuffer = gcnew String(buffer.c_str());
clTimeStampHSCAN1->SetDateStamp(strBuffer);
fprintf(handle, "%s\n", clTimeStampHSCAN1->GetDateTimeStamp());
I am really confused with strings in C++-CLI, there's just too many ways to create them and it gets quite complicated.
Your help will be greatly appreciated.
Edit: Updated with Caninonos' suggestion (change initialization of String variable in the constructor) but the result is still the same.
When programming C++ in Visual Studio 2012, It has a type String (don't confuse with std::string). I need to make a conversion of type String to other string types such as Char, LPCSTR, std::string... How can I do it?
The new Task class works great in WPF. However in Winforms, it is always stuck every time it tries to access a Winform control. The "InvokeRequired" routine below that has been working with BackgroundWorker and Thread classes that prevents cross-thread operation error. However, for some reason when it comes to Task, it gets stuck on the Invoke method. Help ?
Here is a sample code. I use NET 4.5.1 framework.
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinformTaskDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string now = DateTime.Now.ToString();
Task t = new Task(() => { setText(now); });
t.Start();
t.Wait();
}
private void setText(string text)
{
if (textBox1.InvokeRequired)
{
textBox1.Invoke(new Action(() => textBox1.Text = text)); //stuck forever here
}
else
{
textBox1.Text = text;
}
}
}
}
I have web solution (MVC 5). Also in this this solution there are few console applications. I can buil entire solution locally without any errors. But on TC I can't build Web solution (but can all console apps and class libraries). I'm getting such error:
error CS0246: The type or namespace name 'HttpRequestMessage' could not be found (are you missing a using directive or an assembly reference?)
error CS0246: The type or namespace name 'HttpRequestMessage' could not be found (are you missing a using directive or an assembly reference?)
error CS0246: The type or namespace name 'AuthenticationHeaderValue' could not be found (are you missing a using directive or an assembly reference?)
Only these 3 entities can not be found in a different files. I can see referenced System.Net, System.Net.Http, System.ServiceModel.Channels assemblies. I'm sure (from build logs) they are referenced from 4.5 (all projects built with 4.5)
What is the problem in?
Good afternoon, I get this error:
_message = "Thread was being aborted."
after a Response.Redirect("Default.aspx") sentence Anyeone can helpme?
I'd like to rewrite a VB.NET(2010) project in C++. I have a basic knowledge of C++ from books and lessons, but it's mostly about syntax and console apps and I struggle to create a UI. I need a UI designer (with basic common controls + tab and chart, database connection would be great but I could do without). I want to write in C++ (not C++/CLI) but none of the clr-less options I've tested in VS2010 or 2015 come with a UI designer. Is there any way to use a designer without .net framework/clr?
I just recently downloaded and installed Visual Studio Professional 2015 (14.0.23107.0). The first time I opened up our solution (28 projects) and performed a Build -> Rebuild Solution, my development machine came to an absolute crawl. The CPU was maxed out at 100% and the build never completed - even after > 10 minutes.
I opened up Windows Task Manager and noticed: > 10 VBCSCompiler.exe tasks running. When combined, these tasks sent the CPU > 90%.
Any idea why there are so many of these tasks running? Any way to stop this from happening?
This is the closest thing I can find to someone else experiencing the same issue: http://ift.tt/1MCykuR
I use c# and WIA scanner lib. For some pc result image quality is very bad, but if I use standart windows scanning from control panel, image is good. I think from my application wia sometimes not used installed drivers for scanner, and it used some native driver. Please, how I can set special driver or other idea for improve the quality of image???
This page is dynamically created and the control is just a generic HTML drop down control. Sometimes if you double click certain items in the list (usually the middle options are more problematic than the others) it'll display the list of items twice, like so:
I've tried to Google around to see if this was a known issue with either .NET, IE or what but I cannot find a single relevant result.
Has anyone seen anything like this before? I'm completely at a loss as to what might be causing it. Using IE11 in Compatability Mode.
Looking at the ASPX page that gets generated in Visual Studio the control looks like this:
<div id="dlRepOpt_ctl02_DynControl">
<SELECT NAME='Aedates' Class='clsComboBox110' onchange='mDataChanged=1;'>
<option value='Previous Month'>Previous Month</option>
<option value='Current Month'>Current Month</option>
<option value='Previous Quarter'>Previous Quarter</option>
<option value='Current Quarter'>Current Quarter</option>
<option value='Previous Calendar Year'>Previous Calendar Year</option>
<option value='Current Calendar Year'>Current Calendar Year</option>
<option value='Last 12 Months'>Last 12 Months</option>
<option value='User-defined Date Range' Selected>User-defined Date Range</option>
</SELECT>
</div>
Nothing crazy.
If I have clicked a link generated by a Tag widget in Sitefinity, I end up on a page with a URL like this:
/normal-url/-in-tags/tags/tag-name
If I have an MVC control on the /normal-url/ page, how can I pull the tag-name into a View or into the Controller?
I'm currently working on an extension on the Moq framework to be also to mock the implementation of non virtual methods. I currently already have this working by obtaining the Method Handle of the original Method and swapping this with the pointer of a user defined Func.
One issue I'm still running into is that when I create the Func in the Moq internal code (inside a class that uses Generics) I run into an issue with RuntimeHelpers.PrepareMethod. (The Func needs to be prepared before we can execute the pointer swap).
When I create exactly the same Func in a normal class (e.g. Program) everything works fine.
Further investigating the issue traced this back to wether the call class had generic arguments or not.
Exception being thrown:
An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll
Additional information: The given generic instantiation was invalid.
I have isolated the problem in the following codeblock:
class Program
{
static void Main(string[] args)
{
new WithoutGeneric().GoExecute();
new WithGeneric<string>().GoExecute();
}
}
public class WithoutGeneric
{
public void GoExecute()
{
//Works fine
StaticMethods.PrepareThisFunc(() => "Test");
}
}
public class WithGeneric<T>
{
public void GoExecute()
{
//Breaks
StaticMethods.PrepareThisFunc(() => "Test");
}
}
public static class StaticMethods
{
public static void PrepareThisFunc(Func<string> theFunc)
{
RuntimeHelpers.PrepareMethod(theFunc.Method.MethodHandle);
}
}
I have also looked at the current open source CoreCLR code but have not been able to find out what the issue might be.
CoreCLR: http://ift.tt/1MCwuu6
The exception is thrown on the lines: 2435, 2444, 2447
Does anyone have an idea on how to resolve this exception?
I'm creating php rest service which will be consumed by c# desktop application using HttpWebRequest class.
I would like to pass json to service with post method, and create associative array in php which I would use to process user request.
I have tried to send json as a string in different formats (ex. "{"x":"y"}" or "{'x':'y'}"), also to use JsonConvert.SerializeObject form Newtonsoft.Json to serialize object in application and tried to convert that to array using json_encode method. But it always keeps it as a string. I have even tried to change string from post in php to match format required by json_encode (ex. '{"x":"y"}') but can't do it.
So my question basically is how to format json in c# so I can use it in php script?
I have a solution with 3 projects. I made it as a test:
1) The WinFormsProject (setted as Main project): It is just a form that throws an exception when clicking a button. Before throwing the exception, it makes some assignations with an object of the class Person (who is in another assembly).
2) The ConsoleProject: It's another assembly with the same idea: it only plays a little with an object of the class Person and then throws an Exception.
3) The AspectTest: it's an assembly which has defined the class Person and an aspect (called LogBoundary) (inherited from OnMethodBoundaryAspect) who logs OnEntry(), OnExit(), OnSuccess() and OnException().
The three assemblies are configured through an "AspectInfo.cs" class to target every method but the "CompileGenerated" ones. So:
[assembly: LogBoundary()]
[assembly: LogBoundary(
AttributeExclude = true,
AttributePriority = 0,
AttributeTargetMemberAttributes = MulticastAttributes.CompilerGenerated)]
The problem is that all methods in the assembly AspectTest are being logged, but the ones in WinFormsProject not. I have no idea why.
Some things to consider:
Any help would be great, and if you still need some info about this, please ask me (I might forget to tell something).
Thanks!
I'm trying to familiarize myself with the VS 2015 Typescript project, and the differences between all the build options. When I read questions/answers on SO, they are usually referring to command line options, and I don't always know how they translate to the Typescript Build options in the VS 2015 UI.
Is there a window somewhere (or extension?) that shows the actual command line that visual studio runs when you select the various project Typescript Build options?
HI lets say I have a C# code
private const string INSERT = "INSERT INTO Person VALUES (@FirstName, @LastName)";
public static DbCommand INSERTCOMMAND(IPerson person)
{
DbCommand command = null;
var sqlParams = new List<DbParameter>();
if(SQLManagerFactory.SQLManager is SQLServerManager)
{
command = new SqlCommand(INSERT);
sqlParams.Add(new SqlParameter("@FirstName", person.FirstName);
sqlParams.Add(new SqlParameter("@LastName", person.LastName);
}
else // SQLiteManager
{
command = new SQLiteCommand(INSERT);
sqlParams.Add(new SQLiteParameter("@FirstName", person.FirstName);
sqlParams.Add(new SQLiteParameter("@LastName", person.LastName);
}
command.Parameters.AddRange(sqlParams.ToArray());
return command;
}
Which is working perfectly fine. Of course in my production code, it is quite bigger and has a lot more location that does the similar things for different commands.
My question is that is there way to make this shorter? I do not wish to copy and paste code which essentially does the same thing except for calling the different constructors.
Thank you very much in advance.
Is there a .NET/CIL language that supports user-defined default constructors for value types? I know that they were planning that feature for C# 6/VB 14, but it looks like it was dropped.
I have a small batch script to move files from shared to location to my E-drive. The script below moves the file from the shared location and deletes it from the shared location.
@echo off
cls
NET USE Q: \\lMC-Wheat-tick\PQ120R2A3 /USER:SAPQMPQ-LOCAL\USername "Password"
move "Q:\*.csv" "E:\CSV Files\CSV\CSVSource\"
NET USE Q: /DELETE /Y
echo on
I want to modify this code not to delete the file in shared location and pick only the files from the shared location that are not in my E-Drive ("E:\CSV Files\CSV\CSVSource\").
Thanks in advance.
I have some code to process several million data rows in my own R-like C# DataFrame class. There's a number of Parallel.ForEach calls for iterating over the data rows in parallel. This code has been running for over a year using VS2013 and .NET 4.5 without issues.
I have two dev machines (A and B) and recently upgraded machine A to VS2015. I started noticing a strange intermittent freeze in my code about half the time. Letting it run for a long time, it turns out that the code does eventually finish. It just takes 15-120 minutes instead of 1-2 minutes.
Attempts to Break All using the VS2015 debugger keep failing for some reason. So I inserted a bunch of log statements. It turns out that this freeze occurs when there is a Gen2 collection during a Parallel.ForEach loop (comparing the collection count before and after each Parallel.ForEach loop). The entire extra 13-118 minutes is spent inside whichever Parallel.ForEach loop call happens to overlap with a Gen2 collection (if any). If there are no Gen2 collections during any Parallel.ForEach loops (about 50% of the time when I run it), then everything finishes fine in 1-2 minutes.
When I run the same code in VS2013 on Machine A, I get the same freezes. When I run the code in VS2013 on Machine B (which was never upgraded), it works perfectly. It ran dozens of time overnight with no freezing.
Some things I've noticed / tried:
I'm not changing the default GC settings at all. According to GCSettings, all runs are happening with LatencyMode Interactive and IsServerGC as false.
I could just switch to LowLatency before every call to Parallel.ForEach, but I'd really prefer to understand what's going on.
Has anyone else seen strange freezes in Parallel.ForEach after the VS2015 upgrade? Any ideas on what a good next step would be?
UPDATE 1: Adding some sample code to the nebulous explanation above...
Here is some sample code that I hope will demonstrate this issue. This code runs in 10-12 seconds on B machine, consistently. It encounters a number of Gen2 collections, but they take almost no time at all. If I uncomment the two GC settings lines, I can force it to have no Gen2 collections. It's somewhat slower then at 30-50 seconds.
Now on my A machine, the code takes a random amount of time. Seems to be between 5 and 30 minutes. And it seems to get worse, the more Gen2 collections it encounters. If I uncomment the two GC settings lines, it takes 30-50 seconds on Machine A also (same as Machine B).
It might take some tweaking in terms of the number of rows and array size for this to show up on another machine.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using System.Runtime;
public class MyDataRow
{
public int Id { get; set; }
public double Value { get; set; }
public double DerivedValuesSum { get; set; }
public double[] DerivedValues { get; set; }
}
class Program
{
static void Example()
{
const int numRows = 2000000;
const int tempArraySize = 250;
var r = new Random();
var dataFrame = new List<MyDataRow>(numRows);
for (int i = 0; i < numRows; i++) dataFrame.Add(new MyDataRow { Id = i, Value = r.NextDouble() });
Stopwatch stw = Stopwatch.StartNew();
int gcs0Initial = GC.CollectionCount(0);
int gcs1Initial = GC.CollectionCount(1);
int gcs2Initial = GC.CollectionCount(2);
//GCSettings.LatencyMode = GCLatencyMode.LowLatency;
Parallel.ForEach(dataFrame, dr =>
{
double[] tempArray = new double[tempArraySize];
for (int j = 0; j < tempArraySize; j++) tempArray[j] = Math.Pow(dr.Value, j);
dr.DerivedValuesSum = tempArray.Sum();
dr.DerivedValues = tempArray.ToArray();
});
int gcs0Final = GC.CollectionCount(0);
int gcs1Final = GC.CollectionCount(1);
int gcs2Final = GC.CollectionCount(2);
stw.Stop();
//GCSettings.LatencyMode = GCLatencyMode.Interactive;
Console.Out.WriteLine("ElapsedTime = {0} Seconds ({1} Minutes)", stw.Elapsed.TotalSeconds, stw.Elapsed.TotalMinutes);
Console.Out.WriteLine("Gcs0 = {0} = {1} - {2}", gcs0Final - gcs0Initial, gcs0Final, gcs0Initial);
Console.Out.WriteLine("Gcs1 = {0} = {1} - {2}", gcs1Final - gcs1Initial, gcs1Final, gcs1Initial);
Console.Out.WriteLine("Gcs2 = {0} = {1} - {2}", gcs2Final - gcs2Initial, gcs2Final, gcs2Initial);
Console.Out.WriteLine("Press Any Key To Exit...");
Console.In.ReadLine();
}
static void Main(string[] args)
{
Example();
}
}