jeudi 26 juin 2014

Group Items on Their Folder Name Inside a SharePoint Library


As you probably will know, folders could not be used in views to group documents. You could only group documents on their metadata.
Group Documents
Group Documents
A possible solution could be to add a new metadata field to the content type and manually add the folder name as the metadata value. It is very easy to add and requires no custom development, but it requires an extra manual step from the document creator.
This manual step can also be automated by a SharePoint 2010 Document library functionality called Column default value settings. It can be found on the document library settings page under the General settings section.
The Column default value settings enable you to define a default value for a metadata column per folder.
Default column value
Default column value

Approach

  • Go to the document library settings;
  • Create a new column called: Folder name (Single line of text);
  • Click on Column default value settings under the General settings section;
    Culumn default value settings
    Culumn default value settings
  • On the left side you will see your folders, and on the right site the columns for which you could give up a default value;
    Folders, columns
    Folders, columns
  • Click on the folder name, and after that on the column name;
    Default column value
    Default column value
  • Click Use this default value, and fill in the folder value and click OK;
  • Repeat this process for each folder.
Now when you upload a document to a folder, the Folder name column will automatically get the default value.
To prevent users being able to fill in their own value, you could hide the Folder name columnfrom the new and edit forms.
Hidde column from forms
Hidde column from forms

Result

Group by on folder name
Group by on folder name

Attention: SharePoint Foundation

The Column default value functionality is not available in SharePoint Foundation.

Missing “Destination folder” on upload document form

When uploading documents into a document library with folders, you normally see the following screen:

Problem On one of our sites the Destination Folder was not available. After some investigating I found that the site where it didn’t work, was created using the “Blank site” template. 
Solution Since we used the “Blank site” template, some features do not get activated by default.
I found out that the feature that is responsible for the “Destination Folder” is the “Metadata Navigation and Filtering”feature.
image
After activating the solution, the Destination Folder became available. Note that if you turn this feature off, existing libraries will be able to select a destination folder, as where newly created document libraries will not be able to use this feature.

mercredi 28 mai 2014

Small Calendar for SharePoint 2010 & 2013

SharePoint 2010 Small Calendar:
image
SharePoint 2013 Small Calendar:
image
See video below for a video walk through on how to create a small calendar for SharePoint 2010 and & SharePoint 2013 with just CSS.
Per the video above here is the code that I referenced:
2010 CSS link reference in Master Page:
<SharePoint:CssRegistration name="<% $SPUrl:~sitecollection/Style Library/smallcalendar.css %>" After="corev4.css" runat="server"/>
2010 CSS: /**** Small Calendar ***/
.ms-acal-item{height: 10px !important;}
.ms-acal-sdiv,
.ms-acal-mdiv,
.ms-acal-ctrlitem,
.ms-acal-month-weeksel,
.ms-acal-title{display: none;}
.ms-acal-summary-itemrow TD DIV{height: 15px !important;}
2013 Content Editor Web Part CSS: <style>
/**** Small Calendar ***/
.ms-acal-item{height: 10px !important;}
.ms-acal-sdiv,
.ms-acal-mdiv,
.ms-acal-ctrlitem,
.ms-acal-month-weeksel,
.ms-acal-title,
.ms-acal-month-top span{display: none;}
.ms-acal-summary-itemrow TD DIV{height: 15px !important;}
</style>
Thanks & Enjoy!

jeudi 27 mars 2014

Get élement from Liste sharepoint avec une CAML Query

  public static String LoadDocById(int idDoc)
  {
            String etape = "Debut Methode";
            SPList list = SPContext.Current.Web.Site.RootWeb.Lists["Docs"];
            if (list != null)
            {
                etape = "Litse non null";
string caml = @"<Where><Eq><FieldRef Name='ID' /><Value                     Type='Text'>2428</Value></Eq></Where>";

                SPQuery qry = new SPQuery();
                qry.Query = caml;
                SPListItemCollection items = list.GetItems(qry);
                            

foreach (SPListItem item in items)
                    {
                        String nomFichier = "";
                        if (item2["Nom"] != null)
                        {
                            nomFichier = item["Nom"].ToString();
                        }

                        if (item2["ID"] != null)
                        {
                            nomFichier = item["ID"].ToString();
                        }
                    }
                }

 return etape;

            }

