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

ASP.NET Problem with TreeView bind from datasource

$
0
0

Hi

I am trying to populate TreeView from database but I am having problems with sub child nodes 

Why "Durres" doesnt show up as child of "Tirana" and why "Shkoder" doesnt show up as child of "Durres"?

Database code

CREATE TABLE [dbo].[TopBill] (
    [srNo]     INT          NOT NULL IDENTITY,
    [Pid]      INT          NULL,
    [PName]    VARCHAR (50) NULL,
    [PDetails] NCHAR (10)   DEFAULT (NULL) NULL,
    [cId]      INT          NULL,
    [Cname]    VARCHAR (50) NULL,
    [Cqty]     INT          DEFAULT (NULL) NULL,
    CONSTRAINT [PK_TopBill] PRIMARY KEY CLUSTERED ([srNo] ASC)
);

Database data

C# code

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class Index : System.Web.UI.Page
    {
        Boolean m_bNodeFound;
        Boolean intNodeFound;
        string sValuepath;
        protected void Page_Load(object sender, EventArgs e)
        {




            if (!IsPostBack)
            {

                using (var connection = new SqlConnection("Data Source=(localdb)\\ProjectsV13;Initial Catalog=gab;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"))
                {
                    string com = "Select * from dbo.TopBill";
                    SqlDataAdapter adpt = new SqlDataAdapter(com, connection);
                    DataTable dt = new DataTable();
                    adpt.Fill(dt);
                    connection.Open();
                    TreeNode root = new TreeNode();

                    root = new TreeNode();
                    root.Text = dt.Rows[0][5].ToString();
                    root.Value = dt.Rows[0][5].ToString();
                    TreeView1.Nodes.Add(root);
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        //make NodeNotFound  at each row
                        m_bNodeFound = false;

                        //root as it is
                        TreeNode tn = root;

                        //get NodeName by cName
                        string nodeName = dt.Rows[i][5].ToString();

                        //Check if it is not null, to skip errors
                        if (nodeName != null && nodeName != "")
                        {
                            //MainNodecollections
                            TreeNodeCollection nodes = TreeView1.Nodes;

                            //Check if node already exists in Treeview
                            FindNodeInHierarchy(nodeName);

                            //If not found then continue
                            if (!m_bNodeFound)
                            {
                                //If node is root node
                                if (dt.Rows[i][2].ToString() == "" || dt.Rows[i][2].ToString() == null)
                                {
                                    TreeNode root2 = new TreeNode();
                                    root2.Text = dt.Rows[i][5].ToString();
                                    root2.Value = dt.Rows[i][5].ToString();
                                    TreeView1.Nodes.Add(root2);
                                }
                                //Check if node is child node
                                else if (CheckRowsAllValues(dt.Rows[i][1].ToString(), dt))
                                {
                                    //Find New Root of child node
                                    TreeNode NewRoot = FindRoot(dt.Rows[i][1].ToString(), dt, root);
                                    //if New root is not empty 
                                    if (NewRoot != null)
                                    {
                                        TreeNode root2 = new TreeNode();
                                        root2.Text = dt.Rows[i][5].ToString();
                                        root2.Value = dt.Rows[i][5].ToString();
                                        //append child node(current value) with new root
                                        NewRoot.ChildNodes.Add(root2);
                                    }

                                }
                            }

                        }
                    }

                }
            }
        }

        private TreeNode FindRoot(string v, DataTable dt, TreeNode tNode)
        {
            string expression = "cId = " + v;
            DataRow[] foundRows;
            foundRows = dt.Select(expression);

            //Find node using Id of table row
            TreeNode tn = TreeView1.FindNode(foundRows[0][0].ToString());

            //if not found, search using Name
            if (tn == null && foundRows[0][5].ToString() != "")
            {
                var value = foundRows[0][5].ToString();
                TreeNode searchedNode = null;

                //search node by Value(City Name) by looping each node
                foreach (TreeNode node in TreeView1.Nodes)
                {
                    if (searchedNode == null)
                    {
                        searchedNode = SearchNode(node, value);
                        if (searchedNode == null)
                        {
                            foreach (TreeNode childNode in node.ChildNodes)
                            {
                                searchedNode = SearchNode(childNode, value);
                                if (searchedNode != null)
                                    tn = searchedNode;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                tn = searchedNode;

            }

            return tn;
        }

        //Search Node code
        private TreeNode SearchNode(TreeNode node, string searchText = null)
        {
            if (node.Text == searchText) return node;

            TreeNode tn = null;
            foreach (TreeNode childNode in node.ChildNodes)
            {
                tn = SearchNode(childNode);
                if (tn != null) break;
            }

            if (tn != null) node.Expand();
            return tn;
        }

        private bool CheckRowsAllValues(string v, DataTable dt)
        {
            string expression = "cId = " + v;
            DataRow[] foundRows;
            foundRows = dt.Select(expression);
            if (foundRows.Count() > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }



        private void FindNodeByValue(string strValue)
        {
            // If the TreeView control contains any root nodes, perform a
            // preorder traversal of the tree and display the text of each node.
            if (TreeView1.Nodes.Count > 0)
            {

                // Iterate through the root nodes in the Nodes property.
                for (int i = 0; i < TreeView1.Nodes.Count; i++)
                {

                    // Display the nodes.
                    DisplayChildNodeText(TreeView1.Nodes[i], strValue);

                }

            }
        }


        void DisplayChildNodeText(TreeNode node, string strValue)
        {

            // Display the node's text value.
            //Message.Text += node.Text + "<br />";
            if (strValue == node.Text.ToString())
            {
                sValuepath = node.ValuePath;
                intNodeFound = true;
            }

            // Iterate through the child nodes of the parent node passed into
            // this method and display their values.
            for (int i = 0; i < node.ChildNodes.Count; i++)
            {

                DisplayChildNodeText(node.ChildNodes[i], strValue);

            }

            if (intNodeFound) return;

        }



        private void FindNodeInHierarchy(string strSearchValue)
        {

            // If the TreeView control contains any root nodes, perform a
            // preorder traversal of the tree and display the text of each node.
            if (TreeView1.Nodes.Count > 0)
            {

                // Iterate through the root nodes in the Nodes property.
                for (int i = 0; i < TreeView1.Nodes.Count; i++)
                {

                    // Display the nodes.
                    CheckChildNodeText(TreeView1.Nodes[i], strSearchValue);

                }

            }
        }


        void CheckChildNodeText(TreeNode node, string strValue)
        {

            // Display the node's text value.
            //Message.Text += node.Text + "<br />";
            if (strValue == node.Text.ToString())
            {
                m_bNodeFound = true;
            }

            // Iterate through the child nodes of the parent node passed into
            // this method and display their values.
            for (int i = 0; i < node.ChildNodes.Count; i++)
            {

                DisplayChildNodeText(node.ChildNodes[i], strValue);

            }

            if (m_bNodeFound) return;

        }
    }
}


The result 

What code should do or what I want in this case


How to open and display a file in c#

$
0
0

Hi

   I need to open a file and display it by providing the file path. I tried with the below code

FileStream stream = File.Open("C:\\Users\\Desktop\\Sample.txt", FileMode.Open);

But the file is not getting opened. So please help me on this issue.

Thanks in Advance.

DateTime function

$
0
0

Hi Experts, 

How can I convert the below SQL  to an equivalent C# method.. this is the input value ''2019-12-11 04:57:00.5456551 +00:00''

SELECT DATEADD(mi, DATEDIFF(mi, GETUTCDATE(), CURRENT_TIMESTAMP),CAST('2019-12-11 04:57:00.5456551 +00:00' AS DATETIME2)) 


Thanks

Priya

How do I find a picture/image on the screen and get the x,y coordinates? - C#.NET

$
0
0

Hi Guys,

I want to find the picture/image on the screen and get the x,y coordinates if it matched on the screen. I already know how to move the mouse and click using this x,y coordinates.

Example: I have cropped "This PC" image on the windows desktop screen and saved it as "This PC.png". I want to find the x,y coordinates of that picture(This PC.png) that would exactly match on the desktop screen. So my C# code needs to find that "This PC.png" image on the desktop screen and return the x,y mouse coordinates.

I want to click/double-click the "This PC" option using this x,y mouse coordinates and open it.

Thanks

Satheesh


How to update one datatable to another datatable at same time using sql?

$
0
0

I am using desktop application(C#.net) with SQL database which is large data for an example: 500 rows. i want to update particular column data from one table(A Table) to another(B Table) . whenever update or delete is happening in one table has to update another table at same time. I don't know whether to use delete entire rows in the new table (B Table) and to copy  all the rows from (A Table) to (B Table) for every modification in (A Table).

Calling function in injected process dll

$
0
0

I want to call test function in InjectDll.dll which is already injected to the process.

but It's said "The program is stopped working".

and I'm wonder how to get the return value of test function

Here is Inject function:

public void InjectDLL(IntPtr hProcess, String strDLLName)
        {
            IntPtr bytesout;

            // Length of string containing the DLL file name +1 byte padding
            Int32 LenWrite = strDLLName.Length + 1;
            // Allocate memory within the virtual address space of the target process
            IntPtr AllocMem = (IntPtr)VirtualAllocEx(hProcess, (IntPtr)null, (uint)LenWrite, 0x1000, 0x40); //allocation pour WriteProcessMemory

            // Write DLL file name to allocated memory in target process
            WriteProcessMemory(hProcess, AllocMem, strDLLName, (UIntPtr)LenWrite, out bytesout);
            // Function pointer "Injector"
            UIntPtr Injector = (UIntPtr)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
            //UIntPtr Injector = (UIntPtr)GetProcAddress(GetModuleHandle(@"InjectDll.dll"), "test");
            if (Injector == UIntPtr.Zero)
            {
                MessageBox.Show(" Injector Error! \n ");
                // return failed
                return;
            }

            // Create thread in target process, and store handle in hThread
            //IntPtr hThread = (IntPtr)CreateRemoteThread(hProcess, (IntPtr)null, 0, Injector, AllocMem, 0, out bytesout);
            IntPtr hThread = (IntPtr)CreateRemoteThread(hProcess, (IntPtr)null, 0, GetProcAddress(GetModuleHandle(@"InjectDll.dll"), "test"), AllocMem, 0, out bytesout);
            Console.WriteLine("out"+bytesout);
            // Make sure thread handle is valid
            if (hThread == IntPtr.Zero)
            {
                MessageBox.Show(" hThread 1 Error! \n ");
                return;
            }
            // Time-out is 10 seconds...
            int Result = WaitForSingleObject(hThread, 10 * 1000);
            // Check whether thread timed out...
            if (Result == 0x00000080L || Result == 0x00000102L || Result == 0xFFFFFFFF)
            {
                /* Thread timed out... */
                MessageBox.Show(" hThread 2 Error! \n ");
                // Make sure thread handle is valid before closing... prevents crashes.
                if (hThread != IntPtr.Zero)
                {
                    //Close thread in target process
                    CloseHandle(hThread);
                }
                return;
            }
            // Sleep thread for 1 second
            //Thread.Sleep(1000);
            // Clear up allocated space ( Allocmem )
            VirtualFreeEx(hProcess, AllocMem, (UIntPtr)0, 0x8000);
            // Make sure thread handle is valid before closing... prevents crashes.
            if (hThread != IntPtr.Zero)
            {
                //Close thread in target process
                CloseHandle(hThread);
            }
            // return succeeded

            return;
        }

Here is InjectDll.cpp:

// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
					 )
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
		MessageBox(NULL, (LPCWSTR)L"Hello World!", (LPCWSTR)L"Dll says:", MB_OK);
		break;
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	case DLL_PROCESS_DETACH:
		break;
	}
	return TRUE;
}

int test()
{
	return 5;
}

How to integrate C/C++ source code into C# project

$
0
0

Now I have some UI source code written in C#, and my algorithm written in C/C++, I wanna add C/C++ source code(not DLL) in C# project for visually debugging, Is it possible? if so, how to do it

I know firstly compling C/C++ as DLL file ,and then calling  the  C/C++ dll file in C# project is possible, but it is not what I want, because debugging in this way is not convenient, what i want is compliling C# UI code and C/C++ algorithm code at the same time, and display at the same time, like MATLAB does 

regard.

NumberFormatInfo.CurrentInfo returns wrong value for NumberDecimalDigits

$
0
0

Hi Team,

The property NumberFormatInfo.CurrentInfo(read-only) returns wrong value for NumberDecimalDigits with my ASP.Net application, but works correctly in my console application. Actually I have changed the property "No. of digits after decimal" property in Windows Control Panel from "2" to "9". It still returns 2 in my ASP.Net application whereas it returns 9 correctly in my Console application. Please help me on this.


Performance Issue - FileSystemWatcher

$
0
0

Hi Experts, 

Am working on file processing task where I need to bulk load the files into Database SQL Server for this am using the FileSystemWatcher which works as required and am a newbie in C#. 

The problem starts to build up when the drive gets a massive load of 10-20 files gets loaded in the directory getting monitored with each file around 30-40 mb in size.. 

The CPU starts peaking 50-60 percent.. To avoid the CPU issue , am trying 

File Caching but still issue persists. Am thinking if I could delay the processing file by 1-2 seconds interval between each file that may reduce the overhead on the processor.  Please suggest if delay need to be added what's the best way or any other approach.

The process method simply obtains the csv --> use csvhelper to load to data table --> datatable finally gets loaded into SQL Server using bulk insert.  

It may contain 40-50 k records per file. Please share optimisation techniques 

  private static MemoryCache FilesToProcess = MemoryCache.Default;
      

private static void AddToCache(string fullPath) { var item = new CacheItem(fullPath, fullPath); var policy = new CacheItemPolicy { RemovedCallback = ProcessFile, SlidingExpiration = TimeSpan.FromSeconds(5), }; FilesToProcess.Add(item, policy); }


   private static void FileCreated(object sender, FileSystemEventArgs e)
      {

          AddToCache(e.FullPath);
      }


        private static void ProcessFile(CacheEntryRemovedArguments args)
        {

            if (args.RemovedReason == CacheEntryRemovedReason.Expired)
            {
                var fileProcessor = new DataProcessing(args.CacheItem.Key);
                fileProcessor.Process();
            }
            else
            {
               
            }
        }

Thanks 

Priya

Howto get display Windows display numbers

$
0
0

When users setup displays in Windows a number is assigned to each display and the user can show these numbers by clicking identify. When an application wants to launch a new window I want to show these numbers to the user, to make it easy to select where the window must go. Thus I would like to know what the display number of each monitor is.

I have tried different approaches, using the System.Windows.Forms.Screen.AllScreens which is normally used in C#/.Net to get info about monitor, but it does not contain the number. I also tried using WMI with a series of different "select" statements and a lot of different monitor info can be retrieved, but not the number.

So how do you get the display numbers from Windows or is that impossible?

The numbers I am looking for are the ones shown in this screenshot from Windows 10 (in this case 2 is the primary display):



Unhandled Exception

$
0
0
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _11._12._2019
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            using(SqlConnection cn=new SqlConnection(Properties.Settings.Default.connString))
            {

                var selectStatement = "select FirstName, LastName from hawk.dbo.Customers" +"where Identifier=@ID";

                using(var cmd=new SqlCommand() { CommandText=selectStatement, Connection=cn})
                {
                    
                    cmd.Parameters.AddWithValue("@ID", 100);
                    cn.Open();
                        cmd.ExecuteReader();

                  








                }




            }
        }
    }
}

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Incorrect syntax near '='.

