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 have a View using a Grouped DataTable like this:

@model List<master.Models.tbl_Data>


<table class="DTStyle filteredgroupedtable_14">
    <thead>
        <tr>
            <th>
                Field 2
            </th>
            <th>
               Field 1
            </th>
            <th>
                Field 3
            </th>
            <th>
               Field 4
            </th>
            <th>
                Field 5
            </th>
            <th>
               Field 6
            </th>
            <th>
               Field 7
            </th>
            <th>
                Field 8
            </th>
            <th>
                Field 9
            </th>
            <th>
               Field 10
            </th>
            <th>
                Field 11
            </th>
            <th>
               Field 12
            </th>
            <th>
                Field 13
            </th>
                    </tr>
    </thead>
    <tbody>
        @for (int j = 0; j < Model.Count; j++)
        {
            <tr>
                <td>
                  @Model[j].Field2
                </td>
                <td>
                    @Model[j].Field1
                </td>
                <td>
                    @Model[j].Field3
                </td>
                <td>
                    @Model[j].Field4
                </td>
                <td>
                    @Model[j].Field5
                </td>
                <td>
                    

Open in new window

0
I have the following db string  inside of my web app. The localhost work but the live website does not work. do you know how to fix it?
Both DB/IIS is in the same AWS instance.

 <add name="ConnectionString" connectionString="Data Source=WIN-GB8M3MM6asdfasdT2M\SQLEXPRESS;Initial Catalog=Pwr;Integrated Security=True;"
      providerName="System.Data.SqlClient" />
0
I've been having trouble returning an Id from my listview to use for deleting a record.  I have a SQLite table that feeds a list adapter.  Here is my class:
public class EOMCountsheet
    {        
        [PrimaryKey, AutoIncrement, Column("-id")]
        public int Id { get; set; }
        [MaxLength(6)]
        public string Location { get; set; }
        public int InventoryCount { get; set; }
        public string Part { get; set; }
        public string UserID { get; set; }
        public string UniqueStamp { get; set; }
    }    

Open in new window


Here is the Adapter and _listView1.ItemClick:
            string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "CountSheet.db3");
            var tablelistout = new SQLiteConnection(path);
            var list = tablelistout.Table<EOMCountsheet>().OrderByDescending(t => t.Id).ToList();
            var data = new List<string>();

            foreach (var listing in list)
            {
                data.Add(listing.Id + "  " + listing.Part + " - " + listing.InventoryCount);
            }

            ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(Activity, Android.Resource.Layout.SimpleSelectableListItem, data.ToArray());
            listAdapter.NotifyDataSetChanged();

            //_listView1.Adapter = listAdapter;
            //***************************************************************************************************

            _listView1 = EOMScanFragment.FindViewById<ListView>(Resource.Id.listView1);

            _listView1.ItemClick += (object sender, AdapterView.ItemClickEventArgs e) =>
            {
                ///GRAB ID HERE AND PASS TO DeleteRow()
                var item = _listView1.SelectedItemId;
                

            };
            _listView1.Adapter = listAdapter;

Open in new window


Could someone please give a little guidance?  Thanks in advance!
0
I need  to run about  30 payroll scripts (doing  Inserts  , Update Delete) into a postgresql database from my c# application.

The whole scripts must either succeed or  fail with a roll back.

The script must run from more than 3  places in the application

First i decided that  to have scripts run from different places in my application i need to have the script  called from a library
(Is this assumption correct ?)

So I created a Payrollprocessor in my Library

Under my  Run Payroll Button I have the rough structure  of what i need to do as shown below:

Handling Transaction Under a Click Button Event
with  the code also shown  below:

 private void button2_Click(object sender, EventArgs e)
        {
            
            try
            {
                BEGIN TRANSACTION;
                PayrollProcessor processor = new PayrollProcessor();
                //script01 = processor.writetolivefile;
                //script02 = processor.ClearParollTable;
                END TRANSACTION;
            }
            catch (Exception)
            {
                transaction.Rollback();
                throw ex;
                
            }
        }

Open in new window


The issues i need to resolve are:

