Technical Insights: Azure, .NET, Dynamics 365 & EV Charging Architecture

Category: C# Page 3 of 4

C# Code

Simple LINQ Tutorial

I’ve started learning about LINQ because I need to keep up to date with the latest technology out there. I’ve created a simple Business Layer which interact directly with Linq to SQL(DBML). It includes Insert, Update, Delete, Select and paging with LINQ.

Hopefully this tutorial will be useful enough for someone who is going to learn about LINQ. With LINQ we can really simplify/integrate the stored procedure into our Code base but it doesn’t mean LINQ does not support Stored Procedure.

It supports Stored Procedure as well since we might use Stored Procedure for complex calculation. You don’t need to create a table adapter anymore since LINQ does everything the same as table adapter.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqCore.Factories
{
    public class GroupFactory
    {

        /// 
        /// this is used to get all the groups
        /// 
        /// 
        public IQueryable GetAllGroups()
        {
            GroupsDataContext db = new GroupsDataContext();
            var groups = from g in db.Groups
                         select g;

            return groups;
        }

        /// 
        /// this is used to get the group based on the group id
        /// 
        /// 
        /// 
        public Group GetGroup(int groupid)
        {
            GroupsDataContext db = new GroupsDataContext();

            var groups = from g in db.Groups
                         where (g.GroupID == groupid)
                         select g;

            return groups.SingleOrDefault();
        }

        /// 
        /// this is used to insert Or Update which determined by the nullable
        /// integer value of the groupID
        /// 
        /// 
        /// 
        /// 
        public void GroupUpdate(int? groupID, string groupName, bool valid)
        {
            GroupsDataContext db = new GroupsDataContext();
            Group group = new Group();

            if (groupID.HasValue)
            {
               group = db.Groups.Single(p => p.GroupID == groupID.Value);
            }

            group.GroupName = groupName;
            group.valid = valid;

            if (!groupID.HasValue)
            {
                db.Groups.InsertOnSubmit(group);
            }
            db.SubmitChanges();
        }

        /// 
        /// this is used to delete a group based on its ID
        /// 
        /// 
        public void GroupDelete(int groupID)
        {
            GroupsDataContext db = new GroupsDataContext();

            Group group = db.Groups.Single(p => p.GroupID == groupID);
            db.Groups.DeleteOnSubmit(group);
            db.SubmitChanges();
        }

        /// 
        /// this is used to do paging for the returned result
        /// 
        /// 
        /// 
        /// 
        public IQueryable GetAllGroups(int startIndex, int pageSize)
        {
            GroupsDataContext db = new GroupsDataContext();
            var groups = from g in db.Groups
                         select g;

            return groups.Skip(startIndex).Take(pageSize);
        }
    }
}

File Stream/Stream response in AJAX Update Panel

Last few months, I got a problem to place a button to generate a CSV file in the update panel. I was having a problem related with response error. So what i did was to place the button outside the Update Panel. Today, I found a simple solution to place this button inside the AJAX Update panel

1. You need to set the page mode on the page load event

protected void Page_Load(object sender, EventArgs e)
{
    this.Page.Form.Enctype = "multipart/form-data";
}

2. set the update Panel Children as trigger to true


3. set the trigger to your button


   

Filtering Field/Column in DataTable

I was having a problem when I have the same datatable and one datagrid but I want to display different field on the grid for different report and I want to use AutoGenerateColumn = true in the datagrid. Remember, it is about filtering fields not Row(If you want to filter row then you can use dataview).

This is the way of filtering field in datatable

     public static DataTable FilterTableRemoveColumns(tdsReports.ReportSelectDataTable inputTable, List fields)
        {
            //create a new data table
            DataTable newTable = new DataTable();
            newTable.TableName = "newtable";

            //iterate through each column
            foreach (DataColumn col in inputTable.Columns)
            {
                //cross match and filter fields/column
                if (fields.Contains(col.ColumnName))
                {
                    //create a new datacolumn with the same column name and same datatype
                    DataColumn newCol = new DataColumn(col.ColumnName, col.DataType);
                    newTable.Columns.Add(newCol);
                }
            }

            //you ignore the schema because you don't want to throw the exception
            //you merge the data with the new schema
            newTable.Merge(inputTable, true, MissingSchemaAction.Ignore);
            return newTable;
        }

this is how you use it. You pass a string list into the function. The string list contains your desired column

Private Function FilterDataTableColumn(ByVal dtReport As tdsReports.ReportSelectDataTable) As DataTable

        Dim dt As DataTable = New DataTable()
        Try
            Dim list As List(Of String) = New List(Of String)

            If (ReportType = Enums.ReportType.DispatchedOrdersReport) Then
                list.Add("OrderID")
                list.Add("PaymentType")
                list.Add("ProductCode")
                list.Add("Qty")
                list.Add("Price")
                list.Add("Total")
                list.Add("IncGst")

            ElseIf (ReportType = Enums.ReportType.MonthySalesReport) Then
                list.Add("Qty")
                list.Add("ProductCode")
                list.Add("ProductName")

            ElseIf (ReportType = Enums.ReportType.OrderReport) Then
                list.Add("ProductCode")
                list.Add("Qty")
                list.Add("ProductName")

            End If

            dt = objReportService.FilterTableRemoveColumns(dtReport, list)

        Catch ex As Exception

        End Try

        Return dt
    End Function

Error System.NotSupportedException: The given path’s format is not supported

I got this exception when i tried to uploading a file to a web and try to save it as a different name

System.NotSupportedException: The given path’s format is not supported.
at System.Security.Util.StringExpressionSet.CanonicalizePath(String path, Boolean needFullPath)
at