FileSystemWatcher - Move file with fix count

$
0
0

Hi Experts, 

Is there a way I can limit the files to moved which uses the File event watcher for creation & changed. Let say if my directory gets loaded with 100 files of 30 -40 mb each. If I need to move these files to another location just move 3 files and add delay of 10 seconds interval. The reason I am doing this because if I do massive transfer my other background services will try to process all the files and that peaks up the CPU.

Thanks

Priya

Split the string to a structure

$
0
0
Hello,
I need to structure this string.
I see the signs = and | and ,
REQUESTCOMMANDO|id=x|messageID=324|process=CONNECTION|station=4565332|question=serials

BACKCOMMANDO|id=x|messageID=324|process=CONNECTION|station=4565332|software=V1.242|attributedata=bottomSideId,70704315500000,7070431550000001,7070431550000002,7070431550000003,7070431550000004,7070431550000005,7070431550000006,7070431550000007,7070431550000008,7070431550000009,7070431550000010|attributedata=topSideId,70704315500100,7070431550010001,7070431550010002,7070431550010003,7070431550010004,7070431550010005,7070431550010006,7070431550010007,7070431550010008,7070431550010009,7070431550010010|status=PASS
How could I best parse, split this string?
What's the best way to do it? With RegEx?
What's the best course of action?
Please note messageID=324  --> Can be inside or not
                           --> Increase for each message

