Tuesday, June 28, 2011

Fetching user names and E-mail Addresses from SPGroups

There are various groups present over a SharePoint Site. The below code can extract email addresses of all the existing users in all the groups.

Code to get the user names:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{

string username;

SPSite spsite = new SPSite("site url"); //Ex: http://adfsaccount:2222/
SPWeb web= spsite.RootWeb;
SPUserCollection userlist= web.AllUsers;
foreach (SPUser u in userlist)
{
username=u.Name;
}
}
}
}

Code to get the email addresses:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{

SPSite spsite = new SPSite("site url"); //Ex: http://adfsaccount:2222/
SPWeb web= spsite.RootWeb;
SPUserCollection userlist= web.AllUsers;
foreach (SPUser u in userlist)
{

string email = u.Email.ToString();
}

}
}
}

Wednesday, June 22, 2011

Installing and configuring hMailServer for SharePoint.

That is most of the heavy stuff out of the way. From here on in it is all installing and configuring hMail, which is all done via a GUI interface meaning I can use screen shots to do the talking and is hopefully easier to follow. Click any of the images to get a pop-up window displaying a full sized image.
After downloading the latest stable hMail server installer package from the hmailserver website, double click on it to initiate the install process as shown below:

Select the installation path for hMail as shown below:

Select a full or custom install of hmail (full recommended) as shown below:

Select whether to use the MySQL server built into the hMail distribution, or use an external database. If this is a dedicated email server then it is recommended to use the built in database server. However, if you already have MySQL installed (or are planning to) or would like to use Microsoft SQL server then select the external database server option.

Set the start menu program group for hMail as shown below:

Confirm your settings as shown below:

Click install and hMailServer will be installed as shown below:

Once installation is complete, make sure the "Run hMailServer administrator" option is checked as shown below:

Configuring hMailServer
With the installation of hMailServer successfully completed, the next step is configuration. The configuration steps below show you how to add a domain, add an account, create an alias, setting the server host name, configure RFC settings and configure SMTP relay options to prevent open relay. Start by clicking the Add domain button as shown below in

Enter the domain name as shown below, and then set the catch-all address. If a mail is sent to an address on your domain that does not have a POP account or alias, then it is redirected to the catch-all address. In this example we have set the catch-all address to postmaster@example.com. From here you can also set the global maximum mailbox size as well as the maximum message size for your domain. Once the domain is created you are also able to access several other tabs to set global settings, but they are not covered in this guide.

With the domain setup, it is now time to create accounts. To be RFC compliant all domains should accept email to a postmaster account, and as we have set postmaster to be the catch-all we will now set up an account for it. Place the name of the account in the Account address field, and then enter a password as shown below. You can also set individual mailbox and message size, as well as many other options not covered in this guide such as Active Directory integration, auto-reply, forwarding, and signature and fetching of email from external accounts.

Sometimes it is not practical or desirable to setup an account for every email address you want, and in this case it can be handy to uses an email alias that points to an existing account. In this example we will create an alias of abuse@example.com that points to the postmaster@example.com. Simply enter the alias you’d like to use (in this case abuse) in the Redirect from field and enter the account and domain (in this case postmaster and example.com respectively) in “to” fields. Like the postmaster address, domains are also required to accept email to the abuse email address to be RFC compliant.

Now that we have a domain, account and alias setup let’s look at selecting what email services we want to use. Using the navigation window in the left, select and expand the Settings item and then select the Protocols option. Make sure you have at least the SMTP and POP3 servers ticked, as otherwise you will not be able to send or receive mail. You may not wish to use the IMAP server, but you will need it if you wish to provide webmail functionality to your users.

Next step is to set the server host name. In the navigation window on the left, expand the Protocols item and select SMTP. This can be very important as some email servers will not accept email or mark it as spam if the host name does not match the hostname specified in the MX record we set earlier. In the Host Name field enter the full host name you specified in your MX records. In this example we’ll use mail.example.com. Note: If you are looking to host your own email server over your home broadband connection, then you will want to enter the name of your ISP’s SMTP server in the Relayer field. If your ISP requires authentication, then you’ll also need to provide those details in the fields below.

