Monday, December 30, 2013

Error JD Edwards EnterpriseOne 9.1 Not showing all webpage Elements

EnterpriseOne 9.1 Not showing all webpage Elements, you can fix as following:-



  1. Open the desktop, and then tap or click the Internet Explorer icon on the taskbar.

  2. Tap or click the Tools button Tools, and then tap or click Compatibility View settings.
  3. Under Add this website, enter the URL of the site you want to add to the list, and then tap or click Add.


--
Thanks
Shweta Sharma
http://www.svdeals.com

Wednesday, November 27, 2013

Error The query did not run, or the database table could not be opened. Excel 2010

Getting following error when running Stored proc with temp tables in EXCEL 2010


"The query did not run, or the database table could not be opened.
Check the database server or contact your database administrator. Make sure the external database is available and hasn't been moved or reorganized, then try the operation again."

Use folling code at the beginning of the stored proc 
SET NOCOUNT ON

Tuesday, November 26, 2013

Character index sql-server in loop , data in Table

declare

@bu varchar(300)

set

@bu=',0100000011,0100000050,0100000051,0100000026,'

create

table #tempmaintable( inpbu varchar(12))

DECLARE

@Str NVARCHAR(MAX)

SET

@Str = @bu

DECLARE

@Part NVARCHAR(MAX)

DECLARE

@IND INT

SET

@IND = CHARINDEX(',',@Str)

DECLARE

@EIND INT set @EIND = 0

WHILE

(@IND != LEN(@STR))

BEGIN

SET @EIND = ISNULL(((CHARINDEX(',', @Str, @IND + 1)) - @IND - 1), 0)

insert into #tempmaintable SELECT (SUBSTRING(@Str, (@IND + 1), @EIND))

SELECT @IND = ISNULL(CHARINDEX(',', @STR, @IND + 1), 0)

END

select

* from #tempmaintable

Monday, October 14, 2013

Friday, October 11, 2013

Working code for upload data from Excel to Sql-Server Using C#

Working code for  upload data from Excel 2010 to SQL-Server 2008 , working code.
C# , ASP.Net 4.0


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Common;
using System.Configuration;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {


        string ExcelContentType = "application/vnd.ms-excel";
        string Excel2010ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        if (FileUpload1.HasFile)
        {
            //Check the Content Type of the file
            if (FileUpload1.PostedFile.ContentType == ExcelContentType || FileUpload1.PostedFile.ContentType == Excel2010ContentType)
            {
                try
                {
                    //Save file path
                    string path = string.Concat(Server.MapPath("~/File/"), FileUpload1.FileName);//Create this folder ib your project
                    //Save File as Temp then you can delete it if you want
                    FileUpload1.SaveAs(path);
                    
                    string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path);

                    // Create Connection to Excel Workbook
                    using (OleDbConnection connection =  new OleDbConnection(excelConnectionString))
                    {
                        OleDbCommand command = new OleDbCommand("Select * FROM [Sheet1$]", connection);

                        connection.Open();

                        // Create DbDataReader to Data Worksheet
                        using (DbDataReader dr = command.ExecuteReader())
                        {

                            string sqlConnectionString = ConnectionString;

                            // Bulk Copy to SQL Server
                            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
                            {
                                bulkCopy.DestinationTableName = "Tbl_YourTable";
                                bulkCopy.WriteToServer(dr);
                                Label5.Text = "The data has been exported successfully from Excel to SQL";
                            }
                        }
                    }
                }

                catch (Exception ex)
                {
                    Label5.Text = ex.Message;
                }
            }
        }
    }
    private string ConnectionString
    {
        get
        {
            string connectionString = ConfigurationManager.ConnectionStrings["connmy"].ConnectionString;
            return connectionString;
        }
    }

}

Error HTTP Error 404.3 - Not Found The page you are requesting cannot be served because of the extension configuration. If the page is a script, add

run this
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

Tuesday, October 8, 2013

Run SSIS package from C# 4.0 VS 2010

        Microsoft.SqlServer.Dts.Runtime.Wrapper.ApplicationClass app = new Microsoft.SqlServer.Dts.Runtime.Wrapper.ApplicationClass();
        string packagePath = @"C:\Users\kumaraje\Documents\Test SSIS.dtsx";
        Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSPackage100 package = app.LoadPackage(packagePath, true, null);
        package.Execute(); 

Sunday, October 6, 2013

Fix iMessage Apple

Settings->general ->reset->reset network settings

Friday, September 20, 2013

Chart Control ASP.Net

List all the .XLSM files from folder and sub folder - VBA Excel


Public Sub TestListDir()
    Worksheets(1).Cells(2, 1).Activate
    Call listDir("C:\temp\", 1)
End Sub

Public Sub listDir(strPath As String, lngSheet As Long)
Dim strFn As String
Dim strDirList() As String
Dim lngArrayMax, x As Long
lngArrayMax = 0
strFn = Dir(strPath & "*.*", 23)
While strFn <> ""
    If strFn <> "." And strFn <> ".." Then
        If (GetAttr(strPath & strFn) And vbDirectory) = vbDirectory Then
            lngArrayMax = lngArrayMax + 1
            ReDim Preserve strDirList(lngArrayMax)
            strDirList(lngArrayMax) = strPath & strFn & "\"
            'Debug.Print strDirList(lngArrayMax)
            
        Else
            ActiveCell.Value = strPath & strFn
             If InStr(strFn, ".xlsm") > 0 Then Debug.Print strPath & strFn
            'if(strFn.Name.)
            
            
            Worksheets(lngSheet).Cells(ActiveCell.Row + 1, 1).Activate
        End If
    End If
    strFn = Dir()
Wend
If lngArrayMax <> 0 Then
    For x = 1 To lngArrayMax
        Call listDir(strDirList(x), lngSheet)
    Next
End If
End Sub

Divide by zero SQL-server- NULLIF

Select qty/ NULLIF((select amt from amtfile where itemno=123),0) from itemqty


or user case when (select amt from amtfile where itemno=123) =0 then Null else select amt from amtfile where itemno=123) =0 end



