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

Tuesday, November 12, 2013

QB Rating Calculator Web Service


QB Rating Web Service is a WCF service that calculates a QB's NFL and NCAA ratings.  It supports REST, SOAP, XML and JSON. It is a Visual Studio 2012 project written in C# and is another in my series of QB Ratings app samples - InfoPath 2013 QB Rating, Excel 2013 QB Rating and SharePoint 2013 QB Rating (App & App Part).
Download Web Service Source (22K) or ASP.NET QB Rating Sample (8.8M)
View CodePlex Project or MSDN Sample

Features

  • Web Service (WCF)
  • REST and SOAP
  • XML and JSON
  • Calculates both NFL and NCAA ratings
  • Shows detailed calculation formula & steps
  • Source code included

Screenshots

The web service interface in the Visual Studio Object Browser:

Sample XML response from the service

The GetRating service call in the WCF Test Client:

Quick Usage Example

In order to use this service via SOAP, you'll need to create a client and use it to call the service.  Additionally, you can use the REST configuration with a ServiceContract and UriTemplate similar to http://localhost:62370/QBRatingService.svc/calc?formula=NFL&c=10&a=16&y=212&t=3&i=1&fmt=XML. You can quickly create a configuration file and simple client class using the svcutil.exe tool from the command line with the following syntax:

svcutil.exe http://localhost:62370/QBRatingService.svc?wsdl
This will generate a configuration file and a code file that contains the client class. Add the two files to your client application and use the generated client class to call the Service. For example:
C#
class Test
{
    static void Main()
    {
        QBRatingServiceClient client = new QBRatingServiceClient();

        // Use the 'client' variable to call operations on the service.

        // Always close the client.
        client.Close();
    }
}
Visual Basic
Class Test
    Shared Sub Main()
        Dim client As QBRatingServiceClient = New QBRatingServiceClient()
        ' Use the 'client' variable to call operations on the service.

        ' Always close the client.
        client.Close()
    End Sub
End Class

Detailed ASP.NET Usage Example

In addition to the quick usage in the previous section, I developed a working ASP.NET QB Rating Calculator that uses this web service to perform the actual calculations. The complete Visual Studio 2012 project is available on CodePlex and MSDN.


Sunday, October 20, 2013

Silverlight 5 - QB Passer Rating App


Silverlight QB Rating is a Silverlight 5 XAP application package (and source code) that calculates a QB's NFL and NCAA passing efficiency ratings. It is a Visual Studio 2012 project written in C# and is another in my series of QB Ratings app samples - InfoPath 2013 QB Rating, Excel 2013 QB Rating and SharePoint 2013 QB Rating (App & App Part).
Download XAP (152K) or Source (31K)
View Live Demo, CodePlex Project or MSDN Sample

