Sunday, September 30, 2012

cheat sheet on networking

I am beginning to read chapter 15 of C# 4.0 in a Nutshell (on networking) and have so far learned that IPv6 addresses are shaped like so:

[3EA0:FFFF:198A:E4A3:4FF2:54f-A:41BC:8D31]

 
 

ASP.NET requires that you hand it an address with the brackets on either end, but I digress. The real reason for this blog entry is to offer this cheat sheet from pages 582 and 583:

Share photos on twitter with Twitpic

It's the best chart in the book so far. MAC in MAC address stands for Media Access Control. A MAC address is a unique identifier for a network interface.

SQL Profiler and Fiddler are for Voyeurism!

Database

------------->
SQL Profiler
<-------------

C#

------------->
Fiddler
<-------------

HTML

 
 

SQL Profiler will let you watch the SQL statements going between your application and the database while Fiddler will let you watch HTTP traffic.

Saturday, September 29, 2012

some File I/O fun

Say we say I have "Hello" in C:\MyFile.txt and we want add the "World" after the hello. To accomodate, I used to read everything from the file to a string, add to the string, and then write the string back to a text file like so:

using (Stream textReaderAndWriter = new FileStream(@"C:\MyFile.txt", FileMode.Open))
{
   byte[] dataCapacity = new byte[0x100];
   textReaderAndWriter.Read(dataCapacity, 0, dataCapacity.Length);
   string concatinationGrounds = "";
   foreach(char character in ASCIIEncoding.ASCII.GetString(dataCapacity))
   {
      if (char.IsLetterOrDigit(character))
      {
         concatinationGrounds += character;
      }
   }
   concatinationGrounds = concatinationGrounds + " World";
   textReaderAndWriter.Position = 0;
   dataCapacity = ASCIIEncoding.ASCII.GetBytes(concatinationGrounds);
   textReaderAndWriter.Write(dataCapacity, 0, dataCapacity.Length);
}

 
 

Today, I finished reading Chapter 14 of C# 4.0 in a Nutshell which is on File I/O (input/output) stuff. I thought that one of the things I learned in this chapter was this appending shortcut...

byte[] extraData = ASCIIEncoding.ASCII.GetBytes(" World");
using (Stream textAppender = new FileStream(@"C:\MyFile.txt", FileMode.Append))
{
   textAppender.Write(extraData, 0, extraData.Length);
}

 
 

...but then I dug up some of my old notes and found I had done this before:

Share photos on twitter with Twitpic

 
 

So what did I learn from this chapter?

  1. Flush() per the book: "forces any internally buffered data to be written immediately"
  2. \r is a "carriage return" and \n is a "line feed" so think of \r\n as a ReturN
  3. fileInfo.Attribures ^= FileAttributes.Hidden; will toggle the hidden flag from true to false or false to true for a FileInfo object
  4. CRC is cyclic redundancy check
  5. UAC stands for User Account Control and this is the Windows feature that asks you: "Do you want to allow the following program to make changes to this computer?"
  6. In new byte[0x100] the 0x notation is hexadecimal in which:
    • 0x10 is 16
    • 0x100 is 16 x 16 or 256
    • 0x1000 is 16 x 16 x 16 which is some big number
    • etc.

absolute positioning and z-index in CSS

#button {
   z-index: 2;
   width: 108px;
   height: 125px;
   background-image:url('/images/button.png');
   position: absolute;
   margin-top: 8px;
   margin-left: 330px;
   cursor: pointer;
}

use CSS3 selectors to differentiate styles for different input types

.div01 {
   width: 770px;
   height: 117px;
   padding-top: 108px;
}
.div01 input[type=text] {
   width: 206px;
   border: none;
   height: 34px;
   line-height: 34px;
   color: #000000;
   font-size: 24px;
   background-color: bisque;
}
.div01 input[type=password] {
   float: right;
   width: 206px;
   border: none;
   height: 22px;
   line-height: 22px;
   color: #000000;
   background-color: bisque;
}

Get rid of that stupid Safari form field highlighting! It's stupid! Grrr.

input:focus, select:focus, textarea:focus {
   outline: none;
}

Is canned stuff hard to manipulate?

I've read Citizen Coors by Dan Baum, a book on the Coors dynasty of Golden, Colorado. Bill Coors invented the aluminum can, and one of the tangents the book delves into has to do with the history of aluminum cans. At first, you had to have a church key independent of the can to punch a hole in it so that you might drink from it.

 
 

Eventually humanity had the advanced technology of ring pulls. I can just barely remember these from my childhood. You could cut your feet on them and the odds stepping on one barefoot was significant as they were a common piece of litter. Well, at least "you coulda had a V8" without needing a church key too.

 
 

Bill Coors tried different things to deal with the ring pull problem. He made something like the Alcoa tab without the tab allowing drinkers to punch a circle that would cave in and cut their fingers, and he eventually refactored this to something called "Press Tab Two" in which one slowly pressed two comparable tabs on either side of a can's top, but there was some pressurization problem and the approach really only worked well in the high altitudes of the Colorado Rockies. Eventually humanity did persevere and we ended up with the common Alcoa tab we know today. It allows you to open a can without a church key while not producing an independent piece of trash.

 
 

Speaking of canned stuff, I remember learning Allaire (church key) Cold Fusion back in 1999 as my first language for the web. Without a programmer's background, I couldn't write or understand C-shaped code, but I didn't have to! Cold Fusion provided what appeared to be a new set of HTML tags that rendered to real HTML tags when Cold Fusion's server returned content for the browser. I could talk to an access database, cycle through a loop, and write if/then logic. This sure seemed wonderful at the time. As I began working with PHP, and I found there were ways to concatenate and split strings, I saw Macromedia (ring pull) Cold Fusion in a different light and I realized that the technology was limited by way of being canned. The easy pseudoHTML sure was easy to work with, one could pick it up quick, and, best of all, there was no C-shaped language, but the downside was that one could only do canned things, and if concatenation and splits weren't in the canning they were unobtainable. I haven't used Cold Fusion in ages, but I've heard secondhand that modern day Adobe (Alcoa tab) Cold Fusion now includes a tag that allows one to break into a C-shaped code for Cold Fusion the way one might break into JavaScript with a Script tag. The users who loved a canned solution have grown up and have demanded that their software grow with them, hence Cold Fusion had to cease to be canned. This is not what the original Allaire peeps envisioned.

Question: Is this the inevitable path for all canned solutions? SharePoint could be traveling this way. As one progresses from developing in SharePoint 2007 to SharePoint 2010 to what I've heard secondhand of SharePoint 2013, one starts working more and more in Visual Studio and less exclusively through a browser interface. If Pega is here to stay will Pega developers one day be able to break out of the browser-based programming into Peggy script?

Friday, September 28, 2012

Plain-Jane JavaScript way to get the value of a dropdown list and the value of a hidden field

var foo = document.getElementById('Bar');
var baz = document.getElementById('Qux');
alert(foo.options[foo.selectedIndex].value);
alert(baz.value);

UNIONs in SQL

This had the following which makes UNIONs look super simple:

