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

c# SqlDependency on a mirro db

$
0
0

Hi, I wanted to add SqlDependencyEx to my project.

when I tried 

ALTER DATABASE MYDBSET ENABLE_BROKER  WITH ROLLBACK IMMEDIATE


I got error 

Cannot create a new Service Broker in a mirrored database "MYDB".

I checked and the only way is to remove the mirror and return it.

is there any other way i can do to check changes in a table?



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

An error occurred while starting the application

$
0
0

FileNotFoundException: Could not load file or assembly 'System.Web.Abstractions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified. in .net core 2.2 startup class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace TestProject
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

  


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. 

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.

C# how to use different timer with different intervals, but start and stop them at the same time

$
0
0

Hello:

I have to use 2 timers and start and stop them at the same time, having one timer with interval of 1 second, another timer with interval of 2 seconds.  The following is my C# (.NET Core) code:

using System;
using System.Threading;

namespace TimerTask2
{
    class Program
    {
        static void Main()
        {
            AutoResetEvent autoEvent1 = new AutoResetEvent(false);
            StatusChecker1 statusChecker1 = new StatusChecker1(10);
            TimerCallback timerDelegate1 =
                new TimerCallback(statusChecker1.CheckStatus);
            TimeSpan delayTime1 = new TimeSpan(0, 0, 1);
            TimeSpan intervalTime1 = new TimeSpan(0, 0, 0, 0, 1000);
            Console.WriteLine("{0} Creating timer1.\n",
                DateTime.Now.ToString("h:mm:ss.fff"));
            Timer stateTimer1 = new Timer(
                timerDelegate1, autoEvent1, delayTime1, intervalTime1);
            autoEvent1.WaitOne(10000, false);
            stateTimer1.Dispose();
            Console.WriteLine("\nDestroying stateTimer1.");

            AutoResetEvent autoEvent2 = new AutoResetEvent(false);
            StatusChecker2 statusChecker2 = new StatusChecker2(5);
            TimerCallback timerDelegate2 =
                new TimerCallback(statusChecker2.CheckStatus);
            TimeSpan delayTime2 = new TimeSpan(0, 0, 2);
            TimeSpan intervalTime2 = new TimeSpan(0, 0, 0, 0, 2000);
            Console.WriteLine("{0} Creating timer2.\n",
                DateTime.Now.ToString("h:mm:ss.fff"));
            Timer stateTimer2 = new Timer(
                timerDelegate2, autoEvent2, delayTime2, intervalTime2);
            autoEvent2.WaitOne(10000, false);
            stateTimer2.Dispose();
            Console.WriteLine("\nDestroying stateTimer2.");
        }
    }

        class StatusChecker1
        {
            int invokeCount, maxCount;

            public StatusChecker1(int count)
            {
                invokeCount = 0;
                maxCount = count;
            }

            public void CheckStatus(Object stateInfo)
            {
                AutoResetEvent autoEvent1 = (AutoResetEvent)stateInfo;
                Console.WriteLine("{0} Checking status {1,2}.",
                    DateTime.Now.ToString("h:mm:ss.fff"),
                    (++invokeCount).ToString());
                if (invokeCount == maxCount)
                {
                    invokeCount = 0;
                    autoEvent1.Set();
                }
            }
        }

        class StatusChecker2
    {
        int invokeCount, maxCount;

        public StatusChecker2(int count)
        {
            invokeCount = 0;
            maxCount = count;
        }

        public void CheckStatus(Object stateInfo)
        {
            AutoResetEvent autoEvent2 = (AutoResetEvent)stateInfo;
            Console.WriteLine("{0} Checking status {2,2}.",
                DateTime.Now.ToString("h:mm:ss.fff"),
                (++invokeCount).ToString());
            if (invokeCount == maxCount)
            {
                invokeCount = 0;
                autoEvent2.Set();
            }
        }
    }
}

My code can get compiled, but when run, it has the following error:

