C#

94K

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

I need to give the user of windows forms app a reminder before sunset.

This code from the following URL calculates sunset time.

https://blog.ip2location.com/knowledge-base/display-sunrise-sunset-time-using-csharp-and-mysql-database/
 
public class SunsetCalculator
    {
        double longitude;
        double latitude;
        double D2R = Math.PI / 180;
        double R2D = 180 / Math.PI;

        public SunsetCalculator(double longitude, double latitude)
        {
            this.longitude = longitude;
            this.latitude = latitude;
        }

        public string calculate(DateTime date, int set_rise, double offset)
        {
            //Convert longitude into hour value
            double long_hour = longitude / 15;
            double t = 0;

            //sunset = 0, sunrise = 1
            //calculate approximate time
            if (set_rise == 1)
            {
                t = Convert.ToDouble(date.DayOfYear) + ((6 - long_hour) / 24);
            }
            else if (set_rise == 0)
            {
                t = Convert.ToDouble(date.DayOfYear) + ((18 - long_hour) / 24);
            }

            //Calculate Sun's mean anomaly time
            double mean = (0.9856 * t) - 3.289;

            //Calculate Sun's true longitude
            double sun_true_long = mean + (1.916 * Math.Sin(mean * D2R)) + (0.020 * Math.Sin(2 * mean * D2R)) + 282.634;
            if (sun_true_long > 360)
                sun_true_long = sun_true_long - 360;
 

Open in new window

0
Hi Experts,

Currently trying to work out how to open a report in report builder edit mode, this was previously available in pre-2016 but I'm aware MS have removed the clickonce ability. I did have this working in a C# Winform pre 2016 (is commented out in my code below).

Looking at these two topics:

StackOverflow Link

MSDN Forums link

I can see it's possible, and have been able to actually open the report builder application, but it doesn't open the specific report I've clicked on

Here's the users code:

"reportbuilder:Action=Edit&ItemPath=Project/Reports/Realization&Endpoint=http//101.11.11.111/ReportServer"

Open in new window


and here's mine (edited for obvious reasons):  txturl value =
http://xxx/Reports/report/report_folder_here/report_here
for reference

string url = txtURL.Text;

            //var rdl = url.Substring(url.LastIndexOf("ItemPath=/") + 10); //pre 2016 SSRS
            var rdl = url.Substring(url.LastIndexOf("http:/") + 26); //post 2016 SSRS

            try
            {
                //pre 2016 SSRS
                //WebBrowser wb = new WebBrowser();
                

Open in new window

0
Hi,

I built a client/server c# .net Electonic Medical Records app.

The client is a C# Windows Forms desktop App.
The server a managed Windows Service.

How can I protect my app? I mean if someone got the executables and tried them on other machines it does not work.

Thanks,
0
Hi,

I need to secure my C# .NET application code against reverse engineering.

Any help, please.
0
Hi,

I have a windows service which connects to a SQL Server database server using "sa" credentials.

I need to encrypt the connection string section inside the service configuration file.

I really need a robust -yet simple to understand and apply way- to secure the connection string.

Thanks,
0
I have the following api to call MVC.net controller, and it works just fine.
Now, I have some service called https://api.xxx.com/Accounting/Test and I replace it but it is not working.
The  c# parameters and method is  the same. so do you have any ideas what is going on?

 $.ajax({
            url: "/Accounting/Test",
            dataType: 'json',
            data:
            {
                'asso': assoValue
            },

Open in new window

0
on my mvc, I want to the its identity and role based option. I understood there is google, facebook, and etc.
and I own have a custom Single Sign on for one of the providers for our own business. Let us call it FirstSSO
and I want FirstSSO to be used by default. Just assume that someone put login/password in  the form, and it  will take FirstSSO first instead of the using local MS SQL for auth.

Thanks,
0
I have 1000  emails that I want send by sendgrid using mvc/c#
Do you know there is better way  to implement it?
0
Hope that you are able to help. I am looking for software that we are able to integrate into a c# application that will allow us to Batch PDF files into a single document.
For example we receive 10 PDF customer order files that we want to batch into 1.

The challenge we have is that we need to be able to guarantee that the position of each pdf can be aligned. You will see on the attached document that we have 10 customer PDF files on a single PDF file or sheet of paper. The idea being is that we can print this easier and the pack of paper can then go through the guillotine.

I have used software in the past that we can merge pdf files but we need to make sure that the first page, second, third etc up to the 100 pages are on the same position so that when the paper goes through the cutting machine that all the customer orders are not mixed up.

Regards,

Ross
ScanExample.pdf
0
ResultCode=6&ResultMessage=Request+ID+passed+in+is+null+or+invalid.&AID=0808&ARID=1875123456789&CNumber=0&PaymentMethods=

I have above return string in c#.
and I want to get the value of ResultCode.
How can I do that in c# in a foreach loop?
0
I have a following code which is very confusing:
            var myData1 = new List<Product>()
            {
                new Product
                {
                    Suppliments = new Suppliment[]
                    {
                        new Suppliment
                        {
                            Category = ProductType.TypeA, 
                            Tag = new TagCard
                            {
                                Descriptions = new List<DesriptionType>
                                {
                                    new D1 { TName = 'T1', MyJson = JsonConvert.SerializeObject("This is T1") },
                                    new D2 { TName = 'T2', Url = new Uri("http://test.com")}
                                }
                            }
                        }
                    }
                }
            };

Open in new window


In this code, what I am interested in is Descriptions part.
1> How can I delete one property from each DescriptionType?
For example, I want to have
 
Descriptions = new List<DesriptionType>
                               {
                                    new D1 {  MyJson = JsonConvert.SerializeObject("This is T1") },
                                    new D2 { TName = 'T2'}
                                }

Open in new window


2>  How can I replace (Delete existing one and add a new DescriptionType)
For example, I want to have
 
Descriptions = new List<DesriptionType>
                                    {
                                    new D3 { TName = 'T1', TStart ="06222019";},
                                    new D2 { TName = 'T2', Url = new Uri("http://test.com")}
                                }

Open in new window

0
I need to take a view in MVC 5 and open it in Outlook. I have the printing functionality working, but the end users want the capability to click a button to open their Outlook with the contents of the view. I do not want to send the view programmatically on the server side as the end users want to be able to view it as an email on their workstations and add comments before sending to email addresses. Is this possible? I have done lots of searching online and found ways to send emails through MVC on the server side, but I have not found anything that takes a view and pastes it into an Outlook window. I do not want to use any 3rd party plugins except those which are widely used standard plugins (jquery, javascript, ajax, etc.)

Current system:
ASP.NET MVC 5
Entity Framework 6
C# with razor views
Microsoft SQL 2014
Microsoft Exchange (not hosted online)
Various versions of Microsoft Outlook

I can provide code samples for the controller and views if needed.
0
I am designed my Windows Forms application using MVP pattern as follows:

View: is a passive windows forms (or user control) which expose its events to the public.
Presenter: accepts in their constructor an instance of the related view (using Dependency Injection DI ) and subscribe to the events in the view for handling.

Everything works fine except view load event; which fire before the presenter subscribes to the event.
0

STORY:


I need to create a SOAP Envelop with C#.NET to consume a Java-based web service

I can use SoapUI for testing and it works properly.

now I need to create a C#.NET console app to consume this web service.

I was able to compute the <ds:DigestValue> but I couldn't' compute the SignatureValue.

note the "ds" prefix which is required for the Java-based web service and I don't have control over it.

I have tried tens of solutions from the internet and none works.

QUESTION:


How to compute <ds:SignatureValue> base on the node <ds:SignedInfo>, it could be in C#, or any another library like OpenSSL


<ds:SignedInfo>
    <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
        <ec:InclusiveNamespaces PrefixList="#default"
            xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" />
        </ds:CanonicalizationMethod>
        <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
        <ds:Reference URI="#id-2">
            <ds:Transforms>
                <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
                    <ec:InclusiveNamespaces PrefixList=""
                        xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" />
                    </ds:Transform>
                </ds:Transforms>
                <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
                

Open in new window

0
Hi,

If I have a connection set up like this, how can I close it? There is no close or dispose in the application object.

try
{
      // This creates an Instance of the API. 
      VismaLön600.Application lon = new VismaLön600.Application();

      // Initialize the server
      // For Lön 2018.1 or later, use Init (with APIversion 2.0) instead of InitServer
      if (lon.Init(“2.0”, null) != 0)
      {
          return false;
      }

          // Login with a API-user. Username, password and the name of the company in the database
      string Login_Signature = "api";
      string Login_Pwd = "se";
      string DBCompanyName = "SPCS_Lön_Ftg1";

      int returncode = lon.Logon (Signature , Login_Pwd , DBCompanyName);

      if (returncode != 0)
      {
                  Console.WriteLine("Error when trying to login." + returncode);
                  return false;
      }

      // You are now logged in
      return true;
  }

       catch (System.Runtime.InteropServices.COMException ex)
       {
           // When something unexpected happens, like the database could not be Initialized,
           // then the API thows an exception.
           Console.WriteLine("COMException when trying to login." + ex.ErrorCode);
       }

Open in new window


When I read records and then try to read again I get an error that it's already logged on:
try
{
      // Creates a TableObject that contains the records of Employees
    EmployeeTableObject employeeTableObject = lon.CreateTableObject((int)Tables.Table_Employee);

    // Reads all the Records Id and put them in the employeeTableObject              
    employeeTableObject.Fetch();

    // IsEOF is true as long as the position in the table is inside the boundaries.
    while (!employeeTableObject.IsEOF())
    {
            // Reads the current record.
            String firstname = employeeTableObject.GetString((int)Employee_Properties.EMP_FirstName);
            Console.WriteLine(firstname);

          // When moving to a new record, the record is read into the current record.
            TestMain.EmployeeTO.MoveNext();
    }
    catch (System.Runtime.InteropServices.COMException ex)
    {
            Console.WriteLine("COMException:" + ex.ErrorCode);
    }
}

Open in new window


Thanks for help!

Peter
0
I am doing Entity Framework and I have a database where there is no connection between the two tables. My form has two datagridviews each showing the contents of those tables on load. I also have two buttons. When  selected any cell (which selects the entire row)  on  the sport table and click copy it moves the data to the health table and removes it from the sport. The second button does vise versa. what would be like? the edmx modelmy form
0
Hello Experts,
When my following code is executed, the database connection remains open for a long time even after the processing work is done.  If I execute the following code  N number of times, there are N number of connections opened, and they is remain open for a while, which causes our db server to perform slow.

        int returnId = 0;
        SqlParameter[] parm;
            
        try
        {
           parm = new SqlParameter[2];
           parm[0] = SqlHelper.CreatePerameter("@EMP_CODE", SqlDbType.VarChar, strEmpCode, ParameterDirection.Input, 50, false);
           parm[1] = SqlHelper.CreatePerameter("@UPDATED_BY", SqlDbType.VarChar, strUpdatedBy, ParameterDirection.Input, 10, false);
           returnId = SqlHelper.ExecuteNonQuery(SqlHelper.GetConnection(), CommandType.StoredProcedure, "usp_deleteTran", parm);
        }
        catch (Exception ex)
        {
        }

Open in new window


I have a SqlHelper class where I have the GetConnection method, which is used quite often through out the solution.  The question is how can I close the connection automatically once the DB work is done?  If I try to close it in every program, it would be lots of work.  Please see below the GetConnection() method inside the SqlHelper class.  Please let me know.

Thank you very much in advance.


SqlHelper Class
	public static SqlConnection GetConnection()
	{
	    string strConnectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"].ToString();
	    if (strConnectionString.ToLower().IndexOf("database=") == -1)
	    {
		strConnectionString += "Database=sbmwonder" + System.Web.HttpContext.Current.Session["sbm"].ToString();
	    }
	    
	    SqlConnection sqlCon = new SqlConnection(strConnectionString);	
	    return sqlCon;
	}

Open in new window

0
Hello;
Can I open a page in an Internet Explorer through a page in a Chrome browser?
In other word, regardless of the browser type that I'm residing in, I need when click on HTML link to open it in IE only, for that particular link only.
C#, MVC, javaScript
please help.
0
We have an application that needs to pass encrypted data between a server application and client application. We are currently using SslStream.

We're having performance issues with the SslStream, in that when we have large amounts of data to send, it's very slow. The data is in XML format.

Does anyone have any suggestions on how to speed this up? We're willing to implement a different communication method but need to retain the XML data.

We are coding in C#, using .NET 4.6.2
0
Hello Experts,

Currently I have the following:

APP_A is a C# Win Form

APP_HW  is a C++ Windows Application that exposes various COM classes

This works fine, and APP_A can use the COM classes from APP_HW.


Now I want to change APP_HW from a C++ application to a C# WinForm application (I'll call it APP_HW_CS) and expose COM classes from it that can be used by APP_A. However, I do not want to use Reflection to achieve this. Reflection will just load APP_HW_CS for APP_A to use,  and I need to have APP_A link to a running APP_HW_CS for it's COM classes.

I have read a lot of information online. I have a COM object that is registered and exported from the APP_HW_CS (C# version). But the only way to use it appears to add the APP__HW_CS as a reference and then create the objects. But putting it as a reference seems to make it load a new version of APP_HW_CS and not use the running APP_HW_CS.

Is what I am trying to do even possible?

Thanks for any help and any references you can point me too.

Brian.
Using VS2013 on Windows 7 Pro 64bit.
Compiliing as a 32bit app.
0
Need a sample adding a custom ribbon to a SharePoint List that will call some c# code.  Any samples/URLs would be greatly appreciated.
0
Hi

I'm trying to do a load test app to hit my external API from a console app.

I have this code:

Parallel.For(0, totalRequests, options, n => {
            Console.WriteLine(n);
            var result1 = Client.GetAsync(sb.ToString()).Result;
            Console.WriteLine(result1.Content.ReadAsStringAsync().Result);
             });

Open in new window


This works fine, however, from what I have read, the Parallel.For is suited to CPU BOUND stuff, and not IO BOUND work

Therefore I need to convert this to Await Async Task
Can someone help with the code to do this?

I eventually need to put this code into my main app, so want to get it right here first.
0
I have a VS C# 2017 project that consists of several projects and classes. Today I needed to add a method to one of the classes. I then went to reference this new method in another class and I kept getting a message about definition did not exist in the class specified(CS0117). Obviously this was not true so I started cleaning and rebuild and building and that did not help. I then tried removing the bin and obj folders from classes and cleaning and building and that did not help.  Finally I noticed in the obj folder of the class where I added the new method the date stamp of the dll had not changed but the date stamp of the dll in the bin folder did change. So I copied the dll from the bin folder to the obj folder and now I see the new method in the class where I added it. Why did I have to go through all this trouble to get this to work? I thought build would rebuild everything. Is there some option I need to set to get it to update all dlls?
0
I am constantly looking for ways to improve my code. Today I am working an error trapping.  As an example, please look at the C# code below. I want this method to return either true or false depending on success. I am confused about the use of throw. My question is inside this try catch, do i need to include a return false prior to the throw? Do I need the throw at all? Will return false work just as well as the throw ex? Is there any reason to use one or the other?


public bool GetDatabaseNames()
{
    try
    {
        Log.Write("DEBUG: GetDatabaseNames", false);

        /* Get company database name */
        Controller.Instance.Model.GPCompanyDatabase = Dynamics.Globals.IntercompanyId.Value;

        /* Get GP system database name */
        Controller.Instance.Model.GPSystemDatabase = Dynamics.Globals.SystemDatabaseName.Value;
        return true;
    }
    catch (Exception ex)
    {
        string eMsg = "GP.Class.Library - Controller 002: ERROR" + ex.Message;
        if (Model.StackTraceWanted) eMsg += "\n" + ex.StackTrace;
        MessageBox.Show(eMsg);
        throw ex;
    }
}

Open in new window

0
I'm working on an event receiver for a list in SharePoint 2016.  I am having  trouble getting the code to break.  I attached to all the w3wp processes and as I'm attaching them, I see the breakpoint icon changing to hollow and it's popup says I'm not loading the documents symbols.  

Any suggestions with this would be greatly appreciated.
0

C#

94K

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).