Could you please show me different ways or possibilities? Thank you for your help in advance.

tip

Many greetings Markus


Text adventure game page 1 issues?

$
0
0

Hi! So I'm working on a school project and have been asking my professor questions, but he is not very kind or willing to help so I'm turning here. I am trying to have a welcome page on my text adventure game. No matter what, the first page to come up when I hit play on unity is the second page. Stranger still, I have it set to ask if you want to play again when you die, and when you hit y, it is routed to the welcome page, yet the second page is what comes up. In the original game, there was no welcome page. From what I can see, I have changed all previous coding to indicate the new page 1, but my game just will not show it. I copy and pasted the whole code here, because I have no idea where in the code it is getting confused. Sorry this is a lot to ask, but I am just curious as to why I cannot get it to work. To make things more clear page 1 is meant to be welcome, and page 2 is the start of the story, "wake up". 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TrumbleMadison_Week2Project : MonoBehaviour
{
    Text screen;
    Page[] book;

    [SerializeField]
    string prevHeading;
    [SerializeField]
    string currHeading;
    [SerializeField]
    string nextHeading = "welcome!";


    // Start is called before the first frame update
    void Start()
    {
        GameObject go = GameObject.Find("MainText");

        if (go)
        {
            screen = go.GetComponent<Text>();

            if (!screen)
            {
                Debug.LogError("Text Component was not found on Maintext");
            }
        }
        else
        {
            Debug.LogError("MainText not found");
        }

        //screen.text = "Hello World";

        Bindbook();
    }




    // Update is called once per frame
    void Update()
    {
        HandleInput();
        RenderStory();
    }

    void Bindbook()
    {
        book = new Page[]
        {
            //13


            new Page("welcome!", "<i>(this is: welcome)</i>\n\nwelcome to my game! please press <b><color=blue>[space]</color></b> to continue"),

            new Page("wake up", "<i>(this is: wake up)</i>\n\nyou awaken in a sweltering room that smells of dust and dry rot. to your left, you see a woven basket, and about three feet in front of you, there is a deep steel bowl filled with what looks like milk. ten feet beyond that is a heavy iron door you assume is locked. will you check the <color=blue><b>[w]</b></color>oven basket, <color=blue><b>[b]</b></color>owl, or <color=blue><b>[d]</b></color>oor?"),

            new Page("basket", "<i>(this is: basket)</i>\n\nyou walk over to examine the woven basket, which stands almost 3 feet tall. you see that the lid on the basket has a handle, but when you try to pull up, it seems to be tied down. you find ties on four sides of the basket holding the lid on. you undo the ties and find the basket oddly empty. however, you notice the stone beneath it is loose. do you  <color=blue><b>[i]</b></color>nspect the stone, or press  <color=blue><b>[x]</b></color> to return to the previous step."),

            new Page("inspect", "<i>(this is: inspect)</i>\n\nyou reach between the stones and manage to pry it up. it reveals a narrow tunnel leading down, but you can't see too far into it because it is dark. do you go  <color=blue><b>[d]</b></color>own into the tunnel, or look for a <color=blue><b>[l]</b></color>ight source to get a better view?"),

            //lose:(
            new Page("down", "<i>(this is: down)</i>\n\nyou head down into the tunnel despite not knowing what else may be there. you stumble around for a moment before falling straight down a booby trap that you surely would have seen with a light. <b><color=red>you died.</color></b>would you like to try again?\n\n<color=blue><b>[y]</b></color> or  <color=blue><b>[n]</b></color>"),

            new Page("light", "<i>(this is: light)</i>\n\nyou search the area for any possible source of light and discover a flashlight. you turn it on, and it flickers, but you can see a bit further into the tunnel. would you like to go into the  <color=blue><b>[t]</b></color>unnel, or check out the  <color=blue><b>[b]</b></color>owl of milk you noticed earlier"),

            new Page("tunnel", "<i>this is: tunnel)</i>\n\nyou use your light to venture into the tunnel, noticing a large trap hole in the center of the pathway. you side step it and continue onward. you may either continue <color=blue><b>[s]</b></color>traight or <color=blue><b>[r]</b></color>eturn to the surface."),

            //win!
            new Page("straight", "<i>(this is: straight)</i>\n\nyou continue straight and, to your surprise, it comes up to an exit near a desert resort. you check in. <b><color=lime>you have a great time and survive!</color><b>would you like to play again?\n\n<color=blue><b>[y]</b></color> or  <color=blue><b>[n]</b></color>"),
           
            new Page("door", "<i>(this is: door)</i>\n\nyou think it should be easy enough to waltz through an iron door. when you come upon it, you realize it is much heavier than originally thought. you put all your weight on it, but it only groans and will not budge.\n\nit seems you will need a key to unlock the door before it moves anymore. press  <color=blue><b>[x]</b></color> to return to the previous step."),

            new Page("bowl of milk", "<i>(this is: bowl of milk)</i>\n\nyou look at the bowl of creamy liquid before you, unsure of its contents. you tap the bowl with your foot and see that the liquid moves with the same viscosity as milk would. you are quite parched. do you <color=blue><b>[p]</b></color>ick up the bowl, or press <color=blue><b>[x]</b></color> to return?"),

            new Page("pick up", "<i>(this is: pick up)</i>\n\nyou pick up the bowl and bring it closer to sniff the contents. the smell of the liquid is mild, although there is a twinge of something odd to it that you cannot place your finger on. you slosh the liquid a bit and notice something shifting at the bottom of the bowl. do you <color=blue><b>[p]</b></color>our out the contents or <color=blue><b>[d]</b></color>rink the liquid? or press <color=blue><b>[x]</b></color> to return to the previous step."),

            //win!
            new Page("pour", "<i>(this is: pour)</i>\n\nyou pour out all the contents onto the dusty floor, including what seems to be some maggots and a wrought iron key. one that looks to fit in the keyhole of the heavy door. you use to unlatch the door and budge it enough to escape. <color=lime><b>you win!</b></color> would you like to play again?\n\n<color=blue><b>[y]</b></color> or <color=blue><b>[n]</b></color>"),

            //lose:(
            new Page("drink", "<i>(this is: drink)</i>\n\nyou decide your thirst could help to kill two birds with one stone and begin to drink the liquid. the liquid isn't milk at all and has a severe acrid taste. you swallow some more anyways, feeling chunks of items floating on your tongue. you spit out the bits and upon further inspection see they are wriggling. you toss the bowl away from you as you feel the need to wretch. standing up, you see a key laying next to the tossed bowl. as you go to reach for it, you fall forward, mind hazing into unconciousness. <b><color=red>you died.</color></b> would you like to try again?\n\n<color=blue><b>[y]</b></color> or <color=blue><b>[n]</b></color>"),

            new Page("thanks", "<i>(this is: thanks for playing!</i>\n\n thank you for playing!")

        };
    }

    void RenderStory()
    {
       if (!string.IsNullOrEmpty(nextHeading))
        {
            for (int i = 0; i < book.Length; i++)
            {
                if (nextHeading == book[i].Heading)
                {
                    prevHeading = currHeading;
                    currHeading = nextHeading;
                    nextHeading = "";

                    screen.text = book[i].Body;
                    Debug.Log(book[i].Body);

                    return;
                }
            }

            Debug.LogWarning("Heading not found: \"" + nextHeading + "\""); 
        }
    }

    void HandleInput()
    {
        
        
            if (currHeading == "welcome!")
            {
                nextHeading = "wake up";
            }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (currHeading == "welcome!")
            {
                nextHeading = "wake up";
            }
        }

        if (Input.GetKeyDown(KeyCode.W))
        {
            if (currHeading == "wake up")
            {
                nextHeading = "basket";
            }
        }
        else if (Input.GetKeyDown(KeyCode.B))
        {
            if (currHeading == "wake up" || currHeading == "light")
            {
                nextHeading = "bowl of milk";
            }
        }
        else if (Input.GetKeyDown(KeyCode.D))
        {
            if (currHeading == "wake up")
            {
                nextHeading = "door";
            }
            else if (currHeading == "inspect")
            {
                nextHeading = "down";
            }
            else if (currHeading == "pick up")
            {
                nextHeading = "drink";
            }
        }
        else if (Input.GetKeyDown(KeyCode.I))
        {
            if (currHeading == "basket")
            {
                nextHeading = "inspect";
            }
        }
        else if (Input.GetKeyDown(KeyCode.L))
        {
            if (currHeading == "inspect")
            {
                nextHeading = "light";
            }
        }
        else if (Input.GetKeyDown(KeyCode.T))
        {
            if (currHeading == "light")
            {
                nextHeading = "tunnel";
            }
        }
        else if (Input.GetKeyDown(KeyCode.X))
        {
            nextHeading = prevHeading;
        }
        else if (Input.GetKeyDown(KeyCode.Y))
        {
            if (currHeading == "down" || currHeading == "straight" || currHeading == "pour" || currHeading == "drink")
            {
                nextHeading = "welcome!";
            }
        }
        else if (Input.GetKeyDown(KeyCode.P))
        {
            if (currHeading == "bowl of milk")
            {
                nextHeading = "pick up";
            }
            else if (currHeading == "pick up")
            {
                nextHeading = "pour";
            }
        }
        else if (Input.GetKeyDown(KeyCode.N))
        {
            if (currHeading == "drink" || currHeading == "pour" || currHeading == "straight" || currHeading == "down")
            {
                nextHeading = "thanks";
            }
        }
    }
}

