Sitecore Clear Cache Programmatically - web-services

I am trying to publish programmatically in Sitecore. Publishing works fine. But doing so programmatically doesn't clear the sitecore cache. What is the best way to clear the cache programmatically?
I am trying to use the webservice that comes with the staging module. But I am getting a Bad request exception(Exception: The remote server returned an unexpected response: (400) Bad Request.). I tried to increase the service receivetimeout and sendtimeout on the client side config file but that didn't fix the problem. Any pointers would be greatly appreciated?
I am using the following code:
CacheClearService.StagingWebServiceSoapClient client = new CacheClearService.StagingWebServiceSoapClient();
CacheClearService.StagingCredentials credentials = new CacheClearService.StagingCredentials();
credentials.Username = "sitecore\adminuser";
credentials.Password = "***********";
credentials.isEncrypted = false;
bool s = client.ClearCache(true, dt, credentials);
I am using following code to do publish.
Database master = Sitecore.Configuration.Factory.GetDatabase("master");
Database web = Sitecore.Configuration.Factory.GetDatabase("web");
string userName = "default\adminuser";
Sitecore.Security.Accounts.User user = Sitecore.Security.Accounts.User.FromName(userName, true);
user.RuntimeSettings.IsAdministrator = true;
using (new Sitecore.Security.Accounts.UserSwitcher(user))
{
Sitecore.Publishing.PublishOptions options = new Sitecore.Publishing.PublishOptions(master, web,
Sitecore.Publishing.PublishMode.Full, Sitecore.Data.Managers.LanguageManager.DefaultLanguage, DateTime.Now);
options.RootItem = master.Items["/sitecore/content/"];
options.Deep = true;
options.CompareRevisions = true;
options.RepublishAll = true;
options.FromDate = DateTime.Now.AddMonths(-1);
Sitecore.Publishing.Publisher publisher = new Sitecore.Publishing.Publisher(options);
publisher.Publish();
}

In Sitecore 6, the CacheManager class has a static method that will clear all caches. The ClearAll() method is obsolete.
Sitecore.Caching.CacheManager.ClearAllCaches();

Just a quick note, in Sitecore 6.3, that is not needed anymore. Caches are being cleared automatically after a change happens on a remote server.
Also, if you are on previous releases, instead of clearing all caches, you can do partial cache clearing.
There is a free shared source component called Stager that does that.
http://trac.sitecore.net/SitecoreStager
If you need a custom solution, you can simply extract the source code from there.

I got this from Sitecore support. It clears all caches:
Sitecore.Context.Database = this.WebContext.Database;
Sitecore.Context.Database.Engines.TemplateEngine.Reset();
Sitecore.Context.ClientData.RemoveAll();
Sitecore.Caching.CacheManager.ClearAllCaches();
Sitecore.Context.Database = this.ShellContext.Database;
Sitecore.Context.Database.Engines.TemplateEngine.Reset();
Sitecore.Caching.CacheManager.ClearAllCaches();
Sitecore.Context.ClientData.RemoveAll();

Out of the box solution provided by Sitecore to clean caches (ALL of them) is utilized by the following page: http://sitecore_instance_here/sitecore/admin/cache.aspx and code behind looks like the following snippet:
foreach (var cache in Sitecore.Caching.CacheManager.GetAllCaches())
cache.Clear();

Via the SDN:
HtmlCache cache = CacheManager.GetHtmlCache(Context.Site);
if (cache != null) {
cache.Clear();
}

Related

Adding a cookie to DocumentRequest