Features

  • Silverlight 5 (C# in Visual Studio 2012)
  • Calculates both NFL and NCAA ratings
  • Shows detailed calculation formula & steps
  • Deployable XAP & source code included

Screenshots

The Silverlight 5 XAP hosted in Internet Explorer:    IE Hosted XAP
The XAML design surface in Visual Studio 2012:Design
The C# source view in Visual Studio 2012:Source Code

Example Usage

The following is a quick and simple example of embedding the XAP as an object in a web page.  Since this is Silverlight 5-based, you will need to ensure you have the correct version of Silverlight installed.
<div id="silverlightControlHost">
    <object data="data:application/x-silverlight-2," 
       type="application/x-silverlight-2" width="100%" height="100%">
        <param name="source" value="QBRatingSL.xap" />
        <param name="onError" value="onSilverlightError" />
        <param name="background" value="white" />
        <param name="minRuntimeVersion" value="5.0.61118.0" />
        <param name="autoUpgrade" value="true" />
        <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=5.0.61118.0" 
           style="text-decoration:none">
            <img src="http://go.microsoft.com/fwlink/?LinkId=161376" 
                 alt="Get Microsoft Silverlight" style="border-style:none"/>
        </a>
    </object>
    <iframe id="_sl_historyFrame" style="visibility:hidden; height:0px; 
       width:0px; border:0px"></iframe>
</div>
EZFDYMGT5JFS

Thursday, January 31, 2013

How to Serialize FileInfo

How do you serialize a FileInfo object in WinForms or WPF? The basic issue is FileInfo doesn't have a parameterless constructor, which is required by XmlSerializer. While there are other ways to accomplish this task, the simplest way is to create a basic wrapper around FileInfo.

Create a Serializable FileInfo class

 FileInfoSerializable.cs
using System;
using System.IO;

namespace Utilities
{
    /// <summary>
    /// Serializable wrapper for FileInfo.
    /// </summary>
    public class FileInfoSerializable
    {
      #region ~~~ Fields ~~~
        
        private readonly FileInfo _fileInfo;

      #endregion

      #region ~~~ Constructors ~~~

        // A parameterless constructor is required for serialization
        public FileInfoSerializable()
        {
            _fileInfo = new FileInfo("export.xml");
        }

        public FileInfoSerializable(string FileName)
        {
            _fileInfo = new FileInfo(FileName);
        }

        public FileInfoSerializable(FileInfo FileInfo)
        {
            _fileInfo = FileInfo;
        }

      #endregion

      #region ~~~ Properties ~~~

        public string Name { 
            get { return _fileInfo.Name; } set {} }

        public string FullName { 
            get { return _fileInfo.FullName; } set {} }

        public long Length { 
            get { return _fileInfo.Length; } set {} }

        public string Extension { 
            get { return _fileInfo.Extension; } set {} }

        public DateTime CreationTime { 
            get { return _fileInfo.CreationTime; } set {} }

        public DateTime LastWriteTime { 
            get { return _fileInfo.LastWriteTime; } set {} }

        public string DirectoryName { 
            get { return _fileInfo.DirectoryName; } set {} }

      #endregion
    }
}

Monday, November 26, 2012

Enumerate SharePoint Solutions & Features for all Scopes

I have been involved in numerous custom SharePoint development projects, most of which are part of large SharePoint environments that have grown up over the course of many years.  Typically, multiple environments (production, integration, testing, etc) include hundreds of site collections, sites and sub-sites with SharePoint features activated at various scopes (farm, webapp, site collection and web). Determining which features are activated for a single site collection and site is relatively easy (although somewhat time-consuming) with the web interface:


However, what if you need a complete list of every built-in and custom feature (and associated solution) that is installed on a farm for every site collection and site and each feature's ID and activation scope?

This is quick command-line utility I created to provide these details. The complete Visual Studio 2010 project and source code is available for download at https://barkes@bitbucket.org/barkes/sharepoint-utilities.

SPEnumFeatures http://myserver/mysite false



The output can also be pipped to a CSV file from a command line and imported into Excel, for example:
SPEnumFeatures http://myserver/mysite false > features.csv


To Create the Command-line Utility in Visual Studio 2010

  1. Create a new project in Visual Studio named SPEnumFeatures by selecting the Console Application project template in the Visual C# category.

  2. Add a reference to the Microsoft.SharePoint assembly.  Right-click References in the Solution Explorer, select the Add Reference menu.  On the Add Reference dialog, select the .NET tab and locate the Microsoft.SharePoint (version 14.0.0.0) assembly and select the OK button.



  3. Open Program.cs and add the following code.
     Program.cs
    using System;
    using System.Collections.Generic;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Administration;
    
    namespace Barkes.SharePoint.CmdLine
    {
        class SPEnumFeatures
        {
            // Solution Id to name dictionary.
            static Dictionary<Guid, string> ActiveSolutions = new Dictionary<Guid, string>();
            
            /// <summary>
            /// The output of this console app can be pipped to a CSV file from a command line and imported into Excel
            /// SPEnumFeatures http://myserver/mysite true > features.csv
            /// </summary>
            static void Main(string[] args)
            {
                if (args.Length == 2)
                {
                    // Get all solutions from the farm
                    SPSolutionCollection solutionsCollection = SPFarm.Local.Solutions;
                    foreach (SPSolution solution in solutionsCollection)
                    {
                        ActiveSolutions.Add(solution.Id, solution.DisplayName);
                    }
    
                    // Write the column headers
                    Console.WriteLine("{0},{1},{2},{3},{4},{5}",
                        "Url",
                        "Solution Name",
                        "Solution Id",
                        "Feature Name",
                        "Feature Id",
                        "Scope");
    
                    // Process features for all scopes (add a cmdline arg for scope designation in the future)
                    ProcessFeatures(args[0], Convert.ToBoolean(args[1]));
                }
                else
                {
                    WriteUsage();
                }
            }
    
            /// <summary>
            /// Show the command usage on the console.
            /// </summary>
            private static void WriteUsage()
            {
                Console.WriteLine();
                Console.WriteLine("Barkes SharePoint Utilities");
                Console.WriteLine();
                Console.WriteLine("SPEnumFeatures url showhidden [true|false]");
                Console.WriteLine();
                Console.WriteLine("SPEnumFeatures http://myserver/mysite false");
                Console.WriteLine();
                Console.WriteLine("The output of this console app can be pipped to a CSV file from a command line");
                Console.WriteLine("and imported into Excel, for example:");
                Console.WriteLine();
                Console.WriteLine("SPEnumFeatures http://myserver/mysite false > features.csv");
            }
    
            /// <summary>
            /// Retrieve and write the activated features.
            /// </summary>
            private static void ProcessFeatures(string baseUrl, bool showHidden)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    // Farm features
                    WriteActiveFeatures(@"Farm Global", SPWebService.ContentService.Features, showHidden);
    
                    using (SPSite entrySite = new SPSite(baseUrl))
                    {
                        // Web Application features
                        SPWebApplication webApp = entrySite.WebApplication;
                        WriteActiveFeatures(@"WebApp Global", entrySite.WebApplication.Features, showHidden);
    
                        SPSiteCollection siteCollections = webApp.Sites;
    
                        foreach (SPSite siteCollection in siteCollections)
                        {
                            // Site Collection features
                            WriteActiveFeatures(siteCollection.Url.ToString(), siteCollection.Features, showHidden);
    
                            SPWebCollection webCollection = siteCollection.AllWebs;
    
                            for (int i = 0; i < webCollection.Count; i++)
                            {
                                using (SPWeb web = webCollection[i])
                                {
                                    // Web features
                                    SPFeatureCollection webFeatures = web.Features;
                                    WriteActiveFeatures(web.Url, webFeatures, showHidden);
                                }
                            }
    
                            siteCollection.Close();
                        }
                    }
                });
            }
    
            /// <summary>
            /// Overload with default showOOTB = false
            /// </summary>
            private static void WriteActiveFeatures(string webUrl, SPFeatureCollection webFeatures,
                bool showHidden)
            {
                WriteActiveFeatures(webUrl, webFeatures, showHidden, false);
            }
    
            /// <summary>
            /// Write the features contained in the feature collection to the console.
            /// </summary>
            private static void WriteActiveFeatures(string webUrl, SPFeatureCollection webFeatures,
                bool showHidden, bool showOOTB)
            {
                foreach (SPFeature webFeature in webFeatures)
                {
                    try
                    {
                        SPFeatureDefinition webFeatureDefinition = webFeature.Definition;
                        Guid featureId = webFeatureDefinition.Id;
                        Guid solutionId = webFeatureDefinition.SolutionId;
    
                        // Skip the hidden features, if indicated
                        if (!showHidden && webFeatureDefinition.Hidden)
                            continue;
    
                        // Skip the built-in features, if indicated
                        if (!showOOTB && (featureId == Guid.Empty || solutionId == Guid.Empty))
                            continue;
                    
                        Console.WriteLine("{0},{1},{2},{3},{4},{5}",
                            webUrl,
                            ActiveSolutions[webFeatureDefinition.SolutionId],
                            webFeatureDefinition.SolutionId,
                            webFeatureDefinition.DisplayName,
                            webFeatureDefinition.Id,
                            webFeatureDefinition.Scope.ToString());
                    }
                    catch (Exception)
                    {
                        ; // Do nothing
                    }
                }
            }
        }
    }
    

