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

C# Code to get Collection level User Permissions in Team Foundation Server

$
0
0
C# code to get Collection Level User Permissions using IIdentityManagementService and ISecurityService.

Need to get:

Administer build resource permissions

Administer Project Server integration

Administer shelved changes

Administer workspaces

Alter trace settings

Create a workspace

Create new projects

Delete team project 

Edit collection-level information

Make requests on behalf of others

Manage build resources

Manage process template

Manage test controllers

Trigger events

Use build resources

View build resources

View collection-level information

View system synchronization information


















How to delete BOM from a string?

$
0
0
Hello,
How I can delete the BOM?
Picture 1 and 2
bom1     bom 2       
Thanks for tips.
Greetings Markus
private static string RemoveBom(string p)
{
	string BOMMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
	if (p.StartsWith(BOMMarkUtf8, StringComparison.OrdinalIgnoreCase))
		p = p.Remove(0, BOMMarkUtf8.Length);
	return p.Replace("\0", "");
}

private async void FileReadOrTimeout(object sender, RoutedEventArgs e)
{
	try
	{
		var ret = await ReadDataAsync(@"C:\Users\Freitag\Documents\TEST_M_3.xml", 2000);

		string converted = Encoding.UTF8.GetString(ret, 0, ret.Length);
		converted = RemoveBom(converted);

		MessageBox.Show(converted + "\n \nEnd");
	}

}
private async Task<byte[]> ReadDataAsync(string pDatei, int pTimeOutMs)
{
	int n = 0;
	int m = (int)Math.Ceiling(pTimeOutMs / 100.0);

	while (!File.Exists(pDatei))
	{
		await Task.Delay(100);
		n++;
		if (n == m)
			throw new FileNotFoundException();

	}

	FileInfo fi = new FileInfo(pDatei);
	Stream streamXML;

	byte[] data = new byte[fi.Length];
	using (var fs = fi.OpenRead())
	{
		int read = await fs.ReadAsync(data, 0, data.Length);

		streamXML = new MemoryStream(data);

		var gpx = Deserialize<Msg>(streamXML);

		return data;
	}
}

//######################################################

XML Deserialize / Serialize with the same namespace

$
0
0
Hello,
I have an XML file, I copy it and paste it via the clipboard. Classes are created.
I can read the values -> IO
If I change values and save them again the namespaces are lost or look different. So how can I save it correctly? With same namespace as the original?
Thanks in advance for tips.
Greetings Markus
<?xml version="1.0"?><Msg xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://Epicor.com/Message/2.0"><Hdr><Ctrl><MsgID /></Ctrl><Sender><Name /><Subname /></Sender>
// ##################################################################################

static T Deserialize<T>(Stream stream)
{
	var serializer = new XmlSerializer(typeof(T));
	using (stream)
		return (T)serializer.Deserialize(stream);
}

using (var file = File.OpenRead(@"C:\Users\Freitag\Documents\TEST_M.xml"))
{
   var gpx = Deserialize<Msg>(file);

	var jobNo = gpx.Body.Req.Dta.Results.QueryResultDataSet.Results.JobHead_JobNum;

	jobNo = 6666666;
	gpx.Body.Req.Dta.Results.QueryResultDataSet.Results.JobHead_JobNum = 66663333;

	 var serializer = new XmlSerializer(typeof(Msg));

	using (var fileWrite = File.Create(@"C:\Users\Freitag\Documents\TEST_M_NEW.xml"))
		serializer.Serialize(fileWrite, gpx);
}
<?xml version="1.0" encoding="utf-16"?><msg:Msg xsi:schemaLocation="http://EBMThirdProducer.com/Message/2.0 http://scshost/schemas/epicor/ScalaMessage.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:msg="http://EBMThirdProducer.com/Message/2.0"><msg:Hdr><msg:Ctrl><msg:MsgID></msg:MsgID></msg:Ctrl><msg:Sender><msg:Name></msg:Name><msg:Subname></msg:Subname></msg:Sender><msg:Receiver><msg:Name>Company</msg:Name><msg:Subname>OrderData</msg:Subname></msg:Receiver><msg:Logon></msg:Logon></msg:Hdr><msg:Body><msg:Req msg-type="Company" action="GetOrderData"><msg:Dta><ext_UserSchema:Results xmlns:msg="http://EBMThirdProducer.com/InternalMessage/1.1" xmlns:ext_UserSchema="http://EBMThirdProducer.com/SC/UserSchema"><QueryResultDataSet xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Results><JobHead_JobNum>116666580</JobHead_JobNum><JobHead_PartNum>555724307910003</JobHead_PartNum><JobHead_ProdQty>5.06000000</JobHead_ProdQty><CustXPrt_XPartNum>33666-355-03</CustXPrt_XPartNum><CustXPrt_XRevisionNum>D1</CustXPrt_XRevisionNum><CustXPrt_SNLastUsedSeq/><Calculated_TemplateID>31166-355-03</Calculated_TemplateID></Results><ExecutionInfo><Name>ExecutionTime</Name><Value>77.7252</Value></ExecutionInfo></QueryResultDataSet></ext_UserSchema:Results></msg:Dta></msg:Req></msg:Body></msg:Msg>


