Twitter and the painful OAuth API

I Finally manage to get it to works. My previous manual code does not work.

Twitter will give you painful 401. but thanks to TweetSharp , I can get it up and running in just 10 minutes

Cool TweetSharp

Share this post: | | | |
Posted by cipto with no comments

How to Upgrade from CRM 4 to 2011

  • ·First you need to upgrade from crm 4 to 2011. The current live instance.
  • After that Put all the changes to unmanaged Solution, and start using Solution for all customization.
  • ISV can be upgraded succesfully, Detail
  • Javascript you have to use a converter tool. Js changed alot in 2011 and will break the 4th version.Tool
  • Yes avoid Database changes. Just get on step1 changes into solution
  • Plugin from Upgrade result to Solution
  • (Optional,if you don’t wont to change the code and Just a reference issue) Change the machine.config
  • Fix what Breaks
Share this post: | | | |
Posted by cipto with no comments

BlogEngine .NET how to Create Blog automatically for each user

First have the tables in 1 database. after that Change the Services in BlogEngine.NET source

Add this to the services

AppCode\Blog

[WebMethod]
public JsonResponse SaveBlogAsAdmin(
string blogId,
string copyFromExistingBlogId,
string blogName,
string hostname,
bool isAnyTextBeforeHostnameAccepted,
string storageContainerName,
string virtualPath,
bool isActive,string username,string password)
{
Security.ImpersonateUser(username, password);
Security.DemandUserHasRight(Rights.AccessAdminPages, true);
Guid existingId = Guid.Empty;
Blog blog = null;
if (!string.IsNullOrWhiteSpace(blogId) && blogId.Length == 36)
{
existingId = new Guid(blogId);
blog = Blog.GetBlog(existingId);
}
string message;

if (blog == null)
{
// new blog

blog = Blog.CreateNewBlog(copyFromExistingBlogId, blogName, hostname, isAnyTextBeforeHostnameAccepted, storageContainerName, virtualPath, isActive, out message);

if (blog == null || !string.IsNullOrWhiteSpace(message))
{
return new JsonResponse() { Message = (message ?? "Failed to create the new blog.") };
}

return new JsonResponse() { Success = true, Message = blog.Id.ToString()};
}
else
{
// update to an existing blog.

blog.Name = blogName;

blog.VirtualPath = virtualPath;
blog.IsActive = isActive;
blog.Hostname = hostname;
blog.IsAnyTextBeforeHostnameAccepted = isAnyTextBeforeHostnameAccepted;

// intentionally not updating StorageContainerName for an update. this would
// involve renaming the folder on disk, or DB changes (DB changes are not
// likely). if requested, this can be done, but should probably be done as
// a separate "Rename" process/action.


blog.Save();

return new JsonResponse() { Success = true, Message = "Blog was updated." };
}
}

Now call this service using the PrimaryBlog Administrator credential. than Add new user and Role to the BlogEngine Database.

Done

Share this post: | | | |
Posted by cipto with no comments

How to work with Plugin in CRM 2011

After you installed the DeveloperToolkit in SDK. you’ll have the solution template and CRM Explorer directly in your vs.

You will have default class called Plugin, it’s there to make your life easier. Inherit from there, and you shall have localContext which you can access the OrganizationService, Trace, PostImageEntitiies, and PreImageEntities.

Right click on the entity you wanted to on CRM Explorer. and click Create plugin. or do manually if you already understand what to change.

Now you need to understand the Pipeline Stage and Message.

message is pretty straightforward, on Create/Delete/Update of entity

Now Pipeline Stage is very crucial to grasp the understanding.

there are 3:

Pre-Validation

Pre-Operation

Main Operation

Post-Operation

Pre meaning still in transaction, But prior the Main operation. in other words It’s not saved yet .

Main operation is where all the changes of fields such as Create,Update,Delete is submitted/applied to database

Post operation happens after it. So carefully put your logic on pre or post really is the key.

Plugin has 2 minutes of time execution, after that it will continue to next one.

so be sure to not put lengthy operation there.

 

It is advice to use the PreImageEntities and PostImageEntities for performance , instead of retrieve and retrivemultiple .

preimageentities contains field before the changed, and post after

 

Debug can be done by using the sandbox and the other part is just to put on Trace and then Throw InvalidPluginexception.

 

Share this post: | | | |
Posted by cipto with no comments

How to Block anonymous from Looking at the Post , BlogEngine .Net

The powerful BlogEngine .Net , is on his extension ability.

Just post to a class .cs on App_code\Extension\

You will be able to extend it in a way you wanted to.

To block anonymous from looking at your post:

http://blog.lavablast.com/post/2008/08/13/BlogEnginenet-Post-Security.aspx

