Saturday, October 29, 2016

Migrating Asp .Net MVC to .Net Core .. Authentication

Hi all, long time no post...

I am learning the new .NET CORE project type now, and want to rewrite my application from the old ASP .NET MVC in the new project template. Reasons for this for me, are really just that my old project is AngularJS 1.0, and I want to try to rebuild using Angular 2.0 with Typescript.

So one stumbling block I hit was the Identity and Authentication database from the old project would not work with the new project. It gave some errors about certain columns missing. What I have had some partial success with is a migration script to update the old DB. This has allowed me to login using a user name and password, and to create a new user. That is the extent of my testing :


Alter Table ASPNETROLES
ADD
 ConcurrencyStamp varchar(255) null,              
 NormalizedName varchar(255) null

 Drop Table AspNetUserTokens

 CREATE TABLE [AspNetUserTokens] (
    [UserId]        NVARCHAR (450) NOT NULL,
    [LoginProvider] NVARCHAR (450) NOT NULL,
    [Name]          NVARCHAR (450) NOT NULL,
    [Value]         NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_AspNetUserTokens]
PRIMARY KEY CLUSTERED ([UserId] ASC, [LoginProvider] ASC, [Name] ASC)
)

Alter Table AspNetUsers
 Add
 ConcurrencyStamp varchar(255) null,
 LockoutEnd DateTime null,
 NormalizedEmail varchar(255) null,
 NormalizedUserName varchar(255) null

Drop Table [AspNetRoleClaims]

CREATE TABLE [AspNetRoleClaims] (
    [Id]         INT            IDENTITY (1, 1) NOT NULL,
    [ClaimType]  NVARCHAR (MAX) NULL,
    [ClaimValue] NVARCHAR (MAX) NULL,
    [RoleId]     NVARCHAR (128) NOT NULL,
    CONSTRAINT [PK_AspNetRoleClaims]
PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_AspNetRoleClaims_AspNetRoles_RoleId]
FOREIGN KEY ([RoleId])
REFERENCES [dbo].[AspNetRoles] ([Id]) ON DELETE CASCADE
)


GO
CREATE NONCLUSTERED INDEX [IX_AspNetRoleClaims_RoleId]
    ON [AspNetRoleClaims]([RoleId] ASC)

Alter Table AspNetUserLogins
   Add  ProviderDisplayName varchar(255) null





You may find this discussion relevant if you have gotten this error :
SqlException: Invalid column name 'NormalizedUserName'. Invalid column name 'ConcurrencyStamp'. Invalid column name 'LockoutEnd'. Invalid column name 'NormalizedEmail'. Invalid column name 'NormalizedUserName'.

Monday, June 02, 2014

ASP. Net site with many Update Panels?

So you have an ASP. Net site with many Ajax Update Panels? The problem : trying to do client side javascript interactions when the page keeps posting back partial. The scripts need to run after the partial page returns, so they are not overridden by the back end.
The solution:
Capture the page upon return with the following:
            var sysApplication = Sys.WebForms.PageRequestManager.getInstance();
            sysApplication.add_initializeRequest(beginRequest);
            sysApplication.add_endRequest(endRequest);
 
            function beginRequest() {
               // document.getElementById("divMessage").style.display = "inline";
              
            }
 
            function endRequest() {
                setWizardProgress();
            }      

Saturday, March 16, 2013