Read a file within a specified time

$
0
0
Hello,
I send a request via file.
After a specified time, I must read the answer and delete this file.
I make it this way.
I'm not sure that await, async is right.
The user input must be operable, but I can only continue the process after an answer.
Please look here // ####A
    Because of the await is waited, thus a behavior like synchronously, the user interface remains however operable. Do I see that correctly?
Can you check it out, possibly improve it? Thanks in advance.

Thanks for tips.
Greetings Markus
//Event from a Button.
private async void FileReadOrTimeout(object sender, RoutedEventArgs e)
{
	try
	{
	 // ####A
		var ret = await ReadDataAsync(@"C:\Users\Freitag\Documents\TEST_M_3.xml", 6000);
    	string converted = Encoding.UTF8.GetString(ret, 0, ret.Length);
		converted = RemoveBom(converted);

		MessageBox.Show(converted + "\n \nEnd");
	}
	catch (Exception ex)
	{
		MessageBox.Show(ex.Message);
	}
}

private async Task<byte[]> ReadDataAsync(string pDatei, int pTimeOutMs)
{
	int n = 0;
	int m = (int)Math.Ceiling(pTimeOutMs / 100.0);

	while (!File.Exists(pDatei))
	{
		await Task.Delay(100);
		n++;
		if (n == m)
			throw new FileNotFoundException();

	}

	FileInfo fi = new FileInfo(pDatei);
	Stream streamXML;

	byte[] data = new byte[fi.Length];
	using (var fs = fi.OpenRead())
	{
		int read = await fs.ReadAsync(data, 0, data.Length);
		
		read = data?.Length ?? throw new ArgumentNullException(); // ## Needed?

		streamXML = new MemoryStream(data);

		var gpx = Deserialize<Msg>(streamXML);

		return data;
	}
}
//######################################################

How to pass class object to class library constructor

$
0
0

Have C# main program EXE and multiple C# class library DLLs.
Wish to pass delegate [for callback from DLL to EXE] and common class object to each DLL constructor.
What is the proper C# syntax for that?
EXE has public class, e.g.:

namespace X{  public class y  {    int z;  }}


EXE has instance of that public class.
But how, in DLL source, do I declare that public class?
If I put the same above source in both EXE and DLL, Visual Studio generates syntax error when compiling EXE statement that instantiates the DLL; Visual Studio knows namespace and public class are identical but come from different sources and Visual Studio objects to that.
So how to declare one common public class and make that available to all DLLs when DLLs are instantiated?
Thanks.

Convert time to HH:mm format

$
0
0

Hi Team,

App.Config file key: 

<add key="ProcessTimeInterval" value="14:30"/>  <!--Process Time Interval is in HH:mm in 24 hour time format-->



Class file code:

  var ProcessDateTime = DateTime.ParseExact(ConfigurationValues.ProcessTimeInterval, "HH:mm", null, System.Globalization.DateTimeStyles.None);

I have a config key with excepted time format is "HH:mm".  I am facing issues at var ProcessDateTime  when the config key value is 

