Thursday, July 28, 2011

Send an Email via SMTP

Send an Email via SMTP
SMTP stands for Simple Mail Transport Protocol and is a simple, well-defined protocol for exchanging emails with an SMTP server. Thankfully, the specifics of the protocol are handled for you in the System.Net.Mail.SmtpClient class. Figure 1 shows an SMTP client.
Figure 1. It’s very easy to create a simple SMTP client with full attachment support.
To see a full example of a simple email program, look at the EmailClient code example for this chapter. Here is just the method for sending email:

private void SendEmail(string host, int port,
string username, string password,
string from, string to,
string subject, string body,
ICollection attachedFiles)
{
//A MailMessage object must be disposed!
using (MailMessage message = new MailMessage())
{
message.From = new MailAddress(from);
message.To.Add(to);
message.Subject = subject;
message.Body = body;
foreach (string file in attachedFiles)
{
message.Attachments.Add(new Attachment(file));
}

SmtpClient client = new SmtpClient(host, port);
//if your SMTP server requires a password,
//the following line is important
client.Credentials = new NetworkCredential(username, password);
//this send is synchronous. You can also choose
//to send asynchronously
client.Send(message);
}
}
*********************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Utilities;



namespace SMTP_Mail1
{

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//MailMessage message= new MailMessage ();
//message.From =new MailAddress("re@ovi.com");
//message.To.Add(new MailAddress("hi@gmail.com"));
//message.Subject ="Sample Mail";
//message .IsBodyHtml =true ;
//message .Body =" Message to be sent";
//SmtpClient objSMTP =new SmtpClient ("DEV2.Company.com", "25");
//objSMTP .UseDefaultCredentials =true ;
//objSMTP .Send (message );

//MailMessage mailMsg = new MailMessage
// (new MailAddress("spr@gmail.com"), new MailAddress("sh@yahoo.com"));
//mailMsg.Subject = "Sending mail through com Account";
//mailMsg.IsBodyHtml = true;
//mailMsg.Body = "Sening mail through o from asp.net";
//System.Net.NetworkCredential Nc = new System.Net.NetworkCredential("spr@gmail.com", "123456");
//SmtpClient smtpClient = new SmtpClient();
//smtpClient.EnableSsl = true;
//smtpClient.UseDefaultCredentials = false;
//smtpClient.Credentials = Nc;

//smtpClient.Host = "smtp.gmail.com";
//smtpClient.Port = 625;
//smtpClient.Send(mailMsg);
//Response.Write("Mail Successfully sent");




//MailMessage mail = new MailMessage();
//mail.From = new MailAddress("ramesh@ex.com");
//mail.To.Add("hi@.com");
//mail.Subject = "This is an email";
//mail.Body = "this is the bodyof the email";
//SmtpClient smtp = new SmtpClient("127.0.0.1");
//smtp.Credentials = new NetworkCredential("rames","12345");
//smtp.Send(mail);

}
}
}

//public static void CreateTestMessage1(string server, int port)
// {
// string to = "jane@contoso.com";
// string from = "ben@contoso.com";
// string subject = "Using the new SMTP client.";
// string body = @"Using this new feature, you can send an e-mail message from an application very easily.";
// MailMessage message = new MailMessage(from, to, subject, body);
// SmtpClient client = new SmtpClient(server, port);
// // Credentials are necessary if the server requires the client
// // to authenticate before it will send e-mail on the client's behalf.
// client.Credentials = CredentialCache.DefaultNetworkCredentials;

// try {
// client.Send(message);
// }
// catch (Exception ex) {
// Console.WriteLine("Exception caught in CreateTestMessage1(): {0}",
// ex.ToString() );
// }
// }

//private void SendEmail()
//{

// AOSMTPLib.MailClass oSmtp = new AOSMTPLib.MailClass();
// //If you don't have a SMTP server, use the following code
// //send email via DNS lookup, ANSMTP lookups SMTP server automatically.
// oSmtp.ServerAddr = "";