GOOGLE Reader is going away :-(

Well, I am sorry to see Google Reader retire this June. I love it at work. I can read the non-blocked part of the websites I enjoy. And I can take in a lot of information without having to navigate all the sites. For now, I am running my own RSS Reader page at the following URL : http://www.customConfiguration.net/MVC/ Here is a picture of what I have built so far : Anybody who wants to, can register for my page, and I will save his/her favorite feeds list in a SQL Server database I am renting from DiscountASP.Net. I don't anticipate alot of traffic, if any besides myself. That said, the page just persists the list of feeds for the user, not the actual RSS postings.

Thursday, January 31, 2013

Knockout Web API SPA

This is just to explore the new technologies in the Microsoft .Net and Javascript communities. The Web API allows for a lightweight web services tier, while Knockout provides productivity in the browser side. Most of this technique I found in tutorials on www.asp.net and other like sites. I am not feigning originality here.
I am describing the building of a SPA - Single Page Application.
I have built a quick application which performs CRUD operations on the single table using Knockout, Web API, and NHibernate data layer.
Here is the browse data view of the application. There are links to edit, delete and add new items. Also it does paging, because the table is large.

Here is the Edit data view :


How is it built?

A standard MVC project is created in C#, selecting the WEB API project template along the way. A Project Reference is added to the data layer project.


There are 3 main components needed to get a UI running : a Controller class, a Javascript file, and an HTML View file.


The HTML View


References to the various script libraries are added

It is easiest is to build the View and then animate it with code. The View I have above contains edit and list sections which are hidden and shown alternatively, using the JQuery “Hide” and “Show” commands. Just to explain the syntax, here is the relevant part of the Edit section :
And the pertinent code for the List section :
The edit and delete links are accomplished with Knockout Bindings as shown here:

The data paging functionality is also done with Knockout bindings :
The Scripting
Knockout implements the ViewModel part of the MVVM architecture which means we have to code this in the javascript for the html page. Here is my example ViewModel which works in the single page application :
This ViewModel contains objects for the single item and the list of those items.
The Controller code
This is a class which implements the API methods to return data for Knockout to display. The WEB API uses convention to determine which method to execute. Objects are posted intact to the methods, and parameters passed with names are converted to querystring. If passed without name to a GET function, then the value just becomes part of the path "API/THING/1/" for example. Posts and Deletes are translated into methods with those names.

Wednesday, January 16, 2013

Windows 8 RSS Reader Continued

All I added to the template provided by Visual Studio is here : In the HTML document, I did very little except add a ListView, and a WinJS Binding Template for items in the list. I added an Article element for the Blog entry detail pane. The code was added to the existing JS file provided as below :
    // To get the data from the website
                getFeeds(blogPosts, null); 

    // To expose the data to the page.
                var publicMembers =
                    { blogItems: blogPosts };

                WinJS.Namespace.define("DataRSS", publicMembers);

   // To finish setting up the page for view
    args.setPromise(
                WinJS.UI.processAll()
                .done(function () {

   // Add event handlers for the controls
                    var button1 = document.getElementById("bttnMore");
                    button1.addEventListener("click", buttonMoreClick, false);


                   var myList = document.getElementById("myRSSItems");
                   myList.addEventListener("selectionchanged", _selectionChanged);
                }));

Then there is specific acquire and data parsing code for the blogs. First get the data, saving the most recent post date into a variable:
function getFeeds(blogs, after) {

    // To Get more items need to login.
    // // http://www.google.ca/reader/atom/feed/http://forums.corvetteforum.com/external.php?type=RSS2&n=50

    var urlString =
        "http://forums.corvetteforum.com/external.php?type=RSS2";

    var today = new Date();

    today.setDate(today.getDate() - 1);

    var dataPromise = acquireSyndication(urlString, today.toLocaleString());
    
    dataPromise.done(
        function completed(articlesResponse) {

            var lastDate = null;

            lastDate = getPostsAfter(articlesResponse, blogs, after);

            var lastToday = new Date(lastDate);

            // populate a SPAN on the page with the recent date.
            spLastPub.innerText = lastToday.toLocaleString();
        });

}

The RSS feed won't give but the most recent 15 items unless you login to Google
function getPostsAfter(xmlDoc, blogs, afterDate) {

    var articleSyndication = xmlDoc.responseXML;

    if (afterDate != null) {
        var aftDate = new Date(afterDate);
    }

    var posts = articleSyndication.querySelectorAll("item");

    var lastPublished = null;

    for (var postIndex = 0; postIndex < posts.length; postIndex++) {
        // debugger;

        var postTitle = posts[postIndex].querySelector("title").textContent;
        var postLink = posts[postIndex].querySelector("link").textContent;
        var description = posts[postIndex].querySelector("description").textContent;
        var published = posts[postIndex].querySelector("pubDate").textContent;
        var contentEncoded = posts[postIndex].querySelector("encoded").textContent;

        if (postIndex == 0) {
            lastPublished = published;
        }

        var compareDate = new Date(published);

        if (afterDate == null ||
            compareDate > aftDate) {
            blogs.push({
                title: postTitle,
                subtitle: postLink,
                desc: description,
                pubDate: published,
                content: contentEncoded
            });
        }

    }

    return lastPublished;
}
The function for acquiring the feed asynchronously was generously provided in the tutorial, so I used it verbatim :
function acquireSyndication(url, modified) {

    return WinJS.xhr(
        {
            url: url,
            headers: { "If-Modified-Since": modified }
        });

}
The only way to get full coverage of the blog without the login overhead, was to provide a button which would update the list with any new entries since the original opening of the page :
 function buttonMoreClick(arg) {

        getFeeds(blogPosts, spLastPub.innerText);
    }
The Microsoft article is here - http://msdn.microsoft.com/en-us/library/windows/apps/jj663506.aspx

Tuesday, January 15, 2013

My First Windows 8 Store application

I am learning to write code in Windows 8 and wanted an application for reading CorvetteForum.com. While there are other products for reading RSS feeds, I wanted a full application for just this one feed. Here are some screen shots of the user interface :
This app is from the Visual Studio 2012 project template Javascript - Windows Store - Blank Application.
There is a lengthy tutorial about how to write a full blog reader, however I wanted to learn the parts without just pasting a huge code volume and not having time to read it all. I wanted to do alot of my own coding.

Friday, October 19, 2012

ASP .NET MVC 3 RAZOR Dropdownlist Ajax AutoPostback

ASP .NET MVC 3 RAZOR Dropdownlist Ajax AutoPostback
Wow, what a mouthful. I am a bit sick of StackOverflow's policy for today.
So here it is : I want a dropdown list to cause submission of my Ajax form to retrieve some JSON formatted results for use elsewhere in the page.
  @{using (Ajax.BeginForm("SelectState",
           "Census", 
           new AjaxOptions() { 
             HttpMethod = "Post", 
             OnSuccess = "SelectComplete",
             OnFailure = "Fail" })) 
    {
                         
      @Html.DropDownList("ddlState", 
                         (SelectList)ViewData["StateList"],
                         new { onchange = "$('#bSetName').click()" });  
                                                    
      <input id="bSetName" name="bSetName" 
             style="display: block;" type="submit" />
                                                                                                    
    }
   }
 
I hate this, but it works. Any better ideas?

Thursday, March 01, 2012

Back to XmlDomDocument

While we are all moving along to LINQ and other ways to parse XML, I got stuck doing my first pass with the old System.Xml classes. So I needed to solve this problem with parsing when you have many varied namespaces in the data.

Here is my Twitter client code :


WebClient Client = new WebClient();

Stream stream =
Client.OpenRead("http://search.twitter.com/search.atom?q=" +
txtSearchVal.Text);

StreamReader reader = new StreamReader(stream);
XmlDocument doc = new XmlDocument();

string fullResponse = reader.ReadToEnd();
doc.LoadXml(fullResponse);

XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);