Thursday, September 19, 2013

VBA code Export to a Folder


Public Sub ExportModules()
    Dim bExport As Boolean
    Dim wkbSource As Excel.Workbook
    Dim szSourceWorkbook As String
    Dim szExportPath As String
    Dim szFileName As String
    'Dim cmpComponent As VBIDE.VBComponent

    ''' The code modules will be exported in a folder named.
    ''' MFExport in the Documents folder.
    ''' The code below create this folder if it not exist
    ''' or delete all files in the folder if it exist.
    
    On Error Resume Next
    MkDir "MFExport"
    On Error GoTo 0

    
    If FolderWithMFExport = "Error" Then
        MsgBox "Export Folder not exist"
        Exit Sub
    End If
    
    On Error Resume Next
        Kill FolderWithMFExport & "\*.*"
        
'        Dim oldfolder As String
'        Dim Newfolder As String
'        oldfolder = "MFExport"
'        Newfolder = "MFExportOLD"
'        Name oldfolder As Newfolder
        
    On Error GoTo 0

    ''' NOTE: This workbook must be open in Excel.
    szSourceWorkbook = ActiveWorkbook.Name
    Set wkbSource = Application.Workbooks(szSourceWorkbook)
    
    If wkbSource.VBProject.Protection = 1 Then
    MsgBox "The VBA in this workbook is protected," & _
        "not possible to export the code"
    Exit Sub
    End If
    
    szExportPath = FolderWithMFExport & "\"
    
    For Each cmpComponent In wkbSource.VBProject.VBComponents
        
        bExport = True
        szFileName = cmpComponent.Name

        ''' Concatenate the correct filename for export.
        Select Case cmpComponent.Type
            Case vbext_ct_ClassModule
                szFileName = szFileName & ".cls"
            Case vbext_ct_MSForm
                szFileName = szFileName & ".frm"
            Case vbext_ct_StdModule
                szFileName = szFileName & ".bas"
            Case vbext_ct_Document
                ''' This is a worksheet or workbook object.
                ''' Don't try to export.
                bExport = False
        End Select
        
        If bExport Then
            ''' Export the component to a text file.
            cmpComponent.Export szExportPath & szFileName
            
        ''' remove it from the project if you want
        '''wkbSource.VBProject.VBComponents.Remove cmpComponent
        
        End If
   
    Next cmpComponent

 
    Dim OldFolderName As String, NewFolderName As String
    
    '-- Set Folder Names
    OldFolderName = szExportPath
    NewFolderName = Replace(szExportPath, "MFExport\", "MFExport") + "_" + Format(Now(), "yyyymmdd") + "_" + Format(Now(), "HHMMSS")
    
    On Error Resume Next
        Kill NewFolderName
    '-- Rename them
    Name OldFolderName As NewFolderName
        
        
        

    MsgBox "Export is ready"
End Sub


Public Sub ImportModules()
    Dim wkbTarget As Excel.Workbook
    Dim objFSO As Scripting.FileSystemObject
    Dim objFile As Scripting.File
    Dim szTargetWorkbook As String
    Dim szImportPath As String
    Dim szFileName As String
    Dim cmpComponents As VBIDE.VBComponents

    If ActiveWorkbook.Name = ThisWorkbook.Name Then
        MsgBox "Select another destination workbook" & _
        "Not possible to import in this workbook "
        Exit Sub
    End If

    'Get the path to the folder with modules
    If FolderWithMFExport = "Error" Then
        MsgBox "Import Folder not exist"
        Exit Sub
    End If

    ''' NOTE: This workbook must be open in Excel.
    szTargetWorkbook = ActiveWorkbook.Name
    Set wkbTarget = Application.Workbooks(szTargetWorkbook)
    
    If wkbTarget.VBProject.Protection = 1 Then
    MsgBox "The VBA in this workbook is protected," & _
        "not possible to Import the code"
    Exit Sub
    End If

    ''' NOTE: Path where the code modules are located.
    szImportPath = FolderWithMFExport & "\"
        
    Set objFSO = New Scripting.FileSystemObject
    If objFSO.GetFolder(szImportPath).Files.Count = 0 Then
       MsgBox "There are no files to import"
       Exit Sub
    End If

    'Delete all modules/Userforms from the ActiveWorkbook
    Call DeleteVBAModulesAndUserForms

    Set cmpComponents = wkbTarget.VBProject.VBComponents
    
    ''' Import all the code modules in the specified path
    ''' to the ActiveWorkbook.
    For Each objFile In objFSO.GetFolder(szImportPath).Files
    
        If (objFSO.GetExtensionName(objFile.Name) = "cls") Or _
            (objFSO.GetExtensionName(objFile.Name) = "frm") Or _
            (objFSO.GetExtensionName(objFile.Name) = "bas") Then
            cmpComponents.Import objFile.Path
        End If
        
    Next objFile
    
    MsgBox "Import is ready"
End Sub

Function FolderWithMFExport() As String
    Dim WshShell As Object
    Dim FSO As Object
    Dim SpecialPath As String

    Set WshShell = CreateObject("WScript.Shell")
    Set FSO = CreateObject("scripting.filesystemobject")

' Define file Path
    'SpecialPath = WshShell.SpecialFolders("MyDocuments")
    SpecialPath = WshShell.SpecialFolders("c:/")
    
'//SpecialPath = "c:/temp"
    If Right(SpecialPath, 1) <> "\" Then
        SpecialPath = SpecialPath & "\"
    End If
    
    If FSO.FolderExists(SpecialPath & "MFExport") = False Then
        On Error Resume Next
        MkDir SpecialPath & "MFExport_" + Date
        On Error GoTo 0
    End If
    
    If FSO.FolderExists(SpecialPath & "MFExport") = True Then
        FolderWithMFExport = SpecialPath & "MFExport"
    Else
        FolderWithMFExport = "Error"
    End If
    
End Function

Function DeleteVBAModulesAndUserForms()
        Dim VBProj As VBIDE.VBProject
        Dim VBComp As VBIDE.VBComponent
        
        Set VBProj = ActiveWorkbook.VBProject
        
        For Each VBComp In VBProj.VBComponents
            If VBComp.Type = vbext_ct_Document Then
                'Thisworkbook or worksheet module
                'We do nothing
            Else
                VBProj.VBComponents.Remove VBComp
            End If
        Next VBComp
End Function






Rename folder VBA Excel

  Dim OldFolderName As String
  Dim NewFolderName As String
    
    OldFolderName = "C:\testfloderNew"
    NewFolderName = "C:\testfolderOld"
    
    '-- Rename them
    Name OldFolderName As NewFolderName


Wednesday, September 18, 2013

C# 4.0 Graph with 2 Y axis asp.net

<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    <asp:Chart ID="Chart1" runat="server" DataSourceID="SqlDataSource1" 
        Width="643px">
        <series>
            <asp:Series Name="Series1" XValueMember="ObjSub" 
        YValueMembers="Period_04" ChartType="Line" YValuesPerPoint="2"  >
            </asp:Series>
        
        <asp:Series Name="Series2" XValueMember="ObjSub" 
        YValueMembers="Period_05" ChartType="Line" YValuesPerPoint="2">
            </asp:Series>

        
        </series>


        <chartareas>
            <asp:ChartArea Name="ChartArea1">
            </asp:ChartArea>
        </chartareas>
    </asp:Chart>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:BUDGETReports %>" 
        SelectCommand="SELECT top 5  [ObjSub], sum([Period_04]) Period_04, sum([Period_01]) Period_05 FROM [BudgetData] where fy=14 and co=1 group by objsub">
    </asp:SqlDataSource>
    </form>
</body>
</html>

Monday, September 16, 2013

Load Data into Dropdownlist using SQL -server (no sqldatasource)

void filDDPN()
{

    DropDownList1.Items.Clear();
    DataTable subjects = new DataTable();

    using (SqlConnection con = new SqlConnection(ConnectionString))
    {

        try
        {
            SqlDataAdapter adapter = new SqlDataAdapter("SELECT [Period] FROM [tbl500_Periods] order by id desc", con);
            adapter.Fill(subjects);

            DropDownList1.DataSource = subjects;
            DropDownList1.DataTextField = "Period";
            DropDownList1.DataValueField = "Period";
            DropDownList1.DataBind();
        }
        catch (Exception ex)
        {
            // Handle the error
        }

    }
}

Tuesday, September 10, 2013

Date format GirdView

  <asp:boundfield datafield="Your_Date_Column" dataformatstring="{0:MMMM d, yyyy}" htmlencode="false" />


Gridview item wrap fixed width

 
<asp:BoundField DataField="COMMTS" HeaderText="Comments" ItemStyle-Wrap="true" ItemStyle-Width="150"

SortExpression="COMMTS" />

Thursday, August 29, 2013

Get Rolling 6 Months in SQL-Server

SELECT x.months, [YYYYMM] = CAST(CONVERT(CHAR(6),Months,112) AS INT)
FROM (VALUES (0),(1),(2),(3),(4),(5),(6)) r (n)
CROSS APPLY (SELECT Months = DATEADD(mm,-n,GETDATE())) x


Tuesday, August 27, 2013

Introduction to JD Edwards EnterpriseOne Tools: APIs and Business Functions

JD Edwards EnterpriseOne Tools APIs and business functions are used to create
complex, reusable routines in C. Business functions can call APIs directly and can in
turn be invoked from event rules (ER).

http://docs.oracle.com/cd/E17984_01/doc.898/e14700.pdf

JD Edwards main Development Topics

Objects of Interactive Development
Object Management Workbench
User Defined Codes (UDC)
Data Dictionary
Understanding Table Design Aid
Understanding Business View Design Aid
Understanding Form Design Aid (FDA)
Debug Interactive Application
Understanding Asynchronous Processing
Understanding Processing Options
Business Function Overview
Data Structures Design Aid
Create and Code C Business Function
Create and Code NER Business Function
Debugging C Code.
Power Form & Subforms
Cache
Master Business Functions

Wednesday, August 21, 2013

While Loop with temp table in SQL Server


declare @i int
set @i=1
WHILE (@i < 10)
Begin
set @i=@i+1
--select  '1'

drop table #temp32
select  * into  #temp32   from #temp31 
update #temp32 set RemainingLife=(RemainingLife-1), Accum=Accum+DeprPerMonth, NetBookValue=cast(NetCost+(Accum+DeprPerMonth) as decimal(15,2)),PastLife=1+PastLife,[month]=@i --where RemainingLife>0
update #temp32 set DeprPerMonth=0 --where RemainingLife>0
-- for IN N I
update  #temp32  set DeprPerMonth= -(isnull(NetCost,0)+ isnull(Accum,0))
where DeprMeth<>'00' and (cast((isnull(NetCost,0)/AssetLife)* -1 *(PastLife)- isnull(Accum,0) as decimal(15,2))-(isnull(NetCost,0)+ isnull(Accum,0)))>0
 
update  #temp32  set DeprPerMonth= cast((NetCost/AssetLife)* -1 *(PastLife)-isnull(Accum,0) as decimal(15,2))
where DeprMeth<>'00' and (cast((isnull(NetCost,0)/AssetLife)* -1 *(PastLife)- isnull(Accum,0) as decimal(15,2))-(isnull(NetCost,0)+ isnull(Accum,0)))<0
 
update  #temp32  set DeprPerMonth=0 where NetBookValue<=0 
update  #temp32  set Accum=0,NetBookValue=0,DeprPerMonth=0 where  Accum is null
update  #temp32  set PastLife=AssetLife where  PastLife>AssetLife
update  #temp32  set NetBookValue=NetCost where  Accum =0
-- IN '' 'I'
update #temp32 set DeprPerMonth =
(case when (cast((isnull(NetCost,0)/AssetLife)* -1 *(PastLife-1)- isnull(Accum,0) as decimal(15,2))-(isnull(NetCost,0)+ isnull(Accum,0)))>0 then -(isnull(NetCost,0)+ isnull(Accum,0))
Else cast((NetCost/AssetLife)* -1 *(PastLife-1)-isnull(Accum,0) as decimal(15,2))  end )*-1
where  DeprMeth='IN' and DeprInfo='' and CompMeth='I'  
-- 01 'N' 'I'
-- For disposable vale
update #temp32 set DeprPerMonth =cast(isnull(NetBookValue,0)as decimal(15,2))*-1 where  DeprMeth='01' and DeprInfo='N' and CompMeth='P'   and RemainingLife=-1 
update #temp32 set DeprPerMonth =case when RemainingLife+1 >0 then -1*(NetBookValue/(RemainingLife+1)) else 0 end where  DeprMeth='01' and DeprInfo='N' and CompMeth='P'  and AssetLife=84 
and   RemainingLife<>-1 
update #temp32 set DeprPerMonth =cast(isnull(NetCost/AssetLife,0)as decimal(15,2))*-1   where  DeprMeth='01' and DeprInfo='N' and CompMeth='P' and   AssetLife<>84 and NetBookValue>0  and   RemainingLife<>-1 
update #temp32 set DeprPerMonth =cast(isnull(NetBookValue,0)as decimal(15,2))*-1   where  DeprMeth='01' and DeprInfo='N' and CompMeth='P' and   AssetLife<>84 and NetBookValue>0 and   RemainingLife<>-1 
and NetCost/AssetLife>NetBookValue

-- Make it zero after straight line deprication calculation
update  #temp32  set RemainingLife=0 where  RemainingLife<0
--NB N P
update #temp32 set DeprPerMonth =case when RemainingLife+1 >0 then -1*(NetBookValue/(RemainingLife+1)) else 0 end where  DeprMeth='NB' and DeprInfo='N' and CompMeth='P' 
update #temp32 set NetBookValue=cast(NetBookValue as decimal(15,2)),Accum=cast(Accum as decimal(15,2)),DeprPerMonth=cast(DeprPerMonth as decimal(15,2))

drop table #temp31
select  * into  #temp31   from #temp32
insert into testTab  select  *  from #temp32

CONTINUE
end 

Thursday, August 15, 2013

JD Edwards - How to create parent child relationship for Account master(F0901) Object AC


Change level of detail with temp table name.


DECLARE
    @db_name SYSNAME,
    @sql VARCHAR(1000),
    @databaseNM varchar(50),
    @ACOBJ int,
    @ACLDA int
    set @ACLDA=4
    drop table #temp1
    create table #temp1 (fld1 int,fld2 int) 
    
DECLARE db_cursor CURSOR FOR 
--SELECT Name FROM sys.databases where Name=@databaseNM
select ACOBJ  obj from  JDE_PRODUCTION.PRODDTA.F0909 where ACLDA=@ACLDA and acobj>00000 and acobj<100000   --and acobj=41110
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @db_name
WHILE (@@FETCH_STATUS = 0)
BEGIN
select @ACOBJ=MAX(ACOBJ)   from  JDE_PRODUCTION.PRODDTA.f0909 where  ACLDA=@ACLDA-1 and ACOBJ <(select MAX(ACOBJ)  from  JDE_PRODUCTION.PRODDTA.f0909 where ACOBJ=@db_name  and ACLDA=@ACLDA)
--select @ACOBJ=MAX(ACOBJ)  from  JDE_PRODUCTION.PRODDTA.f0909 where  ACLDA=6 and ACOBJ <(select MAX(ACOBJ)  from  JDE_PRODUCTION.PRODDTA.f0909 where ACOBJ=@db_name  and ACLDA=7)
Insert into #temp1 select @ACOBJ,@db_name
FETCH NEXT FROM db_cursor INTO @db_name
END
CLOSE db_cursor
DEALLOCATE db_cursor
--drop table #temp5
select * into #temp5  from #temp1
select *  from #temp1


--select * from #temp5
--select * from #temp6
--select * from #temp7
--select * from #temp8
--drop table  #temp4_1


select a7.fld1 A_071,a7.fld2  A_072,a8.fld1 A_081,a8.fld2 A_082  into #temp7_1 from #temp7 a7
left outer join  #temp8 a8 on  a7.fld2=a8.fld1

select fld1 A_061,fld2 A_062,A_071,A_072,A_081,A_082  into #temp6_1 from #temp7_1 a7 
left outer join  #temp6 a6 on  a6.fld2=a7.A_071

select fld1 A_051,fld2 A_052,A_061,A_062,A_071,A_072,A_081,A_082  into #temp5_1
from #temp6_1
left outer join  #temp5 a5 on  a5.fld2=A_061

select A_051,A_061,A_062,A_072, ISNULL(A_082,'')A_082 from #temp5_1

Tuesday, August 6, 2013

Extract all VBA code from Excel Workbook

Public Sub ExportModules()
    Dim bExport As Boolean
    Dim wkbSource As Excel.Workbook
    Dim szSourceWorkbook As String
    Dim szExportPath As String
    Dim szFileName As String
    'Dim cmpComponent As VBIDE.VBComponent

    ''' The code modules will be exported in a folder named.
    ''' VBAProjectFiles in the Documents folder.
    ''' The code below create this folder if it not exist
    ''' or delete all files in the folder if it exist.
    If FolderWithVBAProjectFiles = "Error" Then
        MsgBox "Export Folder not exist"
        Exit Sub
    End If
    
    On Error Resume Next
        Kill FolderWithVBAProjectFiles & "\*.*"
    On Error GoTo 0

    ''' NOTE: This workbook must be open in Excel.
    szSourceWorkbook = ActiveWorkbook.Name
    Set wkbSource = Application.Workbooks(szSourceWorkbook)
    
    If wkbSource.VBProject.Protection = 1 Then
    MsgBox "The VBA in this workbook is protected," & _
        "not possible to export the code"
    Exit Sub
    End If
    
    szExportPath = FolderWithVBAProjectFiles & "\"
    
    For Each cmpComponent In wkbSource.VBProject.VBComponents
        
        bExport = True
        szFileName = cmpComponent.Name

        ''' Concatenate the correct filename for export.
        Select Case cmpComponent.Type
            Case vbext_ct_ClassModule
                szFileName = szFileName & ".cls"
            Case vbext_ct_MSForm
                szFileName = szFileName & ".frm"
            Case vbext_ct_StdModule
                szFileName = szFileName & ".bas"
            Case vbext_ct_Document
                ''' This is a worksheet or workbook object.
                ''' Don't try to export.
                bExport = False
        End Select
        
        If bExport Then
            ''' Export the component to a text file.
            cmpComponent.Export szExportPath & szFileName
            
        ''' remove it from the project if you want
        '''wkbSource.VBProject.VBComponents.Remove cmpComponent
        
        End If
   
    Next cmpComponent

    MsgBox "Export is ready"