SELECT SUM([Customers]) as [# of Cust]
FROM (
SELECT COUNT(*) AS [Customers]
FROM Customers
WHERE (active = 1)
and (RepID = 4)
union
SELECT COUNT(*) AS [Customers]
FROM Customers
WHERE (active = 1)
and (RepID = 4)
) as aPlus

 
 

Note: ORDER BY must come after both SELECTs to apply to both and should reference columns numerically by column number in from the left on a table.

variable chaining in JavaScript!

This will bring up "Qux" in an alert!

<html>
   <body>
      <script language="javascript" type="text/javascript">
         var Foo = {
            Bar: {
               Baz: "Qux"
            }
         };
         alert(Foo.Bar.Baz);
      </script>
   </body>
</html>

namespace variables

using foo = OurLibraries.OurFooProject;

...could be used like so...

public static string foo.FooRepository GetFooRepository()
{

Thursday, September 27, 2012

Console.ReadLine(); will hold a console app open at the current line of code until you press a key.

I've actually written one of these now, or I should say I started to at least. I hate it that so many examples of C# are console application examples. I've done this ASP.NET work for years without having to have authored a console app. Doing something and then writing it to the console is more confusing than doing something and handing it back from a class in my opinion. I'm not crazy about console application examples. They are not intuitive for learning.

the DateTime.Now of the JavaScript world

The following (in tandem with this posting I wrote on date comparisons and casting a string to a date) show you how to make the most of your favorite poorly decoupled external dependency!

function setPopupDate(targetID) {
   var dateInput = document.getElementById(targetID);
   var clockDate = new Date();
   var clockMonth = clockDate.getMonth() + 1;
   var clockDay = clockDate.getDate();
   var clockYear = clockDate.getFullYear();
   if (clockMonth < 10) {
      dateInput.innerHTML = "0" + clockMonth;
   } else {
      dateInput.innerHTML = clockMonth;
   }
   if (clockDay < 10) {
      dateInput.innerHTML = dateInput.innerHTML + "/0" + clockDay + "/" + clockYear;
   } else {
      dateInput.innerHTML = dateInput.innerHTML + "/" + clockDay + "/" + clockYear;
   }
}

define which SSRS report runs upon previewing in Cassini

If you view the properties of an SSRS project in BIDS (by right-clicking on the project's name in the Solution Explorer and picking "Properties") there will be a subsection for "Debug" where you may define which SSRS report runs upon previewing in Cassini.

How to use the WebMethod attribute is still a mystery to me.

One may get back JSON from a route in a web forms app by reaching out to a method in the code behind of a web form that is decorated with the WebMethod attribute.

[WebMethod(EnableSession = true)]
public static string Foo(string bar)
{

 
 

Santanna Energy is using this technique heavily. I have not been able to get it to work in my own experiments at home. When I figure out the secret, you'll be the first to know. ;)

Wednesday, September 26, 2012

Visual Studio Addins

C:\Users\Whatever\Documents\Visual Studio 2010\Addins\ is where one places Addins for Visual Studio! At Santanna Energy we have a code generation tool which runs as an Addin allowing one to right-click on a class and then launch a WinForms app for generating code within the class. As at AMD, generated classes are split into two partials in two files, one for generated code and one for custom code.

feed an INSERT from a SELECT in MSSQL

INSERT INTO ForReal (Foo, Bar, Baz, Qux)
SELECT TempFoo, TempBar, TempBaz, TempQux FROM StagingGrounds

DECLARE local variables in MSSQL

DECLARE @foo int = 4
DECLARE @bar int = 14

white-space:nowrap;

...ensures text will not wrap to a second line. See: http://www.w3schools.com/cssref/pr_text_white-space.asp

IF versus CASE in MSSQL

IF @x = 0
   BEGIN
      --whatever
   END
ELSE
   BEGIN
      --whatever
   END

...does not seem to require an END the way a CASE statement does.

Tuesday, September 25, 2012

clear: both;

<div style="background-color: #888888; width:380px;">
   <div style="float:left; background-color: #AAAAAA; width:200px; text-align: center;">
      <h1>om</h1>
      <span>is a sacred syllable</span>
   </div>
   <div style="float:right; background-color: #CCCCCC; width:150px; color: #000000;">
      <ol>
         <li>Dharmic</li>
         <li>Hinduism</li>
         <li>Buddhism</li>
         <li>Jainism</li>
      </ol>
   </div>
   <div style="clear:both; background-color: #666666; width:380px;">
      <p>It's Sanskrit!</p>
   </div>
</div>

 
 

The HTML above creates a div with two divs floating side-by-side within it and a third div wrapping beneath the two floating divs. Ken Jackson orginally showed me the clear: both; CSS trick at Headspring. The code makes this:

 
 

om

is a sacred syllable
  1. Dharmic
  2. Hinduism
  3. Buddhism
  4. Jainism

It's Sanskrit!

decimal percision

This suggests that when defining a decimal that one passes into two numbers, the first for precision (the maximum number of places including decimal places) and the second for scale (the number of decimal places). So decimal(5,2) suggests that up to a three digit number (-999 to 999) and that this number may also have up to two decimal places.

3 + 2 = 5

This is also worth a visit as is this.

NOT IN (1,13) does not specify a range.

This instead suggests that the items in the parenthesis specify a list of items to match. There could be six items instead of two in the parenthesis.

manipulate strings in SQL

  1. LTRIM(@mystring) will remove the space off the front of @mystring
  2. RTRIM(@mystring) will remove the space off the end of @mystring
  3. RIGHT(@mystring,5) will give the last five characters in @mystring or all of the characters in @mystring if @mystring is less than six characters in length
  4. LEFT(@mystring,5) will give the first five characters in @mystring or all of the characters in @mystring if @mystring is less than six characters in length

PRINT, CAST, and @@ROWCOUNT

PRINT CAST(@@ROWCOUNT AS varchar(32)) + ' rows'

 
 

Herein:

  1. PRINT will return a string.
  2. @@ROWCOUNT will return the number of rows affected by the last statement.
  3. CAST converts from one type to another.

The double hypen denotes a comment in SQL.

--I am a comment.

I'm using WinMerge with a stored procedure today!

Have you ever encountered a stored procedure which has very similar blobs of code broken up by case elseifs based upon a numeric code handed in as a variable? Do you wish it was easy to see what was really different between two nearly identically blobs of SQL in the name of consolidating them? Why not save two pieces out to .txt files and then compare them? WinMerge is what Ravi Metta had us use at FramesDirect.com for merging files. It's free!

UML in Visio


  • http://www.tutorialspoint.com/uml/uml_activity_diagram.htm and http://www.tutorialspoint.com/images/uml_activity_diagram.jpg show off how UML should look.
    1. A black dot is the start of a process.
    2. A black dot with a circle around it is an end point for the process.
    3. A diamond is a decision. A question will be written before the inbound arrow, and the lines that lead out ultimately as other arrows to elsewhere will have a choice written at their heads.
    4. An oval is a stop along the trip to the destination.
    5. Arrows are drawn between the four items above.
  • Centering copy in a terminator (oval) can keep it from bleeding out the side of the oval.
  • For a Basic Flowchart Visio project use the Dynamic Connector to draw lines (with arrows at one end) between two shapes.
  • Grab a green node on a oval to drag out its shape and make it fatter or thiner.
  • I can't seem to make a Dynamic Connector arrow end midway into a another Dynamic Connector arrow in Visio, however if I just connect to where the arrow ultimately leads to anyway, the desired effect is created for me.
  • One may drag about middle segments of Dynamic Connector arrows to the right and left or up and down to reposition them.
  • Don't try to center copy in an oval vertically with line breaks. Drag the oval vertically to change its shape.
  • If an arrow has too many bends in it, one may remove two segments by dragging two segements that are one segment apart parallel.
  • You may open Visio documents in IE!

Hold the Ctrl key and move the mouse to the edges of a Visio canvas to change its shape.

Your cursor will change to one of a "double arrow" variation indicating that you may click to drag the canvas fatter or thinner.

How do C# partial classes find their dance partners?

This sure makes partial classes in C# look easy. It looks like any classes of the same name in the same namespace will be married together by way of the partial keyword where they would otherwise cause a compilation error!

public partial class AIPlayer
{
   public AIPlayer()
   {
      
//whatever
   }
}
 
public partial class AIPlayer
{      
   public Move GetMove()
   {
      
//whatever
   }
}

 
 

In my googling, I found this showing off the VB way which made me cringe!

Monday, September 24, 2012

Use a common project across numerous solutions in the ASP.NET space.

Today is my first at Santanna Energy and one of the things I've been exposed to already is the use of common projects across numerous solutions. To empower this, a solution utilizing the common project will have a reference out to the common project at one of its own projects that has a path setting which references a file share on the network. I suppose the server holding IIS will need to be able to access this share for the application to run (assuming it is a web app) and a local environment will need to be able to access the share to run an app in Visual Studio. The file share will hold .dlls published from the common project will be kept in its own solution, perhaps with other comparable common projects. This shape of things allows the commonly accessed item to be consistently a work in progress without the need to constantly update dependent solutions. Instead, when one changes the common project, one just has to remember to publish a .dll to the share to broadcast the changes to all subscribers. Cool.

Sunday, September 23, 2012

Play with the latest toys!

  1. Start with Windows 7
  2. Install Service Pack 1 for Windows 7: http://www.microsoft.com/en-us/download/details.aspx?id=5842
  3. Download Visual Studio 2012: http://www.microsoft.com/visualstudio/eng/downloads
    Share photos on twitter with Twitpic Share photos on twitter with Twitpic
  4. Install Microsoft SQL Server Management Studio Express 2012: http://www.microsoft.com/sqlserver/en/us/editions/express.aspx (During the Instance Configuration portion of the install give a consistent value for "Named instance" and "Instance ID" as these define how to reach a local database.)

Saturday, September 22, 2012

create virtual machines

  1. Start with Windows 7
  2. Download and Install Windows XP Mode with Virtual PC: http://www.microsoft.com/windows/virtual-pc/download.aspx
  3. Type "Virtual PC" at the start menu.
  4. Click the "Create virtual machine button" at the quirky folder that opens.
    Share photos on twitter with Twitpic
  5. Make a new machine, and then right-click on it and pick "Settings" to set where the virtual machine should look to install an operating system.
    Share photos on twitter with Twitpic
  6. I found this how-to at: http://www.howtogeek.com/56158/beginner-how-to-create-a-virtual-machine-in-windows-7-using-virtual-pc/

Friday, September 21, 2012

I tasted the "government" experience.

Today was my last at HDRI. Good to work with:
John Halliday (left), Roger Armstrong (center) and Roger's wife Chris (right)
Marc Fairorth (who runs HDRI)
Will Hendrix (stripped shirt), Jim Adcock (black shirt), Marc Fairorth (far right)
Sean Drozd looks into the camera from the baby carriage. Julie Reynolds is at the far right. Chad Levert is the tall guy behind her in the grey shirt. You can see Marc Fairorth in the back in the burgundy shirt. At his right is Lance Warthen in a stripped shirt.
Will Hendrix (far left), Dean Herko (next rightward in from Will), Eric Swann (next rightward in from Dean), Roger Armstrong (is in the stripped shirt conversing with Eric Swann)
Eric Swann is in the blue shirt. Lloyd Bates is immediately to the left, facing the camera in a black shirt. Olufemi Oyekan checks out the food.
Lloyd Bates (left), Dean Herko (right)
John Halliday (far left), Tim Tonneson (far right)
Chad Levert is the tall guy in the grey shirt. Roger Armstrong is to his right in the stripped shirt. Sean Drozd holds his infant daughter. Marc Fairorth is in the burgundy shirt locking eyes with the camera.
At left, Michele Hedrick stands with her husband Glenn. At right sit Julie Reynolds (left), Will Hendrix (center), and Olufemi Oyekan (right).
Lance Warthen
Tim Tonneson faces the camera and Eric Swann is in the blue shirt.
fin.

 
 

Addendum 7/27/2015: I contracted for TEKSystems which subcontracted for HDRI (Helpdesk Response, Inc.) which subcontracted for Computer Sciences Corporation (CSC) which contracted for Veterans Affairs itself.

 
 

Addendum 8/3/2017: While I am thinking of it, the woman at the lower right corner in the last picture looking up into the stars is Jenna Barton who was the secretary at HDRI. That's her boyfriend, Dash or Dashiell, standing next to her. You can see him good in the picture where everyone is getting on the boat. He is kinda staring me down in that photo. Jenna on the other hand appears in lots of the pictures too, but we don't really see her face which is why I never labeled her before. She and he were from some ridiculous place like Kentucky and had silly accents. He worked for Aerotek which is an arm of TEKsystems which places people with more mundane skills like his GF's instead of the bigger talent in these photos. I have no idea what happened to them. The last I heard both Marc and Michele had been run off from the VA.

 
 

Addendum 5/17/2018: Sean Drozd once told me that his wife wanted to use her grandmother's wedding ring as her own wedding ring, and she did. There was a problem with that however in that she had an allergy to the metal and it turned her hand red with rash. The solution was to coat the ring in some sort of clear substance. I think of this story from time to time, most recently just yesterday.

submit a form as serialized JSON

This code was handed to me today by Will Hendrix. I have not tried it out yet. It should allow for a form's contents to be serialized and sent as JSON upon a form submission. I assume it requires a reference to the jQuery library, although there is a joke about the word assume.

function SubmitForm(formName, success, failure) {
   
   
// Select the form, by it's ID
   var theForm = $("#" + formName);
   
   
// Check to see if form exists
   if (theForm.length == 0)
      return;
   
   
// Create the JSON to represent the action parameters
   var params = theForm.serializeObject();
   
   var action = theForm.attr("action");
// action will contain controller/action
   if (action.length == 0)
      return;
   
   $.ajax({
      url: action,
      type: "POST",
      cache: false,
      data: JSON.stringify(params),
      dataType: "html",
      contentType: "application/json; charset=utf-8",
      error: failure,
      success: success
   });
}

 
 

I will also require this...

<script type="text/javascript" src="http://www.JSON.org/json2.js"></script>

 
 

It will also require this plugin too...

$.fn.serializeObject = function () { var o = {}; var a = this.serializeArray(); $.each(a, function () { if (o[this.name] !== undefined) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; };

 
 

It was good working with Will Hendrix at HDRI, he is a very sharp senior developer. This is one of the photos he created in holding the aperture open on a camera while spinning a glowing yo-yo in the dark of the night:

Share photos on twitter with Twitpic

trim away part of a string with jQuery

This suggests I can trim the first character off of a string in jQuery like so:

var val = $("span").html();
$("span").html(val.substring(1, val.length);

find the nth-numbered element in a swath of HTML with jQuery

var detail16a = $(formtablerows[16]).find("select:eq(0)");
var detail16b = $(formtablerows[16]).find("select:eq(1)");
$(detail16a).attr('style', 'display: none !important;');
$(detail16b).attr('style', 'display: none !important;');

Thursday, September 20, 2012

crazy SharePoint noise

The 1 in this post comes from the value (well, the public facing text) of the next drop down list!!! Crazy!

something random (of SQL) I remembered just now

When I was at AMD Craig Likes spoke of potentially querying for just the fields that would display in a paginated list from a table in lieu of a Select * approach in which all of the fields for a table came back in a query of numerous records. That seemed wise. This was a maybe-to-do in the name of optimization, not something to proactively do upfront. We started with the Select * approach by default.

Wednesday, September 19, 2012

wrap numeric types in unit types in advance of calculations

Share photos on twitter with Twitpic

Bjarne Stroustrup spoke on C++ at National Instruments on behalf of IEEE tonight. I saw the talk. The talk was largely on good standards and practices. For example, this is not a particular intuitive interface signature:

Rectangle(int, int, int, int);

Share photos on twitter with Twitpic

The one thing I heard that I had not heard before that really interested me was the notion of wrapping numeric types in simple objects before handing them into method signatures for methods that are to undertake calculations based on the numeric data. If you have a method that is to do something with a number of miles it is probably best to hand in an object of Mile type that contains a double instead of a double. Why? Then the nature of the unit is conveyed and a programmer will not accidentally make calculations inside the method under the false assumption that the double being handed in represents kilometers.

some DNS basics

What is a reverse lookup in DNS? It is the process of finding a domain name from an IP address! There has to be a designated domain name for an IP for this to work. (This is rDNS, the opposite of DNS or Domain Name Services, for finding IPs from domain names.) The Wikipedia explains how reverse stuff is even possible at http://en.wikipedia.org/wiki/Reverse_DNS_lookup and it looks there is a root reverse DNS database to hold the metadata to make the associations. At the event I went to last night, a guy mentioned that hackers may set up malicious DNS servers to return malicious JavaScript in lieu of a domain name via reverse DNS lookups!

DNS associates domain names to IPs by pointing the domain name at nameservers which then suggest how the domain name should be routed. From here there is some branching across different record types. A request to a domain name will be routed to a nameserver and then off to an A or MX or other record which will contain an IP. A browser will try to find a web site at a server with an applicable IP for an applicable A record. From there the server will route the request to a web site running, typically by default, on port 80. Types of records include:

  • A records: These point web traffic to subdomains to IPs. For example: www.example.com might point to 1.2.3.4 while example.com might point to 1.2.3.5 and somethingelse.example.com might point to 1.2.3.6 where all three are separate A records.
  • MX records: These define how to find the mail server for a domain name. When you send mail to example.com the MX record will route the mail to a particular IP for a mail server.
  • SPF records: These try to assert that mail should come from a particular IP for a domain name. If a mail server receiving mail from example.com has an SPF tool it can look up the SPF record and compare it to where mail is arriving to it from in the name of blocking potential spam in the case of a mismatch.

jQuery validation against User type fields in SharePoint

A field with Type="User" specified in SharePoint is a login control. It allows for you to fish for someone in Active Directory or otherwise speced as a user!

Share photos on twitter with Twitpic

I rolled some jQuery validations for these controls like so:

var inputuserfields = new Array();
inputuserfields = $('.ms-inputuserfield');
var isEven = true;
var inputuserdivs = new Array();
$.each(inputuserfields, function() {
   if (isEven){
      inputuserdivs.push($(this));
      isEven = false;
   } else {
      isEven = true;
   }
});
var doesNotMeetUserInputRequirements = false;
$.each(inputuserdivs, function() {
   var divhtml = $(this).html();
   if ((divhtml).indexOf("SPAN") >= 0)
   {
      if ((divhtml).indexOf("ms-entity-unresolved") >= 0)
      {
         doesNotMeetUserInputRequirements = true;
      }
   } else {
      doesNotMeetUserInputRequirements = true;
   }
});
if(doesNotMeetUserInputRequirements)
{

 
 

You'll notice two .each loops above:

  1. I first get everything with the ms-inputuserfield class and then cast the even items to a different array in the name of trimming out some noise. Each User type control will have two elements with ms-inputuserfield associated. ms-inputuserfield will not appear anywhere else on a form. Of the two elements for each control, we only want the first element which is a div containing the public text for the control in a manner that sort of fakes a text input field. The element we don't want is a textarea. I don't know what the textarea does. Is it a storage space for SharePoint to do some needed acrobatics in the name of wrangling user data?
  2. If a User control div is left empty it will only contain &nbsp; and if it has only been typed in it will hold some copy. One has to try to validate some typing with the check icon at a User control's right in order to make a match (or attempt a match) in a User control between an entered value and a User. After clicking the check a span tag will end up in the div, so I check for this span tag in my code in the name of determining if a User control is properly populated. However, if the ms-entity-unresolved class appears inspite of the presence of a span tag, that means an attempt to find a user has failed.
    Share photos on twitter with Twitpic

I got pulled into SharePoint in my 11th hour at HDRI. It turns out I like it! I'm going to miss it when I hand in this badge at week's end:

Share photos on twitter with Twitpic

make sure a function is called when a drop down list changes

This is jQuery. I have the blur (on leave, not focus which is on entry) as the 37,38,39,40 keys for arrows are not recognized in Internet Explorer 9.

$(detail16).live('click', function() {
   $(detail24).html(replacementHtml);
   retrieveOfficeItems();
});
$(detail16).keypress(function (e) {
   $(detail24).html(replacementHtml);
   retrieveOfficeItems();
});
$(detail16).blur(function (e) {
   $(detail24).html(replacementHtml);
   retrieveOfficeItems();
});

jQuery split

Here is now to get at the real public facing value in a SharePoint drop down list with jQuery, stripping away the noise.

var currentAdministration = $(adminselect+':selected').text();
var firstCurrentAdministrationCollection = currentAdministration.split("#");
currentAdministration = firstCurrentAdministrationCollection[1];
var secondCurrentAdministrationCollection = currentAdministration.split("1");
currentAdministration = secondCurrentAdministrationCollection[0];

 
 

I got this from here which has more details.

The 1 to split on is the 1 in the number 12 which I suspect may vary as a number based on the position of the field within the form or perhaps something else.

KaZaA!

Today is International Talk Like a Pirate Day to which I say "KaZaA" which shows off how long it has been since used a peer-to-peer app. Wikipedia tells me it is just "Kazaa" anymore. In this morning's Googling I learned Morpheus is long gone.

I can't say I really miss this stuff with all the malware and pop ups.

 
 

Addendum 4/17/2017: I think Napster was the first of the share/pirate tools.

Google now crawls JavaScript content

http://www.webmasterworld.com/google/4159807.htm is a thread I've found online which speaks to something I learned a few months ago: Google is now using a JavaScript engine in its crawler.

I remember attending Product Camp Austin 20 months ago and being specifically instructed not to use JavaScript in navigation menus as such will confuse the Googlebot. Stuff unhidden to a user by JavaScript would never get unhidden to the Googlebot. This meant that your web site shouldn't have jQuery-driven drop down menus for example. Well, you may forget all that now and embrace drop down menus anew it seems! JavaScript and SEO now jive together.

Tuesday, September 18, 2012

building better mobile apps

Share photos on twitter with Twitpic

I saw Bert Grantges of Appcelerator speak on Titanium which is a framework for mobile development. Using Titanium, cross-platform JavaScript is crafted which will be compiled into deployable packages for Android, iOS, and Mobile Web (HTML5 internet browser apps) platforms. The JavaScript works with the native code of iOS and Android allowing for one to work natively in both without enormous pain. It works sort of like Node.js under the hood and eventually it is to run on top of Node.js in version three of its release later this year. I remember attending a geek lunch perhaps a half of a year ago with Josh Arnold and Jeremy Miller of Surgery Logistics in which they asserted that they were building all of their mobile stuff in HTML5 as trying to build natively in two very different environments (iOS and Android) would have been madness. In contrast, Bert Grantges suggested that one can build natively in both environments without writing wildly different code bases and that Titanium is the tool for the job.

Share photos on twitter with Twitpic

Notes:

  1. Bert asserted that his team does not want to "write once and suck everywhere" with a single rendering context. Instead there is a "write once and be adaptive everywhere" philosophy in play.
  2. Mobile form factors come in many shapes and Titanium can fit them all by interfacing with them natively so that tab groups looks like iOS tab groups on an iPhone and like Android tab groups on an Android. The Titanium namespace within Titanium is a binding layer between JavaScript and the native API of a given form factor abstracting way the particulars of native code from the coder and allowing the coder to just stay heads down in JavaScript. Debugging for the native languages is included and this takes the pain out of trying to debug code to do with a camera or geo-locator in an emulator where such may be otherwise painful.
  3. The IDE is Titanium Studio which is built on top of Eclipse. One may run apps in emulators from Titanium Studio.
    Share photos on twitter with Twitpic
  4. There is support for the @2x.png image convention for iPhone.
  5. Version three of Titanium is to support Blackberry 10 and Windows Phone.
  6. An MVCesque front end framework called Alloy is coming with version three. Presently there is no separation between styling and the rest of the code one writes in Titanium.
  7. There is no DOM to interface with in Titanium. This means that Titanium really needs to interface with JSON-laden APIs. When interfacing with SOAP and getting back XML, the only way Titanium can make good is to fake a DOM to be able to wrangle the XML.
    Share photos on twitter with Twitpic
  8. One may also work with mobile web stuff and make apps that run in the browsers of devices in HTML5. What is more, and really exciting, is that one may have hybrid apps of both native and HTML5 hodgepodges. From a native app, one may launch a browser and have more of the app come up in the browser. From an HTML5 app, one may spin up a native window overtop of the browser. A geo-location example of this was given in the talk. A map was placed over top of a web page. Only locally stored web pages may have native content spliced into them like this, so pages that live in the world have to be scraped and then cached locally to create the illusion of them being manipulated in this manner.
  9. Drillbit is a test harness and there will be a new test harness coming in version three of Titanium.
  10. The compilation folder for an app will have different deployable packages for iOS, Android, and MobileWeb.

This event was of AustinJS and was hosted at Frog Design as per the norm.

Share photos on twitter with Twitpic

I ran into Kassandra Perch at this event and she recommended the book: Learning JavaScript Design Patterns by Addy Osmani.

Share photos on twitter with Twitpic

You may change the types of form field controls in SharePoint with jQuery!

var innerHtml = $(detail24).html();
var replacementHtml = "<select id=";
replacementHtml = replacementHtml + $(innerHtml).find('INPUT').attr('id');
replacementHtml = replacementHtml + " name=";
replacementHtml = replacementHtml + $(innerHtml).find('INPUT').attr('name');
replacementHtml = replacementHtml + "><option value=''>--make a selection--</option>
      </select>"
$(detail24).html(replacementHtml);
retrieveVisnItems();

 
 

In the first line of code above, I the scrape the contents out of a table detail. If I were to put the HTML to the screen with a JavaScript alert it would look like so:

Share photos on twitter with Twitpic

In the next few lines of code I then make a select list with the same id and name as the text input in the blob of html I scraped. I next replace the contents of the table detail I scraped with the html for my select list. The last line is retrieveVisnItems(); which will allow me to reach into a different SharePoint SPWeb (assuming I have appropriate permissions) and grab the contents of a list there to populate my own select list with content from this somewhat external source.

function retrieveVisnItems() {
   var clientContext = new SP.ClientContext('/sites/whatever');
   var oList = clientContext.get_web().get_lists().getByTitle('VISN');
   var camlQuery = new SP.CamlQuery();
   camlQuery.set_viewXml('<View><Query></Query></View>');
   this.collListItem = oList.getItems(camlQuery);
   clientContext.load(collListItem);
   clientContext.executeQueryAsync(Function.createDelegate(this,
      this.onVisnQuerySucceeded),
      Function.createDelegate(this, this.onQueryFailed));
}
   
function onVisnQuerySucceeded(sender, args) {
   var formtablerows = $(".ms-formtable").attr('rows');
   var localeselect = $(formtablerows[24]).find('select:first');
   var listItemEnumerator = collListItem.getEnumerator();
   while (listItemEnumerator.moveNext()) {
      var oListItem = listItemEnumerator.get_current();
      $(localeselect).append($('<option>
            </option>').val(oListItem.get_item('VISN')).html(
            oListItem.get_item('VISN') + " " + oListItem.get_item('FriendlyName')));
   }
}
   
function onQueryFailed(sender, args) {
   alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

 
 

This is a way of changing a SharePoint form field with jQuery. In this example I change a number type field (input type=text) to a select list to constrain the possible numbers entered to those in a list in another source. I have to scrape the id and name of the input I wish to reshape (replace) because it will vary from deployment to deployment as SharePoint is like that. Note that it is easy to fish for attributes within a string holding HTML with jQuery. I was no effort at all to get at what I wanted.

 
 

In another place in code I make sure that a user cannot submit the form without picking something other than the default value from the select list I made:

if($(locationselection+":selected").text().indexOf("make a selection") >= 0)
{
   emptyIfAllIsWell = donotreturnemptystring(emptyIfAllIsWell, "You must specify a
         Location Number!");
}

 
 

I tried to solve this same problem before by making a select list next to the number field which I planned to hide and then to populate a value into the number field whenever the select list changed. ...Too much work and I couldn't get it working. I also thought to just use a lookup or other canned drop down list in SharePoint but then the values I added from an external source wouldn't jive with what SharePoint expected the possibilities to be.

Monday, September 17, 2012

John Teague on REST and Hypermedia at ADNUG tonight.

Share photos on twitter with Twitpic

John Teague of Avenida Software spoke on REST (ReST stands for Representational State Transfer) and what Roy Fielding (who came up with REST) penned to be HatEoAS (Hypertext as the Engine of Application State) which the rest (no pun intended) of the world has come to refer to as Hypermedia APIs (as the later name is less unwieldy) at the Austin .NET Users Group tonight. My takeaway:

  • Representational State Transfer varies from CRUD in that you are pushing state to commands in hitting a REST API.
  • REST is not SOAP (Simple Object Access Protocol) in which one defines gunk on a WSDL (Web Service Definition Language) and interfaces with it exclusively through POST as GET, PUT, DELETE, and PATCH may be used with REST too.
    Share photos on twitter with Twitpic
  • The Richardson Maturity Model is a means to gauge how RESTful your stuff is.
  • A Hypertext implementation varies from a REST-only approach without out it in that the later will expose a bunch of marginally-related routes on an API that a consumer can only know of to implement by way of its programmer be told of by documentation or by human being what the smattering or different routes to hit are. In a Hypermedia implementation, arriving an entry point at one URI provides to the consumer all other routes. A tree of links is exposed at the entry point allowing for navigation to all other functionality.
    Share photos on twitter with Twitpic
  • In the mobile space this is posh because the infrastructure for a site may be pulled into HTML5 local storage once and then referenced even when connectivity is lost allowing for some cached capabilities.
  • There is a movement to have a Hypermedia call return HTML with links nested in unordered lists in lieu of JSON or HAL (Hypertext Application Language). John Teague asserted he was having trouble warming up to this as if one is to try to reshape what comes across the wire as HTML one gets into the slog of XML spelunking. Glen Block has an article on using a link-formatter over top of a Hypermedia API. Perhaps such an approach could minimize the HTML and thus XML wrangling.
  • Mike Amundsen has a book on Hypermedia APIs.
  • Deep link entry points partway into a Hypermedia tree provide a how-to-offer/how-to-maintain challenge.
  • Adding a new item within a Hypermedia API is done with something called a template.
  • REST in Practice by Ian Robinson and Jim Webber is... a book!
  • NBuilder is a great tool with which to make fake data for a test. (Sorry, I know that is off topic.)

The event was held at the facility of Build a Sign! Thanks to Build a Sign for hosting!

Share photos on twitter with Twitpic

URIs versus URLs

URLs (Uniform Resource Location) are a kind of URI (Uniform Resource Identifier). URIs that are not URLs include namespace identifiers for example. A URI (public://myfile.jpg) is a path to something on a network. TCP (Transmission Control Protocol) and IP (Internet Protocol) are of URIs not URLs.

replace a substring in jQuery

innerHtml = innerHtml.replace('<BR>','&nbsp;');

Tiger team

Wikipedia suggests a tiger team "is a group of experts assigned to investigate and/or solve technical or systemic problems" at http://en.wikipedia.org/wiki/Tiger_team

functions and regex in jQuery

One way to validate that a form field holds a number with jQuery is like this:

var detail21 = $(rows[21]).find('input:text:first');
var matches = (detail21).find('input:first').val()).match(/^[0-9]+([0-9]+)*$/);
if(!matches) {

 
 

But here is something more interesting!

var detail21 = $(rows[21]).find('input:text:first');
$(detail21).ForceNumericOnly();

 
 

This function will only allow you to type numbers into the form field in question!

jQuery.fn.ForceNumericOnly = function()
{
   return this.each(function()
   {
      $(this).keydown(function(e)
      {
         var key = e.charCode || e.keyCode || 0;
         return (
            key == 8 ||
            key == 9 ||
            key == 46 ||
            (key >= 37 && key <= 40) ||
            (key >= 48 && key <= 57) ||
            (key >= 96 && key <= 105));
      });
   });
};

 
 

I figured this out with:

use a variable in tandem with a magic string when manipulating an element in jQuery

This...

if($(detail16+':selected').val() == "0") {

 

...is the way to do this with a variable...

if($('#whatever:selected').val() == "0") {

Sunday, September 16, 2012

remove Windows XP mode from Windows 7

http://technet.microsoft.com/en-us/library/ee431673%28v=ws.10%29.aspx suggests it is pretty darn easy to drop Windows XP mode. One just needs to uninstall it as a program from the control panel really.

Friday, September 14, 2012

how to hack jQuery form validations into SharePoint

The button that would allow you to submit a SharePoint form looks like this:

<input type="button" name="ctl00$m$g_426ced44_2eea_4b90_82e1_f6efc8dcc7f2$ctl00$toolBarTbltop$RightRptControls$ctl01$ctl00$diidIOSaveItem" value="Save" onclick="if (!PreSaveItem()) return false;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$m$g_426ced44_2eea_4b90_82e1_f6efc8dcc7f2$ctl00$toolBarTbltop$RightRptControls$ctl01$ctl00$diidIOSaveItem", "", true, "", "", false, true))" id="ctl00_m_g_426ced44_2eea_4b90_82e1_f6efc8dcc7f2_ctl00_toolBarTbltop_RightRptControls_ctl01_ctl00_diidIOSaveItem" accesskey="O" class="ms-ButtonHeightWidth" target="_self" />

 
 

As you can see:

  1. The form does not submit upon a press of the enter key, only upon a click of the button.
  2. ctl00$m$g_426ced44_2eea_4b90_82e1_f6efc8dcc7f2$ctl00 and a lot of other noise is very likely subject to change from deploy to deploy and should not be depended upon and copied elsewhere.
  3. It will be a dirty hack to make this button do more than what it is made to do.

 
 

Let's say I want to roll my own jQuery-based form validation. Why, might I want to do so? Because some fields may be conditionally hidden while required if not hidden. (see: this) But how may I keep the button from submitting if validation requirements are not met? Great question. I have decided to hide the button, put my own save button on the form, and have my save button click the real (hidden) save button if validation requirements are met like so:

var savebutton = $(".ms-formtoolbar:first").find('input:first');
savebutton.click();

 
 

I have "moved" the ability to submit the form out of SharePoint's JavaScript into my own jQuery in this means. My own jQuery will be a lot easier to refactor.

Thursday, September 13, 2012

manipulate drop downs in jQuery

  • Get the value from a drop down:
    var foo = $('#bar:selected').val();
     
  • Get the public-facing value from a drop down:
    var foo = $('#bar:selected').text();
     
  • Set a drop down's value:
    $('#bar').val("baz");
     
  • Empty a drop down:
    $('#bar').empty();
     
  • Append a new option to a drop down:
    $('#bar').append($('<option></option>').val("value").html("text"));
     
  • Remove an item from a drop down:
    $('#bar').find("option[value='foo']").remove();
     
  • Loop through the options in a list:
    var areaselect = $(formtablerows[24]).find('select:first');
    $(areaselect).each(function() {
       $('option', this).each(function () {
          alert($(this).text());
       });
    });

Addendum 4/22/2015: I think that all one has to do anymore is var foo = $('#bar').val(); for getting the value from a drop down.

manhandling a table with jQuery

This is some JavaScript (and other stuff) that I began rolling in a SharePoint web part yesterday. This code shows off jQuery for finding the nth td in a tr, finding an input field inside a parent, collecting the rows of a table in a collection, getting the current time, and hiding table rows.

<div class="me-first">
   Please answer two questions to begin...
   <div class="whatever">
      <strong>Question One:</strong> Do you like cats?
      <div style="padding: 0px 0px 0px 150px;">
         <input type="radio" name="question1" value="xYes"> Yes<br />
         <input type="radio" name="question1" value="xNo"> No
      </div>
   </div>
   <div class="whatever">
      <strong>Question Two:</strong> Do you like dogs?
      <div style="padding: 0px 0px 0px 150px;">
         <input type="radio" name="question1" value="yYes"> Yes<br />
         <input type="radio" name="question1" value="yNo"> No
      </div>
   </div>
</div>
<script type="text/javascript" src="http://www.hdri.net/Scripts/jquery-1.4.4.min.js">
</script>
<script type="text/javascript">
   $(function() {
      $(".me-first").attr('style', 'display: block !important;');
      $('input[name=question1]').keypress(function (e) {
         switch (e.keyCode) {
            case 37:
               unhideform();
               break;
            case 38:
               unhideform();
               break;
            case 39:
               unhideform();
               break;
            case 40:
               unhideform();
               break;
         }
      });
      $('input[name=question1]').bind('click', function () {
         unhideform();
      });
      $('input[name=question2]').keypress(function (e) {
         switch (e.keyCode) {
            case 37:
               unhideform();
               break;
            case 38:
               unhideform();
               break;
            case 39:
               unhideform();
               break;
            case 40:
               unhideform();
               break;
         }
      });
      $('input[name=question2]').bind('click', function () {
         unhideform();
      });
   });
   function unhideform() {
      var checkx = "" + $('input[name=question1]:checked').val();
      var checky = "" + $('input[name=question2]:checked').val();
      if (checkx.indexOf("x") >= 0 && checky.indexOf("y") >= 0) {
         var now = new Date();
         var months = new Array('1','2','3','4','5','6','7','8','9','10','11','12');
         var today = months[now.getMonth()] + "/" + now.getDate()+ "/" + now.getYear();
         var formtablerows = $(".ms-formtable").attr('rows');
         
         /* set registration date */
         var detail0a = $(formtablerows[0]).find("td").eq(2);
         var detail0b = $(detail0a).find('input:text:first');
         detail0b.val(today);
         $(formtablerows[0]).hide();
         
         /* show revamped form */
         $(".me-first").attr('style', 'display: none !important;');
         $(".ms-formtable").attr('style', 'display: block !important;');
         $(".ms-toolbar").attr('style', 'display: block !important;');
      }
   }
</script>

Wednesday, September 12, 2012

FOUCs may be hacked around when using web parts with SharePoint.

I am using web parts to empower jQuery to manipulate list forms in SharePoint as discussed here. I would like a miniform to appear before a proper form asking the user two questions. Upon asking the questions, the real form is to unhidden with particular fields preprepped with certain values. This means I need to initially hide the proper form. I find if I make a web part after the proper form that contains some jQuery that does this...

$(".ms-formtable").attr('style', 'display: none;');

 
 

...will hide the form, but only when it "kicks in" as the form will be visible for a second and then disappear from view. This is known as FOUC (flash of unstyled content). How do we get rid of it? Could we create two separate web parts and wrap the content to hide in a div tag? We could start like this...

<div style='display: none;' id='newhelper'>

 
 

...and end like this...

</div>
<script type="text/javascript" src="http://www.hdri.net/Scripts/jquery-1.4.4.min.js">
</script>
<script type="text/javascript">
   $(function() {
      alert('whatever');
   });
</script>

 
 

...but, unfortunately, this will not work as SharePoint will put a closing div tag after the open div tag in the first web part. Using two web parts is a good idea, but they should not contain an open tag and a close tag for a div. Instead, the second web part should have jQuery content as shown above while the first web part should have CSS content like so:

<style type="text/css">
   .ms-formtable {
      display:none !important;
   }
</style>

 
 

This should both get rid of the FOUC and make the form impossible to use without having JavaScript enabled which really is a must in my scenario.

SSIS how-to youtube movie

http://www.youtube.com/watch?v=A8Hem5WF2yc is a how to movie on SSIS. Thank you Chad Levert.

Tuesday, September 11, 2012

jQuery web parts with SharePoint

Here is how to make jQuery effect a list's forms at SharePoint. An example:

  • Go to the List Settings for the List in SharePoint's web UI (at: List Tools > List > List Settings) and then pick "Advanced settings"
  • Set the "Launch forms in a dialog?" value to "No"
  • Open Microsoft SharePoint Designer 2010
  • Select Open New site and then simply paste in the url of your site in the dialog box that appears to open it. If you have appropriate permissions, you will be able to edit the site from within Microsoft SharePoint Designer 2010.
  • Click on "All Files" and then "SiteAssets"
  • Right-click in the "SiteAssets" pane to make an "Untitled_1.html" and then click upon it to bring it up in a tab. Here, you can rename "Untitled_1.html" to something better. Please use a .txt name. Make a text file.
  • Click on "Edit File" to edit the file. Strip out the HTML inside and add some Hello World JavaScript like so:
    <script type="text/javascript">
       alert('sup?');
    </script>
  • Save the file with the diskette icon at the upperleft.
  • Go to "Lists and Libraries" and then to your particular list.
  • To one side you will see, within the list's pane, links for:
    1. DispForm.aspx
    2. EditForm.aspx
    3. NewForm.aspx
  • Enter the item you wish to add a web part to.
  • Pick the "Design" tab for the pane that appears and pick the "Insert" tab at the ribbon up top.
  • At the ribbon click: Web Part > More Web Parts... > Content Editor
  • Your web part will appear in the Design
  • Right-click in it and pick "Web Part Properties..."
  • You will see:
    Content Link
    To link to a text file, type a URL.
  • Here, add a route to the .txt file you just made.
  • Save the file with the diskette icon at the upperleft.
  • Go to the root of your SharePoint site in the UI and then navigate to your form. You should be asked: sup?

SharePoint images

SharePoint's images are stored in the hive at C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\IMAGES\

what InfoPath can't do for SharePoint

We have given up on solving the Catastrophic failure error from yesterday. We have concluded that the problem has to do with trying to edit the forms of a list built from a ContentType using custom fields in InfoPath and that as much just isn't possible.

Update: I just spoke to Julie Reynolds and she thought that the problem is that I am pushing the ContentTypes from a Visual Studio deploy process and that InfoPath is finding one of my Guids to be dirty.

Guid makers

http://www.guidgenerator.com/online-guid-generator.aspx seems like a good enough tool to use for randomly generating Guids. There are plenty of comparable tools out there. Another one I found is http://www.famkruithof.net/uuid/uuidgen

Monday, September 10, 2012

export a .wsp

  • Site Actions > Site Settings > Site Actions > Save site as template ...will allow one to export a .wsp from the browser in SharePoint 2010.
  • For a subsite navigate to: http://www.example.com/sites/parent/child/_layouts/savetmpl.aspx

Catastrophic failure

At: List Settings > Form Settings ...One may select the radio button for "Customize the current form using Microsoft InfoPath" and a good preparatory step for using InfoPath and then press the "OK" button. Unfortunately one may also end up with message reading:

The publish operation could not be completed. It cannot be determined if the form template was successdully published. Try publishing form template again, or change the list settings to use the default SharePoint form. Catastrophic failure

Share photos on twitter with Twitpic

Make sure you have these settings at: Site Actions > Site Settings > Site Collection Administration > Site collection features

  • SharePoint Server Enterprise Site Collection features
    Features such as InfoPath Forms Services, Visio Services, Access Services, and Excel Services Application, included in the SharePoint Server Enterprise License.
  • SharePoint Server Publishing Infrastructure
    Provides centralized libraries, content types, master pages and page layouts and enables page scheduling and other publishing functionality for a site collection.

 
 

Make sure you have these settings at: Site Actions > Site Settings > Site Actions > Manage site features

  • SharePoint Server Publishing
    Create a Web page library as well as supporting libraries to create and publish pages based on page layouts.

 
 

That said, I still can't get on the other side of this error... :(

sharepointlogviewer.codeplex.com

http://sharepointlogviewer.codeplex.com/ is a cool tool for browsing SharePoint 2010 logs.

In InfoPath, right click on an item and then select Manage Rules from the Properties tab on the ribbon to add rules.

The "Rules" pane should appear. It will contain a link for defining the conditions for the rule.

Share photos on twitter with Twitpic

In InfoPath, just use the data fields for everything.

Ignore the query fields. (mostly)

Create a section in InfoPath...

...by dragging a folder from the advanced view of the Fields pane into the workspace. Next delete the contents of the section so that it is empty and you may drag other gunk into it. Do not copy and paste the empty section to make another. The sections really correspond the the sections back in the Fields pane. Boo. One pain point I am finding so far is that I cannot find another element that I may set a visibility property upon.

Having written the above, I now have found the control pane on the Home tab may be expanded to show an option for creating a new section.

Microsoft Project Server runs ontop of Microsoft SharePoint

SharePoint is here to stay. It's not Silverlight.

Friday, September 7, 2012

How do I save my InfoPath work for redeployment?

After you deploy to a VM from Visual Studio, you will have an instance of a SharePoint SPSite and you may then start messing with the forms in InfoPath, but aren't you then building a delicate little snowflake trapped at the VM at hand? How may you move your work to other VMs? Don't worry about maintaining your .xsn InfoPath files. Under site settings there is an option for saving as a template that will make one big .wsp file that may then be used to template a new SPSite. The template will include all of your lists and forms. Typically when creating a new web you will pick a template and Team Project is a common template to pick. If you make a new template it will show up as an option in the same place as Team Project. A template, in version 2010, is just a .wsp file. One may reimport templates into Visual Studio to get the code equivalent of the InfoPath magic back in one's Visual Studio solution. From there, the code may be redeployed elsewhere.

SharePoint alerts

at List Items > List > Alert Me ...one may assign alerts to a list so that one is notified by email should a list item be added or updated

Share photos on twitter with Twitpic

I've been "serving my country" at the Financial Services Center of Veterans Affairs on Metropolis as a contractor. This is an excellent environment to be trained in SharePoint 2010 from only knowing ASP.NET if anyone is interested. Ping me. They need people.

Thursday, September 6, 2012

What is InfoPath?

InfoPath is now part of Microsoft Office. It allows you to either create independent forms (which might send an email or write to a database upon submission) or make the forms of SharePoint associated with lists more functional and fancy. It has a drag and drop simple interface that reminds me of ASP.NET web forms and writes everything in XML beneath the hood. One has to have the InfoPath Reader to be able to view the standalone forms, but as of 2007 there is something called Form Services which allow one to view the forms in a browser as a web page and SharePoint utilizes Form Services. In SharePoint, under the List Settings for a List there is a Form settings option where one may check a radio button for: Customize the current form using Microsoft InfoPath. This option should allow you to click upon the Customize Form icon at the List tab under the List tools tab (the same place on the ribbon the List Settings icon is found) to bring up a CRUD form for a list in InfoPath. You will need to use the Number type instead of the Integer type for all applicable fields or you will get an error. To save the form and push XML for your work back to SharePoint, first click the Save diskette icon at the upper left and then click the Quick Publish icon immediately after it. Beyond this, the SharePoint stuff does not behave a whole lot differently than one off InfoPath forms. One may just make a blank template to experiment. One may make fields for forms in the Fields pane. One may drag and drop, onto the work canvas, fields from the Fields pane to create controls or may drag generic controls from a tool pallet. Fields drug in a group end up in a Section together. One may hide and show Sections with Rules later. F5 will bring up the form in a browser for testing. Sound like web forms? The Insert tab has prebuild layouts, the ability to insert hyperlinks and pictures, and so on. A form may be broken up into Views. There is a default ribbon for navigating Views. There is a Data tab where one may click on the Data Connections icon to get a connection to a database, or a SharePoint list (supply a URL for this). You will be walked through a wizard to craft the data context and you will end up with a separate drop down option of fields at the Fields pane showing the data fields. Femi recommends using your own handmade fields at the form itself and then having these forms populate data to and draw data from the data context fields. One may right click on any Control (a field drug to the work area) and see configuration options in a dialog box that appears. At the Data tab in the dialog box one may, for example, populate options from a data context field. Data sources may be used for repeating content and repeating content may thus be used for some mild reporting within a form. The ability to offer search filtering based upon conditions is nested deep within the Control configuration options dialog box. At the Data tab are three options for Rules: Form Load, Form Submit, and Form Inspector. Beyond these one may add rules at Controls. There is a Rules pane to work in for this. This allows things to change upon events. When a certain value in a drop down list is picked, then perhaps a hidden Control could be revealed, for instance. If you are not editing the list at hand in SharePoint but are reaching out to monkey with other SharePoint lists, then you will need to use SharePoint web services.

let others access your SharePoint stuff

Site Actions > Site Permissions ...is the place in SharePoint to grant permissions to others.

Wednesday, September 5, 2012

add subsite in SharePoint

add a subsite in SharePoint at: Site Actions > New Site

Include In Project

If you have a folder full of files and you want to add the folder to a project, in the Solution Explorer, click upon the Show All Files toggle to show the files and folders that are not associated to the project. To associate an item, right click upon it and then pick Include In Project.

Tuesday, September 4, 2012

remember to create a user when prepping a site in IIS

Share photos on twitter with Twitpic

update Web.config to be IIS7-friendly

%systemroot%\system32\inetsrv\APPCMD migrate config nameofisssitewithoutanypathbutwithtrailingslash\

...is a better way to approach this.

more SharePoint

While I am thinking about it, you will also need to set "Sandbox Solution" to false at the same locale you set the Site URL and from within Server 2008, at the start menu, type "Central Administration" to bring up SharePoint 2010 Central Administration where you may go to: Application Management > Create site collections ...to make a spweb

Site URL

With a SharePoint project set to the startup project in Visual Studio, click on the project in the Solution Explorer and press F4 to launch the Properties pane where you may set the Site URL. Make sure the site you are deploying to exists.

VMs for SharePoint

It is preferred to develop for SharePoint on a VM running Microsoft Windows Server 2008 R2 as one has to actually install SharePoint in the development environment and SharePoint is heavy. One can install SharePoint at Windows 7, but I get the impression Server 2008 is a better, easier fit. Having the SharePoint environment walled off from everything else you work on is wise. The SharePoint stuff could muck up the environment of everything else.

Monday, September 3, 2012

long-tail link routing made easier in ASP.NET

foo/{bar} could be replaced with foo-{bar} here!

passing variables in web forms routing

I found this which illuminated that passing variables in web forms routing is much easier than I was making it. Expanding upon what I wrote here, TryToGetToMe.aspx looks like:

<%@ Page Language="C#" AutoEventWireup="true"
      CodeBehind="TryToGetToMe.aspx.cs"
      Inherits="WebFormsRoutingExample.TryToGetToMe" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
   <head runat="server">
   <title>You made it here!</title>
   </head>
   <body>
      <form id="form1" runat="server">
         <div>
            <p>You made it here!</p>
            <p>The variable is: <%=Bar %></p>
         </div>
      </form>
   </body>
</html>

 
 

TryToGetToMe.aspx.cs looks like:

using System;
namespace WebFormsRoutingExample
{
   public partial class TryToGetToMe : System.Web.UI.Page
   {
      public string Bar;
      protected void Page_Load(object sender, EventArgs e)
      {
         Bar = Page.RouteData.Values["bar"] as string;
      }
   }
}

starting to learn web forms routing

Attempting to mimic this example, I made a new web forms project in Visual Studio and I made the Web.config end like so:

      <httpModules>
         <add name="RoutingModule" type="System.Web.Routing.UrlRoutingModule,
               System.Web.Routing, Version=3.5.0.0, Culture=neutral,
               PublicKeyToken=31bf3856ad364e35"/>
      </httpModules>
   </system.web>
   <system.webServer>
      <modules runAllManagedModulesForAllRequests="true">
         <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule,
               System.Web.Routing, Version=3.5.0.0, Culture=neutral,
               PublicKeyToken=31BF3856AD364E35" />
      </modules>
      <handlers>
         <add name="UrlRoutingHandler" preCondition="integratedMode" verb="*"
               path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler,
               System.Web, Version=2.0.0.0, Culture=neutral,
               PublicKeyToken=b03f5f7f11d50a3a" />
      </handlers>
   </system.webServer>
</configuration>

 
 

I wrote this class which inheirts from IRouteHandler:

using System.Web;
using System.Web.Compilation;
using System.Web.Routing;
using System.Web.UI;
namespace WebFormsRoutingExample.Objects
{
   public class MyCustomRouteHandler : IRouteHandler
   {
      private string _virtualPath;
      
      public MyCustomRouteHandler(string virtualPath)
      {
         _virtualPath = virtualPath;
      }
      
      public IHttpHandler GetHttpHandler(RequestContext requestContext)
      {
         var display = BuildManager.CreateInstanceFromVirtualPath(_virtualPath,
               typeof(Page)) as IHttpHandler;
         return display;
      }      
   }
}

 
 

Global.asax.cs looks like this:

using System;
using System.Web.Routing;
using WebFormsRoutingExample.Objects;
namespace WebFormsRoutingExample
{
   public class Global : System.Web.HttpApplication
   {
      void Application_Start(object sender, EventArgs e)
      {
         RegisterRoutes();
      }
      
      void Application_End(object sender, EventArgs e)
      {
      }
      
      void Application_Error(object sender, EventArgs e)
      {
      }
      
      void Session_Start(object sender, EventArgs e)
      {
      }
      
      void Session_End(object sender, EventArgs e)
      {
      }
      
      private static void RegisterRoutes()
      {
         RouteTable.Routes.Add("EasyTest", new Route("foo/{bar}", new
               MyCustomRouteHandler("~/TryToGetToMe.aspx")));
      }
   }
}

 
 

So far I have been able to get routes that start with "foo" to route to TryToGetToMe.aspx, but I have had less luck in passing the bar variable denoted in curly brackets. I was unable to mimic the interface-inheirting-from-interface trickery that the example I copied from used. More soon.