mgr.AddNamespace("google", "http://base.google.com/ns/1.0");
mgr.AddNamespace("openSearch", "http://a9.com/-/spec/opensearch/1.1/");
mgr.AddNamespace("atom", "http://www.w3.org/2005/Atom");
mgr.AddNamespace("twitter", "http://api.twitter.com/");
mgr.AddNamespace("georss", "http://www.georss.org/georss");

txtAllXML.Text = doc.OuterXml;

XmlNodeList list = doc.SelectNodes("//atom:entry", mgr);
foreach (XmlNode node in list)
{
listView1.Items.Add(
new ListViewItem() {
Text = node.SelectSingleNode("atom:title", mgr).InnerText })
.SubItems
.AddRange(new string[] {
node.SelectSingleNode("atom:author", mgr).InnerText,
node.SelectSingleNode("atom:content", mgr).InnerText
}
);
}



I had to add the "atom" prefix as no prefix was supplied by the data.

Wednesday, October 12, 2011

RAZOR cascading DropDownList

RAZOR


@Html.DropDownList("ddlElementCode",
TempData["ElementSelects"] as SelectList,
new { onchange = "populateValueTexts(this)" })




// Where the parameter “dropdown” is the first of the two

function populateValueTexts(dropdown) {
var myindex = dropdown.selectedIndex;
var selValue = dropdown.options[myindex].value
var xReq = jQuery.getJSON("ElementTexts",
{ elementCode: selValue },
null)
.complete(receiveValueTexts);
}

function receiveValueTexts(context, textStatus) {
var data = jQuery.parseJSON(context.responseText);

document.getElementById("ddlValueText").options.length = data.length;

jQuery.each(data, function (i, item) {
document.getElementById("ddlValueText").options[i].text = item.Text;
});
}

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult ElementTexts(string elementCode)
{
Data d = new Data();

IList codes =
d.GetElementsByCode(Convert.ToInt32(elementCode));

SelectList items =
new SelectList((from c in codes select c.ELEMENT_VALUE_TXT).Distinct());

return Json(items, JsonRequestBehavior.AllowGet);
}

Tuesday, October 04, 2011

On getting NHibernate to Log the SQL

This feature is very nice. You get to see the SQL that is generated for you.

While logging is not rocket science, I don't want to learn it again on the next project, so I am saving it here. ( I am using Log4Net, but I am sure Enterprise Library or others will work similarly. )

// Configure log4net using the .config file in GLOBAL.ASAX
[assembly: XmlConfigurator(Watch = true)]
protected void Application_BeginRequest(object sender, EventArgs e)
{
XmlConfigurator.Configure();
}

In the Web.config

<log4net debug="true">
<!-- Define some output appenders -->
<appender name="trace" type="log4net.Appender.TraceAppender, log4net">
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d{ABSOLUTE} %-5p %c{1}:%L - %m%n"/>
</layout>
</appender>
<appender name="console" type="log4net.Appender.ConsoleAppender, log4net">
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d{ABSOLUTE} %-5p %c{1}:%L - %m%n"/>
</layout>
</appender>
<appender name="rollingFile" type="log4net.Appender.RollingFileAppender,log4net">
<param name="File" value="hib_log.txt"/>
<param name="AppendToFile" value="true"/>
<param name="maximumFileSize" value="500KB"/>
<param name="RollingStyle" value="Size"/>
<param name="DatePattern" value="yyyy.MM.dd"/>
<param name="StaticLogFileName" value="true"/>
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n"/>
</layout>
</appender>
<!-- Setup the root category, add the appenders and set the default priority -->
<root>
<priority value="DEBUG"/>
<appender-ref ref="rollingFile"/>
</root>
<logger name="NHibernate">
<level value="WARN"/>
</logger>
<logger name="NHibernate.SQL">
<level value="DEBUG"/>
</logger>
</log4net>

