Where can Sitecore webcontrol examples be found? - sitecore

I've been looking over the Sitecore documentation for HtmlControls and WebControls, but none of the items have any meaningful descriptions or example code to show how they're used or what they produce.
I understand how to use simple controls like Text, Date, Image, and Link:
<sc:Text runat="server" ID="content" Field="Content" />
Is there a resource that includes examples for more advanced controls like WebControls.ItemList or HtmlControls.TreePicker to show how they'd be used and what output they produce?

The SDN has some code examples. Essentially, WebControls are .NET server controls where you write all business logic and front-end code via C#. Here's the series on the SDN called "Web Controls":
Part 1
Part 2
Part 3
Here's a sample TextControl:
protected override void DoRender(HtmlTextWriter output) {
if (ClassAttribute.Length > 0) {
output.AddAttribute(HtmlTextWriterAttribute.Class, ClassAttribute);
}
if (StyleAttribute.Length > 0) {
output.AddAttribute(HtmlTextWriterAttribute.Style, StyleAttribute);
}
output.RenderBeginTag(HtmlTextWriterTag.Div);
string val = string.Empty;
if(_text.Length == 0) {
val = GetFieldValue(_textField);
} else {
val = _text;
}
output.AddAttribute(HtmlTextWriterAttribute.Class, TextClass);
output.AddAttribute(HtmlTextWriterAttribute.Style, TextStyle);
output.RenderBeginTag(HtmlTextWriterTag.Div);
output.Write(val);
output.RenderEndTag();
output.RenderEndTag();
}
EDIT: To understand how internal built-in Sitecore components work:
Sitecore is not going to provide the details of how their controls are built. Sitecore is not open source. That being said, I've been told several times by people from Sitecore that if you need to understand how something works to extend it, use the .NET Reflector to de-compile the kernel (Sitecore.Kernel.dll). I've done this many times to figure out how the internal things work. In your case, you can decompile the assembly and look at the classes under Sitecore.Web.UI.WebControls etc.

Related

VSIX how to get current snapshot document name?