Modified a bit, cause you don’t need that Role checking code, and you’re good

using System;

using BlogEngine.Core;

using BlogEngine.Core.Web.Controls;

using BlogEngine.Core.Web.Extensions;
using System.Web.Security;


/// <summary>

/// Summary description for PostSecurity

/// </summary>

[Extension("Checks to see if a user can see this blog post.",

"1.0", "<a href=\"http://www.lavablast.com\">LavaBlast.com</a>")]

public class PostSecurity
{

static protected ExtensionSettings settings = null;



public PostSecurity()
{

Post.Serving += new EventHandler<ServingEventArgs>(Post_Serving);



ExtensionSettings s = new ExtensionSettings("PostSecurity");



s.AddParameter("Role", "Role", 50, true);

s.AddParameter("Category", "Category", 50);



// describe specific rules for entering parameters

s.Help = "Checks to see if the user has any of those roles before displaying the post. ";

s.Help += "You can associate a role with a specific category. ";

s.Help += "All posts having this category will require that the user have the role. ";

s.Help += "A parameter with only a role without a category will enable to filter all posts to this role. ";



s.AddValues(new string[] { "Registered", "" });



ExtensionManager.ImportSettings(s);

settings = ExtensionManager.GetSettings("PostSecurity");

}



protected void Post_Serving(object sender, ServingEventArgs e)
{

Post post = (Post)sender;

bool continu = false;



MembershipUser user = Membership.GetUser();



continu = user != null;
e.Cancel = !continu;

}

}


Share this post: | | | |
Posted by cipto with no comments

TSQL Treat Null as Maximum Value

I’ve got a case where NULL is the maximum value of a date.

I turns out quite simple, just replace the null to some date in future. although some argue that it will replace the data

but if we set it somewhere far in future, than why not.

COALESCE(ENDDATE, '12/31/2099')

and COALESCE(ENDDATE, '12/31/2099')>OrderDate
and OrderDate>StartDate

Share this post: | | | |
Posted by cipto with no comments

Crypto Obfuscator

After Reviewing first on Stackoverflow, decided to test this and Deepsea. Dotfuscator is way too expensive

there is no 1,2,3 product which runs. after Crypto release the 2012. I decided to give it another try.

it turns out quite well.

have some missing problem but after add it to directory source where to locate it, it works.

the support is very responsive.

the explanation really clear and useful

“Different tools have different capabilities to open assemblies even if they have invalid metadata. Prevention of Disassembly is typically done by adding invalid metadata in the assembly (the Protect Against Reflector/Reflection options in Crypto Obfuscator).
However they are not "real" obfuscations - it just adds a little invalid metadata to your assemblies in the hope that tools such as Reflector and ILSpy are unable to parse the invalid metadata. These tools now seems to correctly ignore the invalid metadata. We have been through three cycles like this with Reflector and ILSpy and even if we add some other invalid metadata, its quite possible that these tools fixes their code to get past the invalid metadata. You should not rely on this setting alone.
The real obfuscations are the Symbol Renaming, String Encryption, Control Flow Obfuscation, etc - they perform the real obfuscation so that even when the code is viewable the meaning and intention of the code is extremely hard to determine. Combined together, they will give enough protection to your assemblies.”

The Caveat is when using Reflection

You need to put that attribute, to each class or method that relates and being used to reflect with.

[System.Reflection.ObfuscationAttribute(Exclude = true)]
Share this post: | | | |
Posted by cipto with no comments

Asp.net MVC 3 Deployment

With MVC 3 you could deploy to remote site, create package.

in My case I need to create the package.

How to do that?

in your vs 2010 sp1.

  • Right Click on the MVC3 Project –>Add deployable Dependency-> Check “asp.net MVC” and “asp.net webpages with Razor Syntax”, this will make sure all the presequites dll are being copied to bin folder
  • Right click again –> Build deployment Package
  • Go to that Folder setting, get the package or zip file

Now if you have problem running that cmd/bat file , it’s related to ms deploy.

Install Ms deploy in the server

you can import manually on your IIS manager console in the server.

just choose the website and click Import and choose the zip file.

Done Smile

http://weblogs.asp.net/scottgu/archive/2010/09/13/automating-deployment-with-microsoft-web-deploy.aspx

Remember that on that machine must have :

everything under world wide web->application…-> Checked

“regiis –I” is your latest weapon

.

Share this post: | | | |
Posted by cipto with no comments

Telerik asp.net MVC Extension Custom Grid Command

I’ve got a case that I want to do something after Removing Item on Shopping Cart Grid. I wanna do other action which my subtotal is outside of the grid.

so I need to passed extra data also on the action.

Using and following Telerik API for Grid.

