Posts

Showing posts with the label C#

Donate

Custom AuthorizeAttribute Class In ASP.NET MVC

Hello All! In ASP.NET MVC projects, you would normally handle Unauthorized users if they access to a page in which they don't have access to. To do this I have a custom class that inherits the AuthorizeAttribute class. This class was take from accepted answers in stackoverflow with some modifications according to my needs for the project. Here's the complete AuthorizeUser class. using System.Configuration; using System.Web.Mvc; namespace AuthenticationDemo { public class AuthorizeUsersAttribute : AuthorizeAttribute { private string redirectUrl = "" ; public string NotifyUrl { get { return redirectUrl; } set { redirectUrl = value ; } } public AuthorizeUsersAttribute() : base () { } public AuthorizeUsersAttribute( string redirectUrl) : base () { this .redirectUrl = redirectUrl; } protected ov

Generate Page Numbers Of Word Document Using OpenXML

Hello, I've been working on OpenXML framework specifically for generating reports on a Word Document. One of the task of the project is to add page numbers to a document with the format of "Page 1 of 72". After doing some researches on stackoverflow and google, I found a few links with functions on how to add page numbers but not in the format as specified for my requirement. In case you need to add page numbers to a word document specifically in the footer area, see function below. private Footer GeneratePageNumbers ( string FooterText) { var element = new Footer ( new Paragraph ( new ParagraphProperties ( new ParagraphStyleId () { Val = "Footer" }, new Justification () { Val = JustificationValues.Center }), new Run ( new Text () { Text = FooterText, Space = SpaceProcessingModeValues.Preserve }), new Run ( new SimpleField () { Instruction = "Page" }), new Run ( new Text () { Te

Return Multiple Values From C# Asynchronous Function

Good evening fellow developers! I have a simple application that queries the database and returns list of employees and list of their dependents. Since I've just started learning async programming, I wonder if I could return multiple values for an asynchronous function or method. The initial solution that I have is to create a view model class that has two properties specifically list of employees and list of dependents. And this view model class will be the return type of the function. After reading through the docs, it's possible to return multiple values using System.ValueTuple namespace. If the target framework of the project is 4.6.2 and below, you need to add the System.ValueTuple NuGet package using NuGet Console Manager or add the package using Manage NuGet Package tool. For now, lets install the package using console manager. Install-Package "System.ValueTuple" Next is to modify the existing method to return multiple values using System.ValueTuple. pr

How Get Total Number Of Rows From SQLDataReader Object Using C#

Good Evening Gents! In the office, we were using SQLDataReader class to read from SQL Server database in a straight-forward manner. The SQLDataReader has several properties that are commonly used such as HasRows and FieldCount. However in one of my task, I want to retrieve the total number of rows returned from the SQLDataReader object and there's no such property that support this. Doing some search led me to this link How to get number of rows using SqlDataReader in C# . The one that worked for me was the answer using select @@ROWCOUNT query. I modified his answer by writing my own method that will accept a List of SQLParameters given that the original query requires parameters. private static void GetTotalRowCount( string query, string connectionString, ref int totalRows, List<SqlParameter> sqlParameters) { try { using ( var sqlCon = new SqlConnection(connectionString)) { sqlCon.Open(); var cmd = sqlCon.CreateCommand(); cmd.CommandText = q

Export SQL Server Varbinary Or Blob To Disk Using C#

Image
Good evening Gents! I was given a task to export 100+GB of files from an MSSQL DB of which these files are saved in a table using Varbinary/Blob column. I've made some spike applications using BCP and .NET CLR but to no avail all the spike applications don't work since I don't have full permission to the database. The only solution that work for me was using the OLE Automation Procedures. So in order to export files from Blob, I'll present the steps below using AdventureWorks2012 database. 1. Enable OLE Automation Procedures by running script below. Use AdventureWorks2012 Go EXEC sp_configure 'show advanced options' , 1; GO RECONFIGURE; GO sp_configure 'Ole Automation Procedures' , 1; GO RECONFIGURE; GO 2. Run the stored procedure script below. The script will return the LargePhoto of a specific product. USE AdventureWorks2012 GO IF OBJECT_ID( 'SP_AdventureWorks_Export_Blob' , 'P' ) IS NOT NULL DROP PROCEDURE S

How To Perform Bulk Update Using SqlBulkCopy, C#.NET And SQL Server

Image
Good afternoon! Before I go into details, this post is solely based on the solution provided in this link Bulk Update In C# . The purpose of this tutorial is to provide step by step approach on how bulk update can be achieved using SqlBulkCopy, C#.NET And SQL Server. First is to create a simple table in your database that holds some fictitious records. USE [testdatabase] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[Person]( [ID] [int] NOT NULL , [Name] [varchar](50) NULL , [Address] [varchar](50) NULL ) ON [ PRIMARY ] GO Database table with temp records Next is to create a console app that will perform the bulk update of records. The key to solving performance issues in updating records is to use a temporary table approach. class Program { static void Main( string [] args) { var listPerson = new List<Person> { new Person() {Id = 1001, Name = "James A." , Address = "US" }, new Person(

How To Remove Duplicate Items In A List<T> Using IEqualityComparer<T>

Image
Good evening. Here's a simple demo on how to remove duplicate items in a List object using IEqualityComparer given that the generic list's type is complex. First we setup a simple model Employee class with Age, Name and Address properties. class Employee { public int Age { get ; set ; } public string Name { get ; set ; } public string Address { get ; set ; } } Next is to create a comparer class that implements IEqualityComparer interface. class EmployeeComparer : IEqualityComparer<Employee> { public bool Equals(Employee emp1, Employee emp2) { if (Object.ReferenceEquals(emp1, emp2)) return true ; if (Object.ReferenceEquals(emp1, null ) || Object.ReferenceEquals(emp2, null )) return false ; return (emp1.Age == emp2.Age) && (emp1.Name == emp2.Name) && (emp1.Address == emp2.Address); } public int GetHashCode(Employee obj) {

Microsoft Access - The 'Microsoft.ACE.OLEDB.12.0' Provider Is Not Registered On The Local Machine

Image
Hello, I was working on a project that reads an MS Access database using C# using OLEDB Provider. I already have downloaded and installed the Microsoft Access Database Engine 2010 Redistributable (AccessDatabaseEngine_X64.exe) from Microsoft since my OS is Windows 10 64bit. Upon running the project, I encountered the error as mentioned in the title of this post. I've tried several solutions and it didn't work for me. The only fix that worked is to change the Platform target of the project to "Any CPU" and unchecked the Prefer 32-bit checkbox . Cheers! :)

Read Files From Google Photos Using Google Photos API, REST And C#.NET

Image
Related Tutorials On Google Photos API Read Files From Google Photos Using Google Photos API, REST and VB.NET Upload Photos, Images Or Files To Google Photos Using Google Photos API, Rest and C#.NET I've been working on a project last year to read and download images from Google Photos using the recent Google Photos API and C# as the programming language. During research, there was an existing .NET API called Picasa Web Albums API but has been deprecated and the docs suggested to migrate applications to the recent one. The examples in the current documentation provided are PHP, Java and REST API in which the example is written in Node.js. Since the requirement is to write a scheduled task or windows service in C#.NET, I decided to refresh my skills on sending requests to REST services using WebClient or HTTPWebRequest classes. To access media items, read or even download files using Google Photos API, you need to enable the Google Photos Library API, create a Google Proj

How To Calculate Due Days Excluding Weekends In C#.NET

Here's a function that will calculate the number of days excluding weekends. The parameters passed are the priority which contains number of days and the current date. Sample priorities are 'High[1 day]', 'Average [2 days]' and 'Low [5 days]'. The function then uses Regex to extract the whole numbers from the priority string to be used for incrementing the number of days. public DateTime RecalculateDueDate( string priority, DateTime Today) { int days; int count; DateTime dueDate; count = 0; dueDate = Today; days = int .Parse(Regex.Replace(priority, "[^0-9]" , "" )); while (count < days) { dueDate = dueDate.AddDays(1); if (( int )dueDate.DayOfWeek != 0 && ( int )dueDate.DayOfWeek != 6) count++; } return dueDate; } Source Code: How To Calculate Due Days Excluding Weekends In C#.NET

Return Last Inserted ID In MongoDB Using C# In ASP.NET MVC

Good evening developers! The current project that I'm working with retrieves records from SQL Server and MongoDB. And it's my first time to use the NoSQL db in a real world project. I've attended training before but using the NoSQL db was not approved by the customer. Going back to the topic of this post, I was wondering if there's a similar approach in MongoDB to return the last inserted _id just like in C#'s code like this: int id = Convert.ToInt32(cmd.ExecuteScalar()); After experimenting and debugging, I can get the newly inserted record's id right after the insert statement by retrieving the id from the newly inserted BSONDocument itself. public void Add (UserActivity userActivity) { var activityDocument = new BsonDocument { { "ActivityUserName" , userActivity.ActivityUserName }, { "ActivityName" , userActivity.ActivityName }, { "ActivityModule" , userActivity.ActivityModule }, { "ActivityDate" , user

Create A NuGet Package Using Visual Studio 2017

Image
Hello all! You may have noticed that the trend in adding components or dll's to a project is through a technology called NuGet Package and with that I'll demonstrate on how to create a simple C# Library NuGet package using Visual Studio 2017. Below are the steps to follow. 1. First is to create a C# class library project called StringLib and add a class with a single method to convert the first letter of a string to uppercase. public class ToUpperCase { /// <summary> /// Change first letter to uppercase /// </summary> public string ToUpperFirstLetter ( string s) { if ( string .IsNullOrEmpty(s)) { return string .Empty; } char [] a = s.ToCharArray(); a[ 0 ] = char .ToUpper(a[ 0 ]); return new string (a); } } 2. Build the project to generate a .dll file. 3. Copy the .dll or any files to be included

Check Email Exists In Active Directory Using C#

Good afternoon gents! Here's a method on checking if an email exists in an Active Directory Domain given the format of an email FirstName.LastName@yourcompanyname.com . If the format of your company email is different from the one presented, just change the logic of the code to extract the family name. /* Email Format: Gregory.Esguerra@abcbusiness.com */ private bool CheckIfEmailExistsInDomain ( string email) { string searchName = string .Empty; searchName = email.Substring(email.IndexOf( '.' ) + 1 , (email.IndexOf( '@' )- 1 ) - email.IndexOf( '.' )); using ( var context = new PrincipalContext(ContextType.Domain, "abcbusiness.corp" )) { using ( var searcher = new PrincipalSearcher( new UserPrincipal(context))) { PrincipalSearchResult<Principal> allPrincipal = searcher.FindAll(); List<Principal> principalObjects = allPrincipal.Where(t => t.Name.Contains(ToUpperFirstLetter(searchName))).ToList(); if

Match Item That Exists In A List Using Regular Expression And LINQ

Hi! Using Any() in LINQ, we can match/find an item that exists in a List<T> or IEnumerable using Regular Expressions. if (Products.Any(t => Regex.IsMatch(t, ProductsFromFrance.FrenchProdPattern)) { //true statement here.. } Where Products is the List object and ProductsFromFrance.FrenchProdPattern is the Regular Expression pattern.

Match Network Path In A String Using Regular Expression

Hello, While working on a project, I was confronted with an issue on how to match or extract a network path. Normally, you can use string functions or built-in .NET code to check the validity of a path, but since I'm also refreshing my skills in Regular Expression. I prefer the latter as the solution. So the pattern to match the server path is presented below: ((\\\\)?((?<Folder>[a-zA-Z0-9- _]+)(\\.*[a-zA-Z0-9-_ \\])(?="))) And to declare that pattern in your C# code, you have to escape the back slash characters. string ServerPath = "((\\\\\\\\)?((?<Folder>[a-zA-Z0-9- _]+)(\\\\.*[a-zA-Z0-9-_ \\\\])(?=\")))" ; The input strings tested are as follows. Const ImagesPath As String = "\\ImagesServer\Logo Files\InetPub\TempProjects\" Const docsPath As String = "\\docsPathServer15\Health\Physicians\" Const vsPath As String = "\\vsServer909\vs2017\Projects" string manual = "\\manualServer\CompanyRules\EmployeeFiles\Cebu&

Refactor An MVVM ViewModel Class

Good afternoon! I recently asked the forums on how to refactor a ViewModel class given that in the future additional features or functionalities will be added, so the ViewModel class becomes bloated and hard to trace. All the commands, database operations and properties are declared in this class. So, the option I was thinking was segregation but I also need inputs from other experienced developers in the community. Sample ViewModel Class namespace MVVM.MainApplication.ViewModel { public class EmployeeViewModel : ViewModelBase { private ICommand _saveCommand; private ICommand _resetCommand; private ICommand _editCommand; private ICommand _deleteCommand; private Employee _employeeEntity; private EmployeeRepository _repository; private EmployeeModel _employeeModel; public EmployeeModel EmployeeModel { get { return _employeeModel; }

WPF CRUD With DataGrid, Entity Framework And C#.NET

Image
Good evening! Here's a simple WPF CRUD(Create/Update/Delete) application using DataGrid and Entity Framework. This doesn't involve the MVVM pattern and input validation. Maybe if I have time, in the future I'll post an MVVM equivalent post ( Update: I already have additional examples using RepoDB ORM and MVVM pattern in both C# and VB.NET at the end of this article ). So to proceed, execute the SQL script below and make sure to replace the database name with an existing one. USE [your_database] GO /****** Object: Table [dbo].[Students] Script Date: 3/31/2018 11:24:23 PM ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[Students]( [ID] [ int ] IDENTITY ( 1 , 1 ) NOT NULL , [Name] [ varchar ]( 50 ) NULL , [Age] [ int ] NULL , [Address] [ varchar ]( 50 ) NULL , [Contact] [ varchar ]( 50 ) NULL , CONSTRAINT [PK_Students] PRIMARY KEY CLUSTERED ( [ID] ASC ) WITH (PAD_INDEX = OFF , STATISTICS_N

Donate