C# program execution over the internet

$
0
0

I am attempting to execute a C# program over the internet.  I am trying to do the following:

(1) Initiate the execution of the program from a web page on a client computer.

(2) I want the program to be executed on the server, while all resulting screen displays to be displayed on the client computer's screen.

My question is - Is this doable?


Best way to delete and insert data into xml file

$
0
0

i have two xml file which identical but data could be different. so i need to find data from file1.xml by condition and remove that element if data found and find same data from file2.xml if found then i need to copy that element into file1.xml file.

i have many tables in my xml files.

see one records which give you idea.

<Broker ID="4E" Ticker_Id="ADBE" BrokerCategory="Contributing" Client=""><Broker_Id>0</Broker_Id><ALLTabsUnderBroker><Broker>4E</Broker><TAB>BlueMatrix</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>Model_Introduction</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>Cover</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>Drivers</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings>4Q 2019</ReviewedEarnings><Pre-Post>Pre</Pre-Post></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>IS</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings>4Q 2019</ReviewedEarnings><Pre-Post>Pre</Pre-Post></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>BS</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings>4Q 2019</ReviewedEarnings><Pre-Post>Pre</Pre-Post></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>CF</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings>4Q 2019</ReviewedEarnings><Pre-Post>Pre</Pre-Post></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>FX</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>Dates</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>Variance</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>Consensus</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>Preview</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>Valuation</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>CC Subscriptions &amp; ASPs</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>Valuation_2</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>4Q16</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>Summit2016 Preview</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>CS Seats</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>CC_New_Drivers</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>New Drivers</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>DCF</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>Preview_OLD</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>Estimates</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>Drivers - Historical </TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>Price Chart</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>CheetSheet</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>Digital Marketing</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>PT Raise</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>4E</Broker><TAB>Charts</TAB><Commnet1 /><Commnet2 /><Broker_Id>0</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker></Broker>

