Tuesday 25 September 2012

Edit csproj.cs file programmatically using c#

private void IncludeFilesInProject(string csProjName, string tagContent)
        {
            string csprojPath = txtdefaultPath.Text + "\\" + csProjName;
            XmlDocument myXmlDocument = new XmlDocument();

            myXmlDocument.Load(csprojPath);

            XmlTextReader reader = new XmlTextReader(csprojPath);
            XmlDocument doc = new XmlDocument();

            doc.Load(reader);
            reader.Close();
            XmlNode currNode;

            XmlDocumentFragment docFrag = doc.CreateDocumentFragment();


            docFrag.InnerXml = tagContent;

            // insert the availability node into the document
            currNode = doc.DocumentElement;
            currNode.InsertAfter(docFrag, currNode.LastChild);
           
            //save the output to a file
            doc.Save(csprojPath);

            //Overwrite the existing file with new file content.
            string projFile = File.ReadAllText(csprojPath);
            string newProjFile = projFile.Replace(" xmlns=\"\"", "");
            File.WriteAllText(csprojPath, newProjFile);
        }

Saturday 22 September 2012

LINQ - Conversion Operators

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.ComponentModel; 
using System.Xml.Linq; 
 
namespace ConversionOperators 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            LinqSamples samples = new LinqSamples(); 
 
            //Comment or uncomment the method calls below to run or not 
 
              samples.Linq54(); // This sample uses ToArray to immediately evaluate a sequence into an array 
 
            //samples.Linq55(); // This sample uses ToList to immediately evaluate a sequence into a List<T> 
 
            //samples.Linq56(); // This sample uses ToDictionary to immediately  evaluate a  sequence  and a  
                                // related key expression into a dictionary 
 
            //samples.Linq57(); // This sample uses OfType to return only the elements of the array that are  
                                // of type double 
        } 
 
        class LinqSamples 
        { 
            [Category("Conversion Operators")] 
            [Description("This sample uses ToArray to immediately evaluate a sequence into an array.")] 
            public void Linq54() 
            { 
                double[] doubles = { 1.72.31.94.12.9 }; 
 
                var sortedDoubles = 
                    from d in doubles 
                    orderby d descending 
                    select d; 
                var doublesArray = sortedDoubles.ToArray(); 
 
                Console.WriteLine("Every other double from highest to lowest:"); 
                for (int d = 0; d < doublesArray.Length; d += 2) 
                { 
                    Console.WriteLine(doublesArray[d]); 
                } 
            } 
 
            [Category("Conversion Operators")] 
            [Description("This sample uses ToList to immediately evaluate a sequence into a List<T>.")] 
            public void Linq55() 
            { 
                string[] words = { "cherry""apple""blueberry" }; 
 
                var sortedWords = 
                    from w in words 
                    orderby w 
                    select w; 
                var wordList = sortedWords.ToList(); 
 
                Console.WriteLine("The sorted word list:"); 
                foreach (var w in wordList) 
                { 
                    Console.WriteLine(w); 
                } 
            } 
 
            [Category("Conversion Operators")] 
            [Description("This sample uses ToDictionary to immediately evaluate a sequence and a " + 
                        "related key expression into a dictionary.")] 
            public void Linq56() 
            { 
                var scoreRecords = new[] { new {Name = "Alice", Score = 50}, 
                                        new {Name = "Bob"  , Score = 40}, 
                                        new {Name = "Cathy", Score = 45} 
                                    }; 
 
                var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Name); 
 
                Console.WriteLine("Bob's score: {0}", scoreRecordsDict["Bob"]); 
            } 
 
            [Category("Conversion Operators")] 
            [Description("This sample uses OfType to return only the elements of the array that are of type double.")] 
            public void Linq57() 
            { 
                object[] numbers = { null1.0"two"3"four"5"six"7.0 }; 
 
                var doubles = numbers.OfType<double>(); 
 
                Console.WriteLine("Numbers stored as doubles:"); 
                foreach (var d in doubles) 
                { 
                    Console.WriteLine(d); 
                } 
            } 
        } 
    } 
} 



Some Userful links, must share this.....

Using LINQ to Objects in C#

Read Write Edit Word Document In ASP.NET

In this article i am explaining how to Read Write Edit Word Document With FileStream StreamWriter In ASP.NET. For this i've added a textbox for input text to be written in word document and a button to write, same for reading text from word file.

The word file created is saved in a folder named document in root of application. which can be changed to desired location.


Read Write Edit Word Document In ASP.NET


html source of the page look like

<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server">
</asp:TextBox>
<asp:Button ID="Button1" runat="server" 
                         onclick="Button1_Click" 
                         Text="Click to write to word" />