// oSmtp.FromAddr = "test@emailarchitect.net";
// 'Correct, both support@adminsystem.net and test@adminsystem.net
// 'belong to adminsystem.net
// oSmtp.AddRecipient( "Support Team", "support@adminsystem.net", 0 );
// oSmtp.AddRecipient( "Tester", "test@adminsystem.net", 1 );

// 'Incorrect, support@adminsystem.net and test@hotmail.com don't belong
// 'to the same domain.
// 'oSmtp.AddRecipient( "Support Team", "support@adminsystem.net", 0 );
// 'oSmtp.AddRecipient( "Tester", "test@hotmail.com", 1 );

// oSmtp.Subject = "Test";
// oSmtp.BodyText = "Hello, this is a test....";

// if( oSmtp.SendMail() == 0 )
// Console.WriteLine( "Message delivered!" );
// else
// Console.WriteLine( oSmtp.GetLastErrDescription());
//}
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
http://programming4.us/enterprise/2354.aspx

Sending mails using Asp.net
http://www.codeproject.com/KB/aspnet/EmailApplication.aspx
http://www.worldofasp.net/tut/Email_ASP.NET2/Sending_Email_in_ASPNET_20_83.aspx
http://www.codeproject.com/KB/aspnet/smtp_mail.aspx

http://weblogs.asp.net/jalpeshpvadgama/archive/2010/12/29/sending-mail-with-gmail-account-using-

system-net-mail-in-asp-net.aspx

http://www.codeproject.com/KB/aspnet/Send_Emails_in_ASPNET20.aspx

http://www.dev4side.com/community/blog/2010/3/2/send-e-mail-messages-using-sharepoint-smtp.aspx


Sending Mail
http://www.directsharepoint.com/2011/03/send-mail-through-code-in-sharepoint.html

http://www.systemnetmail.com/forums/forum.aspx?forum=2
http://thehumblecoder.wordpress.com/2007/01/04/systemnetmail-basic-example/
http://snahta.blogspot.com/2009/05/configuring-smtp-using-webconfig.html

http://digsharepoint.blogspot.com/2011/04/configuring-incoming-email-in.html
http://www.directsharepoint.com/2011/03/send-mail-through-code-in-sharepoint.html
http://digsharepoint.blogspot.com/2011/04/configuring-outgoing-email-in.html

http://www.codeproject.com/Articles/125119/Configuring-Sharepoint-2010-to-Accept-Incoming-Ema
http://www.sharepointology.com/development/how-to-create-alerts-programmatically/


http://blog.furuknap.net/send-a-sharepoint-document-library-file-as-email

http://www.dev4side.com/community/blog/2010/3/2/send-e-mail-messages-using-sharepoint-smtp.aspx
http://www.aspnetemail.com/Examples.aspx

Tuesday, July 26, 2011

Power Shell 2010

Using PowerShell to register SPGuidance diagnostic areas


The SPGuidance package delivers a set of components to ease certain administration tasks with SP 2010, for example logging.

It hooks in to the built-in SharePoint logging functionality and exposes a set of classes to easily log your own events in the event log, ULS logs or any custom log sources, like a database.

If one would look into this model, you will find that a diagnostic area corresponds to an event source in the event logs. For instance, if I register a diagnostic area called Boom.MyCustomApplication, the event source mentioned in the logs would read the same. This allows support engineers to easily track the source of the event and act accordingly.

However, although the diagnostic area corresponds to the event source, they are not the same. You can register diagnostic areas using the logging component of the SPGuidance set, but this does not mean a corresponding event source is also created. In fact, event sources need to be registered on each front-end separately with sufficient permissions, before the logging component can write to the event log using the diagnostic area as the event source. So how would you create the event sources on each front-end? Well, there are a couple of possible approaches:

1.Use PowerShell to create the sources on each front-end remotely
2.Use a Timer Job to run custom code on each front-end that registers the event source.
In this post, I will show how to do that from PowerShell. These are only two lines of code and the script can be run from a remote location on each front-end.

# First load object models to use
[void][System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.Practices.SharePoint.Common”)


# call the registration method to ensure all registered diagnostic areas are also registered as event sources
[Microsoft.Practices.SharePoint.Common.Logging.DiagnosticsAreaEventSource]::EnsureConfiguredAreasRegistered()


