Quantcast
Channel: Visual C# forum
Viewing all 31927 articles
Browse latest View live

Make a Select Statement to get the last ID and pass to a variable

$
0
0

Hi folks  good afternoon,

First I would like to apologize myself, because I started this system in portuguese, the next one I will use only fields in english.

I'm having a trouble to get the last ID of a table and pass it to a variable, to show in a Textbox.

Could you please help-me with that?

LastID is declared at the top of the form. 

Int32 LastID = 0;

Table: Base_Titulos_Pagos

Table's ID : Cod_Base_Titulos_Pagos

Here follows the code. I'm using SELECT MAX, but is returning"0". There are four (4) registers in this table.

If you guys could help-me with a Lambda expression also.

Thanks a lot for your help.

   private void btn_InserirPagto_Click(object sender, EventArgs e)
        {

            Data_Agora = DateTime.Now;
        //  data_LoginTextBox.Text = Data_Agora.ToShortDateString();
        //  login_NameTextBox.Text = Login.DadosGerais.Loginusuario;
            btn_salvar.Enabled = true;
            btn_salvar.BackColor = Color.DarkOrange;

            if (data_PagamentoDateTimePicker1.Text != " " && valor_PagoTextBox1.Text != " " && banco_DebitadoTextBox1.Text != " " && numero_ChequeTextBox1.Text != " ")
            {
                try
                {
                    cmd = new SqlCommand("INSERT INTO Base_Titulos_Pagos(Data_Pagamento, Total_Pago, Banco_Debitado, Numero_Cheque, Historico, Data_Login, Login_Name)"+ "VALUES(@Data_Pagamento, @Total_Pago, @Banco_Debitado, @Numero_Cheque, @Historico, @Data_Login, @Login_Name)", conn);
                    conn.Open();
                    DateTime DataPagamento = Convert.ToDateTime(data_PagamentoDateTimePicker1.Value.ToShortDateString());
                    cmd.Parameters.AddWithValue("@Data_Pagamento", DataPagamento);
                    decimal TotalPago = Convert.ToDecimal(valor_PagoTextBox1.Text);
                    cmd.Parameters.AddWithValue("@Total_Pago", TotalPago);
                    Int32 BancoDebitado = Convert.ToInt32(banco_DebitadoTextBox1.Text);
                    cmd.Parameters.AddWithValue("@Banco_Debitado", BancoDebitado);
                    String NumeroCheque = Convert.ToString(numero_ChequeTextBox1.Text);
                    cmd.Parameters.AddWithValue("@Numero_Cheque", NumeroCheque);
                    String Historico = Convert.ToString(historicoTextBox1.Text);
                    cmd.Parameters.AddWithValue("@Historico", Historico);
                    DateTime Data_Agora = DateTime.Now;
                    cmd.Parameters.AddWithValue("@Data_Login", Data_Agora);
                    String LoginName = Login.DadosGerais.Loginusuario;
                    cmd.Parameters.AddWithValue("@Login_Name", LoginName);
                    Int32 result = cmd.ExecuteNonQuery();
                    MessageBox.Show("Inicie a Seleção de Títulos para Pagamentos! " + result.ToString() + "Cheque Inserido!"); cmd = new SqlCommand("SET @LastID = SELECT MAX (Cod_Base_Titulos_Pagos) FROM Base_Titulos_Pagos"); cod_Base_Titulos_PagosTextBox.Text = Convert.ToString(LastID);
                    cod_Base_Titulos_PagosTextBox.Refresh();
                    numero_Parcelas_a_PagarDataGridView.Enabled = true;
                }
                catch (Exception Ex)
                {
                    MessageBox.Show("Erro! " + Ex.Message);
                }
                finally
                {
                    conn.Close();
                    btn_fechar.Enabled = true;
                }
            }
            else
            {
                MessageBox.Show("Informe todos os Dados necessários para incluir o Pagamento do Título!");
            }

        }


C# project and VB Project How can I call a form

$
0
0
What I mean is how can I for example make a form from the C# project visible, while I am using the vb project.

WPF and MVVM ?