I have been trying to to create an extension that highlights specific line numbers for me in Visual Studio in the margins.
I manged to get my marking in the margins using predefined line number but for it to work properly I need to know what the current document FullName is (Path and filename)
After much googling I figured out how to do it with the sample code (which is not ideal)
DTE2 dte = (DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.15.0");
var activeDocument = dte.ActiveDocument;
var docName = activeDocument.Name;
var docFullName = activeDocument.FullName;
Now I know the problems here
is that is for specific version bases on the text
there is no way to select which instance (when running more than one VS)
It seems to be very slow
I have a feeling I should be doing this with MEF Attributes but the MS docs examples are so simple that they do not work for me. I scanned a few SO questions too and I just cannot get them to work. They mostly talk about Services.. which I do not have and have no idea how to get.
The rest of my code uses SnapshotSpans as in the example Extension of Todo_Classification examples which is great if you do NOT need to know the file name.
I have never done any extensions development. Please can somebody help me do this correctly.
You can use following code to get a file from a snapshot without any dependencies.
public string GetDocumentPath(Microsoft.VisualStudio.Text.ITextSnapshot ts)
{
Microsoft.VisualStudio.Text.ITextDocument textDoc;
bool rc = ts.TextBuffer.Properties.TryGetProperty(
typeof(Microsoft.VisualStudio.Text.ITextDocument), out textDoc);
if (rc && textDoc != null)
return textDoc.FilePath;
return null;
}
If you don't mind adding Microsoft.CodeAnalysis.EditorFeatures.Text to your project it will provide you with an extension method Document GetOpenDocumentInCurrentContextWithChanges() on the Microsoft.VisualStudio.Text.Snapshot class. (Plus many other Rosyln based helpers)
using Microsoft.CodeAnalysis.Text;
Document doc = span.Snapshot.GetOpenDocumentInCurrentContextWithChanges();

Sitecore: Glass Mapper Code First

It is possible to automatically generate Sitecore templates just coding models? I'm using Sitecore 8.0 and I saw Glass Mapper Code First approach but I cant find more information about that.
Not sure why there isn't much info about it, but you can definitely model/code first!. I do it alot using the attribute configuration approach like so:
[SitecoreType(true, "{generated guid}")]
public class ExampleModel
{
[SitecoreField("{generated guid}", SitecoreFieldType.SingleLineText)]
public virtual string Title { get; set; }
}
Now how this works. The SitecoreType 'true' value for the first parameter indicates it may be used for codefirst. There is a GlassCodeFirstDataprovider which has an Initialize method, executed in Sitecore's Initialize pipeline. This method will collect all configurations marked for codefirst and create it in the sql dataprovider. The sections and fields are stored in memory. It also takes inheritance into account (base templates).
I think you first need to uncomment some code in the GlassMapperScCustom class you get when you install the project via Nuget. The PostLoad method contains the few lines that execute the Initialize method of each CodeFirstDataprovider.
var dbs = global::Sitecore.Configuration.Factory.GetDatabases();
foreach (var db in dbs)
{
var provider = db.GetDataProviders().FirstOrDefault(x => x is GlassDataProvider) as GlassDataProvider;
if (provider != null)
{
using (new SecurityDisabler())
{
provider.Initialise(db);
}
}
}
Furthermore I would advise to use code first on development only. You can create packages or serialize the templates as usual and deploy them to other environment so you dont need the dataprovider (and potential risks) there.
You can. But it's not going to be Glass related.
Code first is exactly what Sitecore.PathFinder is looking to achieve. There's not a lot of info publicly available on this yet however.
Get started here: https://github.com/JakobChristensen/Sitecore.Pathfinder

How to programmatically update references in sitecore?

I have 2 templates: ArticleItem and ArticlePageItem, the ArticlePageItem has a ReferenceField 'Content.Reference' that links to an ArticleItem. Below is the code to create an article:
Item articlePageItem = articlePageParentItem.Add(articleItem.Name, new TemplateItem(master.GetItem(ConstantString.ArticlePageTemplateID)));
using (new UserSwitcher(Sitecore.Context.User))
{
articlePageItem.Editing.BeginEdit();
articlePageItem.Fields["Content.Reference"].Value = articleItem.ID.ToString();
articlePageItem.Editing.EndEdit();
}
But after I execute the code above, I cannot get the ArticleItem reference through Globals.LinkDatabase.GetReferences(articlePageItem), even though I use Globals.LinkDatabase.UpdateReference(articlePageItem).
Does anyone know how to implement this?
[Update]
Below is our environment:
We have a website based on Sitecore, and we're developing another system aims to simplify the article management. We use .NET 4 & ASP.NET MVC 3 to implement this system, and reference Sitecore.Kernal.dll & Sitecore.Client.dll to our project. But our sitecore version is 6.2 which is incomplatible with .NET 4, so I just copied part of the configurations. I think it maybe dues to the incomplete web.config.
If you are executing the above code you should also consider publishing the item changes.
This can be done by using the following code snippet:
// publish all changed content
Database webDatabase = Sitecore.Configuration.Factory.GetDatabase("web");
PublishOptions publishOptions = new PublishOptions(masterDatabase, webDatabase, PublishMode.Smart, Sitecore.Context.Language, DateTime.Now);
publishOptions.RootItem = vacatureRoot;
publishOptions.Deep = true;
Publisher publisher = new Publisher(publishOptions);
publisher.Publish();
Where 'vacatureRoot' is the root -> in your case articlePageParentItem
After publishing the references should be set automatically and should be retrievable by using the normal way of getting Fields.
It looks like you are using a ReferenceField and therefore your code should look something like this:
ReferenceField rfRef = Sitecore.Context.Item.Fields["Content.Reference"];
if(rfRef != null && rfRef.TargetItem != null)
{
//Your logic here
}
Answer for comment:
I think you could best use the following code fragment ->
Sitecore.Globals.LinkDatabase.UpdateReferences(articlePageItem);
I think this will do what the name says, update the references for this item.
Hope this will work for you!

Pattern for UI configuration

I have a Win32 C++ program that validates user input and updates the UI with status information and options. Currently it is written like this:
void ShowError() {
SetIcon(kError);
SetMessageString("There was an error");
HideButton(kButton1);
HideButton(kButton2);
ShowButton(kButton3);
}
void ShowSuccess() {
SetIcon(kError);
std::String statusText (GetStatusText());
SetMessageString(statusText);
HideButton(kButton1);
HideButton(kButton2);
ShowButton(kButton3);
}
// plus several more methods to update the UI using similar mechanisms
I do not likes this because it duplicates code and causes me to update several methods if something changes in the UI.
I am wondering if there is a design pattern or best practice to remove the duplication and make the functionality easier to understand and update.
I could consolidate the code inside a config function and pass in flags to enable/disable UI items, but I am not convinced this is the best approach.
Any suggestions and ideas?
I would recommend Observer Pattern and State Pattern, when an validation happens to be successful or unsuccessful, attached buttons can change their state according to information provided in "notify" method. Please refer to GoF's book for further details, or just google them. Hope it helps.

Use c++ to access internet explorer

Well as the topic says, I want to know if there is a tool or a tutorial that can help me access IE, get in a certain URL, do some action on that website. So I would have a program to do that for me instead of doing it myself every time.
Here is a project on Internet Explorer automation with C++
you should really rephrase your question.. you said what you want to do is login to hotmail programatically, check the pidgin code, they do it.
Documentation found here , here and you can I think navigate through the code and tutorials at will until you have your understanding of how the pidgin contributors did it.
You can find the main page for pidgin here
Code sample to get you started:
00362 static void
00363 msn_show_hotmail_inbox(PurplePluginAction *action)
00364 {
00365 PurpleConnection *gc;
00366 MsnSession *session;
00367
00368 gc = (PurpleConnection *) action->context;
00369 session = gc->proto_data;
00370
00371 if (session->passport_info.file == NULL)
00372 {
00373 purple_notify_error(gc, NULL,
00374 _("This Hotmail account may not be active."), NULL);
00375 return;
00376 }
00377
00378 purple_notify_uri(gc, session->passport_info.file);
00379 }
00652 void *
00653 purple_notify_uri(void *handle, const char *uri)
00654 {
00655 PurpleNotifyUiOps *ops;
00656
00657 g_return_val_if_fail(uri != NULL, NULL);
00658
00659 ops = purple_notify_get_ui_ops();
00660
00661 if (ops != NULL && ops->notify_uri != NULL) {
00662
00663 void *ui_handle = ops->notify_uri(uri);
00664
00665 if (ui_handle != NULL) {
00666
00667 PurpleNotifyInfo *info = g_new0(PurpleNotifyInfo, 1);
00668 info->type = PURPLE_NOTIFY_URI;
00669 info->handle = handle;
00670 info->ui_handle = ui_handle;
00671
00672 handles = g_list_append(handles, info);
00673
00674 return info->ui_handle;
00675 }
00676 }
00677
00678 return NULL;
00679 }
Rather than using IE for such things, look into appropriate screen scraping libraries for your language of choice. You can google and search Stack Overflow to find many such libraries. From here, you'll use your language's web APIs to send data to the server.
Don't know of any tool.
I use an embedded browser for such things. It is possible to connect to a running instance of IE. See
Connect to Running Instance of IE
Once you get an instance of IWebBrowser2, the coding is the same.
1. Get the Document Interface
pWebBrowser->Document->QueryInterface(
IID_IHTMLDocument2,(LPVOID*)&Doc);
2. Get all the elements on the Document
Doc->get_all(&Elements);
3. enum the Elements
Elements->get_length(&ulLen);
for_each
Elements->item(item, index, &ppvElement);
4. Detemine what element is desired.
* by classname
* by ID etc.. here I used the classname
ppvElement->get_className (&bstrElement);
5. Insert Text for user / password
ppvElement->put_innerText(wsUreser_or_Psswd)
6. Find the Sign in button and click it.
ppvElement->Click();
Your results may vary.
--
Michael
Why don't you make a feed in dapper in two minutes? Apparently some people have already done it as well.