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

Hello Experts,
Need help to write a service which reads from URL.
Can I request for the code reference to do so.

Regards
0
Hi folks,

I have a single-objective optimisation problem. I have a network of pipeworks (pipes + fittings) with various routes, one of them will be the critical route. Designing such systems require to size the pipes and fittings accordingly in order to satisfy local rules related to individual elements (minimum allowed velocity, pressure, etc.), and global rules that have to do with the entire system (i.e hydraulic losses along each considered flow rout). The optimum design should is defined to be the cheapest option that satisfies all defined rules (local and global). While we could iterate through all standard size for pipes, starting from minimum size until a solution is achieved. However, there are challenges in such approach such as the enormous space solution, the nonlinearity of the specified problem and various solutions to explore, the include the possibility of splitting a single pipe into segments with different sizes and new fittings between them, which will add new pressure losses to the system. I was wondering what is the best and simple optimisation problem that I can adopt here? and how it could be implemented in visual studio using C# (though I am a beginner programmer). Any help in this would be highly appreciated.

Many thanks,
Aziz
0
Hi guys,

I am having a really weird issue with sql server deployment. So here is the scenario:

I have a SSIS package which is using a C# user component that reads a file and inserts in a sql server database. When I run package from visual studio, it runs fine, does the insert in sql server which is on a different machine and life is good. Now, I deployed this SSIS package to a sql server and then try to run the SSIS from sql server and I get this error:

OLE DB Destination Input has lineage ID 2000 that was not previously used in the Data Flow task.

OLE DB Command Input has lineage ID 3281 that was not previously used in the Data Flow task.

The buffer type is not valid. Make sure the Pipeline layout and all components pass validation.

INSERT INTO <tablename> failed the pre-execute phase and returned error code 0xC0202020.


Both development machine and Sqlserver machine are 64 bit.

Have been scratching all my hairs out but still can't figure out. Package runs completely fine when I run this in visual studio.

I also copied the C# dlls used by SSIS to the sql machine:

C:\Program Files (x86)\Microsoft SQL Server\110\DTS\PipelineComponents

C:\Program Files\Microsoft SQL Server\110\DTS\PipelineComponents

is this a deployment issue? Because Package runs completely fine from visual studio.

I seriously need some quick help.

I really appreciate it guys.
0
Hi Experts,
How can i show a simple modal pop up in MVC? I have a log in page. When it is a valid login, it takes me to the main page. On the top of main page I need modal pop up with a messge "Welcome X" and some other static contents.

Please help.
Thanks in advance!
0
This is more of an architecture question and high level

We have a vehicle tracking system which has 1 sql server database
we currently see in the region of 400 records a sec on the data import side (which will keep growing and growing)


my concern is
1. reliance on 1 db
2. load on this db will slow down web app, as we process more records per sec it eventually get too busy,

we already use signalR to push to data to client, but older data or reports etc hits the DB
on data import, we use the DbId of each record to further process data (get dumped to rabbitmq and then picked up by microservices like a notification service)


We have been discussing using a 2nd db for replication but that will not seem to solve the load issue
we have also been discussing pushing everything directly to a cache like redis, and also to the db on data import, and then the web looks to the cache

However i'm concerned redis is a key value pair db and sql is a rdbms, so i'm not sure how querying redis will be anything near sql

I would value input on the above
I'm not opposed to moving to MySql (maria db) or other options, but it seems rdbms solutions fit a tracking system very well as you query different columns etc and there is a lot of work and code that already exists, so moving to nosql etc is not a favourite idea

i would like to have some redundancy though, so putting data across regions is appealing
we have lots of small tables like users, etc
and one massive table…
0
What is the best way to introduce a new object to existing classes, in my project i have several classes and now i am implementing reporting and have to log some messages whenever a method execution is failed

Is it a good practice to create object of the new class in all the existing classes or is there any other way?

trying to minimize the code changes

Initial set of code

Class one{

public void method1() {

     try
     {
          //perform something
       }
       catch(Exception ex){
           S.o.p("some message")
        }
  }

public void method2() {

     try
     {
          //perform something
       }
       catch(Exception ex){
           S.o.p("some message")
        }
  }

}



