Wednesday, October 19, 2011

Second post back problem!!!


Windows SharePoint Services JavaScript has a “form onSubmit wrapper” which is used to override the default form action. This work is put in place to ensure that certain types of URLs, which may contain double byte characters, will fully work across most postback and asynchronous callback scenarios. However, if your scenarios do not involve double byte character URLs, you may successful disable this workaround and gain the ability to use ASP.NET AJAX UpdatePanels.

To do this, you may need to register a client startup script which disables this workaround, in addition to resetting the default form action:



This script may be directly embedded in the page. Or write a function like this:

private void EnsureUpdatePanelFixups()
{
if (this.Page.Form != null)
{
string formOnSubmitAtt = this.Page.Form.Attributes["onsubmit"];
if (formOnSubmitAtt == “return _spFormOnSubmitWrapper();”)
{
this.Page.Form.Attributes["onsubmit"] = “_spFormOnSubmitWrapper();”;
}
}
ScriptManager.RegisterStartupScript(this, typeof(UpdatePanel), “UpdatePanelFixup”, “_spOriginalFormAction = document.forms[0].action; _spSuppressFormOnSubmitWrapper=true;”, true);
}

This solves the second post back problem.



Following is the script for  emulate post back in sharepint.



Page.ClientScript.RegisterStartupScript(Page.GetType(), "msg", "script type='text/javascript'>_spOriginalFormAction = document.forms[0].action; _spSuppressFormOnSubmitWrapper=true;",false);




Wednesday, August 3, 2011

Custom Forgot Password form for FBA Sharepoint...can be deployed to layouts








using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.Mail;

public partial class _Default : System.Web.UI.Page
{

private void AutoUnlockUser(string username)
{
//If user try with wrong user name and password combintaion 5 times he will be locked.
//Using this method he will be unlocked after specified minutes, In this case it is 60.
MembershipUser mu = Membership.GetUser(txtUserName.Text);
if ((mu != null) && (mu.IsLockedOut) && (mu.LastLockoutDate.ToUniversalTime().AddMinutes(60) < DateTime.UtcNow))
{
mu.UnlockUser();
}
}

protected void Page_Load(object sender, EventArgs e)
{

if (IsPostBack)
{
AutoUnlockUser(txtUserName.Text);
MembershipUser user1 = Membership.GetUser(txtUserName.Text);
if (user1 == null)
{
lblErrror.Text = "Sorry, the entered email doent match to any valid user, please try again.";
}
else
{

string newpassword = user1.ResetPassword();


MailMessage objemail = new MailMessage();
objemail.To = "";
objemail.From = "";
objemail.Subject = "";
objemail.Body = "" + newpassword + " . Your username is " +txtUserName.Text +"." ;
objemail.BodyFormat = System.Web.Mail.MailFormat.Html;
objemail.Priority = MailPriority.High;
objemail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
objemail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "emailusername");
objemail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "password");
SmtpMail.SmtpServer = "emailservername";
SmtpMail.Send(objemail);
lblErrror.Text = "Your Password has been mailed to you!";
}
}
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{

}
}

Friday, July 29, 2011

Sharepoint Dataview Last 7 days filter

I am creating a dataview within Sharepoint Designer 2007 that uses a Sharepoint list as its database. All is fine and is working well but I want to filter from 7 days before today’s date. I could manually set the date but then I would have to change it everyday…

My solution is to set the filter for Current date and save.

Sharepoint Filter Criteria

Sharepoint Filter Criteria

Go to code view and locate the “Select Command” for the filter. Within that command there should be a entry like:

Type="DateTime"><Today

or something simular. Change to

Type="DateTime"><Today OffsetDays="-7"

where 7 being the number of days you wish to filter from. You also need to use " for ” and > for > etc

SharePoint Data View Trick

When making a new data view certain fields are too long to fit in the cell/div that you need it too. So here’s some XSLT I’ve been using to truncate a field.



                <a href="@FileRef”> 