Friday, February 11, 2011

SilverPaint - Drawing Dynamic Shapes in Silverlight 3

This is a quick demonstration that focuses on some of the geometric shape drawing features that are available in Silverlight and how to use those features in code.

Live Demo: Drawing Dynamic Silverlight Shapes


The following code excerpts show the highlights of performing the primary shape drawing functions:
  • Dynamic shape creation
  • Sizing calculations
  • Brushes
  • Dynamic event handlers
  • Shape re-sizing
  • Shape movement 
///

/// Draws the desired geometrical shape.  This quick example app uses
/// ellipses and rectangles, but others would work here as well.
///
private void DrawShape(Shape shape, SolidColorBrush brush)
{
    double x = 0.0, y = 0.0;

    // These calcs are required to handle sizing in any direction
    if (_ptStart.X > _mX)
    {
        shape.Width = _ptStart.X - _mX;
        x = _mX;
    }
    else
    {
        shape.Width = _mX - _ptStart.X;
        x = _ptStart.X;
    }


    if (_ptStart.Y > _mY)
    
{
        
shape.Height = _ptStart.Y - _mY;
        
y = _mY;
    
}
    
else
    
{
        
shape.Height = _mY - _ptStart.Y;
        
y = _ptStart.Y;
    
}

    // Set the brushes
    
shape.Fill = brush;
    
shape.StrokeThickness = 1;
    
shape.Stroke = _whiteBrush;

    // Set the shape's coordinates
    shape.SetValue(Canvas.LeftProperty, x);
    shape.SetValue(Canvas.TopProperty, y);

    if (_shapeLast != null)
    {
        LayoutRoot.Children.Remove(_shapeLast);
    }

    
// Set the name, tooltip and add the event handlers
    shape.Name = "DynamicShape" + _shapeCount.ToString();
    ToolTipService.SetToolTip(shape, shape.Name + "\r\n" + shape.GetType().ToString());

    shape.MouseEnter += new MouseEventHandler(shape_MouseEnter);
    shape.MouseLeave += new MouseEventHandler(shape_MouseLeave);
    shape.MouseLeftButtonDown += new MouseButtonEventHandler(shape_MouseLeftButtonDown);
    shape.MouseLeftButtonUp += new MouseButtonEventHandler(shape_MouseLeftButtonUp);

    
// Add the shape to the canvas
    _shapeLast = shape;
    _shapeCount++;
    LayoutRoot.Children.Add(shape);
}