$
0
0
I'm starting with WPF and MVVM from Windows Forms Apps. I have to admit that has been confusing. I have big doubts about all this platform and how to face it. But my question is: All the WPF apps are managed by paging? There's not multiple windows management?

Histogram (Data Distribution) using Chart control

$
0
0

Hi , I have no much experience using chart control.

I have test data that I am using for a CPK estimation. For the CPK, 50 data measurements, I have the average, Standard Deviation, LSL and USL (Limits of my Data)

I have made several tries with the SereisChartType.Column and Bar but I cant manage to set it up as data distribution or histogram chart

My objective is:

I want to use the chart control to show my data distribution i.e. histogram/bar chart   which the height of the bars is proportional to the frequencies(normal distribution).  I want to show my data distribution in a range maybe showing USL,LSL and Average with some vertical lines.

1.I am not sure which type of series type I should use:

chart.Series[SeriesHistogram].ChartType =System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column; or Bar

2. How to set up the chart with my data so I can get a bar plot with:

-In the x axis : the range of the values  of my data ( the measurements)

-In the y axis( the height of the bars): the height of the bars will represent the frequency of my data ( higher with the values are repeated more).

3.For a line plot i used:

For (inti = 0; i < NumberOfDataValues; i++)

            {

                chart.Series[SeriesName].Points.AddXY(i,DataArray[i]);

            }

but how should I set the data to plot the bars in data distribution way??

thanks and regards

Trying to convert an IEnumerable to a IList but cannot find proper documentation.

$
0
0

https://docs.microsoft.com/en-us/azure/cognitive-services/face/face-api-how-to-topics/howtoidentifyfacesinimage#step-4-identify-a-face-against-a-defined-persongroup

I am following the above tutorial and on step 4 in the 4th line,

var results = await faceClient.Face.IdentifyAsync(faceIds, personGroupId);,

I am getting an error in converting facesId Ienumerable<Guid?> to an IList<Guid>. what is the best way to approach this?

This tutorial is most likely using an outdated version of .NET, and I am not sure how to convert to an IList<Guid> since its an abstract class.

Any suggestions will be appreciated.

Access to filepath is denied when saving variable data to text file

$
0
0

Hi all,

I'm trying to save variable data to a text file, but whenever I try to write the code, I get the error message "Access to the path [file location] is denied." How do I solve this problem?

Here is my code used to save:

string goalsFilePath = @"E:\Programs\NutrientTracker\NutritionGoals.txt";
List<string> nutritionGoals = new List<string>();
                        nutritionGoals.Add(calorieMin.ToString());
                        nutritionGoals.Add(calorieMax.ToString());
                        nutritionGoals.Add(gramsFatMin.ToString());
                        nutritionGoals.Add(gramsFatMax.ToString());
                        nutritionGoals.Add(gramsCarbsMin.ToString());
                        nutritionGoals.Add(gramsCarbsMax.ToString());
                        nutritionGoals.Add(gramsProteinMin.ToString());
                        nutritionGoals.Add(gramsProteinMax.ToString());

foreach (string line in nutritionGoals)
{
    sw.WriteLine(nutritionGoals);
}

Any help would be appreciated.   I tried to use the File.WriteAllText method as well but with the same result.



Validate visual studio 10

$
0
0

How can I validate my visual studio 10 license or program that expires in 11 days???

