Tuesday, April 16, 2013

SQL Server 2008 database engine login failed for administrator user in windows 7/8


I am administrator in my machine windows 8, But I cannot login to SQL using my administrator user.
Problem I installed SQL using other user and I didn't remember its password to solve this problem I followed the following steps:
  1. Open the command prompt (Right-Click on and select "Run As Administrator")
  2. From the command prompt type net stop MSSQLSERVER
  3. Next type net start MSSQLSERVER /m
  4. Open SQL Server Management Studio. Do not login, cancel the login dialog.
  5. From the file Menu select New->Database engine query, and login (Make sure you use the host name and not localhost).
  6. Execute the query ALTER LOGIN sa WITH PASSWORD = ''; to reset the password (if the sa is not enabled then type ALTER LOGIN sa ENABLE to do so)
  7. Login with the sa user and add the Administrator user.

Failed to install Lync in Windows 8


When tried to install Lync in Windows 8 I faced error Another Installation Already in Progress (Although I didn't run previous installation). After some investigation I discovered I need to call setup as administrator.

But in Windows 8, right-clicking on a program in the Start screen won’t display Run as administrator option. While Run as administrator option is available when you right-click on a program shortcut on the desktop, the same option doesn’t appear when you right-click on program shortcut in the Start screen.

Step 1: Switch to the Metro Start screen and start typing the program’s name to see your program

Step 2: Right-click on the program name to see Advanced option.
Step 3: Click on Advanced and then select Run as administrator option.
After these steps, I can install Lync

Sunday, December 23, 2012

How to Make ODP.NET 4.0 (64 bit) working on 64 bit machine


When you Install ODP.NET 64 bit and try to use it in Visual Studio 2010 and the project is of type ASP.NET Website. it give the error from the web.config file during compile time.


"Could not load file or assembly 'Oracle.DataAccess, Version=4.112.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342' or one of its dependencies. The system cannot find the file specified"

The best possibility to handle this is to use the x86 version locally with Visual Studio and x64 version on the server with IIS. To do this you have to download both versions - copy one in folder lib\x86 and the other in lib\x64 After this you have to modify the project file(s) - visual studio supports conditional references. Add following section to your project file:


 <PropertyGroup>
     <ReferencesPath Condition=" '$(Platform)' == 'x86' ">..\Lib\x86</ReferencesPath>   
     <ReferencesPath Condition=" '$(Platform)' == 'x64' ">..\Lib\x64</ReferencesPath>     
 </PropertyGroup>


After this reference the odp.net assmebly like this:


  <Reference ... processorArchitecture=$(Platform)">
   <SpecificVersion>False</SpecificVersion>
   <HintPath>$(ReferencesPath)\Oracle.DataAccess.dll</HintPath>          
   <Private>True</Private>
  </Reference>

Thursday, October 18, 2012

OpenXml Reset Numbering Level


I want to create Word Document using OpenXml and create numbering level. I faced a problem when I want to start numbering Level.
To Solve this problem you need to create new instance from abstract number using function as below:

   
      static Numbering AddAbstractNumbering(Numbering numbering1, int numberId,
             int abstractNumber)
      {
          NumberingInstance numberingInstance6 = new NumberingInstance ()
          {NumberID = numberId};          
          AbstractNumId abstractNumId6 = new AbstractNumId() { Val = 1 };
          numberingInstance6.Append(abstractNumId6,
             new LevelOverride() {
                    StartOverrideNumberingValue = new StartOverrideNumberingValue() { Val = 1 }
             } );
          numbering1.Append(numberingInstance6);
          return numbering1;
      }


and use this instance to add numbering level to your paragraph:

   
      Paragraph paragraph2 = new Paragraph();
      ParagraphProperties paragraphProperties1 = new ParagraphProperties();
      ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "ListParagraph" };
      NumberingProperties numberingProperties1 = new NumberingProperties();
      NumberingLevelReference numberingLevelReference1 =  
                                            new NumberingLevelReference() { Val = 0 };
      NumberingId numberingId1 = null;
      if (isNumberingStart)
      {
             numberId++;
             numbering1 = AddAbstractNumbering(numbering1, numberId);
             isNumberingStart = false;
       }
       numberingId1 = new NumberingId() { Val = numberId };
       numberingProperties1.Append(numberingLevelReference1);
       numberingProperties1.Append(numberingId1);

       paragraphProperties1.Append(paragraphStyleId1);
       paragraphProperties1.Append(numberingProperties1);

        paragraph2.Append(paragraphProperties1);

Wednesday, September 5, 2012

Extract pages from pdf to new pdf using iTextSharp

