Category

C#

Error log in catch block write Exception Detail in C#

By | ASP.NET, C#, MVC

This method helps you to trace or keeping log of your exception in a text file with a formatted manner. Just use as extension method and pass object of you Catch Exception obj.

 

public class ErrorLog
{
 public static void WriteError(Exception ex)
 {
  string err = "";
  try
  {

   string path = System.AppDomain.CurrentDomain.BaseDirectory + "/ErrorLog/" + 
   DateTime.Today.ToString("dd-MM-yy") + ".txt";

   if (!File.Exists(path))
   {
    File.Create(path).Close();
   }
  using (StreamWriter w = File.AppendText(path))
  {
    w.WriteLine("\r\nLog Entry : ");
    w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
    err = "Error Log at : " + ex.ToString() + "___. Error Message:" + ex.StackTrace;
    w.WriteLine(err);
    w.WriteLine("________________________________________________");
    w.Flush();
    w.Close();
  }
 }
    catch (Exception ex1)
    {
       return;
     }
  }
}


And you can use this extension method anywhere in catch block with class name.


try
{
  //your Code
}
catch(Exception ex)
{
  ErrorLog.WriteError(ex);
}

 

Highlight the tab according to action and controller in asp.net MVC

By | ASP.NET, C#, MVC

In Menu bar, while navigating, “Active” class will add in menu item according to your controller and action, that is fixed by you in your html code.

Just use this extension method in your menu item class.

 

public static string IsActive(this HtmlHelper html,
                                      string control,
                                      string action)
        {
            var routeData = html.ViewContext.RouteData;

            var routeAction = (string)routeData.Values["action"];
            var routeControl = (string)routeData.Values["controller"];

            // both must match
            var returnActive = control == routeControl &&
                               action == routeAction;

            return returnActive ? "active" : ""; //Here you can change class name according to your theme like "active" or anything
        }

Now you have to use this method as HTML helper in your razor page.



<li class="@Html.IsActive("About","Index")">
 <a href="@Url.Action("Index","About")">About Us</a>
</li>

                       
                        
 
<li class="@Html.IsActive("Contact","Index")">
 <a href="@Url.Action("Index","Contact")">Contact Us</a>
 </li>


Now if your controller and action will “About” and “Index” then “active” named class will add in you li class.

Sending Mail To Admin On USB Insertion or Removal In C#

By | C#

Here is the c# console code to create a event watcher to monitor, if any usb attached or detached from PC.

Simple just create a console application in visual studio and install a package from nuget to import namespace System.Management.

Install-Package System.Management -Version 4.5.0

And Code is Bellow :




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;

namespace USB
{
    class Program
    {
        public enum EventType
        {
            Inserted = 2,
            Removed = 3
        }

        static void Main(string[] args)
        {
            ManagementEventWatcher watcher = new ManagementEventWatcher();
            WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 or EventType = 3");

            watcher.EventArrived += (s, e) =>
            {
                string driveName = e.NewEvent.Properties["DriveName"].Value.ToString();
                EventType eventType = (EventType)(Convert.ToInt16(e.NewEvent.Properties["EventType"].Value));

                string eventName = Enum.GetName(typeof(EventType), eventType);

                Console.WriteLine("{0}: {1} {2}", DateTime.Now, driveName, eventName);
                Console.WriteLine("Mail Sending...to admin"); //You can write your email code here
            };

            watcher.Query = query;
            watcher.Start();

            Console.ReadKey();
        }
    }
}




you can write your email sending code after Console.WriteLine(“{0}: {1} {2}”, DateTime.Now, driveName, eventName);

How to Create a byte array from stream in C#?