lundi 24 mars 2014

Problème Base de données SQL suspect :


Solution de réparation de la base de données :


EXEC sp_resetstatus Nom_Base;
ALTER DATABASE Nom_BaseSET EMERGENCY
DBCC checkdb(Nom_Base)

ALTER DATABASE Nom_BaseSET ONLINE, SINGLE_USER
DBCC CheckDB (Nom_Base, REPAIR_ALLOW_DATA_LOSS)

ALTER DATABASE Nom_Base SET MULTI_USER

mardi 11 mars 2014

A CAML Query Quick Reference

Single Line of Text

Value TypeText
Example<Query><Where><Eq><FieldRef Name="Title" /><Value Type="Text">Hello World!</Value></Eq></Where></Query>
NotesThis is one of the simplest queries. The example selects items with a title equal to “Hello World!”

Multiple Lines of Text

Value TypeText
Example<Query><Where><Contains><FieldRef Name="Body" /><Value Type="Text"><![CDATA[</a>]]></Value></Contains></Where></Query>
NotesIf this is a Rich Text field, you can use <![CDATA[]]> around the value to prevent parsing errors when passing HTML into the query. Alternatively, you can encode the HTML by replacing < with &lt;, > with &gt;, and " with &quot;. This query uses <Contains> to return any items that contain a hyperlink in the body field by looking for the closing </a> tag.

Person or Group (By Name)

Value TypeText
Example<Query><Where><Eq><FieldRef Name="Author" /><Value Type="Text">Josh McCarty</Value></Eq></Where></Query>
NotesThis will look for items created by any user with “Josh McCarty” in the Name field of the User Information list. If more than one person has the same display name in the user list, it will select items created by all users with that name.

Person or Group (By ID)

Value TypeInteger
Example<Query><Where><Eq><FieldRef Name="Author" LookupId="TRUE" /><Value Type="Integer"><UserID /></Value></Eq></Where></Query>
NotesBy adding LookupId="TRUE" to the <FieldRef /> and using <UserID /> as the value, the query will filter based on the current user. You can also pass the ID of a specific user in place of <UserID /> (e.g. <Value Type="Integer">283</Value>) if you don’t want to filter by the current user. IDs are always unique, so this method ensures that only one user is a valid value.

Lookup (By Text)

Value TypeLookup
Example<Query><Where><Eq><FieldRef Name="State" /><Value Type="Lookup">Arizona</Value></Eq></Where></Query>
NotesThis will look for items with “Arizona” in the State field. If more than one state has the same display name (not likely in this example, but for other lookups it could happen), it will return items from all states with that display name.

Lookup (By ID)

Value TypeLookup
Example<Query><Where><Eq><FieldRef Name="State" LookupId="TRUE" /><Value Type="Lookup">4</Value></Eq></Where></Query>
NotesBy adding LookupId="TRUE" to the <FieldRef />, the query will filter based on the ID of the lookup rather than the text value. IDs are always unique, so this method ensures that only one state is a valid value.

Date (Day Only)

Value TypeDate
Example<Query><Where><Eq><FieldRef Name="Created" /><Value Type="DateTime">2012-01-10</Value></Eq></Where></Query>
NotesThis type of query seems to work whether the value type is set to DateTime or just Date as long as the value is formatted properly (yyyy-mm-dd). It also works if <Today /> is used as the value (you can offset the current date; e.g. use <Today OffsetDays="-7" /> for 7 days ago). <Today />.

lundi 10 mars 2014

Détecter la version du browser

Méthode 1:

<script>function getInternetExplorerVersion()
{
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer')
    {
        var ua = navigator.userAgent;
        var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
        rv = parseFloat( RegExp.$1 );
    }
    return rv;
}
function checkVersion()
{
    var msg = "Le Portail Internet du Ministère de l’économie et des Finances est optimisé pour les navigateurs Internet explorer 9 , Chrome 33.0 et Firefox 27.0.1. Pour une meilleure navigation, veuillez mettre à jour votre navigateur.";
    var verIE = getInternetExplorerVersion();

    if ( verIE > -1 )
    {
      if (! (verIE > 8.0) )
            alert( msg );
    }

}
checkVersion();</script>


Méthode 2:

<script>navigator.sayswho= (function(){
    var ua= navigator.userAgent, tem,
    M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i) || [];
    if(/trident/i.test(M[1])){
        tem=  /\brv[ :]+(\d+(\.\d+)?)/g.exec(ua) || [];
        return 'IE '+(tem[1] || '');
    }
    M= M[2]? [M[1], M[2]]:[navigator.appName, navigator.appVersion, '-?'];
    if((tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
    return M.join(' ');
})();

var navigatorMEF = navigator.sayswho;

if(navigatorMEF == 'MSIE 7.0' || navigatorMEF == 'MSIE 8.0' || navigatorMEF == 'MSIE 6.0' || navigatorMEF == 'FIREFOX 19.0')
{
 var msg = "Message ";
  alert( msg );
}</script>

vendredi 7 mars 2014

ASP.net Captcha

HTTP Handlers are components that implement the System.Web.IHttpHandler interface. It writes some data to the server HTTP response. A file ending with .ashx. In SharePoint they are deployed to the _layouts directory. Generic handlers are a lightweight and quickier way then creating a SharePoint web service layer. I have found them especially useful in getting data from server side to the client side as JSON. They are also useful in AJAX anonymous access scenarios when you cannot use SharePoint .asmx services.
In the recent project I’ve been doing at work, we have created a few Generic HTTPHandlers to call search and return the results as JSON. This has allowed us to have a pure AJAX single page application that can call server side code.
Visual Studio Item Templates for Generic Handlers are not directly supported by Visual Studio SharePoint Projects. When you Add New Item… and search for Installed Templates in a SharePoint project, you will not find Generic Handler anywhere. The ASP.NET handler will require extra work for you making entries in the web.config just to get it to work. There are two solutions to get a Generic Handler in SharePoint:
  • Use CKSDev. By Installing CKSDev there will be a built in handler that will work for you. Just select it when Adding a New Item, and then set the Build Action to Content. Once deployed you will find it at location http://<site>/_layouts/<ProjectName>/myhandler.ashx (Make sure that you add the handler to the feature)
  • Without using CKSDev.
    • Add New Item… and add an Application page, but name the extension .ashx.
    • Delete the ashx.designer.cs file.
    • Open the .ashx file, delete the contents, and replace with the following. (Add your own GUID and ensure all letters are lower case).
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ WebHandler Class="$SharePoint.Type.be94b0d0-ca37-4783-b8e9-06ba0477a22f.FullName$" %>
  • Open the ashx.cs file.
  • Add the using statement using System.Web
  • Add the using statement using System.Runtime.IntropServices;
  • Change your namespace if you want.
  • Change the class to inherit from IHttpHandler
  • Implement the IHttpHandler interface. (IsReusable and ProcessRequest)
  • Add [Guid("BE94B0D0-CA37-4783-B8E9-06BA0477A22F")] (Guid should match the Guid from the ASHX page, except uppercase)
  • In the Solution Explorer, click the .ashx file and in the Properties pane, set the Build Action to Content.
  • In the Solution Explorer, click the .ashx.cs file and in the Properties pane, set the Build Action to Compile.
  • Now we need to Save and Close the solution.
  • Edit the .csproj file and add the following text to a PropertyGroup, and reload your project in Visual Studio.
<PropertyGroup>
<TokenReplacementFileExtensions>ashx</TokenReplacementFileExtensions>
</PropertyGroup>



jeudi 6 mars 2014

ASP listview structure

  <asp:ListView ID="ListViewName" runat="server"  DataKeyNames="Id" >
    
      <ItemTemplate>
      <tr>
         
        <td>
         <asp:Label ID="champALabel" runat="server" Text='<%# Eval("champA") %>'></asp:Label>
         <asp:Label ID="ChampBLabelAr" runat="server" Text='<%# Eval("ChampB") %>'  Visible="false"></asp:Label>
        </td>
       <td>
       <asp:LinkButton  ID="LinkButton6" runat="server" CommandArgument='<%# Eval("Id") %>'
       Visible="true">
       <img alt="Image1" runat="server" id="Image1" src="/_layouts/MEF/images         /DownloadIconSmall.jpg" />
       </asp:LinkButton>
    </td>

      </tr >
              
    </ItemTemplate>
           <LayoutTemplate>
               <table id="UserList" border="0" cellpadding="0" cellspacing="0">
             <tr>
                 <th style="text-decoration: underline;width: 102%;color: rgb(109, 109, 109);">
                 <asp:Label ID="ChampALab" runat="server" Text="Tx2"></asp:Label>
                 </th>
                  <th style="text-decoration: underline;width: 102%;color: rgb(109, 109, 109);">
                  <asp:Label ID="ChampBLab" runat="server" Text="Tx"></asp:Label>
                  </th>
               </tr>
                     <tr id="itemPlaceholder" runat="server"></tr>
                 </table>
           </LayoutTemplate>
                
      
       </asp:ListView>

lundi 3 mars 2014

Créer script shell pour exporter une base de données oracle

1> Create a folder where you want your backup folder to be placed. I have created a folder called DBIMPEXP at /home/oracle/

$ cd /home/oracle/DBIMPEXP

2> vi DBExport.sh

3> Type all the below into this file.

#!/bin/bash
ORACLE_HOME=/opt/oracle/products/11.1.0/database;export ORACLE_HOME
PATH=$ORACLE_HOME/bin:$PATH;export PATH
ORACLE_SID=CI;export ORACLE_SID
DIRECTORY='dmpdir';export DIRECTORY

echo $ORACLE_HOME
echo $PATH
SUBJECT="Database export operation performed"
EMAIL="email@domain.com"
MSG="/home/oracle/DBIMPEXP/Hi"

echo "Database or tables have been exported successfully!" >$MSG
echo "This is a system generated message so do not reply to this email!" >>$MSG

NOW=$(date +"%d-%m-%Y-%T")
echo $NOW

exp DBusername/DBPassword@yourSID file=/home/oracle/DBIMPEXP/"Backup_$NOW.dmp" log=/home/oracle/DBIMPEXP/"explog_$NOW.log" tables={SC_LEARNING,SC_NEWS}

/bin/mail -s "$SUBJECT" "$EMAIL" < $MSG

4> To save and close hit Esc and ctrl+zz

5> execute the shell script by sh DBExport.sh

6> Now inside the /home/oracle/DBIMPEXP folder you should get the dmp file and the log file.

jeudi 27 février 2014

Keeping ASP.NET Session Open / Alive

Friends, many times we get requirements to increase the session timeout expiry time on the application server, so what we do basically we go in web.config file and set session time out to some time period, by default its 20 mins, but remember sometime you increase time period in web.config file and it doesn't work why?? The reason is you also have to check your application pool recycling time period it should be more than the session expiry period which you are doing in web.config file.

 Yo! But anyways you did not avoid session expiration in your application, session will still expire in your application let's say if user filling a long form in your application or kept a page open and gone out for coffee. So now what will happen? Session will expire right? By the time use will be back and resume with the work.

Some people do session resetting in code behind by checking if session is null then read User ID () from cookies and reset it. Or if it is intranet application and AD authentication then you get the current logged in user in system and set it in session.Now if you don't wanna do all above crap In your application, what all you wanna do is don't let session to get expire unless user close the browser. To implement this behavior in your applications simply follow below steps.
  1. First of all let me give you some brief about working session state in asp.net. By default it is set to 20 min, so if user sends a request to the server (in simple language browse a page) then server stores the time when request came and extend the session time out to 20 min, so if after 10 min user send again a request so it keeps extended to 20 min, if user don't send any request to server till 20 min then session get expires. This is basic working of session state.
  2. From first step you know that, server need to get any request from client to keep session alive, so now we can think of some methodology to keep pinging the server, below is the script which will keep sending request to the server and will keep session alive.

    Create a SessionCheck.aspx page in your application; you can keep this page blank. So that if it gets called from the browser then it should not be over loaded.

    Using Java Scrip:
    Image will be used to keep session alive by changing image src, assigning this property to some 
    <img id="imgSessionCheck" width="1" height="1" />

    <script type="text/javascript" >
    //Variable used to prevent caching on some browsers and knowing the count how many times user sends request to server.
        var counter;
        counter = 0;

        function KeepSession() {
    // Increase counter value
        counter++;

        // Gets reference of image
        var img = document.getElementById("imgSessionCheck");

        // Set new src value, which will send a request to the server
    img.src = "http://servername:port/appName/SessionCheck.aspx?count=" + counter;

        // now schedule this process to happen in some time interval, in this example its 1 min
        setTimeout(KeepSession, 60000);
    }

        // Call this function for a first time
        KeepSession();
        </script>

    Using JQuery:
    <script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    <script language="javascript" type="text/javascript">

        function KeepSession() {
        // A request to server
        $.post("http://servername:port/appName/SessionCheck.aspx");

        //now schedule this process to happen in some time interval, in this example its 1 min
        setInterval(KeepSession, 60000);
    }

        // First time call of function
        KeepSession();
     </script>

    So it's simple just you need to put this script in your page.

Downloading Files C#

A lot of questions are being asked about downloading a file from the web server to the client in ASP.NET. I have updated this blog post due to the high number of view & comments. You will realize i added a function called "ReturnExtension" which will return the proper content type and set it to the Response.ContentType property. Almost well known file types are supported.
C# Code
   // Get the physical Path of the file(test.doc)
   string filepath = Server.MapPath("test.doc");
   // Create New instance of FileInfo class to get the properties of the file being downloaded
   FileInfo file = new FileInfo(filepath);
  
   // Checking if file exists
   if (file.Exists)
   {
    // Clear the content of the response
    Response.ClearContent();
    
    // LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
    Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
    
    // Add the file size into the response header
    Response.AddHeader("Content-Length", file.Length.ToString());
    // Set the ContentType
    Response.ContentType = ReturnExtension(file.Extension.ToLower());
    // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
    Response.TransmitFile(file.FullName);
    // End the response
    Response.End();
   }
private string ReturnExtension(string fileExtension)
{
     switch (fileExtension)
            {
                case ".htm":
                case ".html":
                case ".log":
                    return "text/HTML";
                case ".txt":
                    return "text/plain";
                case ".doc":
                    return "application/ms-word";
                case ".tiff":
                case ".tif":
                    return "image/tiff";
                case ".asf":
                    return "video/x-ms-asf";
                case ".avi":
                    return "video/avi";
                case ".zip":
                    return "application/zip";
                case ".xls":
                case ".csv":
                    return "application/vnd.ms-excel";
                case ".gif":
                    return "image/gif";
                case ".jpg":
                case "jpeg":
                    return "image/jpeg";
                case ".bmp":
                    return "image/bmp";
                case ".wav":
                    return "audio/wav";
                case ".mp3":
                    return "audio/mpeg3";
                case ".mpg":
                case "mpeg":
                    return "video/mpeg";
                case ".rtf":
                    return "application/rtf";
                case ".asp":
                    return "text/asp";
                case ".pdf":
                    return "application/pdf";
                case ".fdf":
                    return "application/vnd.fdf";
                case ".ppt":
                    return "application/mspowerpoint";
                case ".dwg":
                    return "image/vnd.dwg";
                case ".msg":
                    return "application/msoutlook";
                case ".xml":
                case ".sdxl":
                    return "application/xml";
                case ".xdp":
                    return "application/vnd.adobe.xdp+xml";
                default:
                    return "application/octet-stream";
}
N.B:  If you want to bypass the Open/Save/Cancel dialog you just need to replace LINE1 by the below code
Response.AddHeader("Content-Disposition", "inline; filename=" + file.Name);
Response.TransmitFile VS Response.WriteFile:  1- TransmitFile: This method sends the file to the client without loading it to the Application memory on the server. It is the ideal way to use it if the file size being download is large.
 2- WriteFile: This method loads the file being download to the server's memory before sending it to the client. If the file size is large, you might the ASPNET worker process might get restarted.
Hope this helps,

mardi 25 février 2014

Crypter et Décrypter en C#

        public string encrypt(string message)
        {
            byte[] results;
            string passphrase = "Password123";
            UTF8Encoding utf8 = new UTF8Encoding();
            //to create the object for UTF8Encoding  class
            //TO create the object for MD5CryptoServiceProvider
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] deskey = md5.ComputeHash(utf8.GetBytes(passphrase));
            //to convert to binary passkey
            //TO create the object for  TripleDESCryptoServiceProvider
            TripleDESCryptoServiceProvider desalg = new TripleDESCryptoServiceProvider();
            desalg.Key = deskey;//to  pass encode key
            desalg.Mode = CipherMode.ECB;
            desalg.Padding = PaddingMode.PKCS7;
            byte[] encrypt_data = utf8.GetBytes(message);
            //to convert the string to utf encoding binary

            try
            {
                //To transform the utf binary code to md5 encrypt   
                ICryptoTransform encryptor = desalg.CreateEncryptor();
                results = encryptor.TransformFinalBlock(encrypt_data, 0, encrypt_data.Length);
            }
            finally
            {
            //to clear the allocated memory
            desalg.Clear();
            md5.Clear();
            }
            //to convert to 64 bit string from converted md5 algorithm binary code
            return Convert.ToBase64String(results);
            }
           
           
         public string decrypt(string message)
        {
            byte[] results;
            string passphrase = "Password123";
            UTF8Encoding utf8 = new UTF8Encoding();
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] deskey = md5.ComputeHash(utf8.GetBytes(passphrase));
            TripleDESCryptoServiceProvider desalg = new TripleDESCryptoServiceProvider();
            desalg.Key = deskey;
            desalg.Mode = CipherMode.ECB;
            desalg.Padding = PaddingMode.PKCS7;
            byte[] decrypt_data = Convert.FromBase64String(message);
            try
            {
                //To transform the utf binary code to md5 decrypt
                ICryptoTransform decryptor = desalg.CreateDecryptor();
                results = decryptor.TransformFinalBlock(decrypt_data, 0, decrypt_data.Length);
            }
            finally
            {
                desalg.Clear();
                md5.Clear();

            }
            //TO convert decrypted binery code to string
            return utf8.GetString(results);
        }