End Sub


Public Sub ImportModules()
    Dim wkbTarget As Excel.Workbook
    Dim objFSO As Scripting.FileSystemObject
    Dim objFile As Scripting.File
    Dim szTargetWorkbook As String
    Dim szImportPath As String
    Dim szFileName As String
    Dim cmpComponents As VBIDE.VBComponents

    If ActiveWorkbook.Name = ThisWorkbook.Name Then
        MsgBox "Select another destination workbook" & _
        "Not possible to import in this workbook "
        Exit Sub
    End If

    'Get the path to the folder with modules
    If FolderWithVBAProjectFiles = "Error" Then
        MsgBox "Import Folder not exist"
        Exit Sub
    End If

    ''' NOTE: This workbook must be open in Excel.
    szTargetWorkbook = ActiveWorkbook.Name
    Set wkbTarget = Application.Workbooks(szTargetWorkbook)
    
    If wkbTarget.VBProject.Protection = 1 Then
    MsgBox "The VBA in this workbook is protected," & _
        "not possible to Import the code"
    Exit Sub
    End If

    ''' NOTE: Path where the code modules are located.
    szImportPath = FolderWithVBAProjectFiles & "\"
        
    Set objFSO = New Scripting.FileSystemObject
    If objFSO.GetFolder(szImportPath).Files.Count = 0 Then
       MsgBox "There are no files to import"
       Exit Sub
    End If

    'Delete all modules/Userforms from the ActiveWorkbook
    Call DeleteVBAModulesAndUserForms

    Set cmpComponents = wkbTarget.VBProject.VBComponents
    
    ''' Import all the code modules in the specified path
    ''' to the ActiveWorkbook.
    For Each objFile In objFSO.GetFolder(szImportPath).Files
    
        If (objFSO.GetExtensionName(objFile.Name) = "cls") Or _
            (objFSO.GetExtensionName(objFile.Name) = "frm") Or _
            (objFSO.GetExtensionName(objFile.Name) = "bas") Then
            cmpComponents.Import objFile.Path
        End If
        
    Next objFile
    
    MsgBox "Import is ready"