In this script, we first load the assembly Microsoft.Practices.SharePoint.Common.dll. We assume here that the assembly is available from the GAC. In my next post, the solution provided will ensure these assemblies are deployed to the GAC for use. Once we have done that, we can call the static EnsureConfiguredAreasRegistered method of the DiagnosticsAreaEventSource class that will iterate through all the configured and registered diagnostic areas and ensures that an event source is registered for that. The event sources will be registered on the Application event log. During the next couple of days, I will also investigate the possibility of registering the sources to different logs.

In the next post, I will show a custom solution on how to create additional diagnostic areas and use a timer job to ensure the event sources are created at the front end. Till next time!
Posted in PowerShell, SharePoint 2010 | Tagged: Diagnostic Areas, Logger, PowerShell, SharePoint 2010, SharePoint Guidance | 1 Comment »

Using PowerShell to deploy SharePoint Solutions (WSP)
Posted by Patrick Boom on May 31, 2010

The STSADM command line application worked well with previous versions of SharePoint. But the world is progressing and PowerShell will be the new administrative tool for SharePoint. In previous articles, I already showed some amazing powerful scripts that otherwise would require more lines of code. PowerShell offers some great advantages in large farms, as they can be run remotely on target machines, can be signed and therefore be controlled. Building up a repository of scripts or cmdlets to execute common tasks would be worthwhile in the long run.

First off an important thing to note here that this will only work with SharePoint 2010. There are no PowerShell snapins available for 2007, although you could create your own off course. And when run from a SharePoint 2010 Management Shell, the snapins are loaded automatically. But what if you just use the ‘normal’ console? Well, then you would have to register the snapin yourself. Fortunately, MS has already created the PowerShell script that is needed, located at:

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\Config\PowerShell\Registration\SharePoint.ps1.

You could include this script in your scripts to be run first, or just include the command that registers the snapin:

Add-PSSnapin Microsoft.SharePoint.PowerShell

This article covers one of the most basic tasks one would do when administrating SharePoint: Deploy SharePoint solutions (WSP) and enable/disable features.

Working with Solutions
In the ‘old’ days (let us not forget that the stsadm is still there and we have a lot of SharePoint 2007 installations across the globe), the following stsadm command could be used to add a SharePoint solution to SharePoint:

stsadm –o addsolution –filename “D:\Deploy\MySharePointSolution.wsp“

We used the following command to deploy the solution once installed to a specific web application:

stsadm –o deploysolution –name MySharePointSolution.wsp –url http://myspwebappp –allowgacdeployment –immediate

If we would upgrade an existing solution, we would use the following:

stsadm –o upgradesolution –name MySharePointSolution.wsp –filename “D:\Deploy\MySharePointSolution.wsp” -immediate

And finally, we used the following commands to retract and delete a specific solution from the web application:

stsadm –o retractsolution –name MySharePointSolution.wsp –url http://myspwebapp –immediate
stsadm –o deletesolution –name MySharePointSolution.wsp

Now, let us see how we could do above operations with PowerShell. For this, we use the following PowerShell commands:

Add-SPSolution “D:\Deploy\MySharePointSolution.wsp“
Install-SPSolution –Identity MySharePointSolution.wsp –WebApplication http://myspwebapp –GACDeployment

If you would like to add the solution as sandboxed, you would use the Install-SPUserSolution command instead. To upgrade a solution, we specify which solution is to be updated and with which new solution file:

Update-SPSolution –Identity MySharePointSolution.wsp –LiteralPath “D:\Deploy\MySharePointSolution.wsp” –GacDeployment

To retract and remove a solution, we use the following commands:

Uninstall-SPSolution –Identity MySharePointSolution.wsp –WebApplication http://myspwebapp
Remove-SPSolution–Identity MySharePointSolution.wsp

Working with features
Similarly, commands exist for working with features. The stsadm equivalents:

stsadm –o activatefeature –name MyFeatureName –url http://myspwebapp
stsadm –o deactivatefeature –name MyFeatureName –url http://myspwebapp