Monday, October 03, 2011

How to stream a File in MVC

In Classic ASP or ASP .Net, you can simply change the response type and start writing binary. In MVC you have a Controller method which returns an ActionResult. So this class will properly provide that :


public class BinaryResult : ActionResult
{
private byte[] _fileBinary;
private string _contentType;
private string _fileName;

public BinaryResult(byte[] fileBinary, string contentType, string fileName)
{
_fileBinary = fileBinary;
_contentType = contentType;
_fileName = fileName;
}

public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Clear();
context.HttpContext.Response.ContentType = _contentType;
context.HttpContext.Response.AddHeader("Content-Disposition",
"filename=" + _fileName);

if (_fileBinary != null)
{
context.HttpContext.Response.BinaryWrite(_fileBinary);
}
}
}


In my case the only other challenge was getting the Byte array prepared, because I had to call Convert.FromBase64String, because of the way the data was stored.

Sunday, October 02, 2011

Developing for MVC4 using Razor and JSON

Just playing around this weekend, I wanted some data listings in a page that did not post back in MVC. While not such a big deal in regular ASP, MVC does not have page event handlers in a code-behind file. There is instead a Controller class that you can call in Routing code.



First : the client side javascript handler, this is what is called when the Controller method completes.



using (Ajax.BeginForm("SearchForms", "DBForms", new AjaxOptions() { OnSuccess="jsonFSearchComplete", OnFailure="searchFail" })) Then … function jsonFSearchComplete(context) { $("#DBFormsDiv").html(context.Data); }



Next, the Razor syntax for the page :


@{using (Ajax.BeginForm("JsonSearchRequests",
"Request",
new AjaxOptions() {
OnComplete = "searchComplete",
OnFailure= "searchFail"
}))

// Not including the whole form I created here, just
// labels and textboxes, etc..
}





Then the Controller code for getting the Partial view built and sent down (Got this from StackOverflow postings):


private string RenderRazorViewToString(string viewName)
{
using (var sw = new System.IO.StringWriter())
{
var viewResult =
ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext =
new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}


For a form posting in a page, there must be a Controller method ( :


[AcceptVerbs(HttpVerbs.Post)]
public JsonResult JsonSearchRequests(string AccountNumber,
string Subfirm,
string RegistrationType)
{
Data d = new Data();

if (AccountNumber.Length > 0)
{
ViewData["Requests"] =
d.GetRequestsByAccount(AccountNumber);
}
else if (Subfirm.Length > 0)
{
ViewData["Requests"] =
d.GetDBRequests(Subfirm, RegistrationType)
.Skip(0).Take(100);
}
return Json(new { Data = RenderRazorViewToString("dbRequests") });
// Note the HttbVerb must be stated for Posting a form
}


For a link that a user can click in the page :



[AcceptVerbs(HttpVerbs.Get)]
public JsonResult JsonSelectDbRequest(string Id)
{
Data d = new Data();
ViewData["Generations"] = d.GetGenerations(Id);

return Json(new { Data = RenderRazorViewToString("dbGenerations") },
JsonRequestBehavior.AllowGet);
}

// Note the Http Verb for GET must be stated
}



Code for a Partial View of a list that does Ajax posting :


@Ajax.ActionLink("SELECT",
"JsonSelectDbRequest",
"DocRequest",
new { Id = req.REQUEST_ID },
new AjaxOptions() { OnComplete = "requestSelectComplete" });



EDIT: There is no need to include the old MVCAjax script files.

Saturday, September 10, 2011

Generics For Dummys (re:NHibernate)

I am working on a rogue project that is not being paid for by the company for which I work. This is building something that just helps me do my job, so I have to be very quick. I am using NHibernate, and wanted to get listable data without writing even the smallest functions of my own. So I created this (not for production use):

   public IList GetAll()
        {                     
            return Session.GetSession()
            .CreateCriteria(typeof(T))
            .List();
         }


Because NHibernate uses generics, this function can act as a pass-through, requesting the List method be run, but not much more. My ASP .NET webforms application has to give it the table name of interest.

Again, just a fun way to rapidly get a "table viewer" application running but also providing some code value for potential full life cycle development later.

* Re-reading years later, I think I meant
 GetAll(T) 
as the Type would have to be passed to the function.

Text Template Transformation

My team stores some database logic in an XML file that is part of a CSharp project.
This seems to be working efficiently for the application in runtime and for developers to maintain their SQL statements at design. I don't like it because the file has gotten large and finding things is a manual process.
I am trying to keep up with innovations, so I wrote a transformation that changes that XML file into a class. That way Visual Studio can provide its drop-down navigation controls for finding statements in the file.


<#@ template language="C#" #>
<#@ output extension = "cs" #>
<#@ assembly name="System.Xml.dll" #>
<#@ import namespace = "System.Xml" #>


public class SQLConfig {
<#
XmlDocument doc = new XmlDocument();
doc.Load("C:\\Projects\\MySolution\\MyDataLayer\\ORACLESQL.config");

foreach(XmlNode node in doc.SelectNodes("//add")) {

#>

public const string <#= node.Attributes[0].Value.Replace(".","_").Replace("-","_") #> = @"<#= node.InnerText #>";

<#
}

doc = null;
#>
}



What this does is create a Class file using the above code every time the transform template is changed, or the developer can right-click "Run Custom Tool" on it.

Wednesday, August 24, 2011

Developing for Oracle

Since I have seen a lot of hand-wringing over how to write a connection string to Oracle Express, I want to save a note about this.


(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));User Id=Me;Password=dev;


