Go Premium for a chance to win a PS4. Enter to Win

x

C#

92K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

Share tech news, updates, or what's on your mind.

Sign up to Post

Is it possible to convert this code to C#?


	int pos=0,p=0;
	double v1,expo,res;

	p=value.find("e+");
	
	if(value.find("e+")!=-1 ||value.find("e-")!=-1)
	{
		pos=value.find("e");
		if(atof(value.substr(0,pos).c_str()))
		{
		v1=StringToDouble(value.substr(0,pos));
		expo=StringToDouble(value.substr(pos+1,(value.length()-(pos+1))));
		res=pow(10,expo)*v1;
		return DoubleToString(res);


		}
	}

Open in new window


I saw this online, but wasn't sure how to get the Takewhile function to work.
https://msdn.microsoft.com/en-us/library/system.linq.enumerable.takewhile(v=vs.100).aspx

float myAtof(string myString)
{
    Predicate<char> testChar = c => c == '.' || 
                                    c == '-' || 
                                    c == '+' || 
                                    char.IsDigit(c);

    myString = new string(myString.Trim().TakeWhile(testChar).ToArray());

    if (myString.Length > 0)
    {
        float rvl;

        // accounts for bogus strings of valid chars, e.g. ".-":
        if (float.TryParse(myString, out rvl))
        {
            return rvl;
        }
    }

    return 0;
}

Open in new window

0
Free Tool: Path Explorer
LVL 11
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Hello Experts,
I would like to know if there are any PC utilities to read CSV files other than Excel. I see a host of them online, but I would really like your recommendation based on your personal experiences.
0
What would be the difference between these two event handlers, one with async, the other without:
private async void ToolStripPlay_Click(object sender, EventArgs e)
{
    var task = Task.Run(() => this.Play()).ConfigureAwait(continueOnCapturedContext: false);
    await task;
}

Open in new window

private void ToolStripPlay_Click(object sender, EventArgs e)
{
    var task = Task.Run(() => this.Play()).ConfigureAwait(continueOnCapturedContext: false);
}

Open in new window

Is there any benefit to using async in this case?
0
I have this method that gets the connection string. I first have a method that builds the connection string. Then I open the connection and finally I try to execute a SQL stored procedure against this connection. As soon as I try to execute the sp I get the message "Connection property has not been initialized" What am I missing and how do I correct this?

        public static SqlConnection GetConnection(string ConnectionString)
        {
            /* Create and open a connection to the SQL Server */
            /* Return open connection object */
            SqlConnection SQLConn = new SqlConnection();

            string loginType = Properties.Settings.Default.SQLLogintype.ToUpper();

            try
            {
                if (loginType == "WINDOWS")
                {
                    SQLConn.ConnectionString = ConnectionStringWindows(ConnectionString);
                    SQLConn.Open();
                }
                if(loginType == "SQL")
                {
                    SQLConn.ConnectionString = ConnectionStringSQL(ConnectionString);
                    SQLConn.Open();
                }

                return SQLConn;
            }
            catch (Exception ex)
            {
                Log.Write("Failed to get SQL connection to the database " + Controller.Instance.Model.SQLDatabase + ": " + ex.Message);
                Log.Write(SQLConn.ConnectionString);
                throw ex;
            }

        }
0
Trying to find an example of an httpWebRequest vb.net or c# on the QualPay Payment Gateway site.

An authorization would be fine.  Just need to get an example of SOMETHING posting
0
Hi, I'm using Visual Studio 2015 - C#. (I have to admit, I haven't coded in a while, so I'm a bit rusty.)

That said, I have to create a Windows Form Application that will allow the enduser to conduct a survey of several different types of facilities. The application would ask the user questions about each facility and the user would select from a set of predetermined answers (i.e. None, Low, Medium, High, etc) to answer the questions. Each answer would have a predetermined value and all those values would be added up at the end to provide a "total evaluation score." -- That part of the project I think I can accomplish without too much difficulty.

However, my question is this -- since the enduser will have different types of facilities, I wanted to have "one" application and create the controls on the form dynamically depending on what questions and control types are needed for each type of facility. I could use Tab Delimited files to manage the different types.

Therefore, all the questions on the Form will have a Label that makes up the verbiage for the question. And all questions will have a Control of some sort (i.e.. a DropdownBox, or a set of Radio Buttons, or maybe a ComboBox) so, how could I, by way of using Tab Delimited files in conjunction with my Application, add Controls (dynamically) to my Application at Runtime?

