Apart from linq, this extension saves me more time than any other syntactic sugar.
public static class Extension { public static bool Like(this string str, string str1) { if (String.IsNullOrEmpty(str) || String.IsNullOrEmpty(str1 )) return (String.IsNullOrEmpty(str) && String.IsNullOrEmpty(str1)); else return str.Equals(str1, StringComparison.InvariantCultureIgnoreCase); } }
Usage is simple.
instead of having to write:
if (str.Equals(str1, StringComparison.InvariantCultureIgnoreCase))
you can write
if (str.like(str1))
And not have to worry about null exceptions.
Enjoy!
A good test of a web framework is to see how it handles select boxes. It requires managing the list, the selected item across several states, be easily styled, be easily ajax-ed, and connect to a data store.
I like using Enums for static data, but they are a bit limited without a description value, you end up with select options labeled “ItemName ” instead of ”Human Friendly Item Name”.
Binding an enum to a dropdown is well documented. Adding descriptions to enums is also well documented. Here is a way to have enums with descriptions into a dropdown.
Your Enum
The Razor
This function will turn your enum into an IEnumerable<SelectListItem>
Of course shortly after finishing this I found a great post on StackOverflow about making html helpers which results in an even prettier finish in razor, but requires a few extra helpers.
Ever used the definition list tag? Me neither, yet it’s fully supported in all the browsers.
turns into this:
From w3schools: “ The <dl> tag defines a definition list. The <dl> tag is used in conjunction with <dt> (defines the item in the list) and <dd> (describes the item in the list).”
Well now i’ve used it.
CORS was really part of the inspiration for ServerCyde. AJAX is cool, it lets you make the web more responsive, but it only connects to the site that you built. If you wanted to consume the services of a third party then you would have to proxy it over your server or compromise on the functionality that you can offer. As more and more digital services get turned into API services (life graphs, url minification, image manipulation, data storage…) browsers will evolve to allow greater interconnectedness without sacrificing security. Right now each browsing is either trying their own implementation out (is it netscape vs IE all over again) or at some stage op implementing CORS standards, or web sockets. In the mean time I wanted a solution that worked now and supported all of the HTTP verbs so I had to implement one myself.
What it came down to was simple enough. Hidden iFrames and window.href polling. You see, when you open a site in an iframe the parent can only read the URL if the domains match. So what i did was have my server redirect back to your domain with a token in the URL that you could use to make a plain JSONP request for the data. This model, works in every browser, lets you POST with cookies, and even allows a connection to stay open for a COMET implementation.
You can check it out in action here: http://servercyde.com/Developers/
Get the code from GitHub here: https://github.com/easymovet/ServerCyde/wiki
And see a presentation of it’s implementation, that I delivered to JavascriptMN at Refactr in November.
Example: EXEC usp_TableToClass ‘MyTable’
*/
@table_name SYSNAME
AS
SET NOCOUNT ON
DECLARE @temp TABLE
(
sort INT,
code TEXT
)
INSERT INTO @temp
SELECT 1, ‘public class ‘ + @table_name + CHAR(13) + CHAR(10) + ‘{‘
INSERT INTO @temp
SELECT 2, CHAR(13) + CHAR(10) + ‘#region Constructors’ + CHAR(13) + CHAR(10)
INSERT INTO @temp
SELECT 3, ‘public ‘ + @table_name + ‘()’
+ CHAR(13) + CHAR(10) + ‘{‘
+ CHAR(13) + CHAR(10) + ‘}’
INSERT INTO @temp
SELECT 4, ‘#endregion’ + CHAR(13) + CHAR(10)
INSERT INTO @temp
SELECT 5, ‘#region Public Properties’ + CHAR(13) + CHAR(10)
INSERT INTO @temp
SELECT 6, ‘public ‘ +
CASE
WHEN DATA_TYPE LIKE ‘%CHAR%’ THEN ‘string ‘
WHEN DATA_TYPE LIKE ‘%INT%’ THEN ‘int ‘
WHEN DATA_TYPE LIKE ‘%DATETIME%’ THEN ‘DateTime ‘
WHEN DATA_TYPE LIKE ‘%BINARY%’ THEN ‘byte[] ‘
WHEN DATA_TYPE = ‘BIT’ THEN ‘bool ‘
WHEN DATA_TYPE LIKE ‘%TEXT%’ THEN ‘string ‘
WHEN DATA_TYPE = ‘MONEY’ THEN ‘decimal ‘
ELSE ‘object ‘
/*END + ‘_’ + COLUMN_NAME + ‘;’ */
END + COLUMN_NAME + ‘;’
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @table_name
ORDER BY ORDINAL_POSITION
INSERT INTO @temp
SELECT 7, ‘#endregion’ +
CHAR(13) + CHAR(10)
INSERT INTO @temp
SELECT 8, ‘public ‘ + @table_name + ‘(int ‘ + @table_name + ‘ID)’
+ CHAR(13) + CHAR(10) + ‘{‘ + CHAR(13) + CHAR(10) + ‘
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["YourConnectionStringKeyValue"].ToString())) {‘ + CHAR(13) + CHAR(10) + ‘
using (SqlCommand cmd = new SqlCommand(“Select * from ‘+@table_name+‘ where ‘+@table_name+‘ID = @id”, conn)) {‘ + CHAR(13) + CHAR(10) + ‘
cmd.Parameters.AddWithValue(“id”, ‘+@table_name+‘ID);’ + CHAR(13) + CHAR(10) + ‘
conn.Open();’ + CHAR(13) + CHAR(10) + ‘
using (SqlDataReader dr = cmd.ExecuteReader()) {‘ + CHAR(13) + CHAR(10) + ‘
if (dr.Read())’ + CHAR(13) + CHAR(10) + ‘
{‘
INSERT INTO @temp
SELECT 9, ‘this.’ + COLUMN_NAME + ‘ = ‘ +
CASE
WHEN DATA_TYPE LIKE ‘%CHAR%’ THEN ‘Convert.ToString(dr["' + COLUMN_NAME + '"])’
WHEN DATA_TYPE LIKE ‘%INT%’ THEN ‘dr["' + COLUMN_NAME + '"] == DBNull.Value ? new int() : Convert.ToInt32(dr["' + COLUMN_NAME + '"])’
WHEN DATA_TYPE LIKE ‘%DATETIME%’ THEN ‘dr["' + COLUMN_NAME + '"] == DBNull.Value ? new DateTime() : Convert.ToDateTime(dr["' + COLUMN_NAME + '"])’
WHEN DATA_TYPE LIKE ‘%BINARY%’ THEN ‘dr["' + COLUMN_NAME + '"] == DBNull.Value ? new byte() : (byte[])dr["' + COLUMN_NAME + '"])’
WHEN DATA_TYPE = ‘BIT’ THEN ‘Convert.ToBoolean(dr["' + COLUMN_NAME + '"])’
WHEN DATA_TYPE LIKE ‘%TEXT%’ THEN ‘Convert.ToString(dr["' + COLUMN_NAME + '"])’
WHEN DATA_TYPE = ‘MONEY’ THEN ‘dr["' + COLUMN_NAME + '"] == DBNull.Value ? new decimal() : Convert.ToDecimal(dr["' + COLUMN_NAME + '"])’
WHEN DATA_TYPE = ‘DECIMAL’ THEN ‘dr["' + COLUMN_NAME + '"] == DBNull.Value ? new decimal() : Convert.ToDecimal(dr["' + COLUMN_NAME + '"])’
WHEN DATA_TYPE = ‘FLOAT’ THEN ‘dr["' + COLUMN_NAME + '"] == DBNull.Value ? new double() : Convert.ToDouble(dr["' + COLUMN_NAME + '"])’
ELSE ‘ –check: ‘ + COLUMN_NAME
/*END + ‘_’ + COLUMN_NAME + ‘;’ */
END + ‘;’ + CHAR(13) + CHAR(10)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @table_name
ORDER BY ORDINAL_POSITION
INSERT INTO @temp
SELECT 10, ‘ } } } } } ‘
/* insert */
INSERT INTO @temp
SELECT 11, ‘public int insert(‘
INSERT INTO @temp
SELECT 12,
CASE
WHEN DATA_TYPE LIKE ‘%CHAR%’ THEN ‘string _’ + COLUMN_NAME + ‘,’
WHEN DATA_TYPE LIKE ‘%INT%’ THEN ‘int _’ + COLUMN_NAME + ‘,’
WHEN DATA_TYPE LIKE ‘%DATETIME%’ THEN ‘DateTime _’ + COLUMN_NAME + ‘,’
WHEN DATA_TYPE LIKE ‘%BINARY%’ THEN ‘byte[] _’ + COLUMN_NAME + ‘,’
WHEN DATA_TYPE = ‘BIT’ THEN ‘bool _’ + COLUMN_NAME + ‘,’
WHEN DATA_TYPE LIKE ‘%TEXT%’ THEN ‘string _’ + COLUMN_NAME + ‘,’
WHEN DATA_TYPE = ‘MONEY’ THEN ‘decimal _’ + COLUMN_NAME + ‘,’
WHEN DATA_TYPE = ‘DECIMAL’ THEN ‘decimal _’ + COLUMN_NAME + ‘,’
ELSE ‘ –check: ‘ + COLUMN_NAME
END
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @table_name
ORDER BY ORDINAL_POSITION
INSERT INTO @temp
SELECT 13, ‘ )’ + CHAR(13) + CHAR(10) +‘
{‘ + CHAR(13) + CHAR(10) +‘
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CONNSTR"].ToString())) {‘ + CHAR(13) + CHAR(10) +‘
using (SqlCommand cmd = new SqlCommand(@”‘ + CHAR(13) + CHAR(10) +‘
INSERT INTO [' + @table_name + '] (
‘
INSERT INTO @temp
SELECT 14, ‘[' + COLUMN_NAME + '],’
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @table_name
ORDER BY ORDINAL_POSITION
INSERT INTO @temp
SELECT 15, ‘ ) VALUES (‘
INSERT INTO @temp
SELECT 16, ‘[' + COLUMN_NAME + '],’
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @table_name
ORDER BY ORDINAL_POSITION
INSERT INTO @temp
SELECT 17, ‘ )
SELECT SCOPE_IDENTITY() AS ‘ + @table_name + ‘ID “, conn)) {‘ + CHAR(13) + CHAR(10) +‘
‘
INSERT INTO @temp
SELECT 18, ‘cmd.Parameters.AddWithValue(“@’ + COLUMN_NAME + ‘”,’ + COLUMN_NAME + ‘);’
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @table_name
ORDER BY ORDINAL_POSITION
INSERT INTO @temp
SELECT 19, ” + CHAR(13) + CHAR(10) +‘
conn.Open();
return (int)cmd.ExecuteScalar();’ + CHAR(13) + CHAR(10) +‘
}}}’ + CHAR(13) + CHAR(10)
INSERT INTO @temp
SELECT 20, ‘
public void Update()’ + CHAR(13) + CHAR(10) +‘
{‘ + CHAR(13) + CHAR(10) +‘
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CONNSTR"].ToString())) {‘ + CHAR(13) + CHAR(10) +‘
using (SqlCommand cmd = new SqlCommand(@”‘ + CHAR(13) + CHAR(10) +‘
UPDATE
['+ @table_name +']
SET
‘
INSERT INTO @temp
SELECT 21, ‘[' + COLUMN_NAME + '] = @’ + COLUMN_NAME + ‘,’
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @table_name
ORDER BY ORDINAL_POSITION
INSERT INTO @temp
SELECT 22, ‘
WHERE
['+ @table_name + 'ID] = @’+ @table_name + ‘ID
“, conn)) {‘ + CHAR(13) + CHAR(10) +‘
‘
INSERT INTO @temp
SELECT 23, ‘cmd.Parameters.AddWithValue(“@’ + COLUMN_NAME + ‘”,’ + COLUMN_NAME + ‘);’ + CHAR(13) + CHAR(10)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @table_name
ORDER BY ORDINAL_POSITION
INSERT INTO @temp
SELECT 24, ‘cmd.ExecuteNonQuery(); ’ + CHAR(13) + CHAR(10) + ‘
}}}}’
SELECT * FROM @temp
ORDER BY sort
First i tried consuming web services that serialized structs into XML but now I got it spewing JSON which means no more escaping strings for javascript. When dumping large bits of content into a page XML made sense to me since it was already HTML escaped, but if i wanted to send commands in the same message i would have to make sure it was JS safe too, Having an un-escaped string will kill the JS but a pooly formatted HTML will probably survive (nat that its then a an excuse for pooly format HTML), in fact it may make sense to return an XML type in the struct, i’ll have to look into that. So here is how to make it workie:
in the .asmx
using System;
using System.Web.Script.Services;
using System.Web.Script.Serialization;namespace mcpV2
{
///
/// Summary description for WebService2
///[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[ScriptService]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService2 : System.Web.Services.WebService
{
public struct tests
{
public string thestr;
public int theint;}
[WebMethod]
[ScriptMethod]
public tests HelloWorld()
{
tests ttt = new tests();
ttt.theint = 9;
ttt.thestr =”hello worls”;return ttt;
}
}
}
This will spit out:
{“d”:{“__type”:”mcpV2.WebService2+tests”,”thestr”:”hello worls”,”theint”:9}}
I called it with the JQUERY .ajax method :
$.ajax({
type: “POST”,
url: “webservice2.asmx/HelloWorld”,
beforeSend: function(xhr) {
xhr.setRequestHeader(“Content-type”,
“application/json; charset=utf-8″);
},
dataType: “json”,
success: function(msg) {
// Insert the returned HTML into the .
$(‘#Div1′).text(msg.d.thestr);
}
});
I added some other stuff for error catching but you get the idea. I had some trouble with Web services making huge memory leaks with the XMLserializer, hopefully the .NET AJAX serializer is not a memory hog…
.net web services can return structs of any simple datatypes as nicely serialized XML and jquery can consume that like this
struct usefullStuff {
string[] commands;
string content;
}
$(“commands string”, returnedXML).each(function() { eval($(this).text()); });
$(“content”, returnedXML).each(function() { $(“body”).append($(this).text()) ; });