By | C#
Moslty we want to save images or any file in database as byte, so we can convert any stream in byte array in c#, here below a method to convert.

 public static byte[] StreamToBytes(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

Convert List or any type of object to XML string data in C#

By | C#, MVC
Here is a method to conver any type of object to string xml, this method will take parameters of T type and will return XML string.

public static string ConvertToXML<T>(T obj)
        {
            try
            {

                using (StringWriter stringWriter = new StringWriter(new StringBuilder()))
                {
                    System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                    xmlSerializer.Serialize(stringWriter, obj);
                    XDocument xDoc = XDocument.Parse(stringWriter.ToString());
                    xDoc.Declaration = null;
                    return xDoc.ToString();
                }

            }
            catch (Exception ex)
            {
                return ex;
            }
        }

Best way to convert array of object into array of string in C#

By | C# | No Comments

I have an array of object in c#

object arrayofobject = new object[] {"Name", "Password", "Address"}

now i want to convert this array of object into array of string so i’ll use Array.CovertAll() method as string array.

string[] arr = Array.ConvertAll((object[])arrayofobject, Convert.ToString);

Full Code Here

object arrayofobject = new object[] {"Name", "Password", "Address"}
string[] arrayofstring = Array.ConvertAll((object[])arrayofobject, Convert.ToString);

now you can get arrayofstring.

Get Enum Description According to language culture or resource file in C#

By | ASP.NET, C#, MVC | No Comments

if i have an enum and i want to show the description on view or in dropdown than, than we can change the description according to resource language file.

Full example below:

We have an Enum First

public enum MeetingType
        {
            [Description("Booked Meeting")]
            APPOINTMENTBOOKED = 1,
            [Description("Prescription Bookings")]
            MEETINGWITHPRESCRIPTIONRENEWAL = 2,
            [Description("Prescription Renewal")]
            PRESCRIPTIONRENEWAL = 3
        }

And then we will add these description strings in our resource files.

After Adding strings or key in resource file we have created a extension method for further use.

First import

using System.Resources;

public static string GetDisplayName(this Enum e)
        {
            var rm = new ResourceManager(typeof(DoctorPanel.Resources.Resource));
            var resourceDisplayName = rm.GetString(ExtensionMethod.EnumDescription(e).Replace(" ",string.Empty));

            return string.IsNullOrWhiteSpace(resourceDisplayName) ? string.Format("[[{0}]]", e) : resourceDisplayName;
        }

And use this method where you want to get enum description according to resource or language wise.

var GetString=YourEnum.GetDisplayName();

we used white space remover because, Resource file keys accept without spaces or you can write your enum description without spaces.

 

Get disease ICD code in C# using ICD10 API

By | ASP.NET, C#, MVC | No Comments
public string GetICDCode(string ICDCode)
        {
            DiagnosisModel model = new DiagnosisModel();
            String postURL = string.Format("http://icd10api.com/?code={0}&desc=short&r=json", ICDCode);
            WebRequest request = WebRequest.Create(postURL);
            request.Method = "GET";
            request.ContentType = "application/json; charset=utf-8";

            var response = (HttpWebResponse)request.GetResponse();
            string jsonText;
            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                jsonText = sr.ReadToEnd();
            }
            return jsonText;

        }

We created a method for getting icd code.

Create Model for icd code vlaues and data

public class ICDCode
        {
            public string Name { get; set; }
            public string[] Inclusions { get; set; }
            public string[] ExcludesOne { get; set; }
            public string[] ExcludesTwo { get; set; }
            public string Description { get; set; }
            public string Valid { get; set; }
            public string Type { get; set; }
            public string Response { get; set; }
        }

Just pass icd code in above method and it will give you result as json,

deserilize it with you model class and store in your model properties.

ICDCode model = new ICDCode();

var jsonResultICDCode = GetICDCode(yourICDcode);

model.ICDResponse = new JavaScriptSerializer().Deserialize<ICDCode>(jsonResultICDCode);

If your ICD code is valid than, it will return
model.ICDResponse.Valid=1 and model.ICDResponse.Response == “True”

Now you can get all information about icd code in your model properties.

Select multiple count in one result set in sql and C#.

By | C#, Insight Database, ORM, SQL | No Comments

Here, you can select multiple counts from different – 2 tables in one result set. with multiple coulumn names.

i used insight databse ORM in C#.

First i created a Model in c# where result set will bind with Columns name and model property name.

public class AnalyticsModel
    {
        public int totalAppointments { get; set; }
        public int totalPrescriptionRenewal { get; set; }
        public int totalNumberOfDropInsPerDay { get; set; }
        public int totalRequest { get; set; }
    }

And Now My Store Procedure in SQL

CREATE PROC [dbo].[AnalyticsTotal]
AS
BEGIN 
	SET NOCOUNT ON;

	SELECT
	(SELECT COUNT(*) FROM Appointment WHERE MeetingType IN(1,3) AND Status=1) AS [totalAppointments],

	(SELECT COUNT(*) FROM Appointment WHERE MeetingType=2 AND Status=1) AS [totalPrescriptionRenewal],

	(SELECT COUNT(*) FROM Appointment WHERE IsDropIn=1 AND Status=1) AS [totalNumberOfDropInsPerDay],

	(SELECT COUNT(*) FROM Appointment WHERE MeetingType IN(1,2,3) AND Status=1) AS [totalRequest]

END

And in last i got my result set in my DataClass.

var Result = DB.QuerySql<AnalyticsModel>(@"Exec [dbo].[AnalyticsTotal]").FirstOrDefault();

Here QuerySql is the method of Insight Database ORM.

You can Install in your visual studio from nuget package manager.

Install-Package Insight.Database -Version 6.2.8