jeudi 20 février 2014

JavaScript alert et accents

Dans certains cas, un accent saisi dans le code source javascript ne sera pas affiché correctement, mais remplacé par un point d’interrogation.

Encodage octal des caractères

Il suffit de remplacer les caractères accentués par leur équivalent en octal précédé de \ (anti-slash)
Par exemple :
  • é : \351
  • è : \350
  • ê : \352
  • à : \340
 Pour plus de détail : http://www.pjb.com.au/comp/diacritics.html

mercredi 12 février 2014

Executer Sharepoint Designer avec un compte précis


1.lancer cmd
2. tapez la commande suivante : runas /user:username "chemin du exe"
à savoir "chemin du fichier = C:\Program Files\Microsoft Office\Office15\SPDESIGN.exe"
3. entrez votre password

mardi 4 février 2014

SQL utilities

-- Permet d'afficher les noms des colonnes 
d'une table séparé par virgule. 
select name + ', ' as [text()] 
from sys.columns 
where object_id = object_id('YourTable') 
for xml path('')

Programme console qui insère les données dans une base précise en C#



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

Console.WriteLine("This program will insert data in database");
SqlConnection sqlConnection = new SqlConnection(@"data source=NOMDUSERVEUR;initialcatalog=NOMBASEDEDONNES;user id=IDUSER;password=PASSWORD;Trusted_Connection=true;");
sqlConnection.Open();
// Insértion des comptes
for (int i = 0; i < 9000; i++)
{
String insertSql = String.Format("INSERT INTO [dbo].[Compte]([Login],[Email] ,[Nom], [Prenom],[Pays_Id],[Password],[isValid],[langue]) VALUES ('Login','XXX@yahoo.fr','XXX', 'XXXX',60,'111',1,null)");
SqlCommand sqlCommand = new SqlCommand(insertSql, sqlConnection);
sqlCommand.ExecuteNonQuery();
}
Console.ReadLine();