End Sub

Function FolderWithVBAProjectFiles() As String
    Dim WshShell As Object
    Dim FSO As Object
    Dim SpecialPath As String

    Set WshShell = CreateObject("WScript.Shell")
    Set FSO = CreateObject("scripting.filesystemobject")

    SpecialPath = WshShell.SpecialFolders("MyDocuments")

    If Right(SpecialPath, 1) <> "\" Then
        SpecialPath = SpecialPath & "\"
    End If
    
    If FSO.FolderExists(SpecialPath & "VBAProjectFiles") = False Then
        On Error Resume Next
        MkDir SpecialPath & "VBAProjectFiles"
        On Error GoTo 0
    End If
    
    If FSO.FolderExists(SpecialPath & "VBAProjectFiles") = True Then
        FolderWithVBAProjectFiles = SpecialPath & "VBAProjectFiles"
    Else
        FolderWithVBAProjectFiles = "Error"
    End If
    
End Function

Function DeleteVBAModulesAndUserForms()
        Dim VBProj As VBIDE.VBProject
        Dim VBComp As VBIDE.VBComponent
        
        Set VBProj = ActiveWorkbook.VBProject
        
        For Each VBComp In VBProj.VBComponents
            If VBComp.Type = vbext_ct_Document Then
                'Thisworkbook or worksheet module
                'We do nothing
            Else
                VBProj.VBComponents.Remove VBComp
            End If
        Next VBComp