the way how you do it is

on Telerik Grid

   1: columns.Command(commands =>
   2:        {
   3:            commands.Custom("Remove")
   4:                   .Text("Remove")
   5:                   .DataRouteValues(route => route.Add(o => o.OrderItemID).RouteKey("OrderItemID"))
   6:                   .Ajax(true)
   7:                   .Action("RemoveItemCart", "ShoppingCart").HtmlAttributes(new { style = "text-align: center" });
   8:  
   9:        });
  10:  
  11:     }).Footer(false)
  12: .ClientEvents(events => events.OnComplete("onComplete")))

On Controller Return JSON and our custom Data

   1: [HttpPost]
   2:       public JsonResult RemoveItemCart(int id)
   3:       {
   4:           var cartID=ShoppingCart.GetCartId(this.HttpContext);
   5:           ShoppingCart.RemoveFromCart(cartID, id);
   6:           var cartmodel = GetAllItems();
   7:           return Json(new {items=cartmodel.CartItems,Total = cartmodel.Total});
   8:       }

On our Javascript event which is on complete , Bind Grid manually

   1: function onComplete(e) {
   2:        if (e.name == "Remove") {
   3:            debugger;
   4:            var grid = $("#ShoppingCartGrid").data("tGrid");
   5:            grid.dataBind(e.response.items);
   6:            $('#subtotal').html(e.response.Total);
   7:        }    
   8:    }
Share this post: | | | |
Posted by cipto with no comments

asp.net mvc 3 and EF , Circular Reference Issue

This problem is caused by the default JSON serializer is not smart enough to deal with Entity of EF reference each other.

there are couple of solving you can find on internet using Automapper, other better json serializer, but In my Opinion the best one is simply, Generate your ViewModel with what property you need.

although I enable all Lazyload that I disabled, am using codefirst. so put back again virtual the issue remain.

In your View page. avoid using Model.Entity.ReferenceEntity.ColumnName, instead generate what you want .

Example :

Order and OrderItems.

avoid using OrderItems.Product.Description

instead in your ViewModel generate ProductDescription.

and on your linq to Entity query

 

   1: var results = (from a in db.tblCmOrderItems.Include("tblCmProduct")
   2:                                  where a.orderID == order.orderID
   3:                                  select new ShoppingCartItem
   4:                                  {
   5:                                      ValidUntil = validUntil,
   6:                                      UnitPrice = a.unitPrice,
   7:                                      UnitCost = a.unitCost,
   8:                                      Quantity = a.quantity,
   9:                                      OrderItemID = a.orderItemID,
  10:                                      ProductName = a.tblCmProduct.productName,
  11:                                      ProductDescription = a.tblCmProduct.description,
  12:                                      ProductID = a.tblCmProduct.productID
  13:                                  }).ToList();

 

This way You keep the rule of Thumb View only deal with what being passed on and follow the ViewModel Concept.

Share this post: | | | |
Posted by cipto with no comments

How to Debug CRM 2011 Plugin

Well there are a couple of ways and steps of doing it.

Like putting it in sandbox, enable it by registry editing.

and than attach debugger….

But it turns out you could do something like Die in PHP.

What ever you put on Trace , it will appended on the message when exception is thrown.

localContext.Trace([Output server variable)

throw new Exception(“Trace message”);

and you should see it when you Trigger it correctly Smile

Share this post: | | | |
Posted by cipto with no comments

How to Capture WCF/HTTP Post using Fiddler on IIS server

This is very interesting. as I’ve got to examine whether a call is being made to a Services/WCF on external site.

on Localhost Fiddler which capture everything correct. because fiddler run under your local account.

If you test on IIS, it’s different though . Worker process run under network service.

you can change it to whatever. but that is a hassle, so complicated.

Since it’s during post back than call services.

When we do simple enabled Fiddler on firefox. it will just set that browser proxy to 127.0.0.1:8888 where Fiddler listen to.

But that is not enough it’s not capturing what are being post and what are the external UI.

The best approach is by adding on web.config

<defaultProxy>
      <proxy
              usesystemdefault="False"
              bypassonlocal="True"
              proxyaddress="
http://127.0.0.1:8888"             
              />
    </defaultProxy>

 

 

You can now see on fiddler Smile

http://www.west-wind.com/weblog/posts/2009/Jan/14/Monitoring-HTTP-Output-with-Fiddler-in-NET-HTTP-Clients-and-WCF-Proxies

Share this post: | | | |
Posted by cipto with no comments

iTextSharp

iTExtSharp is a port from java iText. an open source to export things to PDF

you could actually export HTML to PDF. it’s very powerful as you can generate on the fly. just a bit of twist you can make report with PDF, or export things to PDF.

since PDF is like vector based. it’s very scalable meaning when printing it can scale to your preferred page size.

unfortunately there is not enough documentation. and the java thing seems to be a bit different in .Net one.

I am using the latest at this article is written, it’s 5.1.3. You could have the iText documentation in Java, or books like iText in action second edition.

things change a bit in property name. like to set the PageEvent actually it’s on writer.PageEvent=[your custom event]

To Export from HTML to PDF ,follow this pattern. this is also example for adding footer.

public class GeneratePDFHandler : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{

context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.Cache.SetExpires(DateTime.Now.AddDays(-1));
CultureInfo culture = new CultureInfo("en-AU");
string ReferalID = context.Request.QueryString["id"];

string contents = File.ReadAllText(context.Server.MapPath("~/template.htm"));
// Create a Document object
iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 50, 50, 25, 25);

// Create a new PdfWriter object, specifying the output stream
var output = new MemoryStream();
var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, output);
writer.PageEvent = new MYPdf();
// Open the Document for writing
document.Open();
// var logo = iTextSharp.text.Image.GetInstance(context.Server.MapPath("~/Images/IoptixxGray.gif"));
//logo.SetAbsolutePosition(10, 10);
//document.Add(logo);