1. Since i have about 30 script with each one accessing the database for inserts, updates and delete how do i
ensure that commits  are only done once, particularly since each visit  would execute a stored procedure.
How do i stop one stored procedure from committing until all …
0
I have a c# application with a Grid
I have a combo box withing the  Grid  displays  3 fields  of a Record

Below is the Grid   with the combo boxCombo Loaded with Records [3 fields  per Record]
The combo is loaded with the code below:


            dgvtxtentcode.DataSource = GlobalConfig.Connection.GetGradedItemCodes_All();
            dgvtxtentcode.ValueMember = "ent_code";
            dgvtxtentcode.DisplayMember = "FullTypeTabName";

The Display in the Grid is from the script below:

  public string FullTypeTabName
        {
            get
            {
                return $" {Ent_type} { Ent_code } {Ent_desc }  ";
            }
        }

Open in new window



When i select a record from the combo I want to fill 2 fields in the grid  as below

this.dgvDetailsTable.CurrentRow.Cells[1].Value = ent-_type
this.dgvDetailsTable.CurrentRow.Cells[2].Value = ent_code

In the first record  ent_type = "A
 and ent_code = "BASIC"

I am using the script below:

 if (SaveButton.Text == "Save")
            {
                // if (e.ColumnIndex >= 0 && Convert.ToInt32(PayRateIdValue.Text) > 0)
                if (e.ColumnIndex > 0)
                {
                    //var dgvDetailsTable = (sender as DataGridView);
                    //PayRateIdValue.Text = dgvDetailsTable.CurrentRow.Cells[8].Value.ToString();
                    
                    switch (this.dgvDetailsTable.Columns[e.ColumnIndex].Name)
                    {
                        case "dgvtxtgradeamt":
      

Open in new window

0
C#, trying to run multiple tasks, want each task to write out #i finished when it is done!
this is my code:

or (int i = 0; i < 5; i++)
            {                
                Task task = Task.Factory.StartNew(() => run()).ContinueWith(t=>dspR(result+="Task# "+i+" Done!\n"));
            }    
All tasks finish with: Task#5 Done!
How can I get #1,#2,#3.. ?
Or I can do with task ID instead of just numbers.
0
I use a datatable to do some sorting for a GridView

dtSort.DefaultView.Sort = e.SortExpression + (string)((e.SortDirection == SortDirection.Ascending) ? " ASC" : " DESC");

Then I save the dtSort in ViewState["DataTable2"].
And then use it with the GridView. And it get sorted. Sorting works great in the GridView.

But when I set this same sorted datatable (ViewState["DataTable2"]) as DetailsViews datasource it looks like the sortorder not comes here.
Then the PageID is not the same as the rowindex in the GridView. I got the rowindex from the DataTable and not from the GridView so it should work in both GridView and DetailsView objects?

What do I miss? Looks like it works different in GridView and DetailsView?
0
Hi
I'm trying to add items to a flowlayoutpanel  something like the picture

kate.JPG
I've managed a picture but the hover is failing because BigPicturePath is being overwritten
so
1. How do I use the picture.tag to pass the url into ThumbPictureBox_MouseHover method
2. How Do I adjust the linq query to order on movies.movielinkpersons.role

3. In order to create the picture example I'm guessing I'd need to create a 2 X 2 TableLayoutPanel with Col1 rowspan of 2 adding a Picture box to col1 a label to col2 row1 (with a click function) and a button to Col2 Row2

What concerns me is my form has a 3 column TableLayoutPanel with a second TableLayoutPanel  in the center column with the flowlayoutpanel   in 1 cell show here

FilmForm.JPG
In the code bellow GetCast is triggered on clicking a title  in a listview

        private void GetCast(int id)
        {
            using (var context = new MoviesEntities())
            {
                var Movies =  context.movielinkpersons.Where(p => p.movieId == id).ToList();
                int i = 1;
                foreach(var person in Movies)
                {
                    string Thumb = "";
                    if (person.person.profile_path == "/JohnWayneBig.png")
                    {
                        Thumb = ImgPath + "JohnWayneSml.png";
                        BigPicturePath = ImgPath + "JohnWayneBig.png";

                    }
                    else
                 

Open in new window

0
Correct philosophy/topology for  SQLite syncing back to Azure.
And querying items in Azure/storing in SQLite
I have just learn that in UWP you cannot store a .DB file in the solution and connect to it with code, instead the .db file is created in a place in appdata when the app is started.
This means I cannot load up the .DB file prehand with lots of data to be used by the app. This must mean the .DB file needs to “sync” in someway to the main data storage this is touched on in this Microsoft doc
https://docs.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-windows-store-dotnet-get-started-offline-data

My question is what is the correct philosophy/topology to obtain data stored in Azure interact with that data in a UWP app and then sync that data back up to Azure?
0
THis is a duplicate question that i asked on a reddit subforum.
but without much response.
https://www.reddit.com/r/UWP/comments/cth82z/is_it_just_me_or_is_there_not_1_single_good_guide/

Iv been looking for weeks to find a comparable guide on using a UWP app with SQLite. All the guides i find are either out of date or using nugget packages that no longer exist. or provide super complex methods.

Im using VS 2019 Community

with this: https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Sqlite/

Trying to connect to a local .DB file

Maybe i am just not googling the correct words?

Does anyone know of a good resource that demonstrates how to connect to a local .DB file submit entry's and retrieve entry's?
0
I've been following this guide: https://blogs.msdn.microsoft.com/appconsult/2018/05/06/using-the-navigationview-in-your-uwp-applications/

I have my Menu items together and they act great!
However when I open the app I am having trouble setting the default view I have made a homepage when the app opens I would like the homepage to display. When using the code line in the guide it throws an exception. Screenshot:Screenshot--57-.pngHere is the code in the guide:
   
       if (item is NavigationViewItem && item.Tag.ToString() == "Home_Page")
          {
                nvTopLevelNav.SelectedItem = item;
                break;
          }
      }

Open in new window


hopefully its something simple i am doing wrong. my homepage location is Views.HomePage

Screenshot of landing page.
Screenshot--71-.png
Full code (abit messy i know):
 MainPage.xaml

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:RussMenu"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:Custom="using:Microsoft.Toolkit.Uwp.UI.Controls"
    x:Class="RussMenu.MainPage"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <NavigationView x:Name="nvTopLevelNav"
                Loaded="nvTopLevelNav_Loaded"
                

Open in new window

0
I have a   script that tries to write to a postgresql database with the script below:

Script that does Insert into a postgresql database
If you observe the line  commented out  . I was able to insert into the database using the query analyser

I reviewed  the log after  the error and the application request an explicit type CAST

See  error below

2019-08-20 17:55:37 PDT ERROR:  function public.sppayrates_updateinsert(curgrdx => character varying, enttypex => character varying, entcodex => character varying, gradeamtx => numeric, filterfieldx => character varying, companycodex => character varying, validrecordynx => character varying, payrateidx => integer) does not exist at character 15
2019-08-20 17:55:37 PDT HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
2019-08-20 17:55:37 PDT STATEMENT:  SELECT * FROM public.sppayrates_updateinsert("curgrdx" := $1,"enttypex" := $2,"entcodex" := $3,"gradeamtx" := $4,"filterfieldx" := $5,"companycodex" := $6,"validrecordynx" := $7,"payrateidx" := $8)
2019-08-20 18:00:54 PDT ERROR:  function public.sppayrates_updateinsert(unknown, unknown, unknown, integer, unknown, unknown, unknown) does not exist at character 8
2019-08-20 18:00:54 PDT HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
2019-08-20 18:00:54 PDT STATEMENT:  SELECT public.sppayrates_updateinsert(
	    'TR3C',
	    'A',
	    'BASIC',
	    50000,
	    'P',
	    'NNPC',
	    'Y'
	);

Open in new window


How do i do an explicit cast type

I have  text , decimal and integer  columns .

I will like to know how to do an explicit cast  each type of data

Thanks

Olukay
0
I have a table in my View.  I want the user to be able to click on a link to view related information in a modal.  I need help implementing this.  

My View just loops thru a list displaying those in a table:

 <tbody>
            @for (int j = 0; j < Model.Count; j++)
            {
                <tr>
                    <td>
                                INSERT LINK TO MODAL HERE FOR  @Model[j].Name
                    </td>
                    <td>
                        @Model[j].Field2
                    </td>
                    <td>
                        @Model[j].Field3
                    </td>
</tr>
 </tbody>

Open in new window

0
I have a form with multiple Text fields.  I need to check when the user completes the form if all of the fields match an entry already in the database.  If so, return a message and send them back to another View - perhaps the one matching their entry.  

Here is my form:  I have several more fields but just included a few as an example

    @using (Html.BeginForm("Add", "MyController", FormMethod.Post, new
    {
        name = "NewForm"
    }))
    {

        <div class="panel panel-info" style="position: relative;">
            <div class="panel-heading">Add Information</div>
            <div class="panel-body">
                <div class="col-xs-12">

                    <div class="row" style="margin-top: 0; margin-bottom: 5px;">
                        <div class="col-xs-6">
                            <div style="color:red;padding-bottom:0px; display:inline">*</div>
                            @Html.Label("Select Field 1")

                        </div>
                    </div>
                    <div class="row" style="margin-top: 0; margin-bottom: 10px;">

                        <div class="col-xs-6">

                            @Html.DropDownListFor(x => x.field1, sl.getField1List(), new
                       {
                           @type = "drop",
                           @id = "field1",
                       })
                            <div class="error">
                                @Html.ValidationMessageFor(x => x.field1)
          

Open in new window

0
Hi
Building on an earlier question

I'm trying to create a Winforms Application

Although related I've split this into 2 questions

I'd like to create an Autocomplete to search   and filter the movies by actor/ person name

I've built Autocomplete in other languages  eg jQuery this is a two step process 1st a list of possible options 2nd  you have an OnSelect action I don't seem to be able to find similar in .Net  so the code bellow is running Loading the  Titles in ListView, if the entire name if correctly typed, with out being able to make a selection

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.IO;
using System.Windows.Forms;
using MoviesDataModel;

namespace FilmsDB
{
    public partial class Form1 : Form
    {
        public string ImgPath = @"E:\Media\thumbs\Movies\";
        public Form1()
        {
            InitializeComponent();
            TitlesLV.View = View.Details;
            ColumnHeader columnHeader = new ColumnHeader();
            columnHeader.Text = "Film Title";
            columnHeader.TextAlign = HorizontalAlignment.Center;
            columnHeader.Width = -2;

            TitlesLV.Columns.Add(columnHeader);
            LoadMovies();
        }

        

Open in new window

0
Hi
Building on an earlier question

I'm trying to create a Winforms Application

Although related I've split this into 2 questions

I can run a query and add a list of All movie titles into a listview but when I click an item I cannot access movie properties to populate the form elements adding a watch to movie
MovieID.JPG
MovieID1.JPG
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 MoviesDataModel;

namespace FilmsDB
{
    public partial class Form1 : Form
    {
        public string ImgPath = @"E:\Media\thumbs\Movies\";
        public Form1()
        {
            InitializeComponent();
            TitlesLV.View = View.Details;
            ColumnHeader columnHeader = new ColumnHeader();
            columnHeader.Text = "Film Title";
            columnHeader.TextAlign = HorizontalAlignment.Center;
            columnHeader.Width = -2;

            TitlesLV.Columns.Add(columnHeader);
            LoadMovies();
        }

        private void LoadMovies()
        {
            TitlesLV.Items.Clear();
            using (var context = new MoviesEntities())
            {
                //get a full list of all movies (will return everything from 

Open in new window

0
Hi,

My response[0].Body[0].Content has the following value:
{"title":"StudentRecord", "students":[
					{"name":"Josh", "age":"45", "sex":"male}, 
					{"name":"James", "age":"18", "sex":"male}, 
					{"name":"Emily", "age":"25", "sex":"female}, 
					{"name":"Nate", "age":"33", "sex":"male}, 
					{"name":"Nichole", "age":"19", "sex":"female}, 
					{"name":"Janet", "age":"21", "sex":"female}
				      ]
}

Open in new window

What I want to do is remove all the students but the first and last ones from students array so that the result becomes
{"title":"StudentRecord", "students":[
					{"name":"Josh", "age":"45", "sex":"male}, 
					{"name":"Janet", "age":"21", "sex":"female}
				      ]
}

Open in new window


I tried like
var myObj = Newtonsoft.Json.Linq.JObject.Parse(response[0].Bocy[0].Content.ToString());
I know how to remove a property totally, but not partial values from the array.
I am also not sure if I have to convert it to JObject first since then I have to convert it back to the original type of response.

Is there any easier way to solve this issue?
0
I need to add grouping to this method:

[HttpPost]
        public JsonResult GetData(string variable1, string variable2, string variable3)
        {
            string[] reportData = (from x in DB.GetDetails().ToList()
                            where x.field1 == variable1
                            && x.field2 == variable2
                            && x.field3 == variable3
                            select x.field4).ToArray();

            return Json(new { option = reportData });
        }

Open in new window


I get duplicate values and need to group the data or add a Distince to the reportData.  I'm not sure how to go about this.  Thanks for any help!
0
Hello,

I need to load data on scroll. So is there any option i can use. I am using windows form .NET normal dropdown but  if i just load data  , as the data is very large it takes lot of time. I am thinking to load data or items in dropdown on scroll. Not getting any option. Please suggest if anything i can use.

Thanks.
Abhilash
0
Hi

I'm using an SQLite  database which doesn't  play nice with Entity Framework

I've been enhancing a previous question here  

in SQL to use LIKE you need to use the '%' wild card eg

Select * from movie where title like '%Big%'

Open in new window


In the code bellow I'm building the query thus
string fName = "%" + Path.GetFileNameWithoutExtension( fi.Name) + "%";

Open in new window

and sending that as a Parameter
Is that the best to do it?

The main part of my question is how do I return a list of movies instead of the last one wins?

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;

using System.Configuration;
using System.Data.SQLite;

using System.Diagnostics;

namespace UpdateMoviePath
{
    class Program
    {
        public class MovieObj
        {
            public int Id { get; set; }
            public string Title { get; set; }
            public int Year { get; set; }
            public int FileId { get; set; }
            public string FilePath { get; set; }

        }
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            string Films = @"E:\Media\TestFilms";

            if (Directory.Exists(Films))
            {
                string[] Files = Directory.GetFiles(Films, "*.mp4");
            

Open in new window

0
Hi,

Today I was asked this question:

We have
actualResult.AdditionalInfo[0].Content

Open in new window


Content itself have several properties such as Title, Type, Id, ActionPacks etc.
ActionPacks has 10 elements as
ActionPacks[0], ActionPacks[1], ActionPacks[2]....ActionPacks{9]

The question was
"how can we know the number of ActionPacks properties?

I answered like
actualResult.AdditionalInfo[0].Content.GetType().GetProperty("ActionPacks").Count

Open in new window

I know it's wrong.

Is there anyway I can find out the number of elements in ActionPacks?

Is this question even valid considering no additional information is given?
0
I think the title says it all. If I don't have a package variable named user::MyVar defined in the package, can it be created at run-time?

I want to be able to populate it with a value in a subsequent T-SQL Script Task.

Just for clarification, I only want to create it (as a string variable) if it does not exist. Its value will be set elsewhere.
0
I use datalayer In VS C# to create table but I drop the table first. I get an error if the table does not exist and give the drop command. . Dtaaccess.dtabase.execute(drop table tablename)
What is the datalayer method to check if table exist?
0
Hello All,

A project has come up to on demand scan a uploaded document for viruses in our site.
 
Some info on our site:
C#, MVC system with razor templates and xml configurations for custom UI.
AWS hosted web server and db.
Currently the users can attach documents to various items in our system.  Those documents are stored as varbinary in the db tables.


It was suggested to me to look into Clamav.net, but I'm wondering what the best solution (tool) other than Clamav, would be for scanning of a file that goes directly into a db table and not a folder structure on the server?  If it is necessary to save the file in a folder structure in order to do the scanning then we can change the system to do that.

Thank you for your time and suggestions.

Sincerely,
Ex
0
I have a horizontal form that I created in an ASP.NET MVC 5 project with Bootstrap 3 (I know this is an old version and may convert to version 4 later). The form-horizontal form is not fitting the full width of the screen even though I have a total of 12 columns in the class. I'm sure it's a simple fix, I just haven't been able to figure it out. I am not using any custom CSS on this page. Here is part of the code. It just has one of the divs. I can provide full code if needed.

<h2>Create Customer</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Customer</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })


        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

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