Example:
   <add key="ProcessTimeInterval" value="7:30"/>
   <add key="ProcessTimeInterval" value="7:3"/>
   <add key="ProcessTimeInterval" value="7"/>

Need inputs to handle the below scenarios because the below time format is not in "HH:mm".

1) when the config key value is "7:30" format  THEN convert the "7:30"  to  "07:30" in the class file code to make it to "HH:mm" format.

2) when the config key value is "7:3" format  THEN convert the "7:3" to  "07:03" in the class file code to make it to "HH:mm" format.

3) when the config key value is "7" format  THEN  convert the "7" to  "07:00" in the class file code to make it to "HH:mm" format.


Vamshi Janagama

textbox dynamic to datagridview in windows form and c#

$
0
0

How generate textbox dynamically and send values to a row of a datagridview in windows form and c#

What is different between reply email and new email send ?

$
0
0

I doing contact system windows application using c sharp 

using library mail kit

the problem is when some one reply to my email from outlook 2010 to any email I sent it then on my desktop windows application reply id

on debug show null when receiving .

so How any email server like google,Microsoft know that email reached to inbox is new mail or reply for email ?

I already loop for inbox and get emails then show it

How email inbox message reached recognize that received message is new mail message or reply to mail sent before ?


if i test send or reply for any message using outlook it not have any problem

also send receiving and reply work good

problem on my desktop application  receiving reply to email for second time .

I need any way solve my problem on windows application .

receiving emails not recognized on my inbox windows application if reply or new message

using mail kit library .

How to solve problem



c# method error CS1056

$
0
0

Hi,

When i am executing MSBuild I am facing issue "error CS1056: Unexpected character '$' " in the below method.  please provide inputs to use string.Format in the method instead of  $  to solve the issue.

publicstaticstringAdjustHourMinutes(thisstring sender){if(!sender.Contains(":")){return sender.Length==1? $"0{sender}:00": $"{sender}:00";}else{var parts = sender.Split(':');return parts[1].Length==2? $"{Convert.ToInt32(parts[0]):D2}:{parts[1]}":
                    $"{Convert.ToInt32(parts[0]):D2}:0{parts[1]}";}}

Thank you.


Vamshi Janagama

string enum inside a class

$
0
0

hi

i want to define a public read only list of named strings inside a class, something like this;

public enum MyEnum
    {
        string str1 = "str1-value",
        string str2 = "str12-value",
        // ...
    }
so i can read any value after i created an instance of the parent class


Autostart application after copied the file

$
0
0

I am using C# 4.5 and SQL Server 2014. I wrote a console application which takes 3 file names and folder which is defined in theapp.config file and validates the data and imports the data in SQL Server.

I have given FTP portal to the client, they upload the data and informed me then manually I am running my exe file then data is importing. But I want an automatic process like once the client uploads 3 files in folder my console application auto start.

I thought of using FileSystemWatcher, but here problem is that if put file watcher to folder, create file event, I am getting event when the file is created, this will not work because I need the event when 3 files copied successfully.

This is my app.config file

<appSettings><add key="SourceFolder" value="E:\UploadData" /><add key="ArchiveFolder" value="E:\UploadData\Archive" /><add key="LogFile" value="E:\UploadData\LogFile" /><add key="DisbursementFile" value="xxx_DISB.csv" /> <add key="EmployeeFile" value="xxx_EMP.csv" /><add key="AmountFile" value="xxx_AMT.csv" /></appSettings>


Thanks Best Regard Naweez

How to get installed click once version details of other connected systems using IP address

$
0
0
I need to get access of control panel of other systems using IP address so that I can get the click once version details installed in it. I will get the IP address from the IIS Log file. Is there any way to achieve it by using the centralized system and without touching each system ? Or any alternate way to achieve the above mentioned thing ?

splitting the panel in split container dynamically when a new device is connected

$
0
0
I have c# application which runs with USB device. Once an USB device is connected,  it displays a real time reading . There is a provision to connect multiple devices. So when multiple  devices are connected , the split container should split automatically to read the data from the respective devices. Please help me. How to dynamically split and resize the panels.

How to add xml element at specific position in multiple records of xml file

$
0
0

