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 am trying to get a old C# service back up and running. In VS2019 I can build the service successfully and view it in the browser. However when I move it to IIS 8.5 I am no longer able to browse the service. Instead I get an HTTP Error 404. IIS-Service-error.docx

I have detailed the steps I have taken in the attached word document. If someone could help me out I'd appreciate it.
0
Database:  SQL
Environment: Visual Studio and C#

Hello Experts,
I am trying to read a table and write the data in 3 tables.  What is the best read/write and loop I should use.

Thank you in advance!
0
I am using Windows Forms and a RichTextBox in c# (Studio 2017) to create a basic editor and now want to add a table. I can do this though the method is very cumbersom, however cannot find an rtf specification, all links I follow are broken. So, two questions:

1. Can anyone point me to an rtf specification?
2. Is there a better way (ie xml?) to do this sort of thing now.
0
dear all

can anyone has a solution for the below error that occured in xamarin :
Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
here is a brief description for my case:
i have an activity and an adapter where this adapter 3 images and 2 labels
upon clicking on the image i am doing the below in adapter
if (!imageView4.HasOnClickListeners)
            {
                //Clicking on upload button
                imageView4.Click += async delegate
                 {
                   
                     var m_HolderID = "";
                     m_HolderID = m_ReferenceNum.ToString().Trim();
                   
                         Activity1 m_Activity1 = new Activity1 ();
                         await  m_Activity1.ResetImageClick(p_Activity, m_HolderID );
                        
                 };
            }

Open in new window


and in the activity below is the function ResetImageClick
public void ResetImageClick(Activity p_Activity, int m_StkTakeNum)
        {
            string m_Message = p_Activity.GetString(Resource.String.StkTakeReset);
            ShowToastMsg(p_Activity,m_Message);
        }
 public void ShowToastMsg(Activity p_Activity,string message, bool IsLengthShort = false)
        {
            try
            {
                Handler mainHandler = new Handler(Looper.MainLooper);
                Java.Lang.Runnable runnableToast = new Java.Lang.Runnable(() =>
                {
                    var duration = IsLengthShort ? ToastLength.Short : ToastLength.Long;
                    //    RunOnUiThread(() =>
                    //    {
                    Toast.MakeText(p_Activity, message, duration).Show();////SHOW MSG CANNOT BE USED INSIDE ASYN METHOD
                    //    });
                    //}
            });
                mainHandler.Post(runnableToast);
            }
            catch
            {

            }

        }

Open in new window

0
Hi All,

I'm a very rusty programmer who has opportunity to get nice business but need to get in shape pretty quickly.

I was programming like 8 years ago, mainly in C# Windows Forms and was pretty good at it. I still remember it.

