C# Method - Publish Entire Sitecore Site - c#

I have an odd request. I am wondering if it is possible to have your C# solution file publish the entire Site from the master database to the web database. I am in my development environment and the amount of items in Sitecore is changing daily as I am working with multiple people. This is not something that is going to be used to Production Content Management or Content Delivery. Purely development.
Is it possible to trigger a full Site publish in C# just like pressing the publish button in the content editor? And what would the code look like?
/sitecore/shell/Applications/Publish.aspx
I assume this C# method would work with Sitecore.Publishing.PublishManager?
Thanks!

We also use that on our projects...
We have that placed in a regular .aspx page. I hope that helps:
protected void Page_Load(object sender, EventArgs e)
{
PublishMode publishMode = PublishMode.Full;
using (new Sitecore.SecurityModel.SecurityDisabler())
{
var webDb = Sitecore.Configuration.Factory.GetDatabase("web");
var masterDb = Sitecore.Configuration.Factory.GetDatabase("master");
try
{
foreach (Language language in masterDb.Languages)
{
//loops on the languages and do a full republish on the whole sitecore content tree
var options = new PublishOptions(masterDb, webDb, publishMode, language, DateTime.Now) { RootItem = masterDb.Items["/sitecore"], RepublishAll = true, Deep = true };
var myPublisher = new Publisher(options);
myPublisher.Publish();
}
}
catch (Exception ex)
{
Sitecore.Diagnostics.Log.Error("Could not publish", ex);
}
}
}

Related

SharePoint: Customize default NewForm.aspx and hide some fields according to given permissions

My requirement is to restrict users to view/add/edit fields of a list as per their given group/permission. To achieve this objective as per my understanding I have to generate custom list forms. If anyone can help me to customize NewFrom.Aspx and code in such a way that we can check current user group/permission and hide fields which should not be accessible to him.
I have derived solution after googling and have thought to apply below thing after creating new custom list form. I want to know if this approach is good enough or give any optimal solution to it.
var web = SPContext.Current.Web;
web.AllowUnsafeUpdates = true;
web.Update();
var lists = web.Lists["SomeList"];
var f = lists.Fields["SomeField"];
if(){ //to check if user is in role
f.ShowInEditForm = false;
f.ShowInNewForm = false;
f.Update();
}
The same list will be used ac cross all the users so I think above solution might not be optimal.
Thanks in advance.
As SharePoint does not support Column level permissions, there are some third party tools available for column level permissions:
Column Level Security
SharePoint Column/View Permission
For Custom NewForm:
You can develop the custom webpart for NewForm where you can display fields as per the permissions.
Then set this webpart in place of default NewForm.aspx, so when ever user click on NewItem link of the list then rather than default sharepoint form it will open custom webpart.
You can replace the default NewForm webpart with custom webpart with following code:
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb currentWeb = (SPWeb)properties.Feature.Parent;
try
{
SPLimitedWebPartManager NewForm = currentWeb.GetLimitedWebPartManager("Lists/listname1/NewForm.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
AddWebPart(NewForm);
}
catch (Exception)
{
throw;
}
}
protected void AddWebPart(SPLimitedWebPartManager MainPage)
{
MainPage.WebParts[0].Hidden = true;
MainPage.SaveChanges(MainPage.WebParts[0]);
try
{
var linqqry = from wp in MainPage.WebParts.Cast()
where wp.GetType() == typeof(Webpart1.Webpart1)
select wp;
if (linqqry.Count() == 0)
{
//Create an instance of WPMenu Webpart and add in a Webpart zone
Webpart1.Webpart1 wpWebPart = new Webpart1.Webpart1();
MainPage.AddWebPart(wpWebPart, "Main", 0);
MainPage.SaveChanges(wpWebPart);
}
}
catch (Exception ex)
{
}
}

C# parsing web site with ajax loaded content