contents = contents.Replace("[Name]", "Cipto");
var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), null);


foreach (var htmlElement in parsedHtmlElements)
document.Add(htmlElement as IElement);



document.Close();
context.Response.ContentType = "application/pdf";
context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=WorkOrder-{0}.pdf", ReferalID));
context.Response.BinaryWrite(output.ToArray());
}
}

Template.htm as you might guess has the html and a marker to be replaced in above example it’s [Name]

 

public class MYPdf : PdfPageEventHelper
{
public override void OnEndPage(PdfWriter writer, iTextSharp.text.Document document)
{

Rectangle rect=new Rectangle(50, 50, 545, 792);
var footerfont = FontFactory.GetFont("Arial",8);
ColumnText.ShowTextAligned(writer.DirectContent,
Element.ALIGN_CENTER, new Phrase("My Footer Message", footerfont),
(rect.GetLeft(0) + rect.GetRight(0)) / 2,
rect.GetBottom(0) - 45, 0);
}
}
For images you can add logo. or embed it in your html template. but the source must be a full internet URL

 

Share this post: | | | |
Posted by cipto with no comments

CRM 2011 SDK explanation Part 1

if you are some one that is sitting between CRM 4 sdk, and 2011 SDK. you'll end up and should upgrade using the 2011 one.

Because 2011 support lot's of fix, improvement, easy to use API than 4th version.

since CRM 2011 use WCF there has to be lot's of improvement, also from the size compression being transported.

CRM 2011 SDK support backward compability,as when it deals with CRM 4. it point to the old asmx services , 2007/xxx.asmx

 

use organizationservice.LoadProperty to load your Lazy load relation property, for example invoices_products

CRM 2011 support Federation Authenticaiton/Claim based authentication.

You only need to use the crmHelperClass and provide username and password with out domain.

 

Solution is major improvement in 2011. a lot of thing are being simplefied because of this.

on 4th version you've got that metadata thing. but Solution means you can package you custom entity, Plugin and import it again to another CRM instance

 

Plugin also being enhanced. Now after you install the Developer Tools. which comes with the SDK

You'll get Solution template, Plus CRM Explorer. Plus when developing Plugin/Workflow you get what they called CRM Package, right click and Deploy :)

You'll get Default class called Plugin which provide you with localContext, you can access the servicecontext,organizationcontext,entity here.

It's a very good one, because now you can implement Base plugin for multiple entities, before you need to create class and another class

It's also recommend to deploy it to your Solution. that way when you moved from staging, to prod server. you only import the solution

the CRM 2011 service is also supporting for you to upload your CRM through SDK

 

most easy to use is Early bound, generate it using CRMSVCutil which will generate strong type for you.

to make sure things is there or not. think of solution.

CRM 2011 use WIF 

LINQ to FetchXMl service request is deprecated

 

 

Share this post: | | | |
Posted by cipto with no comments

Google map is so god damn easy

Google map v3 is very easy to implement. it will take you just minutes to create great application

it's HTML5 and mobile compatible also. sadly again not showing on IE7.

You could add Markup , and "Controls" to the map . so that the map take 1 full screen, and your control (html element)

are shown as you choices, on top left, center , bottom right as you like.

you can change icon easily by defining the icon. so cool

all you have to do is have the geocode location.

 

like on mine it needs filter by post code,  so search through the geolocation, set center and zoom in

 

 

 

Share this post: | | | |
Posted by cipto with no comments
More Posts Next page »