i have large xml file which has multiple tables. i want to add one element at specific position. i tried but in my case element is getting added at last which is not desirable.

my tables are. TickerBroker , Broker, BrokerTab and TickerBrokerDateFormatMap

i have multiple Broker element and when i am adding a new Broker then it is getting added in xml fileafter TickerBrokerDateFormatMap element at the end. i want to add Broker element at the end of last Broker element in xml file.

if no Broker element exist in xml file then my added Broker element should be adding at the end of lastTickerBroker element.

here i am giving my sample xml data which is bit big file.

<?xml version="1.0" standalone="yes"?><TickerBrokerDateMap><TickerBroker><Ticker_Id>ADBE</Ticker_Id><Ticker_Id_auto>ADBE</Ticker_Id_auto></TickerBroker><Broker ID="MV-P1" Ticker_Id="ADBE" BrokerCategory="Cascade" Client=""><Broker_Id>25</Broker_Id><ALLTabsUnderBroker><Broker>MV-P1</Broker><TAB>QIS</TAB><Commnet1 /><Commnet2 /><Broker_Id>25</Broker_Id><ReviewedEarnings>3Q 2019</ReviewedEarnings><Pre-Post>Post</Pre-Post></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>MV-P1</Broker><TAB>BS</TAB><Commnet1 /><Commnet2 /><Broker_Id>25</Broker_Id><ReviewedEarnings>3Q 2019</ReviewedEarnings><Pre-Post>Post</Pre-Post></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>MV-P1</Broker><TAB>METRICS</TAB><Commnet1 /><Commnet2 /><Broker_Id>25</Broker_Id><ReviewedEarnings>3Q 2019</ReviewedEarnings><Pre-Post>Post</Pre-Post></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>MV-P1</Broker><TAB>ESTIMATE</TAB><Commnet1 /><Commnet2 /><Broker_Id>25</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>MV-P1</Broker><TAB>EPS</TAB><Commnet1 /><Commnet2 /><Broker_Id>25</Broker_Id><ReviewedEarnings>3Q 2019</ReviewedEarnings><Pre-Post>Post</Pre-Post></ALLTabsUnderBroker></Broker><Broker ID="UN" Ticker_Id="ADBE" BrokerCategory="Contributing" Client=""><Broker_Id>27</Broker_Id><ALLTabsUnderBroker><Broker>UN</Broker><TAB>ModelCover</TAB><Commnet1 /><Commnet2 /><Broker_Id>27</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>UN</Broker><TAB>Assumptions</TAB><Commnet1 /><Commnet2 /><Broker_Id>27</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>UN</Broker><TAB>Revenue Build</TAB><Commnet1 /><Commnet2 /><Broker_Id>27</Broker_Id><ReviewedEarnings>4Q2019</ReviewedEarnings><Pre-Post>Pre</Pre-Post></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>UN</Broker><TAB>Segment Breakout</TAB><Commnet1 /><Commnet2 /><Broker_Id>27</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>UN</Broker><TAB>Geographic Breakout</TAB><Commnet1 /><Commnet2 /><Broker_Id>27</Broker_Id><ReviewedEarnings>4Q2019</ReviewedEarnings><Pre-Post>Pre</Pre-Post></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>UN</Broker><TAB>Calcs</TAB><Commnet1 /><Commnet2 /><Broker_Id>27</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>UN</Broker><TAB>Debt</TAB><Commnet1 /><Commnet2 /><Broker_Id>27</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>UN</Broker><TAB>GAAP Income Statement</TAB><Commnet1 /><Commnet2 /><Broker_Id>27</Broker_Id><ReviewedEarnings>4Q2019</ReviewedEarnings><Pre-Post>Pre</Pre-Post></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>UN</Broker><TAB>Non-GAAP Income Statement</TAB><Commnet1 /><Commnet2 /><Broker_Id>27</Broker_Id><ReviewedEarnings>4Q2019</ReviewedEarnings><Pre-Post>Pre</Pre-Post></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>UN</Broker><TAB>Balance Sheet</TAB><Commnet1 /><Commnet2 /><Broker_Id>27</Broker_Id><ReviewedEarnings>4Q2019</ReviewedEarnings><Pre-Post>Pre</Pre-Post></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>UN</Broker><TAB>Cash Flow</TAB><Commnet1 /><Commnet2 /><Broker_Id>27</Broker_Id><ReviewedEarnings>4Q2019</ReviewedEarnings><Pre-Post>Pre</Pre-Post></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>UN</Broker><TAB>Disclosures</TAB><Commnet1 /><Commnet2 /><Broker_Id>27</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker></Broker><Broker ID="BW" Ticker_Id="ADBE" BrokerCategory="NonContributing" Client=""><Broker_Id>28</Broker_Id><ALLTabsUnderBroker><Broker>BW</Broker><TAB>Adobe Model_Stifel</TAB><Commnet1 /><Commnet2 /><Broker_Id>28</Broker_Id><ReviewedEarnings>4Q 2019</ReviewedEarnings><Pre-Post>Pre</Pre-Post></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>BW</Broker><TAB>Disclaimer (Read first)</TAB><Commnet1 /><Commnet2 /><Broker_Id>28</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>BW</Broker><TAB>Sources</TAB><Commnet1 /><Commnet2 /><Broker_Id>28</Broker_Id><ReviewedEarnings /></ALLTabsUnderBroker></Broker><Broker ID="PJ-C1" Ticker_Id="ADBE" BrokerCategory="Contributing" Client=""><Broker_Id>29</Broker_Id><ALLTabsUnderBroker><Broker>PJ-C1</Broker><TAB>IS</TAB><Commnet1>Use Custom</Commnet1><Commnet2>Use Custom</Commnet2><Broker_Id>29</Broker_Id><ReviewedEarnings>4Q 2019</ReviewedEarnings><Pre-Post>Pre</Pre-Post></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>PJ-C1</Broker><TAB>BS</TAB><Commnet1>Use Custom</Commnet1><Commnet2>Use Custom</Commnet2><Broker_Id>29</Broker_Id><ReviewedEarnings>4Q 2019</ReviewedEarnings><Pre-Post>Pre</Pre-Post></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>PJ-C1</Broker><TAB>CF</TAB><Commnet1>Use Custom</Commnet1><Commnet2>Use Custom</Commnet2><Broker_Id>29</Broker_Id><ReviewedEarnings>4Q 2019</ReviewedEarnings><Pre-Post>Pre</Pre-Post></ALLTabsUnderBroker><ALLTabsUnderBroker><Broker>PJ-C1</Broker><TAB>Segment Breakout</TAB><Commnet1>Use Custom</Commnet1><Commnet2>Use Custom</Commnet2><Broker_Id>29</Broker_Id><ReviewedEarnings>4Q 2019</ReviewedEarnings><Pre-Post>Pre</Pre-Post></ALLTabsUnderBroker></Broker><BrokerTab name="IS" Broker_Id="0" Ticker_Id="ADBE" Revise_Date="11-19-2019"><BrokerTab_Id>0</BrokerTab_Id><Tab_index>0</Tab_index><save_flag>true</save_flag><isUSed>true</isUSed></BrokerTab><BrokerTab name="Drivers" Broker_Id="0" Ticker_Id="ADBE" Revise_Date="11-19-2019"><BrokerTab_Id>1</BrokerTab_Id><Tab_index>1</Tab_index><save_flag>true</save_flag><isUSed>true</isUSed></BrokerTab><BrokerTab name="BS" Broker_Id="0" Ticker_Id="ADBE" Revise_Date="11-19-2019"><BrokerTab_Id>2</BrokerTab_Id><Tab_index>2</Tab_index><save_flag>true</save_flag><isUSed>true</isUSed></BrokerTab><BrokerTab name="CF" Broker_Id="0" Ticker_Id="ADBE" Revise_Date="11-19-2019"><BrokerTab_Id>3</BrokerTab_Id><Tab_index>3</Tab_index><save_flag>true</save_flag><isUSed>true</isUSed></BrokerTab><TickerBrokerDateFormatMap BrokerTab_Id="154" Broker_Id="29" Ticker_Id="ADBE"><StandardDate>2021 FYE</StandardDate><ColumnCoordinate>AQ</ColumnCoordinate><TickerBrokerDateFormatMaps_Id>168</TickerBrokerDateFormatMaps_Id><BrokerDate StandardDate="2021 FYE" Broker_Id="29" BrokerTab_Id="154"><year>2021 FYE</year><Quater>2021 FYE</Quater></BrokerDate></TickerBrokerDateFormatMap></TickerBrokerDateMap>