Today I'm about to create cloud application where I need:
- nice web front end. Interactive application, wizard
- frontend will send files for remote computing on my server (my PC with C# application, Windows for sure, no Linux absolutely)
- server will compute and generate .pdf (how to generate pdf...?)
- pdf accessible in frontend for download and sent via email
- frontend will ask for payment before computing. Subscription plans 24h access, 6 months, 12 months

More or less I think its good description.

I need to choose technology I will use which is easiest for me to adapt.
ASP.NET or HTML5 or what is at the moment most desirable?
I wish to program in Visual Studio Pro.
I hope I don't need to learn anything more than I need for this project.

Please advise!

Many Thanks!
Marcin
0
Issue -
I am using OfficeOpenXML package in C# to process excel files.

I am not able to read values from the cells with formula, it returns empty string.

I am setting up the formula in the field-
worksheet.Cells["I2"].Formula = "=RIGHT(H2, 9)";

but when I am trying to get the value of cell with formula, I am getting blank value, but the excel file shows value -
string cellValue = worksheet.Cells["I2"].Text

Image of sample fileexcelHelp.xlsx
0
I have been tasked to create a Spotlight type of report.  I am thinking the best way to get all the data I need for each "cell" of the report would be to create a Stored Procedure the contains multiple output parameters with the result of each cell rather than creating multiple methods in a partial model or something like that.  

I need some advice, tips or any help on how to add a Stored Procedure with out put parameters to my EDMX and then use that data in a View.
0
How to create a datatable with the time format string incremeted with nearest 15 minutes.
I am using vb.net

example:

Dim dt as new datatable

If the string value is 2:32 then the datatable should have rows in time incrementing by around 15 minutes :

Having rows like :

2:45
3:00
3:15

example2:
String value is 4:34 then the datatable should have rows in time incrementing by around 15 minutes :

Having rows like :

4:45
5:00
5:15

Please let me know if you have any further queries.

Regards
2
I have this pnp script which adds a button to a list view ribbon.

It runs and I can delete the button in script and know that is was there and deleted by count.

But, the pnp script to add the button doesn't work until after I had run a console app to add a button to the list.  

It is as though some structure needs to be setup that the pnp script isn't doing.

Here is the pnp script

$cUIExtn = "<CommandUIExtension><CommandUIDefinitions><CommandUIDefinition Location=""Ribbon.ListItem.Actions.Controls._children"">
<Button Id=""Ribbon.List.Items.Action.MyButton"" Alt=""Promote Request"" 
Sequence=""03"" Command=""ShowPromoMoreButtons"" 
LabelText=""Promote Selected"" 
TemplateAlias=""o1"" 
Image32by32=""/sites/Practice/images/Perspective-Button-Reboot-icon-32.png"" 
Image16by16=""/sites/Practice/images/Perspective-Button-Reboot-icon-16.png"" />
</CommandUIDefinition></CommandUIDefinitions>
<CommandUIHandlers><CommandUIHandler Command=""ShowPromoMoreButtons"" 
CommandAction=""javascript: PROMOTION.clickMethod();""/></CommandUIHandlers>
</CommandUIExtension>"

Add-PnPCustomAction -Name "MoreButtonsReq" -Title "Promote This" -Description "MoreButtonsReq" -Location "CommandUI.Ribbon" -Group "SiteActions" -RegistrationType List -registrationId "{gggggggg-gggg-421a-gggg-246b00ef7a82}" -Rights EditListItems -Scope Web -CommandUiExtension $cUIExtn

Open in new window



Here is the console app c#

                SPSite osite = new SPSite(SiteURL);

                SPWeb

Open in new window

0
I have a data model like so:

using System;
using System.ComponentModel.DataAnnotations.Schema;

namespace CB_RepWebApp.Models.DataModel
{
    [Table("FreeStockView")]
    public class FreeStockView
    {
        [Column("ItemCode")]
        public string ID { get; set; }

        public string WarehouseCode { get; set; }

        public string UM { get; set; }

        public Decimal FreeStock { get; set; }
    }
}

Open in new window

And my Item.cshtml.cs page is like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using CB_RepWebApp.Models;


namespace CB_RepWebApp.Pages.Inventory
{
    public class ItemModel : PageModel
    {
        private readonly CB_RepWebApp.Data.CRMContext _context;
        public ItemModel(CB_RepWebApp.Data.CRMContext context)
        {
            _context = context;
            _contextB = context;
        }

        public Models.DataModel.InventoryItem Item { get; set; }
        public Models.DataModel.InventoryItem I { get; set; }
        public Models.DataModel.InventoryItemPricingDetail ItemPricing { get; set; }
        public Models.DataModel.ItemCostPricesView_C ItemCosting { get; set; }
        public Models.DataModel.InventoryUnitMeasureBoxView_C IB { get; set; }
        public Models.DataModel.FreeStockView IFSWA { get; set; }
        public 

Open in new window

0
sample.xlsx sample.xlsxI have a small project that I want to use c# to create sample.txt file and the format is attached. I also have a MS SQL database as a data source.
In general, I will get data from MS SQL and write a record to sample.txt.

Each column (e.g. first name) has start & end position. If the value of first name (e.g) in db is empty, it will just create space.
In c#, I know how to write value to text file, but  I don't know what is the best approach to save the start & end  position for each column (data source).
Can you show me how to do that?


Basically, my question is simiar to https://stackoverflow.com/questions/6497400/c-sharp-replacing-part-of-string-by-start-and-end-position
0
I need to have this converted to JavaScript or TypeScript whichever is easier.

public static SqlDataReader ExecuteReader(string cmd, SqlConnection sqlConnection, SqlParameter[] parameters = null)
        {

            SqlCommand command = null;

            try
            {
                SqlDataReader result;
                command = new SqlCommand(cmd, sqlConnection);
                command.Connection.ConnectionString = DB_Connection;
                command.CommandType = CommandType.StoredProcedure;
                command.CommandTimeout = 0;
                AssignParameters(command, parameters);
                sqlConnection.Open();
                result = command.ExecuteReader();
                return result;

            }
            catch (Exception ex)
            {
//Error trap system
            }

        }

Open in new window

0
Is there any way to build SOAP XML by using C# class,In present approach we are building SOAP XML statically.Please suggest us better way to build from class.

C# Class
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
    [XmlRoot(ElementName = "customerIdentifier", Namespace = "http://cls.chase.com/loyalty/service/profile/message/v0700")]
    public class CustomerIdentifier
    {
        [XmlElement(ElementName = "type", Namespace = "http://cls.chase.com/common/service/business/type/v0104")]
        public string Type { get; set; }
        [XmlElement(ElementName = "value", Namespace = "http://cls.chase.com/common/service/business/type/v0104")]
        public string Value { get; set; }
    }

    [XmlRoot(ElementName = "productIdentifier", Namespace = "http://cls.chase.com/loyalty/service/profile/message/v0700")]
    public class ProductIdentifier
    {
        [XmlElement(ElementName = "type", Namespace = "http://cls.chase.com/common/service/business/type/v0104")]
        public string Type { get; set; }
        [XmlElement(ElementName = "value", Namespace = "http://cls.chase.com/common/service/business/type/v0104")]
        public string Value { get; set; }
        [XmlElement(ElementName = "internalIndicator", Namespace = "http://cls.chase.com/loyalty/service/profile/shared/v0700")]
        public string InternalIndicator { get; set; }
    }

    [XmlRoot(ElementName = "credentials", Namespace = 

Open in new window

0
pagination iteration...

I have a SOAP web service that has a pagination limit of 10000 and a dateinterval input.  how do I iterate through in c# to collect all rows rather than just 10000?
0
I'm working on a small program that will perform basic diagnostics between a client workstation and a server hosting a Microsoft SQL Server instance. Testing the TCP connection on port 1433 is very straightforward. I can just do this:
TcpClient client = new TcpClient("SERVERHOSTNAME", 1433);
if (client.Connected)
{
    MessageBox.Show("Yay!");
}
else
{
    MessageBox.Show("BOO!");
}

Open in new window

Now I need to test UDP on port 1434. I have no trouble sending but haven't figured out how to receive back the response. I have the following:
UdpClient client = new UdpClient();
byte[] bytesToSend = new byte[] { 1 };
IPHostEntry ipHost = Dns.GetHostEntry("SERVERHOSTNAME");
IPEndPoint ep = new IPEndPoint(ipHost.AddressList[0], 1434);
int sentByteCount = client.Send(bytesToSend, bytesToSend.Length, ep);
byte[] receivedBytes = client.Receive(ref ep);

Open in new window

The issue I'm running into now is that the Receive method just hangs there. I think this might be due to the fact that I'm not sending anything meaningful to the SQL Server. Does anyone have any idea what I can send to the server that will actually return any kind of result? Also, how do I set a timeout for this?
0
When using Xamarin.Essentials.Geolocation the command
await Geolocation.GetLocationAsync
fails saying it has to be run in the main thread.

Any assistance or examples appreciated.
0
How do I add Bluetooth receiving to our Android application written using  VS2015 and C#?
0
In C# I'm trying to add a new dynamically created partition to and existing Aggregation Design.

If it is done statically in Visual Studio then deployed there is no problem. But when new companies are added I wrote a script task in the ETL to setup everything on the fly since the multi tenant cube is partitioned by Company.

It seems when done dynamically it is trying to create a schema bound indexed view of sums under the hood and since the underlying facts and dimensions are views themselves this fails.

Question is why is it trying to created this new hidden view. And why when the partitions are added in visual studio to the aggregation design prior to deployment i get no such error?

This is my C# code
                        //If Partition isnt found it needs to be created dynamically. Both the Archive and Current.
                        if (!lbFoundPartition)
                        {

                            //Create the new Archive Partition

                            oNewPartitionArchive = oMeasureGroup.Partitions.Add(PartitionNameArchive);
                            oNewPartitionArchive.StorageMode = StorageMode.Molap;
                            oNewPartitionArchive.Source = new QueryBinding(oDB.DataSources[0].ID, PartitionQueryArchive);

                            if (oMeasureGroup.AggregationDesigns.Count > 0)
                            {
                                oNewPartitionArchive.AggregationDesignID = 

Open in new window

0
Error when trying to call a .ps1 file from c# the "FailoverClusters" module is not available. I am trying to provide some self service administration to people via a web page and the first step in that is getting c# to call a .ps1 file using the Get-Cluster command. It appears that when I call the .ps1 from c# most of the modules are available in that run space but the "FailoverClusters" is not. When I create just a test file to run this command from the c# call, it returns nothing.
get-module -ListAvailable | Where-Object {$_.Name -like "*clust*"}

Open in new window


However when I run the above code in the powershell console as me, I see the module name "FailoverClusters".

I don't know what c# is running under, but whatever user it is running under (assumed me since I am clicking the debug button), does not appear to have access to the FailOverClusters module or commands.

See code....

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using Microsoft.FailoverClusters.PowerShell;

PowerShell posh = PowerShell.Create();
            posh.AddCommand(@"C:\test\Test.ps1");
           
            var results = posh.Invoke();
            Console.Out.WriteLine("Done");
            foreach (var result in results)
            {
                Console.Out.WriteLine(result.BaseObject.ToString());
            }
            Console.Out.WriteLine("Done");
            Console.In.ReadLine();

Open in new window

0
Hi;

I am trying to get value of loglevel and logType from below json logs of ElasticSearch by using Nest Code. LogLevel should be "ERROR" LogType should be "Response". How can I write this Nest query. I think that Nest is Really difficult.


            var settings = new connectionsettings(new uri("http://localhost:9200")).defaultındex("mylog-2019-07-29");

            var client = new elasticclient(settings);

            var searchresponse = client.search<rootobject>(s => s
                                            .allındices()
                                            .from(0)
                                            .size(10)
                                            .query(q => q
                                                 .match(m => m
                                                    .field(f => f.logLevel)
                                                    .query("Error")
                                                 )
                                            ));

            var r3 = client.search<rootobject>(search => search.matchall().ındex("mylog-2019-07-29")).documents;

			// OR 
            var result = client.search<rootobject>(q => q.allındices());
            var result2 = result.hits;

            using (httpclient client = new httpclient())
            {
                var result = await client.getasync("http://localhost:9200");

                var data = 

Open in new window

0
Using C# to load csv to excel using EPPlus.
used a formula in Column H to strip a digit from column A,  but now i want to copy the values and paste over A.
the digit is an apostrophe, which if i strip it before excel, it strips the leading zeros.  
anything we have tried so far will just copy the formula in column H, not the value.
worksheet.Cells[string.Format("I{0}", i)].Value = worksheet.Cells[string.Format("H{0}", i)].Text;

Open in new window

here is the formula in column H
worksheet.Cells[string.Format("H{0}", row)].Formula = string.Format("=RIGHT(A{0}, 9)", row);

Open in new window


Thanks in advance.
0
I would like to solicit your help please.
I would like to call a specific C# feature from within a C++ programming environment, such as:
            Microsoft MSVC 2017 enterprise edition.  The specific C# specific is:          
                              System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() method.

This is not a school project/assignment. From what I have looked at, there is a lot more programming required that I am not able to understand.  Could you help me out please.....  Thank you.
RSVP.   Thad.

This is what I have come up with...
 using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Xml;

 using System.Net.NetworkInformation;  /// they say this "networkinformation stuff is C# material.
 public static BOOL IsAvailable(int * xx) {
       bool IsAvail;
       bool IsAvail = NetworkInterface.GetIsNetworkAvailable();
       *xx = IsAvail;
       return (IsAvail);
 }
0
I have a c# console app which using a 3rd party dll which has a memory leak
We currently run this the code and close the app once complete, and use restart on crash app to run the app every 1 min

We now want to use top shelf windows service to run the app in case machine restarts
However, the code would exit the app after 1 min
I've thought about using task scheduler to run the app, but i need to detect if its currently running as it could be running for 5 mins or just 20 secs

Is there a way to configure the service to keep coming back online after it stops/exits ?
Either in topshelf c# or windows config?
0
Hi Experts,
Am using vs2013 c#. Am trying to call this method from console to get token from api. Please help me with either suggestions about this error and if possible post me some solution.


 private void GenerateNewToken()
        {  
 string tokk=string.Empty;
 clientSecret = string.Format("{0},{1}", "<username>", this.ClientID);
                      clientSecret += string.Format("{0},{1}", "<password>", this.ClientSecret);
                      Uri baseAddress = new UriBuilder() { Scheme = "https", Host = this.SSOUrl, Port = 443 }.Uri;                  
                     var cookieContainer = new CookieContainer();
                     Cookie clientCookie = new Cookie("client_cookie", this.ClientSecret);
                      clientCookie.Expires = DateTime.Now.AddDays(2);
                     // clientCookie.Domain = Request.Url.Host;
                  //clientCookie.Path = "/"; //?

                    var credentials = new NetworkCredential(this.SystemID, this.SystemPassword);


                      using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer, Credentials = credentials })
                      using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
                      {
                          Uri uri = new UriBuilder() { Scheme = "https", Host = this.SSOUrl }.Uri;
                          var byteArray = new UTF8Encoding().GetBytes(clientSecret);
                          …
0
I am using ASP.NET 4.7 (not ASP.NET Core) to design a web page, which receive Webhook request from Dialogflow. I use following code to extract the JSON data from request.

using (var reader = new StreamReader(Request.InputStream))
{
    string reqString = reader.ReadToEnd();
}

Open in new window


However, I found the double quotes in the original request are missing in the content. Original message is

{"responseId":"0b0b6903-60be-4fdf-919b-f20103bfd1ec-21947381","queryResult":{"queryText":"I need to book a hotel room with queen size bed.","parameters":{"size":"queen"},"allRequiredParamsPresent":true,"fulfillmentMessages":[{"text":{"text":[""]}}],"intent":{"name":"projects/aets-mknkjs/agent/intents/1727505d-2499-42c4-95ec-7385b5da17a3","displayName":"hotelbooking"},"intentDetectionConfidence":0.7410408,"languageCode":"en"},"originalDetectIntentRequest":{"payload":{}},"session":"projects/aets-mknkjs/agent/sessions/d55e1ae8-c5d3-1ecf-7d6a-9f27391b6b6c"}

Open in new window


But I extracted from Request.InputStream does not have double quotes.

{responseId:0b0b6903-60be-4fdf-919b-f20103bfd1ec-21947381,
queryResult:{queryText:I need to book a hotel room with queen size bed.,
parameters:{size:queen},
allRequiredParamsPresent:true,
fulfillmentMessages:[{text:{text:[]}}],intent:{name:projects/aets-mknkjs/agent/intents/1727505d-2499-42c4-95ec-7385b5da17a3,displayName:hotelbooking},intentDetectionConfidence:0.7410408,languageCode:en},originalDetectIntentRequest:{payload:{}},session:projects/aets-mknkjs/agent/sessions/d55e1ae8-c5d3-1ecf-7d6a-9f27391b6b6c}

Open in new window


How can I retain or extract the orginal message content?
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).