Needless to say, there are easy equivalents in PowerShell:

Enable-SPFeature –Identity MyFeatureNameOrGuid –url http://myspwebapp
Disable-SPFeature –Identity MyFeatureNameOrGuid –url http://myspwebapp

As you can see, PowerShell will completely replace stsadm as the administrative command line tool for SharePoint. Better to start using it as the next version of SharePoint will not have a stsadm command line tool I suspect. To conclude, let us take a look at a script that enables a certain feature across all site collections and sites in a farm. As an example, I have taken the SharePoint Server Enterprise Site Features feature with ID 0806d127-06e6-447a-980e-2e90b03101b8.

Add-PSSnapin Microsoft.SharePoint.PowerShell
$WebApplications = Get-SPWebApplication

foreach ($webapp in $WebApplications) {
$Id = $webapp.Id
Write-Host “Processing web application $Id …”
$sites = $webapp.Sites
foreach ($site in $sites) {
Write-Host Processing site $site.Id
$webs = $site.AllWebs
foreach ($web in $webs) {
Write-Host Processing web $web.Title
if ($web.Features["0806d127-06e6-447a-980e-2e90b03101b8"] -eq $null) {
Enable-SPFeature -Identity 0806d127-06e6-447a-980e-2e90b03101b8 -url $web.Url -Confirm:$false
} else {
Disable-SPFeature -Identity 0806d127-06e6-447a-980e-2e90b03101b8 -url $web.Url -Confirm:$false
}
}
}
}


Please note though that above script will work for small site collections. But for larger object hierarchies, you will need to include proper memory management (SPAssignment) to ensure proper release of memory.

As always, have fun coding.
Posted in PowerShell, SharePoint 2010 | Tagged: Disable Feature, Enable Feature, PowerShell, SharePoint 2010, Snapin, Solutions, WSP | 12 Comments »

Using Powershell to change registry keys for search crawler
Posted by Patrick Boom on May 17, 2010

In one of my earlier posts, I described a way to use PowerShell to change settings in a SharePoint 2007 farm. That started out as my first PowerShell script and I have witnessed the power behind it all.

In our project, we needed a server wide adjustment of the registry for the SharePoint index servers across all farms. Of course, multiple ways to do this, but here is where PowerShell shows its power. I needed to change two registry settings, both covering the maximum file size that is crawled by the indexer. By default, this is 16 MB (mutiplied by 4), leaving a total of 64 MB indexed in each file. As we now enlarged trhe maximum upload size to 100 MB, we needed the crawl settings to be adjusted. To be honest, I was quite surprised it would only take me two lines of script to make this work. The registry keys in question were those below:

HKLM\SYSTEM\CURRENTCONTROLSET\
HKLM\SOFTWARE\MICROSOFT\OFFICE SERVER\12.0\SEARCH\GLOBAL\GATHERING MANAGER

And to change these, the following lines of script would suffice. I have also added some additional lines to check whether we actually are at the index server, otherwise, these changes would have no effect. Pay special attention to the way the registry is accessed. In principle, it is accessed as a file path.

Set Search Crawler Settings

Write-Host “Set registry values for search”
Write-Host “=======================================================================”
Write-Host “”

if ( (Get-Itemproperty -Path “hklm:\SOFTWARE\Microsoft\Office Server\12.0\Search\Global”).Index -eq 1 ) {
Write-Host -f green “Validated that this server is the index Server “
} else {
throw “This server is the not the SharePoint index Server “
}

Write-Host “Processing MaxTextFilterBytes”
set-itemproperty “hklm:\system\currentcontrolset\control\contentindex” MaxTextFilterBytes -type “DWord” -value “104857600″ -force

Write-Host -f green “Done…”
Write-Host “Processing MaxDownloadSize”
set-itemproperty “hklm:\software\microsoft\office server\12.0\search\global\gathering manager” MaxDownloadSize -type “DWord” -value “26214400″ -force

Write-Host -f green “Done…”
Write-Host -f green “Script completed”
Write-Host “=======================================================================”
Write-Host “”