End Function
 




How to find UDF value in P6 Primavira

select * from udfvalue
select * from udfcode
select * from udfvalue where udf_text like '%manager%'
select distinct udf_text from udfvalue where udf_text like '%IT Project Manager%'
select * from udfvalue where udf_text like '%Project Manager%'
select * from udfvalue where udf_type_id=330
user_field_330
sp_help projwbs

Monday, July 22, 2013

Excel VBA 2010 - Read a folder and load file name in SQL-Server 2008

Sub ListAllFile()
     

    Dim objFSO As Object
    Dim objFolder As Object
    Dim objFile As Object
    Dim ws As Worksheet
    Dim cnt As Integer
    
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    'Set ws = Worksheets.Add
    'ActiveSheet.Range("C1").Value
    Set ws = Worksheets("Sheet1")
    cnt = 1
     
     'Get the folder object associated with the directory

    Set objFolder = objFSO.GetFolder("\\abcserver\Fin\Report Output")
    ws.Cells(1, 1).Value = "The files found in This Folder are:- " ' & objFolder.Name & "are:"
    
     'Loop through the Files collection
    For Each objFile In objFolder.Files
        ws.Cells(ws.UsedRange.Rows.Count + 1, 1).Value = objFile.Name
        'Debug.Print objFile
        rptPathName = objFile.Name
        Call InsertRecord(cnt, rptPathName)
    cnt = cnt + 1
    Next
     
     'Clean up!
    Set objFolder = Nothing
    Set objFile = Nothing
    Set objFSO = Nothing
     