Using AngleSharp v 0.9.9, I'm loading a page with OpenAsync which sets a bunch of cookies, something like:
var configuration = Configuration.Default.WithHttpClientRequester().WithCookies();
var currentContext = BrowsingContext.New(configuration);
// ....
var doc = context.OpenAsync(url, token);
This works fine and I can see the cookies have been set. For example, I can do this:
var cookieProvider = currentContext.Configuration.Services.OfType<ICookieProvider>().First() as MemoryCookieProvider;
And examine it in the debugger and see the cookies in there (for domain=.share.state.nm.us)
Then I need to submit a post:
var request = new DocumentRequest(postUrl);
request.Method = HttpMethod.Post;
request.Headers["Content-Type"] = "application/x-www-form-urlencoded";
request.Headers["User-Agent"] = userAgent;
//...
Which eventually gets submitted:
var download = loader.DownloadAsync(request);
And I can see (using Fiddler) that it's submitting the cookies from the cookieProvider.
However, I need to add a cookie (and possible change the value in another) and no matter what I try, it doesn't seem to include it. For example, I do this:
cookieProvider.Container.Add(new System.Net.Cookie()
{
Domain = ".share.state.nm.us",
Name = "psback",
Value = "somevalue",
Path = "/"
});
And again I can examine the cookieProvider in the debugger and see the cookie I set. But when I actually submit the request and look in fiddler, the new cookie isn't included.
This seems like it should be really simple, what is the correct way to set a new cookie and have it included in subsequent requests?
I think there are two potential ways to solve this.
either use document.Cookie for setting a new cookie (would require an active document that already is at the desired domain) or
Use a Filter for getting / manipulating the request before its send. This let's you really just change the used cookie container before actually submitting.
The Filter is set in the DefaultLoader configuration. See https://github.com/AngleSharp/AngleSharp/blob/master/src/AngleSharp/ConfigurationExtensions.cs#L152.

Image file extension randomly is missing in sitecore

I'm experiencing an strange behaviour in our production servers.
We have three servers and It seems sometimes MediaManager.GetMediaUrl doesn't return the file extension. First I thought one server might have different settings. I compared all the configs on the three servers and they are identical.
Surprisingly, I notice If I browse the same page from the same server I can replicate issue.
I checked the value of Media.RequestExtension and for all three is same as following
<setting name="Media.RequestExtension" value=""/>
I cannot replicate the issue on none of our environments( local,test, staging )
I added the metatag and hardcoded the server name and I set the Cacheable property of usercontrol to false and I'm sure it's not Caching issue.
var images = new List<string>();
var imageField1 = (Sitecore.Data.Fields.ImageField)Sitecore.Context.Item.Fields["og Image1"];
if (imageField1 != null && imageField1.MediaItem != null)
{
var image1Url = MediaManager.GetMediaUrl(imageField1.MediaItem);
images.Add(image1Url);
}
Has anyone experienced the same issue?
Even I have faced this issue of extension in media item urls.
Workaround for this issue would be to make use of IncludeExtension property of MediaUrlOptions object.
MediaUrlOptions mediaUrlOpts = new MediaUrlOptions();
mediaUrlOpts.IncludeExtension = false;
Response.Write(MediaManager.GetMediaUrl(item, mediaUrlOpts ));
If you want to always add extension to URL, then set IncludeExtension to true.

Accessing Item Fields via Sitecore Web Service

I am creating items on the fly via Sitecore Web Service. So far I can create the items from this function:
AddFromTemplate
And I also tried this link: http://blog.hansmelis.be/2012/05/29/sitecore-web-service-pitfalls/
But I am finding it hard to access the fields. So far here is my code:
public void CreateItemInSitecore(string getDayGuid, Oracle.DataAccess.Client.OracleDataReader reader)
{
if (getDayGuid != null)
{
var sitecoreService = new EverBankCMS.VisualSitecoreService();
var addItem = sitecoreService.AddFromTemplate(getDayGuid, templateIdRTT, "Testing", database, myCred);
var getChildren = sitecoreService.GetChildren(getDayGuid, database, myCred);
for (int i = 0; i < getChildren.ChildNodes.Count; i++)
{
if (getChildren.ChildNodes[i].InnerText.ToString() == "Testing")
{
var getItem = sitecoreService.GetItemFields(getChildren.ChildNodes[i].Attributes[0].Value, "en", "1", true, database, myCred);
string p = getChildren.ChildNodes[i].Attributes[0].Value;
}
}
}
}
So as you can see I am creating an Item and I want to access the Fields for that item.
I thought that GetItemFields will give me some value, but finding it hard to get it. Any clue?
My advice would be to not use the VSS (Visual Sitecore Service), but write your own service specifically for the thing you want it to do.
This way is usually more efficient because you can do exactly the thing you want, directly inside the service, instead of making a lot of calls to the VSS and handle your logic on the clientside.
For me, this has always been a better solution than using the VSS.
I am assuming you are looking to find out what the fields looks like and what the field IDs are.
You can call GetXml with the ID, it returns the item and all the versions and fields set in it, it won't show fields you haven't set.

Parsing XML webservice and storing the data for presentation on a windows phone 7 device