In addition to these registry changes, a couple of more settings need to be set to get the entire maximum upload size working. Above registry changes instruct the search crawler to enlarge the crawled file size. But this still does not allow SharePoint to upload larger files. Besides SharePoint changes, OS level changes also need to be make on the client side to allow the WebDAV protocol to upload larger files. These are however out of scope of this blog post. In short, three steps are needed to support larger files on SharePoint:

1. Change the crawler settings to support larger files in the registry.
2. Change the Maximum File Size for the Web Application.
3. Change the connection time out setting on the SharePoint search service. (OSearch)

To change the crawler settings, the PowerShell script is located above. To execute steps 2 and 3 in above list, the following PowerShell scripts do the job:

Set Maximum File Size for Web Application

[Void][System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”)
$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local
if ($farm -eq $null ) {
throw “Could not connect to the SharePoint farm”
}

Write-Host “”
Write-Host “====================================================================”
Write-Host “”
$websvcs = new-object Microsoft.SharePoint.Administration.SPWebServiceCollection($farm)
if ($websvcs.Length -eq 0 ) {
throw “Could not connect to any SharePoint Web Service in the farm”
}
$FileSize = 100
$MaximumFileSize = 0

foreach ($websvc in $websvcs) {
foreach ($webapp in $websvc.WebApplications) {
if (($webapp.MaximumFileSize -ne $FileSize) -and ($webapp.MaximumFileSize -lt $FileSize))
{
Write-Host “Set file size for web application $webapp.Name”
$webapp.MaximumFileSize = $FileSize
$MaximumFileSize = $webapp.MaximumFileSize
$webapp.Update()
Write-Host -f green “New file size $MaximumFileSize MB”
} else {
Write-Host -f green “Maximum file size for $($webapp.Name) was already set to or larger than $FileSize MB”
}
}
}
Write-Host -f green “Script completed”
Write-Host “====================================================================”

Set Connection TimeOut for Search Crawler

[Void][System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”)
$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local
if ($farm -eq $null ) {
throw “Could not connect to the SharePoint farm”
}

Write-Host “====================================================================”
Write-Host “”

$searchsvcs = @($farm.Services | where -FilterScript {$_.GetType() -eq [Microsoft.Office.Server.Search.Administration.SearchService]})
if ($searchsvcs.Length -eq 0 ) {
throw “Could not connect to any SharePoint Search Service in the farm”
}

$TimeOut = 90
foreach ($searchsvc in $searchsvcs) {
if (($searchsvc.ConnectionTimeOut -ne $Timeout) -or ($searchsvc.AcknowledgementTimeout -ne $Timeout))
{
Write-Host “Set connection and acknoledgement timeouts for $($searchsvc.Name) to $Timeout”
$searchsvc.ConnectionTimeOut = $Timeout;
$searchsvc.AcknowledgementTimeout = $Timeout;
$searchsvc.Update()
Write-Host -f green “Done…”

} else {
Write-Host -f green “Connection timeout for $($searchsvc.Name) was already set to $Timeout”
}
}

Write-Host -f green “Script completed”
Write-Host “====================================================================”

Thats it! Using three simple scripts, we can change the settings in our entire farm to use new file upload settings and have it supported by the sarch crawler.

CU!
Posted in PowerShell, SharePoint 2007 | Tagged: Crawl Size, File Size, Index, PowerShell, Search, SharePoint 2007 | Leave a Comment »

Using PowerShell 1.0 to change web application setting in SharePoint 2007
Posted by Patrick Boom on April 27, 2010

Sure, PowerShell is already available for a long time on Windows 2003, also in combination with SharePoint 2007. But untill this time, I could avoid the use

But with PowerShell 2.0 becoming more important to SharePoint 2010, it was time to dive a little bit into this scripting language.
At my current customer, the maximum upload size for documents needed to be increased to 100 MB, from the default setting of 50 Mb. Obviously, we could do this using the Central Admin, but it becomes more of a problem when there are a lot of web applications, hence the choice for scripting. Also, a lot of other settings on different layers need to be adjusted to make this work, for example WebDAV settings in Vista and registry settings for the crawler, but this post only covers the PowerShell script to change the setting in the web application general settings.

