Sunday, April 1, 2012

How to enter connection string on runtime?

One of the challenging tasks in .NET programming is changing the connection string on runtime. In this post, I will give you the simple step to complete this task.
Step 1: Create a SQL Conneciton form:
On the Solution Explorer panle, right click on your project,  select Add->New Item. Select Window Form. Name it SLQConnection, then click OK. Design it as the figure bellow:

Step 2: Create an app.config file
On the Solution Explorer, right click on your project, select Add->New Item. On the dialog appeared, click on Application Configuration File, name it app.config. Click OK
Open app.config file, modifying it as the figure bellow
Step 3: Coding
On the SQLConnection.cs file, add the following code:
        public void updateConfigFile(string con)
        {                       
            XmlDocument XmlDoc = new XmlDocument();
            //Road the Config file
            XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
            foreach (XmlElement xElement in XmlDoc.DocumentElement)
            {
                if (xElement.Name == "connectionStrings")
                {
                    //setting the connection string
                    xElement.FirstChild.Attributes[2].Value = con;
                }
            }
            //write the connection string in app.config file
            XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        }

Double click on Connect button of the Form created in step 1
Add the following code to the On_Clikc event of the button
          
                StringBuilder Con = new StringBuilder("Data Source=");
                Con.Append(txtServerName.Text);
                Con.Append(";Initial Catalog=");
                Con.Append(txtDBName.Text);
                Con.Append(";Integrated Security=SSPI;");
                string strCon = Con.ToString();
                updateConfigFile(strCon);
 
                //create a new connection
                SqlConnection conn = new SqlConnection();
                ConfigurationManager.RefreshSection("connectionStrings");
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["Conn"].ToString();                               
                //get data from a table to test the connection
                SqlDataAdapter da = new SqlDataAdapter("select * from Users", conn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                if (dt.Rows.Count > 0)
                {
                    MessageBox.Show("Connection successful", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);                                                
                }
                else
                {
                    MessageBox.Show("Connection failed", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }






To get the connection string on runtime, use the following code
string cnstr = ConfigurationManager.ConnectionStrings["Conn"].ToString();


Now, test it!

Hope this helps!
          

Saturday, March 31, 2012

How to get data from Access database in C#?

The following are the complete code to get data from Access database:

First, we connect to the database.
public DataTable getData()
{
            string cnStr = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=HR.mdb";
            OleDbConnection cn = new OleDbConnection(cnStr);

            string sql = "select * from Employees";
            OleDbDataAdapter da = new OleDbDataAdapter(sql, cn);
            DataTable dt = new DataTable();
            da.Fill(dt);   
            return dt;
}

Then,  we load the data to Listview control
public void loadToListView()
{
             DataTable dt = getData();
             for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow row = dt.Rows[i];
                int id = Convert.ToInt32(row["EmpID"]);
                string fName = row["FirstName"].ToString();
                string lName = row["LastName"].ToString();

                Employees emp = new Employees(id, fName, lName);
                ListViewItem item = new ListViewItem(id.ToString());
                item.SubItems.Add(fName);
                item.SubItems.Add(lName);
                item.Tag = entity;

                lvEmp.Items.Add(item);

            }
}
Make sure that you had copied the Access database file into bin/Debug.
Hope this helps!


Friday, February 10, 2012

Programmatically read and write a text file

The following is the source code for reading and writing a text file by C#

        void readData()
        {
             string filePath = Application.StartupPath + @"\data.txt";           
             if (File.Exists(filePath) == true)
            {
                StreamReader reader = new StreamReader(filePath);
                while (reader.EndOfStream == false)
                {
                    string line = reader.ReadLine();
                    if (string.IsNullOrEmpty(line)) continue;

                    Messagebox.Show(line);
                }
                reader.Close();
            }           
        }

        void writeData()
       {
            string filePath = Application.StartupPath + @"\data.txt";
            StreamWriter writer = new StreamWriter(filePath);                         
            string line = "This is a text file";
            writer.WriteLine(line);
           
            writer.Flush();
            writer.Close();

            MessageBox.Show("Saved");
       }

Hope this help!

Sunday, February 5, 2012

Using SPQuery to return SharePoint list items

Using SPQuery and CAML(Collaborative Application Markup Language) is an efficient way to retrieve data in SharePoint list. It help us to filter and order items in the selected list.
In this post, I want to introduce to you an example of using them.
In the following code, I want to get all the employees with the position of Developer in Employee list, then, I order them by their Salary ascending.

            SPWeb web = SPContext.Current.Web;
            SPList list = web.Lists["Employee"];
            string query = @"<Where>
                                              <Eq>
                                                    <FieldRef Name='Position' /><Value Type='Choice'>{0}</Value>
                                             </Eq>
                                   </Where>
                                   <OrderBy>
                                            <FieldRef Name='Salary' Ascending='False' />
                                   </OrderBy>";
            query = string.Format(query, "Developer");                                                           
            SPQuery spQuery = new SPQuery();
            spQuery.Query = query;
            SPListItemCollection items = list.GetItems(spQuery);
            grid.DataSource = items.GetDataTable();
            grid.DataBind();

Result:



Hope this helps!

Thursday, February 2, 2012

Sharepoint 2010 – New functionalities for listings

Enforce Unique Values in Site Columns Ability

In MOSS 2007, we do not have any option to set unique column value for the field in document library or list. We can still achieve that with the help of event handlers and adding some code in the ItemAdding event. But still there was no direct way to do it.
Now in SharePoint 2010, we have the built in functionality to enforce the uniqueness of the field. But yes do remember that the field must be indexed first before you want to set it as a primary key.
Well, just a quick question. Do we have anything as primary key in MOSS 2007? Yes, we do have and that is ID field in list or library. However that does not solve the purpose as it is just used to identify items and used heavily in coding purpose.
So let’s see how to go ahead with primary key in list field.
Create a list in SharePoint 2010 site and then create a field that you want to have a primary key. Go to list settings. Go to indexed columns and choose that column to be indexed.
When you create a field now then we have an option to enforce the unique value. This can be set only when you have made that column indexed. So if you have not indexed this column, SP 2010 will ask you to do it.
 Once you set this field as unique key, then go ahead and add one value and try to add another with the same. It will not allow you to do so and show the message.

Lookup

SharePoint 2010 offers a lot of new functionality for listings. One of them is “Additional Columns”. So what does it mean?
This means that you create a lookup field from the Annoucement list. But if i want to see the Title and the Expires, simply stick in the check box as the following figure. This is established using so called additional columns.
 

Validation settings

In SharePoint 2010, a new setting point in List and Library settings is available. This point is called “Validation settings”. Validation settings will be very missed in SharePoint 2007, because there wasn’t a way to avoid such easy and daily business related things like dates in the past etc. It seems that this will be worked with SharePoint 2010, but how the feature looks like? In the pre-beta version of SP2010 I work with, you can buil expresions like in calculated columns. I tried the following expression:

And, there’s the trick, I wasn’t able to save the task! Ok, in this version I don’t get the message that was set up in the validation settings, but seems it works! Validation isn’t the newest feature at all, but hey, it’s reeeeaaly usefull!
Hope this help!

Sunday, January 22, 2012

Saving Changes Is Not Permitted On SQL Server 2008. How To Solve?

Saving Changes is not permitted occurs when doing alter table (table structure is changed):
  1. change data type on existing columns
  2. or change allow nulls on existing columns
To allow you to saving changes after you alter table, do disable prevent changes:
  1. Open microsoft SQL Server Management Studio 2008
  2. Click Tools, then click Options
  3. Click Designers
  4. Uncheck prevent saving changes that require table re-creation
  5. Click OK
  6. Try to alter your table.
                                                                                                        codeproject.com

Tuesday, January 17, 2012

Do SharePoint & Silverlight Have a Future Together?

Silverlight was Microsoft's answer to Adobe Flash, an application framework with which to build rich internet applications. It was launched in April 2007 to much fanfare, albeit mainly from Microsoft. Version 5 brought GPU accelerated video decoding and 64-bit support in December of last year. It also brought the conclusion of the Silverlight story, as this version is set to be the final release. Silverlight is no more. Or so people have been speculating, as there has yet to be any official word from Microsoft. Its lifespan might be prolonged as a Windows Phone platform, but it seems likely it will cease to exist as a browser plugin.
However this article is not about SIlverlight per se, but rather its somewhat fractured relationship with SharePoint. If we have really seen the final installment of Silverlight, what does that mean for its use with SharePoint in the future? Let’s start by seeing how it is used today.

 

How SharePoint 2010 Utilizes Silverlight

Silverlight has found some favor with developers as a tool with which to build rich webparts. Video is a popular example, and various media player webparts exist that make use of Silverlight's ability to deliver good quality video over the web. In fact the out-of-the-box SharePoint 2010 media webpart is a Silverlight control. A number of third party webparts also exist that use Silverlight to interact with pictures and audio in interesting ways.
SharePoint 2010 also includes a generic Silverlight webpart, which can be used to host a specific Silverlight application by referencing the document library URL it was deployed to. This method allows such applications to be easily added to content pages. Microsoft tried to encourage this path of integration with an official "blueprint" for Silverlight and SharePoint. This consisted of source code, guidance notes and a number of sample applications.
The out-of-the-box SharePoint 2010 interface also makes use of Silverlight to provide a slick experience for end users. The list selection screen is a good example, offering animation and interaction effects provided by Silverlight.

 

The Future of SharePoint and Silverlight

But if Silverlight 5 really is to be the final release, what will happen in the future with SharePoint? It seems likely that Silverlight's slow growth as a SharePoint development tool will stall, leading it to be replaced altogether in the next version of the product. No one really knows what it will be replaced by, but the smart money would seem to be HTML5.
Microsoft seems to be making a strategic decision to back HTML5 for web and app-style development. Windows 8 is using HTML5 as its application platform, so it seems likely that the next version of SharePoint will fall in line with this vision.
Expect out-of-the-box Silverlight webparts and Silverlight powered interfaces to disappear. The exception will probably be the "host a Silverlight application" webpart, which may still remain to support any existing legacy implementations. SharePoint 2010 made a big push with web accessibility, greatly improving the HTML its pages and webparts produced. I would expect the back-end and admin pages to see an overhaul in the next version of SharePoint and for both to use HTML5. Whilst the accessibility of these pages is probably less important, it is unlikely Silverlight will remain purely to provide some interface bells and whistles.
I expect to see all traces of Silverlight disappear from the next version of SharePoint. It has been a powerful and useful tool for rich media and interfaces, but it seems its niche approach has run its course. SharePoint 2012 (or 2013) will likely adopt HTML5 for everything Silverlight has previously been used for. Put bluntly, SharePoint and Silverlight have no future at all.

                                                                                                                         http://www.cmswire.com

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Affiliate Network Reviews