System.FormatException
  HResult=0x80131537
  Message=Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
  Source=System.Private.CoreLib
  StackTrace:
   at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
   at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
   at System.IO.TextWriter.WriteLine(String format, Object arg0, Object arg1)
   at System.Console.WriteLine(String format, Object arg0, Object arg1)
   at TimerTask2.StatusChecker2.CheckStatus(Object stateInfo) in C:\Test\Helper\TimerTask2\TimerTask2\Program.cs:line 77
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)

Besides, it seems the first timer runs, then the second timer runs.

I want the both to run at the same time, and stop at the same time.

Is there any way to do this?

Thanks,

PS: My IDE: Visual Studio 2019 (Version 16.1.5) on Windows 10 (Version 1903).

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

Benefit of using RenderAction over render partial.

$
0
0
Benefit of using RenderAction over render partial.

C# to create an access database....with password protection.

$
0
0
I have successfuly created access databases but is there something I can place in the code to have the database created have a password added to it?

try
            {
                Catalog cat = new Catalog();
                string strCreateDB = "";
                strCreateDB += "Provider=Microsoft.Jet.OLEDB.4.0;";
                strCreateDB += "Data Source=" + pstrDB + ";";
                strCreateDB += "Jet OLEDB:Engine Type=5";
                cat.Create(strCreateDB);
            }//closes try.
            catch (Exception)
            {
            }//closes catch.

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?

How to set MSBuild to compile multiple times?

$
0
0
In our current product, we have multiple solution files of visual studio and multiple projects in them.

In those, few of the solutions .sln files may fail some times and if we retry , they will be successful.

So, we are using devenv.com till date and retrying for 5 times, if it fails on 5th time, we are failing the build job.

But how to integrate this in MSBuild script. Like, we can use msbuild to build the project but how to set the retry attempts to till 5 and do the build process.

Is there any .msbuild script you can suggest for this.

'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

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 


The underlying connection was closed for concurrent Async request

$
0
0

I have added web reference to my C# 4.0 project as OOPostAcknowledge and while i run code in my PC assume my table have 1000 rows so there are 1000 async request made to webservice and getting completed success response for all.

the same C# Windows application when running from windows server 2012 R2 while making 1000 async request only first approx (150 - 200) requests are posted successfully and latest getting error as

"System.Net.WebException : The underlying connection was closed: An unexpected error occurred on a receive. Inner ExMessage = Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. @ : at System.Web.Services.Protocols.WebClientAsyncResult.WaitForResponse() at System.Web.Services.Protocols.WebClientProtocol.EndSend(IAsyncResult asyncResult, Object& internalAsyncState, Stream& responseStream) at System.Web.Services.Protocols.SoapHttpClientProtocol.InvokeAsyncCallback(IAsyncResult result)"


Kindly advise for the same, code below.

private void PostItemMasterAcknowledgment()
{
	try
	{
		var ActTable = DBO.GetSqlcmdDataTable($"SELECT * FROM  [dbo].[TABLE_NAME]");


		var req = new OOPostAcknowledge.WebServicesProcess();
		req.Timeout = 1000 * 60 * 10; // ms * sec * min -- 10 mins
		req.Credentials = myCred;
		bool success = false;
		req.UpdateProcessedItemCompleted += Req_UpdateProcessedItemCompleted;
		foreach (DataRow row in ActTable.Rows)
		{
			try
			{
				req.UpdateProcessedItemAsync(row["No"].ToString(), AckProcessed_From_API_FLAG, success, "", row["Id"].ToString());
			}
			catch (Exception ex)
			{
				Library.WriteError(ex);
			}
		}
	}
	catch (Exception ex)
	{
		Library.WriteError(ex);
	}
	finally
	{
		GC.Collect(); this.Cursor = Cursors.Default;
	}
}