<xsl:variable name="truncate-length” select="40”/>
<xsl:value-of select="substring(@Title,1, $truncate-length)”/>
<xsl:if test="string-length(@Title) > $truncate-length”>
<xsl:text>...xsl:text>
xsl:if>
a>

The above example runs inline, and grabs the URL and Title fields from a list item. It then truncates the Title to the length specified in the truncate-length variable to however many characters you want to use and then appends on ... to the end. Fairly straightforward but can be hard for some to build from scratch.

Next, how to customize the built in [Current Date] field. Every time you make a filter off of [Current Date] an entry for it gets added in the code behind for the data view under the tag “SharePoint:SPDataSource”. The easiest way I’ve found to edit this field is to export it to notepad, or any basic text editor and replace the masked characters in it with the right ones

& lt; = < 
& gt; = >
& quot; = "

That will make it much easier to read

<View>     <Query>         <Where>             <And>                 <Geq>                     <FieldRef Name="EventDate”/>                     <Value Type="Text”>                         <Today/>                     Value>                 Geq>                 <Leq>                     <FieldRef Name="EndDate”/>                     <Value Type="Text”>                         <Today OffsetDays="14”/>                     Value>                 Leq>             And>         Where>         <OrderBy>             <FieldRef Name="EventDate” Ascending="TRUE”/>         OrderBy>     Query> View>

Unfortunately you can’t paste this much more readable code back in to SharePoint designer, but you can at least find where you need to edit it. In this case were looking for the Today tag after EndDate. I added the OffsetDays attribute and gave it a length of 14 days. You can also go negative for this value, so you can see things from previous times rather than future ones.


Thursday, July 28, 2011

AD password Change

It was always a nice to have for our extranet environment to have a webpart available within SharePoint to let users change their password instead of using an isolated .NET web application (no.. not a SharePoint WebApplication ;)). As it turned out in the last couple of days it became a must-have since the webapplication didn't seem to work properly anymore. Please note that everything did run smoothly for 2yrs. Although a couple of weeks ago we migrated the environment from 2003 to 2007, ever since users received errors like "The server is not operational" when they tried to change their password.

So I once again turned on my best friend Google and try to find any free/opensource ChangePassword webparts. Unfortunately I couldn't find one so I wrote one myself (more fun anyway eh? ;)) Luckily enough I could re-use some of the code that I used to build the webapplication.

So how does my webpart look like in code?