So, below is my first PowerShell script. Note that this script is by no means the best one. It could be extended with exception handling, parameters to specify action and size, but for the purpose of this post, it is clear enough.

[Void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local

Write-Host("Get all web applications within each web service")
$websvcs = @($farm.Services | where -FilterScript {$_.GetType() -eq [Microsoft.SharePoint.Administration.SPWebService]})

foreach ($websvc in $websvcs) {
foreach ($webpp in $websvc.WebApplications) {
$webapp.MaximumFileSize = 100
$webapp.Update()
}
}Not much exiting stuff going on here right? First I load the Microsoft.SharePoint.dll assembly by calling the LoadWithPartialName method of the System.Reflection.Assembly class. Because this method is static, we use the ‘::’ operator. Once loaded, we get the local farm by calling the SPFarm.Local method. Again, becuase Local is a static method, we use the ‘::’ operator.

When done, we get all SPWebService objects within the Services collection of the Farm. This line is a little less obvious. In C#, we would use the SPFarm.Services.GetValue() method. In PowerShell, we filter the Services collection by using a sort of SQL like syntax. Get all services where type (GetType()) equals (-eq) Microsoft.SharePoint.Administration.SPWebService. The rest speaks for itself and looks quite a lot like C# code.

There you have it, my first PowerShell Naturally, we could create a simple command line utility that does the same using C#, but these scripts are created faster and are also easy adjustable to fit needs.

So, in short, with SharePoint 2010 embracing PowerShell, we have no choice then to venture in the world of PowerShell.



introduction to Powershell

Saturday, July 02, 2011

Sharepoint 2010 Authentication Methods

SharePoint Security – SharePoint Authentication Part 1

Running SharePoint on Windows Server 2008 R2 offers a wealth of possible SharePoint authentication scenarios. You are no longer limited to the basic, often unsecure authentication types.
In this article I will cover the SharePoint authentication methods, which closely mirror Windows Server 2008 R2 authentication scenarios since both SharePoint relies on Windows Server for much of its security. I will start with an overview of the primary authentication methods and then I will demonstrate how to configure authentication.
SharePoint Authentication Methods
There are three general types of authentication for SharePoint. The first two base types of authentication modes in SharePoint 2010 are Claims Based Authentication (which is new in SharePoint Server 2010) and Classic Mode Authentication.

Authentication selection window during SharePoint application setup.
Classic Mode Authentication
This is the native, classic type of authentication for Windows systems. There are several methods of Windows Authentication:
• Anonymous Authentication: this method allows external and unauthorized users to access the resources. No credentials are required in this method. This method is mostly used for Internet-enabled sites in SharePoint for Internet Sites licensing.
• Basic Authentication: This is an inherently insecure method and I recommend not using it. The authorization credentials are sent in clear-text, without any encryption which nowadays is extremely easy to snoop by attacker. This type of authentication should only be used in case of compatibility issues (with browsers, web proxies or firewalls) and only with a secure SSL certificate which encrypt the sensitive network traffic (see SharePoint SSL Authentication). Sometimes, old software deployed in the enterprise requires using Basic Authentication (such as old monitoring software) – if you encounter these situations, try to use SSL with Basic Authentication to encrypt the traffic “manually”.
• Digest Authentication: This is similar to Basic Authentication, but it provides greater security since the credentials are encrypted and there is no way to intercept the credentials along the way in the traffic route.
• Certificate Authentication: This method offers the public key certificate mapping authorization. SSL encryption is used for this authentication method. It is not recommended to use this type of authentication over internet traffic.
• NTLM Authentication: This is the native authentication method for most Microsoft applications (including SharePoint), this method is secure and encrypts credentials before they are sent over the network. If you want to move your entire network authentication to Kerberos, you will have to disable NTLM because on most systems it is default authentication method.
• Negotiate Authentication: You can use it this with either NTLM or Kerberos authentication (with Kerberos is the default). On the client side you have to provide SPN (Service Principal Name) and UPN (User Principal Name) for the account.

Blog Archive