<br />
<asp:TextBox ID="TextBox2" runat="server">
</asp:TextBox>
<asp:Button ID="Button2" runat="server" 
                         onclick="Button2_Click" 
                         Text="Read Word Document" />
</div>
</form>

To use Filestream and stringBuilder we need to add these namespace

using System.IO;
using System.Text;

C# code behind
protected void Button1_Click(object sender, EventArgs e)
{
    //Create stringBuilder to write formatted 
    //Text to word file
 StringBuilder strBuilder = new StringBuilder();
 strBuilder.Append("<h1 title='Header' align='Center'>
     Writing To Word Using ASP.NET</h1> ".ToString());

 strBuilder.Append("<br>".ToString());
 strBuilder.Append("<table align='Center'>".ToString());
 strBuilder.Append("<tr>".ToString());

 strBuilder.Append("<td style='width:100px;color:green'>
                          <b>amiT</b></td>".ToString());

 strBuilder.Append("<td style='width:100px;color:red'>
                              India</td>".ToString());
 strBuilder.Append("</tr>".ToString());
 strBuilder.Append("</table>".ToString());

 string strPath = Request.PhysicalApplicationPath
                         + "\\document\\Test.doc";

 //string strTextToWrite = TextBox1.Text;
 FileStream fStream = File.Create(strPath);
 fStream.Close();
 StreamWriter sWriter = new StreamWriter(strPath);
 Writer.Write(strBuilder);
 sWriter.Close(); 

}
protected void Button2_Click(object sender, EventArgs e)
{
 string strPath = Request.PhysicalApplicationPath 
                  + "\\document\\Test.doc";
 FileStream fStream = new FileStream
            (strPath, FileMode.Open, FileAccess.Read);
 StreamReader sReader = new StreamReader(fStream);
 TextBox2.Text = sReader.ReadToEnd();
 sReader.Close();
Response.Write(TextBox2.Text);
}

VB.NET code
Protected Sub Button1_Click
(ByVal sender As Object, ByVal e As EventArgs)
Dim strBuilder As New StringBuilder()
strBuilder.Append("<h1 title='Header' align='Center'>
     Writing To Word Using ASP.NET</h1> ".ToString())
strBuilder.Append("<br>".ToString())
strBuilder.Append("<table align='Center'>".ToString())
strBuilder.Append("<tr>".ToString())

strBuilder.Append("<td style='width:100px;color:green'>
                           <b>amiT</b></td>".ToString())
strBuilder.Append("<td style='width:100px;color:red'>
                               India</td>".ToString())
strBuilder.Append("</tr>".ToString())
strBuilder.Append("</table>".ToString())
'string path = @"C:\Test.doc";

Dim strPath As String = 
Request.PhysicalApplicationPath & "\document\Test.doc"
    
'string strTextToWrite = TextBox1.Text;
Dim fStream As FileStream = File.Create(strPath)
fStream.Close()
Dim sWriter As New StreamWriter(strPath)
sWriter.Write(strBuilder)
      
sWriter.Close()
End Sub

Protected Sub Button2_Click
(ByVal sender As Object, ByVal e As EventArgs)
Dim strPath As String = 
Request.PhysicalApplicationPath & "\document\Test.doc"

Dim fStream As New FileStream
(strPath, FileMode.Open, FileAccess.Read)
Dim sReader As New StreamReader(fStream)
TextBox2.Text = sReader.ReadToEnd()
sReader.Close()
Response.Write(TextBox2.Text)
End Sub

how to read, write, edit, delete using filestream in c#

using System;
using System.IO;

class Test
{

public static void Main()
{
    // Specify a file to read from and to create. 
    string pathSource = @"c:\tests\source.txt";
    string pathNew = @"c:\tests\newfile.txt";

    try
    {

        using (FileStream fsSource = new FileStream(pathSource,
            FileMode.Open, FileAccess.Read))
        {

            // Read the source file into a byte array. 
            byte[] bytes = new byte[fsSource.Length];
            int numBytesToRead = (int)fsSource.Length;
            int numBytesRead = 0;
            while (numBytesToRead > 0)
            {
                // Read may return anything from 0 to numBytesToRead. 
                int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);

                // Break when the end of the file is reached. 
                if (n == 0)
                    break;

                numBytesRead += n;
                numBytesToRead -= n;
            }
             numBytesToRead = bytes.Length;

            // Write the byte array to the other FileStream. 
            using (FileStream fsNew = new FileStream(pathNew,
                FileMode.Create, FileAccess.Write))
            {
                fsNew.Write(bytes, 0, numBytesToRead);
            }
        }
    }
    catch (FileNotFoundException ioEx)
    {
        Console.WriteLine(ioEx.Message);
    }
}
}

Build .Net Project Solution programatically using C#

private void btnBuild_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = "";
            string[] solutions = GetSolutions();
            foreach (string solution in solutions)
            {
                var startinfo = new ProcessStartInfo();
                startinfo.FileName = @"C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe";
                startinfo.Arguments = "/t:rebuild  /p:Configuration=Debug " + solution;
                startinfo.RedirectStandardError = true;

                startinfo.RedirectStandardOutput = true;
                startinfo.UseShellExecute = false;

                Process build = Process.Start(startinfo);

                //string error = build.StandardError.ReadToEnd();
                string output = build.StandardOutput.ReadToEnd();

                build.WaitForExit();

                richTextBox1.Text = output;

             }
        }


private string[] GetSolutions()
        {
            string[] filePaths = Directory.GetFiles(txtLoc.Text);

            return filePaths;
        }

Monday 10 September 2012

Configuring LDAP in Sitefinity 4.4 in Telerik Sitefinity



  Configuring LDAP in Sitefinity 4.4


Windows Active Directory is a directory service created by Microsoft. Active Directory uses a number of standardized protocols to provide a variety of network service, including LDAP. LDAP is Lightweight Directory Access Protocol for accessing directories over an IP network.

You configure LDAP settings in the following way:

  1. In the main menu, click Administration » Settings.
  2. The Basic Settings page appears.
  3. Click, Advanced link.
  4. The Settings page appears.
  5. Expand Security node in the left of the page.
  6. Click LDAP Settings à LDAP Connections.

A list of all configured connections appears. You can edit an existing connection by clicking it or you can create a new connection by clicking Create new button.
Configure the following properties:




                                                                                                                                                            
Note : All the Fields values may be change according to your LDAP Servers setting.

Name 
The name of the connection is used for distinguishing LDAP connections in Sitefinity. It should be IP Address of the server where LDAP directory is hosted (Not the machine name / Server Name).
ServerName
Enter the name of the server where LDAP is hosted.
Port
Enter the LDAP server port. The default port is 389.
ConnectionDomain
Enter the domain of the LDAP server.
ConnectionUsername
Enter the username for logging to the LDAP server.
ConnectionPassword
Enter the password for logging to the LDAP server.
UseSsl
Indicates whether the connection use SSL or not
ResultCacheExpirationTime
Enter the seconds, for which the system caches the LDAP server response results. 
MaxReturnedUsers
Enter the maximum number of users that is returned on one request to the LDAP. This number is used for internal paging of results, in order to avoid overconsumption of memory and slow retrieval of big chunks of data.
UserDns
Enter the base/root distinguished name (DN) for the users.
UserFilter
Enter the filter that is applied when requesting users from the LDAP. You must use the standard LDAP query syntax.
MaxReturnedRoles
Enter the maximum number of roles that is returned on one request to the LDAP. This number is used for internal paging of results, in order to avoid overconsumption of memory  and slow retrieval of big chunks of data.
RolesDNs
Enter the base/root distinguished name (DN) for the roles.
RolesFilter
Enter the filter applied when requesting users from the LDAP. You must use the standard LDAP query syntax.
ConnectWithLogOnCredentials
Indicates whether to use current user credentials or those entered above. If you select this checkbox, the LDAP is connected and browsed with the credentials that the user provides on logging into Sitefinity backend and you do not have to enter user and password into the LDAP configuration.
AuthenticationType
Enter one of the following:
·         Basic
Indicates that basic authentication will be used with the connection.
·         NTLM

  1. When you are finished with the configurations, click Save changes.
  2. To select which is the default LDAP connection to be used, click LDAP Settings and enter the name of the connection in DefaultLdapConnection input field and click Save changes button.

When you successfully saved all these settings restart the Sitefinity server and again run the CMS project and check whether the LDAP users and LDAP roles are showing or not in the Users and Roles section of Administration menu.





How to Design own Custom Templates in Telerik Sitefinity



1.   How to Design own Custom Templates in Telerik Sitefinity


1.    Login to the backend page.

2.    Now follow the following root:
            Design à Page Template

3.    Template page will open. Click on the Create a Template button. Create a Template page will appear as follows

a.    In the Name Textbox give the appropriate template name and select Don’t use template Radio button if you want to design your own template.
b.    Click on the Create and go to add content button.

4.    Now template page will open, you can design the template according to your need.


Save it and return back to dashboard. It is now ready to apply on any page of your CMS project.

How to find a string within a jQuery or javascript string

Sometimes, you required to find a the existence of a small string with in a string. This article will  demonstarte , how could you do by...