so i need to find in file1.xml file those broker element whose ID attribute has value say 4E like ID="4E" if found then i need to remove this records from file1.xml file and find the same records from another file2.xml file whose ID="4E" if found then i need to copy that broker element or that record from that file and add in file1.xml file.

please guide me with example that how to achieve this with minimum line of code. thanks


Please help to find out net variance between NetHrs Clocked and Net Hrs due of the employee

$
0
0

I am looking for the help to create the function in C# to find the  Variance Hrs  between  His DueHrs and ClockedHrs

If an Employee come in 15 minitus  early or leave 15 mins late then only 10 mins be considered as  his extra time worked. So his extra time would be considered only  after 10 mins from clock in and clock out

But if  he clocked in  5  mins late and he left 12 mins late  then  his variance would be 0. Because after compensating his late coming , he has only balance  7 mins.  that means after compensating the late hrs, he has excess 10 mins, then the variance would be  the differece after 10 mins.

if an employee is not entitled to work but if he has come for work , then the variance would be   the difference  between the clockout and clockin. [10 mins rule will not be applied]

Please find my workout in excel given below. Every calculation is done in mins . Please can  you help me how to write  a function in c# to get the variance

With Thanks

Pol


polachan


"The action can't be completed because the folder or a file in it is open in another program"