This is just one of those things, that as a programmer I don't know how to build when I need it. It's a bit of technical stuff that I don't endeavor to deeply understand.

Friday, October 31, 2008

.Net Pie Chart challenge

Note* This is still running at : https://www.customconfiguration.net/ASP/DefaultPie.aspx
My first response to this was very blah. Having seen this stuff done by every product since Access 2.0, made it unexciting to think about. But then my friend added a twist : make the pie chart clickable in a drill-down way. So as easy as it is, to create pie slices from an image of a circle, I was stumped at how to handle a "hotspot", and did not even know there was an ImageMap control available for a .Net webform.

So to hurry up and get something to chart, I created a dataset with one column of numeric values, and a web user control to house the ImageMap control. My control exposes a method called "Draw" and raises an event called "HotSpotClicked" which is declared as follows :


public event ImageMapEventHandler HotSpotClicked;


The graphics to write the circle and pie slices are easy to call in the System.Drawing namespace. Here is Draw method, which calls a separate method to add a percentage column to the DataSet table passed to it. It uses random colors for the pie slices, and selects the colors from the Brushes namespace of System.Drawing using Reflection. It creates a GUID for a temporary file name in which to store the Bitmap. For each pie slice it draws, it saves coordinates for where to put the map hotspot in another column in the dataset. So how to compute X,Y coordinates of the outer edge of a pie slice. My good enough answer is to use a triangle defined by center and two end points of the slice. Those should be easy enough to figure out by conversion from angles and knowing the radius of the bounding circle. But not when you have a large slice, say greater than 100 degrees. For that size and higher the triangle it defines is squeezed thinner and thinner and loses usability as a hot regaion. So in that case I added one more coordinate dividing the "sweep" angle by 2 in my computation.


public void Draw(DataSet ds)
{
// Rectangle of that is the width of the ImageMap control.
Rectangle rect =
new Rectangle(0, 0,
Convert.ToInt32(ImageMap1.Width.Value),
Convert.ToInt32(ImageMap1.Height.Value));

/ Using floats as they are small enough and liked by the Math namespace.
float radius = rect.Width / 2;

string imageName = System.Guid.NewGuid().ToString();
Bitmap bitmap = new Bitmap(rect.Width, rect.Height);

Graphics g = Graphics.FromImage(bitmap);

g.DrawRectangle(Pens.Khaki, rect);
g.FillRectangle(Brushes.LightBlue, rect);

g.DrawEllipse(Pens.Khaki, rect);
g.FillEllipse(Brushes.LightPink, rect);

calcPercents(ds);

// Using reflection to get an array of colors from which to choose.
PropertyInfo[] penInfos = typeof(Pens).GetProperties();
PropertyInfo[] brushInfos = typeof(Brushes).GetProperties();

float startAngle = 0;

// For selecting colors.
Random rand = new System.Random();

// Add a column to the dataset to record color used.
ds.Tables[0].Columns.Add("ChartColor");

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DataRow row = ds.Tables[0].Rows[i];

decimal fSweepAngle = 360 * (Convert.ToDecimal(row[1]) / 100);
float sweepAngle = (float)Math.Truncate(fSweepAngle);

if (i == ds.Tables[0].Rows.Count - 1)
{
sweepAngle += 360 - (startAngle + sweepAngle);
}

int colorIndex = rand.Next(brushInfos.Length - 1);

Brush myBrush = (Brush)brushInfos[colorIndex].GetValue(null, null);

g.DrawPie((Pen)penInfos[colorIndex].GetValue(null, null),
rect,
startAngle,
sweepAngle);

g.FillPie(myBrush,
rect,
startAngle,
sweepAngle);


// Calculate the Hot Spot polygon

// First line from center of the pie out to the edge.
string coords = radius.ToString() + "," +
radius.ToString() + ",";

coords += getCoordinates(startAngle, radius);

if (sweepAngle > 90)
{
//TODO: add more coordinates to get better hotspot coverage.
float intermediateAngle = startAngle + (sweepAngle / 2);

coords += getCoordinates(intermediateAngle, radius);
}

// move the needle up to where we just stopped for the next draw operation.
startAngle += sweepAngle;

coords += getCoordinates(startAngle, radius);

row[2] = coords;
row[3] = ((System.Drawing.SolidBrush)myBrush).Color.Name;
}

