Monday, July 02, 2012

WCF KnownTypes and ServiceKnownTypes

 

When using a compiler one gets used to polymorphism.

How would you describe polymorphism? Polymorphism for data objects is little more than rearranging and adding data to a form.

I'd say someone invites it over to a party, you have the PartInfo class

public class PartyInfo
{
public string Address { get; set; }
public string Phone { get; set; }
}


Sara, your friend calls you up and informs you about three other parties, however these parties have other information, one has Theme information, another has data about the DJ, and a third includes ages of the people there.

public class PartyDJData : PartyInfo
{
public string DJ { get; set; }
public string PreviousPerformances { get; set; }
public string MusicTypesPlayed { get; set; }
}

public class PartyTheme : PartyInfo
{
public string Theme { get; set; }
public bool IsDressup { get; set; }
public bool IsDiscountForDressup { get; set; }
}

public class PartyAges: PartyInfo
{
int[] Ages { get; set; }
}
You're a very diligent person, and want to write this down.  Say you get a pad and paper, and start writing.
Party1:
Address : Yavne 24
Phone: 5555-FFF
 
Party2:
DJ : Joe Schmoe / Previous : saras bash, MusicTypes = House/ClubTrance.
Address: 123 kressent, drv
Phone: XXX-YYY
 
Party3:
Theme: Angels and demons, IsDressup = yeah, IsDiscountForDressup = yeah
Address = 154 vos str
phone: FFF-YYY
 
Party 4: 
Address : Hilton Hotel on the beach
Ages { 25-35}
Phone : GGG-XXX
 
 
now when you talk to your friend Adam, you tell him
You: “Hey Adam, and got the skinny on the good parties, get a pen!”
Adam: Ok, shoot!
Party1: {Address : Yavne 24, Phone: 5555-FFF}
Adam: ok cool
Party2: {Address: 123 kressent, drv, Phone: XXX-YYY}, oh and the dj is DJ “Joe Schmoe” who has Previously done saras bash he plays House/ClubTrance.
Adam: wait. Whos the DJ at the first party ? 
You: I don’t know
Adam: ok, next?
You: It’s a theme party! Theme: Angels and demons, it’s Dressup not required but you get DiscountForDressup!
Address = 154 vos str, phone: FFF-YYY
Adam: Whos the DJ ?
You: Dunno!
Adam: Is the party on kressent themed too ?
You: goo question, I think not.
Adam: Ok, lets continue with the list, then we can divide forces and fill out the rest of the info.
You: It’s ok theres only one more party, my sister told me about it.
its at Hilton on the beach man! oh and it caters to 25-35 so you will finally find someone to teach you some manners!
Adam:Yeah Whatever, so who’s the DJ ?
You: I dunno.
Adam: DUDE!!!!!!

Play-by-play serialization

so what happened here?
You had all kinds of different party the info data which you listed under the party info DTO.  They all derived from PartyInfo, but are not exactly the same and each have different attributes which Adam is not expecting.

When Adams started talking to you on the phone he could've asked you what kind of data are you gonna give me because than a I need to set up my pad correctly.  To which you might answer a different answer for every week.  Sometimes you had DJ information sometimes you have Theme information. !!  Sometimes you had both !!

Sometimes you had none.

But you're not willing to commit.  Not willing to tell him all the options.  So he has no way of knowing.

Adam expected you to give him the same information and details for every party.  He actually created the party info class and was trying to fill it up, but every time you added more details, and you didn't tell him in advance what kind of options to expect, so all this back and forth was in trying to figure out what to do with the new information and where to stick it in his pad!

What basically happened was he was distraught.
 


The KnownType Attribute


By relaying some information at the very beginning we could have helped Adam make sense of information.


If they would have written

[KnownType(typeof(PartyDJData))]
[KnownType(typeof(PartyTheme))]
[KnownType(typeof(PartyAges))]
public class PartyDataForTonight
{
public IEnumerable< PartyInfo > parties { get; set; }
}


Adam could have tried to figure out the data on his own.


So why can’t you just use Polymophism ?


Well Polymorphism makes more sense when you have a the TYPE of the instance at hand.


sometimes this is not the case.


The Deserializer (Adam) will go over the data and try to understand which PartyInfo you were referring to. For some reason they did not try the “try polymiphism first and if stuck shout” the moved directly to the “shout” part.


if you send a bunch of PartyInfo objects down the wire they will fail in deserialization. what you need to do is add the KnownType to them. his will help with understanding how to deal with them and what to deserialize given the chance.


this will prove to be performance degrading as for every “PossibleType” the deserializer will have to stop, ponder what class to deserialize this too and only then deserialize.


If


next time I’ll talk about ServiceKnown Type.

Tuesday, June 26, 2012

DBS Stuff

 

Files

Located under Files

image

clip_image001

Data: Initial at least 3 GB | Autogrowth, at least 100MB each iteration. Better to use in Megabytes rather than in Percent