End Sub




Sub InsertRecord(strcnt, strFilePathName)
            Dim adoCN As ADODB.Connection
            Dim sConnString As String
            Dim sSQL As String
            Dim lRow As Long, lCol As Long
            Dim recnt As Integer
            Dim RecRow As Integer
            Dim tbl As Range
            Dim FileName
            Set adoCN = CreateObject("ADODB.Connection")
            sConnString = stADO
            adoCN.Open sConnString
            FileName = strFilePathName
            strFilePathName = ActiveSheet.Range("C1").Value & "\" & strFilePathName
            
                         Dim MyString As String

                                        sSQL = "insert into budget.dbo.tbltempReport  select " & strcnt & ",'" & Replace(strFilePathName, "'", "''") & "'" & ""

                                       Debug.Print sSQL
                          adoCN.Execute sSQL
            adoCN.Close
            Set adoCN = Nothing
End Sub

Table structure
CREATE TABLE [dbo].[tbltempReportOutPD](
[ID] [int] NULL,
[ReportName] [nvarchar](1000) NULL
) ON [PRIMARY]

Shutdown PC command line

  shutdown /s


Wednesday, July 17, 2013

Run VBA reports in Multiple Instances - Shell

Sub RunExcelMultiple(RecCnt)

    Dim lPid As Long, i As Long
    Dim sRemoteWbName As String, sExeName As String, sParams As String
    sExeName = "excel.exe"
    
    sRemoteWbName = """" & ActiveWorkbook.FullName & """"
    
    sParams = " /e" & " -!- " & " "
    
    If (RecCnt < 11) Then
      lPid = Shell(sExeName & sParams & sRemoteWbName, vbHide)
    Else
        For ShellInstance = 1 To Round(WorksheetFunction.Min(8, RecCnt / 4), 0)
            lPid = Shell(sExeName & sParams & sRemoteWbName, vbHide)
        Next ShellInstance
    End If
    
       

End Sub

Saturday, May 18, 2013

Cannot connect to MS SQL 2008 R2 locally or remotely - Error 53

  • A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 53)

    solution

    Error 53 sql server 2008 r2


    To enable a server network protocol

    1.

    In SQL Server Configuration Manager, in the console pane, expand SQL Server Network Configuration.


    2.

    In the console pane, click Protocols for <instance name>.


    3.

    In the details pane, right-click the protocol you want to change, and then click Enable or Disable.


    4.

    In the console pane, click SQL Server Services.


    5.

    In the details pane, right-click SQL Server (<instance name>), and then click Restart, to stop and restart the SQL Server service.


    http://msdn.microsoft.com/en-us/library/ms191294.aspx




Sunday, May 5, 2013

Login from SQL-server in ASP.Net C#

    private bool SiteLevelCustomAuthenticationMethod(string UserName, string Password)
    {

        bool boolReturnValue = false;

        string strConnection = ConnectionString;

        SqlConnection Connection = new SqlConnection(strConnection);
        string strUserID = UserName;
        String strSQL = "select * from UserDetails where UDUSRID=\'" + (strUserID + "\'");
        SqlCommand command = new SqlCommand(strSQL, Connection);
        SqlDataReader Dr;
        Connection.Open();
        Dr = command.ExecuteReader();
        while (Dr.Read())
        {
            string UserNameDB = Dr["UDUSRID"].ToString();
            string PasswordDB = Dr["UDPASSWD"].ToString();
            //  string UserRoleDB = Dr["UDROLE"].ToString();


            if ((UserName == UserNameDB.TrimEnd().TrimStart()) & (Password == PasswordDB.TrimEnd().TrimStart()))
            {
                Session["Usrid"] = UserNameDB;
                Session["Uspasswd"] = PasswordDB;
                //    Session["Usrole"] = UserRoleDB;
                //  Response.Write(Session["Usrole"]);
                // Response.End();

                boolReturnValue = true;
                break;

            }

        }

        Dr.Close();

        return boolReturnValue;

    }