setHotSpots(ds);

ImageMap1.ImageUrl = "images/" + imageName + ".bmp";

bitmap.Save(Server.MapPath("images/" + imageName + ".bmp"),
System.Drawing.Imaging.ImageFormat.Bmp);
}



Setting hotspots in the map is easy once the coordinates have been solved :


private void setHotSpots(DataSet ds)
{
ImageMap1.HotSpots.Clear();

foreach (DataRow row in ds.Tables[0].Rows)
{
PolygonHotSpot phs = new PolygonHotSpot();
phs.Coordinates = row[2].ToString();
phs.AlternateText = row[0].ToString() + " "
+ row[1].ToString() + " "
+ row[3].ToString();
phs.PostBackValue = row[0].ToString();
phs.HotSpotMode = HotSpotMode.PostBack;
phs.NavigateUrl = "";
ImageMap1.HotSpots.Add(phs);
}
}


Code for calculating the percentage value of each data point provided in the dataset is very trivial ,but I list it here for future reference :


private void calcPercents(DataSet ds)
{
DataColumn PercentColumn = ds.Tables[0].Columns.Add("DataPercentage");
decimal total = 0;

foreach (DataRow row in ds.Tables[0].Rows)
{
total += Convert.ToDecimal(row[0]);
}

decimal totalPercent = 0;
foreach (DataRow row in ds.Tables[0].Rows)
{

decimal percentage = Convert.ToDecimal(row[0]) / total;
row[1] = Math.Round(percentage * 100, 1);
totalPercent += Convert.ToDecimal(row[1]);
}


if (totalPercent < 100)
{
DataRow lastRow = ds.Tables[0].Rows[ds.Tables[0].Rows.Count - 1];
decimal lastRowPercent = Convert.ToDecimal(lastRow[1]) + (100 - totalPercent);
lastRow[1] = lastRowPercent;
}

// add a column for coordinate set.
DataColumn coordinatesColumn = ds.Tables[0].Columns.Add("MapAreaCoordinates");

ds.AcceptChanges();
}


The real brain candy of the project was how to get the X.Y coordinates for an ImageMap knowing the size of the circle in the drawing and the "Sweep Angle" or angle of the pie slice. After some trial and error and merely remembering where to look from high school math, I wrote some calculations using SIN and COSINE. The fatal trap from hell, is that MATH.SIN does not accept Degrees, it accepts Radians. Intellisense doesn't tell us that. So here are the computations :


float Sin90 = (float)Math.Sin(ToRadian(90));

private string getCoordinates(float startAngle,
float radius)
{
float rise = 0;
float run = radius;
string coords = string.Empty;

rise = (radius * SinOfDegree(startAngle)) / Sin90;
run = (radius * CosOfDegree(startAngle)) / Sin90;

coords += Math.Round(radius + run, 0).ToString() + "," +
Math.Round(radius + rise, 0).ToString() + ",";

return coords;
}

private float SinOfDegree(float Degrees)
{
float radianOfDegree = ToRadian(Degrees);
return (float)Math.Sin(radianOfDegree);
}


private float CosOfDegree(float Degrees)
{
float radianOfDegree = ToRadian(Degrees);
return (float)Math.Cos(radianOfDegree);
}

private static float ToRadian(float Degrees)
{
return Degrees * (float)Math.PI / 180;
}

Sunday, October 26, 2008

Update to Config Builder

It has been requested that my tool create configuration elements that look more like old .Net Framework configuration elements, without the "add, remove, clear" syntax.

The new syntax looks like the following :

<BaseballConfig>
<WorldSeriess>
<add Year="2008">
<Teams>
<add Name="Rays" />
</Teams>
</add>
</WorldSeriess>
</BaseballConfig>


While the older, more traditional format looks like :

<BaseballConfig>
<WorldSeriess>
<WorldSeries Year="2008">
<Teams>
<Team Name="Phillies" />
<Team Name="Rays" />
</Teams>
</WorldSeries>
</WorldSeriess>
</BaseballConfig>


In order to get the xml elements to match the configuration class names, an override can be added to the ElementCollection class as follows :


public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType.BasicMap;
}
}



So to handle this update (or not) I have created the following function for my custom configuration tool:


private static void addConfigurationElementCollectionTypeProperty(CodeTypeDeclaration configElements)
{
CodeTypeReferenceExpression ctre = new CodeTypeReferenceExpression(typeof(ConfigurationElementCollectionType));
CodeTypeReference ctr =
new CodeTypeReference(typeof(ConfigurationElementCollectionType));
CodeMemberProperty propCollectionType = new CodeMemberProperty();
propCollectionType.Name = "CollectionType";
propCollectionType.Attributes = MemberAttributes.Override | MemberAttributes.Public;
propCollectionType.HasSet = false;
propCollectionType.HasGet = true;
propCollectionType.Type = ctr;
propCollectionType.GetStatements.Add(
new CodeMethodReturnStatement(
new CodePropertyReferenceExpression(ctre, "BasicMap")));
configElements.Members.Add(propCollectionType);
}

Thursday, August 21, 2008

CodeDom NHibernate Mapping File Builder

I am currently watching the 'Summer of NHibernate' videos and have found myself wanting a tool for generating the HBM Mapping file. This was a painful place to be looking at a white screen to hand-fill with XML, as if anybody wants to state again all of the columns and data types already typed into a class and a "Create Table" script.


I have code already in all my other tools for getting database schema into my "columns" typed dataset. I ran XSD.EXE over the HBM file which I built by hand while watching 'Summer of NHibernate' to get a Class for easily authoring the XML document. Populating this class and then Serializing it was a nice way to stay in C# for the whole operation.

So here is what I am starting out of the gate with.



public static string GetMappingFile(SqlConnection Connection, string TableName)
{
string fileName = TableName + "hbm.xml";
hibernatemapping newMapping = new hibernatemapping();
newMapping.@namespace = "Acme.DataLayer";
newMapping.@class = new hibernatemappingClass();

hibernatemappingClass newClass = newMapping.@class;
newClass.name = TableName;
newClass.table = TableName;

Columns cols = PopulateColumns(Connection, TableName, CommandType.TableDirect);
newClass.property = new hibernatemappingClassProperty[cols.Column.Count];

int index = 0;

foreach (Columns.ColumnRow cRow in cols.Column)
{
newClass.property[index] = new hibernatemappingClassProperty();
hibernatemappingClassProperty prop = newClass.property[index];
prop.column = cRow.Column_Name;
prop.name = cRow.Column_Name;
prop.type = cRow.Data_Type;

switch (cRow.Data_Type.ToUpper())
{
case "DECIMAL":
break;
case "INT":
prop.type = "Int32";
break;
case "SMALLINT":
prop.type = "Int32";
break;
case "BIT":
prop.type = "Int32";
break;
case "VARCHAR":
prop.type = "string";
break;
default:
prop.type = "string";
break;
}
index++;
}

System.Xml.Serialization.XmlSerializer xmlSerializer =
new System.Xml.Serialization.XmlSerializer(typeof(hibernatemapping));

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);

xmlSerializer.Serialize(sw, newMapping);

return sb.ToString();
}

Saturday, August 09, 2008

CodeDom LWDO Builder

Seeing alot of classes that are "Lightweight Data Objects", simple representations of table entries that can be manipulated locally and then sent to a database, or passed around in application code. So I built a small generator using the CodeDom Namespace. Not intended to compete with MyGenerate or any other tool, just wanted to have this quick one handy.
This is for SQL Server database tables. The main function below :


public static string GetClientClass(SqlConnection Connection, string TableName)
{
CodeTypeReference codeTypeRef;
CodeMemberField memberField;
CodeMemberProperty memberPropPublic;

Columns cols = PopulateColumns(Connection, TableName, CommandType.TableDirect);

CodeNamespace codeNS = new CodeNamespace("ACME.Data");

CodeTypeDeclaration ct = new CodeTypeDeclaration(TableName);
ct.IsClass = true;
codeNS.Types.Add(ct);

CodeExpression markDirty = new CodeMethodInvokeExpression(
new CodeThisReferenceExpression(),
"MarkDirty",
new CodeExpression[] { });

foreach (Columns.ColumnRow cRow in cols.Column)
{
switch (cRow.Data_Type.ToUpper())
{
case "DECIMAL":
codeTypeRef = new CodeTypeReference("System.Decimal");
break;
case "INT":
codeTypeRef = new CodeTypeReference("System.Int32");
break;
case "SMALLINT":
codeTypeRef = new CodeTypeReference("System.Int32");
break;
case "BIT":
codeTypeRef = new CodeTypeReference("System.Int32");
break;
case "VARCHAR":
codeTypeRef = new CodeTypeReference("System.String");
break;
default:
codeTypeRef = new CodeTypeReference("System.String");
break;
}

memberField = new CodeMemberField(
codeTypeRef,
"_" + cRow.Column_Name.ToLower());

memberField.Attributes = MemberAttributes.Private;
ct.Members.Add(memberField);
memberPropPublic = new CodeMemberProperty();
memberPropPublic.Name = MakeFieldName(cRow.Column_Name);
memberPropPublic.Attributes = MemberAttributes.Public;
memberPropPublic.Type = codeTypeRef;
ct.Members.Add(memberPropPublic);

// Get Statement
CodeVariableReferenceExpression cvrexp =
new CodeVariableReferenceExpression("_" + cRow.Column_Name.ToLower());
CodeMethodReturnStatement cmrstmnt = new CodeMethodReturnStatement(cvrexp);
memberPropPublic.GetStatements.Add(cmrstmnt);

// Set Statement
memberPropPublic.SetStatements.Add(
new CodeAssignStatement(cvrexp,
new CodePropertySetValueReferenceExpression()));

memberPropPublic.SetStatements.Add(markDirty);
}

CSharpCodeProvider cSharpProvider = new CSharpCodeProvider();
StringBuilder sb = new StringBuilder();
System.IO.TextWriter tw = new System.IO.StringWriter(sb);
cSharpProvider.GenerateCodeFromNamespace(codeNS,
tw,
new System.CodeDom.Compiler.CodeGeneratorOptions());
return sb.ToString();
}