$
0
0

I have build a File Explorer in my C# application and when I am deleting folder/file in Windows Explorer, it does and I don't have this message.

I have such message when I am using Unreal Engine and I would have the same.

I don't want to be able to delete the folder/files in Windows Explorer, that I am using in my C# app.

How can I do that ?

I have read that https://stackoverflow.com/questions/25398264/lock-folder-using-c-sharp-and-want-access-files-from-this-folder

But the problem is that it create a temporary user to lock the file and it does generate not the same message, when trying to delete it from Windows Explorer and it's not what I want.

ASP.NET Problem with TreeView bind from datasource

$
0
0

Hi

I am trying to populate TreeView from database but I am having problems with sub child nodes 

Why "Durres" doesnt show up as child of "Tirana" and why "Shkoder" doesnt show up as child of "Durres"?

Database code

CREATE TABLE [dbo].[TopBill] (
    [srNo]     INT          NOT NULL IDENTITY,
    [Pid]      INT          NULL,
    [PName]    VARCHAR (50) NULL,
    [PDetails] NCHAR (10)   DEFAULT (NULL) NULL,
    [cId]      INT          NULL,
    [Cname]    VARCHAR (50) NULL,
    [Cqty]     INT          DEFAULT (NULL) NULL,
    CONSTRAINT [PK_TopBill] PRIMARY KEY CLUSTERED ([srNo] ASC)
);

