Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, November 1, 2022

Generate Random Numbers in .NET6

 We can generate random number using the following code:

Console.WriteLine("Generate Randoms!");

var objRandom = new Random();

var myValue = objRandom.Next();

Console.WriteLine($"{myValue}");

In the above example, you obtain an int number as result.

You can use the methods NextBytes and NextDouble to obtain the results to obtain random bytes or random doubles values.


In .NET 6 you can use the class RandomNumberGenerator present in the namespace System.Security.Cryptography.


  Console.WriteLine("Generate Randoms in .NET 6!");

   var objRandom = RandomNumberGenerator.Create();

   var objBytes = new byte[sizeof(int)]; // 4 bytes

   objRandom.GetNonZeroBytes(objBytes);

    var myResult = BitConverter.ToInt32(objBytes, 0);

    Console.WriteLine($"{myResult}");

Saturday, December 5, 2020

Thread.Sleep vs. Task.Delay in c#

Thread.Sleep vs. Task.Delay in c# 

The biggest difference between Task.Delay and Thread.Sleep is that Task.Delay is intended to run asynchronously. It does not make sense to use Task.Delay in synchronous code. It is a VERY bad idea to use Thread.Sleep in asynchronous code.


void ThreadSleepSample()

{

            Thread.Sleep(1000);

 }


 async Task TaskDelaySample()

{

         await Task.Delay(1000);

 }

Both Thread.Sleep() and Task.Delay() are used to suspend the execution of a program (thread) for a given timespan. 


Thread.Sleep()

This is the classic way of suspending execution. This method will suspend the current thread until the given amount of time has elapsed. When you call Thread.Sleep in the above way, there is nothing you can do to abort this except waiting until the time elapses or by restarting the application. That’s because Thread.Sleep suspends the thread that's making the call. 


Task.Delay()

Task.Delay acts in a very different way than Thread.Sleep. Basically, Task.Delay will create a task which will complete after a time delay. Task.Delay is not blocking the calling thread so the UI will remain responsive.

Behind the scenes there is a timer ticking until the specified time. Since the timer controls the delay, we can cancel the delay at any time simply by stopping the timer. To cancel,we can modifying the above TaskDelaySample method as follows:

CancellationTokenSource tokenSource = new CancellationTokenSource(); 

async Task TaskDelaySample()
   try
   {
       await Task.Delay(1000, tokenSource.Token);
   }
   catch (TaskCanceledException ex)
   {
       
   }
   catch (Exception ex)
   { 
   
   }
}

In the call to Task.Delay we 've added a cancellation token.  When the task gets cancelled, it will throw a TaskCanceledException Jump .We are catching the exception and suppressing it, because we don't want to show any message about that.

Sunday, November 22, 2020

async await in c#

 Async methods can have the following return types:

Task, for an async method that performs an operation but returns no value.

Task<TResult>, for an async method that returns a value.

void, for an event handler.

Task return type

Async methods that don't contain a return statement or that contain a return statement that doesn't return an operand usually have a return type of Task. Such methods return void if they run synchronously. If you use a Task return type for an async method, a calling method can use an await operator to suspend the caller's completion until the called async method has finished.

Example:

In the following example, the WaitAndApologizeAsync method doesn't contain a return statement, so the method returns a Task object. Returning a Task enables WaitAndApologizeAsync to be awaited. The Task type doesn't include a Result property because it has no return value.

public static async Task DisplayCurrentInfoAsync() { await WaitAndApologizeAsync(); Console.WriteLine($"Today is {DateTime.Now:D}"); Console.WriteLine($"The current time is {DateTime.Now.TimeOfDay:t}"); Console.WriteLine("The current temperature is 76 degrees."); } static async Task WaitAndApologizeAsync() { await Task.Delay(2000); Console.WriteLine("Sorry for the delay...\n"); }


Task<TResult> return type The Task<TResult> return type is used for an async method that contains

a return statement in which the operand is TResult. In the following example, the GetLeisureHoursAsync method contains a

return statement that returns an integer. Therefore, the method

declaration must specify a return type of Task<int>. The FromResult async

method is a placeholder for an operation that returns a DayOfWeek.

public static async Task ShowTodaysInfoAsync() { string message = $"Today is {DateTime.Today:D}\n" + "Today's hours of leisure: " + $"{await GetLeisureHoursAsync()}"; Console.WriteLine(message); } static async Task<int> GetLeisureHoursAsync() { DayOfWeek today = await Task.FromResult(DateTime.Now.DayOfWeek); int leisureHours = today is DayOfWeek.Saturday || today is DayOfWeek.Sunday ? 16 : 5; return leisureHours; }