With the host name set we will now set some extra RFC compliance settings. From the page you are on; simply click on the RFC Compliance tab at the top. It is important that your email server be RFC compliant as otherwise it is likely that many domains will mark your email as spam, and that is if they accept it at all. One of the RFC requirements for email servers is that they accept a null sender address. You can enable this ticking the Allow empty sender address option. It is also a good idea to enable the Allow incorrectly formatted line endings option as several popular email server packages out their vary slightly in the way they terminate email messages, and without this option set you email server may not be able to receive emails from them

The final step in the basic configuration of your email server is to ensure it is not an open relay. An open relay is when a server enables mails to be sent through it to other domains on behalf of domains that do not exist on the local server. Being an open relay is a very quick way in which to get yourself blacklisted, and it can be near impossible to get off these blacklists once you’re on it. Luckily hMailServer makes in very easy to prevent this, and in fact by default you should not have to change a thing. In the navigation window to the left, select the select and expand the advanced menu item from under the Settings tree. From here select the IP Ranges option and then select the Internet option. All you have to do here is ensure that the Local to local, Local to external, and External to local options are ticked from under the Allow deliveries from section. Finally also ensure that to remote accounts option is ticked from under the require authentication for deliveries section. All these options are shown below:

Configure hMailServer for SharePoint to get mail into drop folder.
There is this great free hMailServer called hMailServer which can be found at:
http://www.hmailserver.com/”.
It is very stable and works definitely like a charm. There is some awesome documentation and thus a breeze to configure.
Authentication
SharePoint cannot connect to a mail server that requires authentication. HMailServer is secure by default so you have to add ip-range and define that this ip-range does not require authentication. In my case I defined a range from 0.0.0.0 till 255.255.255.255 and allow message to and from @development.com only. Have a look at the screenshot for were to find these settings and what their value should be.

Drop folder
This one was a bit more complicated. SharePoint requires a path to a ‘drop folder’ where it can find the incoming emails. HMailServer however does not work with drop folders. It creates a folder hierarchy for each account. The drop folder in the screenshot below is created by me. Just note the folder hierarchy.

Bad sender or receiver
Even if you do direct SharePoint to one of those folders inside the hierarchy, it results in a ‘bad sender or receiver’ error when it tries to process the email. This error occurs because the default Microsoft SMTP server adds two headers to an email: the x-sender and the x-receiver. SharePoint uses these headers when it processes the emails.
Solution
The solution to all this is the use of VBScript. HMailServer can be extended by writing some event handlers.

If we could write a script, that copies an incoming message to a ‘drop folder’ AND add the two headers, we are done. Luckily we can!
First we create a drop folder inside the existing hierarchy. (Have a look at the screenshot above). Be sure to set the permissions for this folder to allow the SharePoint Timer Service account to make modifications!
Then – after clicking the ‘Show scripts’ button (see screenshot above) – simply open the script file ‘EventHandlers.vbs’ and add the following script.
Sub OnDeliverMessage(oMessage)
Dim path, filename, fso, original, copy
path = Split(oMessage.Filename, "", -1, 1)
filename = "C:Program Files (x86)hMailServerDatadevelopment.comdropfolder" & _
path(UBound(path))
Set fso = CreateObject("Scripting.FileSystemObject")
Set copy = fso.CreateTextFile(filename, True)
copy.WriteLine("x-sender: " & oMessage.FromAddress)
copy.WriteLine("x-receiver: " & oMessage.To)
Set original = fso.OpenTextFile(oMessage.Filename, 1)
copy.WriteLine(original.ReadAll)
copy.Close
original.Close
End Sub
This should replace the commented Sub OnDeliverMessage(oMessage). Save the Script., ‘Check syntax’ to be sure and click ‘Reload scripts’ to enable this freshly added script. The script simply copies ALL incoming mail messages to the ‘drop folder’ and prepends the two mentioned headers. Now simply point SharePoint to the drop folder and that’s it!
Conclusion
With this script in place you can very well use hMailServer in combination with SharePoint!
Cheers and have fun,
Wesley
Tip: create a catch all address for all your SharePoint incoming mail. You do not want to manually add a new address for each list you want to mail enable.

The timer service and the SharePoint service should be running in network account.
For Errors please check in computer management by right clicking on my computer and selecting manage.

And also you can check log files in:

C:Program Files (x86)hMailServerLogs
For hMailServer related errors and
C:Program FilesCommon FilesMicrosoft Sharedweb server extensions14LOGS
For SharePoint related errors.
For easily analysing error logs you can download: ULSViewer from:
http://archive.msdn.microsoft.com/ULSViewer/Release/ProjectReleases.aspx?ReleaseId=3308

Friday, June 17, 2011

Exporting a Published site / Web Part /Site Template from SharePoint 2010 Enterprise and Importing Into Standard

When stsadm.exe export and import commands are used to move content ,this doesn’t always go as smoothly as planned. Usually site features that exist on the source, but not at the destination is the problem. When importing, you will receive an error indicating that a particular feature can’t be found.

Normally this is because of custom or third party solutions/features, but can also be an issue with out of the box deployments moving content from an Enterprise edition to a standard edition (but not the other way around).

There is some guidance for dealing with this out there for SharePoint 2007 but not much for 2010. Having recently gone through this in a trial and error fashion, I thought that I would share what worked. Essentially, you need to remove the offending feature before you do the export, deactivating doesn’t always suffice. My case below is for a publishing site, and your mileage will vary depending on the site template that you are using. First, the offending features are uninstalled:


stsadm -o uninstallfeature -force -name WACustomReports
stsadm -o uninstallfeature -force -name BizAppsListTemplates
stsadm -o uninstallfeature -force -name IPFSSiteFeatures
stsadm -o uninstallfeature -force -name ReportListTemplate
stsadm -o uninstallfeature -force -name DataConnectionLibrary
stsadm -o uninstallfeature -force -name PremiumSite
stsadm -o uninstallfeature -force -name PremiumWeb


Then the site is exported:
stsadm –o export –url http://mysiteaddress –filename myexportfile
Once done, the export file can be imported. However, don’t forget to reinstall those features – the previous step uninstalled them from all application (read – use with caution)

stsadm -o installfeature -force -name WACustomReports
stsadm -o installfeature -force -name BizAppsListTemplates
stsadm -o installfeature -force -name IPFSSiteFeatures
stsadm -o installfeature -force -name ReportListTemplate
stsadm -o installfeature -force -name DataConnectionLibrary
stsadm -o installfeature -force -name PremiumSite
stsadm -o installfeature -force -name PremiumWeb



Your mileage may vary depending on what you have in your farm, but all you need to do is to add to the commands above with the features in question.

Web Part / Solution Deployment

There are may ways to deploy the Sharepoint solutions depending on the environment. if you have .wsp package ready and you want to deploy it to some sharepoint Server where visual studio is not availabe to deploy it, the following Power shell script can be useful....
follow the steps bellow.

go to START==>>All Programs==>>Microsoft SharePoint 2010 Products==>>SahrePoint 2010 management Shell.(Run it as Administrator)
to deploy particular solution run the following power shell command

Add-SPSolution "D:\WebPartZone\Eventproject_SO.wsp"
3.after deploying the solution to enable it to particular Web Application run the following command with proper web app URL.
Install-SPSolution –Identity "Eventproject_SO.wsp" –WebApplication "Url" -GACDeployment

Thursday, June 16, 2011

Add Web Part inside Master Page in Sharepoint

How you can make a custom web part as part of your master page?

Follow the steps given below to add a web part inside a master page.

1. Deploy the web part in your web application as you do normally.
2. Check whether the web part is showing up in the web part gallery.
3. Create a web part page by navigating to the site settings, create web part page.
4. Add your custom web part on the web part page.
5. Start SharePoint designer and open the newly created web part page.
6. You will now find two entries corresponding to the web part you added on the page
In the page declaration you will find a entry which looks something like this:


"<%@ Register TagPrefix="WpNs0" Namespace="MyNamespace.MyClass" Assembly=" MyNamespace.MyClass, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"%>"


Click on the web part section in the page and you will see an entry like this:


"<WpNs0:WebPartName runat="server" ID="g_34cdbb90_38c6_4561_9182_8fbc0d2423a6" ExportMode="All" Title="WebPartTitle" __MarkupType …………….."


7. Copy these entries in separate notepad, and close the page opened in the SharePoint designer.
8. Now open the master page in SharePoint designer and add the first entry in the declaration
section and second entry at the place where you want to add the web part to.
9. Save the page, check in and publish it and that’s it. Your job is done.
10. Now you can save the above two tags for further use and you can remove web part page from your site.