private void Req_UpdateProcessedItemCompleted(object sender, OOPostAcknowledge.UpdateProcessedItemCompletedEventArgs e)
{
	try
	{
		if (e.Error == null && e.success && !string.IsNullOrEmpty(e.ackItemNo))
		{
			DBO.SqlExecuteNonQuery($"UPDATE [dbo].[TABLE_NAME] SET [STATUS] = '{AckPostStatus}', [MODIFIEDDATE] = GETDATE(), [REMARKS]= ISNULL([REMARKS],'') + ':Acknowledged {e.ackItemNo}' WHERE [No] = '{e.ackItemNo}' AND [Id] = {e.UserState.ToString()}");
		}
		else
		{
			Library.WriteError(e.Error);
		}
	}
	catch (Exception ex)
	{
		Library.WriteError(ex);
	}
	finally
	{


	}
}

Hi, have tried the same code in Windows 10 PC and getting the error after 200 async requests out of 1000 request, but the same is working fine in Windows 7 and get a response for all 1000 async requests.

Is there need to do any setting need to be changed for Windows 10/Windows server 2012 to allow more async request?

or any config needs to be added in Application app.config?

Please advise.


Where is LdapFilterEncode?

$
0
0

I am working on a project using the .NET 4.5 framework. The company requires the application code to pass through a code analyzer, before it can go to production. 

I have an LDAP class where I perform simple searches, but I need to encode the Filter of my queries to make this web application safer. I have found a lot of information on the internet talking about the System.Web.Security.AntiXss namespace, and specifically this website says to use Encoder.LdapFilterEncode(string).

All I can find in that namespace, is what corresponds with the Microsoft documentation, which doesn't have an LdapFilterEncode method. Microsoft even mentions this namespace to prevent LDAP injection attacks on this website, but doesn't identify which method to specifically use for it.

If the LdapFilterEncode is no longer being used, which method should I use in the AntiXss namespace? AntiXssEncoder.HtmlEncode(string, bool)?

Here is a snippet of code to show you what I am working with, the issue is with the _DirectorySearcher.Filter line...

using (DirectorySearcher _DirectorySearcher = new DirectorySearcher(_DirectoryEntry))
{
    _DirectorySearcher.SearchScope = SearchScope.Subtree;
    _DirectorySearcher.Filter = string.Format("(sAMAccountName={0})", _User[1]);
    _DirectorySearcher.PropertiesToLoad.Add("mail");
    _DirectorySearcher.PropertiesToLoad.Add("displayName");
}

Any help would be greatly appreciated. Thank you in advance.


how to get values in c# from sql cte virtual columns?

$
0
0

this is my query from which i am calculating percentage as a virtual column that doesnt exist physically in table

i want to get calculated percentage in any variable to be stored for eg we can access column value by simple writing

                                string percentage = (read["Percentage"].ToString());

above statement will provide desired results only if Percentage column exist in table.

  SqlCommand cmd = new SqlCommand(";with cte as (select distinct s.S_ID, s.Name, (select  cast(count(distinct A_Date) as float)from Attendance where a.C_ID = C_ID) as Total_Classes, (select count(Pre) from Attendance where a.C_ID = C_ID and a.S_ID = S_ID and Pre = 'True') as Attended from Course c left outer join StudentCourse sc on c.C_ID = sc.C_ID left outer join Student s on s.S_ID = sc.S_ID left outer  join Attendance a on a.S_ID = s.S_ID and a.C_ID = c.C_ID where c.C_ID = '"+id+"' and s.S_ID ='"+S_ID+"') select S_ID, Name, Total_Classes, Attended, cast(Attended * 100 / nullif(Total_Classes, 0) as decimal(10, 2))  Percentage from cte ", con3);
                        //   cmd.Parameters.A
                        using (SqlDataReader read2 = cmd.ExecuteReader())
                        {
                            while(read2.Read())
                            {
                                string percentage = (read["Percentage from cte"].ToString());
                            }

                        }

in abve query how i can get value of the calculated percentage and then store it in any variable?

In C# - How to create a string literal with a back slash \ as the value