Thursday, April 23, 2020

Collections in C#

For many applications, you want to create and manage groups of related objects. There are two ways to group objects: by creating arrays of objects, and by creating collections of objects.

Arrays (C# Programming Guide)
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/


Collections   (C# Programming Guide)
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/collections

Simple collection example
// Create a list of strings. var salmons = new List<string>(); salmons.Add("chinook"); salmons.Add("coho"); salmons.Add("pink"); salmons.Add("sockeye");
// Iterate through the list. foreach (var salmon in salmons) { Console.Write(salmon + " "); } // Output: chinook coho pink sockeye


 Sample of Galaxy class that is used by the List<T> is defined in the code.
private static void IterateThroughList()
{
    var theGalaxies = new List<Galaxy>
        {
            new Galaxy() { Name="Tadpole", MegaLightYears=400},
            new Galaxy() { Name="Pinwheel", MegaLightYears=25},
            new Galaxy() { Name="Milky Way", MegaLightYears=0},
            new Galaxy() { Name="Andromeda", MegaLightYears=3}
        };

    foreach (Galaxy theGalaxy in theGalaxies)
    {
        Console.WriteLine(theGalaxy.Name + "  " + theGalaxy.MegaLightYears);
    }

    // Output:
    //  Tadpole  400
    //  Pinwheel  25
    //  Milky Way  0
    //  Andromeda  3
}

public class Galaxy
{
    public string Name { get; set; }
    public int MegaLightYears { get; set; }
}

Thursday, April 18, 2019

String to Array in C#

String to Array in C# 

 public object[] StringToArray(string sInput, string sSeparator, Type type)
        {
            string[] sStringList = sInput.Split(sSeparator.ToCharArray(),
                                              StringSplitOptions.RemoveEmptyEntries);
            object[] list = new object[sStringList.Length];

            for (int i = 0; i < sStringList.Length; i++)
            {
                list[i] = Convert.ChangeType(sStringList[i], type);
            }

            return list;
        }

Tuesday, October 3, 2017

Creating a list of unique random numbers

Creating a list of unique random numbers

public static List<int> GetUniqueRandomNumbers(int iAmountOfRandomNumbers, int iSmallestNumber, int iBiggestNumber)
        {

            //Create a list of numbers from which the routine
            //shall choose the result numbers
            List<int> lstPossibleNumbers = new List<int>();
            for (int i = iSmallestNumber; i <= iBiggestNumber; i++)
            {
           
                    lstPossibleNumbers.Add(i);
            }


            //Create a list, which shall hold the result numbers
            List<int> lstResultList = new List<int>();

            //Initialize a random number generator
            Random objRand = new Random();

            //For-loop which picks each round a unique random number
            for (int i = 0; i < iAmountOfRandomNumbers; i++)
            {
                //Generate random number
                int randomNumber = objRand .Next(1, lstPossibleNumbers.Count) - 1;
                //Use random number as index for the possible number list
                lstResultList.Add(lstPossibleNumbers[randomNumber]);
                //Remove the chosen result number from possible numbers list
                lstPossibleNumbers.RemoveAt(randomNumber);
            }
            return lstResultList;
        }

Monday, May 9, 2016

Standard formats, with their related outputs

Standard formats, with their related outputs

Console.WriteLine("Standard Numeric Format Specifiers");
String s = String.Format("(C) Currency: . . . . . . . . {0:C}\n" +
                                        "(D) Decimal:. . . . . . . . . {0:D}\n" +
                                        "(E) Scientific: . . . . . . . {1:E}\n" +
                                        "(F) Fixed point:. . . . . . . {1:F}\n" +
                                        "(G) General:. . . . . . . . . {0:G}\n" +
                                        " (default):. . . . . . . . {0}    (default = 'G')\n" +
                                        "(N) Number: . . . . . . . . . {0:N}\n" +
                                       "(P) Percent:. . . . . . . . . {1:P}\n" +
                                       "(R) Round-trip: . . . . . . . {1:R}\n" +
                                       "(X) Hexadecimal:. . . . . . . {0:X}\n", - 1234, -1234.565F); Console.WriteLine(s);
Example output (en-us culture):
(C) Currency: . . . . . . . . ($1,234.00)
(D) Decimal:. . . . . . . . . -1234
(E) Scientific: . . . . . . . -1.234565E+003
(F) Fixed point:. . . . . . . -1234.57
(G) General:. . . . . . . . . -1234
    (default):. . . . . . . . -1234 (default = 'G')
(N) Number: . . . . . . . . . -1,234.00
(P) Percent:. . . . . . . . . -123,456.50 %
(R) Round-trip: . . . . . . . -1234.565
(X) Hexadecimal:. . . . . . . FFFFFB2E

https://msdn.microsoft.com/en-us/library/system.string.format%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396




Monday, April 11, 2016

Display text as Subscript and Superscript in C#

Display text as Subscript and Superscript in C#

//Display Subscript O2
MyLabel.Text = "O\x2082        O\xB2"; // O2

//Display Superscript O2
MyLabel.Text = "O\x2082        O\xB2"; // O2

Thursday, December 3, 2015

Thursday, September 27, 2012

Shuffle array in c#

Following is c# code to shuffle an array:

private List<E> ShuffleMyList<E>(List<E> objInputList)



{

List<E> objRandomList = new List<E>();

Random r = new Random();

int randomIndex = 0;

while (objInputList.Count > 0)



{

randomIndex = r.Next(0, objInputList.Count); //Choose a random object in the list

objRandomList.Add(objInputList[randomIndex]); //add it to the new, random list

objInputList.RemoveAt(randomIndex); //remove to avoid duplicates



}

return objRandomList; //return the new random list



}

Wednesday, July 25, 2012

How to pass more than one parameter to c# thread

Here goes sample:-
void MySample()
{
    string sName = "NACL";
    int iAge = 420;
    Thread thread = new Thread(delegate()
    {
        MyTestMethod(sName,iAge);
    });
    thread.Start();
}
void MyTestMethod(string sName ,int iAge)
{
}

Wednesday, March 7, 2012

Updating XML data and binding it to GridView

Following sample shows how data is updated in XML and then XML string is binded to GridView
private void SampleXmlDataUpdateAndBind()

{

try

{



bool bAddNewNode = false;

string sXML = "";



XmlDocument objDocXML = new XmlDocument();

XmlNodeList xnList = null;

XmlNode objNode = null;

int iResourceCount = 0;

string sResourceName = "";

foreach (clsCallSchedular u in mObjSchedular)

{

bAddNewNode =
false;

if (String.IsNullOrEmpty(sXML))

{

bAddNewNode =
true;

}

else

{

objDocXML.LoadXml(
"<xml>" + sXML + "</xml>");

xnList = null;

xnList = objDocXML.SelectNodes("/xml/ResourceShiftInfo[@ResourceID=\"" + u.ResourceID + "\" and @ShiftID = \"" + u.EventTypeID + "\"]");

if (xnList.Count == 0)

{

bAddNewNode =
true;

}

else

{

objNode =
null;

foreach (XmlNode anode in xnList)

{

objNode = anode.SelectSingleNode(
"ResourceCount");

if (objNode != null)

{

iResourceCount =0;

if (anode.SelectSingleNode("ResourceCount").InnerText != null)

iResourceCount = Convert.ToInt32(anode.SelectSingleNode("ResourceCount").InnerText);

anode.SelectSingleNode("ResourceCount").InnerText = (iResourceCount + 1).ToString();

sXML = objDocXML.OuterXml;

sXML = sXML.Replace(
"<xml>","");

sXML = sXML.Replace("</xml>", "");

}

}

}

}

 

if (bAddNewNode)

{

sResourceName = u.ResourceName +
"";

if (String.IsNullOrEmpty(sResourceName))

{

sResourceName =
"Resource not Assigned";

}

sXML = sXML +

"<ResourceShiftInfo ResourceID= \"" + u.ResourceID + "\" ShiftID =\"" + u.EventTypeID + "\">" +

"<ResourceName>" + sResourceName + "</ResourceName>" +

"<Shift>" + u.EventType + "</Shift>" +

"<ResourceCount>" + 1 + "</ResourceCount>" +

"</ResourceShiftInfo>";

}

}

if (!String.IsNullOrEmpty(sXML))

{

sXML = sXML.Replace(
"<xml>", "");

sXML = sXML.Replace("</xml>", "");

sXML = "<xml>" + sXML + "</xml>";

 

DataSet aDataSet = new DataSet();

aDataSet.ReadXml(new StringReader(objDocXML.OuterXml));

grdViewResourceShiftCount.DataSource = aDataSet;

grdViewResourceShiftCount.DataBind();

}

 

}

catch (Exception ex)

{

Response.Write(ex.ToString());

}

}

How to upload app to macOS

1. Open Terminal Press Cmd (⌘) + Space , type Terminal , and hit Enter . 2. Navigate to Your Build Output Directory Your .app file is likel...