This is sample of code to extract pages from pdf file to new file
public static void Main(string[] args)
        {
            try
            {
                string sourcePath = args[0];
                string outputPath = args[1];
                PdfReader reader = new PdfReader(sourcePath);
                Document document = new Document(reader.GetPageSizeWithRotation(1));
                PdfCopy copier = new PdfCopy(document, new FileStream(outputPath, FileMode.Create));
                //PdfCopy copier = PdfCopy.GetInstance(document, new FileStream(args[1], FileMode.Create));
                int startpage = int.Parse(args[2]);
                int endpage = int.Parse(args[3]);
                document.Open();
                for (int pageCounter = startpage; pageCounter <= endpage && pageCounter < reader.NumberOfPages + 1;
                    pageCounter++)
                {
                    PdfImportedPage page = copier.GetImportedPage(reader, pageCounter);
                    //byte[] page = reader.GetPageContent(pageCounter);
                    copier.AddPage(page);
                }
                document.Close();
                reader.Close();

            }
            catch (DocumentException de)
            {
                System.Console.Error.WriteLine(de.Message);
            }
            catch (IOException ioe)
            {
                System.Console.Error.WriteLine(ioe.Message);
            }
        }

Wednesday, May 30, 2012

Getting Date from Excel using openXml

When iterated through excel and read cell contains date it returned int value. you can read cell contains date and convert to simple date format using code below:
  Cell cellDate;            
    string newDate;            
    using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open("2.xlsx", false))            
   {
                var sheets = spreadsheetDocument.WorkbookPart.Workbook.Descendants();

                foreach (Sheet sheet in sheets)
                {
                    var sheets = spreadsheetDocument.WorkbookPart.Workbook.Descendants();
                    foreach (Sheet sheet in sheets)
                   {
                       List news = new List();
                       uint rowIndex = 1;
                       uint colIndex = 1;
                       WorksheetPart worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(sheet.Id);

                       Worksheet worksheet = worksheetPart.Worksheet;
                       SheetData sheetData = worksheet.GetFirstChild();
                       IEnumerator rows = sheetData
                                            .Elements().GetEnumerator();
                      while (rows.MoveNext())
                      {
                        Row row = rows.Current;
                        cellDate = GetCell(sheetData, "C" + rowIndex.ToString());
                        if (cellDate.DataType != null && cellDate.DataType == CellValues.SharedString)
                        {
                             newDate = GetSharedStringItemById(spreadsheetDocument.WorkbookPart, int.Parse(cellDate.CellValue.InnerText));
                        }
                        else
                        {
                           newDate = DateTime.FromOADate(double.Parse(((CellValue)cellDate.FirstChild).Text)).ToString();
                        }
              }
           }
        }
     }

   public static Cell GetCell(SheetData sheetData, string fullAddress)
   {
            return sheetData.Descendants()
                .Where(c => c.CellReference == fullAddress)
                .FirstOrDefault();
   }

    private static Cell GetCell(Worksheet worksheet, string columnName, uint rowIndex)
    {
          Row row = GetRow(worksheet, rowIndex);

          if (row == null)
                return null;

          return row.Elements().Where(c => string.Compare
                   (c.CellReference.Value, columnName +
                   rowIndex, true) == 0).FirstOrDefault();
    }


    // Given a worksheet and a row index, return the row.
    private static Row GetRow(Worksheet worksheet, uint rowIndex)
    {
          return worksheet.GetFirstChild().
              Elements().Where(r => r.RowIndex == rowIndex).FirstOrDefault();
    }

    public static string GetSharedStringItemById(WorkbookPart workbookPart, int id)
    {
          return workbookPart.SharedStringTablePart.SharedStringTable.Elements()
                .ElementAt(id).InnerText;
    }


Friday, May 11, 2012

Database Performance Considerations

While designing your database, keep performance in mind. You can't really tune performance later when your database is in production.
  1. Normalize and De normalize Tables.
  2. Create Table Columns with maximum row size.(If number of columns larger than row size, split table into multiple tables with relations one to one). For column with extended size like binary, ntext, and...etc We prefer to put in separate table.
  3. Create a primary key on each table. Each primary key is clustered index.
  4. Add calculated columns which you need to avoid complicated queries.
  5. Create an index on any column that is a foreign key.
  6. Create indexes for your query, Indexes will eliminate rows scanning and locking problems:
    • Plan your indexes. Indexes enhance performance but increasing them cause drawback. Choose indexes make big filtration of your records.
    • Create simple index (indexes have only one column) for Where condition.
    • For sort create composite indexes(indexes have multiple columns).
  7. Create Indexed View if Possible.
  8. Use owner qualify of your objects (as much as possible) when you reference them in TSQL. Use owner.table instead of just table. 
  9. Use set nocount on at the top of each stored procedure and set nocount off at the bottom. 
  10. If needn't locking your database table, you take a chance on a dirty read? Ways of dirty work:
    • Use the NOLOCK hint.
    • Use SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED at the top of the procedure, then reset to READ COMMITTED at the bottom.
  11. Return the columns and the rows you need.use select column1, coulmn2,.. instead of select *
  12. Use transactions when appropriate, decrease transaction time.
  13. Avoid temp tables as much as you can.
  14. Indexes will not work with Functions for example, where LTRIM(Name) = 'Products'.
  15. Avoid using OR in your query as much as possible (Cause unexpected plan), Use join instead of it.
  16. Avoid negative query NOT IN (Use outer join),<> (Indexes will not work with Negative query). Same thing when you use like as like '%val'.
  17. If you use dynamic sql (executing a concatenated string), use named parameters and sp_executesql (rather than EXEC). 
  18. Reduce the number of round trips to the server.