here i am giving my c# code to add xml broker element which is adding at the end of file which is not desirable.

            string srclocalfile = @"C:\FILE1.xml";
            string strZipBrokerID = "10";
            string strSourceBrokerID = "12";
            string broker = "UN";

            XDocument xmlDocZip = XDocument.Load(srclocalfile);

            var zipbrokerrow = xmlDocZip.Descendants().Elements("Broker").FirstOrDefault(b => b.Attribute("ID").Value.ToString().Trim().Equals(broker));

            if (zipbrokerrow != null)
            {

                XElement oSubElm = null;
                XElement brokerelement = new XElement("Broker",
                    new XAttribute("ID", broker),
                    new XAttribute("Ticker_Id", strTicker),
                    new XAttribute("BrokerCategory", zipbrokerrow.Attribute("BrokerCategory").Value),
                    new XAttribute("Client", zipbrokerrow.Attribute("Client").Value),
                    new XElement("Broker_Id", strSourceBrokerID));

                foreach (XElement e in zipbrokerrow.Descendants("ALLTabsUnderBroker"))
                {
                    string _broker = e.Element("Broker").Value;
                    string _TAB = e.Element("TAB").Value;
                    string _Commnet1 = e.Element("Commnet1").Value;
                    string _Commnet2 = e.Element("Commnet2").Value;
                    string _Broker_Id = e.Element("Broker_Id").Value;
                    string _ReviewedEarnings = e.Element("ReviewedEarnings").Value;

                    oSubElm = new XElement("ALLTabsUnderBroker",
                        new XElement("Broker", _broker),
                        new XElement("TAB", _TAB),
                        new XElement("Commnet1", _Commnet1),
                        new XElement("Commnet2", _Commnet2),
                        new XElement("Broker_Id", _Broker_Id),
                        new XElement("ReviewedEarnings", _ReviewedEarnings));

                    brokerelement.Add(oSubElm);

                }

                xmlDocZip.Root.Descendants("Broker").FirstOrDefault().Parent.Add(brokerelement);
                xmlDocZip.Save(srclocalfile);
            }