Programmatically retrive content database name for Sharepoint Web Application


using (SPSite startSite = new SPSite("url"))
{
SPFarm farm = startSite.WebApplication.Farm;
SPWebService service = farm.Services.GetValue("");

foreach (SPWebApplication webApplication in service.WebApplications)
{
foreach (SPSite site in webApplication.Sites)
{
Console.WriteLine(string.Format("{0} - {1}", site.Url, site.ContentDatabase.Name));
}
}
}

Creating Icon from a image file in C#


using System; 
using System.Drawing; 
using System.IO; 
string sourceFile, destinationFile; sourceFile = "C:\imagen.jpg"; 
destinationFile = Path.ChangeExtension(sourceFile, ".ico"); 
using (Bitmap bitmap = Image.FromFile(sourceFile, true) as Bitmap) 

using (Icon icon = Icon.FromHandle(bitmap.GetHicon())) 
{
using (Stream imageFileStream = File.Create(destinationFile)) 
  { 
icon.Save(imageFileStream); 
Console.WriteLine("File Created - {0}", destinationFile); 


}
}

C# how to Run the application at Windows startup


private void RegisterInStartup(bool Checked)
{
    RegistryKey registryValue= Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
    if (Checked))
    {
        registryKey.SetValue("startupApplication", Application.ExecutablePath);
    }
    else
    {
        registryKey.DeleteValue("startupApplication");
    }
}

Download File from URL, Download Document from SharePoint library using c#


public void DownloadFileFromSite(string siteURL, string saveName  )
{
    try
    {
        System.Net.WebClient _WebClient = new System.Net.WebClient();
        // Downloads the resource with the specified URI to a local file.
        _WebClient.DownloadFile(siteURL, saveName);
}
    catch (Exception _Exception)
    {
        // Error
       MessageBox.Show("Error In Downloading");
    }
}

C# provides a large set of operators

C# provides a large set of operators, which are symbols that specify which operations to perform in an expression. Operations on integral types such as ==!=<><=>=binary +binary -^&|~++--, and sizeof() are generally allowed on enumerations. In addition, many operators can be overloaded by the user, thus changing their meaning when applied to a user-defined type.
The following table lists the C# operators grouped in order of precedence. Operators within each group have equal precedence.
Operator categoryOperators
Primaryx.y
f(x)
a[x]
x++
x--
new
typeof
checked
unchecked
default(T)
delegate
->
Unary+
-
!
~
++x
--x
(T)x
true
false
&
sizeof
Multiplicative*
/
%
Additive+
-
Shift<<
>>
Relational and type testing<
>
<=
>=
is
as
Equality==
!=
Logical AND&
Logical XOR^
Logical OR|
Conditional AND&&
Conditional OR||
Null-coalescing??
Conditional?:
Assignment and lambda expression=
+=
-=
*=
/=
%=
&=
|=
^=
<<=
>>=
=> Lambda Operator

The arithmetic operators (+-*/) can produce results that are outside the range of possible values for the numeric type involved. You should refer to the section on a particular operator for details, but in general:
  • Integer arithmetic overflow either throws an OverflowException or discards the most significant bits of the result. Integer division by zero always throws a DivideByZeroException.
  • Floating-point arithmetic overflow or division by zero never throws an exception, because floating-point types are based on IEEE 754 and so have provisions for representing infinity and NaN (Not a Number).
  • Decimal arithmetic overflow always throws an OverflowException. Decimal division by zero always throws a DivideByZeroException.
When integer overflow occurs, what happens depends on the execution context, which can be checked or unchecked. In a checked context, an OverflowException is thrown. In an unchecked context, the most significant bits of the result are discarded and execution continues. Thus, C# gives you the choice of handling or ignoring overflow.
In addition to the arithmetic operators, integral-type to integral-type casts can cause overflow, for example, casting a long to an int, and are subject to checked or unchecked execution. However, bitwise operators and shift operators never cause overflow.

Featured Posts

How to Install Docker Engine on Ubuntu: Step-by-Step Guide

  Docker has become one of the most important tools in modern software development, DevOps, cloud engineering, and system administration. Wh...