Log: Initial size 7GB |Autogrowth at least 100MB each iteration.

FILE GROUPS

Different files, preferably on different machines

Allows tables, and in general SQL objects, to be created in different files

CREATE TABLE [dbo].[Status](
    [StatusId] [smallint] IDENTITY(1,1) NOT NULL,
    [Type] [nchar](50) NOT NULL,
CONSTRAINT [PK_Status] PRIMARY KEY CLUSTERED
(
    [StatusId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

 

Brown is the index Filegroup

Purple is the Table FileGroup

Primary is the default file group when none are created

 

LOG

Use a sequential writing hard disk - such as Raid 0 or Raid 1.

Full – saves everything, incl all bulk inserts (values), is reduced only when db is backed up| used for differential backups.

Bulk – saves almost everything, not including bulk inserts i.e. It only saves the size of the bulk insert without the data itself.

Simple – a cyclical log file that only saves data not yet committed as well as last check points.

DATA

User random access writing hard disk – such as Raid 5

Hebrew

Use collation "HEBREW_CI_AS"

Collation however only works for varchar

In general than adding data in Unicode don't forget to use N'מידע חשוב'! The N stands for Unicode.

SQL DDL

Decimal (Scale, Precision)

Scale – number of digits

Precision – number of digits (of scale) which are decimal.

SQL prefers INT over other types in general.

 

Nchar / Varchar

Nchar – char that is Unicode (not dynamic)

varchar - Variable (dynamic) sized data strings. (Penalty of size of string – 2bytes)

Nvarchar – Dynamic Unicode string (incl the penalty)

Unicode – takes up 2 chars for every char (2X the space)

Misc

Add Indexes to most ForeignKey constraints

DataBase projects

CLR allows to add Dot.NET CLR dlls that can plugin and create new "Functions", that run using Dot.Net engine per row (like any sql function).

To create ->

Visual Studio è New Projectè DataBase è SqlServerè CLR Database project

Service Broker

Like a crippled msmq.

Includes an Event driven DeQueue that can trigger a stored procedure

You can configure Max currents

Is Transactionable {with rollback support }

Tuesday, June 05, 2012

Publish and deploy

For those still looking, I had to make sure to:

  • Specify port 8172, use the default service name (msdeploy.axd), use https and check the box to allow untrusted certificates in the publish service url from Visual Studio:https://serveraddress:8172/msdeploy.axd

Also, I found this IIS article to be extremely helpful for setting up the service.

Pasted from <http://stackoverflow.com/questions/5490478/vs-2010-publish-using-web-deploy>

http://www.microsoftpdc.com/2009/FT56?type=wmvhigh

http://learn.iis.net/page.aspx/516/configure-the-web-deployment-handler/

When faced with :

Web deployment task failed.(Could not complete the request to remote agent URL 'https://dev1:8172/msdeploy.axd?site=Default web site'.)

Could not complete the request to remote agent URL 'https://dev1:8172/msdeploy.axd?site=Default web site'.

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.The remote certificate is invalid according to the validation procedure.

clip_image001

The Service URL without the http:// defaults to https://

BUT, because Https means Secure, we need a certificate.

However the IIS is not configured with a certificate, so it fails

You need to check the
"Allow untrusted certificate" checkbox

Sunday, April 08, 2012

Web Deployment on IIS7

 

Transforms Web.Config.Release

http://vishaljoshi.blogspot.com/2009/02/web-deployment-with-vs-2010-and-iis.html

 

Install IIS7 Deployment

download Web Platform Installer for IIS7, only way I managed was to install chrome, and then download it.

image YAY microsoft, lock me out and make me install an UNSAFE browser just to do basic admin IT work.

http://technet.microsoft.com/en-us/library/dd569059.aspx

image

image

select custom

image

http://learn.iis.net/page.aspx/1022/how-to-configure-a-site-for-publishing-with-web-deploy/

Web Deploy 2.0 includes a new UI in IIS Manager to configure an IIS site for Web Deploy publishing. This UI serves two purposes:

  1. Sets up file system permissions to enable the Web Deploy publishing service to publish to the site
  2. Generates a publish settings file which can be used in tools like WebMatrix or Visual Studio 2010 to publish to the site without having to enter publishing settings manually

Let's say that we want to grant a local Windows user "JohnDoe" publishing access to the IIS site, contoso.com:

  1. Start IIS Manager by clicking Start > Run and typing "inetmgr.exe"
  2. Connect to the server you want to manage.
  3. Expand the Sites node and right click "contoso.com"
  4. Click Deploy > Configure for Web Deploy Publishing...
  5. The following UI will show - you can simply click "Setup" and the currently logged-in user will be granted Web Deploy publishing permissions.

 

Now try to publish from VS STUDIO 2010

If you get this error Could not load file or assembly bla bla bla one of its dependencies. An attempt was made to load a program with an incorrect format it might be a 32bit/64bit issue

Go to IIS -> Application Pool -> Advance Settings -> Enable 32-bit Assemblies

http://stackoverflow.com/questions/41449/i-get-a-an-attempt-was-made-to-load-a-program-with-an-incorrect-format-error-o

image

 

And now FINALLY

I works

Tuesday, April 03, 2012

Log4Net Configuration trouble

Recently i had some log4net configuration trouble

log4net has a feature in its configuration file where it tries to read Configuration name tags from the config file and locates them as writable properties on the class (Logger/Appender etc..) using reflection.

the function used is

protected void log4net.Repository.Hierarchy.XmlHierarchyConfigurator.SetParameter(XmlElementelement,objecttarget)
this function locates the property for you and updates its data if it finds it if not it fills your screen and logs with garbage until its fixed!
It will even locate the property if you write it in the wrong case.
However, it does not help you in locating your error. I do not expect log4net developers to write a “google-style” {did you mean xxx} function. But I think they could have a better log response
instead of a bland
LogLog.Error(declaringType, "XmlHierarchyConfigurator: Cannot find Property [" + name + "] to set object on [" + target.ToString() + "]");


It would be nicer (I think) to write something like

LogLog.Error(declaringType,
string.Format(
"{2}Reflection did not find Writeable Property/Field named [{0}]. Check ObjectBrowser for class {1} and see what writable attributes/fields exist. maybe misspelled? You XML Error is located in {3}"
, name, target.ToString(), "XmlHierarchyConfigurator", element.ParentNode.InnerXml)
);

which would give something like

XmlHierarchyConfiguratorReflection did not find Writeable Property/Field named [hello]. Check ObjectBrowser for object log4net.Repository.Hierarchy.DefaultLoggerFactory+LoggerImpl and see what writable attributes/fields exist. maybe misspelled? You XML Error is located in <level value=\"Info\" /><hello value=\"4\" /><appender-ref ref=\"LogFileAppender\" /><appender-ref ref=\"RSLogFileAppenderInfo\" /><appender-ref ref=\"RSLogFileAppenderFatal\" />"


for the error of adding the field “hello” to the XML.


This is at the very least a more helpful comment.


At least now I know what to look for. any attribute in log4nt configuration must have a real writeable field/property in the log4net object hierarchy.


good to know.


 


Mickey Perlstein

Preview Pane : Windows 7

 

forgot all about this one

taken from http://www.winvistaclub.com/t81.html

But, if you have a custom file type; and wish to register a plain text or a multimedia preview handler, for this custom file type, you can do so using this utility.

Winhelponline’s PreviewConfig Utility allows you add or remove preview handler for a file type. Its a very useful and a easy-to-use utility. Worth a check-out. Do read its ReadMe file first.

Friday, March 02, 2012

Console write Color Encoder

 

Sometimes I use a console logger, for simple apps.and it’s more important to see the data than the text for a programmer.

I have written a simple Console encoding app that spits color encoded console lines to the console.

I may some day write a log4net logger that does this, but for now:

public static string EncodeConsole(string message
, params object[] args)
{



string content = message;
string pattern = @"{(.*?)}";
MatchCollection mc = Regex.Matches(content, pattern
,RegexOptions.Compiled); //compiled is faster

#region make better Exception that string.format
if (mc.Count > args.Length)
{
string format1 = "you supplied {0} params, but require {1} in the template";
///erro message
string err = string.Format(format1, args.Length, mc.Count);
throw new FormatException( err );
}
#endregion

string encoded = message;
foreach (Match item in mc)
encoded = encoded.Replace(item.Value, ",#,").Replace(",,", ",");

var arr = encoded.Split(',');
string out_ = "";
int matchnum = 0;

for (int i = 0; i < arr.Length; i++)
{
if (arr[i][0] == '#')
{
Console.ForegroundColor = ConsoleColor.White;
Console.BackgroundColor = ConsoleColor.Blue;
var oldmatch = mc[matchnum].Value;
var g = oldmatch.Split(':');

//will always be 0 for data
string match = "{0}";
if (g.Length > 1)
match = "{0:" + g[1];

var data = string.Format(match, args[matchnum]);
arr[i] = data;
matchnum++;
}
else
Console.ResetColor();


Console.Write(arr[i]);
out_ += arr[i];

}
Console.WriteLine("");

return out_;
}



Tuesday, February 14, 2012

Visual Studio TFS very slow

It so happens that in Visual studio, the connection to a TFS server is through a possible proxy server. (A default one)

 

If you VS is slow to take TFS,

go to the

Visual Studio 10.0/Common7/IDE/devenv.exe.config file

go to the bottom

locate <system.net>

and add

    <system.net>
    <defaultProxy enabled="false" />
        <settings>
            <ipv6 enabled="true"/>
        </settings>
    </system.net>
    <appSettings>
        <add key="TestProjectRetargetTo35Allowed" value="true" />
    </appSettings>
</configuration>

this will stop it from looking for your TFS server on the internet