Send email in a format c#

    void sndemail()
    {
        MailMessage objEmail = new MailMessage();
        objEmail.To = "xxxxx@xxxxxx.com";//Session["OEMAL"].ToString().Trim();//Emald.ToString().Trim();//txtTo.Text;
        //objEmail.To = "dostind@gmail.com";//Session["OEMAL"].ToString().Trim();//Emald.ToString().Trim();//txtTo.Text;
   
        //objEmail.From = "rajeev@xxxxxx.net";
        objEmail.From = "noreply@xxxxxx.com";

        //objEmail.Cc = txtCc.Text;
        objEmail.Subject = "HI -- Notification";// +Strrslt.ToString();
        //Response.Write(Session["oename"].ToString());  HI Quiz – Course Completion Notification
        //Response.End();
        //objEmail.Body = "<table border=1 bgcolor=#F3EFE0><tr><td>Date :</td><td><b>" + DateTime.Today.ToLongDateString() + "</td></tr><tr><td>Exam Id:</td><td>" + Request["id"].ToString() + "</td></tr><tr><td>Trainee:</td><td> </b> " + Session["repname"].ToString() + "</td></tr><tr><td>Total Correct:</td><td>" + cortans + " Out of:-" + totrec + "</td></tr><tr><td>Owner: </td><td>" + Session["oename"].ToString() + "</td></tr><tr><td>Program:</td><td>Home Impovement</td></tr><tr><td><b>Result:</b></td><td><b>" + Strrslt.ToString() + "</b></td></tr>  </table>";
        objEmail.Body = "<b>The following trainee has completed the Home Improvement training course:</b><br><br>";
        objEmail.Body += "<table border=0 width=50%   bgcolor=#CCCCCC cellpadding=10 ><tr><td>Trainee :</td><td><b>" + Session["repname"].ToString() + "</td></tr><tr><td>Market:</td><td>" + Session["oeMarket"].ToString() + "</td></tr><tr><td>ICD:</td><td> </b> " + Session["owniNam"].ToString().Replace("'"," ") + "</td></tr><tr><td>Date:</td><td>" + DateTime.Today.ToLongDateString() + "</td></tr><tr><td>Total Correct: </td><td>" + cortans + " Out of:-" + totrec + "</td></tr><tr><td><b>Status:</b></td><td><b>" + Strrslt.ToString() + "</b></td></tr>  </table>";
      
        //objEmail.Body = Label4.Text;

        //objEmail.Priority = MailPriority.High;
        objEmail.BodyFormat = MailFormat.Html;//MailFormat.Html; Session["oeMarket"]
        // Make sure you have appropriate replying permissions from your local system

       SmtpMail.SmtpServer = "10.0.10.123";
        //SmtpMail.SmtpServer = "localhost";

        try
        {
            SmtpMail.Send(objEmail);


        }
        catch (Exception exc)
        {
            Response.Write("Send failure: " + exc.ToString());
        }

    }


    private string ConnectionString
    {
        get
        {
            string connectionString = ConfigurationManager.ConnectionStrings["smdbConnectionString51"].ConnectionString;
            return connectionString;
        }
    }

Tuesday, April 23, 2013

Extract Excel input string "+"

DECLARE @test varchar(100) = '+HARIA+123+MALE+STUDENT+HOUSEWIFE+jhgjh+54545+hgdfjhg+xxxxc'

SELECT TOP 8000
    Num
INTO
    #Number
FROM
    (
    SELECT
       ROW_NUMBER() OVER (ORDER BY c1.object_id) AS Num
    FROM
       sys.columns c1, sys.columns c2, sys.columns c3
    ) N

SELECT
    ROW_NUMBER() OVER (ORDER BY Num) AS Rank,
    LTRIM(RTRIM(SUBSTRING(@test,
                          Num,
                          CHARINDEX('+', @test + '+', Num) - Num
                ))) AS Value
FROM
    #Number
WHERE
    Num <= LEN (@test)
    AND
    SUBSTRING('+' + @test, Num, 1) = '+'

DROP TABLE #Number
Source :stackoverflow

Sunday, April 7, 2013

Excel vba 2010 browse select folder and open file

Private Sub CommandButton1_Click()

Dim myfile As Variant
Dim counter As Integer
Dim path As String
myfolder = "c:\tmp\"
ChDir myfolder
myfile = Application.GetOpenFilename(, , , , True)
counter = 1
If IsNumeric(myfile) = True Then
MsgBox "No files selected"
End If
While counter <= UBound(myfile)
path = myfile(counter)
Workbooks.Open path
counter = counter + 1
Wend

End Sub

Saturday, March 30, 2013

How to Save a PDF to a SQL Server

http://www.ehow.com/how_7334919_save-pdf-sql-server.html

Wednesday, March 13, 2013

How to select cells/ranges by using Visual Basic procedures in Excel

ActiveSheet.Cells(5, 4).Select  
or 

  
ActiveSheet.Range("D5").Select  

http://support.microsoft.com/kb/291308

Excel VBA ComboBox Populate dynamic value