More specifically, if I wanted to (dynamical at Runtime) add a Label and a DropdownBox Control to my Form, how would I do that?
0
Hello Experts,
I am testing a newly developed windows service and need to see how it handles system exceptions (something like outofmemory, etc). Is it possible to simulate any such occurrences from outside (without modifying the underlying code)? Please suggest.
0
consider following XML -->

<?xml version="1.0" encoding="UTF-8"?>
<abc:Root
    xmlns:abc = "http://www.abc.com"
    xmlns:xyz = "http://www.xyz.com
    xmlns:xlink = "http://www.somelink.com"
    xmlns:xsi = "http://www.somelink.com/schema">

I have a class for the purpose of serialization/deserialization

[XmlRoot(Namespace="http://www.abc.com")]
public partial class Root{

}

How do i deserialize the above XML, so that I don't loose any of the additional namespaces?
with what I have, I ran a test

1. I deserialized the above XML , to create an object.
2. then i serialized the object in step 1, and looked at the XML.
3. The XMl generated is missing other namespace attribute in the root element . It only has the xmlns:abc attribute.

How do I make sure, i don't loose other namespace attribute when I deserialize?
0
I came across phrase "It's always better to program against interface than concrete types".

can someone elaborate on this a little, with some examples.
0
I have defined this member in my Model class as such:

        public static bool StackTraceWanted { get; private set; }

I know what to assign it the value of true or false in another portion of the code

            Model.StackTraceWanted = true;

This does not work. How to I assign it a value?
0
Concerto's Cloud Advisory Services
LVL 5
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

We have an Access application running on a remote server.  This server is locked down and opens our application at login.  When they exit the application - it runs the Logoff function and takes them back to their local desktop.  

I have put several functions into the Access application that will allow users to logoff - should an issue occur.  However, I do see a possibility of something going wrong and the user not being able to log out.  The Taskbar/Desktop/TaskManager are all hidden, so if something did get to the point where they were looking at a black screen - they would need someone else to log them off of the server, which is not acceptable.

I was thinking of writing a small c# process, that is triggered by the Access application once it has loaded.  It would pass the process ID the the c# app, which would then monitor the process ID, to see if it's still running.  If not (i.e a crash has taken place), it would log the user off.

Is this a good idea, and as I'm pretty new to c#, does anyone have any pointers (or better suggestions)?
0
Hi,
I need to the following code to custom function.Any idea appreciate
 if (TxtPostcode.Text == null && string.IsNullOrWhiteSpace(TxtPostcode.Text))
                    {
                        validate = 1;
                    }

                    if (TxtDestinationName.Text == null && string.IsNullOrWhiteSpace(TxtDestinationName.Text))
                    {
                        validate = 1;
                    }

                    if (TxtDestinationDescription.Text == null && string.IsNullOrWhiteSpace(TxtDestinationDescription.Text))
                    {
                        validate = 1;
                    }

Open in new window

0
Trying to populate my combobox.  I get an error on "ValueMember".  When I bypass that statement the combobox is filled with "System.Data.DataRow".
    Private _results As New List(Of DataRow)

    Dim SQL As String = String.Empty
    Dim sqlData As New SQLData

    Private Sub PopulateSuppliers()

        Me.cbSupplier.Items.Clear()
        Me.cbSupplier.DataSource = Nothing

        SetSupplierSQL()
        _results = sqlData.SelectStatement(SQL)

        Me.cbSupplier.DataSource = _results
        Me.cbSupplier.DisplayMember = "id"
        Me.cbSupplier.ValueMember = "name"

    End Sub

Open in new window


Any ideas?
0
I have a website coded in .aspx and I need to get help in coding.
Can someone please tell me exactly what programming language it is?