$
0
0
Using C# in 2019.  I would like to create a string literal with a back slash \ as the value.  Need an example.

Edcal

Why is DataGridViewCellStyle.Format being ignored?

$
0
0

I have a DataGridView with three columns. Its DataSource is a DataTable with three Int32 columns. I explicitly set the middle column of the view to use format string "000" as I need it to always show three digits using leading zeroes as a filler when needed. But it never shows the leading zero.

Below is the code. I have included the various other bits that are going on just in case any of this would impact the formatting (although I don't see how it could, but then by my understanding what I have should work and it doesn't, so clearly I don't know what I'm doing).

        // Data definitions at the start of the class

        private DataTable windTable_m = null;

        // Later on - initialisation code

        windTable_m = new DataTable();
        DataColumn windAltCol = new DataColumn("Alt (ft)");
        windTable_m.Columns.Add(windAltCol);
        DataColumn windDirCol = new DataColumn("Dir (T)");
        windTable_m.Columns.Add(windDirCol);
        DataColumn windSpeedCol = new DataColumn("Speed (kt)");
        windTable_m.Columns.Add(windSpeedCol);
        windGrid.DataSource = windTable_m;

        windGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
        windGrid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
        DataGridViewCellStyle hdrStyle = new DataGridViewCellStyle();
        Padding padding = new Padding(0, 1, 0, 1);
        hdrStyle.Padding = padding;
        windGrid.ColumnHeadersDefaultCellStyle = hdrStyle;
        Padding margin = new Padding(0);
        windGrid.Margin = margin;
        windGrid.Columns[0].FillWeight = 1;
        windGrid.Columns[1].FillWeight = 1;
        windGrid.Columns[1].DefaultCellStyle.Format = "000";
        windGrid.Columns[2].FillWeight = 1;

        // Even later - actual data from an input form being transferred via Dictionary "windAlts_m"

        // to windTable_m, which is the DataSource for the grid view.

        windTable_m.Rows.Clear();
        foreach (Int32 alt in windAlts_m.Keys)
        {
            windTable_m.Rows.Add(alt, windAlts_m[alt].DirFrom, windAlts_m[alt].Speed);
        }


Incidentally, I have checked the format string "000" using Microsoft's downloadable format checker utility and it works fine there.

The type or namespace name 'Resources' does not exist in the namespace 'xxxxx.xxxx.Properties' (are you missing an assembly reference?)

$
0
0
I am using VS 2008 on an existing project that was converted from VS2005 long time ago.  The project uses some *.Gif, *.bmp, etc.. files that was imported long before the conversion.

today, I just added a picture box to an existing control by droping the picture box on the control.  And then I assigned a graphic file to the immage property.  Every thing looks cool, and the picture is shown on the control.

After then, I got ton of build errors (same error) on all source file that using any pictures.  The error is below:

"The type or namespace name 'Resources' does not exist in the namespace 'xxx.xx.Properties' (are you missing an assembly reference?) "

Clicking on one of the error leads me to a line of code like this (code like this are auto generated by VS and store in the xxx.designer.cs files):

this

.picSample1.Image = global::xxx.xx.Properties.Resources.Sample_Revenue;
What could have go wrong here?  How do I make my project compile again?

Thanks

David N.

C# Programming Loops

$
0
0

Write an application that can be used to determine if three line segments can form a triangle. Prompt the user for the length of three line segments as integers. If non-numeric characters are entered, re-prompt the user for new values. If the three lines could form a triangle, print the integers and a message indicating that they form a triangle. Use a state-controlled loop to allow users to enter as many different combinations as they want.

A property that applies to triangles:
 *   The sum of the lengths of any two sides of a triangle is greater than the length of the third side.
 *   If you take the three sides of a triangle and add them in pairs, 
 *   the sum should be greater than the third side. i.e. 3-4-5  or  5-8-12
 *
 *  If that is not true, then it is not possible to construct a triangle with the given side lengths.



Viewing all 31927 articles
Browse latest View live


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