mercredi 29 janvier 2014

Trier une liste d'objets selon un critère précis C#

    if (infosLetterList != null && infosLetterList.Count > 0)
    {
        infosLetterList.Sort(delegate(InfoLetter a1, InfoLetter a2) { return string.Compare(a1.CentreInteret, a2.CentreInteret); });
    }

lundi 27 janvier 2014

Session lost problem after Response.Redirect

If you create a session like this and redirect the user to some other page, the session will lost.

Session["UserId"] = "User1";
Response.Redirect("YourPage.aspx");

This is because of the working of session and Response.Redirect, Lets go through.

" When you create a new session (that is, the first time you write to a Session variable), ASP.NET sets a volatile cookie on the client that contains the session token. On all subsequent requests, and as long as the server session and the client cookie have not expired, ASP.NET can look at this cookie and find the right session.
Now, what Redirect does is to send a special header to the client so that it asks the server for a different page than the one it was waiting for. Server-side, after sending this header, Redirect ends the response. This is a very violent thing to do. Response.End actually stops the execution of the page wherever it is using a ThreadAbortException.
What happens really here is that the session token gets lost in the battle.
There are a few things you can do to solve this problem.
First, in the case of the forms authentication, we already provide a special redirect method: FormsAuthentication.RedirectFromLoginPage. This method is great because, well, it works, and also because it will return the user to the page he was asking for in the first place, and not always default. This means that the user can bookmark protected pages on the site, among other things. " - Bertrand Le Roy
Another thing you can do is use the overloaded version of Redirect:

Response.Redirect("YourPage.aspx", false);

This does not abort the thread and thus conserve the session token. Actually, this overload is used internally by RedirectFromLoginPage.

mardi 21 janvier 2014

Créer son premier Projet Sharepoint

On commence par créer un empty sharepoint project

ensuite on met l'adresse du site dans lequel on va déployer:

et pour finir le résultat sera le suivant:

et puis on créera notre 1ère webpart clique droit sur le projet Ajouter -> Nouvel élément -> Visual WebPart et on lui donne un nom :

Ensuite on ouvre le sharepoint designer et on créé une page de webpart et on associe notre webpart qu'on vient de créer. pour plus de détails n'hésitez pas à laisser des commentaires.

Générer un excel avec C#

   public void FichierExcel(List<BeanTelechargementAppelOffre> DemandesBeans)
        {


            HttpResponse response = HttpContext.Current.Response;
            response.Clear();
            response.Charset = "";
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment;filename=\"" +"ListeEntreprises.xls" + "\"");

            Table tbl = new Table() { BorderWidth = new Unit(1) };
            TableHeaderRow th = new TableHeaderRow();
            th.Font.Bold = true;
            th.Cells.Add(new TableCell() { Text = "Liste des Personnes", ColumnSpan = 4, HorizontalAlign = HorizontalAlign.Center, BackColor = Color.DarkBlue, ForeColor = Color.White });
            tbl.Rows.Add(th);

            th = new TableHeaderRow();
            th.Font.Bold = true;

            th.Cells.Add(new TableCell() { Text = "Nom ou raison sociale", BackColor = Color.DarkBlue, ForeColor = Color.White, BorderWidth = new Unit(1) });
            th.Cells.Add(new TableCell() { Text = "Les pi&egrave;ces t&eacute;l&eacute;charg&eacute;es", BackColor = Color.DarkBlue, ForeColor = Color.White, BorderWidth = new Unit(1) });
            th.Cells.Add(new TableCell() { Text = "Email de la personne", BackColor = Color.DarkBlue, ForeColor = Color.White, BorderWidth = new Unit(1) });
            th.Cells.Add(new TableCell() { Text = "Date de la consultation", BackColor = Color.DarkBlue, ForeColor = Color.White, BorderWidth = new Unit(1) });

            tbl.Rows.Add(th);
            foreach (BeanTelechargementAppelOffre bean1 in DemandesBeans)
            {

                var tr = new TableRow();
                tr.Cells.Add(new TableCell() { Text = "" + bean1.NomPersonne, BorderWidth = new Unit(1) });
                tr.Cells.Add(new TableCell() { Text = bean1.TypeFichier, HorizontalAlign = HorizontalAlign.Center, BorderWidth = new Unit(1) });
                tr.Cells.Add(new TableCell() { Text = bean1.EmailPersonne, HorizontalAlign = HorizontalAlign.Center, BorderWidth = new Unit(1) });
                tr.Cells.Add(new TableCell() { Text = Convert.ToDateTime(bean1.DateConsultation).ToShortDateString(), HorizontalAlign = HorizontalAlign.Center, BorderWidth = new Unit(1) });
                tbl.Rows.Add(tr);
            }
            System.Text.StringBuilder stb = new System.Text.StringBuilder();
            System.IO.StringWriter sw = new System.IO.StringWriter(stb);
            HtmlTextWriter textWriter = new HtmlTextWriter(sw);
            tbl.RenderControl(textWriter);
            response.Write(stb.ToString());
            response.End();
        }