If I recive a web site with this function I get the whole page, but without the ajax loaded values.
htmlDoc.LoadHtml(new WebClient().DownloadString(url));
Is it possible to load the web site like in gChrome with all values?
You can use a WebBrowser control to get and render the page. Unfortunately, the control uses Internet Explorer and you have to change a registry value in order to force it to use the latest version and even then the implementation is very brittle.
Another option is to take a standalone browser engine like WebKit and make it work in .NET. I found a page explaining how to do this, but it's pretty dated: http://webkitdotnet.sourceforge.net/basics.php
I worked on a little demo app to get the content and this is what I came up with:
class Program
{
static void Main(string[] args)
{
GetRenderedWebPage("https://siderite.dev", TimeSpan.FromSeconds(5), output =>
{
Console.Write(output);
File.WriteAllText("output.txt", output);
});
Console.ReadKey();
}
private static void GetRenderedWebPage(string url, TimeSpan waitAfterPageLoad, Action<string> callBack)
{
const string cEndLine= "All output received";
var sb = new StringBuilder();
var p = new PhantomJS();
p.OutputReceived += (sender, e) =>
{
if (e.Data==cEndLine)
{
callBack(sb.ToString());
} else
{
sb.AppendLine(e.Data);
}
};
p.RunScript(#"
var page = require('webpage').create();
page.viewportSize = { width: 1920, height: 1080 };
page.onLoadFinished = function(status) {
if (status=='success') {
setTimeout(function() {
console.log(page.content);
console.log('" + cEndLine + #"');
phantom.exit();
}," + waitAfterPageLoad.TotalMilliseconds + #");
}
};
var url = '" + url + #"';
page.open(url);", new string[0]);
}
}
This uses the PhantomJS "headless" browser by way of the wrapper NReco.PhantomJS which you can get through "reference NuGet package" directly from Visual Studio. I am sure it can be done better, but this is what I did today. You might want to take a look at the PhantomJS callbacks so you can properly debug what is going on. My example will wait forever if the URL doesn't work, for example. Here is a useful link: https://newspaint.wordpress.com/2013/04/25/getting-to-the-bottom-of-why-a-phantomjs-page-load-fails/
No its not possible in your example. Since it will load content as a string. You should render that string in "browser engine" or find any components which would do that for you.
I would suggest you to look into abotx they just announce this feature so maybe would be interesting for you but its not free.

Jquery: Page scraping, turn C# code to Jquery

I have been working on some code to scrape data from a webpage using C#. Unfortunately after creating the code and getting it to work i noticed that the webpage i had to implement it on was using Jquery on the input my code was meant to be going on.
So now i have to change my code to work with Jquery. I was wondering if page scrapping is even possible in Jquery and if anyone could give me a hand?
I have found this code but have no idea if it will work as my Jquery skills are very bad.
p.s i am coding in ASP.Net web forms using C# codebehind
EDIT: it would also work if i could execute the current javascript from the code-behind
$.get("/path/to/other/page",function(data){
$('#data').append($('li',data));
}
my C# code is
protected void GetAverageRent_TextChanged(object sender, EventArgs e)
{
string Postcode = _postCodeInput.Value.ToString();
var webGet = new HtmlWeb();
var doc = webGet.Load("http://www.webaddress.com" + Postcode);
HtmlNode AvgPrice = doc.DocumentNode.SelectSingleNode("//div[#class='split2r right']//strong[#class='price big']");
if (AvgPrice != null)
{
AverageRentLbl.Text = AvgPrice.InnerHtml.ToString();
}
else
{
AverageRentLbl.Text = "Invalid Postcode!";
AverageRentLbl.ForeColor = Color.Red;
AverageRentLbl.Font.Bold = true;
}
}

Creating Facebook Application in asp.net

I want to create a Facebook IFRAME applicaton with asp.net. I just want to know should I need to host the application some where over internet? If yes, how could I test my application on localhost?
Update:
I just want a simple app for displaying a user name with "Hello." Can anyone show me the code for that with the complete web.config configuration?
I'm trying this code
using facebook.web;
namespace TestFbApplication
{
public partial class _Default:facebook.web.CanvasFBMLBasePage
{
facebook.Components.FacebookService _fbService = new facebook.Components.FacebookService();
private const string FACEBOOK_APPKEY = "66a8278bb94d969247a80815bab686e5"; // From the Facebook application page
private const string FACEBOOK_SECRET = "de76280e4ddaef72ac2166afe7ffb9d5"; // From the Facebook application page
protected void Page_PreInit(object sender, EventArgs e)
{
base.RequireLogin = false;
_fbService.IsDesktopApplication = false;
_fbService.ApplicationKey = FACEBOOK_APPKEY;
_fbService.Secret = FACEBOOK_SECRET;
_fbService.IsDesktopApplication = false;
_fbService.ConnectToFacebook();
abc.InnerText = _fbService.users.getInfo().ToString();
}
and it is throwing and Exception in the last line that that the object reference is not set.
You will need to host your production application somewhere, but you can test locally. If you set your Canvas URL to http://localhost:81 in Facebook, this should work. It did for me a couple of months ago, but they may have changed it since then.
this might be an interesting for you:
http://www.stevetrefethen.com/blog/DevelopingFacebookapplicationsinCwithASPNET.aspx

When user hit's the site the custom error page is shown. Why? This is to few users and sporadic

Could somebody please help me?
We are developing a asp.net application using asp.net 2.0 framework. The issue is sporadic. As soon as a particular user hits the site in production a custom error page is shown. I been told that this user could get in successfully some times and after some idle time he is getting this error page. We not even not yet log in to site. Just as soon as i hit the site Ex:- www.Mywebsite.com the custom error is dispalyed. Could somebody help me on this. One more thing i have on my local machine .net 3.5 service pack1 installed and in production on only once server the service pack is installed. Could this be the cause of the problem?. some times it is showing the page and some users custom error. They not even visited the login screen yet. As soon as some users hit the site they see the customer error page, instead of login page. As i told this is happening as the user hitting the site I started checking my load code of index.aspx (page set up in virtual directories documents as start up page) and this is the code i am using.
My each .aspx page is inheriting the PageBase class which has the below method overriden and with the below code. If you see carefully the expiration of "langCookie" been given as 30 minutes. Will this be a problem? Below is a little code of my PageBase and my index.aspx. I am not sure what user's are doing. I heard it comes sporadically, so became hard to reproduce. One more thing since this is mix of asp and aspx pages i used below in web.config, Otherwise i am gettinig the sqaure characters in classic asp pages when i open them.
PageBase.cs Code:-
protected override void InitializeCulture()
{
base.InitializeCulture();
HttpCookie langCookie = null;
if (null == Request.Cookies[SESSION_KEY_LANGUAGE])
{
foreach (string s in Request.Cookies)
{
if (HttpUtility.UrlDecode(Request.Cookies[s].Name) == SESSION_KEY_LANGUAGE)
{
langCookie = new HttpCookie(SESSION_KEY_LANGUAGE);
langCookie.Value = HttpUtility.UrlDecode(Request.Cookies[s].Value); langCookie.Expires = DateTime.Now.AddMinutes(30.0);
Response.Cookies.Add(langCookie);
break;
}
}
}
else
{
langCookie = Request.Cookies[SESSION_KEY_LANGUAGE];
}
if (null != langCookie)
{
if (langCookie.Value != "")
{
CultureInfo cultureInfo = new CultureInfo(langCookie.Value);
ApplyNewLanguage(cultureInfo);
}
}
}
index.aspx.cs:- The starting page in virtual is set as index.aspx
protected void Page_Load(object sender, EventArgs e)
{
//Set sign button as default button for login (press enter)
Page.Form.DefaultButton = "ButtonSignIn";
//Get Cookie Language
if (null == Request.Cookies[SESSION_KEY_LANGUAGE])
{
cookie = new HttpCookie(SESSION_KEY_LANGUAGE);
}
else
{
cookie = Request.Cookies[SESSION_KEY_LANGUAGE];
}
if (null == Request.Cookies[SESSION_KEY_LANGUAGE_FORASP])
{
cookieASP = new HttpCookie(SESSION_KEY_LANGUAGE_FORASP);
}
else
{
cookieASP = Request.Cookies[SESSION_KEY_LANGUAGE_FORASP];
}
if (!IsPostBack)
{
//check if chkbtaccess cookies exists
if (null != Request.Cookies[CHECKACCESS])
{
HttpCookie cookieCheckAccess = Request.Cookies[CHECKACCESS];
string strCKBTC = DecryptUsernamePass(cookieCheckAccess.Value.ToString());
if (String.Compare(strCKBTC, string.Empty) != 0)
{
string[] aryCKBTC = strCKBTC.Split(Convert.ToChar(","));
TextBoxUsername.Text = aryCKBTC[0];
TextBoxPassword.Text = aryCKBTC[1];
CheckBoxRememberMe.Checked = true;
}
}
private string DecryptUsernamePassword(string strText)
{
string strDecryptedUsernamePassword = string.Empty;
strDecryptedUsernamePassword = CommonUtil.EncryptDecryptHelper.Decrypt(HttpUtility.UrlDecode(strText, Encoding.Default));
//strDecryptedUsernamePassword = CommonUtil.EncryptDecryptHelper.Decrypt(HttpUtility.UrlDecode(strText, Encoding.Unicode));
return strDecryptedUsernamePassword;
}
private string EncryptUsernamePassword(string strText)
{
string strEncryptedUsernamePassword = string.Empty;
strEncryptedUsernamePassword = HttpUtility.UrlEncode(CommonUtil.EncryptDecryptHelper.Encrypt(strText), Encoding.Default);
//strEncryptedUsernamePassword = HttpUtility.UrlEncode(CommonUtil.EncryptDecryptHelper.Encrypt(strText), Encoding.Unicode);
return strEncryptedUsernamePassword;
}
As a starting point, you should add some logging and exception handling in this code so that you can narrow down what the error could be. It would also make your code more robust and tolerant to invalid cookie values.
An easy way to do this would be to implement the error handler in Global.asax:
protected void Application_Error(Object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
}
This should give you the exception that occurred, which you can then examine (eg. in the debugger, log it to a file, etc...) to see what is causing the error.
For a temporary measure, you could turn off custom errors in web.config:
<customErrors mode="Off"/>
This will enable you to see the exception in your web browser when it occurs. I wouldn't recommend that you use that setting on a live site though.

Categories