C#, HTML, JavaScript, Programming, Web

Write a JavaScript/HTML Form Submit Post From C# APSX Code Behind

There may be a case where you are taking information from a form and need to post it to a web site somewhere else. One quick method of performing that post is to execute it from the code behind using C# (via context.response) and JavaScript. This is a scaled down example of a case where I was submitting a POST from the code behind of a web part control:

A couple things to note:

  • You can add as many fields as you wish to post, I am only using two
  • You can use string.Format to get C# variables to put directly in the POST
protected string value1;
protected string value2;

value1 = "something";
value2 = "something else";

Context.Response.Write("<form name='Form1' id='Form1' method='post' action='https://www.mywebsitetopostto.com/example'>");
Context.Response.Write("<input type='hidden' name='__VIEWSTATE' id='__VIEWSTATE' value='' />");
Context.Response.Write(string.Format("<input type='hidden' name='txtValue1' id='txtValue1' runat='server' value='{0}' />", value1));
Context.Response.Write(string.Format("<input type='hidden' name='txtValue2' id='txtValue2' runat='server' value='{0}' />", value2));
Context.Response.Write("</form>");
Context.Response.Write("document.Form1.submit();");
Context.Response.Flush();
Context.Response.End();

Ideally you would use this in a case where¬†you are posting content and the page you are posting to will process and serve something after the form that receives your post processes what you sent. Please do not use this snippet and blame me for a blank page ūüôā

C#, Programming, SharePoint, Web