using ActiveDs;
using Microsoft.SharePoint; using Microsoft.SharePoint.WebControls; using System; using System.DirectoryServices; using System.Web.UI.WebControls;   namespace ChangePassword {     public class ChangePasswordWebpart : System.Web.UI.WebControls.WebParts.WebPart     {          private TextBox oldpassword;         private TextBox newpassword;         private TextBox checknewpassword;          private LinkButton btn;         private Label output;           protected override void CreateChildControls()         {             this.oldpassword = new TextBox();             this.oldpassword.TextMode = TextBoxMode.Password;             this.Controls.Add(oldpassword);              this.newpassword = new TextBox();             this.newpassword.TextMode = TextBoxMode.Password;             this.Controls.Add(newpassword);              this.checknewpassword = new TextBox();             this.checknewpassword.TextMode = TextBoxMode.Password;             this.Controls.Add(checknewpassword);              this.btn = new LinkButton();             this.btn.Click += new EventHandler(btn_Click);             this.btn.Text = "Change Password";             this.Controls.Add(btn);              this.output = new Label();             this.Controls.Add(output);              base.CreateChildControls();         }                   void btn_Click(object sender, EventArgs e)         {              if (newpassword.Text.ToString() == checknewpassword.Text.ToString())             {                  SPWeb webContext = SPControl.GetContextWeb(Context);                 string strLoginName = webContext.CurrentUser.LoginName;                  int iPosition = strLoginName.IndexOf("\\") + 1;                 strLoginName = strLoginName.Substring(iPosition);                                    DirectoryEntry entry = new DirectoryEntry("LDAP://domain.com", strLoginName, oldpassword.Text.ToString(), AuthenticationTypes.Secure);                 DirectorySearcher search = new DirectorySearcher(entry);                 search.Filter = "(SAMAccountName=" + strLoginName + ")";                 search.SearchScope = SearchScope.Subtree;                 search.CacheResults = false;                  SearchResultCollection results = search.FindAll();                 if (results.Count > 0)                 {                     foreach (SearchResult result in results)                     {                         try                         {                             entry = result.GetDirectoryEntry();                         }                         catch (Exception error) { output.Text += "
"
+ error.Message.ToString(); } } try { entry.Invoke("ChangePassword", new object[] { oldpassword.Text.ToString(), newpassword.Text.ToString() }); entry.CommitChanges(); output.Text += "
Password is changed"
; } catch (Exception) { output.Text += " Password couldn't be changed due to restrictions"; } } else { output.Text += "
User not found or bad password"
; } } else { output.Text += "
Passwords don't match"
; } } protected override void Render(System.Web.UI.HtmlTextWriter writer) { string strLoginName = string.Empty; try { SPWeb webContext = SPControl.GetContextWeb(Context); strLoginName = webContext.CurrentUser.LoginName; } catch (Exception) { output.Text += "
Please sign in first using the 'Sign In' button above"
; } if (strLoginName != string.Empty) { writer.Write(""); writer.Write(""); writer.Write(""); writer.Write(""); writer.Write(""); writer.Write(""); writer.Write(""); writer.Write(""); writer.Write(""); writer.Write(""); writer.Write(""); writer.Write(""); writer.Write(""); writer.Write(""); writer.Write(""); writer.Write(""); writer.Write(""); writer.Write(""); writer.Write(""); writer.Write(""); writer.Write(""); writer.Write("
"); writer.Write("Current password:"); writer.Write(""); oldpassword.RenderControl(writer); writer.Write(""); writer.Write("
"); writer.Write("New password:"); writer.Write(""); newpassword.RenderControl(writer); writer.Write(""); writer.Write("
"); writer.Write("Confirm new password:"); writer.Write(""); checknewpassword.RenderControl(writer); writer.Write(""); writer.Write("
"); writer.Write(""); btn.RenderControl(writer); writer.Write(""); writer.Write("
"
); output.RenderControl(writer); } else { output.RenderControl(writer); } } } }

You have to reference the "System.DirectoryServices" and the COM "Active DS Type Library", also when you package everything together, make sure that the Interop.ActiveDs.dll is included otherwise it doesn't work.

And at runtime it looks like this:

Wednesday, July 6, 2011

Automatically create a 2010 exchange mailbox

SecureString password = new SecureString();
string str_password = "pass";
string username = "userr";

string liveIdconnectionUri = "http://exchange.wenatex.com/Powershell?serializationLevel=Full";

foreach (char x in str_password)
{
password
.AppendChar(x);
}

PSCredential credential = new PSCredential(username, password);

// Set the connection Info
WSManConnectionInfo connectionInfo = new WSManConnectionInfo((new Uri(liveIdconnectionUri)), "http://schemas.microsoft.com/powershell/Microsoft.Exchange",
credential
);

connectionInfo
.AuthenticationMechanism = AuthenticationMechanism.Default;

// create a runspace on a remote path
// the returned instance must be of type RemoteRunspace

Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);

PowerShell powershell = PowerShell.Create();
PSCommand command = new PSCommand();

command
.AddCommand("Enable-Mailbox");
command
.AddParameter("Identity", usercommonname);
command
.AddParameter("Alias", userlogonname);
command
.AddParameter("Database", "MBX_SBG_01");

powershell
.Commands = command;
try
{
// open the remote runspace
runspace
.Open();
// associate the runspace with powershell
powershell
.Runspace = runspace;
// invoke the powershell to obtain the results
return = powershell.Invoke();
}
catch (Exception ex)
{

Console.WriteLine(ex.Message);
}
finally
{
// dispose the runspace and enable garbage collection
runspace
.Dispose();
runspace
= null;
// Finally dispose the powershell and set all variables to null to free
// up any resources.
powershell
.Dispose();
powershell
= null;
}