I'm working on an app that requires extracting data from an xml web service, then I want to store that data (images+titles+datetime ...) to display it on my app then select an item and navigate to another page that displays more info about this item.
Is there a detailed tutorial that explains the parsing and storing process clearly (with the threads) because I'm gonna need it a lot for my app.Thanks!
I usually use this method, but didn't always get me what i want:
var doc = XDocument.Load(new StringReader(e.Result));
var items = from c in doc.Descendants("item")
select new RSSitem()
{
Title = c.Element("title").Value,
Photo = c.Element("img").Attribute("src").Value,
Description = c.Element("description").Value,
Link = c.Element("link").Value,
};
ListBoxNews.ItemsSource = items;
Sounds like you are in over your head (based on the vague nature of your question). So I'm offering my advise to get up to speed, so you can get started and ask a question that we can help give a definitive answer to.
With WP7 and .NET you shouldn't really have to do much manual parsing of Web Services. You should be able to add a Service Reference and generate a proxy which will handle this for you. This will also generate business objects for the data returned by your service.
Once you have that done, you can look into Windows Phone Navigation which should help you transition between pages in your application.
To consume web services:
String baseUri = “your service URI";
WebClient wc = new WebClient();
public MainPage()
{
InitializeComponent();
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_downloadstringcompleted);
// event handler that will handle the ‘downloadstringsompleted’ event
wc.DownloadStringAsync(new Uri(baseUri));
// this method will download your string URI asynchronously
}
void wc_downloadstringcompleted(Object sender, DownloadStringCompletedEventArgs e)
{
// method will get fired after URI download completes
// writes your every code here
}
To parse the data:
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
break;
case XmlNodeType.Text:
break;
case XmlNodeType.EndElement:
break;
}
}
}
}
To store in isolated storage: http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragesettings%28v=vs.95%29.aspx
For navigation:
NavigationService.Navigate(new Uri("/SecondPage.xaml?msg=" + navigationstring, UriKind.Relative));

Sitecore poll module sample code

I installed and configured the Poll Module to work fine. The website I am working on will have a Poll instance on a page either as a left rail or a right rail item. The Polls would be setup in a separate folder. On the page item there will be a multilist field which will point to the Polls folder and the user can select whichever poll they choose to. The folder will also contain different sublayouts which will could be selected to be displayed on the rail. I have some custom code which will look at the above mentioned multilist field and show these rail items.
I don't know how to display a Poll programmatically. I haven't found any code samples and also not sure where to set the sublayout. Should I set it on the Poll template itself and then let use code to display it? How can I achieve this in code? Any code samples would be helpful.
Hoping that you will this time accept the answer, I wrote the following for you (based on the OMS Poll module:
Read out the field on your item:
Sitecore.Data.Fields.ReferenceField selectedPoll = (Sitecore.Data.Fields.ReferenceField)Sitecore.Context.Item.Fields["Poll"];
Get the pollItem:
if (selectedPoll.TargetItem != null)
{
Item pollItem = selectedPoll.TargetItem;
if (pollItem != null)
{
Check if the poll is opened or closed and place:
Sitecore.Data.Fields.CheckboxField pollClosed = (Sitecore.Data.Fields.CheckboxField)pollItem.Fields["Closed"];
if (pollClosed.Checked == false)
{
// Set the header of the snippetBlock
ltPollHeader.Text = pollItem.Name;
PollVotingSublayout pollSublayout = (PollVotingSublayout)LoadControl("/sitecore modules/Shell/Poll Module/Controls/PollVotingSublayout.ascx");
pollSublayout.Attributes.Add("sc_parameters", "PollPath=" + pollItem.Paths.FullPath);
pollSublayout.CurrentPoll = (PollItem)pollItem;
this.pollRegion.Controls.Add(pollSublayout);
phPollSnippet.Visible = true;
int blockPos = 0;
if (snippetField != null)
{
if (snippetField.GetItems().Any())
{
blockPos = 1;
}
}
string cssClass = String.Empty;
if (blockPos == 0)
{
cssClass = "snippetColHomeFirst";
}
this.SetClass("snippetColHome", cssClass);
}
Hope that you can make up something using this snippets. Good luck!
There should be a user account called "poll" on the sitecore domain. This account is normally used internal by the poll. In the comment of this account is stated: "Please do not remove this account". the account should have the Sitecore Minimal Page Editor role. I don't know the poll user credentials, but you might find that by either using reflector or opening cs files that you can get by downloading the source.