///

/// This is the method where the shapes are drawn, resized and moved.
///

private void LayoutRoot_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
    
// Update mouse coordinates
    _mX = e.GetPosition(sender as UIElement).X;
    _mY = e.GetPosition(sender as UIElement).Y;
    ctlCoords.Text = "(" + _mX + " ," + _mY + ")";

    
// If enabled, add event info to the console
    if (chkTrackMouse.IsChecked == true)
    {
        AddConsoleMsg("LayoutRoot_MouseMove: X=" + _mX + ", Y=" + _mY);
    }

    
// Perform a hittest to make sure we're operating within the bounds of our
    
// drawing surface
    IEnumerable elements;
    elements = VisualTreeHelper.FindElementsInHostCoordinates(
        new Point(_mX, _mY), ctlBounds as UIElement);

    if (elements.Any())
    {
        
// If enabled, draw the gridlines
        if (chkGridlines.IsChecked == true)
        {
            DrawGridlines();
        }

        
// If enabled, draw an ellipse
        if (_isLeftMouseButtonDown == true && _isDrawEllipse)
        {
            Ellipse ellipse = new Ellipse();
            DrawShape(ellipse, _brushes[_randBrush.Next(0,_brushes.Count)]);
        }

        
// If enabled, draw a rectangle
        if (_isLeftMouseButtonDown == true && _isDrawRect)
        {
            Rectangle rect = new Rectangle();
            DrawShape(rect, _brushes[_randBrush.Next(0, _brushes.Count)]);
        }

        
// If enabled, draw a line
        if (_isLeftMouseButtonDown == true && _isDrawLine)
        {
            Line line = new Line();
            DrawLine(line);
        }

        
// If a shape is moving
        if (_isShapeMoving)
        {
            double x = _mX - _shapeMove.Width / 2;
            double y = _mY - _shapeMove.Height / 2;

            
// Move the shape
            _shapeMove.SetValue(Canvas.LeftProperty, x);
            _shapeMove.SetValue(Canvas.TopProperty, y);
        }
    }
    else
    {
        // We're outside of the bounds of our drawing surface so remove the gridlines
        RemoveGridlines();
    }
}
You can download the full source here: Drawing Dynamic Silverlight Shapes Demo. This requires Visual Studio 2008 and Silverlight 3 development tools (Expression Blend is notrequired but would be useful as well).