see i am using XDocument class. so please post your sample code using XDocument. thanks



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




How to use async await keywords in any routine

$
0
0

after reading few article i found we can use await if any function is async by default. i am interested to know how to make any routine using asyn and await ?

see this sample code
static async Task DoSomethingAsync() //A Task return type will eventually yield a void
        {
            Console.WriteLine("2. Async task has started...");
            await GetStringAsync(); // we are awaiting the Async Method GetStringAsync
        }

        static async Task GetStringAsync()
        {
            using (var httpClient = new HttpClient())
            {
                Console.WriteLine("3. Awaiting the result of GetStringAsync of Http Client...");
                string result = await httpClient.GetStringAsync(URL); //execution pauses here while awaiting GetStringAsync to complete
                //From this line and below, the execution will resume once the above awaitable is done
                //using await keyword, it will do the magic of unwrapping the Task<string> into string (result variable)
                Console.WriteLine("4. The awaited task has completed. Let's get the content length...");
                Console.WriteLine($"5. The length of http Get for {URL}");
                Console.WriteLine($"6. {result.Length} character");
            }
        }
       
here author can use await because GetStringAsync is async kind of function.

but i want to use await in any function. so how make any routine async await compatible ?

see my below routine where i want to use async & await keyword which allow other to call my sample routine asynchronously.
private List<BrokerData> GetData()
{
    List<BrokerData> Bogeylist = Lidistinctdt.AsEnumerable()
   .Select(row => new BrokerData
   {
       Section = (row.Field<string>(0)).ToString(),
       LineItem = (row.Field<string>(1)).ToString(),
       xFundCode = (row.Field<string>("xFundCode")).ToString()
   }).DistinctBy(a => new { a.Section, a.LineItem }).ToList();
}         
Now tell me how could i use async & await keyword in my above routine?