By using code below it will make sure that you will get the real file name without any trailing path, fuCSV is a file upload control and there is a property file name but it doesn’t guarantee that you will get the actual file name. When i tried to debug it, it also give me the file path. The best way of doing this is to use GetFileName method from System.IO.Path

It was:

string filename = fuCSV.PostedFile.FileName;

Fix

string filename = System.IO.Path.GetFileName(fuCSV.PostedFile.FileName);

Record/Row Filter in DataTable

When I have a smaller rows return from my sql stored procedure, I tend to think of not recreating another stored procedure to do filtering or to use optional parameter. My idea is to do filtering from the code base and not recreating/adding the stored procedure.

The idea was to create a generic stored procedure without any filter and apply the filter from the code base. The example given is by applying filter to dataset and then after that add the datatable to dataset and then cast it back again to the datatable.

  public tdsEvent.EventSummaryDataTable TodayEventSummaryFilter(string filter)
        {
            tdsEvent.EventSummaryDataTable table = TodayEventSummaryCache();
            DataRow[] rows = table.Select(filter); //apply the filter first

            if (rows.Length != 0)
            {
                DataSet ds = new DataSet();

                tdsEvent.EventSummaryDataTable eventTable = new tdsEvent.EventSummaryDataTable();
                ds.Tables.Add(eventTable); // add to the filter
                ds.Merge(rows, false, MissingSchemaAction.Ignore);
                // cast it back to the data table
                table = ds.Tables[0] as tdsEvent.EventSummaryDataTable;
            }
            else
            {
                table = new tdsEvent.EventSummaryDataTable();
            }

            return table;
        }

This is the alternative code which doing the same thing as above

Dim table as tdsEvent.EventSummaryDataTable = TodayEventSummaryCache()
//create dataview instance based on datatable

dim dv as DataView = new DataView(table)

//create the filter to select the valid only
dv.RowFilter = "Valid = 1"

//bind to the grid or repeater
rptEvent.Datasource = dv
rptEvent.DataBind()

Get current page name in ASP.NET

In order to get current page name , we need to get it from server variables of “ScriptName” but that’s not enough since it will bring up the whole path. you need to use System.IO in order to get the file name

C# version:

string strCurrentPage = System.IO.Path.GetFileName(Request.ServerVariables ["SCRIPT_NAME"])

VB.NET version:

 Dim strCurrentPage As String = System.IO.Path.GetFileName(Request.ServerVariables("SCRIPT_NAME"))

Set/Find item in Dropdownlist based on its list item value in ASP.NET

this is a very simple trick on how to select an item in pre binding/pre populated dropdown list from database in asp.net, you can use “FindByValue” method from dropdown list to return you a list item then you can use index of to find the index no of that list item and then set the selected index.

ddlSMSRate.SelectedIndex = ddlSMSRate.Items.IndexOf(ddlSMSRate.Items.FindByValue(drCompany.SMSRate));

Override connection string in TableAdapter with web.config

I found this tip is very useful for me in my day to day coding. Sometimes you create a table adapter in dataset in Data layer project, everything works fine but you will start wondering how to make it configurable or how to use the connection string in my web project which is in web.config.

You don’t want to keep changing it and compile it everytime you change the database right?Ok so what you can do is now to open or to add “settings.cs” which is located in your data layer project and then you can paste this piece of code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Linq.Properties
{

    internal sealed partial class Settings
    {
        #region generated stuff

        public Settings()
        {
            // // To add event handlers for saving and changing settings, uncomment the lines below:
            //
            // this.SettingChanging += this.SettingChangingEventHandler;
            //
            // this.SettingsSaving += this.SettingsSavingEventHandler;
            //
        }

        private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e)
        {
            // Add code to handle the SettingChangingEvent event here.
        }

        private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e)
        {
            // Add code to handle the SettingsSaving event here.
        }

        #endregion

        #region ->this override

        public override object this[string propertyName]
        {
            get
            {
                if (propertyName == "scoutsJamboreeConnectionString")
                {
                    return (System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                }
                return base[propertyName];
            }

            set
            {
                base[propertyName] = value;
            }
        }

        #endregion
    }
}

Only one instance of script manager can be added to the page

I’ve got this error when i have ajax toolkit script manager on the master page while at the same time i’ve script manager on the content page. This is the primary cause of this error.

The work around this is to move the script manager which is located on the master page before the content place holder or if you have any user control which uses script manager as well, place before it. It should be placed on the top of anything which uses this control and the most important thing you need to change the script manager in the content page or user control to be script manager proxy

Failed to enable constraints, one or more rows contain values violating non null, unique or foreign-key constraints

I found this error on my project. Well i spent around one hour to figure out this problem. People might think that this is some silly error message.

The error message i got is “Failed to enable constraints, one or more rows contain values violating non null, unique or foreign-key constraints”.

this is caused by my stored procedure which is

SELECT e.eventid,e.event,e.eventdate,i.email,u.username
,u.firstname,u.surname,i.senttime,i.readtime,i.respond
FROM invitefriends i
inner join users u ON i.franchiseeid=u.userid
inner join events e ON i.eventid = e.eventid
WHERE i.franchiseeid is not null
    and ( (@EventID IS NULL) or (e.eventid=@EventID) )
ORDER BY e.eventdate DESC
GO

Since the query is returning multiple rows with the same eventid and the primary key in my datatable is eventid then it caused the error.

There are two workaround to this problem:

  • by using identity from your own table or you can generate it from your query and you need to regenerate your datatable and make sure check the primary key in datatable since it’s not automatically changed for you.
  • You can also relax the constraint by removing the Primary key on the DataTable
  • Page 3 of 4

    Powered by WordPress & Theme by Anders Norén