Convert A Links List To A DropDownList By A Web Part In SharePoint 2013 (C#)

So I have been enjoying the benefit of Mike Smith’s article for a while now (http://techtrainingnotes.blogspot.com/2010/12/sharepoint-convert-links-list-to.html). A client I did a project for was wanting to carry this functionality forward to 2013. The problem: this method didn’t work in 2013.

So I took a programmatic approach to lose the JavaScript dependency. It also will sort the dropdown names by what you type as the description by using the sortedlist in the code behind. It’s fairly simple, here’s what I did:

  • Created a links list and populated some URLs and Descriptions (!!! You need both for below to work, otherwise remove the description dependency in my code !!!)
  • Create a SharePoint 2013 Visual Web Part project
  • Add the dropdownlist control to the control

In the .ascx control I have:

<asp:DropDownList ID="linkDropDown" runat="server" Font-Names="Arial" Font-Size="10pt"
Width="300px" OnSelectedIndexChanged="linkDropDown_SelectedIndexChanged" AutoPostBack="true" EnableViewState="true">
<asp:ListItem Text="Link to ..." Value="#"></asp:ListItem>
</asp:DropDownList>
  • Add the code to the code behind of the control

Now the code behind, here’s my using statements:

using System;
using System.ComponentModel;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Collections;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

and here is what I have in the Page_Load and the SelectedIndexChanged event

protected void linkDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
Context.Response.Redirect(linkDropDown.SelectedValue.ToString());
}

protected void Page_Load(object sender, EventArgs e)
{
SortedList sortedLists = new SortedList();

using (SPSite siteCol = new SPSite("http://mysharepoint2013site/"))
{
using (SPWeb web = siteCol.RootWeb)
{
SPList list = web.GetList("/Lists/NameOfLinksList");
SPListItemCollection items = list.GetItems();

foreach (SPListItem it in items)
{
SPFieldUrlValue fieldValue = new SPFieldUrlValue(it["URL"].ToString());
string description = fieldValue.Description;
string url = fieldValue.Url;
sortedLists.Add(description, url);
}
}

IDictionaryEnumerator enumerator = sortedLists.GetEnumerator();
while (enumerator.MoveNext())
{
ListItem listitem = new ListItem();
listitem.Text = enumerator.Key.ToString();
listitem.Value = enumerator.Value.ToString();
linkDropDown.Items.Add(new ListItem(listitem.Text.ToString(), listitem.Value.ToString()));
}
}

Deploy and enjoy!

Sitecore, Web

Sluggish Sitecore Development Environment? Here’s An Easy Method To Disable Sitecore Analytics

When you install a new 8.0 instance of Sitecore you will find the site can be laggy and sluggish to load. To speed up your dev environment I would recommend this easy fix.

First create a folder called z in your app config sitecore path: C:\inetpub\wwwroot\yoursitecore\Website\App_Config\z

Then, create a file called zwoa.config and paste the following in:

<configuration xmlns:patch="<a href="http://www.sitecore.net/xmlconfig/">http://www.sitecore.net/xmlconfig/</a>">
 <sitecore>
 <pipelines>
 <initialize>
 <processor type="Sitecore.Pipelines.Initialize.PrecompileSpeakViews, Sitecore.Speak.Clientpro" >
 <patch:delete />
 </processor>
 <processor type="Sitecore.ContentTesting.Pipelines.Initialize.RegisterContentTestingCommandRoute, Sitecore.ContentTesting" >
 <patch:delete />
 </processor>
 <processor type="Sitecore.Pipelines.Initialize.PrecompileSpeakViews, Sitecore.Speak.Client" use="ContentTesting" >
 <patch:delete />
 </processor>
 </initialize>
 <mvc.renderPageExtenders>
 <processor patch:after="processor[@type='Sitecore.Mvc.ExperienceEditor.Pipelines.RenderPageExtenders.RenderExtendersContainer, Sitecore.Mvc.ExperienceEditor']" type="Sitecore.Mvc.ExperienceEditor.Pipelines.RenderPageExtenders.RenderPageEditorExtender, Sitecore.Mvc.ExperienceEditor"></processor>
 <processor patch:after="processor[@type='Sitecore.Mvc.ExperienceEditor.Pipelines.RenderPageExtenders.RenderExtendersContainer, Sitecore.Mvc.ExperienceEditor']" type="Sitecore.Mvc.ExperienceEditor.Pipelines.RenderPageExtenders.RenderPreviewExtender, Sitecore.Mvc.ExperienceEditor"></processor>
 <processor patch:after="processor[@type='Sitecore.Mvc.ExperienceEditor.Pipelines.RenderPageExtenders.RenderExtendersContainer, Sitecore.Mvc.ExperienceEditor']" type="Sitecore.Mvc.ExperienceEditor.Pipelines.RenderPageExtenders.RenderDebugExtender, Sitecore.Mvc.ExperienceEditor"></processor>
 <processor type=""Sitecore.Mvc.ExperienceEditor.Pipelines.RenderPageExtenders.SpeakRibbon.RenderPageEditorSpeakExtender, Sitecore.Mvc.ExperienceEditor" >
 <patch:delete />
 </processor>
 </mvc.renderPageExtenders>
 </pipelines>
 <settings>
 <setting name="Analytics.Enabled" > <patch:attribute name="value" value="false" />
 </setting>
 </settings>
 </sitecore>
 </configuration>

Refresh your Sitecore in a web browser and watch it go!

API, C#, Programming, SMS, Web Service

C# Send A SMS Text Message Programmatically Using Clickatell HTTP API

I would start off by heading here to better understand the Clickatell HTTP API: https://www.clickatell.com/apis-scripts/apis/http-s/. If you are interested they allow you 10 free text messages to try it out before you buy a package. Just sign up for an account and create your HTTP API and use your information to populate the snippet below.

For a particular project I am using this API to send out texts for verification purposes. I am using my method inside of a web service to send the information about a user as well as their pre-generated pin. Of course it is a lot different in my project but I am providing the bare bones below.

If you are a skimmer and you skipped reading anything I said above then here you go:

Code for MyWebRequest class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using System.Configuration;

namespace CustomWebServices
{
public class MyWebRequest
{
private WebRequest request;
private Stream dataStream;

private string status;

public String Status
{
get
{
return status;
}
set
{
status = value;
}
}

public MyWebRequest(string url)
{
// Create a request using a URL that can receive a post.

request = WebRequest.Create(url);
}

public MyWebRequest(string url, string method)
: this(url)
{

if (method.Equals("GET") || method.Equals("POST"))
{
// Set the Method property of the request to POST.
request.Method = method;
}
else
{
throw new Exception("Invalid Method Type");
}
}

public MyWebRequest(string url, string method, string data)
: this(url, method)
{

// Create POST data and convert it to a byte array.
string postData = data;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);

// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";

// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;

// Get the request stream.
dataStream = request.GetRequestStream();

// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);

// Close the Stream object.
dataStream.Close();

}

public string GetResponse()
{
// Get the original response.
WebResponse response = request.GetResponse();

this.Status = ((HttpWebResponse)response).StatusDescription;

// Get the stream containing all content returned by the requested server.
dataStream = response.GetResponseStream();

// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);

// Read the content fully up to the end.
string responseFromServer = reader.ReadToEnd();

// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();

return responseFromServer;
}
}
}

And now the code for the method itself:

public string SendText(string mobile, string pin)
{
// Make sure to add the country code to ensure the text goes through
string phoneCheck = "";
if (mobile.Length == 10)
{
phoneCheck = "1" + mobile;
}
// Clickatell settings
string textmessage = "Your verification pin is " + pin;
string parameters = "";
parameters = "user=yourclickatellusername";
parameters = parameters + "&amp;password=yourclickatellpassword";
parameters = parameters + "&amp;api_id=youruniqueclickatellhttpapiid";
parameters = parameters + "&amp;to=" + phoneCheck;
parameters = parameters + "&amp;text=" + textmessage;
parameters = parameters + "&amp;mo=1";
parameters = parameters + "&amp;from=15558675309";
MyWebRequest myRequest = new MyWebRequest("<a href="http://api.clickatell.com/http/sendmsg">http://api.clickatell.com/http/sendmsg</a>", "POST", parameters);
myRequest.GetResponse();
} // SendText

* Note: If you put this call on a server that will require a proxy then add it to your MyWebRequest class

C#, SharePoint, Web Service

Add An Item To A Custom SharePoint List Using Batch XML With A Web Service (C#)

If you have multiple active directory environments and SharePoint instances in both of those environments then you will understand why I posted this.

I received a requirement that while users from a separate domain and SharePoint instance would need to fill out a form on their SharePoint and have the form submission be sent to the other SharePoint instance (on the other domain). This was because they did not want to mix and mingle with forest trusting or having users to have two separate AD accounts to manage the information. Say what?!

After some initial discovery I had reached a couple quick conclusions:

– SharePoints on different domains do not talk well to each other without trust

– Using the built-in lists service on SharePoint has to be done on the server itself unless you are going to have an instance stood up somewhere on the same domain that has all the required SharePoint dlls to be referenced

All being said, here is an example of what I used as a web service I placed on the SharePoint server that calls the lists web service doing a list add using batch XML:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Administration.Claims;
using Microsoft.SharePoint.WebControls;

namespace CopyOverItemFromOtherSP
{

{
public string CopyOverFromOtherDomain(string userName, string Name, string userEmail,
string userPhone, string listColumn1, string listColumn2, string listColumn3,
string Comments)
{
Boolean done = false;

/* Declare and initialize a variable for the Lists Web service. */
sitesWebServiceLists.Lists listService = new sitesWebServiceLists.Lists();

/* Authenticate the current user by passing their default credentials to the Web service from the system credential cache. */
listService.Credentials = System.Net.CredentialCache.DefaultCredentials;

/* Set the Url property of the service for the path to a subsite. */
// Service URLs - MUST CHANGE TO POINT TO SPECIFIC SERVICE ENVIRONMENT
// Change the web reference URL on the sitesWebServiceLists web service reference to be the address
// that you are wanting to used based on the environment that you want to write to
listService.Url = "<a href="#">http://sharepointtocopyitemto/_vti_bin/Lists.asmx</a>";

/* Get Name attribute values (GUIDs) for list and view. */
System.Xml.XmlNode ndListView = listService.GetListAndView("NameOfSharePointList", "");
string strListID = ndListView.ChildNodes[0].Attributes["Name"].Value;
string strViewID = ndListView.ChildNodes[1].Attributes["Name"].Value;

/* Create an XmlDocument object and construct a Batch element and its
attributes. Note that an empty ViewName parameter causes the method to use the default view. */
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
System.Xml.XmlElement batchElement = doc.CreateElement("Batch");
batchElement.SetAttribute("OnError", "Continue");
batchElement.SetAttribute("ListVersion", "1");
batchElement.SetAttribute("ViewName", strViewID);

/* Specify methods for the batch post using CAML. To update or delete,
specify the ID of the item, and to update or add, specify
the value to place in the specified column. */
batchElement.InnerXml = "<Method ID='1' Cmd='New'>" +
"<Field Name='ID'>New</Field>" +
"<Field Name='Title'>" + userName.ToString() + "</Field>" +
"<Field Name='Name'>" + Name.ToString() + "</Field>" +
"<Field Name='userEmail'>" + userEmail.ToString() + "</Field>" +
"<Field Name='userPhone'>" + userPhone.ToString() + "</Field>" +
"<Field Name='listColumn1'>" + listColumn1.ToString() + "</Field>" +
"<Field Name='listColumn2'>" + listColumn2.ToString() + "</Field>" +
"<Field Name='listColumn3'>" + listColumn3.ToString() + "</Field>" +
"<Field Name='Comments'>" + Comments.ToString() + "</Field>" +
"</Method>";

/* Update list items. This example uses the list GUID, which is recommended,
but the list display name will also work. */
try
{
listService.UpdateListItems(strListID, batchElement);
done = true;
}
catch
{

}
if (done == true)
{
return done.ToString();
}
else
{
return done.ToString();
}
}
}
}