please show me. thaks

Using Datatable can I find cooresponding DataGridView Row?

$
0
0

I want to update color of row in datagridview based off the row I found in datatable.

foreach (DataRow dr in clsHeartbeat.dtHeartbeat.Rows)
                {
                    DateTime dtNow = DateTime.Now;
                    DateTime dtLastSeen = Convert.ToDateTime(dr["Last Seen"]);
                    double minutes = (dtNow - dtLastSeen).TotalMinutes;
                    if (minutes >= 2)
                    {
                        Console.WriteLine($"  > 2 Minutes  {dr["Machine Name"]}  Last Seen({dr["Last Seen"]}");
                        // Find DataGridView Row and change background color.
                    }
                }


FordIT

What we are achieving by interfaces over Abstract class?

$
0
0

Hello,

Actually we(me and my team members) had a debate about differences between interface and abstract classes in oops.Apart from  multiple inheritance what we are achieving by using interface.

Decoupling is one thing.Can any one explain with a real time example. Theoretical definition is not needed.

In real time scenario what we can achieve only thru interface and abstract class.

Its always confusing.I have read many articles so i know the theoretical background.But in real time when we can use interface/abstract class is still a question mark?


Coding.....................................


Read a file within a specified time

$
0
0
Hello,
I send a request via file.
After a specified time, I must read the answer and delete this file.
I make it this way.
I'm not sure that await, async is right.
The user input must be operable, but I can only continue the process after an answer.
Please look here // ####A
    Because of the await is waited, thus a behavior like synchronously, the user interface remains however operable. Do I see that correctly?
Can you check it out, possibly improve it? Thanks in advance.

Thanks for tips.
Greetings Markus
//Event from a Button.
private async void FileReadOrTimeout(object sender, RoutedEventArgs e)
{
	try
	{
	 // ####A
		var ret = await ReadDataAsync(@"C:\Users\Freitag\Documents\TEST_M_3.xml", 6000);
    	string converted = Encoding.UTF8.GetString(ret, 0, ret.Length);
		converted = RemoveBom(converted);

		MessageBox.Show(converted + "\n \nEnd");
	}
	catch (Exception ex)
	{
		MessageBox.Show(ex.Message);
	}
}

private async Task<byte[]> ReadDataAsync(string pDatei, int pTimeOutMs)
{
	int n = 0;
	int m = (int)Math.Ceiling(pTimeOutMs / 100.0);

	while (!File.Exists(pDatei))
	{
		await Task.Delay(100);
		n++;
		if (n == m)
			throw new FileNotFoundException();

	}

	FileInfo fi = new FileInfo(pDatei);
	Stream streamXML;

	byte[] data = new byte[fi.Length];
	using (var fs = fi.OpenRead())
	{
		int read = await fs.ReadAsync(data, 0, data.Length);
		
		read = data?.Length ?? throw new ArgumentNullException(); // ## Needed?

		streamXML = new MemoryStream(data);

		var gpx = Deserialize<Msg>(streamXML);

		return data;
	}
}
//######################################################

How can I save an XML structure without declaration?

$
0
0
Hello,
I'm using namespace empty, nevertheless the header is written.
Can I get a string via the xmlWriter without re-reading it?
Thanks for tips in advance.
protected void SaveRequestXML<T>(string filePath, T dataObject)
{
	XmlSerializer serializer = new XmlSerializer(typeof(T));

	using (Stream stream = new FileStream(filePath, FileMode.Create))
	{
		using (XmlWriter xmlWriter = XmlWriter.Create(stream))
		{
			serializer.Serialize(xmlWriter, dataObject);
		}
	}
	StreamReader reader = new StreamReader(filePath);
	string contents = reader.ReadToEnd();
	Log.Info("Request Message\n \n" + contents);
}

[XmlType(AnonymousType = true)]
[XmlRoot(Namespace = "", IsNullable = false)]
public class Request
{
	/// <remarks/>
	public uint OrderNum { set; get; }
}
With best regards Markus
Viewing all 31927 articles
Browse latest View live


Latest Images

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