Class Two {

public void method1() {

     try
     {
          //perform something
       }
       catch(Exception ex){
           S.o.p("some message")
        }
  }

public void method2() {

     try
     {
          //perform something
       }
       catch(Exception ex){
           S.o.p("some message")
        }
  }

}

class Test
{
   public static void main(String args[]){
         One o = new One(); 
         o.method1();
         o.method2();

         Two t = new Two();
        t.method1();
        t.method2()
   }

}

Open in new window


Code after introducing a new Class (for Ex: Logging for reporting)

   

Class One{

    Private ReportLogger report;

    Public One(Report report)
    { 
         this.report = report;
     }
 

Open in new window

0
Hello,
I am getting an error 'Parameter is not valid'
   Using ms As New MemoryStream(imageData, 0, imageData.Length)
                            ms.Write(imageData, 0, imageData.Length)
                            Try
                                image = Image.FromStream(ms, True)
                                Dim oldbitmap As Bitmap = (image)
                                clsFrmain.ScaleImage(PicImageFin, oldbitmap)
                                OriginalimageLoaded = oldbitmap
                                PicImageHeight = PicImageFin.Height
                                PicImageWidth = PicImageFin.Width
                            Catch ex As Exception
                            End Try
                        End Using

Open in new window

It usually happens for large files especially PDF.

Any suggestion.

Thanks
0
I am creating the WebGrid on the code behind, and am trying to get the cell value so I can format depending on the value.

This is the code I am currently using to populate the WebGrid which works well.  I would like to loop through the rows get a certain cell value and then change the font color how can I do that?

            IGrid<LastActivity> grid = new Grid<LastActivity>(rptRepository.GetLastActivity());
            grid.ViewContext = new ViewContext { HttpContext = HttpContext };
            grid.Query = Request.Query;

            grid.Columns.Add(model => model.OppOwner).Titled("Owner");
            grid.Columns.Add(model => model.OppCount).Titled("Count");


            grid.Id = "grdLastActivity";

            grid.Pager = new GridPager<LastActivity>(grid);
            grid.Processors.Add(grid.Pager);
            grid.Pager.RowsPerPage = 10;

            var oppcount = grid;

            foreach (IGridColumn column in grid.Columns)
            {
               
                column.Filter.IsEnabled = false;
                column.Sort.IsEnabled = true;
 
            }

            return grid;

Open in new window

0
How digitally signature pdf document using e-token in c#? We are provided with a device "ePass 2003 Auto" (USB)
0
hello, expert.
I can't open the project I shared as zip.
I don't know why  don't it to work.
This project is related to the health sector.
This project is written in c # language.
thanks alot.
when I compiler the project, it gives the following error.

There was no endpoint to listen to at http: // localhost: 18699 / HealthFacilityService.svc. This is usually caused by an incorrect address or SOAP action. See InnerException, if available, for details.

Open in new window

0
This is a follow up question to a solution previously provided.

I am reading an Excel spreadsheet and I have come to a column that is defined as date in the spreadsheet.
MessageBox.Show( "The date value is : " + xlRange.Cells[i, j].Value2.ToString()) gets  me 367
However it understands
if (xlRange.Cells[i, j].Value2.ToString() != "0/0/0000")
and when the date is 0/0/0000 if does go to the correct branch.  How can that be?
DateTime.FromOADate(xlRange.Cells[i, j].Value2).ToString(); will convert to the correct date string.

My question is what is the correct way to handle date columns in C# when reading a spreadsheet?
What is that value? Is it a string, and integer or something else?

My apologies for asking such a basic question but I have found this perplexing.
0
I have found myself cornered, so here we go.

Context

I need to produce a fingerprint hash code for object diffing. Comparing the hashes of two sets of objects will need to tell me if there are identical objects with the same hash.

The fingerprint hash must be platform-independent. So I went for **MD5 hashing**. Any equivalent would do.

I am working with a large base of legacy code. All **classes can not be modified**. I cannot add attribute or constructors or modify anything.

Performance is not a concern. **Reflection has complete green-light**.

In addition, I will need to be able to *control the exclusion of properties from the hashing*. If I exclude a certain property, two object that have all the properties identical to each other except that one will still need to get the same hash.


Issue: serializing to `Byte[]` with hands tied on the legacy code

MD5 hashing requires the object to be Serialised in Byte[].

The serialisation requires the class to be marked as `[Serializable]`. Which I cannot add to the legacy code, and naturally it [can not be added at runtime either](https://stackoverflow.com/a/26957174/3873799).

So I went for **`protobuf-net`**.

Protobuf rightly fails when encountering types that implement an interface with Getter-only auto-properties:
public interface ISomeInterface
{
        double Vpy { get; }
        double Vy { get; }
        double Vpz { get; }
        ...
}

Open in new window

Being this Interface implemented by many types, using Surrogates
0
Hi Experts!

Trying to create a Selenium test class (MSTest) in C#. Would like the browser to fire up only once before we run all tests from Test Explorer,
so that for each test method it would be able to use the same browser.

Running the following code below we have this error:
SetupToRunOnceBeforeAllTestsRun has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext. Additionally, if you are using async-await in method then return-type must be Task.

SearchPageTest
[TestClass]
    public class SearchPageTest : BasePageTest
    {

        private SearchPage searchPage { get; private set; }
        private SearchCriteria searchCriteria;

        [ClassInitialize]
        public void SetupToRunOnceBeforeAllTestsRun(TestContext context)
        {
            driver = GetChromeDriver();
            searchPage = new SearchPage(driver);
        }

        [TestMethod]
        [TestCategory("IntegrationAutomation"), TestCategory("UI"), TestCategory("SearchPage")]
        public void SearchPage_GoToSearchPage_Success()
        {
            //Arrange
   
            //Act

            //Assert            
            Assert.IsTrue(searchPage.GoToSearchPage().IsPageVisible);
        }
        
        [TestMethod]
        [TestCategory("IntegrationAutomation"), TestCategory("UI"), TestCategory("SearchPage")]
        public void SearchPage_SomeOtherTest_Success()
        {
            

Open in new window

0
I am using Entity Framework 6 in an MVC 5 project with a SQL database. One of the tables in the database uses integer values for the status_id. I want to assign those values a name in the view rather than presenting the integers. I am having difficulty determining the best way to handle this. My first thought was using a foreach loop but I am having difficulty with the syntax and that may not be the best route.

Relevant part of the View to this question (code remove for brevity)

@model Models.Meeting

@{

    ViewBag.Title = Model.Customer1.Name;
}

<body>
    <div id = "MeetingDetails" class="EmailDetails">
        <h2>Meeting Details</h2>
        <hr />
        <dl class="dl-horizontal">
            <dt>
                @Html.DisplayNameFor(model => model.Customer1.Name)
            </dt>
            <dd>
                @Html.DisplayFor(model => model.Customer1.Name)
            </dd>
            <dt>
                @Html.DisplayNameFor(model => model.Customer1.status_id)
            </dt>
            <dd>
                @Html.DisplayFor(model => model.Customer1.status_id)
            </dd>
            <br />
        </dl>
    </div>
</body>

Open in new window


Relevant portion of Controller (code removed for brevity)
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Meeting meeting = db.Meetings.Find(id);
            if (meeting == null)
            {
                return HttpNotFound();
            }
            foreach (string download in Request.Files)
            {
                if (Request.Files[download].FileName != "")
                {
                    string path = AppDomain.CurrentDomain.BaseDirectory + "/uploads/";
                    string filename = Path.GetFileName(Request.Files[download].FileName);
                    Request.Files[download].SaveAs(Path.Combine(path, filename));
                }
            }
            return View(meeting);
        }

Open in new window


Model Diagram
Model Diagram for Two Tables
Partial screenshot of Details View. The value in the Prospect Status row is the integer value in the status_id in the Customer table.

TestMeetingDetailsScreenshot.JPG
0
Hi,

I am working on .net using c#

I am posting data in method PostAsJsonAsync using package System.Net.Http.

Please advise me with my findings.

I am getting  response as

ReasonPhrase = "Unauthorized" string
StatusCode = "BadRequest" System.Net.HttpStatusCode

Not sure but looks to me that url(https://edg-dev-sit.dfdegg.net/loyalty/identity/v2/ssotoken) where I am submitting the data is not allowing data to be submitted from myside.

or Allow origin is not done.

I am not sure. Please help me with my finding.

My code is
HttpResponseMessage response = mHttpClient.PostAsJsonAsync<T>(uri.ToString(), data).Result;

where 
uri.ToString() is https://edg-dev-sit.dfdegg.net/loyalty/identity/v2/ssotoken

and data is { grantType = "authorization_code", authorizationCode = "umKTS4bKXOedNSjuv2rq" }

Open in new window



mHttpClient is as follows:

System.Net.Http
private HttpClient mHttpClient = null;

mHttpClient = new HttpClient(httpClientHandler)
            {
                Timeout = timeout,
                DefaultRequestHeaders =
                {
                    AcceptEncoding =
                    {
                        StringWithQualityHeaderValue.Parse("gzip"),
                        StringWithQualityHeaderValue.Parse("deflate")
                    },
                    CacheControl = new CacheControlHeaderValue() { NoCache = true }
                }
            };

Open in new window


My response (HttpResponseMessage response) is as follows.
See screenshot attached.


Open in new window

0
I am sending a post request to secure soap service from C# .net application, i am getting return status ok, but server is not receiving my request. but when i am sending request from SOAPUI, then server is receiving request. please solve this issue.
0
I am getting this error message

Unable to determine the principal end of an association between the types 'Delta_Manager.Models.User' and 'Delta_Manager.Models.User'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

We had a member and user table.  I Just combined it into one table  And removed the Member class and added all the fields into the User Class

my class looks like this

    [Table("Contacts")]
    public class User : Register
    {

        public User()
        {
        }

        public Guid ActivationCode { get; set; } 

        public bool Activated { get; set; }

        public string CompanyName { get; set; }

        public string Password { get; set; }

        public override string TextReference
        {
            get
            {
                StringBuilder _text = new StringBuilder();

                _text.Append("UserName ").Append(MemberName).Append(" from ").Append(CompanyName);
                _text.Append(" Email ").Append(Email);
                _text.Append(base.TextReference);

                return _text.ToString();
            }
        }

        public string MemberName { get; set; }
        //    Get
        //        Return RoleNameValue
        //    End Get
        //    Set(ByVal value As String)
        //        RoleNameValue = value
        //    End Set
        //End Property

        public string Email { get; set; }


       

Open in new window

0
Hi, I need to understand if I planing to develope software
"
How will I organise and proceed to your final solution"
any tips much appriciated
0
Hello Folks,

In .net application when image is processed & merged with another image then its colors are affected.
Image image  ---------> Uploaded image
Bitmap xy = new Bitmap(image, image.Width, image.Height);  -----> Conversion into Bitmap to 

Open in new window

perform various operations like resize or merge with another image
So the “image” object has few “PropertyItems” and when we convert image to Bitmap type of object then these “PropertyItems” array is empty, that means these “PropertyItems” were not moved in this conversion.

Please find below snap shot before before move to Bitmap object.
Please find below snap shot before before move to Bitmap object
Now after this image is moved into Bitmap object for resize purpose and “PropertyItems” array is empty
After this image is moved into Bitmap object for resize purpose and “PropertyItems” array is empty
Actual Image
Actual Image
After processing through Bitmap
After processing through Bitmap
Note: This image is captured through Canon DSLR camera.

Questions
1. What is the reason behind that “PropertyItems” array is empty when convert image to Bitmap type of object.
2. How these properties can be managed when I need to merge two images (using “Graphics” class) and I don’t want forcefully to apply one image’s “PropertyItems” on to other image, to keep original colors of each image respectively.
3. What is the real solution to merge two different images with different quality and PropertyItems with each other and produce quality end result image.
4. Do you any other thoughts?


Best Regards,
Mohit Pandit
0
I need to print a range of reports from an SQL DB. I have the report created to let the user select a report, then view it with the option to print. The client wants to be able to print all reports (statements) in the database and or select a range by date.

I am developing in VS2019 Pro, WinForms App, C#, SQL DB. I am using C1FlexReport, but an example in VS controls should work.

So I need to determine how many statements exist in the master/detail tables, iterate through them printing each one. No need to view, just print.

Any sample code would be helpful (just the routine to iterate through the statements)

Thanks so very much for any help...
0
I am importing an Excel csv file.  Have path to the CSV file.

Using C# I have:

IEnumerable<string> fileLines = File.ReadLines(Product_BoM_CSV_path, Encoding.Default);

foreach (string line in AllLines)

Open in new window


The code works OK up to the loop.  In the foreach how do I read each column in the line?
0
We want to include digital signature into our .pdf file. What is the best way to do this? Pdf file is the invoice generated for customer and it will contain multiple rows based on number of products purchased. This means the digital signature will not be at a fixed position. It will scroll down when many product rows are displayed.
Digital-Signature.png
0
I want to remove the windows installed applications with this line...

Get-AppxPackage -allusers PackageFullName | Remove-AppxPackage

Open in new window


I tried running it in a batch file, it did not work. No error, but the script that works correctly when not in a batch file is not running in it, so I decided to make it a little bit fancier since it was going to take me some time to figure it out.

I am trying to run that powershell script above in a C# application now. I can't seem to get this figured out. No matter what I have tried nothing actually happens.
0
I'm stuck.  The following is a working procedure, but i need to run a where clause so that i only return (A) records that meet the criteria on the (B) joined table, after the join is complete.  So if (A) returns 3 records, I want to filter on (B) joined items that meet a filter requirement and only return the (A) records that had (B) items in filter.   Also, i'm using DTO's to frame the data to my needs.  It was the only way i could figure out how to avoid some heavy columns in the resulting query.

        public static IEnumerable<DocumentsLite> GetSearchLite(string search)
        {
            IEnumerable<DocumentsLite> docs = null;
            using (var db = new Entities())
            {
                docs = db.DOCUMENTS.Select(doc => new DocumentsLite()    // *** (A) ***
                {
                    id = doc.ID,
                    create_dt = doc.CREATE_DATE,
                    file_name = doc.FILE_NAME,
                    doc_params = db.DOCUMENT_PARAMETERS.Select(param => new DocumentParams   // *** (B) ***
                    {
                        id = param.ID,
                        doc_id = param.DOCUMENT_ID,
                        param_name = param.PARAMETER_NAME,
                        param_value = param.PARAMETER_VALUE,
                    })
                    .Where(param => param.doc_id == doc.ID ),

                    doc_thumb = db.DOCUMENT_THUMBS.Select(thumb => new DocumentThumb   // *** (C) ***
                    {
  

Open in new window

0
Hi,

How can I unbox and C# object reference and covert it to "System.Diagnostics.EventLogInternal". Specifically I want to be able to get the source.log parameter.
(I want to have an event watcher for multiple logs).

Thanks,

Ward.

Here is my code below:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;

namespace Event_Tracer
{
    public partial class MainForm : Form
    {
        EventLog myLog;
        private static MainForm _instance;

        public MainForm()
        {
            InitializeComponent();
            _instance = this;
        }

        private void Button_Scan_Click(object sender, EventArgs e)
        {
                string watchLog = "Application";
                myLog = new EventLog(watchLog);
                // set event handler
                myLog.EntryWritten += new EntryWrittenEventHandler(OnEntryWritten);
                myLog.EnableRaisingEvents = true;

        }

        private void fnDisplay_Event(EventLogEntry e,object source)
        {

            dataGridView_events.Invoke(new Action(() =>
            {
                dataGridView_events.Rows.Add(source,e.TimeGenerated, e.EntryType,e.InstanceId,e.Message);
            }));

        }

        private static void OnEntryWritten(object source, EntryWrittenEventArgs e)
       

Open in new window

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