Database data

C# code

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class Index : System.Web.UI.Page
    {
        Boolean m_bNodeFound;
        Boolean intNodeFound;
        string sValuepath;
        protected void Page_Load(object sender, EventArgs e)
        {




            if (!IsPostBack)
            {

                using (var connection = new SqlConnection("Data Source=(localdb)\\ProjectsV13;Initial Catalog=gab;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"))
                {
                    string com = "Select * from dbo.TopBill";
                    SqlDataAdapter adpt = new SqlDataAdapter(com, connection);
                    DataTable dt = new DataTable();
                    adpt.Fill(dt);
                    connection.Open();
                    TreeNode root = new TreeNode();

                    root = new TreeNode();
                    root.Text = dt.Rows[0][5].ToString();
                    root.Value = dt.Rows[0][5].ToString();
                    TreeView1.Nodes.Add(root);
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        //make NodeNotFound  at each row
                        m_bNodeFound = false;

                        //root as it is
                        TreeNode tn = root;

                        //get NodeName by cName
                        string nodeName = dt.Rows[i][5].ToString();

                        //Check if it is not null, to skip errors
                        if (nodeName != null && nodeName != "")
                        {
                            //MainNodecollections
                            TreeNodeCollection nodes = TreeView1.Nodes;

                            //Check if node already exists in Treeview
                            FindNodeInHierarchy(nodeName);

                            //If not found then continue
                            if (!m_bNodeFound)
                            {
                                //If node is root node
                                if (dt.Rows[i][2].ToString() == "" || dt.Rows[i][2].ToString() == null)
                                {
                                    TreeNode root2 = new TreeNode();
                                    root2.Text = dt.Rows[i][5].ToString();
                                    root2.Value = dt.Rows[i][5].ToString();
                                    TreeView1.Nodes.Add(root2);
                                }
                                //Check if node is child node
                                else if (CheckRowsAllValues(dt.Rows[i][1].ToString(), dt))
                                {
                                    //Find New Root of child node
                                    TreeNode NewRoot = FindRoot(dt.Rows[i][1].ToString(), dt, root);
                                    //if New root is not empty 
                                    if (NewRoot != null)
                                    {
                                        TreeNode root2 = new TreeNode();
                                        root2.Text = dt.Rows[i][5].ToString();
                                        root2.Value = dt.Rows[i][5].ToString();
                                        //append child node(current value) with new root
                                        NewRoot.ChildNodes.Add(root2);
                                    }

                                }
                            }

                        }
                    }

                }
            }
        }

        private TreeNode FindRoot(string v, DataTable dt, TreeNode tNode)
        {
            string expression = "cId = " + v;
            DataRow[] foundRows;
            foundRows = dt.Select(expression);

            //Find node using Id of table row
            TreeNode tn = TreeView1.FindNode(foundRows[0][0].ToString());

            //if not found, search using Name
            if (tn == null && foundRows[0][5].ToString() != "")
            {
                var value = foundRows[0][5].ToString();
                TreeNode searchedNode = null;

                //search node by Value(City Name) by looping each node
                foreach (TreeNode node in TreeView1.Nodes)
                {
                    if (searchedNode == null)
                    {
                        searchedNode = SearchNode(node, value);
                        if (searchedNode == null)
                        {
                            foreach (TreeNode childNode in node.ChildNodes)
                            {
                                searchedNode = SearchNode(childNode, value);
                                if (searchedNode != null)
                                    tn = searchedNode;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                tn = searchedNode;

            }

            return tn;
        }

        //Search Node code
        private TreeNode SearchNode(TreeNode node, string searchText = null)
        {
            if (node.Text == searchText) return node;

            TreeNode tn = null;
            foreach (TreeNode childNode in node.ChildNodes)
            {
                tn = SearchNode(childNode);
                if (tn != null) break;
            }

            if (tn != null) node.Expand();
            return tn;
        }

        private bool CheckRowsAllValues(string v, DataTable dt)
        {
            string expression = "cId = " + v;
            DataRow[] foundRows;
            foundRows = dt.Select(expression);
            if (foundRows.Count() > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }



        private void FindNodeByValue(string strValue)
        {
            // If the TreeView control contains any root nodes, perform a
            // preorder traversal of the tree and display the text of each node.
            if (TreeView1.Nodes.Count > 0)
            {

                // Iterate through the root nodes in the Nodes property.
                for (int i = 0; i < TreeView1.Nodes.Count; i++)
                {

                    // Display the nodes.
                    DisplayChildNodeText(TreeView1.Nodes[i], strValue);

                }

            }
        }


        void DisplayChildNodeText(TreeNode node, string strValue)
        {

            // Display the node's text value.
            //Message.Text += node.Text + "<br />";
            if (strValue == node.Text.ToString())
            {
                sValuepath = node.ValuePath;
                intNodeFound = true;
            }

            // Iterate through the child nodes of the parent node passed into
            // this method and display their values.
            for (int i = 0; i < node.ChildNodes.Count; i++)
            {

                DisplayChildNodeText(node.ChildNodes[i], strValue);

            }

            if (intNodeFound) return;

        }



        private void FindNodeInHierarchy(string strSearchValue)
        {

            // If the TreeView control contains any root nodes, perform a
            // preorder traversal of the tree and display the text of each node.
            if (TreeView1.Nodes.Count > 0)
            {

                // Iterate through the root nodes in the Nodes property.
                for (int i = 0; i < TreeView1.Nodes.Count; i++)
                {

                    // Display the nodes.
                    CheckChildNodeText(TreeView1.Nodes[i], strSearchValue);

                }

            }
        }


        void CheckChildNodeText(TreeNode node, string strValue)
        {

            // Display the node's text value.
            //Message.Text += node.Text + "<br />";
            if (strValue == node.Text.ToString())
            {
                m_bNodeFound = true;
            }

            // Iterate through the child nodes of the parent node passed into
            // this method and display their values.
            for (int i = 0; i < node.ChildNodes.Count; i++)
            {

                DisplayChildNodeText(node.ChildNodes[i], strValue);

            }

            if (m_bNodeFound) return;

        }
    }
}


The result 

What code should do or what I want in this case

C#, SQL Server. Provider: TCP Provider, error: 0 - No such host is known

$
0
0

My connection string looks like this:

DataSource=sql88;InitialCatalog=Osm;User ID=foouser;Password=foopsw

The code that creates connection string looks like this:

var con =newSqlConnectionStringBuilder();if(string.IsNullOrEmpty(model.Username)&&string.IsNullOrEmpty(model.Password))
    con.IntegratedSecurity=true;else{
    con.UserID= model.Username;
    con.Password= model.Password;}
con.DataSource= model.Host??string.Empty;
con.InitialCatalog= model.Database??string.Empty;return con;

My application creates database structure at SQL Server, then inserting data. So sometimes the applcation works approximately 14 hours. The code that executes SQL at SQL Server looks like this:

using(var cmd = con.CreateCommand()){
    cmd.CommandTimeout=int.MaxValue;
    cmd.CommandText= sql;try{
        cmd.ExecuteNonQuery();}catch(Exception ex){var test = ex.Message;throw;}}

Sometimes application works well, but sometimes application throws an error:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.

provider: TCP Provider, error: 0 - No such host is known.) (Microsoft SQL Server, Error: 11001)

I've read this page, however, in my view this is not my case because sometimes my application works well.

Viewing all 31927 articles
Browse latest View live


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