Authority URI should have atleast one segment in the path (i.e.https:////)"...; When Using UCWA2.0 In C#

$
0
0
We have created an application to send and receive message by interacting with online users in the Skype for business. For achieving this we have followed the below steps, but we are 
facing issue


1. Installed Skype for Business 2016 application

2. Created Azure AD app with "UCWA 2.0" in the Azure. this acts as a user to interact SFB Online users.

3. And gave full delegate access to communicate with SFB online.

4. Generated and error in authority URI "'authority' URI should have atleast one segment in the path (i.e. https://<host>/<path>/)"...

5. Later we downloaded the SFB 2015 system app and tried with UCWA 2.0.

6. But facing the same issue with communicating with SFB. 

Benefit of using RenderAction over render partial.

$
0
0
Benefit of using RenderAction over render partial.

How to generate Click Once Deployment file .exe without depending on .application file?

$
0
0
I have created Click Once Deployment file. It works great.

However, .exe file was created along with .application file and Application Files - Folder which has necessary files.

.exe file works only if it is available along with .application file in the folder. If i share the .exe file without .application file to another user, it throws an error as follows ..

How to make the .exe file independent without depending on .application file?

+ Downloading file:///C:/Users/MyAccName/Downloads/MyProject.application did not succeed.+ Could not find file 'C:\Users\MyAccName\Downloads\MyProject.application'

Streaming Broadcast live camera

$
0
0

Hi everyone,

I premise that I am very noob on this argument;
I should develop an application that receives in input a stream (live) of data from any video camera and shows many connected users on the browser without bandwidth problems.My idea was to have a thread that reads the data stream continuously and saves it (I don't know how); then develop a webservice rest (with which to hook the src of my video tags) that read from the saved data.
is this a wrong way?

thanks

Visual Studio Community 2019 - Tooltip and Menustrip not saving objects

$
0
0

Having posted this as a problem or rather reported the fault a few days ago to which I have received no reply, I will post this here to see if anyone has a solution:

VS 2019 Community is not saving the buttons in a toolstrip and the menu text in a menustrip control. When I restart the solution all of them have disappeared - the toolstrip and menustrip are still there but now devoid of any objects or text I have entered.

Does anyone have an idea how this can be solved?

'String was not recognized as a valid DateTime.'

$
0
0

I am trying to get datetime including time part from the string variable

string dateString = dt.ToString("yyyy-MM-dd HH:mm:ss.FFF"); 
datetime dt = DateTime.ParseExact(dateString, "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);

the value of datestring is "2019-06-19 02:15:00"

when I parse the datestring  into dt the folllowing error is coming 

'String was not recognized as a valid DateTime.'

Please can you help to fix the error

Regards

pol


polachan

Threading Task Canceled Midway Exception

$
0
0

Hi, I have developed a C# ASP.NET Web Application. In that application there is an .aspx page, in which in the Page_Load routine, I select data out of SQL Server 2012 database, check for certain alarm/warning signal, and if the signal is detected in the data, code is used to send out outlook email to email addresses, which are looked up the database again. Also updates are made to the SQL Server tables.

I want to launch this .aspx web page from a c# console program using HttpClient(). The code is attached, shown below. When I execute this console program, after some time, I get an Unhandled exception of type 'System.Threading.Tasks.TaskCanceledException' occured in mscorlib.dll.

But even after the exception is thrown, I can see that the task seems to keep on running in the background for several more minutes and I find that it goes to completion.

The exception details and code are shown below. Can you please help me fix this ? Thanks

Unhandled exception; System.Threading.Tasks.TaskCanceledException: A task was canceled.
at System.Runtime.CompilerService.TaskAwaiter.ThrowForNonSuccess<Task task>
at Syste.Runtime.CompilerService.TaskAwaiter.HandleNonSuccessAndDebuggerNotification<Task task>
at ConsoleApplication2.Program.<DumDum>d__3.MoveNext,> in c....

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;

namespace ConsoleApplication2
{
	class Program
	{
        static System.IO.Stream Response;
		static void Main(string[] args)
		{
			DumDum().GetAwaiter().GetResult();
		}

        static async Task DumDum()
        {
            // Call asynchronous network methods in a try/catch block to handle exceptions
            try
            {
                HttpClient client = new HttpClient();
                HttpResponseMessage response = await client.GetAsync("http://webserver_name/mywebpage.aspx");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                // Above three lines can be replaced with new helper method below
                // string responseBody = await client.GetStringAsync(uri);

                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
            }
        }

	}
}


diana4

What is the default search behavior of an asp.net MVC SelectListItem control on keypress?

$
0
0

I have a dropdownlist control created using the asp.net MVC SelectListItem base control having the following list items (in the following order):

AMERICA
AFGHANISTAN
ALGERIA

With the focus on the control, when I press the key 'A', the control selects AFGHANISTAN. I am assuming that it is selected because it comes first in alphabetical order. Is this assumption true? If yes, is there any way to change this behavior and select the item on the basis of the display order and not alphabetical order i.e. AMERICA?

Using the following code inside my wrapper control class:

selectList =newSelectList(tableData,
                valueExpression,
                descExpression,
                selectedValue);

Expectation is that the control should select the first matching item on the basis of the display order and not alphabetical order.

Any documentation around the filtering functionality of SelectListItem would be helpful.


New deployed program giving error A network-related or instance-specific error occurred while establishing a connection to SQL Server

$
0
0

I am having a nightmarish start on my first program.when i finished my program i used innosetup and put all the required files including the database for me me to make a setup file.When ever i install the program on the computer it gives me a network related error. Here is the connection string

 if (string.IsNullOrEmpty(txtbxusername.Text))
            {
                MessageBox.Show("Please enter username", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtbxusername.Focus();
                return;
            }
            try
            {
                using (LoginEntities data = new LoginEntities())
                {

                    var query = from o in data.Users
                                where o.username == txtbxusername.Text && o.password == txtbxPassword.Text
                                select o;
                    if (query.SingleOrDefault() != null)
                    {
                        MessageBox.Show("You have been authenticated sucessfully.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //add process here


                       MainPage main = new MainPage();
                       main.Show();
                       

                        this.Hide();
                    }
                    else
                    {
                        MessageBox.Show("You have input the wrong credentials", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }

<connectionStrings>
    <add name="Taona_File_Reference_Locator.Properties.Settings.VIMBISOConnectionString" connectionString="Data Source=.\vimbiso;Initial Catalog=VIMBISO;Integrated Security=True" providerName="System.Data.SqlClient" />

Is there another way of installing the software without me having to install sql server software on a client machine.I just want to install my program on a PC like the way we install ms office

Your assistance is greatly appreciated

Winforms Tab control and other components inside it are getting misplaced and truncated in Japanese OS

$
0
0

We have one application which is using winforms for some controls. It's having one base form and tab controls inside it. In Japanese OS, extra margin is being added and tab control component is getting truncated due to it.

And other controls like buttons which are at the bottom of the form are also being misplaced. 

Is there any way we can make it work properly for Japanese OS using any properties. everything works with normal English OS. 

Please let me know how to fix this part ?

how can i load and split a file seprated by // to key value pairs dictionary

$
0
0

hello all i am trying my best to load and split this file here that is seprated by // to key value pairs 

so key // value 

this is the file in question.

File i want to parse

the file is all one line.

but i need to miss out WEAPONFILE at the start as thats just explaining what the file is form there i need to do parse methord but i not sure how to populate the dictionary when you load a file in or how to split them at the // i have tryied string.split 

but it dont seem to work the way i would want it to 

if anyone could help would be so much appeicated 


MemoryMappedFile, persistance and @Could not find a part of the path@ error

$
0
0

I created 2 class 1 that send to the file and one that reads, I am using the persistent option.

1. on the MemoryMappedFile.OpenExisting I get error that "Could not find a part of the path"

not clear why it happends?

2. when I read the data out it's actually erased? or if I run the process again the items will be read again?

my target is pass data between 2 process.

this is the class that send data to the file:

private const int MMF_MAX_SIZE = 1024;  // allocated memory for this memory mapped file (bytes)
        private const int MMF_VIEW_SIZE = 1024*10; // how many bytes of the allocated memory can this process access
        private readonly string filePath;
        private readonly Thread thread;

        public Sender(string filePath)
        {
            this.filePath = filePath;
            thread=new Thread(Send);
            thread.Start();
        }

        public void Send()
        {
            ManageQueue manageQueue = ManageQueue.Instance;
            MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(filePath, FileMode.OpenOrCreate, null,MMF_VIEW_SIZE ,MemoryMappedFileAccess.ReadWrite);
            // creates a stream for this process, which allows it to write data from offset 0 to 1024 (whole memory)
            MemoryMappedViewStream mmvStream = mmf.CreateViewStream(0, MMF_VIEW_SIZE);
            SmsMessage smsMessage = null;
            while (true)
            {
                while (manageQueue.incomingMessages.IsEmpty) ;
                if (manageQueue.incomingMessages.TryDequeue(out smsMessage))
                {
                    // serialize the variable 'message1' and write it to the memory mapped file
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(mmvStream, smsMessage);
                    mmvStream.Seek(0, SeekOrigin.Begin); // sets the current position back to the beginning of the stream
                }
            }//while(true)
        }//Send() // the memory mapped file lives as long as this process is running
    }

this is the reader class :

private const int MMF_MAX_SIZE = 1024;  // allocated memory for this memory mapped file (bytes)
        private const int MMF_VIEW_SIZE = 1024; // how many bytes of the allocated memory can this process access
        private readonly string filePath;
        private readonly Thread thread;

        public Listener(string filePath)
        {
            this.filePath = filePath;
            thread = new Thread(Receiver);
            thread.Start();
        }
        public void Receiver()
        {
            
            // creates the memory mapped file
            MemoryMappedFile mmf = MemoryMappedFile.OpenExisting(filePath,MemoryMappedFileRights.Read);
            MemoryMappedViewStream mmvStream = mmf.CreateViewStream(0, MMF_VIEW_SIZE); // stream used to read data
            BinaryFormatter formatter = new BinaryFormatter();
            byte[] buffer = new byte[MMF_VIEW_SIZE];
            SmsMessage smsMessage;
            while (true)
            {
                // reads every second what's in the shared memory
                while (mmvStream.CanRead)
                {
                    // stores everything into this buffer
                    mmvStream.Read(buffer, 0, MMF_VIEW_SIZE);

                    // deserializes the buffer & prints the message
                    smsMessage = (SmsMessage)formatter.Deserialize(new MemoryStream(buffer));
                    Console.WriteLine(smsMessage.Text + "\n" + smsMessage.CreateDateTime + "\n");
                    //System.Threading.Thread.Sleep(1000);
                }
                Thread.Sleep(1000);
            }//while (true)
        }

thanks

Connection to Dynamics 365 in C#

$
0
0

Hi,

I am using C# to connect to Dynamics 365. I used the same code and it works for one instance and not for another one. I get the following error : "ID3007: The element 'pp' with namespace 'http://schemas.microsoft.com/Passport/SoapServices/SOAPFault' is unrecognized."

The code is the following

namespace ConnectToCRM {
	class Program {
		static void Main(string[] args) {
				try
				{
					IOrganizationService organizationService = null;

					ClientCredentials clientCredentials = new ClientCredentials();
					clientCredentials.UserName.UserName = "y@MyDomain.onmicrosoft.com";
					clientCredentials.UserName.Password ="MyPass";

					// For Dynamics 365 Customer Engagement V9.X, set Security Protocol as TLS12
					ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
					// Get the URL from CRM, Navigate to Settings -> Customizations -> Developer Resources
					// Copy and Paste Organization Service Endpoint Address URL 
					organizationService = (IOrganizationService)new OrganizationServiceProxy(new Uri("https://MyDomain.api.crm12.dynamics.com/XRMServices/2011/Organization.svc"),
					null, clientCredentials, null);

					if (organizationService != null)
					{
						Guid userid = ((WhoAmIResponse)organizationService.Execute(new WhoAmIRequest())).UserId;

						if (userid != Guid.Empty)
						{
							Console.WriteLine("DOTNET 2015 : Connection Established Successfully...");
						}

					}
					else
					{
					Console.WriteLine("DOTNET 2015 : Failed to Established Connection!!!");
					}
				}
				catch (Exception ex)
				{
				Console.WriteLine("DOTNET 2015 : Exception caught - " + ex.Message);

				}
			Console.ReadKey();

			

		}
	}
}

I have the "Microsoft.CrmSdk.CoreAssemblies" package installed V 9.0.2.12 and targeting the .NET Framework 4.7.2.

the first instance in CRM that works fine with my code is a free trial with Server version: 9.1.0000.6227

the second instance that is giving me the error is another free trial with Server version: 9.1.0000.6421


YaraZ

Viewing all 31927 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>