My code uses a DataSet Class I call "Columns.xsd" just for being able to iterate over something that represents the database table, without making a bunch of DataReader calls.



private static Columns PopulateColumns(SqlConnection Connection,
string TableName,
CommandType TableOrSproc)
{
Columns cols = new Columns();

Connection.Open();
SqlCommand sqlCmd = new SqlCommand();

if(TableOrSproc == CommandType.StoredProcedure)
{
// Get Parameters for Command.
sqlCmd = new SqlCommand(
"Select Parameter_Name as Column_Name,Data_Type, Character_maximum_length" +
" from Information_Schema.Parameters Where Specific_Name = '"
+ TableName +
"'",
Connection);
}
else
{
// Get Columns for the Table.
sqlCmd = new SqlCommand(
"Select Column_Name,Data_Type,Character_maximum_length" +
" from Information_Schema.Columns Where Table_Name = '"
+ TableName +
"'",
Connection);
}

sqlCmd.CommandType = CommandType.Text;

SqlDataReader dr = sqlCmd.ExecuteReader();
while (dr.Read())
{
Columns.ColumnRow row = cols.Column.NewColumnRow();
row.Column_Name = dr["Column_Name"].ToString();
row.Data_Type = dr["Data_Type"].ToString();
row.Character_maximum_length = dr["Character_maximum_length"].ToString();
cols.Column.AddColumnRow(row);
}
dr.Close();
Connection.Close();

return cols;
}




Friday, July 25, 2008

More Visual Studio 2008 App Configuration

Much simpler than generating C# code, the class I use to build the XML elements for the .CONFIG file is shown below. Most of the methods take a WinForms TreeView object or some part of it as an input parameter to be able to traverse its nodes and create the XMLElements with the needed Attributes :


using System;
using System.Text;
using System.Xml;
using System.Windows.Forms;
using System.IO;

namespace CustomConfigBuilder
{
public class ConfigXMLBuilder
{
private void appendChildConfigAttributes(XmlDocument doc, XmlElement element, TreeNode node)
{
foreach (TreeNode childNode in node.Nodes)
if (childNode.Tag.ToString() == Shared._attributeImageIndex.ToString())
{
XmlAttribute attr = doc.CreateAttribute(childNode.Text);
element.Attributes.Append(attr);
}
}

private void appendChildConfigElements(XmlDocument document,
XmlElement parentXmlElement,
TreeNode parentTreeNode)
{
foreach (TreeNode node in parentTreeNode.Nodes)
if (node.Tag.ToString() == Shared._elementImageIndex.ToString())
{
if (!Shared.HasChildAttributes(node))
continue;

XmlElement element = document.CreateElement(node.Text + "s");
parentXmlElement.AppendChild(element);

XmlElement elementAdd = document.CreateElement("Add");
element.AppendChild(elementAdd);

appendChildConfigElements(document, elementAdd, node);
}

appendChildConfigAttributes(document, parentXmlElement, parentTreeNode);
}

///
/// Create the actual XML configuration Text for the Web/App Config file.
///

public string BuildXMLConfigDocument(TreeView tvConfigData, string SaveXmlTo)
{
XmlDocument docConfig = new XmlDocument();
docConfig.LoadXml("<" +
tvConfigData.Nodes[Shared._rootConfigNodeName].Text +
"> tvConfigData.Nodes[Shared._rootConfigNodeName].Text + ">");

appendChildConfigElements(docConfig,
docConfig.DocumentElement,
tvConfigData.Nodes[Shared._rootConfigNodeName]);

try
{
if (SaveXmlTo.Length > 0 && (!SaveXmlTo.ToUpper().Equals("SAVE XML TO:")))
docConfig.Save(SaveXmlTo);
}
catch (System.Exception exception)
{
MessageBox.Show(exception.Message);
}

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
docConfig.Save(sw);

// txtXMLConfigResults.Text = sb.ToString();

return sb.ToString();
}


}
}