Here is a snippet:
		Out ('<script language="Javascript" type="text/Javascript">');
		Out ('function valCoupon() { ');
		Out ('var oForm=document.forms.form1; ');
		Out ('var sError=""; ');
		Out ('var nID=0;')
		Out ('for (var i=0;i<oForm.radCoup.length;i++){');
		Out ('if (oForm.radCoup[i].checked==true) {');
		Out ('nID=oForm.radCoup[i].value; }}')
		Out ('if (nID==0) {sError="'+ErrorOut2(73)+'"; alert(sError); }');
		Out ('else {oForm.submit();} ');
		Out ('} </script>');
		Out ('<table cellspacing="0" cellpadding="0" width="745" align="left" border="0"><tbody><tr><td class="header" valign="top" background="images/Community/graphic_com_creambkg.gif" colspan="3"><img alt="SOTA Referral Number" width="643" height="40" src="images/Community/graphic_com_header_referral_number.gif" /><p></p></td></tr>');
		Out ('<tr><td valign="top" background="images/Community/graphic_com_creambkg.gif" colspan="3"><table cellpadding="0" width="655" align="center" border="0"><tbody><tr><td class="content" valign="top" background="images/Public/graphic_pub_rightcontent_bkg.gif">');
		Out ('<div class="subheader_sec">Where did you discover your Referral Number?</div><br />');
		Out ('<p>We love to know how our customers are discovering our Referral Numbers - it\'s such a great way to see how word of our products grows and spreads. We appreciate you 

Open in new window

0
An app was written by another developer.  App contains multiple projects.  One was written in VB and another in C#.  Why?  I don't know.

I created a helper class called "FolderLocation" which is in the VB project.

VbProj -> HelperClass (Folder) - FolderLocation (Class)

I want to reference the Folder in the C# project

C#Proj -> DeliveryEmailer (Folder) -> Sender (Class).

There is a project dependency to the C# Proj in the VB Proj.  I can't add a project dependency to the C# referencing the VB Proj because it will create a circular reference.

Any ideas?
0
Hello Experts,
how does make a bat file for continuous Ping multipal IP with background Colour changes ?
for example:-
start ping -t 192.168.207.11 -l 0
start ping -t 192.168.207.12 -l 0
start ping -t 192.168.207.13 -l 0
start ping -t 192.168.207.14 -l 0
start ping -t 192.168.207.15 -l 0
0
private async void ToolStripPlay_Click(object sender, EventArgs e)
{
    var task = Task.Run(() => this.Play()).ConfigureAwait(continueOnCapturedContext: false);
    await task;
}

Open in new window

as opposed to
private void ToolStripPlay_Click(object sender, EventArgs e)
{
     this.Play();
}

Open in new window

What is the advantage of assigning Play() to a Task and then waiting for that Task to complete, as opposed to just running the task?

I see the Task will run on it's own thread, instead of the UI thread, but it looks like the UI thread waits for the Task to complete before returning. (Play() sets the state to Play mode and returns.)
0
I have some manual code that cleans up a corrupt ini file, for instance removes duplicate sections and keys. I don't like using that custom code, would like to use a standard library instead. Have been looking at https://github.com/rickyah/ini-parser, but it seems to not have any automatic way of cleaning this up. If it encounters an invalid ini file with duplicate sections and keys, it throws an error.

Does anyone here know of a library out there that I can use in .Net C# that automatically fixes the problems described above?
0
I had this question after viewing PDFTK - filling this PDF but got an error.

After talking with the others on this project, we decided it's ok to have the final PDF as read-only and it doesn't need to be editable.

I ran the commands below I can populate the PDF but not the checkbox. Joe (if you're reading this)....is this because of the LiveCycle issue that the checkboxes don't get checked?  If it is, I got approval to buy LiveCycle. I'll get it and see what's going on.

I tried "No" for value, "On", "1" but I don't see the checkbox checked.

1. i-765 is the orig file

2. notsigned.pdf is the file I QPDF-ed to get rid of the password error message

3. Ran this pdftk.exe notsigned.pdf fill_form i-765.txt output OutputFilled.pdf

4. outputfilled.pdf is the populated PDF.
i-765.pdf
notsigned.pdf
OutputFilled.pdf
0
Concerto Cloud for Software Providers & ISVs
LVL 5
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

With a lot of help, I have written a small c# app that will paste the contents of the clipboard to a specified folder.  Sadly, however, when I put the .exe file onto my RDP - it doesn't work (I'm guessing because it's looking at the RDP clipboard).  Any pointers (or nuget suggestions), would be greatly appreciated - here's the code that I've been working with:

using System;
using System.IO;
using System.Windows.Forms;

namespace TSPaste2
{
    class Program
    {
        //Getting destination foler
        String[] args = Environment.GetCommandLineArgs();

        [STAThread]
        static void Main(string[] args)
        {
            //Setting Destination foler
            string DestFolder = args[0];

            if (Clipboard.ContainsFileDropList())
            {
                //copy to folder as set in the Command line
                foreach (string source in Clipboard.GetFileDropList())
                {
                    string Dest = DestFolder + "\\" + Path.GetFileName(source);
                    File.Copy(source, Dest);
                }
            }
        }
    }
}

Open in new window

0
Hi,

I am wanting to ultimatly learn ASP.NET core and have found the following course.

https://www.udemy.com/aspnet-mvc-quick-start/

I am looking at this as just an intro type course. To give me an idea of it before going deeper.

I am comming from a C# / Winforms background with no web. To give you a perspective of my knowledge set.

Anyway what I am wondering is how much this would be wasted (if anything) on a learning journey to ASP.NET core.

From what I can see is ASP.NET runs on windows and .NET core can run on other OS besides windows. However what about *all* the rest.

Is ASP.NET Core a superset of ASP.NET. Still has MVC? Do both have angular?

Thanks,

Ward.
0
HI I need to write a function that Pastes all of the files in the clipboard to "D:\Test".  I have been trying lots of different things, but am very new to C# - so am struggling.  I'd really appreciate some help on this.

Sorry not to post any examples, but I have been working on using the WebBrowser object as a file dialog screen, which gets me close - but if I could just paste whats already there, without user interaction - I can remove a lot of complexity.
0
I'm hoping there's a solution for this problem.

1. I have the FDF that I want to use to populate a PDF. It's attached. It's i-765.txt

2. I have the PDF file. I got it from the INS site. It's attached here and called i-765.pdf

3. I ran this command
   pdftk.exe i-765.pdf fill_form i-765.txt output Output.pdf

but got this error

Error: Failed to open PDF file:
   i-765.pdf
   OWNER PASSWORD REQUIRED, but not given (or incorrect)
Errors encountered.  No output created.
Done.  Input errors, so no output created.


4. I googled the error and came across this solution saying I need to run qpdf Solution to get rid of the error

    a. I downloaded QPDF from here Download QPDF
    b.  It got installed in folder:  C:\Users\bwa\Downloads\qpdf-7.0.0-bin-mingw32\qpdf-7.0.0\bin
    c. I copied i-765.pdf to that folder
    d. Ran this command
qpdf --decrypt i-765.pdf decrypted765.pdf

Open in new window

   e. Now, I have decrypte765.pdf. I open it and get this message. I click ok on it and the PDF is read-only
        Message I get    f.  I ran this command to get rid of the message
pdftk decryptedi765.pdf cat output i-765notsigned.pdf

Open in new window

   g. I open i765notsigned.pdf and there's no error and the fields are editable.
    However,  I noticed this: The functionality of the …
0
If you look at the screenshot below, I've got the code stopped just after the assignment of the List<T> to the DataGridView.DataSource.

The DataSource in the Watch window shows a count of 95 items, and if I expand that list, each item has the correct data.

What am I missing?  : /

datasource
MemParts:

public class MemParts
    {       
        public MemParts() { }

        public void InitMemPartsAsPreview()
        {
            CustID = -1;
            PartNumber = "";
            Description = "";
            TypeID = GlobalDatabaseHelperMethods.GetCellInfo("PartTypes", "PartTypesID", "where Label = 'RAW'", "int").ToString().ExToInt32();
            UMID = GlobalDatabaseHelperMethods.GetCellInfo("UnitMeasureTypes", "UnitMeasureID", "where Label = 'EA'", "int").ToString().ExToInt32();
            ClassID = -1;
            NumberOfLeads = -1;
            CommmonStock = false;
            RoHS = true;
            AllowCrossesID = GlobalDatabaseHelperMethods.GetCellInfo("AllowCrossesTypes", "AllowCrossesID", "where Label = 'APPROVE'", "int").ToString().ExToInt32();
            PackageReqID = -1;
            StatusID = -1;
            Notes = "";
            HasSafetyStock = false;
            ReorderTrigger = 0.00;
            ReorderQnty = 0.00D;
            OtherNotes = "";
        }

        public int CustID = -1;
        public string PartNumber = "";
        public string Description = "";
        public int TypeID = -1;
        public int

Open in new window

0
1. I have this in MVC routeconfig
 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

           
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );


        }

Open in new window


2. I have this Controller

  // [HttpPost]
        public ActionResult Index(string formId)
        {

            ViewBag.FormId = formId;
            return View();
        }

Open in new window


3. This works and when I get to the controller, I see "formId"'s value. The URL shows as ?/index/1

  $scope.openForm = function (formId) {

            //console.log(JSON.stringify(formId))

          
            window.location = "/displayform/index/?formId=" + formId; //https://stackoverflow.com/questions/37031143/asp-net-angularjs-how-to-click-on-link-and-route-to-controller-method-with-id

        };

Open in new window


How come these don't work...I step thru it and 'formId" comes out as null. I added HttpPost as well to the MVC Controller. what am I missing?


 window.location = "/displayform/index/"+ formId;

Open in new window



window.open('/displayform/index/' + formId, '_self', false);

Open in new window

0

C#

92K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).