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

Browser_broker

$
0
0

Browser_broker is troubling me. My files are still open in it after downloading. Kindly assist me with this on priority basis.


My class instance is null when initiated

$
0
0

Hello

So I am trying to play around with a tic tac toe validation principle, nvm - what I am trying to say, I am not interested in any 'game' mechanics.
(If below does not tell you enough, then I have uploaded the project here: https://ufile.io/f1wps )
So I have 3 classes that holds all the game logic;
GameBoard.cs:

namespace tic_tac_toe
{
  public enum Player
  {
    X = 1,
    O = 2,
    Open = 0,
  }

  /// <summary>
  /// Abstract class for creating new game boards, contains all of the logic needed for the AI to play the game.
  /// </summary>
  public abstract class GameBoard
  {
    /// <summary>
    /// Array that contains all of the spaces on the board.
    /// </summary>
    public Player[,] squares;

    /// <summary>
    /// Gets or sets a space on the board.
    /// </summary>
    public abstract Player this[int x, int y] { get; set; }

    /// <summary>
    /// Determines if all spaces on the board are full.
    /// </summary>
    public abstract bool IsFull { get; }
etc...

TicTacToeBoard.cs:

namespace tic_tac_toe
{
  /// <summary>
  /// Contains all of the functions and logic needed for the game of TicTacToe
  /// </summary>
  class TicTacToeBoard : GameBoard
  {
    public TicTacToeBoard()
    {
      squares = new Player[3, 3] { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } };
    }

    public override int Size { get { return 9; } }

    public override Player this[int x, int y]
    {
      get
      {
        return squares[x, y];
      }

      set
      {
        squares[x, y] = value;
      }
    }

    public override bool IsFull
    {
      get
      {
        foreach (Player i in squares)
          if (i == Player.Open) { return false; }
        return true;
      }
    }

etc...

AI.cs:

namespace tic_tac_toe
{
  class AI
  {
    /// <summary>
    /// Implementation of the minimax algorithm.  Determines the best move for the current 
    /// board by playing every move combination until the end of the game.
    /// </summary>
    public static Space GetBestMove(GameBoard gb, Player p)
    {
      Space? bestSpace = null;
      List<Space> openSpaces = gb.OpenSquares;
      GameBoard newBoard;

      for (int i = 0; i < openSpaces.Count; i++)
      {
        newBoard = gb.Clone();
        Space newSpace = openSpaces[i];

        newBoard[newSpace.X, newSpace.Y] = p;

        if (newBoard.Winner == Player.Open && newBoard.OpenSquares.Count > 0)
        {
          Space tempMove = GetBestMove(newBoard, ((Player)(-(int)p)));  //a little hacky, inverts the current player
          newSpace.Rank = tempMove.Rank;
        }

etc:

My main program to test the above classes:

namespace tic_tac_toe
{
    public class Program
  {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>

        static void Main(string[] args)
        {
            GameBoard gb;

            //Space s = new Space(0, 0);
            gb[1, 1] = Player.O;
            //gb[s.X, s.Y] = Player.O;
            Console.WriteLine(gb.OpenSquares.ToString());

In my main the Gameboard instance is unassigned, what is it that I am missing since I am unable to get the class to initiate properly?
Error at gb[1,1] .... first time accesses the class properties it throws:

Severity	Code	Description	Project	File	Line	Suppression State
Error	CS0165	Use of unassigned local variable 'gb'

I hope I provided enough information above, as it's probably something to do with the class access modifiers?

thank you in advance, I hate being stuck :)


Reactive link, Subject Multiple Readers

$
0
0

Hi All,

I using Subject class from reactive link library as follows. Is it possible to have multiple readers for the subscribe method. ?

I could not find any overload which takes number of readers. 

  Subject<BinaryMessage> eventMessage = null;

                eventMessage
                .Buffer(TimeSpan.FromMilliseconds(WaitTimeInMilliseconds), bufferWaitNumberOfEvents)
                .Subscribe(ProcessEvents, e =>
                {
                    if (exceptionCallback != null)
                        exceptionCallback(e);
                    else
                        Console.WriteLine(e);
                }
                                            , _cancelSource.Token);

Thanks



Not able to launh application on second time without arguments if arguments passed is wrong

$
0
0

I have created a WinFrom application WindowsFormsApp2 as follows

static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string [] args)
        {
            for (int i = 0; i < args.Length; i++)
            {
                if (args[i] == "Launch")
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1());
                }
                else if(args[i] == "Exception")
                {
                    throw new Exception("Launch failed");
                }
                else
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form2());
                }
            }
        }
    }

To launch this application from WindowsFormsApp3 app I have written the code as below

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                using (Process process = new Process())
                {
                    process.StartInfo.FileName = @"C:\Users\MYNAME\source\repos\WindowsFormsApp3\WindowsFormsApp3\bin\Debug\WindowsFormsApp3.exe";
                    process.StartInfo.Arguments = @"Exception";
                    if (process.Start())
                    {
                    }
                    else
                    {
                        process.StartInfo.Arguments = string.Empty;
                        process.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                using (Process process = new Process())
                {
                    process.StartInfo.FileName = @"C:\Users\MYNAME\source\repos\WindowsFormsApp3\WindowsFormsApp3\bin\Debug\WindowsFormsApp3.exe";
                    process.StartInfo.Arguments = @"Exception";
                    if (process.Start())
                    {
             
                    }
                    else
                    {
                        process.StartInfo.Arguments = string.Empty;
                        process.Start();
                    }
                }
            
            }
        }

What I want is if the argument passes throws exception I need to relaunch the application without arguments.

But here always process.Start() returns true;

Thanks in advance!!..


How to validate a multi line Address text box using regex

$
0
0

Hi experts,

can u please help me to get regex to validate a multi line address text box 

to allow case incentive alphabets, numbers and only # / , - &

i tried @"^(\w*\s*[\#\-\,\/\(\)\&]*)+"

but it test address

Plot No 6, @Sector:10, Iie Sidcul, Pantnagar, Uttaranchal-263153 

it passes the criteria it , @ before sector  and : before 10 should not be allowe

        Regex regex = new Regex(@"^(\w*\s*[\#\-\,\/\(\)\&]*)+", RegexOptions.Multiline);
        Match match = regex.Match(txtaddress.Text);
            if (match.Success)
            {
                e.Cancel = false;
                errorProvider1.Clear();
            }
            else
            {
                e.Cancel = true;
                errorProvider1.SetError(txtaddress, "Special Characters except (#/,-&) not allowed");
            }
will to be possible to show offending character and their position in a message-box


Function wait until thread(websocket) to finish before returning result

$
0
0
Hello, I am trying to run a Websocket client example:
the lib used is: https://github.com/sta/websocket-sharp

I have made below function to communicate with an Websocket server, the problem is that it returns the result before it is set by the OnMessage function from websocket(ws):
public static Tuple<int, string> wingm(string userName, string extrastr, string)
        {
            var ws = new WebSocket("wss://just.mywssgame.uk:7002/");
            using (ws)
            {
                //ws.Connect();

                String returnResultJSON = "";
                ws.OnMessage += (sender, e) =>
                {
                    dynamic messageJSONresponse = JsonConvert.DeserializeObject(e.Data);
                    if (Convert.ToString(messageJSONresponse.type) == "playerone")
                        {
			    returnResultJSON = Convert.ToString(messageJSONresponse);
                            Console.WriteLine(returnResultJSON);
                        }

                    }
                };
                //we begin here
                ws.Connect();
                ws.Send(userName);
                Console.ReadKey(true);
            }
       return Tuple.Create("0", returnResultJSON);
 }

I then call above function in an console application:
Tuple<int, string> tempResult = wingm("somnam", "");
Console.WriteLine(tempResult.Item1.ToString());
Console.WriteLine(tempResult.Item2.ToString());
The problem is that, the function returns the returnResultJSON before it is set by ws.OnMessage, is there a way to wait for the websocket until it is closed? what would the approach be in this situation?

Thank you in advance, I have been stuck in this for hours.

ambiguous error happen when build project on visual studio 2015 ?

$
0
0

Problem

ambiguous error happen when build project on visual studio 2015 ?

error : Combined length of user strings used by the program exceeds allowed limit..

How to solve this error please ?

my project big and have more files and cannot know 

on which place this problem come 

problem happen on csc file and i dont know on which place this file exist

and also how to solve this problem 

KeyPressEventHandler non-invocable

$
0
0

Here's the MSDN doc on the method but when I I try to do that I get this error. Severity    Code    Description    Project    File    Line    Suppression State
Error    CS0119    'KeyPressEventHandler' is a type, which is not valid in the given context 

MSDN Doc https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.keypresseventhandler?view=netframework-4.7.2

I have this line in the constructor of a winForm class.    textBox1.KeyPress += KeyPressEventHandler(textbox1KeyHandler);


Does .NET (native) have ability to, connect to and manually capture images from webcam? Not looking for 3rd party.

$
0
0

Hi all...

Does .NET have built in abilities to connect to a webcam and manually stream from it?  As I mentioned in the title, I'm not wanting to use 3rd party libs.  Rather hoping to find something directly from Microsoft that I can use. Business reasons for wanting to stay away from 3rd party.

If not anything that's C#(managed) what would be the best option from the C++ APIs that could be wrapped with C#?


Rick

Get latest directory in a path - with respect to the the name of directory

$
0
0
Hi, i have a requirement to get the last created directory in a path with respect to its name, as an application i use created 2 directories during the runtime and i need to consider only one of them, which in order appears later. For e.g the app creates 2 folders with name: 60000c and b3c143 and i need the one with the name "b3c143". How can i acheive this? Thanks.

Service Service OLEDB-connection

$
0
0

Bonjour,

J'ai un service Windows qui se bloque lors de l'ouverture d'une connexion vers un fichier Excel, comme ceci: 
----------------------- 
using (var connection = new OleDbConnection ( 
"Fournisseur = Microsoft.Jet.OLEDB.4.0; Source de données ="  
+ NomFichier + "; Propriétés étendues = \" Excel 8.0 \ "")) 

connection.Open (); 
// commence à utiliser la connexion 

----------------------- 
Ce code fonctionne correctement lorsque vous utilisez une console d'application. Lorsque je débogue le service Windows avec Visual Studio, l’exécution s’arrête  jusqu'à l'appel de connexion.Open ().

TaskFolder.RegisterTaskDefinition method thrown an exceptions [Error] (21,8):UserId:

$
0
0

TaskFolder.RegisterTaskDefinition method thrown an exceptions [Error] (21,8):UserId:

while creating scheduler task programmatically

Piece of code we are using:

ITaskService svc = new TaskScheduler.TaskScheduler();
svc.Connect();
var root = svc.GetFolder("\\");

var sid = (SecurityIdentifier)new NTAccount(username).Translate(typeof(SecurityIdentifier));
            principal.UserId = sid.ToString();

 var regTask = root.RegisterTaskDefinition(taskName, taskDef, (int) _TASK_CREATION.TASK_CREATE_OR_UPDATE,
                    principal.UserId, password,_TASK_LOGON_TYPE.TASK_LOGON_PASSWORD);

Want to know in which scenarios RegisterTaskDefinition() throws an exception.

Currently we re receiving the exception

[Error] (21,8):UserId:


Thanks, Harish

How to parse excel formula and pickup cell address

$
0
0

in my apps excel formula saved in db. which i need to change by c# code

My formula looks like (AM453+AM468+AM483+AM498) which should be change like below one. 

IF(AM453="","",IF(AM468="","",IF(AM483="","",IF(AM498="","",(AM453+AM468+AM483+AM498))))

AM468 or AM453 etc are cell address in excel.

My formula also may look like (AM453+AM468+(AM483/AM498)) OR (AM453+AM468-(AM483*AM498))

actually my formula could be anything which i need to parse and inject IF cell address is blank then return blank this way

IF(AM453="","",IF(AM468="","",IF(AM483="","",IF(AM498="","",(AM453+AM468+AM483+AM498))))

please share some routine which i can use to pick cell address one by one from any kind of formula. after pickup cell address i need to enter this one in formula like IF(AM453="","",.......)

please guide me how to achieve this with sample routine. if possible share a sample routine. thanks

Pass selected text with F9 or another function key from any application to C# application

$
0
0

Hi,

I would like to program a phone dialer to select a phone number in any application, and with a keypress, F9 for example, pass it to a little C# application. The application interfaces with the PBX to automaticly dial the number for the user. 

What solution can i use to pass a selected text from any application to the C# application?

Twan.

How do I put sections of txt file to seperate varibles?

$
0
0

So I have a txt file with several sections and I want to put those sections into diffrent variables.

For exapmple here is my text file:

Section1:
item1

Section2:
item2
item3
item4

so I want to put all item from section1 to a varibale and to put all items from section2 to its own variable



About the standards followed by RNGCryptoServiceProvider

$
0
0
What is the standard that RNGCryptoServiceProvider follows?What is the standard that RNGCryptoServiceProvider follows.
Is it NIST SP 800-90A, or something else?

Use CSharp Protobuf ParseFrom(Stream),But Show Wire Type is Invalid,Could Someone Tell me Where am I wrong?Thanks a lot

$
0
0

Below is the code :

FileStream stream = new FileStream("D:\\share_jcy\\ProtoBuf\\demo.proto", FileMode.Open);
CodedInputStream inStream = new CodedInputStream(stream);
TestDeprecatedFields f = TestDeprecatedFields.Parser.ParseFrom(stream);

TestDeprecatedFields was the class I compiled from the proto file with protoc.I run these code,but it comes System.InvalidOperationException:“Wire Type is invalid.”

Could Someone Tell me How can I Parse the proto file?Thanks a lot.

Calling 3rd Part Code asynchronously

$
0
0

I am customizing some 3rd party code. I want to call some code asynchronously which is currently not working in async/await.

Ex :- Casting an object  - [(Root)system] boot Root and system are 3rd party code.

Note:- This works if i run it synchronously.

inside an async/await which throws exception, Function requires all threads to run and then null reference Exception.

Does this means it involves UI somehow?? As i believe code involving UI cannot run asynchronously.

If it is not UI related then how to rectify this?

New .net web application to for searching files in a folder

$
0
0

Hi Everyone, I am very new to the web development sector. i have got a requirement as described below. 

Create a web application with following functionality.

    • Search Detail :
    1. Date Picker
    2. Customer Number
    3. Stock Number
  1. Configure the parent folder path in the web.config
  2. Write functionality to list all PDF file which matches the search criteria.
  3. On click of listed PDF files, view PDF
  4. i also want to know that if UI part comes along with this functionality? 

    So i am looking for details like how i can achieve this technically in .NET visual studio. quick help will be appreciated.

    any similar projects tutorial would be great.

    Thanks in advance!!!

    Madhu 

      i have a problem while update query in c# access data , please help me it says data type mismatch

      $
      0
      0

       "public static int updatestrecord(String St_name, String St_fname, String Address, int Contact_no, int Student_id)
              {
                  String query= "update St_record set St_name='" + St_name+ "',St_fname='"+St_fname+"',Address='"+Address+"',Contact_no='"+Contact_no+"' where Student_id='"+Student_id+"'";
                  OleDbCommand com= new OleDbCommand(query,conn);
                  int rows = com.ExecuteNonQuery();
                  return rows;
              }"this is a database class code for update button ".

      and thats a button code of update "

      private void update_Click(object sender, EventArgs e)
              {
                  int Student_id = Int32.Parse(textBox1.Text);
                  String St_name = textBox2.Text;
                  String St_fname = textBox3.Text;
                  String Address = textBox4.Text;
                  int Contact_no = Int32.Parse(textBox5.Text);
                  
                  int row = Databaseconn.updatestrecord(St_name,St_fname,Address,Contact_no,Student_id);
                  if (row > 0)
                  {
                      MessageBox.Show("record updated");
                  }
                  else MessageBox.Show("error");

              }

      Viewing all 31927 articles
      Browse latest View live


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