Private Sub UserForm_Click()
With ComboBox1
For Row = 1 To 10 'Each cell in the range
If ActiveSheet.Cells(2, Row) <> "" Then
.AddItem ActiveSheet.Cells(2, Row)
End If
Next Row
End With


ActiveSheet.Cells(5, 5) = ComboBox1.Value

End Sub

Tuesday, March 5, 2013

Write A Report in Excel using VBA - SQL-server

I wrote first report in Excel-VBA using data from SQL-Server 


Sub runreports()


    

    Dim cnt As ADODB.Connection

    Dim rst As ADODB.Recordset

    Dim stSQL As String

    Dim wbBook As Workbook

    Dim wsSheet As Worksheet

    Dim rnStart As Range

    

     

    Const stADO As String = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=xxxxx;Data Source=devDB;User ID=myuser;Password=mypass; Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=myPC;Use Encryption for Data=False;Tag with column collation when possible=False"

    

     

    Set wbBook = ActiveWorkbook

    Set wsSheet = wbBook.Worksheets(5)

    

    With wsSheet

        Set rnStart = .Range("A7")

    End With

    'Report Name

    Cells(1, 10).Value = "Interco Report"

    

    stSQL = "SELECT top 100 * FROM tbl_intercoRep"

    'stSQL = "SP_Int_DeleteThis"

'    stSQL = "SP_IntercoReport"

   

     

    Set cnt = New ADODB.Connection

    

    With cnt

        .CursorLocation = adUseClient

        .Open stADO

        .CommandTimeout = 0

        Set rst = .Execute(stSQL)

    End With

   

'Worksheets("sheet5").Activate

Dim ii As Integer

    For ii = 0 To rst.Fields.Count - 1

    Cells(6, ii + 1).Value = rst.Fields(ii).Name

Next ii

 

    With Range("A1:ZZ1").Font

    .Bold = True

    .Size = 15

   

    End With

   

    With Range("A6:ZZ6").Font

    .Bold = True

   

    

    End With

   

     'Here we add the Recordset to the sheet from A1

    rnStart.CopyFromRecordset rst

    

     'Cleaning up.

    rst.Close

    cnt.Close

    Set rst = Nothing

    Set cnt = Nothing

End Sub


Saturday, March 2, 2013

Building a Word Document Using SQL Server Data

In this walkthrough, you will first create a Microsoft® Office Word 2003 document that contains bookmarks as the location for inserting text retrieved from the Microsoft SQL Server Northwind sample database. You will then use ADO.NET to connect to and retrieve the data. You'll insert the data in the Word document at the specified bookmark.

http://msdn.microsoft.com/en-us/library/office/aa192487(v=office.11).aspx

Thursday, February 28, 2013

Display Sql-server Data into Excel Using VBA


-->
Display Sql-server Data into Excel Using VBA , Working code

Private Sub CommandButton1_Click()
Dim adoCN As ADODB.Connection
Dim sConnString As String
Dim results As ADODB.Recordset
Dim sSQL As String
Dim lRow As Long, lCol As Long
sConnString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=devdb;Data Source=sqlserverdv1;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=USER-PC;Use Encryption for Data=False;Tag with column collation when possible=False"
Set adoCN = CreateObject("ADODB.Connection")
adoCN.Open sConnString

    sSQL = "select top 10 * from tempdata"
Set results = adoCN.Execute(sSQL)
   
    
    
    For Each f In results.Fields
      'Debug.Print f.Name & " " & f
      ActiveSheet.Range("A1").CopyFromRecordset results
    Next
adoCN.Close
Set adoCN = Nothing


End Sub


Tuesday, February 26, 2013

Parent Child Recursive Relation SQL-Server 2008 JDE

 

drop table #temp2

select yaan8,a.ABALPH ChildName, yaanpa,b.ABALPH ParentName into #temp2  from proddta.F060116

left outer join PRODDTA.F0101 a on yaan8=a.aban8

left outer join PRODDTA.F0101 b on yaanpa=b.aban8

where  yapast in('1','0','6') order by 2

go

 

WITH Recursive_CTE AS (

SELECT

  child.YAAN8,

  CAST(child.ChildName as varchar(100)) ChildName,

  child.yaanpa yaanpa,

  CAST(NULL as varchar(100)) ParentUnit,

  CAST('>> ' as varchar(100)) LVL,

  CAST(child.YAAN8 as varchar(100)) Hierarchy,

  1 AS RecursionLevel

FROM #temp2 child

WHERE YAAN8 = 123456

 

UNION ALL

 

SELECT

  child.YAAN8,

  CAST(LVL + child.ChildName as varchar(100)) AS ChildName,

  child.yaanpa,

  parent.ChildName ParentUnit,

  CAST('>> ' + LVL as varchar(100)) AS LVL,

  CAST(Hierarchy + ':' + CAST(child.YAAN8 as varchar(100)) as varchar(100)) Hierarchy,

  RecursionLevel + 1 AS RecursionLevel

FROM Recursive_CTE parent

INNER JOIN #temp2 child ON child.yaanpa = parent.YAAN8

)

SELECT * FROM Recursive_CTE ORDER BY Hierarchy

Thursday, February 21, 2013

Writing Word from Database or Excel

 

 

Writing Word from Database

Best way to do this using Access Database, do following:-

 

1.       Create a Table in access database and define all of the related data for mail merge.

2.       Open this table and click on External Data Word Merge.

3.       Word document will open, Select second option –> Create a new document and then link the data to it.

4.       Type your letter and if you want to attach a field you can click at insert merge field and select your field.

5.       After this you can check the preview.

6.       Click at Finish & merge, once you done.

I think you can use excel by attaching it to access database.